Datasets:
AI4M
/

text
stringlengths
0
3.34M
Formal statement is: lemma brouwer_surjective_cball: fixes f :: "'n::euclidean_space \<Rightarrow> 'n" assumes "continuous_on (cball a e) f" and "e > 0" and "x \<in> S" and "\<And>x y. \<lbrakk>x\<in>S; y\<in>cball a e\<rbrakk> \<Longrightarrow> x + (y - f y) \<in> cball a e" shows "\<exists>y\<in>cball a e. f y = x" Informal statement is: If $f$ is a continuous function from the closed ball of radius $e$ centered at $a$ to itself, and $x$ is a point in the interior of the ball, then there exists a point $y$ in the ball such that $f(y) = x$.
\section{Technical Cryptography} \label{sec:tech_crypto} In this section we present in detail the specifics of the cryptography we will be using for MadNetwork. At times we will be verbose in our algorithmic details and design choices to allow for others to understand our decisions. We will begin by comparing this work with the Ethereum Distributed Key Generation whitepaper~\cite{ethdkg} in Sec.~\ref{ssec:ethdkg_comparison}; our design is based this paper. Some of the implementation-specific details are covered in Sec.~\ref{ssec:pk_curve_specifics}. In Sec.~\ref{ssec:math_def}, we discuss the mathematics related to pairing-based cryptography; this is integral to our work as it is required for our group signatures. We describe the distributed key generation protocol in Sec.~\ref{ssec:dkg}; the specific method of shared secret encryption is described in Sec.~\ref{ssec:secret_enc}. We discuss how to construct group signatures in Sec.~\ref{ssec:crypto_group_sig}. Group signatures from pairing-based cryptography require a hash-to-curve function, and we talk about our construction based on~\cite{ft2012bnhashtocurve,boneh2019h2cBLS12} in Sec.~\ref{ssec:hash-to-curve}. We follow~\cite{ethdkg} in our definition of $\parens{t,n}$-thresholded system, where we need $t+1$ actors for consensus. Unfortunately, this is different than what was used previously, where $\parens{t,n}$-thresholded system meant $t$ actors were needed to agree. We keep this difference for ease of comparison with the referenced paper. \input{tex/tcrypt_comparison.tex} \input{tex/tcrypt_spec_imp.tex} \input{tex/tcrypt_math_def.tex} \input{tex/tcrypt_dkg.tex} \input{tex/tcrypt_sse.tex} \input{tex/tcrypt_grpsig.tex} \input{tex/tcrypt_h2c.tex}
If $f$ and $g$ are analytic at $z$, then the $n$th derivative of $f + g$ at $z$ is equal to the $n$th derivative of $f$ at $z$ plus the $n$th derivative of $g$ at $z$.
module Main import GTK import GTK.Utils -- reference: https://zetcode.com/gui/gtk2/ tooltip_test : IO () tooltip_test = do primIO $ gtk_init nullptr nullptr -- make window window <- primIO $ gtk_window_new GTK_WINDOW_TOPLEVEL primIO $ gtk_window_set_title window "Tooltip Test" primIO $ gtk_container_set_border_width window 15 primIO $ gtk_window_set_default_size window 300 200 _ <- primIO $ g_signal_connect_data (to_object window) "destroy" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) -- make button button <- primIO $ gtk_button_new_with_mnemonic "B_utton" primIO $ gtk_widget_set_halign button GTK_ALIGN_START primIO $ gtk_widget_set_valign button GTK_ALIGN_START primIO $ gtk_widget_set_tooltip_text button "why" primIO $ gtk_container_add window button -- main primIO $ gtk_widget_show_all window primIO $ gtk_main simple_menu : IO () simple_menu = do primIO $ gtk_init nullptr nullptr -- make window window <- primIO $ gtk_window_new GTK_WINDOW_TOPLEVEL primIO $ gtk_window_set_title window "Simple Menu" primIO $ gtk_window_set_position window GTK_WIN_POS_CENTER -- must be before set_default_size or else the size will shrink primIO $ gtk_window_set_default_size window 300 200 _ <- primIO $ g_signal_connect_data (to_object window) "destroy" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) -- make vbox vbox <- primIO $ gtk_vbox_new false 0 primIO $ gtk_container_add window vbox -- create objects menu_bar <- primIO $ gtk_menu_bar_new file_menu <- primIO $ gtk_menu_new file_menu_item <- primIO $ gtk_menu_item_new_with_label "File" quit_menu_item <- primIO $ gtk_menu_item_new_with_label "Quit" -- construct menu primIO $ gtk_menu_item_set_submenu file_menu_item file_menu primIO $ gtk_menu_shell_append file_menu quit_menu_item primIO $ gtk_menu_shell_append menu_bar file_menu_item primIO $ gtk_box_pack_start vbox menu_bar false false 0 _ <- primIO $ g_signal_connect_data (to_object window) "destroy" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) _ <- primIO $ g_signal_connect_data (to_object quit_menu_item) "activate" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) -- main primIO $ gtk_widget_show_all window primIO $ gtk_main submenu : IO () submenu = do primIO $ gtk_init nullptr nullptr -- make window window <- primIO $ gtk_window_new GTK_WINDOW_TOPLEVEL primIO $ gtk_window_set_title window "Submenu" primIO $ gtk_window_set_position window GTK_WIN_POS_CENTER -- must be before set_default_size or else the size will shrink primIO $ gtk_window_set_default_size window 300 200 _ <- primIO $ g_signal_connect_data (to_object window) "destroy" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) -- make vbox vbox <- primIO $ gtk_vbox_new false 0 -- create objects menu_bar <- primIO $ gtk_menu_bar_new file_menu <- primIO $ gtk_menu_new file_menu_item <- primIO $ gtk_menu_item_new_with_label "File" quit_menu_item <- primIO $ gtk_menu_item_new_with_label "Quit" import_menu <- primIO $ gtk_menu_new import_menu_item <- primIO $ gtk_menu_item_new_with_label "Import" import_feed_menu_item <- primIO $ gtk_menu_item_new_with_label "Import News Feed..." import_book_menu_item <- primIO $ gtk_menu_item_new_with_label "Import Bookmarks..." import_mail_menu_item <- primIO $ gtk_menu_item_new_with_label "Import Mail..." sep <- primIO $ gtk_separator_menu_item_new -- construct menu primIO $ gtk_menu_item_set_submenu import_menu_item import_menu primIO $ gtk_menu_shell_append import_menu import_feed_menu_item primIO $ gtk_menu_shell_append import_menu import_book_menu_item primIO $ gtk_menu_shell_append import_menu import_mail_menu_item primIO $ gtk_menu_item_set_submenu file_menu_item file_menu primIO $ gtk_menu_shell_append file_menu import_menu_item primIO $ gtk_menu_shell_append file_menu sep primIO $ gtk_menu_shell_append file_menu quit_menu_item primIO $ gtk_menu_shell_append menu_bar file_menu_item primIO $ gtk_box_pack_start vbox menu_bar false false 0 primIO $ gtk_container_add window vbox _ <- primIO $ g_signal_connect_data (to_object window) "destroy" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) _ <- primIO $ g_signal_connect_data (to_object quit_menu_item) "activate" gtk_main_quit nullanyptr 0 (\_, _ => prim__io_pure ()) -- main primIO $ gtk_widget_show_all window primIO $ gtk_main
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import category_theory.category.Pointed import data.pfun /-! # The category of types with partial functions This defines `PartialFun`, the category of types equipped with partial functions. This category is classically equivalent to the category of pointed types. The reason it doesn't hold constructively stems from the difference between `part` and `option`. Both can model partial functions, but the latter forces a decidable domain. Precisely, `PartialFun_to_Pointed` turns a partial function `α →. β` into a function `option α → option β` by sending to `none` the undefined values (and `none` to `none`). But being defined is (generally) undecidable while being sent to `none` is decidable. So it can't be constructive. ## References * [nLab, *The category of sets and partial functions*] (https://ncatlab.org/nlab/show/partial+function) -/ open category_theory option universes u variables {α β : Type*} /-- The category of types equipped with partial functions. -/ def PartialFun : Type* := Type* namespace PartialFun instance : has_coe_to_sort PartialFun Type* := ⟨id⟩ /-- Turns a type into a `PartialFun`. -/ @[nolint has_inhabited_instance] def of : Type* → PartialFun := id @[simp] lemma coe_of (X : Type*) : ↥(of X) = X := rfl instance : inhabited PartialFun := ⟨Type*⟩ instance large_category : large_category.{u} PartialFun := { hom := pfun, id := pfun.id, comp := λ X Y Z f g, g.comp f, id_comp' := @pfun.comp_id, comp_id' := @pfun.id_comp, assoc' := λ W X Y Z _ _ _, (pfun.comp_assoc _ _ _).symm } /-- Constructs a partial function isomorphism between types from an equivalence between them. -/ @[simps] def iso.mk {α β : PartialFun.{u}} (e : α ≃ β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := (pfun.coe_comp _ _).symm.trans $ congr_arg coe e.symm_comp_self, inv_hom_id' := (pfun.coe_comp _ _).symm.trans $ congr_arg coe e.self_comp_symm } end PartialFun /-- The forgetful functor from `Type` to `PartialFun` which forgets that the maps are total. -/ def Type_to_PartialFun : Type.{u} ⥤ PartialFun := { obj := id, map := @pfun.lift, map_comp' := λ _ _ _ _ _, pfun.coe_comp _ _ } instance : faithful Type_to_PartialFun := ⟨λ X Y, pfun.coe_injective⟩ /-- The functor which deletes the point of a pointed type. In return, this makes the maps partial. This the computable part of the equivalence `PartialFun_equiv_Pointed`. -/ def Pointed_to_PartialFun : Pointed.{u} ⥤ PartialFun := { obj := λ X, {x : X // x ≠ X.point}, map := λ X Y f, pfun.to_subtype _ f.to_fun ∘ subtype.val, map_id' := λ X, pfun.ext $ λ a b, pfun.mem_to_subtype_iff.trans (subtype.coe_inj.trans part.mem_some_iff.symm), map_comp' := λ X Y Z f g, pfun.ext $ λ a c, begin refine (pfun.mem_to_subtype_iff.trans _).trans part.mem_bind_iff.symm, simp_rw [pfun.mem_to_subtype_iff, subtype.exists], refine ⟨λ h, ⟨f.to_fun a, λ ha, c.2 $ h.trans ((congr_arg g.to_fun ha : g.to_fun _ = _).trans g.map_point), rfl, h⟩, _⟩, rintro ⟨b, _, (rfl : b = _), h⟩, exact h, end } /-- The functor which maps undefined values to a new point. This makes the maps total and creates pointed types. This the noncomputable part of the equivalence `PartialFun_equiv_Pointed`. It can't be computable because `= option.none` is decidable while the domain of a general `part` isn't. -/ noncomputable def PartialFun_to_Pointed : PartialFun ⥤ Pointed := by classical; exact { obj := λ X, ⟨option X, none⟩, map := λ X Y f, ⟨λ o, o.elim none (λ a, (f a).to_option), rfl⟩, map_id' := λ X, Pointed.hom.ext _ _ $ funext $ λ o, option.rec_on o rfl $ λ a, part.some_to_option _, map_comp' := λ X Y Z f g, Pointed.hom.ext _ _ $ funext $ λ o, option.rec_on o rfl $ λ a, part.bind_to_option _ _ } /-- The equivalence induced by `PartialFun_to_Pointed` and `Pointed_to_PartialFun`. `part.equiv_option` made functorial. -/ @[simps] noncomputable def PartialFun_equiv_Pointed : PartialFun.{u} ≌ Pointed := by classical; exact equivalence.mk PartialFun_to_Pointed Pointed_to_PartialFun (nat_iso.of_components (λ X, PartialFun.iso.mk { to_fun := λ a, ⟨some a, some_ne_none a⟩, inv_fun := λ a, get $ ne_none_iff_is_some.1 a.2, left_inv := λ a, get_some _ _, right_inv := λ a, by simp only [subtype.val_eq_coe, some_get, subtype.coe_eta] }) $ λ X Y f, pfun.ext $ λ a b, begin unfold_projs, dsimp, rw part.bind_some, refine (part.mem_bind_iff.trans _).trans pfun.mem_to_subtype_iff.symm, obtain ⟨b | b, hb⟩ := b, { exact (hb rfl).elim }, dsimp, simp_rw [part.mem_some_iff, subtype.mk_eq_mk, exists_prop, some_inj, exists_eq_right'], refine part.mem_to_option.symm.trans _, convert eq_comm, convert rfl, end) (nat_iso.of_components (λ X, Pointed.iso.mk { to_fun := λ a, a.elim X.point subtype.val, inv_fun := λ a, if h : a = X.point then none else some ⟨_, h⟩, left_inv := λ a, option.rec_on a (dif_pos rfl) $ λ a, (dif_neg a.2).trans $ by simp only [option.elim, subtype.val_eq_coe, subtype.coe_eta], right_inv := λ a, begin change option.elim (dite _ _ _) _ _ = _, split_ifs, { rw h, refl }, { refl } end } rfl) $ λ X Y f, Pointed.hom.ext _ _ $ funext $ λ a, option.rec_on a f.map_point.symm $ λ a, begin change option.elim (option.elim _ _ _) _ _ = _, rw [option.elim, part.elim_to_option], split_ifs, { refl }, { exact eq.symm (of_not_not h) } end) /-- Forgetting that maps are total and making them total again by adding a point is the same as just adding a point. -/ @[simps] noncomputable def Type_to_PartialFun_iso_PartialFun_to_Pointed : Type_to_PartialFun ⋙ PartialFun_to_Pointed ≅ Type_to_Pointed := nat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩, hom_inv_id' := rfl, inv_hom_id' := rfl }) $ λ X Y f, Pointed.hom.ext _ _ $ funext $ λ a, option.rec_on a rfl $ λ a, by convert part.some_to_option _
1989 House Bill 0979. An Act To Ensure Equal Access To Long Term Care Facilities. Title 1989 House Bill 0979. An Act To Ensure Equal Access To Long Term Care Facilities.
The complex conjugate of a complex number to the $n$th power is the complex conjugate of the complex number to the $n$th power.
(* Title: HOL/Auth/Guard/GuardK.thy Author: Frederic Blanqui, University of Cambridge Computer Laboratory Copyright 2002 University of Cambridge Very similar to Guard except: - Guard is replaced by GuardK, guard by guardK, Nonce by Key - some scripts are slightly modified (+ keyset_in, kparts_parts) - the hypothesis Key n ~:G (keyset G) is added *) section\<open>protocol-independent confidentiality theorem on keys\<close> theory GuardK imports Analz Extensions begin (****************************************************************************** messages where all the occurrences of Key n are in a sub-message of the form Crypt (invKey K) X with K:Ks ******************************************************************************) inductive_set guardK :: "nat => key set => msg set" for n :: nat and Ks :: "key set" where No_Key [intro]: "Key n ~:parts {X} ==> X:guardK n Ks" | Guard_Key [intro]: "invKey K:Ks ==> Crypt K X:guardK n Ks" | Crypt [intro]: "X:guardK n Ks ==> Crypt K X:guardK n Ks" | Pair [intro]: "[| X:guardK n Ks; Y:guardK n Ks |] ==> \<lbrace>X,Y\<rbrace>:guardK n Ks" subsection\<open>basic facts about @{term guardK}\<close> lemma Nonce_is_guardK [iff]: "Nonce p:guardK n Ks" by auto lemma Agent_is_guardK [iff]: "Agent A:guardK n Ks" by auto lemma Number_is_guardK [iff]: "Number r:guardK n Ks" by auto lemma Key_notin_guardK: "X:guardK n Ks ==> X ~= Key n" by (erule guardK.induct, auto) lemma Key_notin_guardK_iff [iff]: "Key n ~:guardK n Ks" by (auto dest: Key_notin_guardK) lemma guardK_has_Crypt [rule_format]: "X:guardK n Ks ==> Key n:parts {X} --> (EX K Y. Crypt K Y:kparts {X} & Key n:parts {Y})" by (erule guardK.induct, auto) lemma Key_notin_kparts_msg: "X:guardK n Ks ==> Key n ~:kparts {X}" by (erule guardK.induct, auto dest: kparts_parts) lemma Key_in_kparts_imp_no_guardK: "Key n:kparts H ==> EX X. X:H & X ~:guardK n Ks" apply (drule in_kparts, clarify) apply (rule_tac x=X in exI, clarify) by (auto dest: Key_notin_kparts_msg) lemma guardK_kparts [rule_format]: "X:guardK n Ks ==> Y:kparts {X} --> Y:guardK n Ks" by (erule guardK.induct, auto dest: kparts_parts parts_sub) lemma guardK_Crypt: "[| Crypt K Y:guardK n Ks; K ~:invKey`Ks |] ==> Y:guardK n Ks" by (ind_cases "Crypt K Y:guardK n Ks") (auto intro!: image_eqI) lemma guardK_MPair [iff]: "(\<lbrace>X,Y\<rbrace>:guardK n Ks) = (X:guardK n Ks & Y:guardK n Ks)" by (auto, (ind_cases "\<lbrace>X,Y\<rbrace>:guardK n Ks", auto)+) lemma guardK_not_guardK [rule_format]: "X:guardK n Ks ==> Crypt K Y:kparts {X} --> Key n:kparts {Y} --> Y ~:guardK n Ks" by (erule guardK.induct, auto dest: guardK_kparts) lemma guardK_extand: "[| X:guardK n Ks; Ks <= Ks'; [| K:Ks'; K ~:Ks |] ==> Key K ~:parts {X} |] ==> X:guardK n Ks'" by (erule guardK.induct, auto) subsection\<open>guarded sets\<close> definition GuardK :: "nat => key set => msg set => bool" where "GuardK n Ks H == ALL X. X:H --> X:guardK n Ks" subsection\<open>basic facts about @{term GuardK}\<close> lemma GuardK_empty [iff]: "GuardK n Ks {}" by (simp add: GuardK_def) lemma Key_notin_kparts [simplified]: "GuardK n Ks H ==> Key n ~:kparts H" by (auto simp: GuardK_def dest: in_kparts Key_notin_kparts_msg) lemma GuardK_must_decrypt: "[| GuardK n Ks H; Key n:analz H |] ==> EX K Y. Crypt K Y:kparts H & Key (invKey K):kparts H" apply (drule_tac P="%G. Key n:G" in analz_pparts_kparts_substD, simp) by (drule must_decrypt, auto dest: Key_notin_kparts) lemma GuardK_kparts [intro]: "GuardK n Ks H ==> GuardK n Ks (kparts H)" by (auto simp: GuardK_def dest: in_kparts guardK_kparts) lemma GuardK_mono: "[| GuardK n Ks H; G <= H |] ==> GuardK n Ks G" by (auto simp: GuardK_def) lemma GuardK_insert [iff]: "GuardK n Ks (insert X H) = (GuardK n Ks H & X:guardK n Ks)" by (auto simp: GuardK_def) lemma GuardK_Un [iff]: "GuardK n Ks (G Un H) = (GuardK n Ks G & GuardK n Ks H)" by (auto simp: GuardK_def) lemma GuardK_synth [intro]: "GuardK n Ks G ==> GuardK n Ks (synth G)" by (auto simp: GuardK_def, erule synth.induct, auto) lemma GuardK_analz [intro]: "[| GuardK n Ks G; ALL K. K:Ks --> Key K ~:analz G |] ==> GuardK n Ks (analz G)" apply (auto simp: GuardK_def) apply (erule analz.induct, auto) by (ind_cases "Crypt K Xa:guardK n Ks" for K Xa, auto) lemma in_GuardK [dest]: "[| X:G; GuardK n Ks G |] ==> X:guardK n Ks" by (auto simp: GuardK_def) lemma in_synth_GuardK: "[| X:synth G; GuardK n Ks G |] ==> X:guardK n Ks" by (drule GuardK_synth, auto) lemma in_analz_GuardK: "[| X:analz G; GuardK n Ks G; ALL K. K:Ks --> Key K ~:analz G |] ==> X:guardK n Ks" by (drule GuardK_analz, auto) lemma GuardK_keyset [simp]: "[| keyset G; Key n ~:G |] ==> GuardK n Ks G" by (simp only: GuardK_def, clarify, drule keyset_in, auto) lemma GuardK_Un_keyset: "[| GuardK n Ks G; keyset H; Key n ~:H |] ==> GuardK n Ks (G Un H)" by auto lemma in_GuardK_kparts: "[| X:G; GuardK n Ks G; Y:kparts {X} |] ==> Y:guardK n Ks" by blast lemma in_GuardK_kparts_neq: "[| X:G; GuardK n Ks G; Key n':kparts {X} |] ==> n ~= n'" by (blast dest: in_GuardK_kparts) lemma in_GuardK_kparts_Crypt: "[| X:G; GuardK n Ks G; is_MPair X; Crypt K Y:kparts {X}; Key n:kparts {Y} |] ==> invKey K:Ks" apply (drule in_GuardK, simp) apply (frule guardK_not_guardK, simp+) apply (drule guardK_kparts, simp) by (ind_cases "Crypt K Y:guardK n Ks", auto) lemma GuardK_extand: "[| GuardK n Ks G; Ks <= Ks'; [| K:Ks'; K ~:Ks |] ==> Key K ~:parts G |] ==> GuardK n Ks' G" by (auto simp: GuardK_def dest: guardK_extand parts_sub) subsection\<open>set obtained by decrypting a message\<close> abbreviation (input) decrypt :: "msg set => key => msg => msg set" where "decrypt H K Y == insert Y (H - {Crypt K Y})" lemma analz_decrypt: "[| Crypt K Y:H; Key (invKey K):H; Key n:analz H |] ==> Key n:analz (decrypt H K Y)" apply (drule_tac P="%H. Key n:analz H" in ssubst [OF insert_Diff]) apply assumption apply (simp only: analz_Crypt_if, simp) done lemma parts_decrypt: "[| Crypt K Y:H; X:parts (decrypt H K Y) |] ==> X:parts H" by (erule parts.induct, auto intro: parts.Fst parts.Snd parts.Body) subsection\<open>number of Crypt's in a message\<close> fun crypt_nb :: "msg => nat" where "crypt_nb (Crypt K X) = Suc (crypt_nb X)" | "crypt_nb \<lbrace>X,Y\<rbrace> = crypt_nb X + crypt_nb Y" | "crypt_nb X = 0" (* otherwise *) subsection\<open>basic facts about @{term crypt_nb}\<close> lemma non_empty_crypt_msg: "Crypt K Y:parts {X} ==> crypt_nb X \<noteq> 0" by (induct X, simp_all, safe, simp_all) subsection\<open>number of Crypt's in a message list\<close> primrec cnb :: "msg list => nat" where "cnb [] = 0" | "cnb (X#l) = crypt_nb X + cnb l" subsection\<open>basic facts about @{term cnb}\<close> lemma cnb_app [simp]: "cnb (l @ l') = cnb l + cnb l'" by (induct l, auto) lemma mem_cnb_minus: "x \<in> set l ==> cnb l = crypt_nb x + (cnb l - crypt_nb x)" by (induct l, auto) lemmas mem_cnb_minus_substI = mem_cnb_minus [THEN ssubst] lemma cnb_minus [simp]: "x \<in> set l ==> cnb (remove l x) = cnb l - crypt_nb x" apply (induct l, auto) by (erule_tac l=l and x=x in mem_cnb_minus_substI, simp) lemma parts_cnb: "Z:parts (set l) ==> cnb l = (cnb l - crypt_nb Z) + crypt_nb Z" by (erule parts.induct, auto simp: in_set_conv_decomp) lemma non_empty_crypt: "Crypt K Y:parts (set l) ==> cnb l \<noteq> 0" by (induct l, auto dest: non_empty_crypt_msg parts_insert_substD) subsection\<open>list of kparts\<close> lemma kparts_msg_set: "EX l. kparts {X} = set l & cnb l = crypt_nb X" apply (induct X, simp_all) apply (rename_tac agent, rule_tac x="[Agent agent]" in exI, simp) apply (rename_tac nat, rule_tac x="[Number nat]" in exI, simp) apply (rename_tac nat, rule_tac x="[Nonce nat]" in exI, simp) apply (rename_tac nat, rule_tac x="[Key nat]" in exI, simp) apply (rule_tac x="[Hash X]" in exI, simp) apply (clarify, rule_tac x="l@la" in exI, simp) by (clarify, rename_tac nat X y, rule_tac x="[Crypt nat X]" in exI, simp) lemma kparts_set: "EX l'. kparts (set l) = set l' & cnb l' = cnb l" apply (induct l) apply (rule_tac x="[]" in exI, simp, clarsimp) apply (rename_tac a b l') apply (subgoal_tac "EX l''. kparts {a} = set l'' & cnb l'' = crypt_nb a", clarify) apply (rule_tac x="l''@l'" in exI, simp) apply (rule kparts_insert_substI, simp) by (rule kparts_msg_set) subsection\<open>list corresponding to "decrypt"\<close> definition decrypt' :: "msg list => key => msg => msg list" where "decrypt' l K Y == Y # remove l (Crypt K Y)" declare decrypt'_def [simp] subsection\<open>basic facts about @{term decrypt'}\<close> lemma decrypt_minus: "decrypt (set l) K Y <= set (decrypt' l K Y)" by (induct l, auto) text\<open>if the analysis of a finite guarded set gives n then it must also give one of the keys of Ks\<close> lemma GuardK_invKey_by_list [rule_format]: "ALL l. cnb l = p --> GuardK n Ks (set l) --> Key n:analz (set l) --> (EX K. K:Ks & Key K:analz (set l))" apply (induct p) (* case p=0 *) apply (clarify, drule GuardK_must_decrypt, simp, clarify) apply (drule kparts_parts, drule non_empty_crypt, simp) (* case p>0 *) apply (clarify, frule GuardK_must_decrypt, simp, clarify) apply (drule_tac P="%G. Key n:G" in analz_pparts_kparts_substD, simp) apply (frule analz_decrypt, simp_all) apply (subgoal_tac "EX l'. kparts (set l) = set l' & cnb l' = cnb l", clarsimp) apply (drule_tac G="insert Y (set l' - {Crypt K Y})" and H="set (decrypt' l' K Y)" in analz_sub, rule decrypt_minus) apply (rule_tac analz_pparts_kparts_substI, simp) apply (case_tac "K:invKey`Ks") (* K:invKey`Ks *) apply (clarsimp, blast) (* K ~:invKey`Ks *) apply (subgoal_tac "GuardK n Ks (set (decrypt' l' K Y))") apply (drule_tac x="decrypt' l' K Y" in spec, simp) apply (subgoal_tac "Crypt K Y:parts (set l)") apply (drule parts_cnb, rotate_tac -1, simp) apply (clarify, drule_tac X="Key Ka" and H="insert Y (set l')" in analz_sub) apply (rule insert_mono, rule set_remove) apply (simp add: analz_insertD, blast) (* Crypt K Y:parts (set l) *) apply (blast dest: kparts_parts) (* GuardK n Ks (set (decrypt' l' K Y)) *) apply (rule_tac H="insert Y (set l')" in GuardK_mono) apply (subgoal_tac "GuardK n Ks (set l')", simp) apply (rule_tac K=K in guardK_Crypt, simp add: GuardK_def, simp) apply (drule_tac t="set l'" in sym, simp) apply (rule GuardK_kparts, simp, simp) apply (rule_tac B="set l'" in subset_trans, rule set_remove, blast) by (rule kparts_set) lemma GuardK_invKey_finite: "[| Key n:analz G; GuardK n Ks G; finite G |] ==> EX K. K:Ks & Key K:analz G" apply (drule finite_list, clarify) by (rule GuardK_invKey_by_list, auto) lemma GuardK_invKey: "[| Key n:analz G; GuardK n Ks G |] ==> EX K. K:Ks & Key K:analz G" by (auto dest: analz_needs_only_finite GuardK_invKey_finite) text\<open>if the analyse of a finite guarded set and a (possibly infinite) set of keys gives n then it must also gives Ks\<close> lemma GuardK_invKey_keyset: "[| Key n:analz (G Un H); GuardK n Ks G; finite G; keyset H; Key n ~:H |] ==> EX K. K:Ks & Key K:analz (G Un H)" apply (frule_tac P="%G. Key n:G" and G=G in analz_keyset_substD, simp_all) apply (drule_tac G="G Un (H Int keysfor G)" in GuardK_invKey_finite) apply (auto simp: GuardK_def intro: analz_sub) by (drule keyset_in, auto) end
open import Issue481PonderBase open import Issue481PonderImportMe as as module Issue481PonderMaster where module M = as as as
corollary Cauchy_contour_integral_circlepath: assumes "continuous_on (cball z r) f" "f holomorphic_on ball z r" "w \<in> ball z r" shows "contour_integral(circlepath z r) (\<lambda>u. f u/(u - w)^(Suc k)) = (2 * pi * \<i>) * (deriv ^^ k) f w / (fact k)"
State Before: l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α ⊢ stdBasisMatrix i j c ⬝ stdBasisMatrix k l d = 0 State After: case a.h l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n ⊢ (stdBasisMatrix i j c ⬝ stdBasisMatrix k l d) a b = OfNat.ofNat 0 a b Tactic: ext (a b) State Before: case a.h l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n ⊢ (stdBasisMatrix i j c ⬝ stdBasisMatrix k l d) a b = OfNat.ofNat 0 a b State After: case a.h l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b Tactic: simp only [mul_apply, boole_mul, stdBasisMatrix] State Before: case a.h l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b State After: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b case neg l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : ¬i = a ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b Tactic: by_cases h₁ : i = a State Before: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b State After: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a ⊢ (∑ x : n, if (k = x ∧ l = b) ∧ j = x then c * d else 0) = 0 Tactic: simp only [h₁, true_and, mul_ite, ite_mul, zero_mul, mul_zero, ← ite_and, zero_apply] State Before: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a ⊢ (∑ x : n, if (k = x ∧ l = b) ∧ j = x then c * d else 0) = 0 State After: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a x : n x✝ : x ∈ Finset.univ ⊢ (if (k = x ∧ l = b) ∧ j = x then c * d else 0) = 0 Tactic: refine Finset.sum_eq_zero (fun x _ => ?_) State Before: case pos l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a x : n x✝ : x ∈ Finset.univ ⊢ (if (k = x ∧ l = b) ∧ j = x then c * d else 0) = 0 State After: case pos.hnc l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a x : n x✝ : x ∈ Finset.univ ⊢ ¬((k = x ∧ l = b) ∧ j = x) Tactic: apply if_neg State Before: case pos.hnc l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : i = a x : n x✝ : x ∈ Finset.univ ⊢ ¬((k = x ∧ l = b) ∧ j = x) State After: case pos.hnc.intro.intro l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h✝ : j ≠ k d : α a : n h₁ : i = a x✝ : k ∈ Finset.univ h : j = k ⊢ False Tactic: rintro ⟨⟨rfl, rfl⟩, h⟩ State Before: case pos.hnc.intro.intro l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h✝ : j ≠ k d : α a : n h₁ : i = a x✝ : k ∈ Finset.univ h : j = k ⊢ False State After: no goals Tactic: contradiction State Before: case neg l✝ : Type ?u.47153 m : Type ?u.47156 n : Type u_1 R : Type ?u.47162 α : Type u_2 inst✝⁴ : DecidableEq l✝ inst✝³ : DecidableEq m inst✝² : DecidableEq n inst✝¹ : Semiring α i j : n c : α i' j' : n inst✝ : Fintype n k l : n h : j ≠ k d : α a b : n h₁ : ¬i = a ⊢ (∑ j_1 : n, (if i = a ∧ j = j_1 then c else 0) * if k = j_1 ∧ l = b then d else 0) = OfNat.ofNat 0 a b State After: no goals Tactic: simp only [h₁, false_and, ite_false, mul_ite, zero_mul, mul_zero, ite_self, Finset.sum_const_zero, zero_apply]
function h=plotgauss2d(mu, Sigma) % PLOTGAUSS2D Plot a 2D Gaussian as an ellipse with optional cross hairs % h=plotgauss2(mu, Sigma) % h = plotcov2(mu, Sigma); return; %%%%%%%%%%%%%%%%%%%%%%%% % PLOTCOV2 - Plots a covariance ellipse with major and minor axes % for a bivariate Gaussian distribution. % % Usage: % h = plotcov2(mu, Sigma[, OPTIONS]); % % Inputs: % mu - a 2 x 1 vector giving the mean of the distribution. % Sigma - a 2 x 2 symmetric positive semi-definite matrix giving % the covariance of the distribution (or the zero matrix). % % Options: % 'conf' - a scalar between 0 and 1 giving the confidence % interval (i.e., the fraction of probability mass to % be enclosed by the ellipse); default is 0.9. % 'num-pts' - the number of points to be used to plot the % ellipse; default is 100. % % This function also accepts options for PLOT. % % Outputs: % h - a vector of figure handles to the ellipse boundary and % its major and minor axes % % See also: PLOTCOV3 % Copyright (C) 2002 Mark A. Paskin function h = plotcov2(mu, Sigma, varargin) if size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end if length(mu) ~= 2, error('mu must be a 2 by 1 vector'); end [p, ... n, ... plot_opts] = process_options(varargin, 'conf', 0.9, ... 'num-pts', 100); h = []; holding = ishold; if (Sigma == zeros(2, 2)) z = mu; else % Compute the Mahalanobis radius of the ellipsoid that encloses % the desired probability mass. k = conf2mahal(p, 2); % The major and minor axes of the covariance ellipse are given by % the eigenvectors of the covariance matrix. Their lengths (for % the ellipse with unit Mahalanobis radius) are given by the % square roots of the corresponding eigenvalues. if (issparse(Sigma)) [V, D] = eigs(Sigma); else [V, D] = eig(Sigma); end % Compute the points on the surface of the ellipse. t = linspace(0, 2*pi, n); u = [cos(t); sin(t)]; w = (k * V * sqrt(D)) * u; z = repmat(mu, [1 n]) + w; % Plot the major and minor axes. L = k * sqrt(diag(D)); h = plot([mu(1); mu(1) + L(1) * V(1, 1)], ... [mu(2); mu(2) + L(1) * V(2, 1)], plot_opts{:}); hold on; h = [h; plot([mu(1); mu(1) + L(2) * V(1, 2)], ... [mu(2); mu(2) + L(2) * V(2, 2)], plot_opts{:})]; end h = [h; plot(z(1, :), z(2, :), plot_opts{:})]; if (~holding) hold off; end %%%%%%%%%%%% % CONF2MAHAL - Translates a confidence interval to a Mahalanobis % distance. Consider a multivariate Gaussian % distribution of the form % % p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C))) % % where MD(x, m, P) is the Mahalanobis distance from x % to m under P: % % MD(x, m, P) = (x - m) * P * (x - m)' % % A particular Mahalanobis distance k identifies an % ellipsoid centered at the mean of the distribution. % The confidence interval associated with this ellipsoid % is the probability mass enclosed by it. Similarly, % a particular confidence interval uniquely determines % an ellipsoid with a fixed Mahalanobis distance. % % If X is an d dimensional Gaussian-distributed vector, % then the Mahalanobis distance of X is distributed % according to the Chi-squared distribution with d % degrees of freedom. Thus, the Mahalanobis distance is % determined by evaluating the inverse cumulative % distribution function of the chi squared distribution % up to the confidence value. % % Usage: % % m = conf2mahal(c, d); % % Inputs: % % c - the confidence interval % d - the number of dimensions of the Gaussian distribution % % Outputs: % % m - the Mahalanobis radius of the ellipsoid enclosing the % fraction c of the distribution's probability mass % % See also: MAHAL2CONF % Copyright (C) 2002 Mark A. Paskin function m = conf2mahal(c, d) m = chi2inv(c, d); % matlab stats toolbox
Formal statement is: lemma lowdim_subset_hyperplane: fixes S :: "'a::euclidean_space set" assumes d: "dim S < DIM('a)" shows "\<exists>a::'a. a \<noteq> 0 \<and> span S \<subseteq> {x. a \<bullet> x = 0}" Informal statement is: If $S$ is a subset of $\mathbb{R}^n$ with dimension less than $n$, then there exists a nonzero vector $a$ such that $S$ is contained in the hyperplane $\{x \in \mathbb{R}^n : a \cdot x = 0\}$.
Require Import CoRN.metric2.Metric CoRN.model.structures.Qpossec Coq.QArith.QArith_base CoRN.model.structures.QposInf CoRN.metric2.UniformContinuity CMorphisms FormTopC.FormTop Algebra.OrderC Algebra.PreOrder Algebra.SetsC FormTopC.FormalSpace Numbers.QFacts Numbers.QPosFacts FormTopC.Cont Coq.QArith.Qminmax. Set Asymmetric Patterns. Set Universe Polymorphism. Local Open Scope FT. Section Metric. Universes A P I. Context {MS : MetricSpace}. Definition M@{} : Type@{A} := msp_is_setoid MS. Definition Ball : Type@{A} := (M * Qpos)%type. Definition lt_ball@{} (Bx By : Ball) : Type@{P} := let (x, delta) := Bx in let (y, eps) := By in { d : Qpos | ball d x y /\ (d + delta < eps)%Qpos }. Definition le_ball@{} (Bx By : Ball) : Type@{P} := let (y, eps) := By in forall e : Qpos, lt_ball Bx (y, e + eps)%Qpos. Lemma lt_ball_center : forall x (eps eps' : Qpos), eps < eps' -> lt_ball (x, eps) (x, eps'). Proof. intros. unfold lt_ball. destruct (Qpos_lt_plus H). destruct (Qpos_smaller x0) as [x0' x0'small]. exists x0'. split. apply ball_refl. rewrite Qplus_comm. rewrite q. apply Qplus_lt_r. assumption. Qed. Instance PreO : PreO.t@{A P} le_ball. Proof. constructor. - intros []. unfold le_ball. intros. apply lt_ball_center. apply Qpos_plus_lt_l. - intros [] [] [] H H0. unfold le_ball in *. intros e. specialize (H (Qpos_one_half * e)%Qpos). specialize (H0 (Qpos_one_half * e)%Qpos). destruct H as (d & balld & dlt). destruct H0 as (d' & balld' & d'lt). exists (d + d')%Qpos. split. eapply ball_triangle; eassumption. simpl. rewrite (Qplus_comm d d'), <- Qplus_assoc. eapply Qlt_le_trans. apply Qplus_lt_r. apply dlt. simpl. rewrite (Qplus_comm _ q0), Qplus_assoc. eapply Qle_trans. apply Qplus_le_l. apply Qlt_le_weak. eassumption. simpl. apply Qeq_le. rewrite Qplus_comm, Qplus_assoc. rewrite (one_half_sum e). reflexivity. Qed. Existing Instance PreO.PreOrder_I. Local Instance PreOrder_le_ball : Transitive le_ball := PreOrder_Transitive. Lemma lt_le_weak : forall a b, lt_ball a b -> le_ball a b. Proof. unfold lt_ball, le_ball. intros [] [] (d & b & l). intros e. exists d. split. assumption. eapply Qlt_le_trans. eassumption. apply Qlt_le_weak. apply Qpos_plus_lt_l. Qed. Lemma lt_le_trans : forall a b c, lt_ball a b -> le_ball b c -> lt_ball a c. Proof. intros [] [] [] H H0. unfold lt_ball, le_ball in *. destruct H as (d & dmm0 & dqq0). destruct (Qpos_lt_plus dqq0) as [e eprf]. specialize (H0 e%Qpos). destruct H0 as (d' & balld' & dd'). exists (d + d')%Qpos. split. eapply ball_triangle; eassumption. rewrite eprf in dd'. apply (Qplus_lt_r _ _ e). eapply Qlt_compat. 3: apply dd'. simpl. ring. reflexivity. Qed. Lemma le_lt_trans a b c : le_ball a b -> lt_ball b c -> lt_ball a c. Proof. intros H H0. destruct a, b, c. unfold lt_ball, le_ball in *. destruct H0 as (d & dmm0 & dqq0). destruct (Qpos_lt_plus dqq0) as [e eprf]. specialize (H e). destruct H as (d' & balld' & dd'). exists (d' + d)%Qpos. split. eapply ball_triangle; eassumption. rewrite eprf in dqq0. rewrite eprf. clear eprf q1. rewrite <- Qplus_assoc. rewrite (Qplus_comm q0 e). simpl. rewrite <- (Qplus_assoc d' d q). rewrite Qplus_comm. rewrite <- (Qplus_assoc d q d'). apply Qplus_lt_r. rewrite Qplus_comm. assumption. Qed. Lemma le_ball_applies {a c} : le_ball a c -> forall x, ball (snd a) (fst a) x -> ball (snd c) (fst c) x. Proof. unfold le_ball. intros H x H0. destruct a, c. simpl in *. apply ball_closed. intros. specialize (H d). destruct H as (d' & balld' & qd'). apply ball_weak_le with (d' + q)%Qpos. apply Qlt_le_weak. simpl. rewrite (Qplus_comm q0 d). assumption. eapply ball_triangle. eapply ball_sym. eassumption. assumption. Qed. Lemma le_ball_center : forall x (eps eps' : Qpos), (eps <= eps')%Q -> le_ball (x, eps) (x, eps'). Proof. intros. simpl. intros. destruct (Qpos_smaller e) as [e' e'prf]. exists e'. split. apply ball_refl. apply Qplus_lt_le_compat; assumption. Qed. Lemma lt_ball_shrink Bx y eps : lt_ball Bx (y, eps) -> {eps' : Qpos & ((eps' < eps) * lt_ball Bx (y, eps'))%type }. Proof. intros H. destruct Bx. destruct H. destruct a. destruct (@Qpos_between (x + q)%Qpos eps H0). destruct a. exists x0. split. assumption. simpl. exists x. split. assumption. assumption. Qed. Lemma lt_ball_grow x delta By : lt_ball (x, delta) By -> { delta' : Qpos & ((delta < delta') * lt_ball (x, delta') By)%type }. Proof. intros H. destruct By. destruct H as (d & balld & dlt). destruct (Qpos_lt_plus dlt). exists (delta + Qpos_one_half * x0)%Qpos. split. - setoid_rewrite Qpos_plus_comm. apply Qpos_plus_lt_l. - simpl. exists d. split. assumption. rewrite q0. rewrite Qplus_assoc. apply Qplus_lt_r. apply Qpos_one_half_lt. Qed. Lemma lt_ball_radius x y (ex ey : Qpos) : lt_ball (x, ex) (y, ey) -> ex < ey. Proof. simpl. intros. destruct H as (d & bd & exey). eapply Qadd_lt. eassumption. Qed. Lemma le_ball_radius {Bx By} : le_ball Bx By -> (snd Bx <= snd By)%Q. Proof. destruct Bx, By. simpl. intros H. apply Qlt_all_Qle. intros. destruct (H eps). destruct a. rewrite Qplus_comm. eapply Qadd_lt. eassumption. Qed. Definition IxUL@{} (x : Ball) : Set := option Qpos. Definition CUL (b : Ball) (i : IxUL b) : Subset@{A P} Ball := match i with | None => fun b' => lt_ball b' b | Some epsilon => fun b' => snd b' = epsilon end. Definition MetricPO : PreOrder@{A P} := {| PO_car := Ball ; PreOrder.le := le_ball |}. Definition MetricPS@{} : PreISpace.t@{A P I} := {| PreISpace.S := MetricPO ; PreISpace.C := CUL |}. Lemma shrink_ball (b : Ball) : { b' : Ball & lt_ball b' b }. Proof. destruct b as [m q]. destruct (Qpos_smaller q) as [q' qq']. exists (m, q'). apply lt_ball_center. assumption. Qed. Lemma MPos_MUniv : FormTop.gtPos MetricPS. Proof. apply gall_Pos. simpl. intros. destruct i. - simpl. exists (fst a, QposMinMax.Qpos_min q (snd a)). split. le_down. destruct a. simpl fst. apply le_ball_center. apply QposMinMax.Qpos_min_lb_r. exists (fst a, q). reflexivity. apply le_ball_center. apply QposMinMax.Qpos_min_lb_l. - destruct (shrink_ball a). exists x. split. le_down. apply lt_le_weak; eassumption. exists x. simpl. eapply lt_le_trans; eassumption. reflexivity. Qed. Set Printing Universes. Local Instance MPos@{API'} : FormTop.gtPos MetricPS := MPos_MUniv@{API' API' P P P P P API' P P P P P}. Definition Metric@{API'} : IGt@{A P I API'} := {| IGS := MetricPS |}. End Metric. Arguments Ball MS : clear implicits. Section Map. (** In an open ball *) Inductive o_ball {X : MetricSpace} {eps : Qpos} {a b : X} : Set := In_o_ball : forall e : Qpos, e < eps -> ball e a b -> o_ball. Arguments o_ball {X} eps a b. Lemma o_ball_ball {X : MetricSpace} eps (a b : X) : o_ball eps a b -> ball eps a b. Proof. intros H. induction H. eapply ball_weak_le. apply Qlt_le_weak. eassumption. assumption. Qed. Lemma o_ball_shrink {X : MetricSpace} {eps : Qpos} {a b : X} : o_ball eps a b -> { eps' : Qpos & ((eps' < eps) * o_ball eps' a b)%type }. Proof. intros. destruct H. destruct (Qpos_between q) as (mid & midl & midh). exists mid. split. assumption. eapply In_o_ball; eassumption. Qed. Lemma le_ball_applies_o {X : MetricSpace} {a c : Ball X} : le_ball a c -> forall x : X, o_ball (snd a) (fst a) x -> o_ball (snd c) (fst c) x. Proof. intros H x H0. destruct a, c. simpl in *. induction H0. destruct (Qpos_lt_plus q1) as (diff & diffeq). destruct (H diff) as (d & balld & dlt). econstructor. Focus 2. eapply ball_triangle. apply ball_sym. eassumption. eassumption. rewrite diffeq in dlt. apply Qplus_lt_r with diff. eapply Qlt_compat. 3: apply dlt. simpl. ring. reflexivity. Qed. Lemma true_union S T (F : S -> Subset T) (t : T) : { x : S & F x t} -> union (fun _ => True) F t. Proof. intros H. destruct H. econstructor; unfold In; eauto. Qed. Local Open Scope Subset. Lemma true_union' S T (F : S -> Subset T) : (fun t => { x : S & F x t}) ⊆ union (fun _ => True) F. Proof. unfold Included, In, pointwise_rel, arrow. apply true_union. Qed. Lemma o_ball_refl : forall {X : MetricSpace} (x : X) eps, o_ball eps x x. Proof. intros. destruct (Qpos_smaller eps). econstructor. eassumption. apply ball_refl. Qed. Lemma o_ball_sym : forall {X : MetricSpace} (x y : X) eps, o_ball eps x y -> o_ball eps y x. Proof. intros. induction H. econstructor; eauto. apply ball_sym; assumption. Qed. Lemma Qle_inv (k x y : Qpos) : (y <= / k * x)%Q -> (y * k <= x)%Q. Proof. intros H. apply <- Q.Qle_shift_div_l. etransitivity. eassumption. rewrite Qmult_comm. unfold Qdiv. reflexivity. apply Qpos_prf. Qed. Lemma uniformly_smaller (l l' h h' : Q) (H : l < h) (H' : l' < h') : { eps : Qpos | (l + eps < h) /\ (l' + eps < h') }. Proof. destruct (Qpos_lt_plus H) as [eps1 P1]. destruct (Qpos_lt_plus H') as [eps2 P2]. destruct (Qpos_smaller (QposMinMax.Qpos_min eps1 eps2)) as [eps P]. exists eps. split. - rewrite P1. apply Qplus_lt_r. eapply Qlt_le_trans. eassumption. apply QposMinMax.Qpos_min_lb_l. - rewrite P2. apply Qplus_lt_r. eapply Qlt_le_trans. eassumption. apply QposMinMax.Qpos_min_lb_r. Qed. Section Lipschitz. Context {X Y : MetricSpace}. (** Yoneda embeddding of a point in its completion *) Definition Yoneda (x : X) : Subset (Ball X) := fun B => let (y, eps) := B in o_ball eps x y. Existing Instance PreO. Variable f : X -> Y. Variable k : Qpos. Definition Lipschitz : Prop := forall x x' eps, ball eps x x' -> ball (k * eps) (f x) (f x'). Hypothesis f_lip : Lipschitz. Lemma lt_monotone : forall x x' eps eps', lt_ball (x, eps) (x', eps') -> lt_ball (f x, k * eps)%Qpos (f x', k * eps')%Qpos. Proof. simpl. intros. destruct H as (d & bd & dlt). exists (k * d)%Qpos. split. apply f_lip. assumption. simpl. rewrite <- Qmult_plus_distr_r. apply Qmult_lt_compat_l. apply Qpos_prf. assumption. Qed. Lemma le_monotone x x' eps eps' : le_ball (x, eps) (x', eps') -> le_ball (f x, k * eps)%Qpos (f x', k * eps')%Qpos. Proof. intros H. unfold le_ball. intros. apply lt_le_trans with (f x', k * (Qpos_inv k * e + eps'))%Qpos. apply lt_monotone. apply H. apply le_ball_center. apply Qeq_le. simpl. rewrite Qmult_plus_distr_r. rewrite (Qpos_inv_scale_1 k e). reflexivity. Qed. Definition lift : Cont.map (toPSL (IGS (@Metric X))) (toPSL (IGS (@Metric Y))) := fun By Bx => let (x, delta) := Bx in lt_ball (f x, k * delta)%Qpos By. Lemma lift_f_ap_lt : forall x (eps eps' : Qpos), eps < eps' -> lift (f x, k * eps')%Qpos (x, eps). Proof. intros. simpl. destruct (Qpos_lt_plus H). exists (k * (Qpos_one_half * x0))%Qpos. split. apply ball_refl. rewrite q. rewrite Qplus_comm. simpl. rewrite <- Qmult_plus_distr_r. apply Qmult_lt_compat_l. apply Qpos_prf. apply Qplus_lt_r. apply Qpos_one_half_lt. Qed. Lemma lift_f_ap_lt' x (eps eps' : Qpos) : k * eps < eps' -> lift (f x, eps') (x, eps). Proof. intros H. pose proof (lift_f_ap_lt x eps (Qpos_inv k * eps')%Qpos) as H0. simpl in H0. assert (eps < / k * eps'). apply Qmult_lt_compat_l_inv with k. apply Qpos_prf. rewrite Qmult_assoc. rewrite Qmult_inv_r. rewrite Qmult_1_l. assumption. unfold not. intros. eapply Qlt_not_eq. apply (Qpos_prf k). symmetry; assumption. specialize (H0 H1). clear H1. destruct H0 as (d & balld & dlt). exists d. split. assumption. rewrite Qmult_assoc in dlt. rewrite Qmult_inv_r in dlt. rewrite Qmult_1_l in dlt. simpl. assumption. unfold not. intros. eapply Qlt_not_eq. apply (Qpos_prf k). symmetry; assumption. Qed. Lemma lift_f_le {a b u} : lift b a -> le_ball u a -> lift b u. Proof. intros. destruct a, b, u. unfold lift in *. eapply le_lt_trans. apply le_monotone. eassumption. assumption. Qed. Lemma lift_total (Bx : Ball X) : {By : Ball Y & lift By Bx }. Proof. destruct Bx as [m q]. exists (f m, q + k * q)%Qpos. simpl. destruct (Qpos_smaller q). exists x. split. apply ball_refl. apply Qplus_lt_l. assumption. Qed. Arguments M : clear implicits. Lemma lift_ball_le_helper (m : M X) (q : Qpos) (m0 : M Y) (q0 x : Qpos) (l : lt_ball (f m, (k * q)%Qpos) (m0, x)) (x1 : Qpos) (q4 : (x + x1 <= q0)%Q) (m2 : M X) (q7 : Qpos) (l1 : (m2, q7) <=[PreISpace.S MetricPS] (m, q)) : (f m2, x1) <=[PreSpace.S (toPSL (IGS Metric))] (m0, q0). Proof. simpl. intros. destruct l as (d & balld & dlt). exists (e + k * q + d)%Qpos. split. Focus 2. apply (Qlt_le_trans _ (e + (x + x1))). Focus 2. apply Qplus_le_r. assumption. simpl. rewrite <- !Qplus_assoc. apply Qplus_lt_r. rewrite Qplus_assoc. eapply Qplus_lt_le_compat. rewrite Qplus_comm. assumption. reflexivity. destruct (l1 (Qpos_inv k * e))%Qpos as [x4 a]. destruct a as [H H0]. eapply ball_triangle. 2:eassumption. eapply ball_weak_le. 2: eapply f_lip. 2: eassumption. etransitivity. Focus 2. apply Qlt_le_weak. simpl. rewrite <- (Qpos_inv_scale_1 k e). rewrite <- Qmult_plus_distr_r. eapply Qmult_lt_compat_l. apply Qpos_prf. eassumption. simpl. rewrite Qmult_plus_distr_r. rewrite <- (Qplus_0_r (k * x4)) at 1. apply Qplus_le_r. apply Qlt_le_weak. apply (Qpos_prf (k * q7)%Qpos). Qed. Ltac lt_ball_shrink H a b := let H' := fresh in destruct (lt_ball_shrink _ _ _ H) as (a & b & H'); clear H; rename H' into H. Theorem Cont : IGCont.t (toPSL (IGS Metric)) (IGS Metric) lift. Proof. constructor; simpl PO_car in *. - intros a. apply FormTop.refl. apply true_union'. apply lift_total. - intros a b c l l0. unfold lift in l, l0. destruct a. destruct b, c. lt_ball_shrink l x q2. lt_ball_shrink l0 x0 q3. destruct (uniformly_smaller _ _ _ _ q2 q3) as (eps & xeps & x0eps). destruct (Qpos_smaller eps) as [eps' Heps']. apply (fun U => FormTop.gle_infinity (A := MetricPS) (m, q) U (m, q) (Some (Qpos_inv k * eps'))%Qpos (PreO.le_refl (m, q))). intros u X0. destruct X0 as (l1 & P2). le_downH l1. destruct P2. simpl in i. unfold In in i. destruct a as [m4 x4]. simpl snd in *. subst. destruct u as [m2 ?]. apply FormTop.glrefl. exists (f m2, eps). + split; le_down. * eapply lift_ball_le_helper; try eassumption. apply Qlt_le_weak. eassumption. * eapply lift_ball_le_helper; try eassumption. apply Qlt_le_weak. eassumption. + clear - l2 Heps'. pose proof (le_ball_radius l2) as H. simpl in H. apply lift_f_ap_lt'. eapply Qle_lt_trans. 2: eassumption. rewrite Qmult_comm. apply Qle_inv. assumption. - simpl. intros. eapply lift_f_le; eassumption. - intros [] b c H H0. unfold lift. unfold lift in H. eapply lt_le_trans; eassumption. - intros a b c ix l H. destruct ix; simpl in *. + simpl. clear c l. destruct (Qpos_smaller (Qpos_inv k * q)%Qpos). apply (FormTop.gle_infinity (A := MetricPS) a _ a (Some x)). reflexivity. intros. destruct X0 as (l & d0). le_downH l. destruct d0 as [a0 i l0]. pose proof (lift_f_le H l) as H0. clear H l. destruct (Qpos_between q0) as (x0 & K). destruct K as (H1 & H2). unfold lift in H0. destruct u as [m q1]. pose proof (lt_ball_grow _ _ _ H0) as H3. destruct H3 as (del' & q1del & lt_del'). apply FormTop.glrefl. exists (f m, QposMinMax.Qpos_min (k * x0)%Qpos del'). unfold In. split. le_down. eapply lt_le_weak. eapply le_lt_trans. 2: eassumption. apply le_ball_center. apply QposMinMax.Qpos_min_lb_r. exists (f m, q). reflexivity. apply le_ball_center. etransitivity. apply QposMinMax.Qpos_min_lb_l. apply Qlt_le_weak. apply Qpos_inv_lt. assumption. apply lift_f_ap_lt'. induction (QposMinMax.Qpos_min (k * x0) del') using (QposMinMax.Qpos_min_case (k * x0) del'). 2: eassumption. apply le_ball_radius in l0. simpl in l0. apply Qmult_lt_compat_l_inv with (Qpos_inv k). apply Qpos_prf. unfold In in i. simpl in i. subst. setoid_rewrite Qpos_inv_scale_2. eapply Qle_lt_trans; eassumption. + unfold lift in H. destruct a as [m q]. destruct (lt_ball_grow _ _ _ H) as [x [q0 l0]]. clear H. apply FormTop.glrefl. econstructor. unfold In. split. le_down. apply lt_le_weak. eassumption. exists (f m, x). eapply lt_le_trans; eassumption. reflexivity. apply lift_f_ap_lt'. assumption. Qed. End Lipschitz. (** Try to do it with maps that are only uniformly continuous, rather than just Lipschitz. I can't figure out how to do this proof. *) Context {X Y : MetricSpace}. Delimit Scope uc_scope with uc. Variable f : (X --> Y)%uc. Definition mu' (eps : Qpos) : Qpos := Qpossmaller (mu f eps). Definition mu'_cont (eps : Qpos) a b : ball (mu' eps) a b -> ball eps (f a) (f b). Proof. intros. apply uc_prf. eapply ball_ex_weak_le. apply Qpossmaller_prf. simpl. assumption. Qed. Existing Instances PreO PreO.PreOrder_I. Definition lift_uc : Cont.map (toPSL (IGS (@Metric X))) (toPSL (IGS (@Metric Y))) := fun By Bx => let (x, delta) := Bx in { eps' : Qpos & ((delta < mu' eps') * lt_ball (f x, eps') By)%type }. Lemma lift_shrink {x y delta eps} : lift_uc (y, eps) (x, delta) -> { eps' : Qpos & ((eps' < eps) * lift_uc (y, eps') (x, delta))%type }. Proof. intros H. destruct H as (eps' & mueps' & ltballeps'). pose proof (lt_ball_shrink _ _ _ ltballeps') as H. destruct H as (eps'0 & eps'small & lt_ball_shrunk). exists eps'0. split. assumption. unfold lift. exists eps'. split. assumption. assumption. Qed. Theorem Cont_uc : Cont.t (toPSL (IGS (@Metric X))) (toPSL (IGS (@Metric Y))) lift_uc. Proof. Abort. End Map.
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) b97mv_par_n := 5: b97mv_gamma_x := 0.004: b97mv_par_x := [ [ 1.000, 0, 0], [ 1.308, 0, 1], [ 1.901, 0, 2], [ 0.416, 1, 0], [ 3.070, 1, 1] ]: b97mv_gamma_ss := 0.2: b97mv_par_ss := [ [ 1.000, 0, 0], [ -1.855, 0, 2], [ -5.668, 1, 0], [-20.497, 3, 2], [-20.364, 4, 2] ]: b97mv_gamma_os := 0.006: b97mv_par_os := [ [ 1.000, 0, 0], [ 1.573, 0, 1], [ -6.298, 0, 3], [ 2.535, 1, 0], [ -6.427, 3, 2] ]: $define lda_x_params $include "lda_x.mpl" $include "b97mv.mpl" b97mv_f_aux := (rs, z, xs0, xs1, ts0, ts1) -> + opz_pow_n( z,1)/2 * f_lda_x(rs*(2/(1 + z))^(1/3), 1) * b97mv_g(b97mv_gamma_x, b97mv_wx_ss, b97mv_par_x, b97mv_par_n, xs0, ts0, 0) + opz_pow_n(-z,1)/2 * f_lda_x(rs*(2/(1 - z))^(1/3), 1) * b97mv_g(b97mv_gamma_x, b97mv_wx_ss, b97mv_par_x, b97mv_par_n, xs1, ts1, 0): f := (rs, z, xt, xs0, xs1, us0, us1, ts0, ts1) -> + b97mv_f_aux(rs, z, xs0, xs1, ts0, ts1) + b97mv_f(rs, z, xs0, xs1, ts0, ts1):
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.simplicial_object import category_theory.limits.shapes.finite_products /-! # Split simplicial objects In this file, we introduce the notion of split simplicial object. If `C` is a category that has finite coproducts, a splitting `s : splitting X` of a simplical object `X` in `C` consists of the datum of a sequence of objects `s.N : ℕ → C` (which we shall refer to as "nondegenerate simplices") and a sequence of morphisms `s.ι n : s.N n → X _[n]` that have the property that a certain canonical map identifies `X _[n]` with the coproduct of objects `s.N i` indexed by all possible epimorphisms `[n] ⟶ [i]` in `simplex_category`. (We do not assume that the morphisms `s.ι n` are monomorphisms: in the most common categories, this would be a consequence of the axioms.) Simplicial objects equipped with a splitting form a category `simplicial_object.split C`. ## References * [Stacks: Splitting simplicial objects] https://stacks.math.columbia.edu/tag/017O -/ noncomputable theory open category_theory category_theory.category category_theory.limits opposite simplex_category open_locale simplicial universe u variables {C : Type*} [category C] namespace simplicial_object namespace splitting /-- The index set which appears in the definition of split simplicial objects. -/ def index_set (Δ : simplex_categoryᵒᵖ) := Σ (Δ' : simplex_categoryᵒᵖ), { α : Δ.unop ⟶ Δ'.unop // epi α } namespace index_set /-- The element in `splitting.index_set Δ` attached to an epimorphism `f : Δ ⟶ Δ'`. -/ @[simps] def mk {Δ Δ' : simplex_category} (f : Δ ⟶ Δ') [epi f] : index_set (op Δ) := ⟨op Δ', f, infer_instance⟩ variables {Δ' Δ : simplex_categoryᵒᵖ} (A : index_set Δ) (θ : Δ ⟶ Δ') /-- The epimorphism in `simplex_category` associated to `A : splitting.index_set Δ` -/ def e := A.2.1 instance : epi A.e := A.2.2 lemma ext' : A = ⟨A.1, ⟨A.e, A.2.2⟩⟩ := by tidy lemma ext (A₁ A₂ : index_set Δ) (h₁ : A₁.1 = A₂.1) (h₂ : A₁.e ≫ eq_to_hom (by rw h₁) = A₂.e) : A₁ = A₂ := begin rcases A₁ with ⟨Δ₁, ⟨α₁, hα₁⟩⟩, rcases A₂ with ⟨Δ₂, ⟨α₂, hα₂⟩⟩, simp only at h₁, subst h₁, simp only [eq_to_hom_refl, comp_id, index_set.e] at h₂, simp only [h₂], end instance : fintype (index_set Δ) := fintype.of_injective ((λ A, ⟨⟨A.1.unop.len, nat.lt_succ_iff.mpr (len_le_of_epi (infer_instance : epi A.e))⟩, A.e.to_order_hom⟩) : index_set Δ → (sigma (λ (k : fin (Δ.unop.len+1)), (fin (Δ.unop.len+1) → fin (k+1))))) begin rintros ⟨Δ₁, α₁⟩ ⟨Δ₂, α₂⟩ h₁, induction Δ₁ using opposite.rec, induction Δ₂ using opposite.rec, simp only at h₁, have h₂ : Δ₁ = Δ₂ := by { ext1, simpa only [fin.mk_eq_mk] using h₁.1, }, subst h₂, refine ext _ _ rfl _, ext : 2, exact eq_of_heq h₁.2, end variable (Δ) /-- The distinguished element in `splitting.index_set Δ` which corresponds to the identity of `Δ`. -/ def id : index_set Δ := ⟨Δ, ⟨𝟙 _, by apply_instance,⟩⟩ instance : inhabited (index_set Δ) := ⟨id Δ⟩ variable {Δ} /-- The condition that an element `splitting.index_set Δ` is the distinguished element `splitting.index_set.id Δ`. -/ @[simp] def eq_id : Prop := A = id _ lemma eq_id_iff_eq : A.eq_id ↔ A.1 = Δ := begin split, { intro h, dsimp at h, rw h, refl, }, { intro h, rcases A with ⟨Δ', ⟨f, hf⟩⟩, simp only at h, subst h, refine ext _ _ rfl _, { haveI := hf, simp only [eq_to_hom_refl, comp_id], exact eq_id_of_epi f, }, }, end lemma eq_id_iff_len_eq : A.eq_id ↔ A.1.unop.len = Δ.unop.len := begin rw eq_id_iff_eq, split, { intro h, rw h, }, { intro h, rw ← unop_inj_iff, ext, exact h, }, end lemma eq_id_iff_len_le : A.eq_id ↔ Δ.unop.len ≤ A.1.unop.len := begin rw eq_id_iff_len_eq, split, { intro h, rw h, }, { exact le_antisymm (len_le_of_epi (infer_instance : epi A.e)), }, end lemma eq_id_iff_mono : A.eq_id ↔ mono A.e := begin split, { intro h, dsimp at h, subst h, dsimp only [id, e], apply_instance, }, { intro h, rw eq_id_iff_len_le, exact len_le_of_mono h, } end /-- Given `A : index_set Δ₁`, if `p.unop : unop Δ₂ ⟶ unop Δ₁` is an epi, this is the obvious element in `A : index_set Δ₂` associated to the composition of epimorphisms `p.unop ≫ A.e`. -/ @[simps] def epi_comp {Δ₁ Δ₂ : simplex_categoryᵒᵖ} (A : index_set Δ₁) (p : Δ₁ ⟶ Δ₂) [epi p.unop] : index_set Δ₂ := ⟨A.1, ⟨p.unop ≫ A.e, epi_comp _ _⟩⟩ /-- When `A : index_set Δ` and `θ : Δ → Δ'` is a morphism in `simplex_categoryᵒᵖ`, an element in `index_set Δ'` can be defined by using the epi-mono factorisation of `θ.unop ≫ A.e`. -/ def pull : index_set Δ' := mk (factor_thru_image (θ.unop ≫ A.e)) @[reassoc] lemma fac_pull : (A.pull θ).e ≫ image.ι (θ.unop ≫ A.e) = θ.unop ≫ A.e := image.fac _ end index_set variables (N : ℕ → C) (Δ : simplex_categoryᵒᵖ) (X : simplicial_object C) (φ : Π n, N n ⟶ X _[n]) /-- Given a sequences of objects `N : ℕ → C` in a category `C`, this is a family of objects indexed by the elements `A : splitting.index_set Δ`. The `Δ`-simplices of a split simplicial objects shall identify to the coproduct of objects in such a family. -/ @[simp, nolint unused_arguments] def summand (A : index_set Δ) : C := N A.1.unop.len variable [has_finite_coproducts C] /-- The coproduct of the family `summand N Δ` -/ @[simp] def coprod := ∐ summand N Δ variable {Δ} /-- The inclusion of a summand in the coproduct. -/ @[simp] def ι_coprod (A : index_set Δ) : N A.1.unop.len ⟶ coprod N Δ := sigma.ι _ A variables {N} /-- The canonical morphism `coprod N Δ ⟶ X.obj Δ` attached to a sequence of objects `N` and a sequence of morphisms `N n ⟶ X _[n]`. -/ @[simp] def map (Δ : simplex_categoryᵒᵖ) : coprod N Δ ⟶ X.obj Δ := sigma.desc (λ A, φ A.1.unop.len ≫ X.map A.e.op) end splitting variable [has_finite_coproducts C] /-- A splitting of a simplicial object `X` consists of the datum of a sequence of objects `N`, a sequence of morphisms `ι : N n ⟶ X _[n]` such that for all `Δ : simplex_categoryhᵒᵖ`, the canonical map `splitting.map X ι Δ` is an isomorphism. -/ @[nolint has_nonempty_instance] structure splitting (X : simplicial_object C) := (N : ℕ → C) (ι : Π n, N n ⟶ X _[n]) (map_is_iso' : ∀ (Δ : simplex_categoryᵒᵖ), is_iso (splitting.map X ι Δ)) namespace splitting variables {X Y : simplicial_object C} (s : splitting X) instance map_is_iso (Δ : simplex_categoryᵒᵖ) : is_iso (splitting.map X s.ι Δ) := s.map_is_iso' Δ /-- The isomorphism on simplices given by the axiom `splitting.map_is_iso'` -/ @[simps] def iso (Δ : simplex_categoryᵒᵖ) : coprod s.N Δ ≅ X.obj Δ := as_iso (splitting.map X s.ι Δ) /-- Via the isomorphism `s.iso Δ`, this is the inclusion of a summand in the direct sum decomposition given by the splitting `s : splitting X`. -/ def ι_summand {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) : s.N A.1.unop.len ⟶ X.obj Δ := splitting.ι_coprod s.N A ≫ (s.iso Δ).hom @[reassoc] lemma ι_summand_eq {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) : s.ι_summand A = s.ι A.1.unop.len ≫ X.map A.e.op := begin dsimp only [ι_summand, iso.hom], erw [colimit.ι_desc, cofan.mk_ι_app], end lemma ι_summand_id (n : ℕ) : s.ι_summand (index_set.id (op [n])) = s.ι n := by { erw [ι_summand_eq, X.map_id, comp_id], refl, } /-- As it is stated in `splitting.hom_ext`, a morphism `f : X ⟶ Y` from a split simplicial object to any simplicial object is determined by its restrictions `s.φ f n : s.N n ⟶ Y _[n]` to the distinguished summands in each degree `n`. -/ @[simp] def φ (f : X ⟶ Y) (n : ℕ) : s.N n ⟶ Y _[n] := s.ι n ≫ f.app (op [n]) @[simp, reassoc] lemma ι_summand_comp_app (f : X ⟶ Y) {Δ : simplex_categoryᵒᵖ} (A : index_set Δ) : s.ι_summand A ≫ f.app Δ = s.φ f A.1.unop.len ≫ Y.map A.e.op := by simp only [ι_summand_eq_assoc, φ, nat_trans.naturality, assoc] lemma hom_ext' {Z : C} {Δ : simplex_categoryᵒᵖ} (f g : X.obj Δ ⟶ Z) (h : ∀ (A : index_set Δ), s.ι_summand A ≫ f = s.ι_summand A ≫ g) : f = g := begin rw ← cancel_epi (s.iso Δ).hom, ext A, discrete_cases, simpa only [ι_summand_eq, iso_hom, colimit.ι_desc_assoc, cofan.mk_ι_app, assoc] using h A, end lemma hom_ext (f g : X ⟶ Y) (h : ∀ n : ℕ, s.φ f n = s.φ g n) : f = g := begin ext Δ, apply s.hom_ext', intro A, induction Δ using opposite.rec, induction Δ using simplex_category.rec with n, dsimp, simp only [s.ι_summand_comp_app, h], end /-- The map `X.obj Δ ⟶ Z` obtained by providing a family of morphisms on all the terms of decomposition given by a splitting `s : splitting X` -/ def desc {Z : C} (Δ : simplex_categoryᵒᵖ) (F : Π (A : index_set Δ), s.N A.1.unop.len ⟶ Z) : X.obj Δ ⟶ Z := (s.iso Δ).inv ≫ sigma.desc F @[simp, reassoc] lemma ι_desc {Z : C} (Δ : simplex_categoryᵒᵖ) (F : Π (A : index_set Δ), s.N A.1.unop.len ⟶ Z) (A : index_set Δ) : s.ι_summand A ≫ s.desc Δ F = F A := begin dsimp only [ι_summand, desc], simp only [assoc, iso.hom_inv_id_assoc, ι_coprod], erw [colimit.ι_desc, cofan.mk_ι_app], end /-- A simplicial object that is isomorphic to a split simplicial object is split. -/ @[simps] def of_iso (e : X ≅ Y) : splitting Y := { N := s.N, ι := λ n, s.ι n ≫ e.hom.app (op [n]), map_is_iso' := λ Δ, begin convert (infer_instance : is_iso ((s.iso Δ).hom ≫ e.hom.app Δ)), tidy, end, } @[reassoc] lemma ι_summand_epi_naturality {Δ₁ Δ₂ : simplex_categoryᵒᵖ} (A : index_set Δ₁) (p : Δ₁ ⟶ Δ₂) [epi p.unop] : s.ι_summand A ≫ X.map p = s.ι_summand (A.epi_comp p) := begin dsimp [ι_summand], erw [colimit.ι_desc, colimit.ι_desc, cofan.mk_ι_app, cofan.mk_ι_app], dsimp only [index_set.epi_comp, index_set.e], rw [op_comp, X.map_comp, assoc, quiver.hom.op_unop], end end splitting variable (C) /-- The category `simplicial_object.split C` is the category of simplicial objects in `C` equipped with a splitting, and morphisms are morphisms of simplicial objects which are compatible with the splittings. -/ @[ext, nolint has_nonempty_instance] structure split := (X : simplicial_object C) (s : splitting X) namespace split variable {C} /-- The object in `simplicial_object.split C` attached to a splitting `s : splitting X` of a simplicial object `X`. -/ @[simps] def mk' {X : simplicial_object C} (s : splitting X) : split C := ⟨X, s⟩ /-- Morphisms in `simplicial_object.split C` are morphisms of simplicial objects that are compatible with the splittings. -/ @[nolint has_nonempty_instance] structure hom (S₁ S₂ : split C) := (F : S₁.X ⟶ S₂.X) (f : Π (n : ℕ), S₁.s.N n ⟶ S₂.s.N n) (comm' : ∀ (n : ℕ), S₁.s.ι n ≫ F.app (op [n]) = f n ≫ S₂.s.ι n) @[ext] lemma hom.ext {S₁ S₂ : split C} (Φ₁ Φ₂ : hom S₁ S₂) (h : ∀ (n : ℕ), Φ₁.f n = Φ₂.f n) : Φ₁ = Φ₂ := begin rcases Φ₁ with ⟨F₁, f₁, c₁⟩, rcases Φ₂ with ⟨F₂, f₂, c₂⟩, have h' : f₁ = f₂ := by { ext, apply h, }, subst h', simp only [eq_self_iff_true, and_true], apply S₁.s.hom_ext, intro n, dsimp, rw [c₁, c₂], end restate_axiom hom.comm' attribute [simp, reassoc] hom.comm end split instance : category (split C) := { hom := split.hom, id := λ S, { F := 𝟙 _, f := λ n, 𝟙 _, comm' := by tidy, }, comp := λ S₁ S₂ S₃ Φ₁₂ Φ₂₃, { F := Φ₁₂.F ≫ Φ₂₃.F, f := λ n, Φ₁₂.f n ≫ Φ₂₃.f n, comm' := by tidy, }, } variable {C} namespace split lemma congr_F {S₁ S₂ : split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) : Φ₁.F = Φ₂.F := by rw h lemma congr_f {S₁ S₂ : split C} {Φ₁ Φ₂ : S₁ ⟶ S₂} (h : Φ₁ = Φ₂) (n : ℕ) : Φ₁.f n = Φ₂.f n := by rw h @[simp] lemma id_F (S : split C) : (𝟙 S : S ⟶ S).F = 𝟙 (S.X) := rfl @[simp] lemma id_f (S : split C) (n : ℕ) : (𝟙 S : S ⟶ S).f n = 𝟙 (S.s.N n) := rfl @[simp] lemma comp_F {S₁ S₂ S₃ : split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) : (Φ₁₂ ≫ Φ₂₃).F = Φ₁₂.F ≫ Φ₂₃.F := rfl @[simp] lemma comp_f {S₁ S₂ S₃ : split C} (Φ₁₂ : S₁ ⟶ S₂) (Φ₂₃ : S₂ ⟶ S₃) (n : ℕ) : (Φ₁₂ ≫ Φ₂₃).f n = Φ₁₂.f n ≫ Φ₂₃.f n := rfl @[simp, reassoc] lemma ι_summand_naturality_symm {S₁ S₂ : split C} (Φ : S₁ ⟶ S₂) {Δ : simplex_categoryᵒᵖ} (A : splitting.index_set Δ) : S₁.s.ι_summand A ≫ Φ.F.app Δ = Φ.f A.1.unop.len ≫ S₂.s.ι_summand A := by rw [S₁.s.ι_summand_eq, S₂.s.ι_summand_eq, assoc, Φ.F.naturality, ← Φ.comm_assoc] variable (C) /-- The functor `simplicial_object.split C ⥤ simplicial_object C` which forgets the splitting. -/ @[simps] def forget : split C ⥤ simplicial_object C := { obj := λ S, S.X, map := λ S₁ S₂ Φ, Φ.F, } /-- The functor `simplicial_object.split C ⥤ C` which sends a simplicial object equipped with a splitting to its nondegenerate `n`-simplices. -/ @[simps] def eval_N (n : ℕ) : split C ⥤ C := { obj := λ S, S.s.N n, map := λ S₁ S₂ Φ, Φ.f n, } /-- The inclusion of each summand in the coproduct decomposition of simplices in split simplicial objects is a natural transformation of functors `simplicial_object.split C ⥤ C` -/ @[simps] def nat_trans_ι_summand {Δ : simplex_categoryᵒᵖ} (A : splitting.index_set Δ) : eval_N C A.1.unop.len ⟶ forget C ⋙ (evaluation simplex_categoryᵒᵖ C).obj Δ := { app := λ S, S.s.ι_summand A, naturality' := λ S₁ S₂ Φ, (ι_summand_naturality_symm Φ A).symm, } end split end simplicial_object
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** The Cminor language after instruction selection. *) Require Import Coqlib. Require Import Maps. Require Import AST. Require Import Integers. Require Import Events. Require Import Values. Require Import Memory. Require Import Cminor. Require Import Op. Require Import Globalenvs. Require Import Switch. Require Import Smallstep. (** * Abstract syntax *) (** CminorSel programs share the general structure of Cminor programs: functions, statements and expressions. However, CminorSel uses machine-dependent operations, addressing modes and conditions, as defined in module [Op] and used in lower-level intermediate languages ([RTL] and below). Moreover, to express sharing of sub-computations, a "let" binding is provided (constructions [Elet] and [Eletvar]), using de Bruijn indices to refer to "let"-bound variables. *) Inductive expr : Type := | Evar : ident -> expr | Eop : operation -> exprlist -> expr | Eload : memory_chunk -> addressing -> exprlist -> expr | Econdition : condition -> exprlist -> expr -> expr -> expr | Elet : expr -> expr -> expr | Eletvar : nat -> expr with exprlist : Type := | Enil: exprlist | Econs: expr -> exprlist -> exprlist. Infix ":::" := Econs (at level 60, right associativity) : cminorsel_scope. (** Statements are as in Cminor, except that the [Sifthenelse] construct uses a machine-dependent condition (with multiple arguments), and the [Sstore] construct uses a machine-dependent addressing mode. *) Inductive stmt : Type := | Sskip: stmt | Sassign : ident -> expr -> stmt | Sstore : memory_chunk -> addressing -> exprlist -> expr -> stmt | Scall : option ident -> signature -> expr + ident -> exprlist -> stmt | Stailcall: signature -> expr + ident -> exprlist -> stmt | Sbuiltin : option ident -> external_function -> exprlist -> stmt | Sseq: stmt -> stmt -> stmt | Sifthenelse: condition -> exprlist -> stmt -> stmt -> stmt | Sloop: stmt -> stmt | Sblock: stmt -> stmt | Sexit: nat -> stmt | Sswitch: expr -> list (int * nat) -> nat -> stmt | Sreturn: option expr -> stmt | Slabel: label -> stmt -> stmt | Sgoto: label -> stmt. Record function : Type := mkfunction { fn_id: ident; fn_sig: signature; fn_params: list ident; fn_vars: list ident; fn_stackspace: Z; fn_body: stmt }. Definition fundef := AST.fundef function. Definition program := AST.program fundef unit. Definition funsig (fd: fundef) := match fd with | Internal f => fn_sig f | External ef => ef_sig ef end. (** * Operational semantics *) (** Three kinds of evaluation environments are involved: - [genv]: global environments, define symbols and functions; - [env]: local environments, map local variables to values; - [lenv]: let environments, map de Bruijn indices to values. *) Definition genv := Genv.t fundef unit. Definition letenv := list val. (** Continuations *) Inductive cont: Type := | Kstop: cont (**r stop program execution *) | Kseq: stmt -> cont -> cont (**r execute stmt, then cont *) | Kblock: cont -> cont (**r exit a block, then do cont *) | Kcall: option ident -> function -> val -> env -> cont -> cont. (**r return to caller *) (** States *) Inductive state: Type := | State: (**r execution within a function *) forall (f: function) (**r currently executing function *) (s: stmt) (**r statement under consideration *) (k: cont) (**r its continuation -- what to do next *) (sp: val) (**r current stack pointer *) (e: env) (**r current local environment *) (m: mem), (**r current memory state *) state | Callstate: (**r invocation of a fundef *) forall (f: fundef) (**r fundef to invoke *) (args: list val) (**r arguments provided by caller *) (k: cont) (**r what to do next *) (m: mem), (**r memory state *) state | Returnstate: forall (v: val) (**r return value *) (k: cont) (**r what to do next *) (m: mem), (**r memory state *) state. Section RELSEM. Variable ge: genv. (** The evaluation predicates have the same general shape as those of Cminor. Refer to the description of Cminor semantics for the meaning of the parameters of the predicates. *) Section EVAL_EXPR. Variable sp: val. Variable e: env. Variable m: mem. Inductive eval_expr: letenv -> expr -> val -> Prop := | eval_Evar: forall le id v, PTree.get id e = Some v -> eval_expr le (Evar id) v | eval_Eop: forall le op al vl v, eval_exprlist le al vl -> eval_operation ge sp op vl m = Some v -> eval_expr le (Eop op al) v | eval_Eload: forall le chunk addr al vl vaddr v, eval_exprlist le al vl -> eval_addressing ge sp addr vl = Some vaddr -> Mem.loadv chunk m vaddr = Some v -> eval_expr le (Eload chunk addr al) v | eval_Econdition: forall le cond al b c vl vb v, eval_exprlist le al vl -> eval_condition cond vl m = Some vb -> eval_expr le (if vb then b else c) v -> eval_expr le (Econdition cond al b c) v | eval_Elet: forall le a b v1 v2, eval_expr le a v1 -> eval_expr (v1 :: le) b v2 -> eval_expr le (Elet a b) v2 | eval_Eletvar: forall le n v, nth_error le n = Some v -> eval_expr le (Eletvar n) v with eval_exprlist: letenv -> exprlist -> list val -> Prop := | eval_Enil: forall le, eval_exprlist le Enil nil | eval_Econs: forall le a1 al v1 vl, eval_expr le a1 v1 -> eval_exprlist le al vl -> eval_exprlist le (Econs a1 al) (v1 :: vl). Scheme eval_expr_ind2 := Minimality for eval_expr Sort Prop with eval_exprlist_ind2 := Minimality for eval_exprlist Sort Prop. Inductive eval_expr_or_symbol: letenv -> expr + ident -> val -> Prop := | eval_eos_e: forall le e v, eval_expr le e v -> eval_expr_or_symbol le (inl _ e) v | eval_eos_s: forall le id b, Genv.find_symbol ge id = Some b -> eval_expr_or_symbol le (inr _ id) (Vptr b Int.zero). End EVAL_EXPR. (** Pop continuation until a call or stop *) Fixpoint call_cont (k: cont) : cont := match k with | Kseq s k => call_cont k | Kblock k => call_cont k | _ => k end. Definition is_call_cont (k: cont) : Prop := match k with | Kstop => True | Kcall _ _ _ _ _ => True | _ => False end. (** Find the statement and manufacture the continuation corresponding to a label *) Fixpoint find_label (lbl: label) (s: stmt) (k: cont) {struct s}: option (stmt * cont) := match s with | Sseq s1 s2 => match find_label lbl s1 (Kseq s2 k) with | Some sk => Some sk | None => find_label lbl s2 k end | Sifthenelse cond al s1 s2 => match find_label lbl s1 k with | Some sk => Some sk | None => find_label lbl s2 k end | Sloop s1 => find_label lbl s1 (Kseq (Sloop s1) k) | Sblock s1 => find_label lbl s1 (Kblock k) | Slabel lbl' s' => if ident_eq lbl lbl' then Some(s', k) else find_label lbl s' k | _ => None end. (** One step of execution *) Inductive step: state -> trace -> state -> Prop := | step_skip_seq: forall f s k sp e m, step (State f Sskip (Kseq s k) sp e m) E0 (State f s k sp e m) | step_skip_block: forall f k sp e m, step (State f Sskip (Kblock k) sp e m) E0 (State f Sskip k sp e m) | step_skip_call: forall f k sp e m m', is_call_cont k -> Mem.free m sp 0 f.(fn_stackspace) = Some m' -> forall FID (HFID: FID = f.(fn_id)), step (State f Sskip k (Vptr sp Int.zero) e m) (Event_return FID :: E0) (Returnstate Vundef k m') | step_assign: forall f id a k sp e m v, eval_expr sp e m nil a v -> step (State f (Sassign id a) k sp e m) E0 (State f Sskip k sp (PTree.set id v e) m) | step_store: forall f chunk addr al b k sp e m vl v vaddr m', eval_exprlist sp e m nil al vl -> eval_expr sp e m nil b v -> eval_addressing ge sp addr vl = Some vaddr -> Mem.storev chunk m vaddr v = Some m' -> step (State f (Sstore chunk addr al b) k sp e m) E0 (State f Sskip k sp e m') | step_call: forall f optid sig a bl k sp e m vf vargs fd, eval_expr_or_symbol sp e m nil a vf -> eval_exprlist sp e m nil bl vargs -> Genv.find_funct ge vf = Some fd -> funsig fd = sig -> step (State f (Scall optid sig a bl) k sp e m) E0 (Callstate fd vargs (Kcall optid f sp e k) m) | step_tailcall: forall f sig a bl k sp e m vf vargs fd m', eval_expr_or_symbol (Vptr sp Int.zero) e m nil a vf -> eval_exprlist (Vptr sp Int.zero) e m nil bl vargs -> Genv.find_funct ge vf = Some fd -> funsig fd = sig -> Mem.free m sp 0 f.(fn_stackspace) = Some m' -> forall FID (HFID: FID = f.(fn_id)), step (State f (Stailcall sig a bl) k (Vptr sp Int.zero) e m) (Event_return FID :: E0) (Callstate fd vargs (call_cont k) m') | step_builtin: forall f optid ef al k sp e m vl t v m', eval_exprlist sp e m nil al vl -> external_call ef ge vl m t v m' -> step (State f (Sbuiltin optid ef al) k sp e m) t (State f Sskip k sp (set_optvar optid v e) m') | step_seq: forall f s1 s2 k sp e m, step (State f (Sseq s1 s2) k sp e m) E0 (State f s1 (Kseq s2 k) sp e m) | step_ifthenelse: forall f cond al s1 s2 k sp e m vl b, eval_exprlist sp e m nil al vl -> eval_condition cond vl m = Some b -> step (State f (Sifthenelse cond al s1 s2) k sp e m) E0 (State f (if b then s1 else s2) k sp e m) | step_loop: forall f s k sp e m, step (State f (Sloop s) k sp e m) E0 (State f s (Kseq (Sloop s) k) sp e m) | step_block: forall f s k sp e m, step (State f (Sblock s) k sp e m) E0 (State f s (Kblock k) sp e m) | step_exit_seq: forall f n s k sp e m, step (State f (Sexit n) (Kseq s k) sp e m) E0 (State f (Sexit n) k sp e m) | step_exit_block_0: forall f k sp e m, step (State f (Sexit O) (Kblock k) sp e m) E0 (State f Sskip k sp e m) | step_exit_block_S: forall f n k sp e m, step (State f (Sexit (S n)) (Kblock k) sp e m) E0 (State f (Sexit n) k sp e m) | step_switch: forall f a cases default k sp e m n, eval_expr sp e m nil a (Vint n) -> step (State f (Sswitch a cases default) k sp e m) E0 (State f (Sexit (switch_target n default cases)) k sp e m) | step_return_0: forall f k sp e m m', Mem.free m sp 0 f.(fn_stackspace) = Some m' -> forall FID (HFID: FID = f.(fn_id)), step (State f (Sreturn None) k (Vptr sp Int.zero) e m) (Event_return FID :: E0) (Returnstate Vundef (call_cont k) m') | step_return_1: forall f a k sp e m v m', eval_expr (Vptr sp Int.zero) e m nil a v -> Mem.free m sp 0 f.(fn_stackspace) = Some m' -> forall FID (HFID: FID = f.(fn_id)), step (State f (Sreturn (Some a)) k (Vptr sp Int.zero) e m) (Event_return FID :: E0) (Returnstate v (call_cont k) m') | step_label: forall f lbl s k sp e m, step (State f (Slabel lbl s) k sp e m) E0 (State f s k sp e m) | step_goto: forall f lbl k sp e m s' k', find_label lbl f.(fn_body) (call_cont k) = Some(s', k') -> step (State f (Sgoto lbl) k sp e m) E0 (State f s' k' sp e m) | step_internal_function: forall f vargs k m m' sp e, Mem.alloc m 0 f.(fn_stackspace) = (m', sp) -> set_locals f.(fn_vars) (set_params vargs f.(fn_params)) = e -> forall FID (HFID: FID = f.(fn_id)), step (Callstate (Internal f) vargs k m) (Event_call FID :: E0) (State f f.(fn_body) k (Vptr sp Int.zero) e m') | step_external_function: forall ef vargs k m t vres m', external_call ef ge vargs m t vres m' -> step (Callstate (External ef) vargs k m) t (Returnstate vres k m') | step_return: forall v optid f sp e k m, step (Returnstate v (Kcall optid f sp e k) m) E0 (State f Sskip k sp (set_optvar optid v e) m). End RELSEM. Inductive initial_state (p: program): state -> Prop := | initial_state_intro: forall b f m0, let ge := Genv.globalenv p in Genv.init_mem p = Some m0 -> Genv.find_symbol ge p.(prog_main) = Some b -> Genv.find_funct_ptr ge b = Some f -> funsig f = mksignature nil (Some Tint) -> initial_state p (Callstate f nil Kstop m0). Inductive final_state: state -> int -> Prop := | final_state_intro: forall r m, final_state (Returnstate (Vint r) Kstop m) r. Definition semantics (p: program) := Semantics step (initial_state p) final_state (Genv.globalenv p). Hint Constructors eval_expr eval_exprlist: evalexpr. (** * Lifting of let-bound variables *) (** Instruction selection sometimes generate [Elet] constructs to share the evaluation of a subexpression. Owing to the use of de Bruijn indices for let-bound variables, we need to shift de Bruijn indices when an expression [b] is put in a [Elet a b] context. *) Fixpoint lift_expr (p: nat) (a: expr) {struct a}: expr := match a with | Evar id => Evar id | Eop op bl => Eop op (lift_exprlist p bl) | Eload chunk addr bl => Eload chunk addr (lift_exprlist p bl) | Econdition cond al b c => Econdition cond (lift_exprlist p al) (lift_expr p b) (lift_expr p c) | Elet b c => Elet (lift_expr p b) (lift_expr (S p) c) | Eletvar n => if le_gt_dec p n then Eletvar (S n) else Eletvar n end with lift_exprlist (p: nat) (a: exprlist) {struct a}: exprlist := match a with | Enil => Enil | Econs b cl => Econs (lift_expr p b) (lift_exprlist p cl) end. Definition lift (a: expr): expr := lift_expr O a. (** We now relate the evaluation of a lifted expression with that of the original expression. *) Inductive insert_lenv: letenv -> nat -> val -> letenv -> Prop := | insert_lenv_0: forall le v, insert_lenv le O v (v :: le) | insert_lenv_S: forall le p w le' v, insert_lenv le p w le' -> insert_lenv (v :: le) (S p) w (v :: le'). Lemma insert_lenv_lookup1: forall le p w le', insert_lenv le p w le' -> forall n v, nth_error le n = Some v -> (p > n)%nat -> nth_error le' n = Some v. Proof. induction 1; intros. omegaContradiction. destruct n; simpl; simpl in H0. auto. apply IHinsert_lenv. auto. omega. Qed. Lemma insert_lenv_lookup2: forall le p w le', insert_lenv le p w le' -> forall n v, nth_error le n = Some v -> (p <= n)%nat -> nth_error le' (S n) = Some v. Proof. induction 1; intros. simpl. assumption. simpl. destruct n. omegaContradiction. apply IHinsert_lenv. exact H0. omega. Qed. Lemma eval_lift_expr: forall ge sp e m w le a v, eval_expr ge sp e m le a v -> forall p le', insert_lenv le p w le' -> eval_expr ge sp e m le' (lift_expr p a) v. Proof. intros until w. apply (eval_expr_ind2 ge sp e m (fun le a v => forall p le', insert_lenv le p w le' -> eval_expr ge sp e m le' (lift_expr p a) v) (fun le al vl => forall p le', insert_lenv le p w le' -> eval_exprlist ge sp e m le' (lift_exprlist p al) vl)); simpl; intros; eauto with evalexpr. eapply eval_Econdition; eauto. destruct vb; eauto. eapply eval_Elet. eauto. apply H2. apply insert_lenv_S; auto. case (le_gt_dec p n); intro. apply eval_Eletvar. eapply insert_lenv_lookup2; eauto. apply eval_Eletvar. eapply insert_lenv_lookup1; eauto. Qed. Lemma eval_lift: forall ge sp e m le a v w, eval_expr ge sp e m le a v -> eval_expr ge sp e m (w::le) (lift a) v. Proof. intros. unfold lift. eapply eval_lift_expr. eexact H. apply insert_lenv_0. Qed. Hint Resolve eval_lift: evalexpr.
module Issue282 where module Works where record R : Set where constructor c foo = R.c module Doesn't_work where private record R : Set where constructor c foo = R.c -- Bug.agda:17,9-12 -- Not in scope: -- R.c at Bug.agda:17,9-12 -- when scope checking R.c module Doesn't_work_either where private data D : Set where c : D foo = D.c
theory T96 imports Main begin lemma "( (\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) & (\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) & (\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) & (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) & (\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) & (\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) & (\<forall> x::nat. invo(invo(x)) = x) ) \<longrightarrow> (\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) " nitpick[card nat=4,timeout=86400] oops end
[STATEMENT] lemma merge_terms_idem: "s \<up> s = s" [PROOF STATE] proof (prove) goal (1 subgoal): 1. s \<up> s = s [PROOF STEP] by (induct s) (auto simp add: map_nth_eq_conv)
function [ml] = l2ml(l) % Convert volume from liters to milliliters. % Chad Greene 2012 ml = l*1000;
lemma bilinear_eq: assumes bf: "bilinear f" and bg: "bilinear g" and SB: "S \<subseteq> span B" and TC: "T \<subseteq> span C" and "x\<in>S" "y\<in>T" and fg: "\<And>x y. \<lbrakk>x \<in> B; y\<in> C\<rbrakk> \<Longrightarrow> f x y = g x y" shows "f x y = g x y"
header{* Lemmas about undirected graphs *} theory Ugraph_Lemmas imports Prob_Lemmas "../Girth_Chromatic/Girth_Chromatic" Lattices_Big begin text{* The complete graph is a graph where all possible edges are present. It is wellformed by definition. *} definition complete :: "nat set \<Rightarrow> ugraph" where "complete V = (V, all_edges V)" lemma complete_wellformed: "uwellformed (complete V)" unfolding complete_def uwellformed_def all_edges_def by simp text{* If the set of vertices is finite, the set of edges in the complete graph is finite. *} lemma all_edges_finite: "finite V \<Longrightarrow> finite (all_edges V)" unfolding all_edges_def by simp corollary complete_finite_edges: "finite V \<Longrightarrow> finite (uedges (complete V))" unfolding complete_def using all_edges_finite by simp text{* The sets of possible edges of disjoint sets of vertices are disjoint. *} lemma all_edges_disjoint: "S \<inter> T = {} \<Longrightarrow> all_edges S \<inter> all_edges T = {}" unfolding all_edges_def by force text{* A graph is called `finite' if its set of edges and its set of vertices are finite. *} definition "finite_graph G \<equiv> finite (uverts G) \<and> finite (uedges G)" text{* The complete graph is finite. *} corollary complete_finite: "finite V \<Longrightarrow> finite_graph (complete V)" using complete_finite_edges unfolding finite_graph_def complete_def by simp text{* A graph is called `nonempty' if it contains at least one vertex and at least one edge. *} definition "nonempty_graph G \<equiv> uverts G \<noteq> {} \<and> uedges G \<noteq> {}" text{* A random graph is both wellformed and finite. *} lemma (in edge_space) wellformed_and_finite: assumes "E \<in> Pow S_edges" shows "finite_graph (edge_ugraph E)" "uwellformed (edge_ugraph E)" unfolding finite_graph_def proof show "finite (uverts (edge_ugraph E))" unfolding edge_ugraph_def S_verts_def by simp next show "finite (uedges (edge_ugraph E))" using assms unfolding edge_ugraph_def S_edges_def by (auto intro: all_edges_finite) next show "uwellformed (edge_ugraph E)" using complete_wellformed unfolding edge_ugraph_def S_edges_def complete_def uwellformed_def by force qed text{* The probability for a random graph to have $e$ edges is $p ^ e$. *} lemma (in edge_space) cylinder_empty_prob: "A \<subseteq> S_edges \<Longrightarrow> prob (cylinder S_edges A {}) = p ^ (card A)" using cylinder_prob by auto subsection{* Subgraphs *} definition subgraph :: "ugraph \<Rightarrow> ugraph \<Rightarrow> bool" where "subgraph G' G \<equiv> uverts G' \<subseteq> uverts G \<and> uedges G' \<subseteq> uedges G" lemma subgraph_refl: "subgraph G G" unfolding subgraph_def by simp lemma subgraph_trans: "subgraph G'' G' \<Longrightarrow> subgraph G' G \<Longrightarrow> subgraph G'' G" unfolding subgraph_def by auto lemma subgraph_antisym: "subgraph G G' \<Longrightarrow> subgraph G' G \<Longrightarrow> G = G'" unfolding subgraph_def by (auto simp add: Product_Type.prod_eqI) lemma subgraph_complete: assumes "uwellformed G" shows "subgraph G (complete (uverts G))" proof - { fix e assume "e \<in> uedges G" with assms have "card e = 2" and u: "\<And>u. u \<in> e \<Longrightarrow> u \<in> uverts G" unfolding uwellformed_def by auto moreover then obtain u v where "e = {u, v}" "u \<noteq> v" by (metis card_2_elements) ultimately have "e = mk_uedge (u, v)" "u \<in> uverts G" "v \<in> uverts G" by auto hence "e \<in> all_edges (uverts G)" unfolding all_edges_def using `u \<noteq> v` by fastforce } thus ?thesis unfolding complete_def subgraph_def by auto qed corollary wellformed_all_edges: "uwellformed G \<Longrightarrow> uedges G \<subseteq> all_edges (uverts G)" using subgraph_complete subgraph_def complete_def by simp lemma subgraph_finite: "\<lbrakk> finite_graph G; subgraph G' G \<rbrakk> \<Longrightarrow> finite_graph G'" unfolding finite_graph_def subgraph_def by (metis rev_finite_subset) corollary wellformed_finite: assumes "finite (uverts G)" and "uwellformed G" shows "finite_graph G" proof (rule subgraph_finite[where G = "complete (uverts G)"]) show "subgraph G (complete (uverts G))" using assms by (simp add: subgraph_complete) next have "finite (uedges (complete (uverts G)))" using complete_finite_edges[OF assms(1)] . thus "finite_graph (complete (uverts G))" unfolding finite_graph_def complete_def using assms(1) by auto qed definition subgraphs :: "ugraph \<Rightarrow> ugraph set" where "subgraphs G = {G'. subgraph G' G}" definition nonempty_subgraphs :: "ugraph \<Rightarrow> ugraph set" where "nonempty_subgraphs G = {G'. uwellformed G' \<and> subgraph G' G \<and> nonempty_graph G'}" lemma subgraphs_finite: assumes "finite_graph G" shows "finite (subgraphs G)" proof - have "subgraphs G = {(V', E'). V' \<subseteq> uverts G \<and> E' \<subseteq> uedges G}" unfolding subgraphs_def subgraph_def by force moreover have "finite (uverts G)" "finite (uedges G)" using assms unfolding finite_graph_def by auto ultimately show ?thesis by simp qed corollary nonempty_subgraphs_finite: "finite_graph G \<Longrightarrow> finite (nonempty_subgraphs G)" using subgraphs_finite unfolding nonempty_subgraphs_def subgraphs_def by auto subsection{* Induced subgraphs *} definition induced_subgraph :: "uvert set \<Rightarrow> ugraph \<Rightarrow> ugraph" where "induced_subgraph V G = (V, uedges G \<inter> all_edges V)" lemma induced_is_subgraph: "V \<subseteq> uverts G \<Longrightarrow> subgraph (induced_subgraph V G) G" "V \<subseteq> uverts G \<Longrightarrow> subgraph (induced_subgraph V G) (complete V)" unfolding subgraph_def induced_subgraph_def complete_def by simp+ lemma induced_wellformed: "uwellformed G \<Longrightarrow> V \<subseteq> uverts G \<Longrightarrow> uwellformed (induced_subgraph V G)" unfolding uwellformed_def induced_subgraph_def all_edges_def by force lemma subgraph_union_induced: assumes "uverts H\<^sub>1 \<subseteq> S" and "uverts H\<^sub>2 \<subseteq> T" assumes "uwellformed H\<^sub>1" and "uwellformed H\<^sub>2" shows "subgraph H\<^sub>1 (induced_subgraph S G) \<and> subgraph H\<^sub>2 (induced_subgraph T G) \<longleftrightarrow> 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)" unfolding induced_subgraph_def subgraph_def apply auto using all_edges_mono apply blast using all_edges_mono apply blast using 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)] apply auto done lemma (in edge_space) induced_subgraph_prob: assumes "uverts H \<subseteq> V" and "uwellformed H" and "V \<subseteq> S_verts" shows "prob {es \<in> space P. subgraph H (induced_subgraph V (edge_ugraph es))} = p ^ card (uedges H)" (is "prob ?A = _") proof - have "prob ?A = prob (cylinder S_edges (uedges H) {})" unfolding cylinder_def space_eq subgraph_def induced_subgraph_def edge_ugraph_def S_edges_def 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) also have "\<dots> = p ^ card (uedges H)" proof (rule cylinder_empty_prob) have "uedges H \<subseteq> all_edges (uverts H)" by (rule wellformed_all_edges[OF assms(2)]) also have "all_edges (uverts H) \<subseteq> all_edges S_verts" using assms by (auto simp: all_edges_mono[OF subset_trans]) finally show "uedges H \<subseteq> S_edges" unfolding S_edges_def . qed finally show ?thesis . qed subsection{* Graph isomorphism *} text{* We define graph isomorphism slightly different than in the literature. The usual definition is that two graphs are isomorphic iff there exists a bijection between the vertex sets which preserves the adjacency. However, this complicates many proofs. Instead, we define the intuitive mapping operation on graphs. An isomorphism between two graphs arises if there is a suitable mapping function from the first to the second graph. Later, we show that this operation can be inverted. *} fun map_ugraph :: "(nat \<Rightarrow> nat) \<Rightarrow> ugraph \<Rightarrow> ugraph" where "map_ugraph f (V, E) = (f ` V, (\<lambda>e. f ` e) ` E)" definition isomorphism :: "ugraph \<Rightarrow> ugraph \<Rightarrow> (nat \<Rightarrow> nat) \<Rightarrow> bool" where "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" abbreviation isomorphic :: "ugraph \<Rightarrow> ugraph \<Rightarrow> bool" ("_ \<simeq> _") where "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)" lemma map_ugraph_id: "map_ugraph id = id" unfolding fun_eq_iff by simp lemma map_ugraph_trans: "map_ugraph (g \<circ> f) = (map_ugraph g) \<circ> (map_ugraph f)" unfolding fun_eq_iff by auto (metis imageI image_comp)+ lemma map_ugraph_wellformed: assumes "uwellformed G" and "inj_on f (uverts G)" shows "uwellformed (map_ugraph f G)" unfolding uwellformed_def proof safe fix e' assume "e' \<in> uedges (map_ugraph f G)" hence "e' \<in> (\<lambda>e. f ` e) ` (uedges G)" by (metis map_ugraph.simps snd_conv surjective_pairing) then obtain e where e: "e' = f ` e" "e \<in> uedges G" by blast hence "card e = 2" "e \<subseteq> uverts G" using assms(1) unfolding uwellformed_def by blast+ thus "card e' = 2" using e(1) by (simp add: card_inj_subs[OF assms(2)]) fix u' assume "u' \<in> e'" hence "u' \<in> f ` e" using e by force then obtain u where u: "u' = f u" "u \<in> e" by blast hence "u \<in> uverts G" using assms(1) e(2) unfolding uwellformed_def by blast hence "u' \<in> f ` uverts G" using u(1) by simp thus "u' \<in> uverts (map_ugraph f G)" by (metis map_ugraph.simps fst_conv surjective_pairing) qed lemma map_ugraph_finite: "finite_graph G \<Longrightarrow> finite_graph (map_ugraph f G)" unfolding finite_graph_def by (metis finite_imageI fst_conv map_ugraph.simps snd_conv surjective_pairing) lemma map_ugraph_preserves_sub: assumes "subgraph G\<^sub>1 G\<^sub>2" shows "subgraph (map_ugraph f G\<^sub>1) (map_ugraph f G\<^sub>2)" proof - 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" using assms(1) unfolding subgraph_def by auto thus ?thesis unfolding subgraph_def by (metis map_ugraph.simps fst_conv snd_conv surjective_pairing) qed lemma isomorphic_refl: "uwellformed G \<Longrightarrow> G \<simeq> G" unfolding isomorphism_def by (metis bij_betw_id id_def map_ugraph_id) lemma isomorphic_trans: assumes "G\<^sub>1 \<simeq> G\<^sub>2" and "G\<^sub>2 \<simeq> G\<^sub>3" shows "G\<^sub>1 \<simeq> G\<^sub>3" proof - from assms obtain f\<^sub>1 f\<^sub>2 where 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 map: "G\<^sub>2 = map_ugraph f\<^sub>1 G\<^sub>1" "G\<^sub>3 = map_ugraph f\<^sub>2 G\<^sub>2" unfolding isomorphism_def by blast let ?f = "f\<^sub>2 \<circ> f\<^sub>1" have "bij_betw ?f (uverts G\<^sub>1) (uverts G\<^sub>3)" using bij by (simp add: bij_betw_comp_iff) moreover have "G\<^sub>3 = map_ugraph ?f G\<^sub>1" using map by (simp add: map_ugraph_trans) moreover have "uwellformed G\<^sub>1" "uwellformed G\<^sub>3" using assms unfolding isomorphism_def by simp+ ultimately show "G\<^sub>1 \<simeq> G\<^sub>3" unfolding isomorphism_def by blast qed lemma isomorphic_sym: assumes "G\<^sub>1 \<simeq> G\<^sub>2" shows "G\<^sub>2 \<simeq> G\<^sub>1" proof safe from assms obtain f where "isomorphism G\<^sub>1 G\<^sub>2 f" by blast hence bij: "bij_betw f (uverts G\<^sub>1) (uverts G\<^sub>2)" and map: "G\<^sub>2 = map_ugraph f G\<^sub>1" unfolding isomorphism_def by auto let ?f' = "inv_into (uverts G\<^sub>1) f" have bij': "bij_betw ?f' (uverts G\<^sub>2) (uverts G\<^sub>1)" by (rule bij_betw_inv_into) fact moreover have "uverts G\<^sub>1 = ?f' ` uverts G\<^sub>2" using bij' unfolding bij_betw_def by force moreover have "uedges G\<^sub>1 = (\<lambda>e. ?f' ` e) ` uedges G\<^sub>2" proof - have "uedges G\<^sub>1 = id ` uedges G\<^sub>1" by simp also have "\<dots> = (\<lambda>e. ?f' ` (f ` e)) ` uedges G\<^sub>1" proof (rule image_cong) fix a assume "a \<in> uedges G\<^sub>1" hence "a \<subseteq> uverts G\<^sub>1" using assms unfolding isomorphism_def uwellformed_def by blast thus "id a = inv_into (uverts G\<^sub>1) f ` f ` a" by (metis (full_types) id_def bij bij_betw_imp_inj_on inv_into_image_cancel) qed simp also have "\<dots> = (\<lambda>e. ?f' ` e) ` ((\<lambda>e. f ` e) ` uedges G\<^sub>1)" by (rule image_image[symmetric]) also have "\<dots> = (\<lambda>e. ?f' ` e) ` uedges G\<^sub>2" using bij map by (metis map_ugraph.simps pair_collapse snd_eqD) finally show ?thesis . qed ultimately have "isomorphism G\<^sub>2 G\<^sub>1 ?f'" unfolding isomorphism_def by (metis map_ugraph.simps split_pairs) thus "\<exists>f. isomorphism G\<^sub>2 G\<^sub>1 f" by blast qed (auto simp: assms) lemma isomorphic_cards: assumes "G\<^sub>1 \<simeq> G\<^sub>2" shows "card (uverts G\<^sub>1) = card (uverts G\<^sub>2)" (is "?V") "card (uedges G\<^sub>1) = card (uedges G\<^sub>2)" (is "?E") proof - from assms obtain f where bij: "bij_betw f (uverts G\<^sub>1) (uverts G\<^sub>2)" and map: "G\<^sub>2 = map_ugraph f G\<^sub>1" unfolding isomorphism_def by blast from assms have wellformed: "uwellformed G\<^sub>1" "uwellformed G\<^sub>2" by simp+ show ?V by (rule bij_betw_same_card[OF bij]) let ?g = "\<lambda>e. f ` e" have "bij_betw ?g (Pow (uverts G\<^sub>1)) (Pow (uverts G\<^sub>2))" by (rule bij_lift[OF bij]) moreover have "uedges G\<^sub>1 \<subseteq> Pow (uverts G\<^sub>1)" using wellformed(1) unfolding uwellformed_def by blast ultimately have "card (?g ` uedges G\<^sub>1) = card (uedges G\<^sub>1)" unfolding bij_betw_def by (metis card_inj_subs) thus ?E by (metis map map_ugraph.simps snd_conv surjective_pairing) qed subsection{* Isomorphic subgraphs *} text{* The somewhat sloppy term `isomorphic subgraph' denotes a subgraph which is isomorphic to a fixed other graph. For example, saying that a graph contains a triangle usually means that it contains \emph{any} triangle, not the specific triangle with the nodes $1$, $2$ and $3$. Hence, such a graph would have a triangle as an isomorphic subgraph. *} definition subgraph_isomorphic :: "ugraph \<Rightarrow> ugraph \<Rightarrow> bool" ("_ \<sqsubseteq> _") where "G' \<sqsubseteq> G \<equiv> uwellformed G \<and> (\<exists>G''. G' \<simeq> G'' \<and> subgraph G'' G)" lemma subgraph_is_subgraph_isomorphic: "\<lbrakk> uwellformed G'; uwellformed G; subgraph G' G \<rbrakk> \<Longrightarrow> G' \<sqsubseteq> G" unfolding subgraph_isomorphic_def by (metis isomorphic_refl) lemma isomorphic_is_subgraph_isomorphic: "G\<^sub>1 \<simeq> G\<^sub>2 \<Longrightarrow> G\<^sub>1 \<sqsubseteq> G\<^sub>2" unfolding subgraph_isomorphic_def by (metis subgraph_refl) lemma subgraph_isomorphic_refl: "uwellformed G \<Longrightarrow> G \<sqsubseteq> G" unfolding subgraph_isomorphic_def by (metis isomorphic_refl subgraph_refl) lemma subgraph_isomorphic_pre_iso_closed: assumes "G\<^sub>1 \<simeq> G\<^sub>2" and "G\<^sub>2 \<sqsubseteq> G\<^sub>3" shows "G\<^sub>1 \<sqsubseteq> G\<^sub>3" unfolding subgraph_isomorphic_def proof show "uwellformed G\<^sub>3" using assms unfolding subgraph_isomorphic_def by blast next from assms(2) obtain G\<^sub>2' where "G\<^sub>2 \<simeq> G\<^sub>2'" "subgraph G\<^sub>2' G\<^sub>3" unfolding subgraph_isomorphic_def by blast moreover with assms(1) have "G\<^sub>1 \<simeq> G\<^sub>2'" by (metis isomorphic_trans) ultimately show "\<exists>G''. G\<^sub>1 \<simeq> G'' \<and> subgraph G'' G\<^sub>3" by blast qed lemma subgraph_isomorphic_pre_subgraph_closed: assumes "uwellformed G\<^sub>1" and "subgraph G\<^sub>1 G\<^sub>2" and "G\<^sub>2 \<sqsubseteq> G\<^sub>3" shows "G\<^sub>1 \<sqsubseteq> G\<^sub>3" unfolding subgraph_isomorphic_def proof show "uwellformed G\<^sub>3" using assms unfolding subgraph_isomorphic_def by blast next from assms(3) obtain G\<^sub>2' where "G\<^sub>2 \<simeq> G\<^sub>2'" "subgraph G\<^sub>2' G\<^sub>3" unfolding subgraph_isomorphic_def by blast 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" unfolding isomorphism_def by blast let ?G\<^sub>1' = "map_ugraph f G\<^sub>1" have "bij_betw f (uverts G\<^sub>1) (f ` uverts G\<^sub>1)" using bij(1) assms(2) unfolding subgraph_def by (auto intro: bij_betw_subset) moreover hence "uwellformed ?G\<^sub>1'" using map_ugraph_wellformed[OF assms(1)] unfolding bij_betw_def .. ultimately have "G\<^sub>1 \<simeq> ?G\<^sub>1'" using assms(1) unfolding isomorphism_def by (metis map_ugraph.simps fst_conv surjective_pairing) moreover have "subgraph ?G\<^sub>1' G\<^sub>3" (* Yes, I will TOTALLY understand that step tomorrow. *) using subgraph_trans[OF map_ugraph_preserves_sub[OF assms(2)]] bij(2) `subgraph G\<^sub>2' G\<^sub>3` by simp ultimately show "\<exists>G''. G\<^sub>1 \<simeq> G'' \<and> subgraph G'' G\<^sub>3" by blast qed lemmas subgraph_isomorphic_pre_closed = subgraph_isomorphic_pre_subgraph_closed subgraph_isomorphic_pre_iso_closed lemmas subgraph_isomorphic_post_closed = subgraph_isomorphic_post_iso_closed lemmas subgraph_isomorphic_closed = subgraph_isomorphic_pre_closed subgraph_isomorphic_post_closed subsection{* Density *} text{* The density of a graph is the quotient of the number of edges and the number of vertices of a graph. *} definition density :: "ugraph \<Rightarrow> real" where "density G = card (uedges G) / card (uverts G)" text{* The maximum density of a graph is the density of its densest nonempty subgraph. *} definition max_density :: "ugraph \<Rightarrow> real" where "max_density G = Lattices_Big.Max (density ` nonempty_subgraphs G)" text{* We prove some obvious results about the maximum density, such as that there is a subgraph which has the maximum density and that the (maximum) density is preserved by isomorphisms. The proofs are a bit complicated by the fact that most facts about @{term Lattices_Big.Max} require non-emptiness of the target set, but we need that anyway to get a value out of it. *} lemma max_density_is_max: assumes "finite_graph G" and "finite_graph G'" and "nonempty_graph G'" and "uwellformed G'" and "subgraph G' G" shows "density G' \<le> max_density G" unfolding max_density_def proof (rule Max_ge) show "finite (density ` nonempty_subgraphs G)" using assms(1) by (simp add: nonempty_subgraphs_finite) next show "density G' \<in> density ` nonempty_subgraphs G" unfolding nonempty_subgraphs_def using assms by blast qed lemma max_density_gr_zero: assumes "finite_graph G" and "nonempty_graph G" and "uwellformed G" shows "0 < max_density G" proof - have "0 < card (uverts G)" "0 < card (uedges G)" using assms unfolding finite_graph_def nonempty_graph_def by auto hence "0 < density G" unfolding density_def by simp also have "density G \<le> max_density G" using assms by (simp add: max_density_is_max subgraph_refl) finally show ?thesis . qed lemma isomorphic_density: assumes "G\<^sub>1 \<simeq> G\<^sub>2" shows "density G\<^sub>1 = density G\<^sub>2" unfolding density_def using isomorphic_cards[OF assms] by simp lemma isomorphic_max_density: 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" shows "max_density G\<^sub>1 = max_density G\<^sub>2" proof - --{* The proof strategy is not completely straightforward. We first show that if two graphs are isomorphic, the maximum density of one graph is less or equal than the maximum density of the other graph. The reason is that this proof is quite long and the desired result directly follows from the symmetry of the isomorphism relation.\footnote{Some famous mathematician once said that if you prove that $a \le b$ and $b \le a$, you know \emph{that} these numbers are equal, but not \emph{why}. Since many proofs in this work are mostly opaque to me, I can live with that.} *} { fix A B assume A: "nonempty_graph A" "finite_graph A" assume iso: "A \<simeq> B" then obtain f where f: "B = map_ugraph f A" "bij_betw f (uverts A) (uverts B)" unfolding isomorphism_def by blast have wellformed: "uwellformed A" using iso unfolding isomorphism_def by simp --{* We observe that the set of densities of the subgraphs does not change if we map the subgraphs first. *} have "density ` nonempty_subgraphs A = density ` (map_ugraph f ` nonempty_subgraphs A)" proof (rule image_comp_cong) fix G assume "G \<in> nonempty_subgraphs A" hence "uverts G \<subseteq> uverts A" "uwellformed G" unfolding nonempty_subgraphs_def subgraph_def by simp+ hence "inj_on f (uverts G)" using f(2) unfolding bij_betw_def by (metis subset_inj_on) hence "G \<simeq> map_ugraph f G" unfolding isomorphism_def bij_betw_def by (metis map_ugraph.simps fst_conv surjective_pairing map_ugraph_wellformed `uwellformed G`) thus "density G = density (map_ugraph f G)" by (fact isomorphic_density) qed --{* Additionally, we show that the operations @{term nonempty_subgraphs} and @{term map_ugraph} can be swapped without changing the densities. This is an obvious result, because @{term map_ugraph} does not change the structure of a graph. Still, the proof is a bit hairy, which is why we only show inclusion in one direction and use symmetry of isomorphism later. *} also have "\<dots> \<subseteq> density ` nonempty_subgraphs (map_ugraph f A)" proof (rule image_mono, rule subsetI) fix G'' assume "G'' \<in> map_ugraph f ` nonempty_subgraphs A" then obtain G' where G_subst: "G'' = map_ugraph f G'" "G' \<in> nonempty_subgraphs A" by blast hence G': "subgraph G' A" "nonempty_graph G'" "uwellformed G'" unfolding nonempty_subgraphs_def by auto hence "inj_on f (uverts G')" using f unfolding bij_betw_def subgraph_def by (metis subset_inj_on) hence "uwellformed G''" using map_ugraph_wellformed G' G_subst by simp moreover have "nonempty_graph G''" using G' G_subst unfolding nonempty_graph_def by (metis map_ugraph.simps fst_conv snd_conv surjective_pairing empty_is_image) moreover have "subgraph G'' (map_ugraph f A)" using map_ugraph_preserves_sub G' G_subst by simp ultimately show "G'' \<in> nonempty_subgraphs (map_ugraph f A)" unfolding nonempty_subgraphs_def by simp qed finally have "density ` nonempty_subgraphs A \<subseteq> density ` nonempty_subgraphs (map_ugraph f A)" . hence "max_density A \<le> max_density (map_ugraph f A)" unfolding max_density_def proof (rule Max_mono) have "A \<in> nonempty_subgraphs A" using A iso unfolding nonempty_subgraphs_def by (simp add: subgraph_refl) thus "density ` nonempty_subgraphs A \<noteq> {}" by blast next have "finite (nonempty_subgraphs (map_ugraph f A))" by (rule nonempty_subgraphs_finite[OF map_ugraph_finite[OF A(2)]]) thus "finite (density ` nonempty_subgraphs (map_ugraph f A))" by blast qed hence "max_density A \<le> max_density B" by (subst f) } note le = this show ?thesis using le[OF assms(2) assms(4) assms(1)] le[OF assms(3) assms(5) isomorphic_sym[OF assms(1)]] by (fact antisym) qed subsection{* Fixed selectors *} text{* \label{sec:selector} In the proof of the main theorem in the lecture notes, the concept of a ``fixed copy'' of a graph is fundamental. Let $H$ be a fixed graph. A `fixed selector' is basically a function mapping a set with the same size as the vertex set of $H$ to a new graph which is isomorphic to $H$ and its vertex set is the same as the input set.\footnote{We call such a selector \emph{fixed} because its result is deterministic.} *} definition "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)" text{* Obviously, there may be many possible fixed selectors for a given graph. First, we show that there is always at least one. This is sufficient, because we can always obtain that one and use its properties without knowing exactly which one we chose. *} lemma ex_fixed_selector: assumes "uwellformed H" and "finite_graph H" obtains f where "is_fixed_selector H f" proof --{* I guess this is the only place in the whole work where we make use of a nifty little HOL feature called \emph{SOME}, which is basically Hilbert's choice operator. The reason is that any bijection between the the vertex set of @{term H} and the input set gives rise to a fixed selector function. In the lecture notes, a specific bijection was defined, but this is shorter and more elegant. *} let ?bij = "\<lambda>V. SOME g. bij_betw g (uverts H) V" let ?f = "\<lambda>V. map_ugraph (?bij V) H" { fix V :: "uvert set" assume "finite V" "card (uverts H) = card V" moreover have "finite (uverts H)" using assms unfolding finite_graph_def by simp ultimately have "bij_betw (?bij V) (uverts H) V" by (metis finite_same_card_bij someI_ex) moreover hence *: "uverts (?f V) = V \<and> uwellformed (?f V)" using map_ugraph_wellformed[OF assms(1)] by (metis bij_betw_def map_ugraph.simps fst_conv surjective_pairing) ultimately have **: "H \<simeq> ?f V" unfolding isomorphism_def using assms(1) by auto note * ** } thus "is_fixed_selector H ?f" unfolding is_fixed_selector_def by blast qed lemma fixed_selector_induced_subgraph: assumes "is_fixed_selector H f" and "card (uverts H) = card V" and "finite V" assumes sub: "subgraph (f V) (induced_subgraph V G)" and V: "V \<subseteq> uverts G" and G: "uwellformed G" shows "H \<sqsubseteq> G" proof - have post: "H \<simeq> f V" "uverts (f V) = V" using assms unfolding is_fixed_selector_def by auto have "H \<sqsubseteq> f V" by (rule isomorphic_is_subgraph_isomorphic) (simp add: post) also have "f V \<sqsubseteq> induced_subgraph V G" by (rule subgraph_is_subgraph_isomorphic) (auto simp: induced_wellformed[OF G V] post sub) also have "\<dots> \<sqsubseteq> G" by (rule subgraph_is_subgraph_isomorphic[OF induced_wellformed]) (auto simp: G V induced_is_subgraph(1)[OF V]) finally show "H \<sqsubseteq> G" . qed end
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import logic.encodable.basic import order.atoms import order.upper_lower.basic /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal P`: the type of nonempty, upward directed, and downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `order.is_ideal P`: a predicate for when a `set P` is an ideal. - `order.ideal.principal p`: the principal ideal generated by `p : P`. - `order.ideal.is_proper P`: a predicate for proper ideals. Dual to the notion of a proper filter. - `order.ideal.is_maximal`: a predicate for maximal ideals. Dual to the notion of an ultrafilter. - `order.cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `order.ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. (This a form of the Rasiowa–Sikorski lemma.) ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> - <https://en.wikipedia.org/wiki/Cofinal_(mathematics)> - <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_lemma> Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ open function set namespace order variables {P : Type*} /-- An ideal on an order `P` is a subset of `P` that is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ structure ideal (P) [has_le P] extends lower_set P := (nonempty' : carrier.nonempty) (directed' : directed_on (≤) carrier) /-- A subset of a preorder `P` is an ideal if it is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ @[mk_iff] structure is_ideal {P} [has_le P] (I : set P) : Prop := (is_lower_set : is_lower_set I) (nonempty : I.nonempty) (directed : directed_on (≤) I) /-- Create an element of type `order.ideal` from a set satisfying the predicate `order.is_ideal`. -/ def is_ideal.to_ideal [has_le P] {I : set P} (h : is_ideal I) : ideal P := ⟨⟨I, h.is_lower_set⟩, h.nonempty, h.directed⟩ namespace ideal section has_le variables [has_le P] section variables {I J s t : ideal P} {x y : P} lemma to_lower_set_injective : injective (to_lower_set : ideal P → lower_set P) := λ s t h, by { cases s, cases t, congr' } instance : set_like (ideal P) P := { coe := λ s, s.carrier, coe_injective' := λ s t h, to_lower_set_injective $ set_like.coe_injective h } @[ext] lemma ext {s t : ideal P} : (s : set P) = t → s = t := set_like.ext' @[simp] lemma carrier_eq_coe (s : ideal P) : s.carrier = s := rfl @[simp] lemma coe_to_lower_set (s : ideal P) : (s.to_lower_set : set P) = s := rfl protected lemma lower (s : ideal P) : is_lower_set (s : set P) := s.lower' protected lemma nonempty (s : ideal P) : (s : set P).nonempty := s.nonempty' protected lemma directed (s : ideal P) : directed_on (≤) (s : set P) := s.directed' protected lemma is_ideal (s : ideal P) : is_ideal (s : set P) := ⟨s.lower, s.nonempty, s.directed⟩ lemma mem_compl_of_ge {x y : P} : x ≤ y → x ∈ (I : set P)ᶜ → y ∈ (I : set P)ᶜ := λ h, mt $ I.lower h /-- The partial ordering by subset inclusion, inherited from `set P`. -/ instance : partial_order (ideal P) := partial_order.lift coe set_like.coe_injective @[simp] lemma coe_subset_coe : (s : set P) ⊆ t ↔ s ≤ t := iff.rfl @[simp] lemma coe_ssubset_coe : (s : set P) ⊂ t ↔ s < t := iff.rfl @[trans] lemma mem_of_mem_of_le {x : P} {I J : ideal P} : x ∈ I → I ≤ J → x ∈ J := @set.mem_of_mem_of_subset P x I J /-- A proper ideal is one that is not the whole set. Note that the whole set might not be an ideal. -/ @[mk_iff] class is_proper (I : ideal P) : Prop := (ne_univ : (I : set P) ≠ univ) lemma is_proper_of_not_mem {I : ideal P} {p : P} (nmem : p ∉ I) : is_proper I := ⟨λ hp, begin change p ∉ ↑I at nmem, rw hp at nmem, exact nmem (mem_univ p), end⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. Note that `is_coatom` is less general because ideals only have a top element when `P` is directed and nonempty. -/ @[mk_iff] class is_maximal (I : ideal P) extends is_proper I : Prop := (maximal_proper : ∀ ⦃J : ideal P⦄, I < J → (J : set P) = univ) lemma inter_nonempty [is_directed P (≥)] (I J : ideal P) : (I ∩ J : set P).nonempty := begin obtain ⟨a, ha⟩ := I.nonempty, obtain ⟨b, hb⟩ := J.nonempty, obtain ⟨c, hac, hbc⟩ := exists_le_le a b, exact ⟨c, I.lower hac ha, J.lower hbc hb⟩, end end section directed variables [is_directed P (≤)] [nonempty P] {I : ideal P} /-- In a directed and nonempty order, the top ideal of a is `univ`. -/ instance : order_top (ideal P) := { top := ⟨⊤, univ_nonempty, directed_on_univ⟩, le_top := λ I, le_top } @[simp] lemma top_to_lower_set : (⊤ : ideal P).to_lower_set = ⊤ := rfl @[simp] lemma coe_top : ((⊤ : ideal P) : set P) = univ := rfl lemma is_proper_of_ne_top (ne_top : I ≠ ⊤) : is_proper I := ⟨λ h, ne_top $ ext h⟩ lemma is_proper.ne_top (hI : is_proper I) : I ≠ ⊤ := λ h, is_proper.ne_univ $ congr_arg coe h lemma _root_.is_coatom.is_proper (hI : is_coatom I) : is_proper I := is_proper_of_ne_top hI.1 lemma is_proper_iff_ne_top : is_proper I ↔ I ≠ ⊤ := ⟨λ h, h.ne_top, λ h, is_proper_of_ne_top h⟩ lemma is_maximal.is_coatom (h : is_maximal I) : is_coatom I := ⟨is_maximal.to_is_proper.ne_top, λ J h, ext $ is_maximal.maximal_proper h⟩ lemma is_maximal.is_coatom' [is_maximal I] : is_coatom I := is_maximal.is_coatom ‹_› lemma _root_.is_coatom.is_maximal (hI : is_coatom I) : is_maximal I := { maximal_proper := λ _ _, by simp [hI.2 _ ‹_›], ..is_coatom.is_proper ‹_› } lemma is_maximal_iff_is_coatom : is_maximal I ↔ is_coatom I := ⟨λ h, h.is_coatom, λ h, h.is_maximal⟩ end directed section order_bot variables [order_bot P] @[simp] lemma bot_mem (s : ideal P) : ⊥ ∈ s := s.lower bot_le s.nonempty.some_mem end order_bot section order_top variables [order_top P] {I : ideal P} lemma top_of_top_mem (h : ⊤ ∈ I) : I = ⊤ := by { ext, exact iff_of_true (I.lower le_top h) trivial } lemma is_proper.top_not_mem (hI : is_proper I) : ⊤ ∉ I := λ h, hI.ne_top $ top_of_top_mem h end order_top end has_le section preorder variables [preorder P] section variables {I J : ideal P} {x y : P} /-- The smallest ideal containing a given element. -/ @[simps] def principal (p : P) : ideal P := { to_lower_set := lower_set.Iic p, nonempty' := nonempty_Iic, directed' := λ x hx y hy, ⟨p, le_rfl, hx, hy⟩ } instance [inhabited P] : inhabited (ideal P) := ⟨ideal.principal default⟩ @[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I := ⟨λ h, h le_rfl, λ hx y hy, I.lower hy hx⟩ @[simp] lemma mem_principal : x ∈ principal y ↔ x ≤ y := iff.rfl end section order_bot variables [order_bot P] /-- There is a bottom ideal when `P` has a bottom element. -/ instance : order_bot (ideal P) := { bot := principal ⊥, bot_le := by simp } @[simp] lemma principal_bot : principal (⊥ : P) = ⊥ := rfl end order_bot section order_top variables [order_top P] @[simp] lemma principal_top : principal (⊤ : P) = ⊤ := to_lower_set_injective $ lower_set.Iic_top end order_top end preorder section semilattice_sup variables [semilattice_sup P] {x y : P} {I s : ideal P} /-- A specific witness of `I.directed` when `P` has joins. -/ lemma sup_mem (hx : x ∈ s) (hy : y ∈ s) : x ⊔ y ∈ s := let ⟨z, hz, hx, hy⟩ := s.directed x hx y hy in s.lower (sup_le hx hy) hz @[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := ⟨λ h, ⟨I.lower le_sup_left h, I.lower le_sup_right h⟩, λ h, sup_mem h.1 h.2⟩ end semilattice_sup section semilattice_sup_directed variables [semilattice_sup P] [is_directed P (≥)] {x : P} {I J K s t : ideal P} /-- The infimum of two ideals of a co-directed order is their intersection. -/ instance : has_inf (ideal P) := ⟨λ I J, { to_lower_set := I.to_lower_set ⊓ J.to_lower_set, nonempty' := inter_nonempty I J, directed' := λ x hx y hy, ⟨x ⊔ y, ⟨sup_mem hx.1 hy.1, sup_mem hx.2 hy.2⟩, by simp⟩ }⟩ /-- The supremum of two ideals of a co-directed order is the union of the down sets of the pointwise supremum of `I` and `J`. -/ instance : has_sup (ideal P) := ⟨λ I J, { carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j}, nonempty' := by { cases inter_nonempty I J, exact ⟨w, w, h.1, w, h.2, le_sup_left⟩ }, directed' := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩, ⟨x ⊔ y, ⟨xi ⊔ yi, sup_mem ‹_› ‹_›, xj ⊔ yj, sup_mem ‹_› ‹_›, sup_le (calc x ≤ xi ⊔ xj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left) (calc y ≤ yi ⊔ yj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩, le_sup_left, le_sup_right⟩, lower' := λ x y h ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, h.trans ‹_›⟩ }⟩ instance : lattice (ideal P) := { sup := (⊔), le_sup_left := λ I J (i ∈ I), by { cases J.nonempty, exact ⟨i, ‹_›, w, ‹_›, le_sup_left⟩ }, le_sup_right := λ I J (j ∈ J), by { cases I.nonempty, exact ⟨w, ‹_›, j, ‹_›, le_sup_right⟩ }, sup_le := λ I J K hIK hJK a ⟨i, hi, j, hj, ha⟩, K.lower ha $ sup_mem (mem_of_mem_of_le hi hIK) (mem_of_mem_of_le hj hJK), inf := (⊓), inf_le_left := λ I J, inter_subset_left I J, inf_le_right := λ I J, inter_subset_right I J, le_inf := λ I J K, subset_inter, .. ideal.partial_order } @[simp] lemma coe_sup : ↑(s ⊔ t) = {x | ∃ (a ∈ s) (b ∈ t), x ≤ a ⊔ b} := rfl @[simp] lemma coe_inf : (↑(s ⊓ t) : set P) = s ∩ t := rfl @[simp] lemma mem_inf : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_sup : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff.rfl lemma lt_sup_principal_of_not_mem (hx : x ∉ I) : I < I ⊔ principal x := le_sup_left.lt_of_ne $ λ h, hx $ by simpa only [left_eq_sup, principal_le_iff] using h end semilattice_sup_directed section semilattice_sup_order_bot variables [semilattice_sup P] [order_bot P] {x : P} {I J K : ideal P} instance : has_Inf (ideal P) := ⟨λ S, { to_lower_set := ⨅ s ∈ S, to_lower_set s, nonempty' := ⟨⊥, begin rw [lower_set.carrier_eq_coe, lower_set.coe_infi₂, set.mem_Inter₂], exact λ s _, s.bot_mem, end⟩, directed' := λ a ha b hb, ⟨a ⊔ b, ⟨ begin rw [lower_set.carrier_eq_coe, lower_set.coe_infi₂, set.mem_Inter₂] at ⊢ ha hb, exact λ s hs, sup_mem (ha _ hs) (hb _ hs), end, le_sup_left, le_sup_right⟩⟩ }⟩ variables {S : set (ideal P)} @[simp] lemma coe_Inf : (↑(Inf S) : set P) = ⋂ s ∈ S, ↑s := lower_set.coe_infi₂ _ @[simp] lemma mem_Inf : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := by simp_rw [←set_like.mem_coe, coe_Inf, mem_Inter₂] instance : complete_lattice (ideal P) := { ..ideal.lattice, ..complete_lattice_of_Inf (ideal P) (λ S, begin refine ⟨λ s hs, _, λ s hs, by rwa [←coe_subset_coe, coe_Inf, subset_Inter₂_iff]⟩, rw [←coe_subset_coe, coe_Inf], exact bInter_subset_of_mem hs, end) } end semilattice_sup_order_bot section distrib_lattice variables [distrib_lattice P] variables {I J : ideal P} lemma eq_sup_of_le_sup {x i j: P} (hi : i ∈ I) (hj : j ∈ J) (hx : x ≤ i ⊔ j) : ∃ (i' ∈ I) (j' ∈ J), x = i' ⊔ j' := begin refine ⟨x ⊓ i, I.lower inf_le_right hi, x ⊓ j, J.lower inf_le_right hj, _⟩, calc x = x ⊓ (i ⊔ j) : left_eq_inf.mpr hx ... = (x ⊓ i) ⊔ (x ⊓ j) : inf_sup_left, end lemma coe_sup_eq : ↑(I ⊔ J) = {x | ∃ i ∈ I, ∃ j ∈ J, x = i ⊔ j} := set.ext $ λ _, ⟨λ ⟨_, _, _, _, _⟩, eq_sup_of_le_sup ‹_› ‹_› ‹_›, λ ⟨i, _, j, _, _⟩, ⟨i, ‹_›, j, ‹_›, le_of_eq ‹_›⟩⟩ end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_proper.not_mem_of_compl_mem (hI : is_proper I) (hxc : xᶜ ∈ I) : x ∉ I := begin intro hx, apply hI.top_not_mem, have ht : x ⊔ xᶜ ∈ I := sup_mem ‹_› ‹_›, rwa sup_compl_eq_top at ht, end lemma is_proper.not_mem_or_compl_not_mem (hI : is_proper I) : x ∉ I ∨ xᶜ ∉ I := have h : xᶜ ∈ I → x ∉ I := hI.not_mem_of_compl_mem, by tauto end boolean_algebra end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P) [preorder P] := (carrier : set P) (mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y) namespace cofinal variables [preorder P] instance : inhabited (cofinal P) := ⟨{ carrier := univ, mem_gt := λ x, ⟨x, trivial, le_rfl⟩ }⟩ instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩ variables (D : cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := classical.some $ D.mem_gt x lemma above_mem : D.above x ∈ D := exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a lemma le_above : x ≤ D.above x := exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b end cofinal section ideal_of_cofinals variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequence_of_cofinals : ℕ → P | 0 := p | (n+1) := match encodable.decode ι n with | none := sequence_of_cofinals n | some i := (𝒟 i).above (sequence_of_cofinals n) end lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) := by { apply monotone_nat_of_le_succ, intros n, dunfold sequence_of_cofinals, cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, } lemma sequence_of_cofinals.encode_mem (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, } /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals : ideal P := { carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n }, lower' := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, nonempty' := ⟨p, 0, le_rfl⟩, directed' := λ x ⟨n, hn⟩ y ⟨m, hm⟩, ⟨_, ⟨max n m, le_rfl⟩, le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩ } lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_rfl⟩ /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := ⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_rfl⟩ end ideal_of_cofinals end order
Barker was equally proficient in watercolour , pen and ink , oils , and pastels . Kate Greenaway and the Pre @-@ Raphaelites were the principal influences on her work . She claimed to paint instinctively and rejected artistic theories . Barker died in 1973 . Though she published Flower Fairy books with spring , summer , and autumn themes , it wasn 't until 1985 that a winter collection was assembled from her remaining work and published posthumously .
The complex number $rcis(r, 0)$ is equal to the real number $r$.
# The Gamma Function $\Gamma$ $\Gamma(p)$ is a generalization of the factorial function to real and complex $p$. If $p$ is a positive integer then $\Gamma(p) = (p-1)!$, the familar factorial __except with the argument offset by 1__ (widely described as an unfortunate historical accident). More generally we can define $$ \Gamma(z) = \int_0^{\infty} x^{z-1} e^{-x} dx \quad \text{for} \quad Re(z) > 0 $$ Gamma functions still obey the same recursion relation as factorials, $\Gamma(z+1) = z \Gamma(z)$, even for $Re(z) < 0$. Rearranging this slightly gives the definition for negative numbers: $$ \Gamma(z) = \frac{1}{z} \Gamma(z+1) $$ However, the function is undefined (divergent) when $z$ is zero or a negative integer. ```python import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) ``` SciPy will evaluate Gamma functions very simply: ```python import scipy.special as sp xlims = (-4, 4) x = np.linspace(xlims[0], xlims[1], 500) gammas = sp.gamma(x) # display(gammas) plt.figure(figsize=(9, 9)) plt.plot(x, gammas) plt.xlim(xlims) plt.ylim((-10, 10)) plt.xlabel('$x$') plt.ylabel('$\\Gamma(x)$') plt.title('Plot of the Gamma function for real x') plt.grid(True) ``` Complex values also work without fuss, but remember that $\sqrt{-1}$ is entered as `1j` in Python. Plots of $\Gamma(z)$ in the complex plane are not at all simple and quite pretty, so there are plenty of examples on the web. ```python sp.gamma(1.1+0.5j) ``` (0.7911433469580142-0.14123664385292767j) SymPy will do all sorts of complicated things with Gamma and related functions, but I've not yet found anything simple and obviously useful to me. ```python from sympy import gamma, pi, init_printing, diff from sympy.abc import x init_printing() display(gamma(x)) display(diff(gamma(x),x)) ``` ## Beta functions These are somewhat related to Gamma functions but take two arguments: $$ B(p,q) = \int_0^1 x^{p-1} (1-x)^{q-1} dx, \quad p>0, \quad q>0 $$ They can be expressed in terms of Gamma functions: $$ B(p,q) = \frac{\Gamma(p) \Gamma(q)}{\Gamma(p+q)} $$ ## References: - Boas, "Mathematical methods in the physical sciences", 3rd ed, sections 11.3-11.6 - MathWorld, http://mathworld.wolfram.com/GammaFunction.html and http://mathworld.wolfram.com/BetaFunction.html - Wikipedia, https://en.wikipedia.org/wiki/Gamma_function and https://en.wikipedia.org/wiki/Beta_function ```python ```
\documentclass{article} \usepackage[utf8]{inputenc} \title{MAT257 Notes} \author{Jad Elkhaleq Ghalayini} \date{October 22 2018} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsthm} \usepackage{mathtools} \usepackage{enumitem} \usepackage{graphicx} \usepackage{cancel} \usepackage[margin=1in]{geometry} \newtheorem{theorem}{Theorem} \newtheorem{lemma}{Lemma} \newtheorem{definition}{Definition} \newtheorem*{corollary}{Corollary} \newtheorem{exercise}{Exercise} \newcommand{\reals}[0]{\mathbb{R}} \newcommand{\nats}[0]{\mathbb{N}} \newcommand{\ints}[0]{\mathbb{Z}} \newcommand{\rationals}[0]{\mathbb{Q}} \newcommand{\brac}[1]{\left(#1\right)} \newcommand{\sbrac}[1]{\left[#1\right]} \newcommand{\mc}[1]{\mathcal{#1}} \newcommand{\eval}[3]{\left.#3\right|_{#1}^{#2}} \newcommand{\ip}[2]{\left\langle#1,#2\right\rangle} \newcommand{\prt}[2]{\frac{\partial #1}{\partial #2}} \begin{document} \maketitle \section*{Tangent Space} We begin with some examples: \begin{enumerate} \item Consider an ellipsoid \[\frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1\] The tangent plane at a point \((x_0, y_0, z_0)\) of the ellipsoid is given by \[\frac{\cancel{2}x_0}{a^2}(x - x_0) + \frac{\cancel{2}y_0}{b^2}(y - y_0) + \frac{\cancel{2}z_0}{c^2}(z - z_0) = 0\] \[\frac{x_0}{a^2}x + \frac{y_0}{b^2}y + \frac{z_0}{c^2}z = 1\] \item Let \(f(x, y) = 0\) and \(g(x, y) = 0\) be curves in \(\reals^2\). Assume the curves are smooth and intersect at point \((a, b)\). The two curves are \underline{orthogonal} at \((a, b)\) if \[\prt{f}{x}\prt{g}{x} + \prt{f}{y}\prt{g}{y} = 0\] at \((a, b)\). The two curves are \underline{tangent} at \((a, b)\) if the gradients are proportional to each other, i.e. \[\prt{f}{x}\prt{g}{y} - \prt{f}{y}\prt{g}{x} = 0\] at \((a, b)\). \item Consider the family of parabolas \[y^2 - 2p(x + p/2) = 0\] Here, \(p\) is the parameter. These parabolas open along the \(x\) axis, either to the right or two the left, with \(x\) acting like a function of \(y\). This kind of family is what's called \textit{confocal}: these parabolas all have the same focus, 0. Of course, they don't all intersect, but all those which open to the right intersect all those which open to the left. Let's look at the intersections. If \(p_1 > 0\) and \(p_2 > 0\) then the two parabolas \[f(x, y) = y^2 - 2p_1(x + p_1/2) = 0, g(x, y) = y^2 - 2p_2(x + p_2/2) = 0\] intersect where \[f(x, y) = y^2 - 2p_1(x + p_1/2) = 0 = g(x, y) = y^2 - 2p_2(x + p_2/2)\] Let's show that all the intersections among all these possible parabolas are right angles. Let's try to compute the inner product of the gradients. That is, we want to show \[f_xg_x + f_yg_y = 0\] at an intersection point. So what's the product of the \(x\) derivatives? Well it'll just be \[f_xg_x = (-2p_1)(-2p_2) = 4p_1p_2\] And what's the product of the \(y\) derivatives? \[f_yg_y = (2y)(2y) = 4y^2\] So we want to see that \[f_xg_x + f_yg_y = 4p_1p_2 + 4y^2\] vanishes when both \(f\) and \(g\) are zero. If you take \(p_2\) times \(f\), and subtract \(p_1\) times \(g\), you get rid of the \(x\) terms: \[p_2f - p_1g = p_2y^2 - 2p_2p_1(x + p_1/2) - p_1y^2 + 2p_1p_2(x + p_2/2) = (p_1 - p_2)y^2 + (p_2 - p_1)p_1p_2\] So we have \[f_xg_x + f_yg_y = 4p_1p_2 + 4y^2 = 4\frac{p_2f - p_1g}{p_2 - p_1} = 0\] Since \(f = g = 0\) and \(p_2 - p_1 \neq 0\) at the intersection point. \end{enumerate} So these are some examples of computations with tangent spaces. \section*{Proof of the Inverse Function Theorem} The hypotheses of the inverse function theorem are as follows: \(f: \reals^n \to \reals^n\) is a \(\mc{C}^1\) function in a neighborhood of a point \(a \in \reals^n\) such that \[\det f'(a) \neq 0\] We have to show that there are open neighborhoods \(V\) of \(a\) and \(W\) of \(f(a)\) such that \(f: V \to W\) and has an inverse \(f^{-1}: W \to V\) which is differentiable. Remember of course that the inverse function theorem includes a very important formula for the inverse, but this is theminimum that we have to prove, since if we prove this we can get the formula for the inverse function just from the Chain Rule. We also already checked before that if we have the formula for the inverse, we can check from the formula that the inverse if \(\mc{C}^1\), or in the general case \(\mc{C}^r\). One thing that in general it is good to do at the beginning, and it's something that in general we'll do at the beginning of a lot of things in this course, is that when you're given a problem which has a condition depending on the linear part of a function, for example, here, that the linear part is invertible, its always very simple to reduce to the case that the linear part is the identity. So let's just see here why we can make that assumption, that is, that we can assume without loss of generality that \[f'(a) = I\] So, why? Let \[\lambda = f'(a)\] If we know this, how can we use \(\lambda\) and \(f\) to find another function such that it's derivative at that point will be the identity? Quite simply, we can write, since \(\lambda\) is invertible, \[g = \lambda^{-1} \circ f \implies g'(a) = (\lambda^{-1})Df + (\cancel{D\lambda^{-1}})f = \lambda^{-1}\lambda = I\] by the Chain Rule. And if \(g\) has an inverse \(g^{-1}: W' \to V\) where \(W'\) is an open neighborhood of \(g(a)\), then \(f\) has an inverse \(f^{-1}: W \to V\) given by \[f = \lambda \circ g \implies f^{-1} = g^{-1} \circ \lambda^{-1}\] where \(W' = \lambda(W)\). So knowing the theorem for \(g\), it follows for \(f\). So first we'll show the statement above, but we'll check that the inverse is merely continuous instead of differentiable. Let's stop here, and hopefully do the entire proof next time. \end{document}
(* Title: HOL/Auth/n_german_lemma_inv__28_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_german Protocol Case Study*} theory n_german_lemma_inv__28_on_rules imports n_german_lemma_on_inv__28 begin section{*All lemmas on causal relation between inv__28*} lemma lemma_inv__28_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__28 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqEVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__28) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__28) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
% CLASS Go_Settings % ========================================================================= % % DESCRIPTION % Class to store all the Processing parameters % % EXAMPLE % state = Go_Settings(); % % FOR A LIST OF CONSTANTs and METHODS use doc Go_Settings %-------------------------------------------------------------------------- % ___ ___ ___ % __ _ ___ / __| _ | __| % / _` / _ \ (_ | _|__ \ % \__, \___/\___|_| |___/ % |___/ v 1.0RC1 % %-------------------------------------------------------------------------- % Copyright (C) 2021 Geomatics Research & Development srl (GReD) % Written by: Andrea Gatti % Contributors: Andrea Gatti, Giulio Taliaferro, ... % A list of all the historical goGPS contributors is in CREDITS.nfo %-------------------------------------------------------------------------- % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. % %-------------------------------------------------------------------------- % 01100111 01101111 01000111 01010000 01010011 %-------------------------------------------------------------------------- classdef Go_Settings < Settings_Interface properties (Constant, Access = 'protected') end % Real constant properties(Constant, Access = 'private') CUR_INI = 'goGPS_settings.ini'; LOG_DEFAULT_MODE = 1; % 0 text mode, 1 graphic mode LOG_COLOR_MODE = 1; GUI_DEFAULT_MODE = 'dark'; GUI_DEFAULT_EXPORT_MODE = 'light'; FLAG_EXPORT_TRANSPARENT = true; end properties (Constant, Access = 'public') end properties (SetAccess = protected, GetAccess = protected) % Location of the current ini file log_default_mode = Go_Settings.LOG_DEFAULT_MODE; % 0 text mode, 1 graphic mode log_color_mode = Go_Settings.LOG_COLOR_MODE; gui_default_mode = Go_Settings.GUI_DEFAULT_MODE; gui_default_export_mode = Go_Settings.GUI_DEFAULT_EXPORT_MODE; flag_export_transparent = Go_Settings.FLAG_EXPORT_TRANSPARENT; end properties (SetAccess = public, GetAccess = public) cur_ini = Go_Settings.CUR_INI; creation_time = GPS_Time(now); end % ========================================================================= %% INIT % ========================================================================= methods(Static,Access = private) % Guard the constructor against external invocation. We only want % to allow a single instance of this class. See description in % Singleton superclass. function this = Go_Settings(ini_settings_file) % Creator % % SYNTAX % s_obj = Go_Settings(<ini_settings_file>, <prj_home>); log = Core.getLogger(); log.addMarkedMessage('Preparing goGPS settings...'); log.newLine(); if nargin == 1 && not(isempty(ini_settings_file)) this.cur_ini = ini_settings_file; end if (exist(this.cur_ini, 'file') == 2) this.import(this.cur_ini); else log.addMarkedMessage('Using default settings'); log.newLine(); end end end methods (Static) function this = getInstance(ini_settings_file) % Concrete implementation. See Singleton superclass. persistent unique_instance_gocfg__ if isempty(unique_instance_gocfg__) if nargin == 1 this = Go_Settings(ini_settings_file); else this = Go_Settings(); end unique_instance_gocfg__ = this; else this = unique_instance_gocfg__; if nargin == 1 this.import(ini_settings_file) end end end end % ========================================================================= %% INTERFACE REQUIREMENTS % ========================================================================= methods (Access = 'public') function releoad(this) this.import(); end function importIniFile(this, file_name) this.import(file_name); end function import(this, file_name) % This function import processing settings from another setting object or ini file % % SYNTAX % s_obj.import(state) if nargin < 2 || isempty(file_name) file_name = this.cur_ini; end ini = Ini_Manager(file_name); try this.log_default_mode = ini.getData('LOG', 'default_mode'); catch, keyboard, end try this.log_color_mode = ini.getData('LOG', 'color_mode'); catch, keyboard, end try this.gui_default_mode = ini.getData('GUI', 'default_mode'); catch, keyboard, end try this.gui_default_export_mode = ini.getData('GUI', 'default_export_mode'); catch, keyboard, end try this.flag_export_transparent = ini.getData('EXPORT', 'flag_export_transparent'); catch, keyboard, end this.check(); % check after import end function str_cell = export(this, str_cell) % Conversion to string ini format of the minimal information needed to reconstruct the this % % SYNTAX % s_obj.export(str_cell) log.addMarkedMessage('Export of goGPS settings - to do...'); end function toString(this) ini = Ini_Manager(this.cur_ini); ini.showData; end end %% CHECKING FUNCTIONS - to be kept here to access private parameters % ========================================================================= methods (Access = 'protected') function checkLogicalField(this, field_name) % Check if a logical field of the object is a valid logical number % To make the function works it is needed to have defined the default % value of the field as a constant with same name but upper case % % SYNTAX % this.checkLogicalField(string_field_name); this.(field_name) = this.checkLogical(field_name, this.(field_name), this.(upper(field_name))); end function checkCellStringField(this, field_name, empty_is_valid, check_existence) % Check if a string field of the object is a valid string % To make the function works it is needed to have defined the default % value of the field as a constant with same name but upper case % % SYNTAX % this.Field(string_field_name, <empty_is_valid == false>, <check_existence == false>); switch nargin case 2, this.(field_name) = this.checkCellString(field_name, this.(field_name), this.(upper(field_name))); case 3, this.(field_name) = this.checkCellString(field_name, this.(field_name), this.(upper(field_name)), empty_is_valid); case 4, this.(field_name) = this.checkCellString(field_name, this.(field_name), this.(upper(field_name)), empty_is_valid, check_existence); otherwise, error('Settings checkCellStringField called with the wrong number of parameters'); end end function is_existing = checkStringField(this, field_name, empty_is_valid, check_existence) % Check if a string field of the object is a valid string % To make the function works it is needed to have defined the default % value of the field as a constant with same name but upper case % % check_existence 0: do not check % 1: check and do nothing % 2: check and try to correct % % SYNTAX % % this.checkStringField(string_field_name, <empty_is_valid == false>, <check_existence == false>); switch nargin case 2, [this.(field_name), is_existing] = this.checkString(field_name, this.(field_name), this.(upper(field_name))); case 3, [this.(field_name), is_existing] = this.checkString(field_name, this.(field_name), this.(upper(field_name)), empty_is_valid); case 4, [this.(field_name), is_existing] = this.checkString(field_name, this.(field_name), this.(upper(field_name)), empty_is_valid, check_existence); otherwise, error('Settings checkStringField called with the wrong number of parameters'); end end function is_existing = checkPathField(this, field_name, empty_is_valid, check_existence) % Check if a string path field of the object is a valid path % To make the function works it is needed to have defined the default % value of the field as a constant with same name but upper case % % SYNTAX % this.checkPathField(string_field_name, <empty_is_valid == false>, <check_existence == false>); fnp = File_Name_Processor(); tmp_path = fnp.checkPath(this.(field_name), this.getHomeDir); tmp_default_path = fnp.getFullDirPath(fnp.checkPath(this.(upper(field_name)), this.getHomeDir), this.getHomeDir); if ~isempty(tmp_path) || empty_is_valid this.(field_name) = fnp.getFullDirPath(tmp_path, this.prj_home, [], fnp.getFullDirPath(tmp_default_path)); switch nargin case 2, [this.(field_name), is_existing] = this.checkString(field_name, tmp_path, tmp_default_path); case 3, [this.(field_name), is_existing] = this.checkString(field_name, tmp_path, tmp_default_path, empty_is_valid); case 4, [this.(field_name), is_existing] = this.checkString(field_name, tmp_path, tmp_default_path, empty_is_valid, check_existence); otherwise, error('Settings checkStringField called with the wrong number of parameters'); end this.(field_name) = fnp.getFullDirPath(this.(field_name), this.getHomeDir); else this.(field_name) = tmp_default_path; end end function checkNumericField(this, field_name, limits, valid_val) % Check if a numeric field of the object is valid % To make the function works it is needed to have defined the default % value of the field as a constant with same name but upper case % % SYNTAX % this.checkNumericField(string_field_name, <limits>, <valid_values>); switch nargin case 2, this.(field_name) = this.checkNumber(field_name, this.(field_name), this.(upper(field_name))); case 3, this.(field_name) = this.checkNumber(field_name, this.(field_name), this.(upper(field_name)), limits); case 4, this.(field_name) = this.checkNumber(field_name, this.(field_name), this.(upper(field_name)), limits, valid_val); otherwise, error('Settings checkNumericField called with the wrong number of parameters'); end end end % ========================================================================= %% TEST PARAMETERS VALIDITY % ========================================================================= methods (Access = 'public') function check(this) % Check the validity of the fields % % SYNTAX % this.check(); this.checkNumericField('log_default_mode', [0 1]); this.checkLogicalField('log_color_mode'); this.checkLogicalField('flag_export_transparent'); if isdeployed this.log_color_mode = false; end end end % ========================================================================= %% GETTERS % ========================================================================= methods function out = getLogMode(this) out = this.log_default_mode; end function out = isLogColorMode(this) out = logical(this.log_color_mode); end function out = getGUIMode(this) out = this.gui_default_mode; end function out = getGUIModeExport(this) out = this.gui_default_export_mode; end function out = isExportTransparent(this) out = logical(this.flag_export_transparent); end end %% SETTERS % ========================================================================= methods function out = setLogMode(this, val) this.log_default_mode = val; end function out = setLogColorMode(this, val) this.log_color_mode = logical(val); end function out = setGUIMode(this, val) this.gui_default_mode = val; end function out = setGUIModeExport(this, val) this.gui_default_export_mode = val; end function out = setExportTransparent(this, val) this.flag_export_transparent = logical(val); end end end
from __future__ import print_function import re import numpy as np import os import sys from astropy.io import ascii import glob from time import sleep def set_gyre_inlist(inputFileName, summaryFileName, nu_max, delta_nu): # reads in the template inlist and writes out a new inlist with the # parameters set appropriately try: inlist = open('gyre_template.in','r') outlist = open('gyre.in','w') except: sleep(2.0) inlist = open('gyre_template.in','r') sleep(2.0) outlist = open('gyre.in','w') k, b = 0.9638, -1.7145 width = np.exp(k*np.log(nu_max) + b) freqMinRadial = nu_max - width*5 freqMaxRadial = nu_max + width*5 freqMinNonRadial = nu_max - 2*delta_nu freqMaxNonRadial = nu_max + 2*delta_nu # freqMin = nu_max - 10.*delta_nu # freqMax = nu_max + 10.*delta_nu if freqMinRadial <= 0.: freqMinRadial = 1. if freqMinNonRadial <= 0: freqMinNonRadial = 1. for line in inlist.read().split('\n'): first = line.split() if len(first)>0: if first[0] != '!': if re.search("file = 'spb.mesa'",line): line = "\tfile = '%s' !set by driver.py" % inputFileName if re.search("summary\_file = 'summary.txt'",line): line = "\tsummary_file = '%s' !set by driver.py" % summaryFileName if re.search("freq\_min\_radial = 100",line): line = "\tfreq_min={:0.5f} !set by driver.py".format(freqMinRadial) if re.search("freq\_max\_radial = 1800",line): line = "\tfreq_max={:0.5f} !set by driver.py".format(freqMaxRadial) if re.search("freq\_min\_non\_radial = 100",line): line = "\tfreq_min={:0.5f} !set by driver.py".format(freqMinNonRadial) if re.search("freq\_max\_non\_radial = 1800",line): line = "\tfreq_max={:0.5f} !set by driver.py".format(freqMaxNonRadial) print(line,file=outlist) outlist.close() inlist.close() class readTable: ''' A parent class to be wrapped by other class, in order to read in such as mesa history file. These files have very similar structures, typically header+table. ''' def __init__(self, filepath, verbose=True): ''' Args: filepath: the path of .history file. verbose: whether print info to device. default: True. Attributes: header: a dictionary containing history file header track: a structure numpy array containing the evol track colnames: a tuple containing column names ''' self.filepath = filepath if verbose: print('Processing :', self.filepath) return def readFile(self, filepath, headerNameLine=1, headerDataLine=2, tableHeaderLine=6): ''' Reads in a file. ''' with open(self.filepath) as f: content = [line.split() for line in f] header = {content[headerNameLine-1][i]:content[headerDataLine-1][i] for i in range(len(content[headerNameLine-1]))} table = np.genfromtxt(self.filepath, skip_header=tableHeaderLine-1, names=True) colnames = table.dtype.names return header, table, colnames class history(readTable): ''' A class to read mesa history files, store the data within, and offer useful routines (?). ''' def __init__(self, filepath, verbose=True, ifReadProfileIndex=False): ''' Args: filepath: the path of .history file. verbose: whether print info to device. default: True. Attributes: header: a dictionary containing history file header track: a structure numpy array containing the evol track colnames: a tuple containing column names profileIndex: a structured array containing the map between model_number and profile_number ''' super().__init__(filepath, verbose) self.header, self.track, self.colnames = self.readFile(filepath, headerNameLine=2, headerDataLine=3, tableHeaderLine=6) if ifReadProfileIndex: self.profileIndex = self.read_profile_index() return def read_profile_index(self): ''' Reads in the profile.index file ''' filepath = self.filepath.split('.history')[0] + 'profile.index' profileIndex = np.genfromtxt(filepath, skip_header=1, names=('model_number', 'priority', 'profile_number')) return profileIndex class profile(readTable): ''' A class to read mesa history files, store the data within, and offer useful routines. ''' def __init__(self, filepath, verbose=True): ''' Args: filepath: the path of *profile*.data file. verbose: whether print info to device. default: True. Attributes: header: a dictionary containing history file header profile: a structure numpy array containing the structure profile colnames: a tuple containing column names ''' super().__init__(filepath, verbose) self.header, self.profile, self.colnames = self.readFile(filepath, headerNameLine=2, headerDataLine=3, tableHeaderLine=6) return class sums(readTable): ''' A class to read gyre mode summary file, store the data within, and offer useful routines. ''' def __init__(self, filepath, verbose=True): ''' Args: filepath: the path of .sums file. verbose: whether print info to device. default: True. Attributes: header: a dictionary containing history file header modeSummary: a structure numpy array containing the summary table colnames: a tuple containing column names ''' super().__init__(filepath, verbose) self.header, self.modeSummary, self.colnames = self.readFile(filepath, headerNameLine=3, headerDataLine=4, tableHeaderLine=6) return def set_mesa_inlist(index, inlist_path, outlist_path, initial_mass, final_mass, Xinit, Yinit, Zinit, amlt, fov_shell, fov0_shell, fov_core, fov0_core, ifsetfinalmodel): # reads in the template inlist and writes out a new inlist with the # parameters set appropriately try: inlist = open(inlist_path,'r') outlist = open(outlist_path,'w') except: sleep(2.0) inlist = open(inlist_path,'r') sleep(2.0) outlist = open(outlist_path,'w') for line in inlist.read().split('\n'): first = line.split() if len(first)>0: if first[0] != '!': if re.search('initial\_mass',line): line = "\tinitial_mass = %g !set by driver.py" % initial_mass if initial_mass != final_mass: if re.search('mass\_change',line): line = "\tmass_change = -1d-6 !set by driver.py" if re.search('min\_star\_mass\_for\_loss',line): line = "\tmin_star_mass_for_loss = %g !set by driver.py" % final_mass if re.search('initial\_z =',line): line = "\tinitial_z = %g !set by driver.py" % Zinit if re.search('Zbase =',line): line = "\tZbase =%g !set by driver.py" % Zinit if re.search('initial\_y',line): line = "\tinitial_y = %g !set by driver.py" % Yinit if re.search('mixing\_length\_alpha',line): line = "\tmixing_length_alpha = %g !set by driver.py" % amlt if fov_shell >0: if re.search('overshoot\_scheme\(1\)',line): line = "\tovershoot_scheme(1) = '%s' !set by driver.py " % "exponential" if re.search('overshoot\_zone\_type\(1\)',line): line = "\tovershoot_zone_type(1) = '%s' !set by driver.py " % "any" if re.search('overshoot\_zone\_loc\(1\)',line): line = "\tovershoot_zone_loc(1) = '%s' !set by driver.py " % "shell" if re.search('overshoot\_bdy\_loc\(1\)',line): line = "\tovershoot_bdy_loc(1) = '%s' !set by driver.py " % "any" if re.search('overshoot\_f\(1\)',line): line = "\tovershoot_f(1) = %g !set by driver.py" %fov_shell if re.search('overshoot\_f0\(1\)',line): line = "\tovershoot_f0(1) = %g !set by driver.py" %fov0_shell else: if re.search('overshoot\_scheme\(1\)',line): line = "\t!overshoot_scheme(1) = '%s' !set by driver.py " % "" if re.search('overshoot\_zone\_type\(1\)',line): line = "\t!overshoot_zone_type(1) = '%s' !set by driver.py " % "" if re.search('overshoot\_zone\_loc\(1\)',line): line = "\t!overshoot_zone_loc(1) = '%s' !set by driver.py " % "" if re.search('overshoot\_bdy\_loc\(1\)',line): line = "\t!overshoot_bdy_loc(1) = '%s' !set by driver.py " % "" if re.search('overshoot\_f\(1\)',line): line = "\t!overshoot_f(1) = %g !set by driver.py" % 0. if re.search('overshoot\_f0\(1\)',line): line = "\t!overshoot_f0(1) = %g !set by driver.py" % 0. if fov_core >0: if re.search('overshoot\_scheme\(2\)',line): line = "\tovershoot_scheme(2) = '%s' !set by driver.py " % "exponential" if re.search('overshoot\_zone\_type\(2\)',line): line = "\tovershoot_zone_type(2) = '%s' !set by driver.py " % "any" if re.search('overshoot\_zone\_loc\(2\)',line): line = "\tovershoot_zone_loc(2) = '%s' !set by driver.py " % "core" if re.search('overshoot\_bdy\_loc\(2\)',line): line = "\tovershoot_bdy_loc(2) = '%s' !set by driver.py " % "any" if re.search('overshoot\_f\(2\)',line): line = "\tovershoot_f(2) = %g !set by driver.py" %fov_core if re.search('overshoot\_f0\(2\)',line): line = "\tovershoot_f0(2) = %g !set by driver.py" %fov0_core else: if re.search('overshoot\_scheme\(2\)',line): line = "\t!overshoot_scheme(2) = '%s' !set by driver.py " % "" if re.search('overshoot\_zone\_type\(2\)',line): line = "\t!overshoot_zone_type(2) = '%s' !set by driver.py " % "" if re.search('overshoot\_zone\_loc\(2\)',line): line = "\t!overshoot_zone_loc(2) = '%s' !set by driver.py " % "" if re.search('overshoot\_bdy\_loc\(2\)',line): line = "\t!overshoot_bdy_loc(2) = '%s' !set by driver.py " % "" if re.search('overshoot\_f\(2\)',line): line = "\t!overshoot_f(2) = %g !set by driver.py" % 0. if re.search('overshoot\_f0\(2\)',line): line = "\t!overshoot_f0(2) = %g !set by driver.py" % 0. # smass = 'm{:03.0f}'.format(mass*100) header = 'index{:06.0f}'.format(index) if re.search('star\_history\_name',line): output_history_name = header + '.history' line = "\tstar_history_name = '%s' !set by driver.py" % output_history_name if re.search('profile\_data\_prefix',line): output_profile = header + 'profile' line = "\tprofile_data_prefix = '%s' !set by driver.py " % output_profile if re.search('profiles\_index\_name =', line): output_index = header + 'profile.index' line = "\tprofiles_index_name = '%s' !set by driver.py " % output_index if ifsetfinalmodel: if re.search('save\_model\_filename =', line): output_final_model = header + 'final.mod' line = "\tsave_model_filename = '%s' !set by driver.py " % output_final_model print(line,file=outlist) outlist.close() inlist.close() # free parameters: mass, feh, alpha, y ''' masses = np.arange(0.4,1.2,0.1) #1.0,0.4 fehs = np.array([-0.4]) alphas = np.array([1.7]) ''' tracks = ascii.read('coarse_grid_input_params_v0.txt', delimiter=',')[58:] # ### remove those already existed # indexes_existed = np.array([int(f[5:11]) for f in os.listdir('../finalmodels/') if f.endswith('final.mod')]) # tracks = tracks[~np.isin(tracks['index'], indexes_existed)] # ### Ntracks = len(tracks) indexes = np.arange(0, Ntracks) ipart, Npart = int(sys.argv[1]), int(sys.argv[2]) bounds = np.round(np.arange(0,Npart+1)/(Npart)*Ntracks) idx = (indexes >= bounds[ipart-1]) & (indexes <= bounds[ipart]) for track in tracks[idx]: index, initial_mass, final_mass = track['index'], track['initial_mass'], track['final_mass'] Xinit, Yinit, Zinit, amlt = track['Xinit'], track['Yinit'], track['Zinit'], track['amlt'] fov_shell, fov0_shell, fov_core, fov0_core = track['fov_shell'], track['fov0_shell'], track['fov_core'], track['fov0_core'] output_history_name = 'index{:06.0f}'.format(index)+'.history' output_final_model_name = 'index{:06.0f}final.mod'.format(index) output_profile_index_name = 'index{:06.0f}profile.index'.format(index) print('Now calculating ',output_history_name) # if os.path.exists('LOGS/'+output_history_name): continue stages = ['ms', 'rgb', 'rgbtip', 'heb'] for istage in range(len(stages)): current_stage = stages[istage] if istage!=0: prev_stage = stages[istage-1] # check whether the final model exists if os.path.exists('../{:s}/finalmodels/{:s}'.format(current_stage, output_final_model_name)): continue # check whether start model exists & not void if istage!=0: if os.path.exists('../{:s}/finalmodels/{:s}'.format(prev_stage, output_final_model_name)) & os.path.exists('../{:s}/history/{:s}'.format(prev_stage, output_history_name)): if os.path.getsize('../{:s}/finalmodels/{:s}'.format(prev_stage, output_final_model_name))>1: os.system('cp ../{:s}/finalmodels/{:s} start.mod'.format(prev_stage, output_final_model_name)) else: continue else: continue # modify inlist from template set_mesa_inlist(index, 'inlist_{:s}'.format(current_stage), 'inlist', initial_mass, final_mass, Xinit, Yinit, Zinit, amlt, fov_shell, fov0_shell, fov_core, fov0_core, True) #os.system('\\rm -r LOGS; \\rm -r png; \\rm -r photos') # run mesa print('------ MESA start ------') os.system('./rn1') print('------ MESA done ------') # move final model if os.path.exists(output_final_model_name): os.system('mv {:s} ../{:s}/finalmodels/'.format(output_final_model_name, current_stage)) else: os.system('touch ../{:s}/finalmodels/{:s}'.format(current_stage, output_final_model_name)) # check if history and index file exists, if so, use GYRE to get frequencies if os.path.exists('LOGS/'+output_history_name) & os.path.exists('LOGS/'+output_profile_index_name): filepath = 'LOGS/' h = history(filepath+output_history_name, ifReadProfileIndex=True) track = h.track # 'delta_nu', 'nu_max' profileIndex = h.profileIndex # 'model_number', 'priority', 'profile_number' fgongPaths = [f for f in os.listdir(filepath) if (f.endswith('.FGONG') & f.startswith('index{:06.0f}'.format(index)))] for fgongPath in fgongPaths: inputFileName = filepath+fgongPath summaryFileName = filepath+fgongPath+'.sum' # if os.path.exists(summaryFileName): continue profileNo = int(fgongPath.split('profile')[-1].split('.data')[0]) modelNo = profileIndex['model_number'][profileIndex['profile_number'] == profileNo][0] delta_nu = track['delta_nu'][track['model_number'] == modelNo][0] nu_max = track['nu_max'][track['model_number'] == modelNo][0] set_gyre_inlist(inputFileName, summaryFileName, nu_max, delta_nu) # print('------ GYRE start ------') os.system('$GYRE_DIR/bin/gyre gyre.in') # print('------ GYRE done ------') # move frequencies if (not os.path.exists('../{:s}/freqs/index{:06.0f}/'.format(current_stage, index))): os.mkdir('../{:s}/freqs/index{:06.0f}/'.format(current_stage, index)) os.system('mv LOGS/*.sum ../{:s}/freqs/index{:06.0f}/'.format(current_stage, index)) # move FGONG and profile data os.system('mv LOGS/*.FGONG ../{:s}/freqs/index{:06.0f}/'.format(current_stage, index)) os.system('mv LOGS/*profile*.data ../{:s}/freqs/index{:06.0f}/'.format(current_stage, index)) # remove FGONG & profile data # os.system('rm LOGS/*.FGONG') # os.system('rm LOGS/*profile*.data') # check if history and index file exists, and move history and index if os.path.exists('LOGS/'+output_history_name): os.system('mv LOGS/{:s} ../{:s}/history/'.format(output_history_name, current_stage)) if os.path.exists('LOGS/'+output_profile_index_name): os.system('mv LOGS/{:s} ../{:s}/history/'.format(output_profile_index_name, current_stage))
-- TypeFuns.idr -- Demonstrates type functions to calculate stuff for either an int or string StringOrInt : Bool -> Type StringOrInt False = String StringOrInt True = Int ||| Returns a String or Int literal, depending on the input ||| parameter. getStringOrInt : (isInt : Bool) -> StringOrInt isInt getStringOrInt False = "Ninety four" getStringOrInt True = 94 ||| Converts the given StringOrInt to a (trimmed) String valToString : (isInt : Bool) -> StringOrInt isInt -> String valToString False y = trim y valToString True y = cast y ||| Converts the given StringOrInt to a (trimmed) String ||| Alternative implementation using a case construct ||| in the type signature valToString2 : (isInt : Bool) -> (case isInt of False => String True => Int) -> String valToString2 False y = trim y valToString2 True y = cast y
theory Re1 imports "Main" begin section {* Sequential Composition of Sets *} definition Sequ :: "string set \<Rightarrow> string set \<Rightarrow> string set" ("_ ;; _" [100,100] 100) where "A ;; B = {s1 @ s2 | s1 s2. s1 \<in> A \<and> s2 \<in> B}" text {* Two Simple Properties about Sequential Composition *} lemma seq_empty [simp]: shows "A ;; {[]} = A" and "{[]} ;; A = A" by (simp_all add: Sequ_def) lemma seq_null [simp]: shows "A ;; {} = {}" and "{} ;; A = {}" by (simp_all add: Sequ_def) section {* Regular Expressions *} datatype rexp = NULL | EMPTY | CHAR char | SEQ rexp rexp | ALT rexp rexp fun SEQS :: "rexp \<Rightarrow> rexp list \<Rightarrow> rexp" where "SEQS r [] = r" | "SEQS r (r'#rs) = SEQ r (SEQS r' rs)" section {* Semantics of Regular Expressions *} fun L :: "rexp \<Rightarrow> string set" where "L (NULL) = {}" | "L (EMPTY) = {[]}" | "L (CHAR c) = {[c]}" | "L (SEQ r1 r2) = (L r1) ;; (L r2)" | "L (ALT r1 r2) = (L r1) \<union> (L r2)" fun zeroable where "zeroable NULL = True" | "zeroable EMPTY = False" | "zeroable (CHAR c) = False" | "zeroable (ALT r1 r2) = (zeroable r1 \<and> zeroable r2)" | "zeroable (SEQ r1 r2) = (zeroable r1 \<or> zeroable r2)" lemma L_ALT_cases: "L (ALT r1 r2) \<noteq> {} \<Longrightarrow> (L r1 \<noteq> {}) \<or> (L r1 = {} \<and> L r2 \<noteq> {})" by(auto) fun nullable :: "rexp \<Rightarrow> bool" where "nullable (NULL) = False" | "nullable (EMPTY) = True" | "nullable (CHAR c) = False" | "nullable (ALT r1 r2) = (nullable r1 \<or> nullable r2)" | "nullable (SEQ r1 r2) = (nullable r1 \<and> nullable r2)" lemma nullable_correctness: shows "nullable r \<longleftrightarrow> [] \<in> (L r)" apply (induct r) apply(auto simp add: Sequ_def) done section {* Values *} datatype val = Void | Char char | Seq val val | Right val | Left val fun Seqs :: "val \<Rightarrow> val list \<Rightarrow> val" where "Seqs v [] = v" | "Seqs v (v'#vs) = Seqs (Seq v v') vs" section {* The string behind a value *} fun flat :: "val \<Rightarrow> string" where "flat(Void) = []" | "flat(Char c) = [c]" | "flat(Left v) = flat(v)" | "flat(Right v) = flat(v)" | "flat(Seq v1 v2) = flat(v1) @ flat(v2)" fun flats :: "val \<Rightarrow> string list" where "flats(Void) = [[]]" | "flats(Char c) = [[c]]" | "flats(Left v) = flats(v)" | "flats(Right v) = flats(v)" | "flats(Seq v1 v2) = (flats v1) @ (flats v2)" value "flats(Seq(Char c)(Char b))" section {* Relation between values and regular expressions *} inductive Prfs :: "string \<Rightarrow> val \<Rightarrow> rexp \<Rightarrow> bool" ("\<Turnstile>_ _ : _" [100, 100, 100] 100) where "\<lbrakk>\<Turnstile>s1 v1 : r1; \<Turnstile>s2 v2 : r2\<rbrakk> \<Longrightarrow> \<Turnstile>(s1 @ s2) (Seq v1 v2) : SEQ r1 r2" | "\<Turnstile>s v1 : r1 \<Longrightarrow> \<Turnstile>s (Left v1) : ALT r1 r2" | "\<Turnstile>s v2 : r2 \<Longrightarrow> \<Turnstile>s (Right v2) : ALT r1 r2" | "\<Turnstile>[] Void : EMPTY" | "\<Turnstile>[c] (Char c) : CHAR c" lemma Prfs_flat: "\<Turnstile>s v : r \<Longrightarrow> flat v = s" apply(induct s v r rule: Prfs.induct) apply(auto) done inductive Prfn :: "nat \<Rightarrow> val \<Rightarrow> rexp \<Rightarrow> bool" ("\<TTurnstile>_ _ : _" [100, 100, 100] 100) where "\<lbrakk>\<TTurnstile>n1 v1 : r1; \<TTurnstile>n2 v2 : r2\<rbrakk> \<Longrightarrow> \<TTurnstile>(n1 + n2) (Seq v1 v2) : SEQ r1 r2" | "\<TTurnstile>n v1 : r1 \<Longrightarrow> \<TTurnstile>n (Left v1) : ALT r1 r2" | "\<TTurnstile>n v2 : r2 \<Longrightarrow> \<TTurnstile>n (Right v2) : ALT r1 r2" | "\<TTurnstile>0 Void : EMPTY" | "\<TTurnstile>1 (Char c) : CHAR c" lemma Prfn_flat: "\<TTurnstile>n v : r \<Longrightarrow> length (flat v) = n" apply(induct rule: Prfn.induct) apply(auto) done inductive Prf :: "val \<Rightarrow> rexp \<Rightarrow> bool" ("\<turnstile> _ : _" [100, 100] 100) where "\<lbrakk>\<turnstile> v1 : r1; \<turnstile> v2 : r2\<rbrakk> \<Longrightarrow> \<turnstile> Seq v1 v2 : SEQ r1 r2" | "\<turnstile> v1 : r1 \<Longrightarrow> \<turnstile> Left v1 : ALT r1 r2" | "\<turnstile> v2 : r2 \<Longrightarrow> \<turnstile> Right v2 : ALT r1 r2" | "\<turnstile> Void : EMPTY" | "\<turnstile> Char c : CHAR c" lemma Prf_Prfn: shows "\<turnstile> v : r \<Longrightarrow> \<TTurnstile>(length (flat v)) v : r" apply(induct v r rule: Prf.induct) apply(auto intro: Prfn.intros) by (metis One_nat_def Prfn.intros(5)) lemma Prfn_Prf: shows "\<TTurnstile>n v : r \<Longrightarrow> \<turnstile> v : r" apply(induct n v r rule: Prfn.induct) apply(auto intro: Prf.intros) done lemma Prf_Prfs: shows "\<turnstile> v : r \<Longrightarrow> \<Turnstile>(flat v) v : r" apply(induct v r rule: Prf.induct) apply(auto intro: Prfs.intros) done lemma Prfs_Prf: shows "\<Turnstile>s v : r \<Longrightarrow> \<turnstile> v : r" apply(induct s v r rule: Prfs.induct) apply(auto intro: Prf.intros) done lemma not_nullable_flat: assumes "\<turnstile> v : r" "\<not>nullable r" shows "flat v \<noteq> []" using assms apply(induct) apply(auto) done fun mkeps :: "rexp \<Rightarrow> val" where "mkeps(EMPTY) = Void" | "mkeps(SEQ r1 r2) = Seq (mkeps r1) (mkeps r2)" | "mkeps(ALT r1 r2) = (if nullable(r1) then Left (mkeps r1) else Right (mkeps r2))" lemma mkeps_nullable: assumes "nullable(r)" shows "\<turnstile> mkeps r : r" using assms apply(induct rule: nullable.induct) apply(auto intro: Prf.intros) done lemma mkeps_nullable_n: assumes "nullable(r)" shows "\<TTurnstile>0 (mkeps r) : r" using assms apply(induct rule: nullable.induct) apply(auto intro: Prfn.intros) apply(drule Prfn.intros(1)) apply(assumption) apply(simp) done lemma mkeps_nullable_s: assumes "nullable(r)" shows "\<Turnstile>[] (mkeps r) : r" using assms apply(induct rule: nullable.induct) apply(auto intro: Prfs.intros) apply(drule Prfs.intros(1)) apply(assumption) apply(simp) done lemma mkeps_flat: assumes "nullable(r)" shows "flat (mkeps r) = []" using assms apply(induct rule: nullable.induct) apply(auto) done text {* The value mkeps returns is always the correct POSIX value. *} lemma Prf_flat_L: assumes "\<turnstile> v : r" shows "flat v \<in> L r" using assms apply(induct v r rule: Prf.induct) apply(auto simp add: Sequ_def) done lemma L_flat_Prf: "L(r) = {flat v | v. \<turnstile> v : r}" apply(induct r) apply(auto dest: Prf_flat_L simp add: Sequ_def) apply (metis Prf.intros(4) flat.simps(1)) apply (metis Prf.intros(5) flat.simps(2)) apply (metis Prf.intros(1) flat.simps(5)) apply (metis Prf.intros(2) flat.simps(3)) apply (metis Prf.intros(3) flat.simps(4)) apply(erule Prf.cases) apply(auto) done definition prefix :: "string \<Rightarrow> string \<Rightarrow> bool" ("_ \<sqsubseteq> _" [100, 100] 100) where "s1 \<sqsubseteq> s2 \<equiv> \<exists>s3. s1 @ s3 = s2" definition sprefix :: "string \<Rightarrow> string \<Rightarrow> bool" ("_ \<sqsubset> _" [100, 100] 100) where "s1 \<sqsubset> s2 \<equiv> (s1 \<sqsubseteq> s2 \<and> s1 \<noteq> s2)" lemma length_sprefix: "s1 \<sqsubset> s2 \<Longrightarrow> length s1 < length s2" unfolding sprefix_def prefix_def by (auto) definition Prefixes :: "string \<Rightarrow> string set" where "Prefixes s \<equiv> {sp. sp \<sqsubseteq> s}" definition Suffixes :: "string \<Rightarrow> string set" where "Suffixes s \<equiv> rev ` (Prefixes (rev s))" lemma Suffixes_in: "\<exists>s1. s1 @ s2 = s3 \<Longrightarrow> s2 \<in> Suffixes s3" unfolding Suffixes_def Prefixes_def prefix_def image_def apply(auto) by (metis rev_rev_ident) lemma Prefixes_Cons: "Prefixes (c # s) = {[]} \<union> {c # sp | sp. sp \<in> Prefixes s}" unfolding Prefixes_def prefix_def apply(auto simp add: append_eq_Cons_conv) done lemma finite_Prefixes: "finite (Prefixes s)" apply(induct s) apply(auto simp add: Prefixes_def prefix_def)[1] apply(simp add: Prefixes_Cons) done lemma finite_Suffixes: "finite (Suffixes s)" unfolding Suffixes_def apply(rule finite_imageI) apply(rule finite_Prefixes) done lemma prefix_Cons: "((c # s1) \<sqsubseteq> (c # s2)) = (s1 \<sqsubseteq> s2)" apply(auto simp add: prefix_def) done lemma prefix_append: "((s @ s1) \<sqsubseteq> (s @ s2)) = (s1 \<sqsubseteq> s2)" apply(induct s) apply(simp) apply(simp add: prefix_Cons) done definition Values :: "rexp \<Rightarrow> string \<Rightarrow> val set" where "Values r s \<equiv> {v. \<turnstile> v : r \<and> flat v \<sqsubseteq> s}" definition rest :: "val \<Rightarrow> string \<Rightarrow> string" where "rest v s \<equiv> drop (length (flat v)) s" lemma rest_Suffixes: "rest v s \<in> Suffixes s" unfolding rest_def by (metis Suffixes_in append_take_drop_id) lemma Values_recs: "Values (NULL) s = {}" "Values (EMPTY) s = {Void}" "Values (CHAR c) s = (if [c] \<sqsubseteq> s then {Char c} else {})" "Values (ALT r1 r2) s = {Left v | v. v \<in> Values r1 s} \<union> {Right v | v. v \<in> Values r2 s}" "Values (SEQ r1 r2) s = {Seq v1 v2 | v1 v2. v1 \<in> Values r1 s \<and> v2 \<in> Values r2 (rest v1 s)}" unfolding Values_def apply(auto) (*NULL*) apply(erule Prf.cases) apply(simp_all)[5] (*EMPTY*) apply(erule Prf.cases) apply(simp_all)[5] apply(rule Prf.intros) apply (metis append_Nil prefix_def) (*CHAR*) apply(erule Prf.cases) apply(simp_all)[5] apply(rule Prf.intros) apply(erule Prf.cases) apply(simp_all)[5] (*ALT*) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(2)) apply (metis Prf.intros(3)) (*SEQ*) apply(erule Prf.cases) apply(simp_all)[5] apply (simp add: append_eq_conv_conj prefix_def rest_def) apply (metis Prf.intros(1)) apply (simp add: append_eq_conv_conj prefix_def rest_def) done lemma Values_finite: "finite (Values r s)" apply(induct r arbitrary: s) apply(simp_all add: Values_recs) thm finite_surj apply(rule_tac f="\<lambda>(x, y). Seq x y" and A="{(v1, v2) | v1 v2. v1 \<in> Values r1 s \<and> v2 \<in> Values r2 (rest v1 s)}" in finite_surj) prefer 2 apply(auto)[1] apply(rule_tac B="\<Union>sp \<in> Suffixes s. {(v1, v2). v1 \<in> Values r1 s \<and> v2 \<in> Values r2 sp}" in finite_subset) apply(auto)[1] apply (metis rest_Suffixes) apply(rule finite_UN_I) apply(rule finite_Suffixes) apply(simp) done section {* Greedy Ordering according to Frisch/Cardelli *} inductive GrOrd :: "val \<Rightarrow> val \<Rightarrow> bool" ("_ \<prec> _") where "v1 \<prec> v1' \<Longrightarrow> (Seq v1 v2) \<prec> (Seq v1' v2')" | "v2 \<prec> v2' \<Longrightarrow> (Seq v1 v2) \<prec> (Seq v1 v2')" | "v1 \<prec> v2 \<Longrightarrow> (Left v1) \<prec> (Left v2)" | "v1 \<prec> v2 \<Longrightarrow> (Right v1) \<prec> (Right v2)" | "(Right v1) \<prec> (Left v2)" | "(Char c) \<prec> (Char c)" | "(Void) \<prec> (Void)" lemma Gr_refl: assumes "\<turnstile> v : r" shows "v \<prec> v" using assms apply(induct) apply(auto intro: GrOrd.intros) done lemma Gr_total: assumes "\<turnstile> v1 : r" "\<turnstile> v2 : r" shows "v1 \<prec> v2 \<or> v2 \<prec> v1" using assms apply(induct v1 r arbitrary: v2 rule: Prf.induct) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply (metis GrOrd.intros(1) GrOrd.intros(2)) apply(rotate_tac 2) apply(erule Prf.cases) apply(simp_all) apply(clarify) apply (metis GrOrd.intros(3)) apply(clarify) apply (metis GrOrd.intros(5)) apply(rotate_tac 2) apply(erule Prf.cases) apply(simp_all) apply(clarify) apply (metis GrOrd.intros(5)) apply(clarify) apply (metis GrOrd.intros(4)) apply(erule Prf.cases) apply(simp_all) apply (metis GrOrd.intros(7)) apply(erule Prf.cases) apply(simp_all) apply (metis GrOrd.intros(6)) done lemma Gr_trans: assumes "v1 \<prec> v2" "v2 \<prec> v3" "\<turnstile> v1 : r" "\<turnstile> v2 : r" "\<turnstile> v3 : r" shows "v1 \<prec> v3" using assms apply(induct r arbitrary: v1 v2 v3) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] defer (* ALT case *) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply (metis GrOrd.intros(3)) apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply (metis GrOrd.intros(5)) apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply (metis GrOrd.intros(5)) apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply (metis GrOrd.intros(4)) (* seq case *) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply(clarify) apply (metis GrOrd.intros(1)) apply (metis GrOrd.intros(1)) apply(erule GrOrd.cases) apply(simp_all (no_asm_use))[7] apply (metis GrOrd.intros(1)) by (metis GrOrd.intros(1) Gr_refl) definition GrMaxM :: "val set => val" where "GrMaxM S == SOME v. v \<in> S \<and> (\<forall>v' \<in> S. v' \<prec> v)" definition "GrMax r s \<equiv> GrMaxM {v. \<turnstile> v : r \<and> flat v = s}" inductive ValOrd3 :: "val \<Rightarrow> val \<Rightarrow> bool" ("_ 3\<succ> _" [100, 100] 100) where "v2 3\<succ> v2' \<Longrightarrow> (Seq v1 v2) 3\<succ> (Seq v1 v2')" | "v1 3\<succ> v1' \<Longrightarrow> (Seq v1 v2) 3\<succ> (Seq v1' v2')" | "length (flat v1) \<ge> length (flat v2) \<Longrightarrow> (Left v1) 3\<succ> (Right v2)" | "length (flat v2) > length (flat v1) \<Longrightarrow> (Right v2) 3\<succ> (Left v1)" | "v2 3\<succ> v2' \<Longrightarrow> (Right v2) 3\<succ> (Right v2')" | "v1 3\<succ> v1' \<Longrightarrow> (Left v1) 3\<succ> (Left v1')" | "Void 3\<succ> Void" | "(Char c) 3\<succ> (Char c)" section {* Sulzmann's Ordering of values *} inductive ValOrd :: "val \<Rightarrow> rexp \<Rightarrow> val \<Rightarrow> bool" ("_ \<succ>_ _" [100, 100, 100] 100) where "v2 \<succ>r2 v2' \<Longrightarrow> (Seq v1 v2) \<succ>(SEQ r1 r2) (Seq v1 v2')" | "\<lbrakk>v1 \<succ>r1 v1'; v1 \<noteq> v1'\<rbrakk> \<Longrightarrow> (Seq v1 v2) \<succ>(SEQ r1 r2) (Seq v1' v2')" | "length (flat v1) \<ge> length (flat v2) \<Longrightarrow> (Left v1) \<succ>(ALT r1 r2) (Right v2)" | "length (flat v2) > length (flat v1) \<Longrightarrow> (Right v2) \<succ>(ALT r1 r2) (Left v1)" | "v2 \<succ>r2 v2' \<Longrightarrow> (Right v2) \<succ>(ALT r1 r2) (Right v2')" | "v1 \<succ>r1 v1' \<Longrightarrow> (Left v1) \<succ>(ALT r1 r2) (Left v1')" | "Void \<succ>EMPTY Void" | "(Char c) \<succ>(CHAR c) (Char c)" inductive ValOrdStr :: "string \<Rightarrow> val \<Rightarrow> val \<Rightarrow> bool" ("_ \<turnstile> _ \<succ>_" [100, 100, 100] 100) where "\<lbrakk>s \<turnstile> v1 \<succ> v1'; rest v1 s \<turnstile> v2 \<succ> v2'\<rbrakk> \<Longrightarrow> s \<turnstile> (Seq v1 v2) \<succ> (Seq v1' v2')" | "\<lbrakk>flat v2 \<sqsubseteq> flat v1; flat v1 \<sqsubseteq> s\<rbrakk> \<Longrightarrow> s \<turnstile> (Left v1) \<succ> (Right v2)" | "\<lbrakk>flat v1 \<sqsubset> flat v2; flat v2 \<sqsubseteq> s\<rbrakk> \<Longrightarrow> s \<turnstile> (Right v2) \<succ> (Left v1)" | "s \<turnstile> v2 \<succ> v2' \<Longrightarrow> s \<turnstile> (Right v2) \<succ> (Right v2')" | "s \<turnstile> v1 \<succ> v1' \<Longrightarrow> s \<turnstile> (Left v1) \<succ> (Left v1')" | "s \<turnstile> Void \<succ> Void" | "(c#s) \<turnstile> (Char c) \<succ> (Char c)" inductive ValOrd2 :: "val \<Rightarrow> val \<Rightarrow> bool" ("_ 2\<succ> _" [100, 100] 100) where "v2 2\<succ> v2' \<Longrightarrow> (Seq v1 v2) 2\<succ> (Seq v1 v2')" | "\<lbrakk>v1 2\<succ> v1'; v1 \<noteq> v1'\<rbrakk> \<Longrightarrow> (Seq v1 v2) 2\<succ> (Seq v1' v2')" | "length (flat v1) \<ge> length (flat v2) \<Longrightarrow> (Left v1) 2\<succ> (Right v2)" | "length (flat v2) > length (flat v1) \<Longrightarrow> (Right v2) 2\<succ> (Left v1)" | "v2 2\<succ> v2' \<Longrightarrow> (Right v2) 2\<succ> (Right v2')" | "v1 2\<succ> v1' \<Longrightarrow> (Left v1) 2\<succ> (Left v1')" | "Void 2\<succ> Void" | "(Char c) 2\<succ> (Char c)" lemma Ord1: "v1 \<succ>r v2 \<Longrightarrow> v1 2\<succ> v2" apply(induct rule: ValOrd.induct) apply(auto intro: ValOrd2.intros) done lemma Ord2: "v1 2\<succ> v2 \<Longrightarrow> \<exists>r. v1 \<succ>r v2" apply(induct v1 v2 rule: ValOrd2.induct) apply(auto intro: ValOrd.intros) done lemma Ord3: "\<lbrakk>v1 2\<succ> v2; \<turnstile> v1 : r\<rbrakk> \<Longrightarrow> v1 \<succ>r v2" apply(induct v1 v2 arbitrary: r rule: ValOrd2.induct) apply(auto intro: ValOrd.intros elim: Prf.cases) done lemma ValOrd_refl: assumes "\<turnstile> v : r" shows "v \<succ>r v" using assms apply(induct) apply(auto intro: ValOrd.intros) done lemma "flat Void = []" "flat (Seq Void Void) = []" apply(simp_all) done lemma ValOrd_total: shows "\<lbrakk>\<turnstile> v1 : r; \<turnstile> v2 : r\<rbrakk> \<Longrightarrow> v1 \<succ>r v2 \<or> v2 \<succ>r v1" apply(induct r arbitrary: v1 v2) apply(auto) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(8)) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(case_tac "v1a = v1b") apply(simp) apply(rule ValOrd.intros(1)) apply (metis ValOrd.intros(1)) apply(rule ValOrd.intros(2)) apply(auto)[2] apply(erule contrapos_np) apply(rule ValOrd.intros(2)) apply(auto) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply (metis Ord1 Ord3 Prf.intros(2) ValOrd2.intros(6)) apply(rule ValOrd.intros) apply(erule contrapos_np) apply(rule ValOrd.intros) apply (metis le_eq_less_or_eq neq_iff) apply(erule Prf.cases) apply(simp_all)[5] apply(rule ValOrd.intros) apply(erule contrapos_np) apply(rule ValOrd.intros) apply (metis le_eq_less_or_eq neq_iff) apply(rule ValOrd.intros) apply(erule contrapos_np) apply(rule ValOrd.intros) by metis lemma ValOrd_anti: shows "\<lbrakk>\<turnstile> v1 : r; \<turnstile> v2 : r; v1 \<succ>r v2; v2 \<succ>r v1\<rbrakk> \<Longrightarrow> v1 = v2" apply(induct r arbitrary: v1 v2) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule Prf.cases) apply(simp_all)[5] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] apply(erule ValOrd.cases) apply(simp_all)[8] done lemma refl_on_ValOrd: "refl_on (Values r s) {(v1, v2). v1 \<succ>r v2 \<and> v1 \<in> Values r s \<and> v2 \<in> Values r s}" unfolding refl_on_def apply(auto) apply(rule ValOrd_refl) apply(simp add: Values_def) done (* inductive ValOrd3 :: "val \<Rightarrow> rexp \<Rightarrow> val \<Rightarrow> bool" ("_ 3\<succ>_ _" [100, 100, 100] 100) where "\<lbrakk>v2 3\<succ>r2 v2'; \<turnstile> v1 : r1\<rbrakk> \<Longrightarrow> (Seq v1 v2) 3\<succ>(SEQ r1 r2) (Seq v1 v2')" | "\<lbrakk>v1 3\<succ>r1 v1'; v1 \<noteq> v1'; flat v2 = flat v2'; \<turnstile> v2 : r2; \<turnstile> v2' : r2\<rbrakk> \<Longrightarrow> (Seq v1 v2) 3\<succ>(SEQ r1 r2) (Seq v1' v2')" | "length (flat v1) \<ge> length (flat v2) \<Longrightarrow> (Left v1) 3\<succ>(ALT r1 r2) (Right v2)" | "length (flat v2) > length (flat v1) \<Longrightarrow> (Right v2) 3\<succ>(ALT r1 r2) (Left v1)" | "v2 3\<succ>r2 v2' \<Longrightarrow> (Right v2) 3\<succ>(ALT r1 r2) (Right v2')" | "v1 3\<succ>r1 v1' \<Longrightarrow> (Left v1) 3\<succ>(ALT r1 r2) (Left v1')" | "Void 3\<succ>EMPTY Void" | "(Char c) 3\<succ>(CHAR c) (Char c)" *) section {* Posix definition *} definition POSIX :: "val \<Rightarrow> rexp \<Rightarrow> bool" where "POSIX v r \<equiv> (\<turnstile> v : r \<and> (\<forall>v'. (\<turnstile> v' : r \<and> flat v = flat v') \<longrightarrow> v \<succ>r v'))" definition POSIX2 :: "val \<Rightarrow> rexp \<Rightarrow> bool" where "POSIX2 v r \<equiv> (\<turnstile> v : r \<and> (\<forall>v'. (\<turnstile> v' : r \<and> flat v = flat v') \<longrightarrow> v 2\<succ> v'))" lemma "POSIX v r = POSIX2 v r" unfolding POSIX_def POSIX2_def apply(auto) apply(rule Ord1) apply(auto) apply(rule Ord3) apply(auto) done definition POSIXs :: "val \<Rightarrow> rexp \<Rightarrow> string \<Rightarrow> bool" where "POSIXs v r s \<equiv> (\<Turnstile>s v : r \<and> (\<forall>v'. (\<Turnstile>s v' : r \<longrightarrow> v 2\<succ> v')))" definition POSIXn :: "val \<Rightarrow> rexp \<Rightarrow> nat \<Rightarrow> bool" where "POSIXn v r n \<equiv> (\<TTurnstile>n v : r \<and> (\<forall>v'. (\<TTurnstile>n v' : r \<longrightarrow> v 2\<succ> v')))" lemma "POSIXn v r (length (flat v)) \<Longrightarrow> POSIX2 v r" unfolding POSIXn_def POSIX2_def apply(auto) apply (metis Prfn_Prf) by (metis Prf_Prfn) lemma Prfs_POSIX: "POSIXs v r s \<Longrightarrow> \<Turnstile>s v: r \<and> flat v = s" apply(simp add: POSIXs_def) by (metis Prfs_flat) lemma "POSIXs v r (flat v) = POSIX2 v r" unfolding POSIXs_def POSIX2_def apply(auto) apply (metis Prfs_Prf) apply (metis Prf_Prfs) apply (metis Prf_Prfs) by (metis Prfs_Prf Prfs_flat) section {* POSIX for some constructors *} lemma POSIX_SEQ1: assumes "POSIX (Seq v1 v2) (SEQ r1 r2)" "\<turnstile> v1 : r1" "\<turnstile> v2 : r2" shows "POSIX v1 r1" using assms unfolding POSIX_def apply(auto) apply(drule_tac x="Seq v' v2" in spec) apply(simp) apply(erule impE) apply(rule Prf.intros) apply(simp) apply(simp) apply(erule ValOrd.cases) apply(simp_all) apply(clarify) by (metis ValOrd_refl) lemma POSIXn_SEQ1: assumes "POSIXn (Seq v1 v2) (SEQ r1 r2) (n1 + n2)" "\<TTurnstile>n1 v1 : r1" "\<TTurnstile>n2 v2 : r2" shows "POSIXn v1 r1 n1" using assms unfolding POSIXn_def apply(auto) apply(drule_tac x="Seq v' v2" in spec) apply(erule impE) apply(rule Prfn.intros) apply(simp) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) apply(clarify) by (metis Ord1 Prfn_Prf ValOrd_refl) lemma POSIXs_SEQ1: assumes "POSIXs (Seq v1 v2) (SEQ r1 r2) (s1 @ s2)" "\<Turnstile>s1 v1 : r1" "\<Turnstile>s2 v2 : r2" shows "POSIXs v1 r1 s1" using assms unfolding POSIXs_def apply(auto) apply(drule_tac x="Seq v' v2" in spec) apply(erule impE) apply(rule Prfs.intros) apply(simp) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) apply(clarify) by (metis Ord1 Prfs_Prf ValOrd_refl) lemma POSIX_SEQ2: assumes "POSIX (Seq v1 v2) (SEQ r1 r2)" "\<turnstile> v1 : r1" "\<turnstile> v2 : r2" shows "POSIX v2 r2" using assms unfolding POSIX_def apply(auto) apply(drule_tac x="Seq v1 v'" in spec) apply(simp) apply(erule impE) apply(rule Prf.intros) apply(simp) apply(simp) apply(erule ValOrd.cases) apply(simp_all) done lemma POSIXn_SEQ2: assumes "POSIXn (Seq v1 v2) (SEQ r1 r2) (n1 + n2)" "\<TTurnstile>n1 v1 : r1" "\<TTurnstile>n2 v2 : r2" shows "POSIXn v2 r2 n2" using assms unfolding POSIXn_def apply(auto) apply(drule_tac x="Seq v1 v'" in spec) apply(erule impE) apply(rule Prfn.intros) apply(simp) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIXs_SEQ2: assumes "POSIXs (Seq v1 v2) (SEQ r1 r2) (s1 @ s2)" "\<Turnstile>s1 v1 : r1" "\<Turnstile>s2 v2 : r2" shows "POSIXs v2 r2 s2" using assms unfolding POSIXs_def apply(auto) apply(drule_tac x="Seq v1 v'" in spec) apply(erule impE) apply(rule Prfs.intros) apply(simp) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIX_ALT2: assumes "POSIX (Left v1) (ALT r1 r2)" shows "POSIX v1 r1" using assms unfolding POSIX_def apply(auto) apply(erule Prf.cases) apply(simp_all)[5] apply(drule_tac x="Left v'" in spec) apply(simp) apply(drule mp) apply(rule Prf.intros) apply(auto) apply(erule ValOrd.cases) apply(simp_all) done lemma POSIXn_ALT2: assumes "POSIXn (Left v1) (ALT r1 r2) n" shows "POSIXn v1 r1 n" using assms unfolding POSIXn_def apply(auto) apply(erule Prfn.cases) apply(simp_all)[5] apply(drule_tac x="Left v'" in spec) apply(drule mp) apply(rule Prfn.intros) apply(auto) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIXs_ALT2: assumes "POSIXs (Left v1) (ALT r1 r2) s" shows "POSIXs v1 r1 s" using assms unfolding POSIXs_def apply(auto) apply(erule Prfs.cases) apply(simp_all)[5] apply(drule_tac x="Left v'" in spec) apply(drule mp) apply(rule Prfs.intros) apply(auto) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIX_ALT1a: assumes "POSIX (Right v2) (ALT r1 r2)" shows "POSIX v2 r2" using assms unfolding POSIX_def apply(auto) apply(erule Prf.cases) apply(simp_all)[5] apply(drule_tac x="Right v'" in spec) apply(simp) apply(drule mp) apply(rule Prf.intros) apply(auto) apply(erule ValOrd.cases) apply(simp_all) done lemma POSIXn_ALT1a: assumes "POSIXn (Right v2) (ALT r1 r2) n" shows "POSIXn v2 r2 n" using assms unfolding POSIXn_def apply(auto) apply(erule Prfn.cases) apply(simp_all)[5] apply(drule_tac x="Right v'" in spec) apply(drule mp) apply(rule Prfn.intros) apply(auto) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIXs_ALT1a: assumes "POSIXs (Right v2) (ALT r1 r2) s" shows "POSIXs v2 r2 s" using assms unfolding POSIXs_def apply(auto) apply(erule Prfs.cases) apply(simp_all)[5] apply(drule_tac x="Right v'" in spec) apply(drule mp) apply(rule Prfs.intros) apply(auto) apply(erule ValOrd2.cases) apply(simp_all) done lemma POSIX_ALT1b: assumes "POSIX (Right v2) (ALT r1 r2)" shows "(\<forall>v'. (\<turnstile> v' : r2 \<and> flat v' = flat v2) \<longrightarrow> v2 \<succ>r2 v')" using assms apply(drule_tac POSIX_ALT1a) unfolding POSIX_def apply(auto) done lemma POSIXn_ALT1b: assumes "POSIXn (Right v2) (ALT r1 r2) n" shows "(\<forall>v'. (\<TTurnstile>n v' : r2 \<longrightarrow> v2 2\<succ> v'))" using assms apply(drule_tac POSIXn_ALT1a) unfolding POSIXn_def apply(auto) done lemma POSIXs_ALT1b: assumes "POSIXs (Right v2) (ALT r1 r2) s" shows "(\<forall>v'. (\<Turnstile>s v' : r2 \<longrightarrow> v2 2\<succ> v'))" using assms apply(drule_tac POSIXs_ALT1a) unfolding POSIXs_def apply(auto) done lemma POSIX_ALT_I1: assumes "POSIX v1 r1" shows "POSIX (Left v1) (ALT r1 r2)" using assms unfolding POSIX_def apply(auto) apply (metis Prf.intros(2)) apply(rotate_tac 2) apply(erule Prf.cases) apply(simp_all)[5] apply(auto) apply(rule ValOrd.intros) apply(auto) apply(rule ValOrd.intros) by simp lemma POSIXn_ALT_I1: assumes "POSIXn v1 r1 n" shows "POSIXn (Left v1) (ALT r1 r2) n" using assms unfolding POSIXn_def apply(auto) apply (metis Prfn.intros(2)) apply(rotate_tac 2) apply(erule Prfn.cases) apply(simp_all)[5] apply(auto) apply(rule ValOrd2.intros) apply(auto) apply(rule ValOrd2.intros) by (metis Prfn_flat order_refl) lemma POSIXs_ALT_I1: assumes "POSIXs v1 r1 s" shows "POSIXs (Left v1) (ALT r1 r2) s" using assms unfolding POSIXs_def apply(auto) apply (metis Prfs.intros(2)) apply(rotate_tac 2) apply(erule Prfs.cases) apply(simp_all)[5] apply(auto) apply(rule ValOrd2.intros) apply(auto) apply(rule ValOrd2.intros) by (metis Prfs_flat order_refl) lemma POSIX_ALT_I2: assumes "POSIX v2 r2" "\<forall>v'. \<turnstile> v' : r1 \<longrightarrow> length (flat v2) > length (flat v')" shows "POSIX (Right v2) (ALT r1 r2)" using assms unfolding POSIX_def apply(auto) apply (metis Prf.intros) apply(rotate_tac 3) apply(erule Prf.cases) apply(simp_all)[5] apply(auto) apply(rule ValOrd.intros) apply metis done lemma POSIXs_ALT_I2: assumes "POSIXs v2 r2 s" "\<forall>s' v'. \<Turnstile>s' v' : r1 \<longrightarrow> length s > length s'" shows "POSIXs (Right v2) (ALT r1 r2) s" using assms unfolding POSIXs_def apply(auto) apply (metis Prfs.intros) apply(rotate_tac 3) apply(erule Prfs.cases) apply(simp_all)[5] apply(auto) apply(rule ValOrd2.intros) apply metis done lemma "\<lbrakk>POSIX (mkeps r2) r2; nullable r2; \<not> nullable r1\<rbrakk> \<Longrightarrow> POSIX (Right (mkeps r2)) (ALT r1 r2)" apply(auto simp add: POSIX_def) apply(rule Prf.intros(3)) apply(auto) apply(rotate_tac 3) apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: mkeps_flat) apply(auto)[1] apply (metis Prf_flat_L nullable_correctness) apply(rule ValOrd.intros) apply(auto) done lemma mkeps_POSIX: assumes "nullable r" shows "POSIX (mkeps r) r" using assms apply(induct r) apply(auto)[1] apply(simp add: POSIX_def) apply(auto)[1] apply (metis Prf.intros(4)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros) apply(simp) apply(auto)[1] apply(simp add: POSIX_def) apply(auto)[1] apply (metis mkeps.simps(2) mkeps_nullable nullable.simps(5)) apply(rotate_tac 6) apply(erule Prf.cases) apply(simp_all)[5] apply (simp add: mkeps_flat) apply(case_tac "mkeps r1a = v1") apply(simp) apply (metis ValOrd.intros(1)) apply (rule ValOrd.intros(2)) apply metis apply(simp) (* ALT case *) thm mkeps.simps apply(simp) apply(erule disjE) apply(simp) apply (metis POSIX_ALT_I1) (* *) apply(auto)[1] thm POSIX_ALT_I1 apply (metis POSIX_ALT_I1) apply(simp (no_asm) add: POSIX_def) apply(auto)[1] apply(rule Prf.intros(3)) apply(simp only: POSIX_def) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] thm mkeps_flat apply(simp add: mkeps_flat) apply(auto)[1] thm Prf_flat_L nullable_correctness apply (metis Prf_flat_L nullable_correctness) apply(rule ValOrd.intros) apply(subst (asm) POSIX_def) apply(clarify) apply(drule_tac x="v2" in spec) by simp section {* Derivatives *} fun der :: "char \<Rightarrow> rexp \<Rightarrow> rexp" where "der c (NULL) = NULL" | "der c (EMPTY) = NULL" | "der c (CHAR c') = (if c = c' then EMPTY else NULL)" | "der c (ALT r1 r2) = ALT (der c r1) (der c r2)" | "der c (SEQ r1 r2) = (if nullable r1 then ALT (SEQ (der c r1) r2) (der c r2) else SEQ (der c r1) r2)" fun ders :: "string \<Rightarrow> rexp \<Rightarrow> rexp" where "ders [] r = r" | "ders (c # s) r = ders s (der c r)" fun red :: "char \<Rightarrow> rexp \<Rightarrow> rexp" where "red c (NULL) = NULL" | "red c (EMPTY) = CHAR c" | "red c (CHAR c') = SEQ (CHAR c) (CHAR c')" | "red c (ALT r1 r2) = ALT (red c r1) (red c r2)" | "red c (SEQ r1 r2) = (if nullable r1 then ALT (SEQ (red c r1) r2) (red c r2) else SEQ (red c r1) r2)" lemma L_der: shows "L (der c r) = {s. c#s \<in> L r}" apply(induct r) apply(simp_all) apply(simp add: Sequ_def) apply(auto)[1] apply (metis append_Cons) apply (metis append_Nil nullable_correctness) apply (metis append_eq_Cons_conv) apply (metis append_Cons) apply (metis Cons_eq_append_conv nullable_correctness) apply(auto) done lemma L_red: shows "L (red c r) = {c#s | s. s \<in> L r}" apply(induct r) apply(simp_all) apply(simp add: Sequ_def) apply(simp add: Sequ_def) apply(auto)[1] apply (metis append_Nil nullable_correctness) apply (metis append_Cons) apply (metis append_Cons) apply(auto) done lemma L_red_der: "L(red c (der c r)) = {c#s | s. c#s \<in> L r}" apply(simp add: L_red) apply(simp add: L_der) done lemma L_der_red: "L(der c (red c r)) = L r" apply(simp add: L_der) apply(simp add: L_red) done section {* Injection function *} fun injval :: "rexp \<Rightarrow> char \<Rightarrow> val \<Rightarrow> val" where "injval (EMPTY) c Void = Char c" | "injval (CHAR d) c Void = Char d" | "injval (CHAR d) c (Char c') = Seq (Char d) (Char c')" | "injval (ALT r1 r2) c (Left v1) = Left(injval r1 c v1)" | "injval (ALT r1 r2) c (Right v2) = Right(injval r2 c v2)" | "injval (SEQ r1 r2) c (Char c') = Seq (Char c) (Char c')" | "injval (SEQ r1 r2) c (Seq v1 v2) = Seq (injval r1 c v1) v2" | "injval (SEQ r1 r2) c (Left (Seq v1 v2)) = Seq (injval r1 c v1) v2" | "injval (SEQ r1 r2) c (Right v2) = Seq (mkeps r1) (injval r2 c v2)" section {* Projection function *} fun projval :: "rexp \<Rightarrow> char \<Rightarrow> val \<Rightarrow> val" where "projval (CHAR d) c _ = Void" | "projval (ALT r1 r2) c (Left v1) = Left (projval r1 c v1)" | "projval (ALT r1 r2) c (Right v2) = Right (projval r2 c v2)" | "projval (SEQ r1 r2) c (Seq v1 v2) = (if flat v1 = [] then Right(projval r2 c v2) else if nullable r1 then Left (Seq (projval r1 c v1) v2) else Seq (projval r1 c v1) v2)" text {* Injection value is related to r *} lemma v3: assumes "\<turnstile> v : der c r" shows "\<turnstile> (injval r c v) : r" using assms apply(induct arbitrary: v rule: der.induct) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(case_tac "c = c'") apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(5)) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(2)) apply (metis Prf.intros(3)) apply(simp) apply(case_tac "nullable r1") apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply (metis Prf.intros(1)) apply(auto)[1] apply (metis Prf.intros(1) mkeps_nullable) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(rule Prf.intros) apply(auto)[2] done lemma v3_red: assumes "\<turnstile> v : r" shows "\<turnstile> (injval (red c r) c v) : (red c r)" using assms apply(induct c r arbitrary: v rule: red.induct) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(1) Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(2)) apply (metis Prf.intros(3)) apply(erule Prf.cases) apply(simp_all)[5] apply(auto) prefer 2 apply (metis Prf.intros(1)) oops lemma v3s: assumes "\<Turnstile>s v : der c r" shows "\<Turnstile>(c#s) (injval r c v) : r" using assms apply(induct arbitrary: s v rule: der.induct) apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(case_tac "c = c'") apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply (metis Prfs.intros(5)) apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply (metis Prfs.intros(2)) apply (metis Prfs.intros(3)) apply(simp) apply(case_tac "nullable r1") apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(auto)[1] apply (metis Prfs.intros(1) append_Cons) apply(auto)[1] apply (metis Prfs.intros(1) append_Nil mkeps_nullable_s) apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(auto)[1] by (metis Prfs.intros(1) append_Cons) lemma v3n: assumes "\<TTurnstile>n v : der c r" shows "\<TTurnstile>(Suc n) (injval r c v) : r" using assms apply(induct arbitrary: n v rule: der.induct) apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply(case_tac "c = c'") apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply (metis One_nat_def Prfn.intros(5)) apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply (metis Prfn.intros(2)) apply (metis Prfn.intros(3)) apply(simp) apply(case_tac "nullable r1") apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prfn.cases) apply(simp_all)[5] apply(auto)[1] apply (metis Prfn.intros(1) add.commute add_Suc_right) apply(auto)[1] apply (metis Prfn.intros(1) mkeps_nullable_n plus_nat.add_0) apply(simp) apply(erule Prfn.cases) apply(simp_all)[5] apply(auto)[1] by (metis Prfn.intros(1) add_Suc) lemma v3_proj: assumes "\<turnstile> v : r" and "\<exists>s. (flat v) = c # s" shows "\<turnstile> (projval r c v) : der c r" using assms apply(induct rule: Prf.induct) prefer 4 apply(simp) prefer 4 apply(simp) apply (metis Prf.intros(4)) prefer 2 apply(simp) apply (metis Prf.intros(2)) prefer 2 apply(simp) apply (metis Prf.intros(3)) apply(auto) apply(rule Prf.intros) apply(simp) apply (metis Prf_flat_L nullable_correctness) apply(rule Prf.intros) apply(rule Prf.intros) apply (metis Cons_eq_append_conv) apply(simp) apply(rule Prf.intros) apply (metis Cons_eq_append_conv) apply(simp) done lemma v3s_proj: assumes "\<Turnstile>(c#s) v : r" shows "\<Turnstile>s (projval r c v) : der c r" using assms apply(induct s\<equiv>"c#s" v r arbitrary: s rule: Prfs.induct) prefer 4 apply(simp) apply (metis Prfs.intros(4)) prefer 2 apply(simp) apply (metis Prfs.intros(2)) prefer 2 apply(simp) apply (metis Prfs.intros(3)) apply(auto) apply(rule Prfs.intros) apply (metis Prfs_flat append_Nil) prefer 2 apply(rule Prfs.intros) apply(subst (asm) append_eq_Cons_conv) apply(auto)[1] apply (metis Prfs_flat) apply(rule Prfs.intros) apply metis apply(simp) apply(subst (asm) append_eq_Cons_conv) apply(auto)[1] apply (metis Prf_flat_L Prfs_Prf nullable_correctness) apply (metis Prfs_flat list.distinct(1)) apply(subst (asm) append_eq_Cons_conv) apply(auto)[1] apply (metis Prfs_flat) by (metis Prfs.intros(1)) text {* The string behind the injection value is an added c *} lemma v4s: assumes "\<Turnstile>s v : der c r" shows "flat (injval r c v) = c # (flat v)" using assms apply(induct arbitrary: s v rule: der.induct) apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(case_tac "c = c'") apply(simp) apply(auto)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] apply(simp) apply(case_tac "nullable r1") apply(simp) apply(erule Prfs.cases) apply(simp_all (no_asm_use))[5] apply(auto)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(clarify) apply(simp only: injval.simps flat.simps) apply(auto)[1] apply (metis mkeps_flat) apply(simp) apply(erule Prfs.cases) apply(simp_all)[5] done lemma v4: assumes "\<turnstile> v : der c r" shows "flat (injval r c v) = c # (flat v)" using assms apply(induct arbitrary: v rule: der.induct) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(case_tac "c = c'") apply(simp) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(case_tac "nullable r1") apply(simp) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(simp only: injval.simps flat.simps) apply(auto)[1] apply (metis mkeps_flat) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] done lemma v4_proj: assumes "\<turnstile> v : r" and "\<exists>s. (flat v) = c # s" shows "c # flat (projval r c v) = flat v" using assms apply(induct rule: Prf.induct) prefer 4 apply(simp) prefer 4 apply(simp) prefer 2 apply(simp) prefer 2 apply(simp) apply(auto) by (metis Cons_eq_append_conv) lemma v4_proj2: assumes "\<turnstile> v : r" and "(flat v) = c # s" shows "flat (projval r c v) = s" using assms by (metis list.inject v4_proj) lemma injval_inj: "inj_on (injval r c) {v. \<turnstile> v : der c r}" apply(induct c r rule: der.induct) unfolding inj_on_def apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply (metis list.distinct(1) mkeps_flat v4) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(rotate_tac 6) apply(erule Prf.cases) apply(simp_all)[5] apply (metis list.distinct(1) mkeps_flat v4) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] done lemma Values_nullable: assumes "nullable r1" shows "mkeps r1 \<in> Values r1 s" using assms apply(induct r1 arbitrary: s) apply(simp_all) apply(simp add: Values_recs) apply(simp add: Values_recs) apply(simp add: Values_recs) apply(auto)[1] done lemma Values_injval: assumes "v \<in> Values (der c r) s" shows "injval r c v \<in> Values r (c#s)" using assms apply(induct c r arbitrary: v s rule: der.induct) apply(simp add: Values_recs) apply(simp add: Values_recs) apply(case_tac "c = c'") apply(simp) apply(simp add: Values_recs) apply(simp add: prefix_def) apply(simp) apply(simp add: Values_recs) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(case_tac "nullable r1") apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(simp add: rest_def) apply(subst v4) apply(simp add: Values_def) apply(simp add: Values_def) apply(rule Values_nullable) apply(assumption) apply(simp add: rest_def) apply(subst mkeps_flat) apply(assumption) apply(simp) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(simp add: rest_def) apply(subst v4) apply(simp add: Values_def) apply(simp add: Values_def) done lemma Values_projval: assumes "v \<in> Values r (c#s)" "\<exists>s. flat v = c # s" shows "projval r c v \<in> Values (der c r) s" using assms apply(induct r arbitrary: v s c rule: rexp.induct) apply(simp add: Values_recs) apply(simp add: Values_recs) apply(case_tac "c = x") apply(simp) apply(simp add: Values_recs) apply(simp) apply(simp add: Values_recs) apply(simp add: prefix_def) apply(case_tac "nullable x1") apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(simp add: rest_def) apply (metis hd_Cons_tl hd_append2 list.sel(1)) apply(simp add: rest_def) apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(subst v4_proj2) apply(simp add: Values_def) apply(assumption) apply(simp) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(auto simp add: Values_def not_nullable_flat)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(simp add: rest_def) apply(subst v4_proj2) apply(simp add: Values_def) apply(assumption) apply(simp) apply(simp add: Values_recs) apply(auto)[1] done definition "MValue v r s \<equiv> (v \<in> Values r s \<and> (\<forall>v' \<in> Values r s. v 2\<succ> v'))" lemma assumes "MValue v1 r1 s" shows "MValue (Seq v1 v2) (SEQ r1 r2) s lemma MValue_SEQE: assumes "MValue v (SEQ r1 r2) s" shows "(\<exists>v1 v2. MValue v1 r1 s \<and> MValue v2 r2 (rest v1 s) \<and> v = Seq v1 v2)" using assms apply(simp add: MValue_def) apply(simp add: Values_recs) apply(erule conjE) apply(erule exE)+ apply(erule conjE)+ apply(simp) apply(auto) apply(drule_tac x="Seq x v2" in spec) apply(drule mp) apply(rule_tac x="x" in exI) apply(rule_tac x="v2" in exI) apply(simp) oops lemma MValue_ALTE: assumes "MValue v (ALT r1 r2) s" 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> (\<exists>vr. v = Right vr \<and> MValue vr r2 s \<and> (\<forall>vl \<in> Values r1 s. length (flat vl) < length (flat vr)))" using assms apply(simp add: MValue_def) apply(simp add: Values_recs) apply(auto) apply(drule_tac x="Left x" in bspec) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) apply(drule_tac x="Right vr" in bspec) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) apply(drule_tac x="Right x" in bspec) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) apply(drule_tac x="Left vl" in bspec) apply(simp) apply(erule ValOrd2.cases) apply(simp_all) done lemma MValue_ALTI1: assumes "MValue vl r1 s" "\<forall>vr \<in> Values r2 s. length (flat vr) \<le> length (flat vl)" shows "MValue (Left vl) (ALT r1 r2) s" using assms apply(simp add: MValue_def) apply(simp add: Values_recs) apply(auto) apply(rule ValOrd2.intros) apply metis apply(rule ValOrd2.intros) apply metis done lemma MValue_ALTI2: assumes "MValue vr r2 s" "\<forall>vl \<in> Values r1 s. length (flat vl) < length (flat vr)" shows "MValue (Right vr) (ALT r1 r2) s" using assms apply(simp add: MValue_def) apply(simp add: Values_recs) apply(auto) apply(rule ValOrd2.intros) apply metis apply(rule ValOrd2.intros) apply metis done lemma MValue_injval: assumes "MValue v (der c r) s" shows "MValue (injval r c v) r (c#s)" using assms apply(induct c r arbitrary: v s rule: der.induct) apply(simp add: MValue_def) apply(simp add: Values_recs) apply(simp add: MValue_def) apply(simp add: Values_recs) apply(case_tac "c = c'") apply(simp) apply(simp add: MValue_def) apply(simp add: Values_recs) apply(simp add: prefix_def) apply(rule ValOrd2.intros) apply(simp) apply(simp add: MValue_def) apply(simp add: Values_recs) apply(simp) apply(drule MValue_ALTE) apply(erule disjE) apply(auto)[1] apply(rule MValue_ALTI1) apply(simp) apply(subst v4) apply(simp add: MValue_def Values_def) apply(rule ballI) apply(simp) apply(case_tac "flat vr = []") apply(simp) apply(drule_tac x="projval r2 c vr" in bspec) apply(rule Values_projval) apply(simp) apply(simp add: Values_def prefix_def) apply(auto)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(simp add: Values_def prefix_def) apply(auto)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(subst (asm) v4_proj2) apply(assumption) apply(assumption) apply(simp) apply(auto)[1] apply(rule MValue_ALTI2) apply(simp) apply(subst v4) apply(simp add: MValue_def Values_def) apply(rule ballI) apply(simp) apply(case_tac "flat vl = []") apply(simp) apply(drule_tac x="projval r1 c vl" in bspec) apply(rule Values_projval) apply(simp) apply(simp add: Values_def prefix_def) apply(auto)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(simp add: Values_def prefix_def) apply(auto)[1] apply(simp add: append_eq_Cons_conv) apply(auto)[1] apply(subst (asm) v4_proj2) apply(simp add: MValue_def Values_def) apply(assumption) apply(assumption) apply(case_tac "nullable r1") defer apply(simp) apply(frule MValue_SEQE) apply(auto)[1] apply(simp add: MValue_def) apply(simp add: Values_recs) lemma nullable_red: "\<not>nullable (red c r)" apply(induct r) apply(auto) done lemma twq: assumes "\<turnstile> v : r" shows "\<turnstile> injval r c v : red c r" using assms apply(induct) apply(auto) oops lemma injval_inj_red: "inj_on (injval (red c r) c) {v. \<turnstile> v : r}" using injval_inj apply(auto simp add: inj_on_def) apply(drule_tac x="red c r" in meta_spec) apply(drule_tac x="c" in meta_spec) apply(drule_tac x="x" in spec) apply(drule mp) oops lemma assumes "POSIXs v (der c r) s" shows "POSIXs (injval r c v) r (c # s)" using assms apply(induct c r arbitrary: v s rule: der.induct) apply(auto simp add: POSIXs_def)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(erule Prfs.cases) apply(simp_all)[5] apply(auto simp add: POSIXs_def)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(erule Prfs.cases) apply(simp_all)[5] apply(case_tac "c = c'") apply(auto simp add: POSIXs_def)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply (metis Prfs.intros(5)) apply(erule Prfs.cases) apply(simp_all)[5] apply(erule Prfs.cases) apply(simp_all)[5] apply (metis ValOrd2.intros(8)) apply(auto simp add: POSIXs_def)[1] apply(erule Prfs.cases) apply(simp_all)[5] apply(erule Prfs.cases) apply(simp_all)[5] apply(frule Prfs_POSIX) apply(drule conjunct1) apply(erule Prfs.cases) apply(simp_all)[5] apply(rule POSIXs_ALT_I1) apply (metis POSIXs_ALT2) apply(rule POSIXs_ALT_I2) apply (metis POSIXs_ALT1a) apply(frule POSIXs_ALT1b) apply(auto) apply(frule POSIXs_ALT1a) (* HERE *) oops lemma t: "(c#xs = c#ys) \<Longrightarrow> xs = ys" by (metis list.sel(3)) lemma t2: "(xs = ys) \<Longrightarrow> (c#xs) = (c#ys)" by (metis) lemma "\<not>(nullable r) \<Longrightarrow> \<not>(\<exists>v. \<turnstile> v : r \<and> flat v = [])" by (metis Prf_flat_L nullable_correctness) lemma LeftRight: assumes "(Left v1) \<succ>(der c (ALT r1 r2)) (Right v2)" and "\<turnstile> v1 : der c r1" "\<turnstile> v2 : der c r2" shows "(injval (ALT r1 r2) c (Left v1)) \<succ>(ALT r1 r2) (injval (ALT r1 r2) c (Right v2))" using assms apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd.intros) apply(clarify) apply(subst v4) apply(simp) apply(subst v4) apply(simp) apply(simp) done lemma RightLeft: assumes "(Right v1) \<succ>(der c (ALT r1 r2)) (Left v2)" and "\<turnstile> v1 : der c r2" "\<turnstile> v2 : der c r1" shows "(injval (ALT r1 r2) c (Right v1)) \<succ>(ALT r1 r2) (injval (ALT r1 r2) c (Left v2))" using assms apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd.intros) apply(clarify) apply(subst v4) apply(simp) apply(subst v4) apply(simp) apply(simp) done lemma h: assumes "nullable r1" "\<turnstile> v1 : der c r1" shows "injval r1 c v1 \<succ>r1 mkeps r1" using assms apply(induct r1 arbitrary: v1 rule: der.induct) apply(simp) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(auto)[1] apply (metis ValOrd.intros(6)) apply (metis ValOrd.intros(6)) apply (metis ValOrd.intros(3) le_add2 list.size(3) mkeps_flat monoid_add_class.add.right_neutral) apply(auto)[1] apply (metis ValOrd.intros(4) length_greater_0_conv list.distinct(1) list.size(3) mkeps_flat v4) apply (metis ValOrd.intros(4) length_greater_0_conv list.distinct(1) list.size(3) mkeps_flat v4) apply (metis ValOrd.intros(5)) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply (metis ValOrd.intros(2) list.distinct(1) mkeps_flat v4) apply(clarify) by (metis ValOrd.intros(1)) lemma LeftRightSeq: assumes "(Left (Seq v1 v2)) \<succ>(der c (SEQ r1 r2)) (Right v3)" and "nullable r1" "\<turnstile> v1 : der c r1" shows "(injval (SEQ r1 r2) c (Seq v1 v2)) \<succ>(SEQ r1 r2) (injval (SEQ r1 r2) c (Right v2))" using assms apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(simp) apply(rule ValOrd.intros(2)) prefer 2 apply (metis list.distinct(1) mkeps_flat v4) by (metis h) lemma rr1: assumes "\<turnstile> v : r" "\<not>nullable r" shows "flat v \<noteq> []" using assms by (metis Prf_flat_L nullable_correctness) section {* TESTTEST *} inductive ValOrdA :: "val \<Rightarrow> rexp \<Rightarrow> val \<Rightarrow> bool" ("_ A\<succ>_ _" [100, 100, 100] 100) where "v2 A\<succ>r2 v2' \<Longrightarrow> (Seq v1 v2) A\<succ>(SEQ r1 r2) (Seq v1 v2')" | "v1 A\<succ>r1 v1' \<Longrightarrow> (Seq v1 v2) A\<succ>(SEQ r1 r2) (Seq v1' v2')" | "length (flat v1) \<ge> length (flat v2) \<Longrightarrow> (Left v1) A\<succ>(ALT r1 r2) (Right v2)" | "length (flat v2) > length (flat v1) \<Longrightarrow> (Right v2) A\<succ>(ALT r1 r2) (Left v1)" | "v2 A\<succ>r2 v2' \<Longrightarrow> (Right v2) A\<succ>(ALT r1 r2) (Right v2')" | "v1 A\<succ>r1 v1' \<Longrightarrow> (Left v1) A\<succ>(ALT r1 r2) (Left v1')" | "Void A\<succ>EMPTY Void" | "(Char c) A\<succ>(CHAR c) (Char c)" inductive ValOrd4 :: "val \<Rightarrow> rexp \<Rightarrow> val \<Rightarrow> bool" ("_ 4\<succ> _ _" [100, 100] 100) where (*"v1 4\<succ>(der c r) v1' \<Longrightarrow> (injval r c v1) 4\<succ>r (injval r c v1')" | "\<lbrakk>v1 4\<succ>r v2; v2 4\<succ>r v3\<rbrakk> \<Longrightarrow> v1 4\<succ>r v3" |*) "\<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')" | "\<lbrakk>v2 4\<succ>r2 v2'; \<turnstile> v1 : r1\<rbrakk> \<Longrightarrow> (Seq v1 v2) 4\<succ>(SEQ r1 r2) (Seq v1 v2')" | "\<lbrakk>flat v1 = flat v2; \<turnstile> v1 : r1; \<turnstile> v2 : r2\<rbrakk> \<Longrightarrow> (Left v1) 4\<succ>(ALT r1 r2) (Right v2)" | "v2 4\<succ>r2 v2' \<Longrightarrow> (Right v2) 4\<succ>(ALT r1 r2) (Right v2')" | "v1 4\<succ>r1 v1' \<Longrightarrow> (Left v1) 4\<succ>(ALT r1 r2) (Left v1')" | "Void 4\<succ>(EMPTY) Void" | "(Char c) 4\<succ>(CHAR c) (Char c)" lemma ValOrd4_Prf: assumes "v1 4\<succ>r v2" shows "\<turnstile> v1 : r \<and> \<turnstile> v2 : r" using assms apply(induct v1 r v2) apply(auto intro: Prf.intros) done lemma ValOrd4_flat: assumes "v1 4\<succ>r v2" shows "flat v1 = flat v2" using assms apply(induct v1 r v2) apply(simp_all) done lemma ValOrd4_refl: assumes "\<turnstile> v : r" shows "v 4\<succ>r v" using assms apply(induct v r) apply(auto intro: ValOrd4.intros) done lemma assumes "v1 4\<succ>r v2" "v2 4\<succ>r v3" shows "v1 A\<succ>r v3" using assms apply(induct v1 r v2 arbitrary: v3) apply(rotate_tac 5) apply(erule ValOrd4.cases) apply(simp_all) apply(clarify) apply (metis ValOrdA.intros(2)) apply(clarify) apply (metis ValOrd4_refl ValOrdA.intros(2)) apply(rotate_tac 3) apply(erule ValOrd4.cases) apply(simp_all) apply(clarify) apply (metis ValOrdA.intros(2)) apply (metis ValOrdA.intros(1)) apply (metis ValOrdA.intros(3) order_refl) apply (auto intro: ValOrdA.intros) done lemma assumes "v1 4\<succ>r v2" shows "v1 A\<succ>r v2" using assms apply(induct v1 r v2 arbitrary:) apply (metis ValOrdA.intros(2)) apply (metis ValOrdA.intros(1)) apply (metis ValOrdA.intros(3) order_refl) apply (auto intro: ValOrdA.intros) done lemma assumes "v1 \<succ>r v2" "\<turnstile> v1 : r" "\<turnstile> v2 : r" "flat v1 = flat v2" shows "v1 4\<succ>r v2" using assms apply(induct v1 r v2 arbitrary:) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply (metis ValOrd4.intros(4) ValOrd4_flat ValOrd4_refl) apply(simp) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) lemma assumes "v1 \<succ>r v2" "\<turnstile> v1 : r" "\<turnstile> v2 : r" "flat v1 = flat v2" shows "v1 4\<succ>r v2" using assms apply(induct v1 r v2 arbitrary:) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply (metis ValOrd4.intros(4) ValOrd4_flat ValOrd4_refl) apply(simp) apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(erule Prf.cases) apply(simp_all (no_asm_use))[5] apply(clarify) apply(simp) apply(erule Prf.cases) lemma rr2: "hd (flats v) \<noteq> [] \<Longrightarrow> flats v \<noteq> []" apply(induct v) apply(auto) done lemma rr3: "flats v = [] \<Longrightarrow> flat v = []" apply(induct v) apply(auto) done lemma POSIXs_der: assumes "POSIXs v (der c r) s" "\<Turnstile>s v : der c r" shows "POSIXs (injval r c v) r (c#s)" using assms unfolding POSIXs_def apply(auto) thm v3s apply (erule v3s) apply(drule_tac x="projval r c v'" in spec) apply(drule mp) thm v3s_proj apply(rule v3s_proj) apply(simp) thm v3s_proj apply(drule v3s_proj) oops term Values (* HERE *) lemma Prf_inj_test: assumes "v1 \<succ>(der c r) v2" "v1 \<in> Values (der c r) s" "v2 \<in> Values (der c r) s" "injval r c v1 \<in> Values r (c#s)" "injval r c v2 \<in> Values r (c#s)" shows "(injval r c v1) 2\<succ> (injval r c v2)" using assms apply(induct c r arbitrary: v1 v2 s rule: der.induct) (* NULL case *) apply(simp add: Values_recs) (* EMPTY case *) apply(simp add: Values_recs) (* CHAR case *) apply(case_tac "c = c'") apply(simp) apply(simp add: Values_recs) apply (metis ValOrd2.intros(8)) apply(simp add: Values_recs) (* ALT case *) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(6)) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(5)) (* SEQ case*) apply(simp) apply(case_tac "nullable r1") apply(simp) defer apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros) apply(simp) apply (metis Ord1) apply(clarify) apply(rule ValOrd2.intros) apply(subgoal_tac "rest v1 (flat v1 @ flat v2) = flat v2") apply(simp) apply(subgoal_tac "rest (injval r1 c v1) (c # flat v1 @ flat v2) = flat v2") apply(simp) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply (metis Ord1 ValOrd2.intros(1)) apply(clarify) apply(rule ValOrd2.intros(2)) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros(2)) thm h apply(rule Ord1) apply(rule h) apply(simp) apply(simp add: Values_def) apply(simp add: Values_def) apply (metis list.distinct(1) mkeps_flat v4) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(simp add: Values_def) defer apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros(1)) apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="v2'" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="s" in meta_spec) apply(simp) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(simp) apply(simp add: rest_def mkeps_flat) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(simp) apply(clarify) apply(simp add: prefix_Cons) apply(subgoal_tac "((flat v1c) @ (flat v2b)) \<sqsubseteq> (flat v2)") prefer 2 apply(simp add: prefix_def) apply(auto)[1] (* HEREHERE *) lemma Prf_inj_test: assumes "v1 \<succ>r v2" "v1 \<in> Values r s" "v2 \<in> Values r s" "injval r c v1 \<in> Values (red c r) (c#s)" "injval r c v2 \<in> Values (red c r) (c#s)" shows "(injval r c v1) \<succ>(red c r) (injval r c v2)" using assms apply(induct v1 r v2 arbitrary: s rule: ValOrd.induct) apply(simp add: Values_recs) apply (metis ValOrd.intros(1)) apply(simp add: Values_recs) apply(rule ValOrd.intros(2)) apply(metis) defer apply(simp add: Values_recs) apply(rule ValOrd.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) using injval_inj_red apply(simp add: Values_def inj_on_def) apply(rule notI) apply(drule_tac x="r1" in meta_spec) apply(drule_tac x="c" in meta_spec) apply(drule_tac x="injval r1 c v1" in spec) apply(simp) apply(drule_tac x="c" in meta_spec) apply metis apply (metis ValOrd.intros(1)) done (* EMPTY case *) apply(simp add: Values_recs) (* CHAR case *) apply(case_tac "c = c'") apply(simp) apply(simp add: Values_recs) apply (metis ValOrd2.intros(8)) apply(simp add: Values_recs) (* ALT case *) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(6)) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(5)) (* SEQ case*) apply(simp) apply(case_tac "nullable r1") apply(simp) defer apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros) apply(simp) apply (metis Ord1) apply(clarify) apply(rule ValOrd2.intros) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply (metis Ord1 ValOrd2.intros(1)) apply(clarify) apply(rule ValOrd2.intros(2)) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros(2)) thm h apply(rule Ord1) apply(rule h) apply(simp) apply(simp add: Values_def) apply(simp add: Values_def) apply (metis list.distinct(1) mkeps_flat v4) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(simp add: Values_def) defer apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros(1)) apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="v2'" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="s" in meta_spec) apply(simp) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(simp) apply(simp add: rest_def mkeps_flat) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(simp) apply(clarify) apply(simp add: prefix_Cons) apply(subgoal_tac "((flat v1c) @ (flat v2b)) \<sqsubseteq> (flat v2)") prefer 2 apply(simp add: prefix_def) apply(auto)[1] (* HEREHERE *) lemma Prf_inj_test: assumes "v1 \<succ>(der c r) v2" "v1 \<in> Values (der c r) s" "v2 \<in> Values (der c r) s" "injval r c v1 \<in> Values r (c#s)" "injval r c v2 \<in> Values r (c#s)" shows "(injval r c v1) 2\<succ> (injval r c v2)" using assms apply(induct c r arbitrary: v1 v2 s rule: der.induct) (* NULL case *) apply(simp add: Values_recs) (* EMPTY case *) apply(simp add: Values_recs) (* CHAR case *) apply(case_tac "c = c'") apply(simp) apply(simp add: Values_recs) apply (metis ValOrd2.intros(8)) apply(simp add: Values_recs) (* ALT case *) apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(6)) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros) apply(subst v4) apply(simp add: Values_def) apply(subst v4) apply(simp add: Values_def) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis ValOrd2.intros(5)) (* SEQ case*) apply(simp) apply(case_tac "nullable r1") apply(simp) defer apply(simp) apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros) apply(simp) apply (metis Ord1) apply(clarify) apply(rule ValOrd2.intros) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(simp add: Values_recs) apply(auto)[1] apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply (metis Ord1 ValOrd2.intros(1)) apply(clarify) apply(rule ValOrd2.intros(2)) apply metis using injval_inj apply(simp add: Values_def inj_on_def) apply metis apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd2.intros(2)) thm h apply(rule Ord1) apply(rule h) apply(simp) apply(simp add: Values_def) apply(simp add: Values_def) apply (metis list.distinct(1) mkeps_flat v4) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(simp add: Values_def) defer apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(rule ValOrd2.intros(1)) apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="v2'" in meta_spec) apply(rotate_tac 8) apply(drule_tac x="s" in meta_spec) apply(simp) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(drule_tac meta_mp) apply(simp add: rest_def mkeps_flat) apply(simp) apply(simp add: rest_def mkeps_flat) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(subst (asm) (5) v4) apply(simp) apply(simp) apply(clarify) apply(simp add: prefix_Cons) apply(subgoal_tac "((flat v1c) @ (flat v2b)) \<sqsubseteq> (flat v2)") prefer 2 apply(simp add: prefix_def) apply(auto)[1] (* HEREHERE *) apply(subst (asm) (7) v4) apply(simp) (* HEREHERE *) apply(simp add: Values_def) apply(simp add: Values_recs) apply(simp add: Values_recs) done lemma POSIX_der: assumes "POSIX v (der c r)" "\<turnstile> v : der c r" shows "POSIX (injval r c v) r" using assms unfolding POSIX_def apply(auto) thm v3 apply (erule v3) thm v4 apply(subst (asm) v4) apply(assumption) apply(drule_tac x="projval r c v'" in spec) apply(drule mp) apply(rule conjI) thm v3_proj apply(rule v3_proj) apply(simp) apply(rule_tac x="flat v" in exI) apply(simp) thm t apply(rule_tac c="c" in t) apply(simp) thm v4_proj apply(subst v4_proj) apply(simp) apply(rule_tac x="flat v" in exI) apply(simp) apply(simp) thm Prf_inj_test apply(drule_tac r="r" in Prf_inj_test) oops lemma POSIX_der: assumes "POSIX v (der c r)" "\<turnstile> v : der c r" shows "POSIX (injval r c v) r" using assms apply(induct c r arbitrary: v rule: der.induct) (* null case*) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] (* empty case *) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] (* char case *) apply(simp add: POSIX_def) apply(case_tac "c = c'") apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(8)) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] (* alt case *) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(simp (no_asm) add: POSIX_def) apply(auto)[1] apply (metis Prf.intros(2) v3) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] apply (metis POSIX_ALT2 POSIX_def ValOrd.intros(6)) apply (metis ValOrd.intros(3) order_refl) apply(simp (no_asm) add: POSIX_def) apply(auto)[1] apply (metis Prf.intros(3) v3) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] defer apply (metis POSIX_ALT1a POSIX_def ValOrd.intros(5)) prefer 2 apply(subst (asm) (5) POSIX_def) apply(auto)[1] apply(rotate_tac 5) apply(erule Prf.cases) apply(simp_all)[5] apply(rule ValOrd.intros) apply(subst (asm) v4) apply(simp) apply(drule_tac x="Left (projval r1a c v1)" in spec) apply(clarify) apply(drule mp) apply(rule conjI) apply (metis Prf.intros(2) v3_proj) apply(simp) apply (metis v4_proj2) apply(erule ValOrd.cases) apply(simp_all)[8] apply (metis less_not_refl v4_proj2) (* seq case *) apply(case_tac "nullable r1") defer apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis Prf.intros(1) v3) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(subst (asm) (3) v4) apply(simp) apply(simp) apply(subgoal_tac "flat v1a \<noteq> []") prefer 2 apply (metis Prf_flat_L nullable_correctness) apply(subgoal_tac "\<exists>s. flat v1a = c # s") prefer 2 apply (metis append_eq_Cons_conv) apply(auto)[1] apply(auto) thm v3 apply (erule v3) thm v4 apply(subst (asm) v4) apply(assumption) apply(drule_tac x="projval r c v'" in spec) apply(drule mp) apply(rule conjI) thm v3_proj apply(rule v3_proj) apply(simp) apply(rule_tac x="flat v" in exI) apply(simp) thm t apply(rule_tac c="c" in t) apply(simp) thm v4_proj apply(subst v4_proj) apply(simp) apply(rule_tac x="flat v" in exI) apply(simp) apply(simp) oops lemma POSIX_ex: "\<turnstile> v : r \<Longrightarrow> \<exists>v. POSIX v r" apply(induct r arbitrary: v) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(rule_tac x="Void" in exI) apply(simp add: POSIX_def) apply(auto)[1] apply (metis Prf.intros(4)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule Prf.cases) apply(simp_all)[5] apply(rule_tac x="Char c" in exI) apply(simp add: POSIX_def) apply(auto)[1] apply (metis Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(8)) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(drule_tac x="v1" in meta_spec) apply(drule_tac x="v2" in meta_spec) apply(auto)[1] defer apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply (metis POSIX_ALT_I1) apply (metis POSIX_ALT_I1 POSIX_ALT_I2) apply(case_tac "nullable r1a") apply(rule_tac x="Seq (mkeps r1a) va" in exI) apply(auto simp add: POSIX_def)[1] apply (metis Prf.intros(1) mkeps_nullable) apply(simp add: mkeps_flat) apply(rotate_tac 7) apply(erule Prf.cases) apply(simp_all)[5] apply(case_tac "mkeps r1 = v1a") apply(simp) apply (rule ValOrd.intros(1)) apply (metis append_Nil mkeps_flat) apply (rule ValOrd.intros(2)) apply(drule mkeps_POSIX) apply(simp add: POSIX_def) apply metis apply(simp) apply(simp) apply(erule disjE) apply(simp) apply(drule_tac x="v2" in spec) lemma POSIX_ex2: "\<turnstile> v : r \<Longrightarrow> \<exists>v. POSIX v r \<and> \<turnstile> v : r" apply(induct r arbitrary: v) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(rule_tac x="Void" in exI) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply (metis Prf.intros(4)) apply(erule Prf.cases) apply(simp_all)[5] apply(rule_tac x="Char c" in exI) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(8)) apply (metis Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(drule_tac x="v1" in meta_spec) apply(drule_tac x="v2" in meta_spec) apply(auto)[1] apply(simp add: POSIX_def) apply(auto)[1] apply(rule ccontr) apply(simp) apply(drule_tac x="Seq v va" in spec) apply(drule mp) defer apply (metis Prf.intros(1)) oops lemma POSIX_ALT_cases: assumes "\<turnstile> v : (ALT r1 r2)" "POSIX v (ALT r1 r2)" shows "(\<exists>v1. v = Left v1 \<and> POSIX v1 r1) \<or> (\<exists>v2. v = Right v2 \<and> POSIX v2 r2)" using assms apply(erule_tac Prf.cases) apply(simp_all) unfolding POSIX_def apply(auto) apply (metis POSIX_ALT2 POSIX_def assms(2)) by (metis POSIX_ALT1b assms(2)) lemma POSIX_ALT_cases2: assumes "POSIX v (ALT r1 r2)" "\<turnstile> v : (ALT r1 r2)" shows "(\<exists>v1. v = Left v1 \<and> POSIX v1 r1) \<or> (\<exists>v2. v = Right v2 \<and> POSIX v2 r2)" using assms POSIX_ALT_cases by auto lemma Prf_flat_empty: assumes "\<turnstile> v : r" "flat v = []" shows "nullable r" using assms apply(induct) apply(auto) done lemma POSIX_proj: assumes "POSIX v r" "\<turnstile> v : r" "\<exists>s. flat v = c#s" shows "POSIX (projval r c v) (der c r)" using assms apply(induct r c v arbitrary: rule: projval.induct) defer defer defer defer apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule_tac [!] exE) prefer 3 apply(frule POSIX_SEQ1) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(case_tac "flat v1 = []") apply(subgoal_tac "nullable r1") apply(simp) prefer 2 apply(rule_tac v="v1" in Prf_flat_empty) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(frule POSIX_SEQ2) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(drule meta_mp) apply(erule Prf.cases) apply(simp_all)[5] apply(rule ccontr) apply(subgoal_tac "\<turnstile> val.Right (projval r2 c v2) : (ALT (SEQ (der c r1) r2) (der c r2))") apply(rotate_tac 11) apply(frule POSIX_ex) apply(erule exE) apply(drule POSIX_ALT_cases2) apply(erule Prf.cases) apply(simp_all)[5] apply(drule v3_proj) apply(simp) apply(simp) apply(drule POSIX_ex) apply(erule exE) apply(frule POSIX_ALT_cases2) apply(simp) apply(simp) apply(erule prefer 2 apply(case_tac "nullable r1") prefer 2 apply(simp) apply(rotate_tac 1) apply(drule meta_mp) apply(rule POSIX_SEQ1) apply(assumption) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(rotate_tac 7) apply(drule meta_mp) apply(erule Prf.cases) apply(simp_all)[5] apply(rotate_tac 7) apply(drule meta_mp) apply (metis Cons_eq_append_conv) apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(simp) apply(simp) apply(simp_all)[5] apply(simp add: POSIX_def) lemma POSIX_proj: assumes "POSIX v r" "\<turnstile> v : r" "\<exists>s. flat v = c#s" shows "POSIX (projval r c v) (der c r)" using assms apply(induct r arbitrary: c v rule: rexp.induct) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule_tac [!] exE) prefer 3 apply(frule POSIX_SEQ1) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(case_tac "flat v1 = []") apply(subgoal_tac "nullable r1") apply(simp) prefer 2 apply(rule_tac v="v1" in Prf_flat_empty) apply(erule Prf.cases) apply(simp_all)[5] lemma POSIX_proj: assumes "POSIX v r" "\<turnstile> v : r" "\<exists>s. flat v = c#s" shows "POSIX (projval r c v) (der c r)" using assms apply(induct r c v arbitrary: rule: projval.induct) defer defer defer defer apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(erule_tac [!] exE) prefer 3 apply(frule POSIX_SEQ1) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(case_tac "flat v1 = []") apply(subgoal_tac "nullable r1") apply(simp) prefer 2 apply(rule_tac v="v1" in Prf_flat_empty) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(rule ccontr) apply(drule v3_proj) apply(simp) apply(simp) apply(drule POSIX_ex) apply(erule exE) apply(frule POSIX_ALT_cases2) apply(simp) apply(simp) apply(erule prefer 2 apply(case_tac "nullable r1") prefer 2 apply(simp) apply(rotate_tac 1) apply(drule meta_mp) apply(rule POSIX_SEQ1) apply(assumption) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(rotate_tac 7) apply(drule meta_mp) apply(erule Prf.cases) apply(simp_all)[5] apply(rotate_tac 7) apply(drule meta_mp) apply (metis Cons_eq_append_conv) apply(erule Prf.cases) apply(simp_all)[5] apply(simp add: POSIX_def) apply(simp) apply(simp) apply(simp_all)[5] apply(simp add: POSIX_def) done (* NULL case *) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(7)) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) prefer 2 apply(simp) apply(frule POSIX_ALT1a) apply(drule meta_mp) apply(simp) apply(drule meta_mp) apply(erule Prf.cases) apply(simp_all)[5] apply(rule POSIX_ALT_I2) apply(assumption) apply(auto)[1] thm v4_proj2 prefer 2 apply(subst (asm) (13) POSIX_def) apply(drule_tac x="projval v2" in spec) apply(auto)[1] apply(drule mp) apply(rule conjI) apply(simp) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] prefer 2 apply(clarify) apply(subst (asm) (2) POSIX_def) apply (metis ValOrd.intros(5)) apply(clarify) apply(simp) apply(rotate_tac 3) apply(drule_tac c="c" in t2) apply(subst (asm) v4_proj) apply(simp) apply(simp) thm contrapos_np contrapos_nn apply(erule contrapos_np) apply(rule ValOrd.intros) apply(subst v4_proj2) apply(simp) apply(simp) apply(subgoal_tac "\<not>(length (flat v1) < length (flat (projval r2a c v2a)))") prefer 2 apply(erule contrapos_nn) apply (metis nat_less_le v4_proj2) apply(simp) apply(blast) thm contrapos_nn apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(rule ValOrd.intros) apply(drule meta_mp) apply(auto)[1] apply (metis POSIX_ALT2 POSIX_def flat.simps(3)) apply metis apply(clarify) apply(rule ValOrd.intros) apply(simp) apply(simp add: POSIX_def) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(rule ValOrd.intros) apply(simp) apply(drule meta_mp) apply(auto)[1] apply (metis POSIX_ALT2 POSIX_def flat.simps(3)) apply metis apply(clarify) apply(rule ValOrd.intros) apply(simp) done (* EMPTY case *) apply(simp add: POSIX_def) apply(auto)[1] apply(rotate_tac 3) apply(erule Prf.cases) apply(simp_all)[5] apply(drule_tac c="c" in t2) apply(subst (asm) v4_proj) apply(auto)[2] apply(erule ValOrd.cases) apply(simp_all)[8] (* CHAR case *) apply(case_tac "c = c'") apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd.intros) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] (* ALT case *) unfolding POSIX_def apply(auto) thm v4 lemma Prf_inj: assumes "v1 \<succ>(der c r) v2" "\<turnstile> v1 : der c r" "\<turnstile> v2 : der c r" "flat v1 = flat v2" shows "(injval r c v1) \<succ>r (injval r c v2)" using assms apply(induct arbitrary: v1 v2 rule: der.induct) (* NULL case *) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] (* EMPTY case *) apply(erule ValOrd.cases) apply(simp_all)[8] (* CHAR case *) apply(case_tac "c = c'") apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd.intros) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] (* ALT case *) apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(rule ValOrd.intros) apply(subst v4) apply(clarify) apply(rotate_tac 3) apply(erule Prf.cases) apply(simp_all)[5] apply(subst v4) apply(clarify) apply(rotate_tac 2) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(rule ValOrd.intros) apply(clarify) apply(rotate_tac 3) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(rule ValOrd.intros) apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] (* SEQ case*) apply(simp) apply(case_tac "nullable r1") defer apply(simp) apply(erule ValOrd.cases) apply(simp_all)[8] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(rule ValOrd.intros) apply(simp) apply(simp) apply(rule ValOrd.intros(2)) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) defer apply(simp) apply(erule ValOrd.cases) apply(simp_all del: injval.simps)[8] apply(simp) apply(clarify) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(rule ValOrd.intros(2)) done txt {* done (* nullable case - unfinished *) apply(simp) apply(erule ValOrd.cases) apply(simp_all del: injval.simps)[8] apply(simp) apply(clarify) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(simp) apply(rule ValOrd.intros(2)) oops *} oops text {* Injection followed by projection is the identity. *} lemma proj_inj_id: assumes "\<turnstile> v : der c r" shows "projval r c (injval r c v) = v" using assms apply(induct r arbitrary: c v rule: rexp.induct) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(case_tac "c = char") apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(erule Prf.cases) apply(simp_all)[5] defer apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(simp) apply(case_tac "nullable rexp1") apply(simp) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply (metis list.distinct(1) v4) apply(auto)[1] apply (metis mkeps_flat) apply(auto) apply(erule Prf.cases) apply(simp_all)[5] apply(auto)[1] apply(simp add: v4) done lemma "L r \<noteq> {} \<Longrightarrow> \<exists>v. POSIX3 v r" apply(induct r) apply(simp) apply(simp add: POSIX3_def) apply(rule_tac x="Void" in exI) apply(auto)[1] apply (metis Prf.intros(4)) apply (metis POSIX3_def flat.simps(1) mkeps.simps(1) mkeps_POSIX3 nullable.simps(2) order_refl) apply(simp add: POSIX3_def) apply(rule_tac x="Char char" in exI) apply(auto)[1] apply (metis Prf.intros(5)) apply(erule Prf.cases) apply(simp_all)[5] apply (metis ValOrd.intros(8)) apply(simp add: Sequ_def) apply(auto)[1] apply(drule meta_mp) apply(auto)[2] apply(drule meta_mp) apply(auto)[2] apply(rule_tac x="Seq v va" in exI) apply(simp (no_asm) add: POSIX3_def) apply(auto)[1] apply (metis POSIX3_def Prf.intros(1)) apply(erule Prf.cases) apply(simp_all)[5] apply(clarify) apply(case_tac "v \<succ>r1a v1") apply(rule ValOrd.intros(2)) apply(simp) apply(case_tac "v = v1") apply(rule ValOrd.intros(1)) apply(simp) apply(simp) apply (metis ValOrd_refl) apply(simp add: POSIX3_def) oops lemma "\<exists>v. POSIX v r" apply(induct r) apply(rule exI) apply(simp add: POSIX_def) apply (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) apply(rule_tac x = "Void" in exI) apply(simp add: POSIX_def) apply (metis POSIX_def flat.simps(1) mkeps.simps(1) mkeps_POSIX nullable.simps(2)) apply(rule_tac x = "Char char" in exI) apply(simp add: POSIX_def) apply(auto) [1] apply(erule Prf.cases) apply(simp_all) [5] apply (metis ValOrd.intros(8)) defer apply(auto) apply (metis POSIX_ALT_I1) (* maybe it is too early to instantiate this existential quantifier *) (* potentially this is the wrong POSIX value *) apply(case_tac "r1 = NULL") apply(simp add: POSIX_def) apply(auto)[1] apply (metis L.simps(1) L.simps(4) Prf_flat_L mkeps_flat nullable.simps(1) nullable.simps(2) nullable_correctness seq_null(2)) apply(case_tac "r1 = EMPTY") apply(rule_tac x = "Seq Void va" in exI ) apply(simp (no_asm) add: POSIX_def) apply(auto) apply(erule Prf.cases) apply(simp_all) apply(auto)[1] apply(erule Prf.cases) apply(simp_all) apply(rule ValOrd.intros(2)) apply(rule ValOrd.intros) apply(case_tac "\<exists>c. r1 = CHAR c") apply(auto) apply(rule_tac x = "Seq (Char c) va" in exI ) apply(simp (no_asm) add: POSIX_def) apply(auto) apply(erule Prf.cases) apply(simp_all) apply(auto)[1] apply(erule Prf.cases) apply(simp_all) apply(auto)[1] apply(rule ValOrd.intros(2)) apply(rule ValOrd.intros) apply(case_tac "\<exists>r1a r1b. r1 = ALT r1a r1b") apply(auto) oops (* not sure if this can be proved by induction *) text {* HERE: Crucial lemma that does not go through in the sequence case. *} lemma v5: assumes "\<turnstile> v : der c r" "POSIX v (der c r)" shows "POSIX (injval r c v) r" using assms apply(induct arbitrary: v rule: der.induct) (* NULL case *) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] (* EMPTY case *) apply(simp) apply(erule Prf.cases) apply(simp_all)[5] (* CHAR case *) apply(simp) apply(case_tac "c = c'") apply(auto simp add: POSIX_def)[1] apply(erule Prf.cases) apply(simp_all)[5] apply(erule Prf.cases) apply(simp_all)[5] apply(rule ValOrd.intros) apply(auto)[1] apply(erule Prf.cases) apply(simp_all)[5] (* base cases done *) (* ALT case *) apply(erule Prf.cases) apply(simp_all)[5] using POSIX_ALT POSIX_ALT_I1 apply blast apply(clarify) apply(simp) apply(rule POSIX_ALT_I2) apply(drule POSIX_ALT1a) apply metis apply(auto)[1] apply(subst v4) apply(assumption) apply(simp) apply(drule POSIX_ALT1a) apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(simp) apply(rotate_tac 4) apply(erule Prf.cases) apply(simp_all)[5] apply(rule ValOrd.intros) apply(simp) apply(subst (asm) v4) apply(assumption) apply(clarify) thm POSIX_ALT1a POSIX_ALT1b POSIX_ALT_I2 apply(subst (asm) v4) apply(auto simp add: POSIX_def)[1] apply(subgoal_tac "POSIX v2 (der c r2)") prefer 2 apply(auto simp add: POSIX_def)[1] apply (metis POSIX_ALT1a POSIX_def flat.simps(4)) apply(frule POSIX_ALT1a) apply(drule POSIX_ALT1b) apply(rule POSIX_ALT_I2) apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(simp) apply(subgoal_tac "\<turnstile> Right (injval r2 c v2) : (ALT r1 r2)") prefer 2 apply (metis Prf.intros(3) v3) apply auto[1] apply(subst v4) apply(auto)[2] apply(subst (asm) (4) POSIX_def) apply(subst (asm) v4) apply(drule_tac x="v2" in meta_spec) apply(simp) apply(auto)[2] thm POSIX_ALT_I2 apply(rule POSIX_ALT_I2) apply(rule ccontr) apply(auto simp add: POSIX_def)[1] apply(rule allI) apply(rule impI) apply(erule conjE) thm POSIX_ALT_I2 apply(frule POSIX_ALT1a) apply(drule POSIX_ALT1b) apply(rule POSIX_ALT_I2) apply auto[1] apply(subst v4) apply(auto)[2] apply(rotate_tac 1) apply(drule_tac x="v2" in meta_spec) apply(simp) apply(subst (asm) (4) POSIX_def) apply(subst (asm) v4) apply(auto)[2] (* stuck in the ALT case *)
[STATEMENT] lemma r_min_code[code_unfold]: "r_min = (MIN s. MIN a. r(s,a))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. r_min = (MIN s a. r (s, a)) [PROOF STEP] by (auto simp: cInf_eq_Min)
[GOAL] ι : Type u_1 β : ι → Type u_2 r✝ : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : (i : ι) → PartialOrder (β i) r : ι → ι → Prop hwf : WellFounded r x y : (i : ι) → β i hlt : x < y ⊢ Pi.Lex r (fun i x x_1 => x < x_1) x y [PROOFSTEP] simp_rw [Pi.Lex, le_antisymm_iff] [GOAL] ι : Type u_1 β : ι → Type u_2 r✝ : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : (i : ι) → PartialOrder (β i) r : ι → ι → Prop hwf : WellFounded r x y : (i : ι) → β i hlt : x < y ⊢ ∃ i, (∀ (j : ι), r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i [PROOFSTEP] exact lex_lt_of_lt_of_preorder hwf hlt [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] cases' eq_or_ne a b with hab hab [GOAL] case inl ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : a = b ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] exact Or.inr (Or.inl hab) [GOAL] case inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : a ≠ b ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] rw [Function.ne_iff] at hab [GOAL] case inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] let i := wf.min _ hab [GOAL] case inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] have hri : ∀ j, r j i → a j = b j := by intro j rw [← not_imp_not] exact fun h' => wf.not_lt_min _ _ h' [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab ⊢ ∀ (j : ι), r j i → a j = b j [PROOFSTEP] intro j [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab j : ι ⊢ r j i → a j = b j [PROOFSTEP] rw [← not_imp_not] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab j : ι ⊢ ¬a j = b j → ¬r j i [PROOFSTEP] exact fun h' => wf.not_lt_min _ _ h' [GOAL] case inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab hri : ∀ (j : ι), r j i → a j = b j ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] have hne : a i ≠ b i := wf.min_mem _ hab [GOAL] case inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab hri : ∀ (j : ι), r j i → a j = b j hne : a i ≠ b i ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] cases' trichotomous_of s (a i) (b i) with hi hi [GOAL] case inr.inl ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab hri : ∀ (j : ι), r j i → a j = b j hne : a i ≠ b i hi : s (a i) (b i) ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a case inr.inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝ : ∀ (i : ι), IsTrichotomous (β i) s wf : WellFounded r a b : (i : ι) → β i hab : ∃ a_1, a a_1 ≠ b a_1 i : ι := WellFounded.min wf (fun x => a x = b x → False) hab hri : ∀ (j : ι), r j i → a j = b j hne : a i ≠ b i hi : a i = b i ∨ s (b i) (a i) ⊢ Pi.Lex r s a b ∨ a = b ∨ Pi.Lex r s b a [PROOFSTEP] exacts [Or.inl ⟨i, hri, hi⟩, Or.inr <| Or.inr <| ⟨i, fun j hj => (hri j hj).symm, hi.resolve_left hne⟩] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝¹ : LinearOrder ι inst✝ : (a : ι) → PartialOrder (β a) ⊢ ∀ (a b c : Lex ((i : ι) → β i)), a < b → b < c → a < c [PROOFSTEP] rintro a b c ⟨N₁, lt_N₁, a_lt_b⟩ ⟨N₂, lt_N₂, b_lt_c⟩ [GOAL] case intro.intro.intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝¹ : LinearOrder ι inst✝ : (a : ι) → PartialOrder (β a) a b c : Lex ((i : ι) → β i) N₁ : ι lt_N₁ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₁ → a j = b j a_lt_b : a N₁ < b N₁ N₂ : ι lt_N₂ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₂ → b j = c j b_lt_c : b N₂ < c N₂ ⊢ a < c [PROOFSTEP] rcases lt_trichotomy N₁ N₂ with (H | rfl | H) [GOAL] case intro.intro.intro.intro.inl ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝¹ : LinearOrder ι inst✝ : (a : ι) → PartialOrder (β a) a b c : Lex ((i : ι) → β i) N₁ : ι lt_N₁ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₁ → a j = b j a_lt_b : a N₁ < b N₁ N₂ : ι lt_N₂ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₂ → b j = c j b_lt_c : b N₂ < c N₂ H : N₁ < N₂ ⊢ a < c case intro.intro.intro.intro.inr.inl ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝¹ : LinearOrder ι inst✝ : (a : ι) → PartialOrder (β a) a b c : Lex ((i : ι) → β i) N₁ : ι lt_N₁ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₁ → a j = b j a_lt_b : a N₁ < b N₁ lt_N₂ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₁ → b j = c j b_lt_c : b N₁ < c N₁ ⊢ a < c case intro.intro.intro.intro.inr.inr ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝¹ : LinearOrder ι inst✝ : (a : ι) → PartialOrder (β a) a b c : Lex ((i : ι) → β i) N₁ : ι lt_N₁ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₁ → a j = b j a_lt_b : a N₁ < b N₁ N₂ : ι lt_N₂ : ∀ (j : ι), (fun x x_1 => x < x_1) j N₂ → b j = c j b_lt_c : b N₂ < c N₂ H : N₂ < N₁ ⊢ a < c [PROOFSTEP] exacts [⟨N₁, fun j hj => (lt_N₁ _ hj).trans (lt_N₂ _ <| hj.trans H), lt_N₂ _ H ▸ a_lt_b⟩, ⟨N₁, fun j hj => (lt_N₁ _ hj).trans (lt_N₂ _ hj), a_lt_b.trans b_lt_c⟩, ⟨N₂, fun j hj => (lt_N₁ _ (hj.trans H)).trans (lt_N₂ _ hj), (lt_N₁ _ H).symm ▸ b_lt_c⟩] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i✝ : ι a✝ : β i✝ a b : (i : ι) → β i h : a ≤ b hne : ¬↑toLex a = ↑toLex b i : ι hi : i ∈ {i | a i ≠ b i} hl : ∀ (x : ι), x ∈ {i | a i ≠ b i} → ¬x < i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ ↑toLex a j = ↑toLex b j [PROOFSTEP] contrapose! hl [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i✝ : ι a✝ : β i✝ a b : (i : ι) → β i h : a ≤ b hne : ¬↑toLex a = ↑toLex b i : ι hi : i ∈ {i | a i ≠ b i} j : ι hj : (fun x x_1 => x < x_1) j i hl : ↑toLex a j ≠ ↑toLex b j ⊢ ∃ x, x ∈ {i | a i ≠ b i} ∧ x < i [PROOFSTEP] exact ⟨j, hl, hj⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i✝ : ι a✝ : β i✝ a b : (i : ι) → β i h : a < b i : ι hi : i ∈ {i | a i ≠ b i} hl : ∀ (x : ι), x ∈ {i | a i ≠ b i} → ¬x < i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ ↑toLex a j = ↑toLex b j [PROOFSTEP] contrapose! hl [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i✝ : ι a✝ : β i✝ a b : (i : ι) → β i h : a < b i : ι hi : i ∈ {i | a i ≠ b i} j : ι hj : (fun x x_1 => x < x_1) j i hl : ↑toLex a j ≠ ↑toLex b j ⊢ ∃ x, x ∈ {i | a i ≠ b i} ∧ x < i [PROOFSTEP] exact ⟨j, hl, hj⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex x < ↑toLex (update x i a) ↔ x i < a [PROOFSTEP] refine' ⟨_, fun h => toLex_strictMono <| lt_update_self_iff.2 h⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex x < ↑toLex (update x i a) → x i < a [PROOFSTEP] rintro ⟨j, hj, h⟩ [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x i a) j_1 h : ↑toLex x j < ↑toLex (update x i a) j ⊢ x i < a [PROOFSTEP] dsimp at h [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x i a) j_1 h : x j < update x i a j ⊢ x i < a [PROOFSTEP] obtain rfl : j = i := by by_contra H rw [update_noteq H] at h exact h.false [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x i a) j_1 h : x j < update x i a j ⊢ j = i [PROOFSTEP] by_contra H [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x i a) j_1 h : x j < update x i a j H : ¬j = i ⊢ False [PROOFSTEP] rw [update_noteq H] at h [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x i a) j_1 h : x j < x j H : ¬j = i ⊢ False [PROOFSTEP] exact h.false [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i j : ι a : β j hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex x j_1 = ↑toLex (update x j a) j_1 h : x j < update x j a j ⊢ x j < a [PROOFSTEP] rwa [update_same] at h [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex (update x i a) < ↑toLex x ↔ a < x i [PROOFSTEP] refine' ⟨_, fun h => toLex_strictMono <| update_lt_self_iff.2 h⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex (update x i a) < ↑toLex x → a < x i [PROOFSTEP] rintro ⟨j, hj, h⟩ [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x i a) j_1 = ↑toLex x j_1 h : ↑toLex (update x i a) j < ↑toLex x j ⊢ a < x i [PROOFSTEP] dsimp at h [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x i a) j_1 = ↑toLex x j_1 h : update x i a j < x j ⊢ a < x i [PROOFSTEP] obtain rfl : j = i := by by_contra H rw [update_noteq H] at h exact h.false [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x i a) j_1 = ↑toLex x j_1 h : update x i a j < x j ⊢ j = i [PROOFSTEP] by_contra H [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x i a) j_1 = ↑toLex x j_1 h : update x i a j < x j H : ¬j = i ⊢ False [PROOFSTEP] rw [update_noteq H] at h [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i j : ι hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x i a) j_1 = ↑toLex x j_1 h : x j < x j H : ¬j = i ⊢ False [PROOFSTEP] exact h.false [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i j : ι a : β j hj : ∀ (j_1 : ι), (fun x x_1 => x < x_1) j_1 j → ↑toLex (update x j a) j_1 = ↑toLex x j_1 h : update x j a j < x j ⊢ a < x j [PROOFSTEP] rwa [update_same] at h [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex x ≤ ↑toLex (update x i a) ↔ x i ≤ a [PROOFSTEP] simp_rw [le_iff_lt_or_eq, lt_toLex_update_self_iff, toLex_inj, eq_update_self_iff] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : LinearOrder ι inst✝¹ : IsWellOrder ι fun x x_1 => x < x_1 inst✝ : (i : ι) → PartialOrder (β i) x y : (i : ι) → β i i : ι a : β i ⊢ ↑toLex (update x i a) ≤ ↑toLex x ↔ a ≤ x i [PROOFSTEP] simp_rw [le_iff_lt_or_eq, toLex_update_lt_self_iff, toLex_inj, update_eq_self_iff] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) ⊢ ∀ (a₁ a₂ : Lex ((i : ι) → β i)), a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ [PROOFSTEP] rintro _ a₂ ⟨i, h, hi⟩ [GOAL] case intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i ⊢ ∃ a, a₁✝ < a ∧ a < a₂ [PROOFSTEP] obtain ⟨a, ha₁, ha₂⟩ := exists_between hi [GOAL] case intro.intro.intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ ∃ a, a₁✝ < a ∧ a < a₂ [PROOFSTEP] classical refine' ⟨Function.update a₂ _ a, ⟨i, fun j hj => _, _⟩, i, fun j hj => _, _⟩ rw [h j hj] dsimp only at hj · rw [Function.update_noteq hj.ne a] · rwa [Function.update_same i a] · rw [Function.update_noteq hj.ne a] · rwa [Function.update_same i a] [GOAL] case intro.intro.intro.intro ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ ∃ a, a₁✝ < a ∧ a < a₂ [PROOFSTEP] refine' ⟨Function.update a₂ _ a, ⟨i, fun j hj => _, _⟩, i, fun j hj => _, _⟩ [GOAL] case intro.intro.intro.intro.refine'_1 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ a₁✝ j = Function.update a₂ i a j case intro.intro.intro.intro.refine'_2 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (a₁✝ i) (Function.update a₂ i a i) case intro.intro.intro.intro.refine'_3 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ Function.update a₂ i a j = a₂ j case intro.intro.intro.intro.refine'_4 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (Function.update a₂ i a i) (a₂ i) [PROOFSTEP] rw [h j hj] [GOAL] case intro.intro.intro.intro.refine'_1 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ a₂ j = Function.update a₂ i a j case intro.intro.intro.intro.refine'_2 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (a₁✝ i) (Function.update a₂ i a i) case intro.intro.intro.intro.refine'_3 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ Function.update a₂ i a j = a₂ j case intro.intro.intro.intro.refine'_4 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (Function.update a₂ i a i) (a₂ i) [PROOFSTEP] dsimp only at hj [GOAL] case intro.intro.intro.intro.refine'_1 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : j < i ⊢ a₂ j = Function.update a₂ i a j [PROOFSTEP] rw [Function.update_noteq hj.ne a] [GOAL] case intro.intro.intro.intro.refine'_2 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (a₁✝ i) (Function.update a₂ i a i) [PROOFSTEP] rwa [Function.update_same i a] [GOAL] case intro.intro.intro.intro.refine'_3 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i j : ι hj : (fun x x_1 => x < x_1) j i ⊢ Function.update a₂ i a j = a₂ j [PROOFSTEP] rw [Function.update_noteq hj.ne a] [GOAL] case intro.intro.intro.intro.refine'_4 ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) inst✝ : ∀ (i : ι), DenselyOrdered (β i) a₁✝ a₂ : Lex ((i : ι) → β i) i : ι h : ∀ (j : ι), (fun x x_1 => x < x_1) j i → a₁✝ j = a₂ j hi : a₁✝ i < a₂ i a : β i ha₁ : a₁✝ i < a ha₂ : a < a₂ i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (Function.update a₂ i a i) (a₂ i) [PROOFSTEP] rwa [Function.update_same i a] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) i : ι inst✝ : NoMaxOrder (β i) a : Lex ((i : ι) → β i) ⊢ ∃ b, a < b [PROOFSTEP] let ⟨b, hb⟩ := exists_gt (a i) [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) i : ι inst✝ : NoMaxOrder (β i) a : Lex ((i : ι) → β i) b : β i hb : a i < b ⊢ ∃ b, a < b [PROOFSTEP] classical exact ⟨Function.update a i b, i, fun j hj => (Function.update_noteq hj.ne b a).symm, by rwa [Function.update_same i b]⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) i : ι inst✝ : NoMaxOrder (β i) a : Lex ((i : ι) → β i) b : β i hb : a i < b ⊢ ∃ b, a < b [PROOFSTEP] exact ⟨Function.update a i b, i, fun j hj => (Function.update_noteq hj.ne b a).symm, by rwa [Function.update_same i b]⟩ [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop inst✝² : Preorder ι inst✝¹ : (i : ι) → LT (β i) i : ι inst✝ : NoMaxOrder (β i) a : Lex ((i : ι) → β i) b : β i hb : a i < b ⊢ (fun x x_1 x_2 => x_1 < x_2) i (a i) (Function.update a i b i) [PROOFSTEP] rwa [Function.update_same i b] [GOAL] ι : Type u_1 β : ι → Type u_2 r : ι → ι → Prop s : {i : ι} → β i → β i → Prop α : Type u_3 inst✝² : Preorder ι inst✝¹ : DecidableEq ι inst✝ : Preorder α f : ι → α i j : ι h₁ : i ≤ j h₂ : f j < f i ⊢ (fun x x_1 x_2 => x_1 < x_2) i (↑toLex (f ∘ ↑(Equiv.swap i j)) i) (↑toLex f i) [PROOFSTEP] simpa only [Pi.toLex_apply, Function.comp_apply, Equiv.swap_apply_left] using h₂
State Before: 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G m n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : m + 1 ≤ n ⊢ ContDiffOn 𝕜 m (derivWithin f₂ s₂) s₂ State After: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : none + 1 ≤ n ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ case some 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ val✝ : ℕ hmn : some val✝ + 1 ≤ n ⊢ ContDiffOn 𝕜 (some val✝) (derivWithin f₂ s₂) s₂ Tactic: cases m State Before: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : none + 1 ≤ n ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ State After: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ Tactic: change ∞ + 1 ≤ n at hmn State Before: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ State After: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n this : n = ⊤ ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ Tactic: have : n = ∞ := by simpa using hmn State Before: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n this : n = ⊤ ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ State After: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 ⊤ f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n this : n = ⊤ ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ Tactic: rw [this] at hf State Before: case none 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 ⊤ f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n this : n = ⊤ ⊢ ContDiffOn 𝕜 none (derivWithin f₂ s₂) s₂ State After: no goals Tactic: exact ((contDiffOn_top_iff_derivWithin hs).1 hf).2 State Before: 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ hmn : ⊤ + 1 ≤ n ⊢ n = ⊤ State After: no goals Tactic: simpa using hmn State Before: case some 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ val✝ : ℕ hmn : some val✝ + 1 ≤ n ⊢ ContDiffOn 𝕜 (some val✝) (derivWithin f₂ s₂) s₂ State After: case some 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ val✝ : ℕ hmn : ↑(Nat.succ val✝) ≤ n ⊢ ContDiffOn 𝕜 (some val✝) (derivWithin f₂ s₂) s₂ Tactic: change (Nat.succ _ : ℕ∞) ≤ n at hmn State Before: case some 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.3032059 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F f₂ : 𝕜 → F s₂ : Set 𝕜 hf : ContDiffOn 𝕜 n f₂ s₂ hs : UniqueDiffOn 𝕜 s₂ val✝ : ℕ hmn : ↑(Nat.succ val✝) ≤ n ⊢ ContDiffOn 𝕜 (some val✝) (derivWithin f₂ s₂) s₂ State After: no goals Tactic: exact ((contDiffOn_succ_iff_derivWithin hs).1 (hf.of_le hmn)).2
[STATEMENT] lemma ideduct_synth_reduce: fixes M::"('fun,'var) terms" and t::"('fun,'var) term" shows "\<lbrakk>M \<union> M' \<turnstile>\<^sub>c t; \<And>t'. t' \<in> M' \<Longrightarrow> M \<turnstile>\<^sub>c t'\<rbrakk> \<Longrightarrow> M \<turnstile>\<^sub>c t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>M \<union> M' \<turnstile>\<^sub>c t; \<And>t'. t' \<in> M' \<Longrightarrow> M \<turnstile>\<^sub>c t'\<rbrakk> \<Longrightarrow> M \<turnstile>\<^sub>c t [PROOF STEP] by (induct rule: intruder_synth_induct) auto
[STATEMENT] lemma quasi_transI[intro]: "(\<And>x y z. \<lbrakk> x \<^bsub>r\<^esub>\<prec> y; y \<^bsub>r\<^esub>\<prec> z \<rbrakk> \<Longrightarrow> x \<^bsub>r\<^esub>\<prec> z) \<Longrightarrow> quasi_trans r" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>x y z. \<lbrakk>x \<^bsub>r\<^esub>\<prec> y; y \<^bsub>r\<^esub>\<prec> z\<rbrakk> \<Longrightarrow> x \<^bsub>r\<^esub>\<prec> z) \<Longrightarrow> quasi_trans r [PROOF STEP] unfolding quasi_trans_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>x y z. \<lbrakk>x \<^bsub>r\<^esub>\<prec> y; y \<^bsub>r\<^esub>\<prec> z\<rbrakk> \<Longrightarrow> x \<^bsub>r\<^esub>\<prec> z) \<Longrightarrow> \<forall>x y z. x \<^bsub>r\<^esub>\<prec> y \<and> y \<^bsub>r\<^esub>\<prec> z \<longrightarrow> x \<^bsub>r\<^esub>\<prec> z [PROOF STEP] by blast
import data.set import data.set.basic import set_theory.zfc -- import data.nat.basic -- import set_theory.cardinal -- open Set open set --open cardinal universes u v variables {α β : Type u} variables {a b c: Type u} variables {A C: set α} variable B: set β #check prod α β #reduce prod A B #check α #check (set α) #eval 1 + 2 --#check set({a b}) #check (a,b) #reduce (a, b).1 #reduce (a, b).2 #check [1, 2] -- list ℕ #check [a,b] -- List (Type u) --instance i: (x: nat) (y: nat) := ⟨1, 2⟩ def v : set nat := {1,2} #check v def v2 : set nat := {2, 3} def v3: set (ℕ × ℕ) := {(1,2), (2,4)} def v4: set(ℕ × ℕ) := {(1,2),(3,4)} def powerset' (A : set α) : set (set α) := {B : set α | B ⊆ A} #reduce ∃⦃x:v3⦄, x.val.1 = 1 ∧ x.val.2 = 4 #print v3 #reduce (1,2) ∈ v3 #print powerset #reduce powerset A #reduce v × v2 -- #reduce (1,2) ∈ set(v × v2) #reduce 1 ∈ v2 #reduce 2 ∈ v #reduce 1 ∈ v #reduce A × B #reduce powerset A × B -- this is parsed with: powerset (A) × B #reduce powerset v2 × v2 -- parswed with: powerset (v2) × v2 #reduce powerset' {v2 × v2} --set(v2 × v2) #check v2 × v2 #print × #print prod #check prod v2 v2 #check set (prod v2 v2) #reduce (2,2) ∈ {v2 × v2} --#check (2,2) ∈ set (v2 × v2) #check A × B #check set (A × B) #check powerset {A × B} #check powerset A #reduce powerset A #reduce powerset {A × B} #check powerset {A × B} #check (1,2) ∈ powerset {A × B} #check powerset {v2 × v2} #check (2,2) ∈ powerset {v2 × v2} #reduce (2,2) ∈ powerset {v2 × v2} #check set (powerset {v2 × v2}) #check ℕ × ℕ #check set (ℕ × ℕ) -- are these same? def p : ℕ × ℤ := ⟨ 1, 2 ⟩ def p2 : ℕ × ℤ := (1, 2) #check p #check p2 #check Π x : α, β #check λ x: α, β -- these are same #check fun x: nat, x + 5 #check λ x: nat, x+ 5 #print ∣ def evens : set ℕ := {n | even n} #check nat × nat #check evens variable n':nat def n₂ : ℕ := 10 #check even n₂ #reduce even n₂ --variable e:nat variable s': set ℕ #check 1 ∈ s' -- caution!! `∣`(\mid) and `|` is different!! we can not use \mid in -- set comprehension. def test_false : set ℕ := {e | even e } #check test_false variables {A' B': set ℕ} #check A' × B' #check powerset {A' × B'} #check {(a,b)} ∈ powerset {A × B} #print A #print powerset -- This does not raises error but `set (set Type u)` does not seem what we want def test_function_from_set : set (set(Type u)) := {f | f ⊆ {A × B}} --def test_function_from_set : set (set(A × B)) := -- {sf | sf ∈ powerset (A.prod B)} def test_function_from_set2 {X' X'': set ℕ}: set (set(ℕ × ℕ)) := {sf | sf ∈ powerset (X'.prod X'')} namespace test variables X Y: set ℕ #check X × Y variables x: ℕ × ℕ #check x -- !caution! `prod X Y` and `set.prod X Y` are different!! #check prod X Y -- ↥X × ↥Y : Type #check set.prod X Y -- set (ℕ × ℕ) : Type ;; is equivalent to `X.prod Y` #check set (prod X Y) #print set.prod -- {p : α × β | p.fst ∈ s ∧ p.snd ∈ t} #print prod #print × -- prod def t {X Y: set ℕ}: set(ℕ × ℕ) := X.prod Y def t' : set(ℕ × ℕ) := X.prod Y #check t -- t : set (ℕ × ℕ) #check t' -- t' : set ℕ → set ℕ → set (ℕ × ℕ) #check t' 3 5 -- t' 3 5 : set (ℕ × ℕ) ; t' requires two parameters! #check x ∈ t variable f₂: ℕ → ℕ #check f₂ variable f₃: α → β #check f₃ #check ℕ namespace function def graph {α β: Type u} (f: α → β) : set (α × β) := {p | p.2 = f p.1} end function #check function.graph(f₃) def test_function_from_set2 {X' X'': set ℕ}: set (set(ℕ × ℕ)) := {sf | sf ∈ powerset (X'.prod X'')} variables {D E: set (Type u)} #check {p | p ∈ 𝒫(D.prod E)} -- not yet defined def setA {a: α} : set α:= {a | a ∈ A} def setA2 {A2: set α}: set α := {a | a ∈ A2} def setN {N: set ℕ}: set ℕ := {n | n ∈ N} variable θ: Type def setC {C2: set θ} :set θ := {c | c ∈ C2} -- Type*, Type u, Type _ is used for dependant type variable γ : Type* -- to avoid arbitaly universe name we can use `Type*` #check α -- Type u #check γ -- Type u_1 #check setN -- set ℕ #check setA -- set ?M_1 (this can not have set `α` because `α` is `Type u`) #check setA2 -- set ?M_1 #check setC -- set θ (this have type `set θ` is because `θ` is `Type`) #check ℕ -- Type #print ℕ -- `ℕ`:1024 := nat #check A -- set α #check {l | l ∈ setA} -- set ?M_1 #check {l2 | l2 ∈ A} -- set α -- We can not remove the hint `{setA: set α}` from `setA_from_setA` definition. -- Is this because `def` has its own scope that `setA` is missing the type info? def setA_from_setA {setA: set α}: set α := {x | x ∈ setA} -- Why OK? because the scope inside the {} is global? #check {l: α | l ∈ setA} end test --#reduce {f:nat × nat ∣ f ∈ powerset {v2 × v2}}don't know how to synthesize placeholder -- #check {n sf ∣ n ∈ ℕ} --#reduce {f ∣ f ∈ powerset {v2 × v2}} -- v = {1,2}, v2 = {2,3} -- v × v2 = {(1,2),(1,3),(2,2),(2,3)} -- powerset v × v2 = {∅, -- {(1,2)}, {(1,2),(1,3)},{(1,2),(2,2)},{(1,2),(2,3)},{} -- {(1,3),(2,2)}, {(1,3),(2,3)}, -- {(2,2),(2,3)}, -- {(1,2),(1,3),(2,2)},{(1,2),(2,2),(2,3)}, -- {(1,3),(2,2),(2,3)}, -- {(1,2),(1,3),(2,2),(2,3)}} namespace test2 #check a #check α #check 'a' -- We can not define the following -- def onetwo : α×β := ⟨α, β⟩ def ab : char × char := ⟨ 'a', 'b'⟩ #print char #print nat #print α #check (1,2) def sf₁ : set (set (ℕ × ℕ)) := {{(1,2)},{(1,2),(1,3)}} -- def sf₂ : set (set (α × β)) := {{⟨a,b⟩ },{(a,b)}} #check sf₁ def npair : ℕ × ℕ := (1,2) #check npair -- npair : ℕ × ℕ def npair₂ : ℕ × ℕ := ⟨1,2⟩ -- whats the difference on `()` and `⟨ ⟩`? #check npair₂ -- npair₂ : ℕ × ℕ def nset₁ : set ℕ := {1,2} def nset₂ : set ℕ := {1,2} -- we can not call this. why? --#check nset₁.prod nset₂ #check nset₁ -- set: ℕ -- we can not infer the type of {1,2} --def setnpair : set (ℕ × ℕ) := {1,2}.prod {2,3} -- the type is `set (ℕ × ℕ)` (not `(set ℕ) × (set ℕ)`) def npairset : set (ℕ × ℕ) := ({1,2}:set ℕ).prod ({2,3}:set ℕ) #check npairset -- set (ℕ × ℕ) #reduce npairset def npairset₂ : set (ℕ × ℕ) := {(1,2),(3,4),(5,6)} #check npairset₂ -- npaierset₂ : set (ℕ × ℕ ) #reduce npairset₂ -- λ (b : ℕ × ℕ), b = (1, 2) ∨ b = (3, 4) ∨ b = (5, 6) def setnpair : set ℕ × set ℕ := ⟨ {1,2,3} , {2,3,4,5} ⟩ #check setnpair -- set ℕ × set ℕ #check A -- set α #check A.prod B -- set (α × β) -- When the type is ℕ variables {n₁ n₂ : ℕ} variable {N₁: set ℕ} variable {N₂: set ℕ} #check N₁.prod N₂ -- set (ℕ × ℕ) #check (1,2) ∈ N₁.prod N₂ --(X.prod Y) #check (n₁,n₂) ∈ N₁.prod N₂ #print ℕ #print nat -- When it is generic Type variables {x₁ y₁: Type} variables {X₁: set Type} variables {Y₁: set Type} #check X₁.prod Y₁ -- X₁.prod Y₁ : set (Type × Type) #check (x₁,y₁) ∈ X₁.prod Y₁ variable f₁ : set (Type × Type) #check f₁ -- f₁ : set (Type × Type) #check set(X₁ × Y₁) -- set (↥X₁ × ↥Y₁) : Type 1 #check ↥X₁ #reduce ↥X₁ -- {x // X₁ x} #check ↥X₁ × ↥Y₁ -- ↥X₁ × ↥Y₁ : Type 1 #reduce coe_sort X₁ #check X₁.prod Y₁ -- X₁.prod Y₁ : set (Type × Type) #check (x₁,y₁) -- (x₁, y₁) : Type × Type #check (x₁,y₁) ∈ f₁ -- (x₁, y₁) ∈ f₁ : Prop #check coe_sort X₁ × coe_sort Y₁ -- ↥X₁ × ↥Y₁ : Type 1 #check coe_sort X₁ --#check (x₁, y₁) ∈ (X₁ × Y₁) #check ↑X₁ --↑X₁ : ?M_1 #check subtype X₁ -- subtype X₁ : Type 1 variable s : set α #check subtype s /-- invalid definition -/ -- Pitfalls -- ======== -- 1. The type of f is not `set (X × Y)` because the type of `X` is `set Type*`, -- This it means it is a term not a type, so `X × Y` does not work as -- expected. -- 2. `x:X` is expected to express `x ∈ X`, but again -- `X` does not express the expected type. (it is coerced type ↥X in reality) -- Thus `x:X` does not mean that `x` is a member of the set `X`. -- It also does not mean `x` is a type of `Type*`. -- Instead, it means `x` is a type of `↥X`, therefore `(x, y)` has -- the type `(↥X, ↥Y)`. def is_function_invalid (X Y: set Type*) (f: set (X × Y)): Prop := ∀x:X,∃!y:Y, (x,y) ∈ f /-- invalid definition -/ def funs_invalid {X Y: set Type*} : set (set (X × Y)) := {f | f ∈ 𝒫 (X.prod Y) ∧ (is_function_invalid X Y f)} /-- The function x is a triple: (T, T, (T, T)) (T can be any type) -/ -- Note that: -- `∀x ∈ X` means `∀x: α, x ∈ X → ...` -- `∃y ∈ Y` means `∃y: β, y ∈ Y ∧ ... ` def is_function (X:set α) (Y: set β) (f: set (α × β)): Prop := f ⊆ X.prod Y ∧ ∀x ∈ X,∃!y ∈ Y, (x,y) ∈ f -- not yet defined -- `funs X Y` is `Y ^ X` def funs (X : set α) (Y: set β): set (set (α × β)) := {f | f ∈ 𝒫 (X.prod Y) ∧ (is_function X Y f)} theorem mem_funs_equiv_isfunction {X: set α} {Y: set β } {f: set (α × β)}: f ∈ funs X Y ↔ is_function X Y f := by simp [funs, is_function] --variable a_number₂ : --def setN: set ℕ := {n | n: ℕ} def example2 {n: ℕ} : Prop := n = 1 --lemma example3: ∀n:ℕ, n = 1 := sorry #print set -- universes u v -- this definition is from library/init/data/set.lean def set₁ (α : Type u) := α → Prop end test2 namespace ZFCSet -- These definitions are copied from set_theorey/zfc.lean /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet #check pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} #check Set #reduce Set.{u} #check Set.{v} #print pSet.setoid --variable (x : Set.{u}) notation `⋃` := Set.Union /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b} /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λa b, true) /-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function (a set of ordered pairs) -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀z:Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} end ZFCSet
Require Import prosa.classic.util.all. Require Import prosa.classic.model.priority. Require Import prosa.classic.model.arrival.basic.task. Require Import prosa.classic.model.arrival.jitter.job prosa.classic.model.arrival.jitter.task_arrival prosa.classic.model.arrival.jitter.arrival_sequence prosa.classic.model.arrival.jitter.arrival_bounds. Require Import prosa.classic.model.schedule.uni.schedule_of_task prosa.classic.model.schedule.uni.service prosa.classic.model.schedule.uni.schedulability prosa.classic.model.schedule.uni.response_time. Require Import prosa.classic.model.schedule.uni.jitter.schedule prosa.classic.model.schedule.uni.jitter.busy_interval prosa.classic.model.schedule.uni.jitter.platform. Require Import prosa.classic.analysis.uni.jitter.workload_bound_fp. From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop. Module ResponseTimeAnalysisFP. Import ArrivalSequenceWithJitter JobWithJitter TaskArrivalWithJitter ArrivalBounds UniprocessorScheduleWithJitter ScheduleOfTask SporadicTaskset Priority ResponseTime WorkloadBoundFP Platform Schedulability BusyInterval. (* In this section, we prove that any fixed point in the RTA for jitter-aware uniprocessor FP scheduling is a response-time bound. *) Section ResponseTimeBound. Context {SporadicTask: eqType}. Variable task_cost: SporadicTask -> time. Variable task_period: SporadicTask -> time. Variable task_deadline: SporadicTask -> time. Variable task_jitter: SporadicTask -> time. Context {Job: eqType}. Variable job_arrival: Job -> time. Variable job_cost: Job -> time. Variable job_jitter: Job -> time. Variable job_task: Job -> SporadicTask. (* Consider any task set ts... *) Variable ts: seq SporadicTask. (* ...with positive task periods. *) Hypothesis H_positive_periods: forall tsk, tsk \in ts -> task_period tsk > 0. (* Consider any job arrival sequence with consistent, duplicate-free arrivals... *) Variable arr_seq: arrival_sequence Job. Hypothesis H_arrival_times_are_consistent: arrival_times_are_consistent job_arrival arr_seq. Hypothesis H_arr_seq_is_a_set: arrival_sequence_is_a_set arr_seq. (* ... in which jobs arrive sporadically,... *) Hypothesis H_sporadic_tasks: sporadic_task_model task_period job_arrival job_task arr_seq. (* ...the cost of each job is bounded by the cost of its task, ... *) Hypothesis H_job_cost_le_task_cost: forall j, arrives_in arr_seq j -> job_cost j <= task_cost (job_task j). (* ...and the jitter of each job is bounded by the jitter of its task. *) Hypothesis H_job_jitter_le_task_jitter: forall j, arrives_in arr_seq j -> job_jitter j <= task_jitter (job_task j). (* Assume that all jobs in the arrival sequence come from the task set. *) Hypothesis H_all_jobs_from_taskset: forall j, arrives_in arr_seq j -> job_task j \in ts. (* Next, consider any uniprocessor schedule of this arrival sequence... *) Variable sched: schedule Job. Hypothesis H_jobs_come_from_arrival_sequence: jobs_come_from_arrival_sequence sched arr_seq. (* ...such that jobs do not execute before the jitter has passed nor after completion. *) Hypothesis H_jobs_execute_after_jitter: jobs_execute_after_jitter job_arrival job_jitter sched. Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched. (* Consider any FP policy that indicates a higher-or-equal priority relation, where the relation is reflexive and transitive. *) Variable higher_eq_priority: FP_policy SporadicTask. Hypothesis H_priority_is_reflexive: FP_is_reflexive higher_eq_priority. Hypothesis H_priority_is_transitive: FP_is_transitive higher_eq_priority. (* Next, assume that the schedule is a jitter-aware, work-conserving FP schedule. *) Hypothesis H_work_conserving: work_conserving job_arrival job_cost job_jitter arr_seq sched. Hypothesis H_respects_fp_policy: respects_FP_policy job_arrival job_cost job_jitter job_task arr_seq sched higher_eq_priority. (* Now we proceed with the analysis. Let tsk be any task in ts that is to be analyzed. *) Variable tsk: SporadicTask. Hypothesis H_tsk_in_ts: tsk \in ts. (* Recall the definition of response-time bound and the total workload bound W for higher-or-equal-priority tasks (with respect to tsk). *) Let response_time_bounded_by := is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched. Let W := total_workload_bound_fp task_cost task_period task_jitter higher_eq_priority ts tsk. (* Let R be any positive fixed point of the response-time recurrence. *) Variable R: time. Hypothesis H_R_positive: R > 0. Hypothesis H_response_time_is_fixed_point: R = W R. (* Since R = W R bounds the workload of higher-or-equal priority and actual arrival time in any interval of length R, it follows from the busy-interval lemmas that R bounds the response-time of job j. (For more details, see model/uni/jitter/busy_interval.v and analysis/uni/jitter/workload_bound_fp.v.) *) Theorem uniprocessor_response_time_bound_fp: response_time_bounded_by tsk (task_jitter tsk + R). Proof. unfold valid_sporadic_job_with_jitter, valid_sporadic_job, valid_sporadic_taskset, is_valid_sporadic_task in *. rename H_response_time_is_fixed_point into FIX. intros j IN JOBtsk. set arr := actual_arrival job_arrival job_jitter. apply completion_monotonic with (t := arr j + R); try (by done). { rewrite -addnA leq_add2l leq_add2r. by rewrite -JOBtsk; apply H_job_jitter_le_task_jitter. } set prio := FP_to_JLFP job_task higher_eq_priority. apply busy_interval_bounds_response_time with (arr_seq0 := arr_seq) (higher_eq_priority0 := prio); try (by done). - by intros x; apply H_priority_is_reflexive. - by intros x z y; apply H_priority_is_transitive. intros t. apply fp_workload_bound_holds with (task_cost0 := task_cost) (task_period0 := task_period) (task_jitter0 := task_jitter) (ts0 := ts); try (by done). by rewrite JOBtsk. Qed. End ResponseTimeBound. End ResponseTimeAnalysisFP.
module Cat import World %access export record Cat where constructor MkCat catHealth : Int catBlack : Bool %name Cat cat, cat' catAttack : Int -> Cat -> Cat catAttack x (MkCat h b) = if b then MkCat (h + x) b else if h <= x then MkCat 0 True else MkCat (h - x) b entityCat : Entity Cat entityCat = MkEntity catHealth catAttack spawnCat : Key -> Cat -> Host -> Host spawnCat = spawn entityCat
(** Well-founded order on products of [nat] *) From Coq Require Import Relation_Operators Lexicographic_Product Lia. From Coq Require Export Wf_nat. Set Implicit Arguments. (** * Well founded order on pairs of [nat] *) Definition lt_nat_nat := slexprod _ _ lt lt. Definition wf_nat_nat := wf_slexprod _ _ _ _ lt_wf lt_wf. Ltac lt_nat_nat_solve := match goal with | |- lt_nat_nat _ _ => try (left; cbn; lia); try (right; cbn; lia); fail | |- slexprod _ _ lt lt _ _ => try (left; cbn; lia); try (right; cbn; lia); fail end. (** * Well founded order on triples of [nat] *) Definition lt_nat_nat_nat := slexprod _ _ lt lt_nat_nat. Definition wf_nat_nat_nat := wf_slexprod _ _ _ _ lt_wf wf_nat_nat. Ltac lt_nat_nat_nat_solve := match goal with | |- lt_nat_nat_nat _ _ => try (left; cbn; lia); try (right; left; cbn; lia); try (right; right; cbn; lia); fail | |- slexprod _ _ lt lt_nat_nat _ _ => try (left; cbn; lia); try (right; left; cbn; lia); try (right; right; cbn; lia); fail | |- slexprod _ _ lt (slexprod _ _ lt lt) _ _ => try (left; cbn; lia); try (right; left; cbn; lia); try (right; right; cbn; lia); fail end.
-- @@stderr -- dtrace: failed to compile script test/unittest/types/err.D_OP_INT.badbitop.d: [D_OP_INT] line 20: operator & requires operands of integral type
[STATEMENT] lemma fixedpoint: "\<exists>!x. f (g x) = x \<Longrightarrow> \<exists>!y. g (f y) = y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>!x. f (g x) = x \<Longrightarrow> \<exists>!y. g (f y) = y [PROOF STEP] by metis
open import Data.Nat using (ℕ; zero; suc; _+_; _*_) open import Data.Product using (∃; _,_) open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym) +-identity : ∀ (m : ℕ) → m + zero ≡ m +-identity zero = refl +-identity (suc m) rewrite +-identity m = refl +-suc : ∀ (m n : ℕ) → n + suc m ≡ suc (n + m) +-suc m zero = refl +-suc m (suc n) rewrite +-suc m n = refl +-comm : ∀ (m n : ℕ) → m + n ≡ n + m +-comm zero n rewrite +-identity n = refl +-comm (suc m) n rewrite +-suc m n | +-comm m n = refl mutual data even : ℕ → Set where zero : even zero suc : ∀ {n : ℕ} → odd n → even (suc n) data odd : ℕ → Set where suc : ∀ {n : ℕ} → even n → odd (suc n) +-lemma : ∀ (m : ℕ) → suc (suc (m + (m + 0))) ≡ suc m + suc (m + 0) +-lemma m rewrite +-identity m | +-suc m m = refl mutual is-even : ∀ (n : ℕ) → even n → ∃(λ (m : ℕ) → n ≡ 2 * m) is-even zero zero = zero , refl is-even (suc n) (suc oddn) with is-odd n oddn ... | m , n≡1+2*m rewrite n≡1+2*m | +-lemma m = suc m , refl is-odd : ∀ (n : ℕ) → odd n → ∃(λ (m : ℕ) → n ≡ 1 + 2 * m) is-odd (suc n) (suc evenn) with is-even n evenn ... | m , n≡2*m rewrite n≡2*m = m , refl +-lemma′ : ∀ (m : ℕ) → suc (suc (m + (m + 0))) ≡ suc m + suc (m + 0) +-lemma′ m rewrite +-suc (m + 0) m = refl is-even′ : ∀ (n : ℕ) → even n → ∃(λ (m : ℕ) → n ≡ 2 * m) is-even′ zero zero = zero , refl is-even′ (suc n) (suc oddn) with is-odd n oddn ... | m , n≡1+2*m rewrite n≡1+2*m | +-identity m | +-suc m m = suc m , {!!}
struct PairFeatureDescriptor <: AbstractPairFeatureDescriptor name::String encode_f::Any decode_f::Any length::Int # maybe, maybe not (does constrain/assume vector encoding) # probably needs some other stuff... end
%% Double Pendulum % Clear work space and initaliza figure clear; clc; close all; %figure; %% Initial and Constant Values % Initial values for tuned state (1): % gamma0 = pi/12; % dtgamma0 = pi; % alpha0 = 0; % dtalpha0 = 0; % Initial values for tuned state (2): % gamma0 = 0; % dtgamma0 = 0; % alpha0 = pi/6; % dtalpha0 = pi/36; % Initial values for tuned state (3): % gamma0 = 0; % dtgamma0 = 0; % alpha0 = pi/24; % dtalpha0 = pi/2; % Initial values for chaotic solution: % gamma0 = 0; % dtgamma0 = 0; % alpha0 = pi/2; % dtalpha0 = 5; % Initial values for chaotic solution2: gamma0 = 0; dtgamma0 = 0; alpha0 = pi/2; dtalpha0 = 5.025; % Constant Values beta0 = pi/2; lambda = 2.74; %rad/s omega = 5.48; %rad/s psi = 0.96; eta = 0.24; fps = 10; %movie = true; %% Using solver ode45 duration = 100; ivp = [gamma0; dtgamma0; alpha0; dtalpha0; beta0; lambda; omega; psi; eta]; [t,x] = ode45(@dpendulum,[0 duration], ivp); %options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]); %[t,x]=ode45(@dpendulum,[0 duration], ivp, options); %% Plot nframes=duration*fps; %t = linspace(0,duration,nframes); %x = deval(sol,t); gamma = x(:,1); dtgamma = x(:,2); alpha = x(:,3); dtalpha = x(:,4); % we assume: l1=1; % b distance l2=2; % c distance %% Plot alpha vs Gamma figure; plot (t,x(:,3),'-.',t,x(:,1),'-') %% Plot d_alpha vs d_Gamma figure; plot (t,x(:,4),'-.',t,x(:,2),'-')
Formal statement is: lemma filterlim_at_infinity_conv_norm_at_top: "filterlim f at_infinity G \<longleftrightarrow> filterlim (\<lambda>x. norm (f x)) at_top G" Informal statement is: The limit of $f$ at infinity is the same as the limit of $f$ at infinity.
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Eric Wieser -/ import data.matrix.basis import ring_theory.tensor_product /-! We show `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)`. -/ universes u v w open_locale tensor_product open_locale big_operators open tensor_product open algebra.tensor_product open matrix variables {R : Type u} [comm_semiring R] variables {A : Type v} [semiring A] [algebra R A] variables {n : Type w} variables (R A n) namespace matrix_equiv_tensor /-- (Implementation detail). The function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an `R`-bilinear map. -/ def to_fun_bilinear : A →ₗ[R] matrix n n R →ₗ[R] matrix n n A := (algebra.lsmul R (matrix n n A)).to_linear_map.compl₂ (algebra.linear_map R A).map_matrix @[simp] lemma to_fun_bilinear_apply (a : A) (m : matrix n n R) : to_fun_bilinear R A n a m = a • m.map (algebra_map R A) := rfl /-- (Implementation detail). The function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an `R`-linear map. -/ def to_fun_linear : A ⊗[R] matrix n n R →ₗ[R] matrix n n A := tensor_product.lift (to_fun_bilinear R A n) variables [decidable_eq n] [fintype n] /-- The function `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an algebra homomorphism. -/ def to_fun_alg_hom : (A ⊗[R] matrix n n R) →ₐ[R] matrix n n A := alg_hom_of_linear_map_tensor_product (to_fun_linear R A n) begin intros, simp_rw [to_fun_linear, lift.tmul, to_fun_bilinear_apply, mul_eq_mul, matrix.map_mul], ext, dsimp, simp_rw [matrix.mul_apply, pi.smul_apply, matrix.map_apply, smul_eq_mul, finset.mul_sum, _root_.mul_assoc, algebra.left_comm], end begin intros, simp_rw [to_fun_linear, lift.tmul, to_fun_bilinear_apply, matrix.map_one (algebra_map R A) (map_zero _) (map_one _), algebra_map_smul, algebra.algebra_map_eq_smul_one], end @[simp] lemma to_fun_alg_hom_apply (a : A) (m : matrix n n R) : to_fun_alg_hom R A n (a ⊗ₜ m) = a • m.map (algebra_map R A) := by simp [to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear] /-- (Implementation detail.) The bare function `matrix n n A → A ⊗[R] matrix n n R`. (We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.) -/ def inv_fun (M : matrix n n A) : A ⊗[R] matrix n n R := ∑ (p : n × n), M p.1 p.2 ⊗ₜ (std_basis_matrix p.1 p.2 1) @[simp] lemma inv_fun_zero : inv_fun R A n 0 = 0 := by simp [inv_fun] @[simp] lemma inv_fun_add (M N : matrix n n A) : inv_fun R A n (M + N) = inv_fun R A n M + inv_fun R A n N := by simp [inv_fun, add_tmul, finset.sum_add_distrib] @[simp] lemma inv_fun_smul (a : A) (M : matrix n n A) : inv_fun R A n (a • M) = (a ⊗ₜ 1) * inv_fun R A n M := by simp [inv_fun,finset.mul_sum] @[simp] lemma inv_fun_algebra_map (M : matrix n n R) : inv_fun R A n (M.map (algebra_map R A)) = 1 ⊗ₜ M := begin dsimp [inv_fun], simp only [algebra.algebra_map_eq_smul_one, smul_tmul, ←tmul_sum, mul_boole], congr, conv_rhs {rw matrix_eq_sum_std_basis M}, convert finset.sum_product, simp, end lemma right_inv (M : matrix n n A) : (to_fun_alg_hom R A n) (inv_fun R A n M) = M := begin simp only [inv_fun, alg_hom.map_sum, std_basis_matrix, apply_ite ⇑(algebra_map R A), smul_eq_mul, mul_boole, to_fun_alg_hom_apply, ring_hom.map_zero, ring_hom.map_one, matrix.map_apply, pi.smul_def], convert finset.sum_product, apply matrix_eq_sum_std_basis, end lemma left_inv (M : A ⊗[R] matrix n n R) : inv_fun R A n (to_fun_alg_hom R A n M) = M := begin induction M using tensor_product.induction_on with a m x y hx hy, { simp, }, { simp, }, { simp [alg_hom.map_sum, hx, hy], }, end /-- (Implementation detail) The equivalence, ignoring the algebra structure, `(A ⊗[R] matrix n n R) ≃ matrix n n A`. -/ def equiv : (A ⊗[R] matrix n n R) ≃ matrix n n A := { to_fun := to_fun_alg_hom R A n, inv_fun := inv_fun R A n, left_inv := left_inv R A n, right_inv := right_inv R A n, } end matrix_equiv_tensor variables [fintype n] [decidable_eq n] /-- The `R`-algebra isomorphism `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)`. -/ def matrix_equiv_tensor : matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R) := alg_equiv.symm { ..(matrix_equiv_tensor.to_fun_alg_hom R A n), ..(matrix_equiv_tensor.equiv R A n) } open matrix_equiv_tensor @[simp] lemma matrix_equiv_tensor_apply (M : matrix n n A) : matrix_equiv_tensor R A n M = ∑ (p : n × n), M p.1 p.2 ⊗ₜ (std_basis_matrix p.1 p.2 1) := rfl @[simp] lemma matrix_equiv_tensor_apply_std_basis (i j : n) (x : A): matrix_equiv_tensor R A n (std_basis_matrix i j x) = x ⊗ₜ (std_basis_matrix i j 1) := begin have t : ∀ (p : n × n), (i = p.1 ∧ j = p.2) ↔ (p = (i, j)) := by tidy, simp [ite_tmul, t, std_basis_matrix], end @[simp] lemma matrix_equiv_tensor_apply_symm (a : A) (M : matrix n n R) : (matrix_equiv_tensor R A n).symm (a ⊗ₜ M) = M.map (λ x, a * algebra_map R A x) := begin simp [matrix_equiv_tensor, to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear], refl, end
[STATEMENT] lemma ex1_iff_Collect_singleton: "P x \<Longrightarrow> (\<exists>!x. P x) \<longleftrightarrow> Collect P = {x}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P x \<Longrightarrow> (\<exists>!x. P x) = (Collect P = {x}) [PROOF STEP] by (subst ex1_imp_Collect_singleton[symmetric], auto)
def chℕ := Π X : Type, (X → X) → X → X namespace chnat open nat definition to_nat (m : chℕ) : ℕ := m ℕ nat.succ 0 def of_nat : ℕ → chℕ | (zero) X f x := x | (succ n) X f x := f (of_nat n X f x) -- f (f^n x) def pow : chℕ → chℕ → chℕ := λ m n, λ X f x, n (X → X) (m X) f x #print chnat.pow def pow' (m n : chℕ) : chℕ | X f x := n (X → X) (m X) f x #print chnat.pow' theorem of_nat_pow (m n : ℕ) : of_nat (m ^ n) = pow (of_nat m) (of_nat n) := begin induction n with n H;funext,refl, unfold has_pow.pow, unfold nat.pow, unfold has_pow.pow at H, end end chnat
```python import numpy as np import sympy as sym import matplotlib.pyplot as plt %matplotlib inline import control ``` # Criterio de estabilidad de Routh Hasta el momento se ha mostrado que se puede identificar si un sistema LTI es estable o no al encontrar los polos del sistema, pues si TODOS los polos del sistema tienen parte real negativa, el sistema es estable. Además, se ha evidenciado que al realimentar negativamente un sistema, los polos del sistema se desplazan a nuevas ubicaciones. El [Criterio de estabilidad de Routh-Hurwitz](https://en.wikipedia.org/wiki/Routh%E2%80%93Hurwitz_stability_criterion) es una forma de determinar la estabilidad del sistema sin tener que calcular sus raíces. Además, al evitar el cálculo de las raíces, se evaden posibles errores al trabajar con polinomios de orden elevado. **Ejemplo** Suponga un proceso modelado por: $$G_p(s) = \frac{1}{\left (s + 1\right )^{10}}$$ Las raíces del sistema son: $$s_{1,2,3...,10} = -1$$ ```python # Se define la función de transferencia del proceso Gp = control.tf(1, [1,1]) Gp10 = Gp*Gp*Gp*Gp*Gp*Gp*Gp*Gp*Gp*Gp Gp10 ``` $$\frac{1}{s^{10} + 10 s^9 + 45 s^8 + 120 s^7 + 210 s^6 + 252 s^5 + 210 s^4 + 120 s^3 + 45 s^2 + 10 s + 1}$$ ```python ceros = Gp10.zero() ceros ``` array([], dtype=float64) ```python polos = Gp10.pole() polos ``` array([-1.04908973+0.01621888j, -1.04908973-0.01621888j, -1.02967474+0.04196254j, -1.02967474-0.04196254j, -0.99920869+0.05091358j, -0.99920869-0.05091358j, -0.96983514+0.04045704j, -0.96983514-0.04045704j, -0.9521917 +0.01528717j, -0.9521917 -0.01528717j]) Observe que los polos no están ubicados en $s=-1$. Estos errores se deben a las representaciones discretas de los números. La función `routh` permite encontrar la matriz de Routh a partir de un objeto tipo `Poly` de `Sympy` ```python from tbcontrol.symbolic import routh help(routh) ``` Help on function routh in module tbcontrol.symbolic: routh(p) Construct the Routh-Hurwitz array given a polynomial in s Input: p - a sympy.Poly object Output: The Routh-Hurwitz array as a sympy.Matrix object ```python s = sym.Symbol('s') a0, a1, a2, a3, a4,a5,a6,a7,a8,a9,a10 = sym.symbols('a_0:11') p = (a0 + a1*s**1 + a2*s**2 + a3*s**3 + a4*s**4 + a5*s**5 + a6*s**6) p = sym.Poly(p, s) p ``` $\displaystyle \operatorname{Poly}{\left( a_{6} s^{6} + a_{5} s^{5} + a_{4} s^{4} + a_{3} s^{3} + a_{2} s^{2} + a_{1} s + a_{0}, s, domain=\mathbb{Z}\left[a_{0}, a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, a_{6}\right] \right)}$ ```python routh(p) ``` $\displaystyle \left[\begin{matrix}a_{6} & a_{4} & a_{2} & a_{0}\\a_{5} & a_{3} & a_{1} & 0\\- \frac{a_{3} a_{6}}{a_{5}} + a_{4} & - \frac{a_{1} a_{6}}{a_{5}} + a_{2} & a_{0} & 0\\\frac{a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) + a_{5} \left(- a_{1} a_{6} + a_{2} a_{5}\right)}{a_{3} a_{6} - a_{4} a_{5}} & \frac{a_{0} a_{5}^{2} + a_{1} \left(a_{3} a_{6} - a_{4} a_{5}\right)}{a_{3} a_{6} - a_{4} a_{5}} & 0 & 0\\\frac{\left(a_{0} a_{5}^{2} + a_{1} \left(a_{3} a_{6} - a_{4} a_{5}\right)\right) \left(a_{3} a_{6} - a_{4} a_{5}\right) - \left(a_{1} a_{6} - a_{2} a_{5}\right) \left(a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) - a_{5} \left(a_{1} a_{6} - a_{2} a_{5}\right)\right)}{a_{5} \left(a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) - a_{5} \left(a_{1} a_{6} - a_{2} a_{5}\right)\right)} & a_{0} & 0 & 0\\\frac{- a_{0} a_{5} \left(a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) - a_{5} \left(a_{1} a_{6} - a_{2} a_{5}\right)\right)^{2} + \left(a_{0} a_{5}^{2} + a_{1} \left(a_{3} a_{6} - a_{4} a_{5}\right)\right) \left(\left(a_{0} a_{5}^{2} + a_{1} \left(a_{3} a_{6} - a_{4} a_{5}\right)\right) \left(a_{3} a_{6} - a_{4} a_{5}\right) - \left(a_{1} a_{6} - a_{2} a_{5}\right) \left(a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) - a_{5} \left(a_{1} a_{6} - a_{2} a_{5}\right)\right)\right)}{\left(a_{3} a_{6} - a_{4} a_{5}\right) \left(\left(a_{0} a_{5}^{2} + a_{1} \left(a_{3} a_{6} - a_{4} a_{5}\right)\right) \left(a_{3} a_{6} - a_{4} a_{5}\right) - \left(a_{1} a_{6} - a_{2} a_{5}\right) \left(a_{3} \left(a_{3} a_{6} - a_{4} a_{5}\right) - a_{5} \left(a_{1} a_{6} - a_{2} a_{5}\right)\right)\right)} & 0 & 0 & 0\\a_{0} & 0 & 0 & 0\end{matrix}\right]$ El sistema es estable siempre que los elementos de la primera columna sean del mismo signo. ---------------------------------- ¿Qué pasa con el sistema de décimo orden definido anteriormente? ```python Coef_den = Gp10.den[0][0].tolist() orden_den = len(Coef_den)-1 Gp10Den = 0 for val in Coef_den: Gp10Den = Gp10Den + val*s**(orden_den) orden_den = orden_den-1 Gp10Den = sym.Poly(Gp10Den, s) routh(Gp10Den) ``` $\displaystyle \left[\begin{matrix}1 & 45 & 210 & 210 & 45 & 1\\10 & 120 & 252 & 120 & 10 & 0\\33 & \frac{924}{5} & 198 & 44 & 1 & 0\\64 & 192 & \frac{320}{3} & \frac{320}{33} & 0 & 0\\\frac{429}{5} & 143 & 39 & 1 & 0 & 0\\\frac{256}{3} & \frac{2560}{33} & \frac{1280}{143} & 0 & 0 & 0\\65 & 30 & 1 & 0 & 0 & 0\\\frac{16384}{429} & \frac{16384}{2145} & 0 & 0 & 0 & 0\\17 & 1 & 0 & 0 & 0 & 0\\\frac{65536}{12155} & 0 & 0 & 0 & 0 & 0\\1 & 0 & 0 & 0 & 0 & 0\end{matrix}\right]$ Todos los elementos de la primera columna son positivos, por lo cuál el sistema es estable. ¿y si se realimenta y se configura un controlador $G_c(s) = k_c$? ```python kc = sym.symbols('k_c', real=True,positive = True) ########################################## Coef_num = Gp10.num[0][0].tolist() orden_num = len(Coef_num)-1 Gp10Num = 0 for val in Coef_num: Gp10Num = Gp10Num + val*s**(orden_num) orden_num = orden_num-1 Gp10Num = sym.Poly(Gp10Num, s) ########################################## Coef_den = Gp10.den[0][0].tolist() orden_den = len(Coef_den)-1 Gp10Den = 0 for val in Coef_den: Gp10Den = Gp10Den + val*s**(orden_den) orden_den = orden_den-1 Gp10Den = sym.Poly(Gp10Den, s) #########################################3 ### DenominadorLC = Nc*Np + Dc*Dp A = routh(kc*Gp10Num + Gp10Den) A ``` $\displaystyle \left[\begin{matrix}1.0 & 45.0 & 210.0 & 210.0 & 45.0 & 1.0 k_{c} + 1.0\\10.0 & 120.0 & 252.0 & 120.0 & 10.0 & 0\\33.0 & 184.8 & 198.0 & 44.0 & 1.0 k_{c} + 1.0 & 0\\64.0 & 192.0 & 106.666666666667 & 9.6969696969697 - 0.303030303030303 k_{c} & 0 & 0\\85.8 & 143.0 & 0.15625 k_{c} + 39.0 & 1.0 k_{c} + 1.0 & 0 & 0\\85.3333333333333 & 77.5757575757576 - 0.116550116550117 k_{c} & 8.95104895104895 - 1.04895104895105 k_{c} & 0 & 0 & 0\\0.1171875 k_{c} + 65.0 & 1.2109375 k_{c} + 30.0 & 1.0 k_{c} + 1.0 & 0 & 0 & 0\\\frac{- 0.0136582167832168 k_{c}^{2} - 101.818181818182 k_{c} + 2482.42424242424}{0.1171875 k_{c} + 65.0} & \frac{- 0.122923951048951 k_{c}^{2} - 152.4662004662 k_{c} + 496.484848484848}{0.1171875 k_{c} + 65.0} & 0 & 0 & 0 & 0\\\frac{1.0 \left(0.00213409637237762 k_{c}^{3} + 97.8480113636364 k_{c}^{2} - 9803.63636363636 k_{c} - 42201.2121212121\right)}{0.0136582167832168 k_{c}^{2} + 101.818181818182 k_{c} - 2482.42424242424} & 1.0 k_{c} + 1.0 & 0 & 0 & 0 & 0\\\frac{- 7.5784672314546 \cdot 10^{-5} k_{c}^{5} - 9.57174557804885 k_{c}^{4} - 3410.44077134987 k_{c}^{3} + 1053278.06738716 k_{c}^{2} + 7223819.82623436 k_{c} - 14789832.2865014}{0.000250089418638002 k_{c}^{4} + 11.6052800958807 k_{c}^{3} + 5211.25710227273 k_{c}^{2} - 642181.818181818 k_{c} - 2743078.78787879} & 0 & 0 & 0 & 0 & 0\\1.0 k_{c} + 1.0 & 0 & 0 & 0 & 0 & 0\end{matrix}\right]$ ```python sym.solve([e > 0 for e in A[:, 0]], kc) ``` $\displaystyle \left(104.09924325141 < k_{c} \vee k_{c} < 24.3017308778435\right) \wedge \left(\left(104.09924325141 < k_{c} \wedge k_{c} < 203.14827879423\right) \vee k_{c} < 1.65172120576948\right) \wedge k_{c} < 24.3017308778435$ Esto indica que $k_c<1.652$ permite obtener un sistema estable en lazo cerrado. ```python k1 = 1.6 k2 = 1.7 Gp10LC1 = control.feedback(k1*Gp10,1) Gp10LC2 = control.feedback(k2*Gp10,1) ``` ```python routh(k1*Gp10Num + Gp10Den) ``` $\displaystyle \left[\begin{matrix}1.0 & 45.0 & 210.0 & 210.0 & 45.0 & 2.6\\10.0 & 120.0 & 252.0 & 120.0 & 10.0 & 0\\33.0 & 184.8 & 198.0 & 44.0 & 2.6 & 0\\64.0 & 192.0 & 106.666666666667 & 9.21212121212121 & 0 & 0\\85.8 & 143.0 & 39.25 & 2.6 & 0 & 0\\85.3333333333333 & 77.3892773892774 & 7.27272727272727 & 0 & 0 & 0\\65.1875 & 31.9375 & 2.6 & 0 & 0 & 0\\35.5816711252953 & 3.86921177256748 & 0 & 0 & 0 & 0\\24.8488997615212 & 2.6 & 0 & 0 & 0 & 0\\0.146216154506988 & 0 & 0 & 0 & 0 & 0\\2.6 & 0 & 0 & 0 & 0 & 0\end{matrix}\right]$ ```python routh(k2*Gp10Num + Gp10Den) ``` $\displaystyle \left[\begin{matrix}1.0 & 45.0 & 210.0 & 210.0 & 45.0 & 2.7\\10.0 & 120.0 & 252.0 & 120.0 & 10.0 & 0\\33.0 & 184.8 & 198.0 & 44.0 & 2.7 & 0\\64.0 & 192.0 & 106.666666666667 & 9.18181818181818 & 0 & 0\\85.8 & 143.0 & 39.265625 & 2.7 & 0 & 0\\85.3333333333333 & 77.3776223776224 & 7.16783216783217 & 0 & 0 & 0\\65.19921875 & 32.05859375 & 2.7 & 0 & 0 & 0\\35.4190419051122 & 3.63404749345675 & 0 & 0 & 0 & 0\\25.3690548825024 & 2.7 & 0 & 0 & 0 & 0\\-0.135561330629251 & 0 & 0 & 0 & 0 & 0\\2.7 & 0 & 0 & 0 & 0 & 0\end{matrix}\right]$ ```python control.pzmap(Gp10LC1) ``` ```python control.pzmap(Gp10LC2) ``` Considere un proceso modelado por: $$G_p(s) = \frac{s+3}{\left (s+2 \right )\left (s+1 \right )} $$ y un controlador $G_c(s)=k_c$ Encuentre qué valores de $k_c$ permiten que el sistema en lazo cerrado sea estable. ```python ```
% Version 1.000 % % Code provided by Ruslan Salakhutdinov % % Permission is granted for anyone to copy, use, modify, or distribute this % program and accompanying programs and documents for any purpose, provided % this copyright notice is retained and prominently displayed, along with % a note saying that the original programs are available from our % web page. % The programs and documents are distributed without any warranty, express or % implied. As the programs were written for research purposes only, they have % not been tested to the degree that would be advisable in any important % application. All use of these programs is entirely at the user's own risk. %%%%% Initialize biases of the base-rate model by ML %%%%%%%%%%%%%%%%%%%%% [numcases numdims numbatches]=size(batchdata); count_int = zeros(numdims,1); for batch=1:numbatches xx = sum(batchdata(:,:,batch)); count_int = count_int + xx'; end lp=5; p_int = (count_int+lp*numbatches)/(numcases*numbatches+lp*numbatches); log_base_rate = log( p_int) - log(1-p_int);
blockMiss = function(n){ # n = length of song nsections = sqrt(n) # quick way to determine number of sections in the song mix = c(0.3,0.4,0.2,0.1) # mixture probabilities of difficulty of a section: Easy, Medium ,Hard, Very Hard missprop = c(0.01,0.05,0.25,0.5) # Probability of missing a note for each of the four types of sections sectiontype = sample(1:4,nsections,mix,replace=T) # randomly assign a difficulty to each section with probability from the mix vector sectionsize = rmultinom(1,n,rep(1,nsections))[,1] # randomly allocate section sizes for song using multinomial distribution song = numeric(n) notes = 0 for(i in 1:nsections){ song[(notes+1):(notes + sectionsize[i])] = rbinom(sectionsize[i],1,missprop[sectiontype[i]]) notes = notes + sectionsize[i] } return(song) } x = matrix(0,200,100) for(j in 1:100){ x[,j] = blockMiss(200) } write(t(x),"p.varies_block_n200_r100.txt",ncol=200) # each row in this file is a different simulated song y = matrix(0,600,100) for(j in 1:100){ y[,j] = blockMiss(600) } write(t(y),"p.varies_block_n600_r100.txt",ncol=600) # each row in this file is a different simulated song
/* * File: oref.r * Contents: bang, random, sect, subsc */ "!x - generate successive values from object x." operator{*} ! bang(underef x -> dx) declare { register C_integer i, j; tended union block *ep; struct hgstate state; char ch; } if is:variable(x) && is:string(dx) then { abstract { return new tvsubs(type(x)) } inline { /* * A nonconverted string from a variable is being banged. * Loop through the string suspending one-character substring * trapped variables. */ for (i = 1; i <= StrLen(dx); i++) { suspend tvsubs(&x, i, (word)1); deref(&x, &dx); if (!is:string(dx)) runerr(103, dx); } } } else type_case dx of { integer: { abstract { return integer } inline { C_integer from=1, to; if (!cnv:C_integer(dx, to)) fail; if (to < 1) fail; for ( ; from <= to; from += 1) { suspend C_integer from; } } } list: { abstract { return type(dx).lst_elem } inline { #if E_Lsub word xi = 0; #endif /* E_Lsub */ /* static struct threadstate *curtstate; if (!curtstate) curtstate=&roottstate;*/ EVValD(&dx, E_Lbang); #ifdef Arrays ep = BlkD(dx,List)->listhead; if (BlkType(ep)==T_Realarray){ tended struct b_realarray *ap = ( struct b_realarray * ) ep; word asize = BlkD(dx,List)->size; for (i=0;i<asize;i++){ #if E_Lsub ++xi; EVVal(xi, E_Lsub); #endif /* E_Lsub */ suspend struct_var(&ap->a[i], ap); } } else if ( BlkType(ep)==T_Intarray){ tended struct b_intarray *ap = ( struct b_intarray * ) ep; word asize = BlkD(dx,List)->size; for (i=0;i<asize;i++){ #if E_Lsub ++xi; EVVal(xi, E_Lsub); #endif /* E_Lsub */ suspend struct_var(&ap->a[i], ap); } } else{ #endif /* Arrays */ /* * x is a list. Chain through each list element block and for * each one, suspend with a variable pointing to each * element contained in the block. */ for (ep = BlkD(dx,List)->listhead; BlkType(ep) == T_Lelem; ep = Blk(ep,Lelem)->listnext){ for (i = 0; i < Blk(ep,Lelem)->nused; i++) { j = ep->Lelem.first + i; if (j >= ep->Lelem.nslots) j -= ep->Lelem.nslots; #if E_Lsub ++xi; EVVal(xi, E_Lsub); #endif /* E_Lsub */ suspend struct_var(&ep->Lelem.lslots[j], ep); } } #ifdef Arrays } #endif /* Arrays */ } } file: { abstract { return string } body { FILE *fd; char sbuf[MaxCvtLen]; register char *sptr; register C_integer slen, rlen; word status; #ifdef Dbm datum key; #endif /* Dbm */ #if ConcurrentCOMPILER && defined(Graphics) CURTSTATE(); #endif /* ConcurrentCOMPILER */ /* * x is a file. Read the next line into the string space * and suspend the newly allocated string. */ fd = BlkD(dx,File)->fd.fp; status = BlkLoc(dx)->File.status; if ((status & Fs_Read) == 0) runerr(212, dx); if (status & Fs_Writing) { fseek(fd, 0L, SEEK_CUR); BlkLoc(dx)->File.status &= ~Fs_Writing; } BlkLoc(dx)->File.status |= Fs_Reading; status = BlkLoc(dx)->File.status; #ifdef Messaging if (status & Fs_Messaging) { struct MFile *mf = (struct MFile *)fd; if (!MFIN(mf, READING)) { Mstartreading(mf); } if (strcmp(mf->tp->uri.scheme, "pop") == 0) { char buf[100]; Tprequest_t req = {0, NULL, 0}; unsigned msgnum; long int msglen; req.args = buf; msgnum = 1; for (;;) { snprintf(buf, sizeof(buf), "%d", msgnum); if (mf->resp != NULL) tp_freeresp(mf->tp, mf->resp); req.type = LIST; mf->resp = tp_sendreq(mf->tp, &req); if (mf->resp->sc != 200) fail; if (sscanf(mf->resp->msg, "%*s %*d %ld", &msglen) < 1) runerr(1212, dx); tp_freeresp(mf->tp, mf->resp); Protect(reserve(Strings, msglen), runerr(0)); StrLen(result) = msglen; StrLoc(result) = alcstr(NULL, msglen); req.type = RETR; mf->resp = tp_sendreq(mf->tp, &req); if (mf->resp->sc != 200) runerr(1212, dx); tp_read(mf->tp, StrLoc(result), (size_t)msglen); while (buf[0] != '.') tp_readln(mf->tp, buf, sizeof(buf)); suspend result; msgnum++; } } } #endif /* Messaging */ #ifdef Dbm if (status & Fs_Dbm) { key = dbm_firstkey((DBM *)fd); } #endif /* Dbm */ for (;;) { StrLen(result) = 0; do { #ifdef Graphics pollctr >>= 1; pollctr++; if (status & Fs_Window) { slen = wgetstrg(sbuf,MaxCvtLen,fd); if (slen == -1) runerr(141); else if (slen < -1) runerr(143); } else #endif /* Graphics */ #if HAVE_LIBZ if (status & Fs_Compress) { if (gzeof(fd)) fail; if (gzgets((gzFile)fd,sbuf,MaxCvtLen+1) == Z_NULL) { runerr(214); } slen = strlen(sbuf); if (slen==MaxCvtLen && sbuf[slen-1]!='\n') slen = -2; else if (sbuf[slen-1] == '\n') { sbuf[slen-1] = '\0'; slen--; } } else #endif /* HAVE_LIBZ */ #ifdef ReadDirectory #if !NT || defined(NTGCC) if (status & Fs_Directory) { struct dirent *d; char *s, *p=sbuf; DEC_NARTHREADS; d = readdir((DIR *)fd); INC_NARTHREADS_CONTROLLED; if (d == NULL) fail; s = d->d_name; slen = 0; while(*s && slen++ < MaxCvtLen) *p++ = *s++; if (slen == MaxCvtLen) slen = -2; } else #endif /* !NT */ #endif /* ReadDirectory */ #ifdef Dbm if (status & Fs_Dbm) { DBM *db = (DBM *)fd; datum content; int i; if (key.dptr == NULL) fail; content = dbm_fetch(db, key); if (content.dsize > MaxCvtLen) slen = MaxCvtLen; else slen = content.dsize; for (i = 0; i < slen; i++) sbuf[i] = ((char *)(content.dptr))[i]; key = dbm_nextkey(db); } else #endif /* Dbm */ if ((slen = getstrg(sbuf,MaxCvtLen,BlkD(dx,File))) == -1) fail; rlen = slen < 0 ? (word)MaxCvtLen : slen; Protect(reserve(Strings, rlen), runerr(0)); #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ if (!InRange(strbase,StrLoc(result),strfree)) { Protect(reserve(Strings, StrLen(result)+rlen), runerr(0)); Protect((StrLoc(result) = alcstr(StrLoc(result), StrLen(result))), runerr(0)); } Protect(sptr = alcstr(sbuf,rlen), runerr(0)); if (StrLen(result) == 0) StrLoc(result) = sptr; StrLen(result) += rlen; } while (slen < 0); suspend result; } } } table: { abstract { return type(dx).tbl_val } inline { struct b_tvtbl *tp; EVValD(&dx, E_Tbang); /* * x is a table. Chain down the element list in each bucket * and suspend a variable pointing to each element in turn. */ for (ep = hgfirst(BlkLoc(dx), &state); ep != 0; ep = hgnext(BlkLoc(dx), &state, ep)) { EVValD(&(Blk(ep,Telem)->tval), E_Tval); Protect(tp = alctvtbl(&dx, &ep->Telem.tref, ep->Telem.hashnum), runerr(0)); suspend tvtbl(tp); } } } set: { abstract { return store[type(dx).set_elem] } inline { EVValD(&dx, E_Sbang); /* * This is similar to the method for tables except that a * value is returned instead of a variable. */ for (ep = hgfirst(BlkLoc(dx), &state); ep != 0; ep = hgnext(BlkLoc(dx), &state, ep)) { EVValD(&(ep->Selem.setmem), E_Sval); suspend ep->Selem.setmem; } } } record: { abstract { return type(dx).all_fields } inline { /* * x is a record. Loop through the fields and suspend * a variable pointing to each one. */ EVValD(&dx, E_Rbang); j = Blk(BlkD(dx,Record)->recdesc,Proc)->nfields; for (i = 0; i < j; i++) { EVVal(i+1, E_Rsub); suspend struct_var(&BlkLoc(dx)->Record.fields[i], BlkD(dx, Record)); } } } default: if cnv:tmp_string(dx) then { abstract { return string } inline { /* * A (converted or non-variable) string is being banged. * Loop through the string suspending simple one character * substrings. */ for (i = 1; i <= StrLen(dx); i++) { ch = *(StrLoc(dx) + i - 1); suspend string(1, (char *)&allchars[FromAscii(ch) & 0xFF]); } } } else runerr(116, dx); } inline { fail; } end #define RandVal (RanScale*(k_random=(RandA*k_random+RandC)&0x7FFFFFFFL)) "?x - produce a randomly selected element of x." operator{0,1} ? random(underef x -> dx) #ifndef LargeInts declare { C_integer v = 0; } #endif /* LargeInts */ if is:variable(x) && is:string(dx) then { abstract { return new tvsubs(type(x)) } body { C_integer val; double rval; #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ /* * A string from a variable is being banged. Produce a one * character substring trapped variable. */ if ((val = StrLen(dx)) <= 0) fail; rval = RandVal; /* This form is used to get around */ rval *= val; /* a bug in a certain C compiler */ return tvsubs(&x, (word)rval + 1, (word)1); } } else type_case dx of { string: { /* * x is a string, but it is not a variable. Produce a * random character in it as the result; a substring * trapped variable is not needed. */ abstract { return string } body { C_integer val; double rval; #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ if ((val = StrLen(dx)) <= 0) fail; rval = RandVal; rval *= val; return string(1, StrLoc(dx)+(word)rval); } } cset: { /* * x is a cset. Convert it to a string, select a random character * of that string and return it. A substring trapped variable is * not needed. */ if !cnv:tmp_string(dx) then { /* cannot fail */ } abstract { return string } body { C_integer val; double rval; char ch; #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ if ((val = StrLen(dx)) <= 0) fail; rval = RandVal; rval *= val; ch = *(StrLoc(dx) + (word)rval); return string(1, (char *)&allchars[FromAscii(ch) & 0xFF]); } } list: { abstract { return type(dx).lst_elem } /* * x is a list. Set i to a random number in the range [1,*x], * failing if the list is empty. */ body { C_integer val; double rval; register C_integer i, j; union block *bp; /* doesn't need to be tended */ #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ val = BlkD(dx,List)->size; if (val <= 0) fail; rval = RandVal; rval *= val; i = (word)rval + 1; EVValD(&dx, E_Lrand); EVVal(i, E_Lsub); bp = BlkD(dx,List)->listhead; #ifdef Arrays if (BlkD(dx,List)->listtail!=NULL){ #endif /* Arrays */ j = 1; /* * Work down chain list of list blocks and find the block that * contains the selected element. */ while (i >= j + Blk(bp,Lelem)->nused) { j += Blk(bp,Lelem)->nused; bp = Blk(bp,Lelem)->listnext; if (BlkType(bp) == T_List) syserr("list reference out of bounds in random"); } /* * Locate the appropriate element and return a variable * that points to it. */ i += Blk(bp,Lelem)->first - j; if (i >= bp->Lelem.nslots) i -= bp->Lelem.nslots; return struct_var(&(bp->Lelem.lslots[i]), bp); #ifdef Arrays } else if (BlkType(bp)==T_Realarray) return struct_var(&((struct b_realarray *)(bp))->a[i-1], bp); else /* if (Blk(bp, Intarray)->title==T_Intarray) assumed to be int array*/ return struct_var(&((struct b_intarray *)(bp))->a[i-1], bp); #endif /* Arrays */ } } table: { abstract { return type(dx).tbl_val } /* * x is a table. Set n to a random number in the range [1,*x], * failing if the table is empty. */ body { C_integer val; double rval; register C_integer i, j, n; union block *ep, *bp; /* doesn't need to be tended */ struct b_slots *seg; struct b_tvtbl *tp; #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ bp = BlkLoc(dx); val = Blk(bp,Table)->size; if (val <= 0) fail; rval = RandVal; rval *= val; n = (word)rval + 1; EVValD(&dx, E_Trand); EVVal(n, E_Tsub); /* * Walk down the hash chains to find and return the nth element * as a variable. */ for (i=0; i < HSegs && (seg = Blk(bp,Table)->hdir[i])!=NULL;i++) for (j = segsize[i] - 1; j >= 0; j--) for (ep = seg->hslots[j]; BlkType(ep) == T_Telem; ep = Blk(ep,Telem)->clink) if (--n <= 0) { Protect(tp = alctvtbl(&dx, &(ep->Telem.tref), (ep->Telem.hashnum)), runerr(0)); return tvtbl(tp); } syserr("table reference out of bounds in random"); } } set: { abstract { return store[type(dx).set_elem] } /* * x is a set. Set n to a random number in the range [1,*x], * failing if the set is empty. */ body { C_integer val; double rval; register C_integer i, j, n; union block *bp, *ep; /* doesn't need to be tended */ struct b_slots *seg; #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ bp = BlkLoc(dx); val = Blk(bp,Set)->size; if (val <= 0) fail; rval = RandVal; rval *= val; n = (word)rval + 1; EVValD(&dx, E_Srand); /* * Walk down the hash chains to find and return the nth element. */ for (i=0; i < HSegs && (seg = Blk(bp,Table)->hdir[i]) != NULL; i++) for (j = segsize[i] - 1; j >= 0; j--) for (ep = seg->hslots[j]; ep != NULL; ep = Blk(ep,Telem)->clink) if (--n <= 0) { EVValD(&(ep->Selem.setmem), E_Selem); return Blk(ep,Selem)->setmem; } syserr("set reference out of bounds in random"); } } record: { abstract { return type(dx).all_fields } /* * x is a record. Set val to a random number in the range * [1,*x] (*x is the number of fields), failing if the * record has no fields. */ body { C_integer val; double rval; struct b_record *rec; /* doesn't need to be tended */ #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ rec = BlkD(dx, Record); val = Blk(rec->recdesc,Proc)->nfields; if (val <= 0) fail; /* * Locate the selected element and return a variable * that points to it */ rval = RandVal; rval *= val; EVValD(&dx, E_Rrand); EVVal(rval + 1, E_Rsub); return struct_var(&rec->fields[(word)rval], rec); } } default: { #ifdef LargeInts if !cnv:integer(dx) then runerr(113, dx) #else /* LargeInts */ if !cnv:C_integer(dx,v) then runerr(113, dx) #endif /* LargeInts */ abstract { return integer ++ real } body { double rval; #ifdef LargeInts C_integer v; if (Type(dx) == T_Lrgint) { if (bigrand(&dx, &result) == RunError) /* alcbignum failed */ runerr(0); return result; } v = IntVal(dx); #endif /* LargeInts */ #if ConcurrentCOMPILER CURTSTATE(); #endif /* ConcurrentCOMPILER */ /* * x is an integer, be sure that it's non-negative. */ if (v < 0) runerr(205, dx); /* * val contains the integer value of x. If val is 0, return * a real in the range [0,1), else return an integer in the * range [1,val]. */ if (v == 0) { rval = RandVal; return C_double rval; } else { rval = RandVal; rval *= v; return C_integer (long)rval + 1; } } } } end "x[i:j] - form a substring or list section of x." operator{0,1} [:] sect(underef x -> dx, i, j) declare { int use_trap = 0; } if is:list(dx) then { abstract { return type(dx) } /* * If it isn't a C integer, but is a large integer, fail on * the out-of-range index. */ if !cnv:C_integer(i) then { if cnv : integer(i) then inline { fail; } runerr(101, i) } if !cnv:C_integer(j) then { if cnv : integer(j) then inline { fail; } runerr(101, j) } body { C_integer t; i = cvpos((long)i, (long)BlkD(dx,List)->size); if (i == CvtFail) fail; j = cvpos((long)j, (long)BlkD(dx,List)->size); if (j == CvtFail) fail; if (i > j) { t = i; i = j; j = t; } #ifdef Arrays if (BlkD(dx,List)->listtail!=NULL){ #endif /* Arrays */ if (cplist(&dx, &result, i, j) == RunError) runerr(0); #ifdef Arrays } else if ( BlkType(BlkD(dx,List)->listhead)==T_Realarray){ if (cprealarray(&dx, &result, i, j) == RunError) runerr(0); } else /*if ( BlkType(BlkD(dx,List)->listhead)==T_Intarray)*/{ if (cpintarray(&dx, &result, i, j) == RunError) runerr(0); } #endif /* Arrays */ return result; } } else { /* * x should be a string. If x is a variable, we must create a * substring trapped variable. */ if is:variable(x) && is:string(dx) then { abstract { return new tvsubs(type(x)) } inline { use_trap = 1; } } else if cnv:string(dx) then abstract { return string } else runerr(110, dx) /* * If it isn't a C integer, but is a large integer, fail on * the out-of-range index. */ if !cnv:C_integer(i) then { if cnv : integer(i) then inline { fail; } runerr(101, i) } if !cnv:C_integer(j) then { if cnv : integer(j) then inline { fail; } runerr(101, j) } body { C_integer t; i = cvpos((long)i, (long)StrLen(dx)); if (i == CvtFail) fail; j = cvpos((long)j, (long)StrLen(dx)); if (j == CvtFail) fail; if (i > j) { /* convert section to substring */ t = i; i = j; j = t - j; } else j = j - i; if (use_trap) { return tvsubs(&x, i, j); } else return string(j, StrLoc(dx)+i-1); } } end "x[y] - access yth character or element of x." operator{0,1} [] subsc(underef x -> dx,y) declare { int use_trap = 0; } type_case dx of { file: { abstract { return string ++ integer /* bug: this value is for messaging */ } body { int status = BlkD(dx,File)->status; #ifdef Dbm if (status & Fs_Dbm) { struct b_tvtbl *tp; EVValD(&dx, E_Tref); EVValD(&y, E_Tsub); Protect(tp = alctvtbl(&dx, &y, 0), runerr(0)); return tvtbl(tp); } else #endif /* Dbm */ #ifdef Messaging if (status & Fs_Messaging) { tended char *c_y; long int msglen; struct MFile *mf = BlkD(dx,File)->fd.mf; if (!cnv:C_string(y, c_y)) { runerr(103, y); } if ((mf->resp == NULL) && !MFIN(mf, READING)){ Mstartreading(mf); } if (mf->resp == NULL) { fail; } if (strcmp(c_y, "Status-Code") == 0 || strcmp(c_y, "code") == 0) { return C_integer mf->resp->sc; } else if (strcmp(c_y, "Reason-Phrase") == 0 || strcmp(c_y, "message") == 0) { if (mf->resp->msg != NULL && (msglen = strlen(mf->resp->msg)) > 0) { /* * we could just return string(strlen(mf->resp->msg), mf->resp->msg) * but mf->resp->msg could be gone by the time the result is accessed * if the user called close() so, just allocate a string and return it. */ StrLen(result) = msglen; StrLoc(result) = alcstr(mf->resp->msg, msglen); return result; } else { fail; } } else if (c_y[0] >= '0' && c_y[0] <= '9' && strcmp(mf->tp->uri.scheme, "pop") == 0) { Tprequest_t req = { LIST, NULL, 0 }; char buf[100]; buf[0]='\0'; req.args = c_y; tp_freeresp(mf->tp, mf->resp); mf->resp = tp_sendreq(mf->tp, &req); if (mf->resp->sc != 200) { fail; } if (sscanf(mf->resp->msg, "%*s %*d %ld", &msglen) < 1) { runerr(1212, dx); } tp_freeresp(mf->tp, mf->resp); Protect(reserve(Strings, msglen), runerr(0)); StrLen(result) = msglen; StrLoc(result) = alcstr(NULL, msglen); req.type = RETR; mf->resp = tp_sendreq(mf->tp, &req); if (mf->resp->sc != 200) { runerr(1212, dx); } tp_read(mf->tp, StrLoc(result), (size_t)msglen); while (buf[0] != '.') { tp_readln(mf->tp, buf, sizeof(buf)); } return result; } else { char *val = tp_headerfield(mf->resp->header, c_y); char *end; tended char *tmp; if (val == NULL) { fail; } if (((end = strchr(val, '\r')) != NULL) || ((end = strchr(val, '\n')) != NULL)) { Protect(tmp = alcstr(val, end-val), runerr(0)); return string(end-val, tmp); } else { Protect(tmp = alcstr(val, strlen(val)), runerr(0)); return string(strlen(val), tmp); } } } else #endif /* Messaging */ runerr(114,dx); } } list: { abstract { return type(dx).lst_elem } /* * Make sure that y is a C integer. */ if !cnv:C_integer(y) then { /* * If it isn't a C integer, but is a large integer, * fail on the out-of-range index. */ if cnv : integer(y) then inline { fail; } runerr(101, y) } body { word i, j; register union block *bp; /* doesn't need to be tended */ struct b_list *lp; /* doesn't need to be tended */ EVValD(&dx, E_Lref); EVVal(y, E_Lsub); /* * Make sure that subscript y is in range. */ lp = BlkD(dx, List); MUTEX_LOCKBLK_CONTROLLED(lp, "x[y]: lock list"); i = cvpos((long)y, (long)lp->size); if (i == CvtFail || i > lp->size){ MUTEX_UNLOCKBLK(lp, "x[y]: unlock list"); fail; } /* * Locate the list-element block containing the * desired element. */ bp = lp->listhead; #ifdef Arrays if (lp->listtail!=NULL){ #endif /* Arrays */ /* * y is in range, so bp can never be null here. if it was, a memory * violation would occur in the code that follows, anyhow, so * exiting the loop on a NULL bp makes no sense. */ j = 1; while (i >= j + Blk(bp,Lelem)->nused) { j += bp->Lelem.nused; bp = bp->Lelem.listnext; } /* * Locate the desired element and return a pointer to it. */ i += bp->Lelem.first - j; if (i >= bp->Lelem.nslots) i -= bp->Lelem.nslots; MUTEX_UNLOCKBLK(BlkD(dx,List), "x[y]: unlock list"); return struct_var(&bp->Lelem.lslots[i], bp); #ifdef Arrays } else if (BlkType(bp)==T_Realarray) return struct_var(&((struct b_realarray *)(bp))->a[i-1], bp); else { /* if (BlkType(bp)==T_Intarray) assumed to be int array*/ return struct_var(&((struct b_intarray *)(bp))->a[i-1], bp); } #endif /* Arrays */ } } table: { abstract { store[type(dx).tbl_key] = type(y) /* the key might be added */ return type(dx).tbl_val ++ new tvtbl(type(dx)) } /* * x is a table. Return a table element trapped variable * representing the result; defer actual lookup until later. */ body { uword hn; struct b_tvtbl *tp; EVValD(&dx, E_Tref); EVValD(&y, E_Tsub); hn = hash(&y); EVVal(hn, E_HashNum); Protect(tp = alctvtbl(&dx, &y, hn), runerr(0)); return tvtbl(tp); } } record: { abstract { return type(dx).all_fields } /* * x is a record. Convert y to an integer and be sure that it * it is in range as a field number. */ if !cnv:C_integer(y) then body { if (!cnv:tmp_string(y,y)) runerr(101,y); else { register union block *bp; /* doesn't need to be tended */ register union block *bp2; /* doesn't need to be tended */ register word i; register int len; char *loc; int nf; bp = BlkLoc(dx); bp2 = BlkD(dx,Record)->recdesc; nf = Blk(bp2,Proc)->nfields; loc = StrLoc(y); len = StrLen(y); for(i=0; i<nf; i++) { if (len == StrLen(Blk(bp2,Proc)->lnames[i]) && !strncmp(loc, StrLoc(Blk(bp2,Proc)->lnames[i]), len)) { EVValD(&dx, E_Rref); EVVal(i+1, E_Rsub); /* * Found the field, return a pointer to it. */ return struct_var(&(Blk(bp,Record)->fields[i]), bp); } } fail; } } else body { word i; register union block *bp; /* doesn't need to be tended */ union block *rd; bp = BlkLoc(dx); rd = Blk(bp,Record)->recdesc; /* * check if the record is an object, if yes, add 2 to the subscript */ if (Blk(rd,Proc)->ndynam == -3) { i = cvpos(y, (word)(Blk(rd,Proc)->nfields-2)); i += 2; } else { i = cvpos(y, (word)(Blk(rd,Proc)->nfields)); } if (i == CvtFail || i > Blk(Blk(bp,Record)->recdesc,Proc)->nfields) fail; EVValD(&dx, E_Rref); EVVal(i, E_Rsub); /* * Locate the appropriate field and return a pointer to it. */ return struct_var(&Blk(bp,Record)->fields[i-1], bp); } } default: { /* * dx must either be a string or be convertible to one. Decide * whether a substring trapped variable can be created. */ if is:variable(x) && is:string(dx) then { abstract { return new tvsubs(type(x)) } inline { use_trap = 1; } } else if cnv:tmp_string(dx) then abstract { return string } else runerr(114, dx) /* * Make sure that y is a C integer. */ if !cnv:C_integer(y) then { /* * If it isn't a C integer, but is a large integer, fail on * the out-of-range index. */ if cnv : integer(y) then inline { fail; } runerr(101, y) } body { char ch; word i; /* * Convert y to a position in x and fail if the position * is out of bounds. */ i = cvpos(y, StrLen(dx)); if (i == CvtFail || i > StrLen(dx)) fail; if (use_trap) { /* * x is a string, make a substring trapped variable for the * one character substring selected and return it. */ return tvsubs(&x, i, (word)1); } else { /* * x was converted to a string, so it cannot be assigned * back into. Just return a string containing the selected * character. */ ch = *(StrLoc(dx)+i-1); return string(1, (char *)&allchars[FromAscii(ch) & 0xFF]); } } } } end
module Test.TestFixed import Test.TestUtil import Data.Time.Clock.Internal.Fixed getDec : Integer -> Dec getDec x = MkFixed x getPico : Integer -> Pico getPico x = MkFixed x export testAdd: IO () testAdd = do let a = getPico 1 let b = getPico 1 assertEq "testAdd" (a + b) 2 "" export testSub: IO () testSub = do let a = getPico 5 let b = getPico 3 assertEq "testSub" (a - b) 2 "" export testNegate: IO () testNegate = do let a = negate $ getPico 5 assertEq "testNegate" a (-5) (show a) export testMultFixed: IO () testMultFixed = do let a = getDec 123 let b = getDec 25 let result = a * b assertEq "testMultFixed" result 30 (show result) export testFracDiv: IO () testFracDiv = do let a = getDec 3456 let b = getDec 1234 let result = a / b assertEq "testMultFixed" result 280 (show result) export testRecip: IO () testRecip = do let a = getDec 3456 let result = recip a assertEq "testRecip" result 2 (show result)
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.mv_polynomial.rename import data.mv_polynomial.variables /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by { ext1 i, simp } variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, algebra_map_eq] @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext : 2; simp } @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := ring_hom.ext $ bind₂_C_right _ @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := ring_hom.ext $ join₂_map _ lemma aeval_id_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, function.comp.left_id] @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext : 2; simp } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ lemma rename_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ (λ i, rename g $ f i) := by { ext1 i, simp } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_comp_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by { ext1 i, simp } lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext : 2; simp } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((↑(aeval f : _ →ₐ[S] _) : _ →+* _).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] section open_locale classical lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h instance monad : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance is_lawful_functor : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance is_lawful_monad : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
[STATEMENT] lemma closed_components: "\<lbrakk>closed s; c \<in> components s\<rbrakk> \<Longrightarrow> closed c" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>closed s; c \<in> components s\<rbrakk> \<Longrightarrow> closed c [PROOF STEP] by (metis closed_connected_component components_iff)
(*<*) theory Formula imports Event_Data Regex "MFOTL_Monitor_Devel.Interval" "MFOTL_Monitor_Devel.Trace" "MFOTL_Monitor_Devel.Abstract_Monitor" "HOL-Library.Mapping" Containers.Set_Impl begin (*>*) section \<open>Metric first-order dynamic logic\<close> subsection \<open> Instantiations \<close> derive (eq) ceq enat instantiation enat :: ccompare begin definition ccompare_enat :: "enat comparator option" where "ccompare_enat = Some (\<lambda>x y. if x = y then order.Eq else if x < y then order.Lt else order.Gt)" instance by intro_classes (auto simp: ccompare_enat_def split: if_splits intro!: comparator.intro) end instantiation enat :: card_UNIV begin definition "finite_UNIV = Phantom(enat) False" definition "card_UNIV = Phantom(enat) 0" instance by intro_classes (simp_all add: finite_UNIV_enat_def card_UNIV_enat_def infinite_UNIV_char_0) end datatype rec_safety = Unused | PastRec | NonFutuRec | AnyRec instantiation rec_safety :: "{finite, bounded_semilattice_sup_bot, monoid_mult, mult_zero}" begin fun less_eq_rec_safety where "Unused \<le> _ = True" | "PastRec \<le> PastRec = True" | "PastRec \<le> NonFutuRec = True" | "PastRec \<le> AnyRec = True" | "NonFutuRec \<le> NonFutuRec = True" | "NonFutuRec \<le> AnyRec = True" | "AnyRec \<le> AnyRec = True" | "(_::rec_safety) \<le> _ = False" definition "(x::rec_safety) < y \<longleftrightarrow> x \<le> y \<and> x \<noteq> y" definition [code_unfold]: "\<bottom> = Unused" fun sup_rec_safety where "AnyRec \<squnion> _ = AnyRec" | "_ \<squnion> AnyRec = AnyRec" | "NonFutuRec \<squnion> _ = NonFutuRec" | "_ \<squnion> NonFutuRec = NonFutuRec" | "PastRec \<squnion> _ = PastRec" | "_ \<squnion> PastRec = PastRec" | "Unused \<squnion> Unused = Unused" definition [code_unfold]: "0 = Unused" definition [code_unfold]: "1 = NonFutuRec" fun times_rec_safety where "Unused * _ = Unused" | "_ * Unused = Unused" | "AnyRec * _ = AnyRec" | "_ * AnyRec = AnyRec" | "PastRec * _ = PastRec" | "_ * PastRec = PastRec" | "NonFutuRec * NonFutuRec = NonFutuRec" instance proof fix x y z :: rec_safety have "x \<in> {Unused, PastRec, NonFutuRec, AnyRec}" for x by (cases x) simp_all then have UNIV_alt: "UNIV = \<dots>" by blast show "finite (UNIV :: rec_safety set)" unfolding UNIV_alt by blast show "(x < y) = (x \<le> y \<and> \<not> y \<le> x)" unfolding less_rec_safety_def by (cases x; cases y) simp_all show "x \<le> x" by (cases x) simp_all show "x \<le> y \<Longrightarrow> y \<le> z \<Longrightarrow> x \<le> z" by (cases x; cases y; cases z) simp_all show "x \<le> y \<Longrightarrow> y \<le> x \<Longrightarrow> x = y" by (cases x; cases y) simp_all show "x \<le> x \<squnion> y" by (cases x; cases y) simp_all show "y \<le> x \<squnion> y" by (cases x; cases y) simp_all show "y \<le> x \<Longrightarrow> z \<le> x \<Longrightarrow> y \<squnion> z \<le> x" by (cases x; cases y; cases z) simp_all show "\<bottom> \<le> x" unfolding bot_rec_safety_def by (cases x) simp_all show "(x * y) * z = x * (y * z)" by (cases x; cases y; cases z) simp_all show "1 * x = x" unfolding one_rec_safety_def by (cases x) simp_all show "x * 1 = x" unfolding one_rec_safety_def by (cases x) simp_all show "0 * x = 0" unfolding zero_rec_safety_def by simp show "x * 0 = 0" unfolding zero_rec_safety_def by (cases x) simp_all qed end instantiation rec_safety :: Sup begin definition "\<Squnion> A = Finite_Set.fold (\<squnion>) Unused A" instance .. end lemma (in semilattice_sup) comp_fun_idem_on_sup: "comp_fun_idem_on UNIV sup" using comp_fun_idem_sup by (simp add: comp_fun_idem_def') lemma Sup_rec_safety_empty[simp]: "\<Squnion> {} = Unused" by (simp add: Sup_rec_safety_def) lemma Sup_rec_safety_insert[simp]: "\<Squnion>(insert (x::rec_safety) A) = x \<squnion> \<Squnion>A" by (simp add: Sup_rec_safety_def comp_fun_idem_on.fold_insert_idem[OF comp_fun_idem_on_sup]) lemma Sup_rec_safety_union: "\<Squnion>((A::rec_safety set) \<union> B) = \<Squnion>A \<squnion> \<Squnion>B" unfolding Sup_rec_safety_def using finite[of A] by (induction A rule: finite_induct) (simp_all flip: bot_rec_safety_def add: comp_fun_idem_on.fold_insert_idem[OF comp_fun_idem_on_sup] sup_assoc) context begin subsection \<open>Syntax and semantics\<close> qualified type_synonym name = string8 qualified type_synonym event = "(name \<times> event_data list)" qualified type_synonym database = "event set" qualified type_synonym prefix = "database prefix" qualified type_synonym trace = "database trace" qualified type_synonym env = "event_data list" subsubsection \<open>Terms\<close> qualified datatype trm = is_Var: Var nat | is_Const: Const event_data | Plus trm trm | Minus trm trm | UMinus trm | Mult trm trm | Div trm trm | Mod trm trm | F2i trm | I2f trm lemma trm_exhaust: "(\<And>x. t = Var x \<Longrightarrow> P (Var x)) \<Longrightarrow> (\<And>a. t = Const a \<Longrightarrow> P (Const a)) \<Longrightarrow> (\<And>t1 t2. t = Plus t1 t2 \<Longrightarrow> P (Plus t1 t2)) \<Longrightarrow> (\<And>t1 t2. t = Minus t1 t2 \<Longrightarrow> P (Minus t1 t2)) \<Longrightarrow> (\<And>t1. t = UMinus t1 \<Longrightarrow> P (UMinus t1)) \<Longrightarrow> (\<And>t1 t2. t = Mult t1 t2 \<Longrightarrow> P (Mult t1 t2)) \<Longrightarrow> (\<And>t1 t2. t = Div t1 t2 \<Longrightarrow> P (Div t1 t2)) \<Longrightarrow> (\<And>t1 t2. t = Mod t1 t2 \<Longrightarrow> P (Mod t1 t2)) \<Longrightarrow> (\<And>t1. t = F2i t1 \<Longrightarrow> P (F2i t1)) \<Longrightarrow> (\<And>t1. t = I2f t1 \<Longrightarrow> P (I2f t1)) \<Longrightarrow> P t" by (cases t, simp_all) text \<open> In this implementation of MFODL, to use De Bruijn indices, binding operators increase the value of the bounding number @{term b} (that starts at $0$) and this number is subtracted from all free variables (type @{typ nat}) greater than @{term b}. For instance, the free variable of $\exists.\ P\, (Var 0) \land Q\, (Var 1)$ is @{term "Var 0"} because the existential makes $b=1$ and this value is subtracted from $Q$s argument while that of $P$ is not even taken into account. \<close> qualified primrec fvi_trm :: "nat \<Rightarrow> trm \<Rightarrow> nat set" where "fvi_trm b (Var x) = (if b \<le> x then {x - b} else {})" | "fvi_trm b (Const _) = {}" | "fvi_trm b (Plus x y) = fvi_trm b x \<union> fvi_trm b y" | "fvi_trm b (Minus x y) = fvi_trm b x \<union> fvi_trm b y" | "fvi_trm b (UMinus x) = fvi_trm b x" | "fvi_trm b (Mult x y) = fvi_trm b x \<union> fvi_trm b y" | "fvi_trm b (Div x y) = fvi_trm b x \<union> fvi_trm b y" | "fvi_trm b (Mod x y) = fvi_trm b x \<union> fvi_trm b y" | "fvi_trm b (F2i x) = fvi_trm b x" | "fvi_trm b (I2f x) = fvi_trm b x" abbreviation "fv_trm \<equiv> fvi_trm 0" qualified primrec eval_trm :: "env \<Rightarrow> trm \<Rightarrow> event_data" where "eval_trm v (Var x) = v ! x" | "eval_trm v (Const x) = x" | "eval_trm v (Plus x y) = eval_trm v x + eval_trm v y" | "eval_trm v (Minus x y) = eval_trm v x - eval_trm v y" | "eval_trm v (UMinus x) = - eval_trm v x" | "eval_trm v (Mult x y) = eval_trm v x * eval_trm v y" | "eval_trm v (Div x y) = eval_trm v x div eval_trm v y" | "eval_trm v (Mod x y) = eval_trm v x mod eval_trm v y" | "eval_trm v (F2i x) = EInt (integer_of_event_data (eval_trm v x))" | "eval_trm v (I2f x) = EFloat (double_of_event_data (eval_trm v x))" lemma eval_trm_fv_cong: "\<forall>x\<in>fv_trm t. v ! x = v' ! x \<Longrightarrow> eval_trm v t = eval_trm v' t" by (induction t) simp_all subsubsection \<open>Formulas\<close> text \<open> Aggregation operators @{term "Agg nat agg_op nat trm formula"} are special formulas with five parameters: \begin{itemize} \item Variable @{term "y::nat"} that saves the value of the aggregation operation. \item Type of aggregation (sum, avg, min, max, ...). \item Binding number @{term "b::nat"} for many variables in the next two arguments. \item Term @{term "t::trm"} that represents an operation to be aggregated. \item Formula @{term "\<phi>"} that restricts the domain where the aggregation takes place. \end{itemize} \<close> datatype ty = TInt | TFloat | TString qualified datatype agg_type = Agg_Cnt | Agg_Min | Agg_Max | Agg_Sum | Agg_Avg | Agg_Med qualified type_synonym 't agg_op = "agg_type \<times> 't" definition flatten_multiset :: "(event_data \<times> enat) set \<Rightarrow> event_data list" where "flatten_multiset M = concat (map (\<lambda>(x, c). replicate (the_enat c) x) (csorted_list_of_set M))" definition finite_multiset :: "(event_data \<times> enat) set \<Rightarrow> bool" where "finite_multiset M = (finite M \<and> \<not>(\<exists>s. (s,\<infinity>) \<in> M ))" definition aggreg_default_value :: "agg_type \<Rightarrow> ty \<Rightarrow> event_data" where "aggreg_default_value op t = (case (op, t) of (Agg_Min, TFloat) \<Rightarrow> EFloat Code_Double.infinity | (Agg_Max, TFloat) \<Rightarrow> EFloat (-Code_Double.infinity) | (_, TFloat) \<Rightarrow> EFloat 0 | (_, TInt) \<Rightarrow> EInt 0 | (_, TString) \<Rightarrow> EString empty_string)" fun eval_agg_op :: "ty agg_op \<Rightarrow> (event_data \<times> enat) set \<Rightarrow> event_data" where "eval_agg_op (Agg_Cnt, ty) M = (let y0 = aggreg_default_value Agg_Cnt ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (xs,_) \<Rightarrow> EInt (integer_of_int (length xs)))" | "eval_agg_op (Agg_Min, ty) M = (let y0 = aggreg_default_value Agg_Min ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (x # xs,_) \<Rightarrow> foldl min x xs)" | "eval_agg_op (Agg_Max, ty) M = (let y0 = aggreg_default_value Agg_Max ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (x # xs,_) \<Rightarrow> foldl max x xs)" | "eval_agg_op (agg_type.Agg_Sum, ty) M = (let y0 = aggreg_default_value Agg_Sum ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (x # xs,_) \<Rightarrow> foldl (+) x xs)" | "eval_agg_op (Agg_Avg, ty) M =(let y0 = aggreg_default_value Agg_Avg ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (x#xs,_) \<Rightarrow> EFloat ( double_of_event_data_agg (foldl plus x xs) / double_of_int (length (x#xs))))" | "eval_agg_op (Agg_Med, ty) M =(let y0 = aggreg_default_value Agg_Med ty in case (flatten_multiset M, finite_multiset M) of (_, False) \<Rightarrow> y0 | ([],_) \<Rightarrow> y0 | (xs,_) \<Rightarrow> EFloat (let u = length xs; u' = u div 2 in if even u then (double_of_event_data_agg (xs ! (u'-1)) + double_of_event_data_agg (xs ! u')) / double_of_int 2 else double_of_event_data_agg (xs ! u')))" qualified datatype (discs_sels) 't formula = Pred name "trm list" | Let name "'t formula" "'t formula" | LetPast name "'t formula" "'t formula" | Eq trm trm | Less trm trm | LessEq trm trm | Neg "'t formula" | Or "'t formula" "'t formula" | And "'t formula" "'t formula" | Ands "'t formula list" | Exists 't "'t formula" | Agg nat "'t agg_op" "'t list" trm "'t formula" | Prev \<I> "'t formula" | Next \<I> "'t formula" | Since "'t formula" \<I> "'t formula" | Until "'t formula" \<I> "'t formula" | MatchF \<I> "'t formula Regex.regex" | MatchP \<I> "'t formula Regex.regex" | TP trm | TS trm qualified definition "FF = Eq (Const (EInt 0)) (Const (EInt 1))" qualified definition "TT \<equiv> Eq (Const (EInt 0)) (Const (EInt 0))" qualified fun fvi :: "nat \<Rightarrow> 't formula \<Rightarrow> nat set" where "fvi b (Pred r ts) = (\<Union>t\<in>set ts. fvi_trm b t)" | "fvi b (Let p \<phi> \<psi>) = fvi b \<psi>" | "fvi b (LetPast p \<phi> \<psi>) = fvi b \<psi>" | "fvi b (Eq t1 t2) = fvi_trm b t1 \<union> fvi_trm b t2" | "fvi b (Less t1 t2) = fvi_trm b t1 \<union> fvi_trm b t2" | "fvi b (LessEq t1 t2) = fvi_trm b t1 \<union> fvi_trm b t2" | "fvi b (Neg \<phi>) = fvi b \<phi>" | "fvi b (Or \<phi> \<psi>) = fvi b \<phi> \<union> fvi b \<psi>" | "fvi b (And \<phi> \<psi>) = fvi b \<phi> \<union> fvi b \<psi>" | "fvi b (Ands \<phi>s) = (let xs = map (fvi b) \<phi>s in \<Union>x\<in>set xs. x)" | "fvi b (Exists t \<phi>) = fvi (Suc b) \<phi>" | "fvi b (Agg y \<omega> tys f \<phi>) = fvi (b + length tys) \<phi> \<union> fvi_trm (b + length tys) f \<union> (if b \<le> y then {y - b} else {})" | "fvi b (Prev I \<phi>) = fvi b \<phi>" | "fvi b (Next I \<phi>) = fvi b \<phi>" | "fvi b (Since \<phi> I \<psi>) = fvi b \<phi> \<union> fvi b \<psi>" | "fvi b (Until \<phi> I \<psi>) = fvi b \<phi> \<union> fvi b \<psi>" | "fvi b (MatchF I r) = Regex.fv_regex (fvi b) r" | "fvi b (MatchP I r) = Regex.fv_regex (fvi b) r" | "fvi b (TP t) = fvi_trm b t" | "fvi b (TS t) = fvi_trm b t" abbreviation "fv \<equiv> fvi 0" abbreviation "fv_regex \<equiv> Regex.fv_regex fv" lemma fv_abbrevs[simp]: "fv TT = {}" "fv FF = {}" unfolding TT_def FF_def by auto lemma fv_subset_Ands: "\<phi> \<in> set \<phi>s \<Longrightarrow> fv \<phi> \<subseteq> fv (Ands \<phi>s)" by auto lemma finite_fvi_trm[simp]: "finite (fvi_trm b t)" by (induction t) simp_all lemma finite_fvi[simp]: "finite (fvi b \<phi>)" by (induction \<phi> arbitrary: b) simp_all lemma fvi_trm_plus: "x \<in> fvi_trm (b + c) t \<longleftrightarrow> x + c \<in> fvi_trm b t" by (induction t) auto lemma fvi_trm_minus: "x \<in> fvi_trm b t \<and> x \<ge> c \<longrightarrow> x-c \<in> fvi_trm (b+c) t" by (induction t) auto lemma fvi_trm_iff_fv_trm: "x \<in> fvi_trm b t \<longleftrightarrow> x + b \<in> fv_trm t" using fvi_trm_plus[where b=0 and c=b] by simp_all lemma fvi_plus: "x \<in> fvi (b + c) \<phi> \<longleftrightarrow> x + c \<in> fvi b \<phi>" proof (induction \<phi> arbitrary: b rule: formula.induct) case (Exists \<phi>) then show ?case by force next case (Agg y \<omega> tys f \<phi>) let ?b' = "length tys" have *: "b + c + ?b' = b + ?b' + c" by simp from Agg show ?case by (force simp: * fvi_trm_plus) qed (auto simp add: fvi_trm_plus fv_regex_commute[where g = "\<lambda>x. x + c"]) lemma fvi_minus: "x \<in> fvi b \<phi> \<and> x \<ge> c \<longrightarrow> x - c \<in> fvi (b+c) \<phi>" by (simp add: fvi_plus) lemma fvi_Suc: "x \<in> fvi (Suc b) \<phi> \<longleftrightarrow> Suc x \<in> fvi b \<phi>" using fvi_plus[where c=1] by simp lemma fvi_plus_bound: assumes "\<forall>i\<in>fvi (b + c) \<phi>. i < n" shows "\<forall>i\<in>fvi b \<phi>. i < c + n" proof fix i assume "i \<in> fvi b \<phi>" show "i < c + n" proof (cases "i < c") case True then show ?thesis by simp next case False then obtain i' where "i = i' + c" using nat_le_iff_add by (auto simp: not_less) with assms \<open>i \<in> fvi b \<phi>\<close> show ?thesis by (simp add: fvi_plus) qed qed lemma fvi_Suc_bound: assumes "\<forall>i\<in>fvi (Suc b) \<phi>. i < n" shows "\<forall>i\<in>fvi b \<phi>. i < Suc n" using assms fvi_plus_bound[where c=1] by simp lemma fvi_iff_fv: "x \<in> fvi b \<phi> \<longleftrightarrow> x + b \<in> fv \<phi>" using fvi_plus[where b=0 and c=b] by simp_all qualified definition nfv :: "'t formula \<Rightarrow> nat" where "nfv \<phi> = Max (insert 0 (Suc ` fv \<phi>))" qualified abbreviation nfv_regex where "nfv_regex \<equiv> Regex.nfv_regex fv" qualified definition envs :: "'t formula \<Rightarrow> env set" where "envs \<phi> = {v. length v = nfv \<phi>}" lemma nfv_simps[simp]: "nfv (Let p \<phi> \<psi>) = nfv \<psi>" "nfv (LetPast p \<phi> \<psi>) = nfv \<psi>" "nfv (Neg \<phi>) = nfv \<phi>" "nfv (Or \<phi> \<psi>) = max (nfv \<phi>) (nfv \<psi>)" "nfv (And \<phi> \<psi>) = max (nfv \<phi>) (nfv \<psi>)" "nfv (Prev I \<phi>) = nfv \<phi>" "nfv (Next I \<phi>) = nfv \<phi>" "nfv (Since \<phi> I \<psi>) = max (nfv \<phi>) (nfv \<psi>)" "nfv (Until \<phi> I \<psi>) = max (nfv \<phi>) (nfv \<psi>)" "nfv (MatchP I r) = Regex.nfv_regex fv r" "nfv (MatchF I r) = Regex.nfv_regex fv r" "nfv_regex (Regex.Skip n) = 0" "nfv_regex (Regex.Test \<phi>) = Max (insert 0 (Suc ` fv \<phi>))" "nfv_regex (Regex.Plus r s) = max (nfv_regex r) (nfv_regex s)" "nfv_regex (Regex.Times r s) = max (nfv_regex r) (nfv_regex s)" "nfv_regex (Regex.Star r) = nfv_regex r" unfolding nfv_def Regex.nfv_regex_def by (simp_all add: image_Un Max_Un[symmetric]) lemma nfv_Ands[simp]: "nfv (Ands l) = Max (insert 0 (nfv ` set l))" proof (induction l) case Nil then show ?case unfolding nfv_def by simp next case (Cons a l) have "fv (Ands (a # l)) = fv a \<union> fv (Ands l)" by simp then have "nfv (Ands (a # l)) = max (nfv a) (nfv (Ands l))" unfolding nfv_def by (auto simp: image_Un Max.union[symmetric]) with Cons.IH show ?case by (cases l) auto qed lemma fvi_less_nfv: "\<forall>i\<in>fv \<phi>. i < nfv \<phi>" unfolding nfv_def by (auto simp add: Max_gr_iff intro: max.strict_coboundedI2) lemma fvi_less_nfv_regex: "\<forall>i\<in>fv_regex \<phi>. i < nfv_regex \<phi>" unfolding Regex.nfv_regex_def by (auto simp add: Max_gr_iff intro: max.strict_coboundedI2) fun contains_pred :: "name \<times> nat \<Rightarrow> 't formula \<Rightarrow> bool" where "contains_pred p (Eq t1 t2) = False" | "contains_pred p (Less t1 t2) = False" | "contains_pred p (LessEq t1 t2) = False" | "contains_pred p (Pred e ts) = (p = (e, length ts))" | "contains_pred p (Let e \<phi> \<psi>) = ((contains_pred p \<phi> \<and> contains_pred (e, nfv \<phi>) \<psi>) \<or> (p \<noteq> (e, nfv \<phi>) \<and> contains_pred p \<psi>))" | "contains_pred p (LetPast e \<phi> \<psi>) = (p \<noteq> (e, nfv \<phi>) \<and> ((contains_pred p \<phi> \<and> contains_pred (e, nfv \<phi>) \<psi>) \<or> contains_pred p \<psi>))" | "contains_pred p (Neg \<phi>) = contains_pred p \<phi>" | "contains_pred p (Or \<phi> \<psi>) = (contains_pred p \<phi> \<or> contains_pred p \<psi>)" | "contains_pred p (And \<phi> \<psi>) = (contains_pred p \<phi> \<or> contains_pred p \<psi>)" | "contains_pred p (Ands l) = (\<exists>\<phi>\<in>set l. contains_pred p \<phi>)" | "contains_pred p (Exists t \<phi>) = contains_pred p \<phi>" | "contains_pred p (Agg y \<omega> tys f \<phi>) = contains_pred p \<phi>" | "contains_pred p (Prev I \<phi>) = contains_pred p \<phi>" | "contains_pred p (Next I \<phi>) = contains_pred p \<phi>" | "contains_pred p (Since \<phi> I \<psi>) = (contains_pred p \<phi> \<or> contains_pred p \<psi>)" | "contains_pred p (Until \<phi> I \<psi>) = (contains_pred p \<phi> \<or> contains_pred p \<psi>)" | "contains_pred p (MatchP I r) = (\<exists>\<phi>\<in>Regex.atms r. contains_pred p \<phi>)" | "contains_pred p (MatchF I r) = (\<exists>\<phi>\<in>Regex.atms r. contains_pred p \<phi>)" | "contains_pred p (TP t) = False" | "contains_pred p (TS t) = False" subsubsection \<open>Semantics\<close> definition "ecard A = (if finite A then card A else \<infinity>)" declare conj_cong[fundef_cong] fun letpast_sat where "letpast_sat sat v (i::nat) = sat (\<lambda>w j. j < i \<and> letpast_sat sat w j) v i" declare letpast_sat.simps[simp del] lemma V_subst_letpast_sat: "(\<And>X v j. j \<le> i \<Longrightarrow> f X v j = g X v j) \<Longrightarrow> Formula.letpast_sat f v i = Formula.letpast_sat g v i" by (induct f v i rule: letpast_sat.induct) (subst (1 2) letpast_sat.simps, auto cong: conj_cong) qualified fun sat :: "trace \<Rightarrow> (name \<times> nat \<rightharpoonup> env \<Rightarrow> nat \<Rightarrow> bool) \<Rightarrow> env \<Rightarrow> nat \<Rightarrow> ty formula \<Rightarrow> bool" where "sat \<sigma> V v i (Pred r ts) = (case V (r, length ts) of None \<Rightarrow> (r, map (eval_trm v) ts) \<in> \<Gamma> \<sigma> i | Some X \<Rightarrow> X (map (eval_trm v) ts) i)" | "sat \<sigma> V v i (Let p \<phi> \<psi>) = sat \<sigma> (V((p, nfv \<phi>) \<mapsto> \<lambda>w j. sat \<sigma> V w j \<phi>)) v i \<psi>" | "sat \<sigma> V v i (LetPast p \<phi> \<psi>) = (let pn = (p, nfv \<phi>) in sat \<sigma> (V(pn \<mapsto> letpast_sat (\<lambda>X u k. sat \<sigma> (V(pn \<mapsto> X)) u k \<phi>))) v i \<psi>)" | "sat \<sigma> V v i (Eq t1 t2) = (eval_trm v t1 = eval_trm v t2)" | "sat \<sigma> V v i (Less t1 t2) = (eval_trm v t1 < eval_trm v t2)" | "sat \<sigma> V v i (LessEq t1 t2) = (eval_trm v t1 \<le> eval_trm v t2)" | "sat \<sigma> V v i (Neg \<phi>) = (\<not> sat \<sigma> V v i \<phi>)" | "sat \<sigma> V v i (Or \<phi> \<psi>) = (sat \<sigma> V v i \<phi> \<or> sat \<sigma> V v i \<psi>)" | "sat \<sigma> V v i (And \<phi> \<psi>) = (sat \<sigma> V v i \<phi> \<and> sat \<sigma> V v i \<psi>)" | "sat \<sigma> V v i (Ands l) = (\<forall>\<phi> \<in> set l. sat \<sigma> V v i \<phi>)" | "sat \<sigma> V v i (Exists t \<phi>) = (\<exists>z. sat \<sigma> V (z # v) i \<phi>)" | "sat \<sigma> V v i (Agg y \<omega> tys f \<phi>) = (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> {}} in (M = {} \<longrightarrow> fv \<phi> \<subseteq> {0..<length tys}) \<and> v ! y = eval_agg_op \<omega> M)" | "sat \<sigma> V v i (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>)" | "sat \<sigma> V v i (Next I \<phi>) = (mem I ((\<tau> \<sigma> (Suc i) - \<tau> \<sigma> i)) \<and> sat \<sigma> V v (Suc i) \<phi>)" | "sat \<sigma> V v i (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>))" | "sat \<sigma> V v i (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>))" | "sat \<sigma> V v i (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)" | "sat \<sigma> V v i (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)" | "sat \<sigma> V v i (TP t) = (eval_trm v t = EInt (integer_of_nat i))" | "sat \<sigma> V v i (TS t) = (eval_trm v t = EInt (integer_of_nat (\<tau> \<sigma> i)))" lemma sat_abbrevs[simp]: "sat \<sigma> V v i TT" "\<not> sat \<sigma> V v i FF" unfolding TT_def FF_def by auto lemma sat_Ands: "sat \<sigma> V v i (Ands l) \<longleftrightarrow> (\<forall>\<phi>\<in>set l. sat \<sigma> V v i \<phi>)" by (simp add: list_all_iff) lemma sat_Until_rec: "sat \<sigma> V v i (Until \<phi> I \<psi>) \<longleftrightarrow> memL I 0 \<and> sat \<sigma> V v i \<psi> \<or> (memR I (\<Delta> \<sigma> (i + 1)) \<and> sat \<sigma> V v i \<phi> \<and> sat \<sigma> V v (i + 1) (Until \<phi> (subtract (\<Delta> \<sigma> (i + 1)) I) \<psi>))" (is "?L \<longleftrightarrow> ?R") proof (rule iffI; (elim disjE conjE)?) assume ?L then obtain j where j: "i \<le> j" "mem I (\<tau> \<sigma> j - \<tau> \<sigma> i)" "sat \<sigma> V v j \<psi>" "\<forall>k \<in> {i ..< j}. sat \<sigma> V v k \<phi>" by auto then show ?R proof (cases "i = j") case False with j(1,2) have "memR I (\<Delta> \<sigma> (i + 1))" by (auto elim: order_trans[rotated] simp: diff_le_mono) moreover from False j(1,4) have "sat \<sigma> V v i \<phi>" by auto moreover from False j have "sat \<sigma> V v (i + 1) (Until \<phi> (subtract (\<Delta> \<sigma> (i + 1)) I) \<psi>)" by (auto intro!: exI[of _ j]) ultimately show ?thesis by blast qed simp next assume \<Delta>: "memR I (\<Delta> \<sigma> (i + 1))" and now: "sat \<sigma> V v i \<phi>" and "next": "sat \<sigma> V v (i + 1) (Until \<phi> (subtract (\<Delta> \<sigma> (i + 1)) I) \<psi>)" from "next" obtain j where j: "i + 1 \<le> j" "mem ((subtract (\<Delta> \<sigma> (i + 1)) I)) (\<tau> \<sigma> j - \<tau> \<sigma> (i + 1))" "sat \<sigma> V v j \<psi>" "\<forall>k \<in> {i + 1 ..< j}. sat \<sigma> V v k \<phi>" by (auto simp: diff_le_mono memL_mono) from \<Delta> j(1,2) have "mem I (\<tau> \<sigma> j - \<tau> \<sigma> i)" by auto with now j(1,3,4) show ?L by (auto simp: le_eq_less_or_eq[of i] intro!: exI[of _ j]) qed auto lemma sat_Since_rec: "sat \<sigma> V v i (Since \<phi> I \<psi>) \<longleftrightarrow> mem I 0 \<and> sat \<sigma> V v i \<psi> \<or> (i > 0 \<and> memR I (\<Delta> \<sigma> i) \<and> sat \<sigma> V v i \<phi> \<and> sat \<sigma> V v (i - 1) (Since \<phi> (subtract (\<Delta> \<sigma> i) I) \<psi>))" (is "?L \<longleftrightarrow> ?R") proof (rule iffI; (elim disjE conjE)?) assume ?L then obtain j where j: "j \<le> i" "mem I (\<tau> \<sigma> i - \<tau> \<sigma> j)" "sat \<sigma> V v j \<psi>" "\<forall>k \<in> {j <.. i}. sat \<sigma> V v k \<phi>" by auto then show ?R proof (cases "i = j") case False with j(1) obtain k where [simp]: "i = k + 1" by (cases i) auto with j(1,2) False have "memR I (\<Delta> \<sigma> i)" by (auto elim: order_trans[rotated] simp: diff_le_mono2 le_Suc_eq) moreover from False j(1,4) have "sat \<sigma> V v i \<phi>" by auto moreover from False j have "sat \<sigma> V v (i - 1) (Since \<phi> (subtract (\<Delta> \<sigma> i) I) \<psi>)" by (auto intro!: exI[of _ j]) ultimately show ?thesis by auto qed simp next assume i: "0 < i" and \<Delta>: "memR I (\<Delta> \<sigma> i)" and now: "sat \<sigma> V v i \<phi>" and "prev": "sat \<sigma> V v (i - 1) (Since \<phi> (subtract (\<Delta> \<sigma> i) I) \<psi>)" from "prev" obtain j where j: "j \<le> i - 1" "mem (subtract (\<Delta> \<sigma> i) I) (\<tau> \<sigma> (i - 1) - \<tau> \<sigma> j)" "sat \<sigma> V v j \<psi>" "\<forall>k \<in> {j <.. i - 1}. sat \<sigma> V v k \<phi>" by (auto simp: diff_le_mono2 memL_mono) from \<Delta> i j(1,2) have "mem I (\<tau> \<sigma> i - \<tau> \<sigma> j)" by auto with now i j(1,3,4) show ?L by (auto simp: le_Suc_eq gr0_conv_Suc intro!: exI[of _ j]) qed auto lemma sat_MatchF_rec: "sat \<sigma> V v i (MatchF I r) \<longleftrightarrow> memL I 0 \<and> Regex.eps (sat \<sigma> V v) i r \<or> memR I (\<Delta> \<sigma> (i + 1)) \<and> (\<exists>s \<in> Regex.lpd (sat \<sigma> V v) i r. sat \<sigma> V v (i + 1) (MatchF (subtract (\<Delta> \<sigma> (i + 1)) I) s))" (is "?L \<longleftrightarrow> ?R1 \<or> ?R2") proof (rule iffI; (elim disjE conjE bexE)?) assume ?L then obtain j where j: "j \<ge> i" "mem I (\<tau> \<sigma> j - \<tau> \<sigma> i)" and "Regex.match (sat \<sigma> V v) r i j" by auto then show "?R1 \<or> ?R2" proof (cases "i < j") case True with \<open>Regex.match (sat \<sigma> V v) r i j\<close> lpd_match[of i j "sat \<sigma> V v" r] obtain s where "s \<in> Regex.lpd (sat \<sigma> V v) i r" "Regex.match (sat \<sigma> V v) s (i + 1) j" by auto with True j have ?R2 by (auto simp: le_diff_conv le_diff_conv2 intro!: exI[of _ j] elim: le_trans[rotated]) then show ?thesis by blast qed (auto simp: eps_match) next assume "memR I (\<Delta> \<sigma> (i + 1))" moreover fix s assume [simp]: "s \<in> Regex.lpd (sat \<sigma> V v) i r" and "sat \<sigma> V v (i + 1) (MatchF (subtract (\<Delta> \<sigma> (i + 1)) I) s)" then obtain j where "j > i" "Regex.match (sat \<sigma> V v) s (i + 1) j" "mem (subtract (\<Delta> \<sigma> (i + 1)) I) (\<tau> \<sigma> j - \<tau> \<sigma> (Suc i))" by (auto simp: diff_le_mono memL_mono Suc_le_eq) ultimately show ?L by (auto simp: le_diff_conv lpd_match intro!: exI[of _ j] bexI[of _ s]) qed (auto simp: eps_match intro!: exI[of _ i]) lemma sat_MatchP_rec: "sat \<sigma> V v i (MatchP I r) \<longleftrightarrow> memL I 0 \<and> Regex.eps (sat \<sigma> V v) i r \<or> i > 0 \<and> memR I (\<Delta> \<sigma> i) \<and> (\<exists>s \<in> Regex.rpd (sat \<sigma> V v) i r. sat \<sigma> V v (i - 1) (MatchP (subtract (\<Delta> \<sigma> i) I) s))" (is "?L \<longleftrightarrow> ?R1 \<or> ?R2") proof (rule iffI; (elim disjE conjE bexE)?) assume ?L then obtain j where j: "j \<le> i" "mem I (\<tau> \<sigma> i - \<tau> \<sigma> j)" and "Regex.match (sat \<sigma> V v) r j i" by auto then show "?R1 \<or> ?R2" proof (cases "j < i") case True with \<open>Regex.match (sat \<sigma> V v) r j i\<close> rpd_match[of j i "sat \<sigma> V v" r] obtain s where "s \<in> Regex.rpd (sat \<sigma> V v) i r" "Regex.match (sat \<sigma> V v) s j (i - 1)" by auto with True j have ?R2 by (auto simp: diff_le_mono2 intro!: exI[of _ j]) then show ?thesis by blast qed (auto simp: eps_match) next assume "memR I (\<Delta> \<sigma> i)" moreover fix s assume [simp]: "s \<in> Regex.rpd (sat \<sigma> V v) i r" and "sat \<sigma> V v (i - 1) (MatchP (subtract (\<Delta> \<sigma> i) I) s)" "i > 0" then obtain j where "j < i" "Regex.match (sat \<sigma> V v) s j (i - 1)" "mem (subtract (\<Delta> \<sigma> i) I) (\<tau> \<sigma> (i - 1) - \<tau> \<sigma> j)" by (auto simp: gr0_conv_Suc less_Suc_eq_le) ultimately show ?L by (auto simp: rpd_match intro!: exI[of _ j] bexI[of _ s]) qed (auto simp: eps_match intro!: exI[of _ i]) lemma sat_Since_0: "sat \<sigma> V v 0 (Since \<phi> I \<psi>) \<longleftrightarrow> memL I 0 \<and> sat \<sigma> V v 0 \<psi>" by auto lemma sat_MatchP_0: "sat \<sigma> V v 0 (MatchP I r) \<longleftrightarrow> memL I 0 \<and> Regex.eps (sat \<sigma> V v) 0 r" by (auto simp: eps_match) lemma sat_Since_point: "sat \<sigma> V v i (Since \<phi> I \<psi>) \<Longrightarrow> (\<And>j. j \<le> i \<Longrightarrow> mem I (\<tau> \<sigma> i - \<tau> \<sigma> j) \<Longrightarrow> sat \<sigma> V v i (Since \<phi> (point (\<tau> \<sigma> i - \<tau> \<sigma> j)) \<psi>) \<Longrightarrow> P) \<Longrightarrow> P" by (auto intro: diff_le_self) lemma sat_MatchP_point: "sat \<sigma> V v i (MatchP I r) \<Longrightarrow> (\<And>j. j \<le> i \<Longrightarrow> mem I (\<tau> \<sigma> i - \<tau> \<sigma> j) \<Longrightarrow> sat \<sigma> V v i (MatchP (point (\<tau> \<sigma> i - \<tau> \<sigma> j)) r) \<Longrightarrow> P) \<Longrightarrow> P" by (auto intro: diff_le_self) lemma sat_Since_pointD: "sat \<sigma> V v i (Since \<phi> (point t) \<psi>) \<Longrightarrow> mem I t \<Longrightarrow> sat \<sigma> V v i (Since \<phi> I \<psi>)" by auto lemma sat_MatchP_pointD: "sat \<sigma> V v i (MatchP (point t) r) \<Longrightarrow> mem I t \<Longrightarrow> sat \<sigma> V v i (MatchP I r)" by auto lemma sat_fv_cong: "\<forall>x\<in>fv \<phi>. v!x = v'!x \<Longrightarrow> sat \<sigma> V v i \<phi> = sat \<sigma> V v' i \<phi>" proof (induct \<phi> arbitrary: V v v' i rule: formula.induct) case (Pred n ts) show ?case by (simp cong: map_cong eval_trm_fv_cong[OF Pred[simplified, THEN bspec]] split: option.splits) next case (Let p \<phi> \<psi>) then show ?case by auto next case (Eq x1 x2) then show ?case unfolding fvi.simps sat.simps by (metis UnCI eval_trm_fv_cong) next case (Less x1 x2) then show ?case unfolding fvi.simps sat.simps by (metis UnCI eval_trm_fv_cong) next case (LessEq x1 x2) then show ?case unfolding fvi.simps sat.simps by (metis UnCI eval_trm_fv_cong) next case (Ands l) have "\<And>\<phi>. \<phi> \<in> set l \<Longrightarrow> sat \<sigma> V v i \<phi> = sat \<sigma> V v' i \<phi>" proof - fix \<phi> assume "\<phi> \<in> set l" then have "fv \<phi> \<subseteq> fv (Ands l)" using fv_subset_Ands by blast then have "\<forall>x\<in>fv \<phi>. v!x = v'!x" using Ands.prems by blast then show "sat \<sigma> V v i \<phi> = sat \<sigma> V v' i \<phi>" using Ands.hyps \<open>\<phi> \<in> set l\<close> by blast qed then show ?case using sat_Ands by blast next case (Exists t \<phi>) then show ?case unfolding sat.simps by (intro iff_exI) (simp add: fvi_Suc nth_Cons') next case (Agg y \<omega> tys f \<phi>) let ?b = "length tys" have "v ! y = v' ! y" using Agg.prems by simp moreover have "sat \<sigma> V (zs @ v) i \<phi> = sat \<sigma> V (zs @ v') i \<phi>" if "length zs = ?b" for zs using that Agg.prems by (simp add: Agg.hyps[where v="zs @ v" and v'="zs @ v'"] nth_append fvi_iff_fv(1)[where b= ?b]) moreover have "eval_trm (zs @ v) f = eval_trm (zs @ v') f" if "length zs = ?b" for zs using that Agg.prems by (auto intro!: eval_trm_fv_cong[where v="zs @ v" and v'="zs @ v'"] simp: nth_append fvi_iff_fv(1)[where b= ?b] fvi_trm_iff_fv_trm[where b= ?b]) ultimately show ?case by (simp cong: conj_cong) next case (MatchF I r) then have "Regex.match (sat \<sigma> V v) r = Regex.match (sat \<sigma> V v') r" by (intro match_fv_cong) (auto simp: fv_regex_alt) then show ?case by auto next case (MatchP I r) then have "Regex.match (sat \<sigma> V v) r = Regex.match (sat \<sigma> V v') r" by (intro match_fv_cong) (auto simp: fv_regex_alt) then show ?case by auto next case (TP t) then show ?case unfolding fvi.simps sat.simps by (metis eval_trm_fv_cong) next case (TS t) then show ?case unfolding fvi.simps sat.simps by (metis eval_trm_fv_cong) qed (auto 10 0 simp: Let_def split: nat.splits intro!: iff_exI) lemma sat_the_restrict: "fv \<phi> \<subseteq> A \<Longrightarrow> Formula.sat \<sigma> V (map the (restrict A v)) i \<phi> = Formula.sat \<sigma> V (map the v) i \<phi>" by (rule sat_fv_cong) (auto intro!: map_the_restrict) lemma match_fv_cong: "\<forall>x\<in>fv_regex r. v!x = v'!x \<Longrightarrow> Regex.match (sat \<sigma> V v) r = Regex.match (sat \<sigma> V v') r" by (rule match_fv_cong, rule sat_fv_cong) (auto simp: fv_regex_alt) lemma eps_fv_cong: "\<forall>x\<in>fv_regex r. v!x = v'!x \<Longrightarrow> Regex.eps (sat \<sigma> V v) i r = Regex.eps (sat \<sigma> V v') i r" unfolding eps_match by (erule match_fv_cong[THEN fun_cong, THEN fun_cong]) subsection \<open>Past-only formulas\<close> fun past_only :: "'t formula \<Rightarrow> bool" where "past_only (Pred _ _) = True" | "past_only (Eq _ _) = True" | "past_only (Less _ _) = True" | "past_only (LessEq _ _) = True" | "past_only (Let _ \<alpha> \<beta>) = (past_only \<alpha> \<and> past_only \<beta>)" | "past_only (LetPast _ \<alpha> \<beta>) = (past_only \<alpha> \<and> past_only \<beta>)" | "past_only (Neg \<psi>) = past_only \<psi>" | "past_only (Or \<alpha> \<beta>) = (past_only \<alpha> \<and> past_only \<beta>)" | "past_only (And \<alpha> \<beta>) = (past_only \<alpha> \<and> past_only \<beta>)" | "past_only (Ands l) = (\<forall>\<alpha>\<in>set l. past_only \<alpha>)" | "past_only (Exists _ \<psi>) = past_only \<psi>" | "past_only (Agg _ _ _ _ \<psi>) = past_only \<psi>" | "past_only (Prev _ \<psi>) = past_only \<psi>" | "past_only (Next _ _) = False" | "past_only (Since \<alpha> _ \<beta>) = (past_only \<alpha> \<and> past_only \<beta>)" | "past_only (Until \<alpha> _ \<beta>) = False" | "past_only (MatchP _ r) = Regex.pred_regex past_only r" | "past_only (MatchF _ _) = False" | "past_only (TP _) = True" | "past_only (TS _) = True" lemma past_only_sat: assumes "prefix_of \<pi> \<sigma>" "prefix_of \<pi> \<sigma>'" shows "i < plen \<pi> \<Longrightarrow> dom V = dom V' \<Longrightarrow> (\<And>p v i. p \<in> dom V \<Longrightarrow> i < plen \<pi> \<Longrightarrow> the (V p) v i = the (V' p) v i) \<Longrightarrow> past_only \<phi> \<Longrightarrow> sat \<sigma> V v i \<phi> = sat \<sigma>' V' v i \<phi>" proof (induction \<phi> arbitrary: V V' v i) case (Pred e ts) let ?en = "(e, length ts)" show ?case proof (cases "V ?en") case None then have "V' (e, length ts) = None" using \<open>dom V = dom V'\<close> by auto with None \<Gamma>_prefix_conv[OF assms(1,2) Pred(1)] show ?thesis by simp next case (Some a) moreover obtain a' where "V' ?en = Some a'" using Some \<open>dom V = dom V'\<close> by auto moreover have "the (V ?en) w i = the (V' ?en) w i" for w using Some Pred(1,3) by (fastforce intro: domI) ultimately show ?thesis by simp qed next case (Let p \<phi> \<psi>) let ?pn = "(p, nfv \<phi>)" let ?V = "\<lambda>V \<sigma>. (V(?pn \<mapsto> \<lambda>w j. sat \<sigma> V w j \<phi>))" show ?case unfolding sat.simps proof (rule Let.IH(2)) show "i < plen \<pi>" by fact from Let.prems show "past_only \<psi>" by simp from Let.prems show "dom (?V V \<sigma>) = dom (?V V' \<sigma>')" by (simp del: fun_upd_apply) next fix p' v i assume *: "p' \<in> dom (?V V \<sigma>)" "i < plen \<pi>" show "the (?V V \<sigma> p') v i = the (?V V' \<sigma>' p') v i" proof (cases "p' = ?pn") case True with Let \<open>i < plen \<pi>\<close> show ?thesis by auto next case False with * show ?thesis by (auto intro!: Let.prems(3)) qed qed next case (LetPast p \<phi> \<psi>) let ?pn = "(p, nfv \<phi>)" let ?V = "\<lambda>V \<sigma>. V(?pn \<mapsto> letpast_sat (\<lambda>X u k. sat \<sigma> (V(?pn \<mapsto> X)) u k \<phi>))" show ?case unfolding sat.simps Let_def proof (rule LetPast.IH(2)) show "i < plen \<pi>" by fact from LetPast.prems show "past_only \<psi>" by simp from LetPast.prems show "dom (?V V \<sigma>) = dom (?V V' \<sigma>')" by (simp del: fun_upd_apply) next fix p' v i' assume *: "p' \<in> dom (?V V \<sigma>)" "i' < plen \<pi>" show "the (?V V \<sigma> p') v i' = the (?V V' \<sigma>' p') v i'" proof (cases "p' = ?pn") case True then have "?pn \<in> dom (?V V \<sigma>)" by simp then have "letpast_sat (\<lambda>X u k. sat \<sigma> (V(?pn \<mapsto> X)) u k \<phi>) v j = letpast_sat (\<lambda>X u k. sat \<sigma>' (V'(?pn \<mapsto> X)) u k \<phi>) v j" if "j < plen \<pi>" for j using that proof (induct "\<lambda>X u k. sat \<sigma> (V(?pn \<mapsto> X)) u k \<phi>" v j rule: letpast_sat.induct) case (1 v j) show ?case proof (subst (1 2) letpast_sat.simps, rule LetPast.IH(1), goal_cases plen dom eq past_only) case plen from "1" show ?case by simp next case dom from LetPast.prems show ?case by (auto simp add: dom_def) next case (eq p'' v' j') with "1" LetPast.prems(3)[of p'' j' v'] show ?case by (cases "p'' = ?pn") fastforce+ next case past_only from LetPast.prems show ?case by simp qed qed with True \<open>i' < plen \<pi>\<close> show ?thesis by simp next case False with * show ?thesis by (auto intro!: LetPast.prems(3)) qed qed next case (Ands l) with \<Gamma>_prefix_conv[OF assms] show ?case by simp next case (Prev I \<phi>) with \<tau>_prefix_conv[OF assms] show ?case by (simp split: nat.split) next case (Since \<phi>1 I \<phi>2) with \<tau>_prefix_conv[OF assms] show ?case by auto next case (MatchP I r) then have "Regex.match (sat \<sigma> V v) r a b = Regex.match (sat \<sigma>' V' v) r a b" if "b < plen \<pi>" for a b using that by (intro Regex.match_cong_strong) (auto simp: regex.pred_set) with \<tau>_prefix_conv[OF assms] MatchP(2) show ?case by auto next case (TP t) with \<tau>_prefix_conv[OF assms] show ?case by simp next case (TS t) with \<tau>_prefix_conv[OF assms] show ?case by simp qed auto subsection \<open>Well-formed formulas\<close> fun wf_formula :: "'t formula \<Rightarrow> bool" where "wf_formula (Let p \<phi> \<psi>) = ({0..<nfv \<phi>} \<subseteq> fv \<phi> \<and> wf_formula \<phi> \<and> wf_formula \<psi>)" | "wf_formula (LetPast p \<phi> \<psi>) = ({0..<nfv \<phi>} \<subseteq> fv \<phi> \<and> wf_formula \<phi> \<and> wf_formula \<psi>)" | "wf_formula (Neg \<phi>) = wf_formula \<phi>" | "wf_formula (Or \<phi> \<psi>) = (wf_formula \<phi> \<and> wf_formula \<psi>)" | "wf_formula (And \<phi> \<psi>) = (wf_formula \<phi> \<and> wf_formula \<psi> )" | "wf_formula (Ands l) = (list_all wf_formula l)" | "wf_formula (Exists x \<phi>) = (wf_formula \<phi> \<and> 0 \<in> fv \<phi>)" | "wf_formula (Agg y \<omega> tys f \<phi>) = (wf_formula \<phi> \<and> y + length tys \<notin> fv \<phi> \<and> {0..< length tys} \<subseteq> fv \<phi> )" | "wf_formula (Prev I \<phi>) = (wf_formula \<phi>)" | "wf_formula (Next I \<phi>) = (wf_formula \<phi>)" | "wf_formula (Since \<phi> I \<psi>) = (wf_formula \<phi> \<and> wf_formula \<psi>)" | "wf_formula (Until \<phi> I \<psi>) = (wf_formula \<phi> \<and> wf_formula \<psi>)" | "wf_formula (MatchP I r) = Regex.pred_regex wf_formula r" | "wf_formula (MatchF I r) = Regex.pred_regex wf_formula r" | "wf_formula _ = True" end (* context *) subsection \<open> Notation \<close> context begin abbreviation "eval_trm_option v t \<equiv> Formula.eval_trm (map the v) t" abbreviation "sat_the \<sigma> V v i \<equiv> Formula.sat \<sigma> V (map the v) i" end bundle MFODL_no_notation begin no_notation trm.Var ("\<^bold>v") and trm.Const ("\<^bold>c") no_notation formula.Pred ("_ \<dagger> _" [85, 85] 85) and formula.Eq (infixl "=\<^sub>F" 75) and formula.LessEq ("(_/ \<le>\<^sub>F _)" [76,76] 75) and formula.Less ("(_/ <\<^sub>F _)" [76,76] 75) and formula.Neg ("\<not>\<^sub>F _" [82] 82) and formula.And (infixr "\<and>\<^sub>F" 80) and formula.Or (infixr "\<or>\<^sub>F" 80) and formula.Exists ("\<exists>\<^sub>F:_. _" [70,70] 70) and formula.Ands ("\<And>\<^sub>F _" [70] 70) and formula.Prev ("\<^bold>Y _ _" [55, 65] 65) and formula.Next ("\<^bold>X _ _" [55, 65] 65) and formula.Since ("_ \<^bold>S _ _" [60,55,60] 60) and formula.Until ("_ \<^bold>U _ _" [60,55,60] 60) no_notation Formula.fv_trm ("FV\<^sub>t") and Formula.fv ("FV") and eval_trm_option ("_\<lbrakk>_\<rbrakk>\<^sub>M" [51,89] 89) and sat_the ("\<langle>_, _, _, _\<rangle> \<Turnstile>\<^sub>M _" [56, 56, 56, 56, 56] 55) and Formula.sat ("\<langle>_, _, _, _\<rangle> \<Turnstile> _" [56, 56, 56, 56, 56] 55) and Interval.interval ("\<^bold>[_,_\<^bold>]") end bundle MFODL_notation begin notation trm.Var ("\<^bold>v") and trm.Const ("\<^bold>c") notation formula.Pred ("_ \<dagger> _" [85, 85] 85) and formula.Eq (infixl "=\<^sub>F" 75) and formula.LessEq ("(_/ \<le>\<^sub>F _)" [76,76] 75) and formula.Less ("(_/ <\<^sub>F _)" [76,76] 75) and formula.Neg ("\<not>\<^sub>F _" [82] 82) and formula.And (infixr "\<and>\<^sub>F" 80) and formula.Or (infixr "\<or>\<^sub>F" 80) and formula.Exists ("\<exists>\<^sub>F:_. _" [70,70] 70) and formula.Ands ("\<And>\<^sub>F _" [70] 70) and formula.Prev ("\<^bold>Y _ _" [55, 65] 65) and formula.Next ("\<^bold>X _ _" [55, 65] 65) and formula.Since ("_ \<^bold>S _ _" [60,55,60] 60) and formula.Until ("_ \<^bold>U _ _" [60,55,60] 60) notation Formula.fv_trm ("FV\<^sub>t") and Formula.fv ("FV") and eval_trm_option ("_\<lbrakk>_\<rbrakk>\<^sub>M" [51,89] 89) and sat_the ("\<langle>_, _, _, _\<rangle> \<Turnstile>\<^sub>M _" [56, 56, 56, 56, 56] 55) and Formula.sat ("\<langle>_, _, _, _\<rangle> \<Turnstile> _" [56, 56, 56, 56, 56] 55) and Interval.interval ("\<^bold>[_,_\<^bold>]") end unbundle MFODL_notation \<comment> \<open> enable notation \<close> term "\<^bold>c (EInt 0) =\<^sub>F \<^bold>c (EInt 0)" term "v\<lbrakk>\<^bold>c t\<rbrakk>\<^sub>M" term "\<And>\<^sub>F [\<exists>\<^sub>F:t. (trm =\<^sub>F \<^bold>v x) \<and>\<^sub>F (a \<le>\<^sub>F \<^bold>c z), \<phi> \<^bold>U I \<psi>]" term "\<langle>\<sigma>, V, v, i + length v\<rangle> \<Turnstile>\<^sub>M \<^bold>Y I (\<not>\<^sub>F (P \<dagger> [\<^bold>c a, \<^bold>v 0]) \<and>\<^sub>F (Q \<dagger> [\<^bold>v y])) \<^bold>S (point n) ((\<^bold>X \<^bold>[2,3\<^bold>] (P \<dagger> [\<^bold>c b, \<^bold>v 0])) \<or>\<^sub>F Q \<dagger> [\<^bold>v y])" unbundle MFODL_no_notation \<comment> \<open> disable notation \<close> (*<*) end (*>*)
(* This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_int_add_inv_right imports "../../Test_Base" begin datatype Nat = Z | S "Nat" datatype Integer = P "Nat" | N "Nat" definition(*fun*) zero :: "Integer" where "zero = P Z" fun pred :: "Nat => Nat" where "pred (S y) = y" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S z) y = S (plus z y)" fun neg :: "Integer => Integer" where "neg (P (Z)) = P Z" | "neg (P (S z)) = N z" | "neg (N n) = P (plus (S Z) n)" fun t2 :: "Nat => Nat => Integer" where "t2 x y = (let fail :: Integer = (case y of Z => P x | S z => (case x of Z => N y | S x2 => t2 x2 z)) in (case x of Z => (case y of Z => P Z | S x4 => fail) | S x3 => fail))" fun plus2 :: "Integer => Integer => Integer" where "plus2 (P m) (P n) = P (plus m n)" | "plus2 (P m) (N o2) = t2 m (plus (S Z) o2)" | "plus2 (N m2) (P n2) = t2 n2 (plus (S Z) m2)" | "plus2 (N m2) (N n3) = N (plus (plus (S Z) m2) n3)" theorem property0 : "((plus2 x (neg x)) = zero)" oops end
lemma brouwer_surjective_cball: fixes f :: "'n::euclidean_space \<Rightarrow> 'n" assumes "continuous_on (cball a e) f" and "e > 0" and "x \<in> S" and "\<And>x y. \<lbrakk>x\<in>S; y\<in>cball a e\<rbrakk> \<Longrightarrow> x + (y - f y) \<in> cball a e" shows "\<exists>y\<in>cball a e. f y = x"
{-| Module : MachineLearning.Model.Measure Description : TIR expression data structures Copyright : (c) Fabricio Olivetti de Franca, 2022 License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : POSIX Performance measures for Regression and Classification. -} module MachineLearning.Model.Measure ( Measure(..) , toMeasure , measureAll , _rmse ) where import Data.Semigroup (Sum(..)) import qualified Numeric.LinearAlgebra as LA import qualified Numeric.Morpheus.Statistics as Stat import qualified Data.Vector.Storable as V type Vector = LA.Vector Double -- * Performance measures -- | A performance measure has a string name and a function that -- takes a vector of the true values, a vector of predict values -- and returns a `Double`. data Measure = Measure { _name :: String , _fun :: Vector -> Vector -> Double -- ^ true values -> predicted values -> measure } instance Show Measure where show (Measure n _) = n -- | Mean for a vector of doubles mean :: Vector -> Double mean xs = V.sum xs / fromIntegral (V.length xs) {-# INLINE mean #-} -- | Variance for a vector of doubles var :: Vector -> Double var xs = sum' / fromIntegral (V.length xs) where mu = mean xs sum' = V.foldl (\s x -> s + (x-mu)^(2 :: Int)) 0 xs {-# INLINE var #-} -- | generic mean error measure meanError :: (Vector -> Vector) -- ^ a function to be applied to the error terms (abs, square,...) -> Vector -- ^ target values -> Vector -- ^ fitted values -> Double meanError op ys ysHat = mean $ op $ ysHat - ys {-# INLINE meanError #-} -- * Common error measures for regression: -- MSE, MAE, RMSE, NMSE, r^2 -- | Mean Squared Error mse :: Vector -> Vector -> Double --mse = meanError (^(2 :: Int)) mse ys ysHat = mean $ (ysHat - ys) ^(2 :: Int) {-# INLINE mse #-} -- | Mean Absolute Error mae :: Vector -> Vector -> Double mae ys ysHat = mean $ abs (ysHat - ys) -- meanError abs {-# INLINE mae #-} -- | Normalized Mean Squared Error nmse :: Vector -> Vector -> Double nmse ys ysHat = mse ysHat ys / var ys {-# INLINE nmse #-} -- | Root of the Mean Squared Error rmse :: Vector -> Vector -> Double rmse ys ysHat = sqrt $ mse ysHat ys {-# INLINE rmse #-} -- | negate R^2 - minimization metric rSq :: Vector -> Vector -> Double rSq ys ysHat = negate (1 - r/t) where ym = Stat.mean ys t = sumOfSq $ V.map (\yi -> yi - ym) ys r = sumOfSq $ ys - ysHat sumOfSq = V.foldl (\s di -> s + di^(2 :: Int)) 0 {-# INLINE rSq #-} -- * Regression measures _rmse, _mae, _nmse, _r2 :: Measure _rmse = Measure "RMSE" rmse _mae = Measure "MAE" mae _nmse = Measure "NMSE" nmse _r2 = Measure "R^2" rSq -- * Classification measures _accuracy,_recall,_precision,_f1,_logloss :: Measure _accuracy = Measure "Accuracy" accuracy _recall = Measure "Recall" recall _precision = Measure "Precision" precision _f1 = Measure "F1" f1 _logloss = Measure "Log-Loss" logloss -- | Accuracy: ratio of correct classification accuracy :: Vector -> Vector -> Double accuracy ys ysHat = -equals/tot where ys' = map round $ LA.toList ys ysHat' = map round $ LA.toList ysHat (Sum equals, Sum tot) = foldMap cmp $ zip ysHat' ys' cmp :: (Integer, Integer) -> (Sum Double, Sum Double) cmp (yH, y) | yH == y = (Sum 1, Sum 1) | otherwise = (Sum 0, Sum 1) -- | Precision: ratio of correct positive classification precision :: Vector -> Vector -> Double precision ys ysHat = equals/tot where ys' = map round $ LA.toList ys ysHat' = map round $ LA.toList ysHat (Sum equals, Sum tot) = foldMap cmp $ zip ysHat' ys' cmp :: (Integer, Integer) -> (Sum Double, Sum Double) cmp (1, 1) = (Sum 1, Sum 1) cmp (1, 0) = (Sum 0, Sum 1) cmp (_, _) = (Sum 0, Sum 0) -- | Recall: ratio of retrieval of positive labels recall :: Vector -> Vector -> Double recall ys ysHat = equals/tot where ys' = map round $ LA.toList ys ysHat' = map round $ LA.toList ysHat (Sum equals, Sum tot) = foldMap cmp $ zip ysHat' ys' cmp :: (Integer, Integer) -> (Sum Double, Sum Double) cmp (1, 1) = (Sum 1, Sum 1) cmp (0, 1) = (Sum 0, Sum 1) cmp (_, _) = (Sum 0, Sum 0) -- | Harmonic average between Precision and Recall f1 :: Vector -> Vector -> Double f1 ys ysHat = 2*prec*rec/(prec+rec) where prec = precision ysHat ys rec = recall ysHat ys -- | LogLoss of a classifier that returns a probability. logloss :: Vector -> Vector -> Double logloss ys ysHat = mean $ -(ys * log ysHat' + (1 - ys)*log(1 - ysHat')) where ysHat' = LA.cmap (min (1.0 - 1e-15) . max 1e-15) ysHat -- | List of all measures measureAll :: [Measure] measureAll = [_rmse, _mae, _nmse, _r2 , _accuracy, _recall, _precision, _f1, _logloss ] -- | Read a string into a measure toMeasure :: String -> Measure toMeasure input | null cmp = error ("Invalid measure: " ++ input) | otherwise = (snd.head) cmp where cmp = filter fst $ map isThis measureAll isThis m@(Measure name _) = (name == input, m)
Anderson dated ( and frequently collaborated with ) singer Fiona Apple for several years during the late 1990s and early 2000s . He has been in a relationship with actress and comedian Maya Rudolph since 2001 . They live together in the San Fernando Valley with their four children : daughters Pearl Bailey ( born October 2005 ) , Lucille ( born November 2009 ) , and Minnie Ida ( born August 2013 ) and son Jack ( born July 2011 ) .
State Before: α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α ⊢ Ioo (↑toDual a) (↑toDual b) = map (Equiv.toEmbedding toDual) (Ioo b a) State After: α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α ⊢ Ioo (↑toDual a) (↑toDual b) = Ioo b a Tactic: refine' Eq.trans _ map_refl.symm State Before: α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α ⊢ Ioo (↑toDual a) (↑toDual b) = Ioo b a State After: case a α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α c : (fun x => αᵒᵈ) a ⊢ c ∈ Ioo (↑toDual a) (↑toDual b) ↔ c ∈ Ioo b a Tactic: ext c State Before: case a α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α c : (fun x => αᵒᵈ) a ⊢ c ∈ Ioo (↑toDual a) (↑toDual b) ↔ c ∈ Ioo b a State After: case a α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α c : (fun x => αᵒᵈ) a ⊢ ↑toDual a < c ∧ c < ↑toDual b ↔ b < c ∧ c < a Tactic: rw [mem_Ioo, mem_Ioo (α := α)] State Before: case a α : Type u_1 β : Type ?u.113900 inst✝² : Preorder α inst✝¹ : Preorder β inst✝ : LocallyFiniteOrder α a b : α c : (fun x => αᵒᵈ) a ⊢ ↑toDual a < c ∧ c < ↑toDual b ↔ b < c ∧ c < a State After: no goals Tactic: exact and_comm
! ! Copyright 2011 Sebastian Heimann ! ! Licensed under the Apache License, Version 2.0 (the "License"); ! you may not use this file except in compliance with the License. ! You may obtain a copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0 ! ! Unless required by applicable law or agreed to in writing, software ! distributed under the License is distributed on an "AS IS" BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ! See the License for the specific language governing permissions and ! limitations under the License. ! module source_circular use constants use orthodrome use parameterized_source use discrete_source use piecewise_linear_function use euler use better_varying_string use unit use util implicit none private integer, public, parameter :: n_source_params_circular = 11 integer, public, parameter :: n_grid_dims_circular = 3 public psm_to_tdsm_circular, psm_write_info_file_circular, psm_set_circular public psm_get_param_name_circular, psm_get_param_unit_circular, psm_get_param_id_circular public psm_cleanup_circular private psm_to_tdsm_size_circular, psm_to_tdsm_table_circular type(varying_string), private, dimension(:), allocatable :: psm_param_names_circular, psm_param_units_circular real, dimension(n_source_params_circular), public, parameter :: psm_params_norm_circular = & (/ 1., 10000., 10000., 10000., 7e18, 360., 90., 360., 10000., 3000.,1. /) real, private, parameter :: big = huge(psm_params_norm_circular(1)) ! logical, physical or computational accuracy limits for params real, dimension(n_source_params_circular), public, parameter :: psm_params_min_hard_circular = & (/ -big, -100000., -100000., 0., 1., -big, -big, -big, 0., 100., 0./) real, dimension(n_source_params_circular), public, parameter :: psm_params_max_hard_circular = & (/ big, 100000., 100000., 1000000., 7e25, big, big, big, 1000000., 100000., 10./) ! these limits give range of realistic, non-redundant or practical params real, dimension(n_source_params_circular), public, parameter :: psm_params_min_soft_circular = & (/ -20., -10000., -10000., 0., 1., -180., 0., -180., 0., 1000., 0./) real, dimension(n_source_params_circular), public, parameter :: psm_params_max_soft_circular = & (/ 20., 10000., 10000., 150000., 7e25, 180., 90., 180., 100000., 10000., 5./) ! defaults for external use real, dimension(n_source_params_circular), public, parameter :: psm_params_default_circular = & (/ 0.,0., 0., 10000., 7e18, 0., 80., 0., 5000., 3500., 1./) ! M0 = 7e18 Nm <=> Mw = 6.5 contains subroutine psm_cleanup_circular() integer :: i if (allocated( psm_param_names_circular )) then do i=1,n_source_params_circular call delete( psm_param_names_circular(i) ) end do deallocate( psm_param_names_circular ) end if if (allocated( psm_param_units_circular )) then do i=1,n_source_params_circular call delete( psm_param_units_circular(i) ) end do deallocate( psm_param_units_circular ) end if end subroutine subroutine psm_init_param_names_circular() if (.not. allocated( psm_param_names_circular )) then allocate( psm_param_names_circular( n_source_params_circular ) ) psm_param_names_circular(1) = "time" psm_param_names_circular(2) = "north-shift" psm_param_names_circular(3) = "east-shift" psm_param_names_circular(4) = "depth" psm_param_names_circular(5) = "moment" psm_param_names_circular(6) = "strike" psm_param_names_circular(7) = "dip" psm_param_names_circular(8) = "slip-rake" psm_param_names_circular(9) = "radius" psm_param_names_circular(10) = "rupture-velocity" psm_param_names_circular(11) = "rise-time" end if if (.not. allocated( psm_param_units_circular )) then allocate( psm_param_units_circular( n_source_params_circular ) ) psm_param_units_circular(1) = "s" psm_param_units_circular(2) = "m" psm_param_units_circular(3) = "m" psm_param_units_circular(4) = "m" psm_param_units_circular(5) = "Nm" psm_param_units_circular(6) = "degrees" psm_param_units_circular(7) = "degrees" psm_param_units_circular(8) = "degrees" psm_param_units_circular(9) = "m" psm_param_units_circular(10) = "m/s" psm_param_units_circular(11) = "s" end if end subroutine subroutine psm_get_param_name_circular( iparam, name ) integer, intent(in) :: iparam type(varying_string), intent(inout) :: name call psm_init_param_names_circular() name = "" if (iparam < 1 .or. n_source_params_circular < iparam) return name = psm_param_names_circular(iparam) end subroutine subroutine psm_get_param_unit_circular( iparam, unit ) integer, intent(in) :: iparam type(varying_string), intent(inout) :: unit call psm_init_param_names_circular() unit = "" if (iparam < 1 .or. n_source_params_circular < iparam) return unit = psm_param_units_circular(iparam) end subroutine subroutine psm_get_param_id_circular( name, iparam ) type(varying_string), intent(in) :: name integer, intent(out) :: iparam integer :: i call psm_init_param_names_circular() iparam = 0 do i=1, n_source_params_circular if (name .eq. psm_param_names_circular(i)) then iparam = i return end if end do end subroutine subroutine psm_set_circular( psm, params, normalized, only_moment_changed ) type(t_psm), intent(inout) :: psm real, dimension(:), intent(in) :: params logical, intent(in) :: normalized logical, intent(out) :: only_moment_changed logical :: must_reset_grid real, dimension(size(params)) :: new_params must_reset_grid = .false. if (.not. allocated(psm%grid_size) .or. (psm%sourcetype .ne. psm_circular)) then must_reset_grid = .true. end if call resize( psm%params, 1, n_source_params_circular ) call resize( psm%grid_size, 1, n_grid_dims_circular ) call resize( psm%params_norm, 1, n_source_params_circular ) psm%params_norm(:) = psm_params_norm_circular(:) if (must_reset_grid) then psm%grid_size = 1 end if if (size(params,1) .ne. size(psm%params)) call die("wrong number of source parameters in psm_set_circular()") if (normalized) then new_params = params * psm%params_norm else new_params = params end if only_moment_changed = (count(new_params .ne. psm%params) .le. 1 .and. new_params(5) .ne. psm%params(5)) psm%params = new_params psm%moment = psm%params(5) call psm_update_dep_params_circular( psm ) end subroutine subroutine psm_update_dep_params_circular( psm ) type(t_psm), intent(inout) :: psm real :: dip, strike, rupdir, rake real, dimension(3) :: pol ! set up rotation matrices, using the eulerian angles ! strike=praezessionswinkel, dip=nutationswinkel, rupdir=drehwinkel strike = d2r(psm%params(6)) dip = d2r(psm%params(7)) rake = d2r(psm%params(8)) rupdir = d2r(psm%params(9)) call init_euler(dip,strike,-rupdir, psm%rotmat_rup) call init_euler(dip,strike,-rake, psm%rotmat_slip) ! p- and t- axis pol = r2d(domeshot(polar(matmul(psm%rotmat_slip,(/ sqrt(2.),0.,-sqrt(2.)/))))) psm%pax(1:2) = pol(2:3) pol = r2d(domeshot(polar(matmul(psm%rotmat_slip,(/-sqrt(2.),0.,-sqrt(2.)/))))) psm%tax(1:2) = pol(2:3) end subroutine subroutine psm_to_tdsm_circular( psm, tdsm, shortest_doi, ok ) ! translate a specific psm to tdsm ! shortest_duration is the shortest duration of interest ! automatically determines shape of output grid type(t_psm), intent(inout) :: psm type(t_tdsm), intent(out) :: tdsm real, intent(in) :: shortest_doi logical, intent(out) :: ok real :: rupvel real :: maxdx, maxdt integer :: nx, ny, nt ok = .true. rupvel = psm%params(10) maxdt = shortest_doi maxdx = 0.5 * shortest_doi * rupvel call psm_to_tdsm_size_circular( psm, maxdx, maxdt, nx, ny, nt ) ! calculate centroid moment tensor density call psm_to_tdsm_table_circular( psm, tdsm, nx,ny,nt ) psm%grid_size(1) = nx psm%grid_size(2) = ny psm%grid_size(3) = nt end subroutine subroutine psm_to_tdsm_size_circular( in, maxdx, maxdt, nx, ny, nt) ! given a psm, determine perfect number of grid points ! based on wanted maxdx, maxdy and maxdt type(t_psm), intent(inout) :: in real, intent(in) :: maxdx, maxdt integer, intent(out) :: nx, ny, nt real dursf, durfull, length, radius, rupvel, risetime radius = in%params(9) rupvel = in%params(10) risetime = in%params(11) length = radius * 2 nx = floor(length/maxdx) + 1 ! need at least 2 points to get partial deriv. depend on width if (nx .le. 1) nx = 2 ! a line source may be made with width=0 if (length .eq. 0.) nx = 1 ny = nx dursf = length/nx/rupvel ! duration of rupture front passing subfault durfull = risetime + dursf ! total duration of rupture on a subfault ! set temporal extension of source grid according to durfull nt = floor(durfull/maxdt) + 1 ! need at least 2 points to get partial deriv. depend on duration if (nt .le. 1) nt = 2 end subroutine subroutine psm_to_tdsm_table_circular( psm, out, nx, ny, nt ) ! translate parameterized source model psm psm ! to centroid table out on a grid of size nx * ny * nt ! nx, ny, nt should be determined by the psm_to_tdsm_size() sub type(t_psm), intent(inout) :: psm type(t_tdsm), intent(out) :: out integer, intent(in) :: nx,ny,nt ! make some aliases to the parameters, so that the code get's readable real :: time, depth, length, rupvel, risetime real :: north, east, radius real, dimension(nx*ny) :: tshift real, dimension(3,nx*ny) :: grid real, dimension(nt) :: wt, toff integer :: ix, iy, it integer :: ip, np, id, nd real :: dt real, dimension(3,3) :: trotmat real, dimension(3) :: p real, dimension(3,3) :: m_rot real, dimension(3,3) :: m_unrot = reshape((/0,0,-1,0,0,0,-1,0,0/),(/3,3/)) type(t_plf) :: stf real :: dursf, durfull, tbeg, ta, tb,r real :: x, y time = psm%params(1) north = psm%params(2) east = psm%params(3) depth = psm%params(4) radius = psm%params(9) rupvel = psm%params(10) risetime = psm%params(11) length = 2*radius ! set up grid. ! it is first layed out in the x-y plane; rupture direction is y ! later it is rotated to the desired orientation ! set up spacial grid, allocate temporary array to hold the coordinates ! lay out the grid, centered in the x-y plane ! let it start at tshift=0 at its bottom border ! must work for width=0 or length=0 for point/line-sources ! grid points are at the center of the subfaults call eikonal_grid_destroy( psm%cgrid ) psm%cgrid%ndims(1) = nx psm%cgrid%ndims(2) = ny allocate( psm%cgrid%points(3,nx,ny) ) ! keep a copy of the stuff in here, so that allocate( psm%cgrid%times(nx,ny) ) ! we can output consistent output files... ip = 1 do ix=1,nx do iy=1,ny x = (2.*(ix-1.)-nx+1.)/(2.*nx) * length y = (2.*(iy-1.)-ny+1.)/(2.*ny) * length r = sqrt( x**2 + y**2 ) p = matmul(psm%rotmat_rup,(/x,y,0./)) + (/north,east,depth/) if (r <= radius) then grid(:,ip) = p(:) tshift(ip) = r/rupvel + time ip = ip+1 psm%cgrid%times(ix,iy) = r/rupvel else psm%cgrid%times(ix,iy) = -1. end if psm%cgrid%points(:,ix,iy) = p(:) end do end do np = ip-1 ! source time function is a convolution of a box of width risetime with ! another box with width of duration of the subfault ! the integral shall be normalized to 1 ! setup piecewise linear function to represent this: dursf = length/nx/rupvel ! duration of subfault if (risetime < dursf) then call plf_make( stf, (-dursf-risetime)/2., 0., & (-dursf+risetime)/2., 1./dursf, & (dursf-risetime)/2., 1./dursf, & (dursf+risetime)/2., 0. ) else call plf_make( stf, (-risetime-dursf)/2., 0., & (-risetime+dursf)/2., 1./risetime, & (risetime-dursf)/2., 1./risetime, & (risetime+dursf)/2., 0. ) end if durfull = dursf+risetime ! total time a subfault is rupturing tbeg = stf%f(1,1) dt = durfull/nt ! weight on each time interval ! and do it=1,nt ta = tbeg+dt*(it-1) tb = tbeg+dt*it call plf_integrate_and_centroid( stf, ta, tb, wt(it), toff(it) ) end do ! all grid points should get the same moment nd = np*nt if (allocated( out%centroids )) deallocate(out%centroids) allocate( out%centroids(nd) ) ! all grid points should get the same moment ! the proper mt is made by rotating a moment tensor ! according to strike, dip and rake trotmat = transpose(psm%rotmat_slip) m_rot = matmul( psm%rotmat_slip, matmul( m_unrot, trotmat ) ) m_rot(:,:) = m_rot(:,:) / np ! fill output arrays id = 1 do ip=1,np do it=1,nt out%centroids(id)%north = grid(1,ip) out%centroids(id)%east = grid(2,ip) out%centroids(id)%depth = grid(3,ip) out%centroids(id)%time = tshift(ip) + toff(it) out%centroids(id)%m(1) = m_rot(1,1)*wt(it) out%centroids(id)%m(2) = m_rot(2,2)*wt(it) out%centroids(id)%m(3) = m_rot(3,3)*wt(it) out%centroids(id)%m(4) = m_rot(1,2)*wt(it) out%centroids(id)%m(5) = m_rot(1,3)*wt(it) out%centroids(id)%m(6) = m_rot(2,3)*wt(it) id = id+1 end do end do end subroutine subroutine psm_write_info_file_circular( psm, fn ) type(t_psm), intent(in) :: psm type(varying_string), intent(in) :: fn integer :: unit, ix,iy real :: north, east, depth, radius integer :: i north = psm%params(2) east = psm%params(3) depth = psm%params(4) radius = psm%params(9) call claim_unit( unit ) open( unit=unit, file=char(fn), status='unknown' ) write (unit,"(a)") "origin" write (unit,*) psm%origin%lat, psm%origin%lon write (unit,*) write (unit,"(a)") "center" write (unit,*) north, east, depth write (unit,*) write (unit,"(a)") "outline" do i=1,36 write (unit,*) matmul(psm%rotmat_rup,(/radius*cos(-i/36.*2.*pi),radius*sin(-i/36.*2.*pi),0./)) & +(/north,east,depth/) end do write (unit,*) write (unit,"(a)") "rupture" write (unit,*) matmul(psm%rotmat_rup,(/0.,0.,0./))+(/north,east,depth/) write (unit,*) matmul(psm%rotmat_rup,(/radius,0.,0./)) write (unit,*) write (unit,"(a)") "slip" ! at position write (unit,*) matmul(psm%rotmat_slip,(/0.,0.,-200./))+(/north, east, depth/) ! slip vector write (unit,*) matmul(psm%rotmat_slip,(/1000.,0.,0./)) ! at position write (unit,*) matmul(psm%rotmat_slip,(/0.,0.,200./))+(/north, east, depth/) ! slip vector write (unit,*) matmul(psm%rotmat_slip,(/-1000.,0.,0./)) write (unit,*) write (unit,"(a)") "p-axis" write (unit,*) psm%pax(:) write (unit,*) write (unit,"(a)") "t-axis" write (unit,*) psm%tax(:) write (unit,*) write (unit,"(a)") "eikonal-grid" write (unit,*) psm%cgrid%ndims(:) do iy=1,size(psm%cgrid%times,2) do ix=1,size(psm%cgrid%times,1) write (unit,*) psm%cgrid%points(:,ix,iy), psm%cgrid%times(ix,iy) end do end do write (unit,*) close( unit ) call release_unit( unit ) end subroutine function polar( xyz ) real, dimension(3), intent(in) :: xyz real, dimension(3) :: polar polar(1) = sqrt(dot_product(xyz,xyz)) polar(2) = atan2(xyz(2),xyz(1)) polar(3) = acos(xyz(3)/polar(1)) end function function domeshot( polar ) real, dimension(3), intent(in) :: polar real, dimension(3) :: domeshot domeshot(1) = polar(1) domeshot(2:3) = wrap(polar(2:3),pi,-pi) if (domeshot(3) > pi/2.) then domeshot(2) = wrap(domeshot(2)+pi,-pi,pi) domeshot(3) = pi-domeshot(3) end if end function elemental function wrap( x, mi, ma ) real, intent(in) :: x, mi, ma real :: wrap wrap = x - floor((x-mi)/(ma-mi)) * (ma-mi) end function end module
= = Destruction of Polish culture = =
program test_menu use, intrinsic:: iso_c_binding, only: c_ptr, c_int use cinter, only: initscr, endwin, nodelay use menu, only: title implicit none (type, external) type(c_ptr) :: stdscr stdscr = initscr() call title() call endwin() end program
Formal statement is: lemma is_nth_power_mult_coprime_natD: fixes a b :: nat assumes "coprime a b" "is_nth_power n (a * b)" "a > 0" "b > 0" shows "is_nth_power n a" "is_nth_power n b" Informal statement is: If $a$ and $b$ are coprime and $a b$ is an $n$th power, then $a$ and $b$ are $n$th powers.
The preamble included the words " it is intended to substitute for the House of Lords as it at present exists a Second Chamber constituted on a popular instead of hereditary basis , but such substitution cannot be immediately brought into operation " at the request of prominent Cabinet member Sir Edward Grey . The long title of the Act was " An Act to make provision with respect to the powers of the House of Lords in relation to those of the House of Commons , and to limit the duration of Parliament . " Section 8 defined the short title as the " Parliament Act 1911 " .
Formal statement is: proposition homotopic_paths_eq: "\<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" Informal statement is: If $p$ is a path in $s$ and $q$ is a path in $s$ such that $p(t) = q(t)$ for all $t \in [0,1]$, then $p$ and $q$ are homotopic paths in $s$.
[STATEMENT] lemma autoref_id[autoref_rules]: "(id,id)\<in>R\<rightarrow>R" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (id, id) \<in> R \<rightarrow> R [PROOF STEP] by auto
------------------------------------------------------------------------ -- Various constants ------------------------------------------------------------------------ open import Atom module Constants (atoms : χ-atoms) where open χ-atoms atoms c-zero : Const c-zero = C.name 0 c-suc : Const c-suc = C.name 1 c-nil : Const c-nil = C.name 2 c-cons : Const c-cons = C.name 3 c-apply : Const c-apply = C.name 4 c-case : Const c-case = C.name 5 c-rec : Const c-rec = C.name 6 c-lambda : Const c-lambda = C.name 7 c-const : Const c-const = C.name 8 c-var : Const c-var = C.name 9 c-branch : Const c-branch = C.name 10 c-true : Const c-true = C.name 11 c-false : Const c-false = C.name 12 c-pair : Const c-pair = C.name 13 v-equal : Var v-equal = V.name 0 v-m : Var v-m = V.name 1 v-n : Var v-n = V.name 2 v-x : Var v-x = V.name 3 v-new : Var v-new = V.name 4 v-e : Var v-e = V.name 5 v-subst : Var v-subst = V.name 6 v-e₁ : Var v-e₁ = V.name 7 v-e₂ : Var v-e₂ = V.name 8 v-bs : Var v-bs = V.name 9 v-y : Var v-y = V.name 10 v-c : Var v-c = V.name 11 v-es : Var v-es = V.name 12 v-ys : Var v-ys = V.name 13 v-member : Var v-member = V.name 14 v-xs : Var v-xs = V.name 15 v-lookup : Var v-lookup = V.name 16 v-b : Var v-b = V.name 17 v-c′ : Var v-c′ = V.name 18 v-underscore : Var v-underscore = V.name 19 v-substs : Var v-substs = V.name 20 v-e′ : Var v-e′ = V.name 21 v-map : Var v-map = V.name 22 v-p : Var v-p = V.name 23 v-eval : Var v-eval = V.name 24 v-internal-code : Var v-internal-code = V.name 25 v-halts : Var v-halts = V.name 26 v-z : Var v-z = V.name 27 v-f : Var v-f = V.name 28 v-g : Var v-g = V.name 29
[STATEMENT] lemma HStartBallot_HInv5_p: assumes act: "HStartBallot s s' p" and inv: "HInv5_inner s p" shows "HInv5_inner s' p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. HInv5_inner s' p [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: HStartBallot s s' p HInv5_inner s p goal (1 subgoal): 1. HInv5_inner s' p [PROOF STEP] by(auto simp add: StartBallot_def HInv5_inner_def)
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.monad.basic import data.int.basic import data.stream.defs import control.uliftable import tactic.norm_num import data.bitvec.basic /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) := (random [] : Π (g : Type) [random_gen g], rand_g g α) /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [fact (0 < n)] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← le_tsub_iff_right hxy; apply le_of_succ_le_succ z.is_lt⟩ } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ instance int_bounded_random : bounded_random ℤ := { random_r := λ g inst x y hxy, do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial, pure ⟨z + x, int.le_add_of_nonneg_left (int.coe_nat_nonneg _), int.add_le_of_le_sub_right $ le_trans (int.coe_nat_le_coe_nat_of_le h₁) (le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ } instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := { random := λ g inst, @fin.random g inst _ _ } instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := { random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (nat.not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) } instance : bounded_random bool := { random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } open_locale fin_fact /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n } instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := { random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
module Foos import SearchLight: AbstractModel, DbId import Base: @kwdef export Foo @kwdef mutable struct Foo <: AbstractModel id::DbId = DbId() end end
{-# OPTIONS --without-K --safe #-} -- Defines Restriction Category -- https://ncatlab.org/nlab/show/restriction+category -- but see also -- https://github.com/jmchapman/restriction-categories -- Notation choice: one of the interpretations is that the -- restriction structure captures the "domain of definedness" -- of a morphism, as a (partial) identity. As this is positive -- information, we will use f ↓ (as a postfix operation) to -- denote this. Note that computability theory uses the same -- notation to mean definedness. -- Note, as we're working in Setoid-Enriched Categories, we need -- to add an explicit axiom, that ↓ preserves ≈ module Categories.Category.Restriction where open import Level using (Level; _⊔_) open import Categories.Category.Core using (Category) private variable o ℓ e : Level record Restriction (C : Category o ℓ e) : Set (o ⊔ ℓ ⊔ e) where open Category C using (Obj; _⇒_; _∘_; _≈_; id) field _↓ : {A B : Obj} → A ⇒ B → A ⇒ A -- partial identity on the right pidʳ : {A B : Obj} {f : A ⇒ B} → f ∘ f ↓ ≈ f -- the domain-of-definition arrows commute ↓-comm : {A B C : Obj} {f : A ⇒ B} {g : A ⇒ C} → f ↓ ∘ g ↓ ≈ g ↓ ∘ f ↓ -- domain-of-definition denests (on the right) ↓-denestʳ : {A B C : Obj} {f : A ⇒ B} {g : A ⇒ C} → (g ∘ f ↓) ↓ ≈ g ↓ ∘ f ↓ -- domain-of-definition has a skew-commutative law ↓-skew-comm : {A B C : Obj} {g : A ⇒ B} {f : C ⇒ A} → g ↓ ∘ f ≈ f ∘ (g ∘ f) ↓ -- and the new axiom, ↓ is a congruence ↓-cong : {A B : Obj} {f g : A ⇒ B} → f ≈ g → f ↓ ≈ g ↓ -- it is convenient to define the total predicate in this context total : {A B : Obj} (f : A ⇒ B) → Set e total f = f ↓ ≈ id
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison ! This file was ported from Lean 3 source module data.vector.zip ! leanprover-community/mathlib commit 1126441d6bccf98c81214a0780c73d499f6721fe ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Vector.Basic import Mathlib.Data.List.Zip /-! # The `zipWith` operation on vectors. -/ namespace Vector section ZipWith variable {α β γ : Type _} {n : ℕ} (f : α → β → γ) /-- Apply the function `f : α → β → γ` to each corresponding pair of elements from two vectors. -/ def zipWith : Vector α n → Vector β n → Vector γ n := fun x y => ⟨List.zipWith f x.1 y.1, by simp⟩ #align vector.zip_with Vector.zipWith @[simp] theorem zipWith_toList (x : Vector α n) (y : Vector β n) : (Vector.zipWith f x y).toList = List.zipWith f x.toList y.toList := rfl #align vector.zip_with_to_list Vector.zipWith_toList @[simp] theorem zipWith_get (x : Vector α n) (y : Vector β n) (i) : (Vector.zipWith f x y).get i = f (x.get i) (y.get i) := by dsimp only [Vector.zipWith, Vector.get] cases x; cases y simp only [List.nthLe_zipWith] #align vector.zip_with_nth Vector.zipWith_get @[simp] theorem zipWith_tail (x : Vector α n) (y : Vector β n) : (Vector.zipWith f x y).tail = Vector.zipWith f x.tail y.tail := by ext simp [get_tail] #align vector.zip_with_tail Vector.zipWith_tail @[to_additive] theorem prod_mul_prod_eq_prod_zipWith [CommMonoid α] (x y : Vector α n) : x.toList.prod * y.toList.prod = (Vector.zipWith (· * ·) x y).toList.prod := List.prod_mul_prod_eq_prod_zipWith_of_length_eq x.toList y.toList ((toList_length x).trans (toList_length y).symm) #align vector.prod_mul_prod_eq_prod_zip_with Vector.prod_mul_prod_eq_prod_zipWith #align vector.sum_add_sum_eq_sum_zip_with Vector.sum_add_sum_eq_sum_zipWith end ZipWith end Vector
-- Andreas, 2014-11-08 -- This used to be a failed test case, but works now. open import Common.Prelude postulate some : Nat data D : Nat → Set where d₀ : D some d₁ : D (suc some) f : (n : Nat) → D n → Nat f .some d₀ = zero f .(suc some) d₁ = f some d₀ -- Since x < suc x for all x in the structural order, -- some < suc some is a valid descent.
%SoundSubCodes SoundSubCodes enumeration for the brick % % Notes:: % - SoundSubCodes can be found in the EV3 documentation and source code % (bytecodes.h) classdef SoundSubCodes < uint8 enumeration Break (0) Tone (1) Play (2) Repeat (3) Service (4) end end
theory Defs imports "HOL-Library.Extended_Real" begin type_synonym val = "ereal option" datatype bound = NegInf ("\<infinity>\<^sup>-") | PosInf ("\<infinity>\<^sup>+") | NaN | Real lemma UNIV_bound: "UNIV = {\<infinity>\<^sup>-,\<infinity>\<^sup>+,NaN,Real}" by (smt (verit, best) UNIV_eq_I bound.exhaust insert_iff) instantiation bound :: enum begin definition "enum_bound = [\<infinity>\<^sup>-,\<infinity>\<^sup>+,NaN,Real]" definition "enum_all_bound P \<equiv> P \<infinity>\<^sup>- \<and> P \<infinity>\<^sup>+ \<and> P NaN \<and> P Real" definition "enum_ex_bound P \<equiv> P \<infinity>\<^sup>- \<or> P \<infinity>\<^sup>+ \<or> P NaN \<or> P Real" instance by standard (auto simp: enum_bound_def enum_all_bound_def enum_ex_bound_def UNIV_bound) end datatype bounds = B "bound set" fun \<gamma>_bound :: "bound \<Rightarrow> val set" where "\<gamma>_bound \<infinity>\<^sup>- = {Some (- \<infinity>)}" | "\<gamma>_bound \<infinity>\<^sup>+ = {Some \<infinity>}" | "\<gamma>_bound NaN = {None}" | "\<gamma>_bound Real = {Some r|r. r\<in>\<real>}" fun \<gamma>_bounds :: "bounds \<Rightarrow> val set" where "\<gamma>_bounds (B bnds) = \<Union> (\<gamma>_bound ` bnds)" fun num_bound :: "ereal \<Rightarrow> bound" where "num_bound PInfty = \<infinity>\<^sup>+" | "num_bound MInfty = \<infinity>\<^sup>-" | "num_bound (ereal r) = Real" definition num_bounds :: "ereal \<Rightarrow> bounds" where "num_bounds v = B {num_bound v}" fun plus_bound :: "bound \<Rightarrow> bound \<Rightarrow> bound" where "plus_bound NaN _ = NaN" | "plus_bound _ NaN = NaN" | "plus_bound \<infinity>\<^sup>- \<infinity>\<^sup>+ = NaN" | "plus_bound \<infinity>\<^sup>+ \<infinity>\<^sup>- = NaN" | "plus_bound \<infinity>\<^sup>- _ = \<infinity>\<^sup>-" | "plus_bound _ \<infinity>\<^sup>- = \<infinity>\<^sup>-" | "plus_bound _ \<infinity>\<^sup>+ = \<infinity>\<^sup>+" | "plus_bound \<infinity>\<^sup>+ _ = \<infinity>\<^sup>+" | "plus_bound Real Real = Real" fun plus_bounds :: "bounds \<Rightarrow> bounds \<Rightarrow> bounds" where "plus_bounds (B X) (B Y) = B {plus_bound a b | a b. a \<in> X \<and> b \<in> Y}" lemma minfty_bound[simp]: "Some (- \<infinity>) \<in> \<gamma>_bound bd \<longleftrightarrow> bd = \<infinity>\<^sup>-" by (cases bd; auto) lemma pinfty_bound[simp]: "Some (\<infinity>) \<in> \<gamma>_bound bd \<longleftrightarrow> bd = \<infinity>\<^sup>+" by (cases bd; auto) lemma NaN_bound[simp]: "None \<in> \<gamma>_bound bd \<longleftrightarrow> bd = NaN" by (cases bd; auto) lemma Real_bound[simp]: "Some (ereal r) \<in> \<gamma>_bound bd \<longleftrightarrow> bd = Real" by (cases bd; auto simp: Reals_def) consts inv_plus' :: "bounds \<Rightarrow> bounds \<Rightarrow> bounds \<Rightarrow> (bounds * bounds)" consts inv_less' :: "bool option \<Rightarrow> bounds \<Rightarrow> bounds \<Rightarrow> (bounds * bounds)" end
-- Andreas, 2018-11-03, issue #3361 -- -- Empty variable blocks should trigger warning rather than parse error. variable -- Expected warning: -- Empty variable block.
[STATEMENT] lemma fv_not_fresh: "atom x \<sharp> e \<longleftrightarrow> x \<notin> fv e" [PROOF STATE] proof (prove) goal (1 subgoal): 1. atom x \<sharp> e = (x \<notin> fv e) [PROOF STEP] unfolding fv_def fresh_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (atom x \<notin> supp e) = (x \<notin> {v. atom v \<in> supp e}) [PROOF STEP] by blast
Require Export Fiat.Common.Coq__8_4__8_5__Compat. (** Fixed precision machine words *) Require Import Coq.Arith.Arith Coq.Arith.Div2 Coq.NArith.NArith Coq.Bool.Bool Coq.ZArith.ZArith. Require Import Bedrock.Nomega. Set Implicit Arguments. (** * Basic definitions and conversion to and from [nat] *) Inductive word : nat -> Set := | WO : word O | WS : bool -> forall n, word n -> word (S n). Fixpoint wordToNat sz (w : word sz) : nat := match w with | WO => O | WS false w' => (wordToNat w') * 2 | WS true w' => S (wordToNat w' * 2) end. Fixpoint wordToNat' sz (w : word sz) : nat := match w with | WO => O | WS false w' => 2 * wordToNat w' | WS true w' => S (2 * wordToNat w') end. Theorem wordToNat_wordToNat' : forall sz (w : word sz), wordToNat w = wordToNat' w. Proof. induction w. auto. simpl. rewrite mult_comm. reflexivity. Qed. Fixpoint mod2 (n : nat) : bool := match n with | 0 => false | 1 => true | S (S n') => mod2 n' end. Fixpoint natToWord (sz n : nat) : word sz := match sz with | O => WO | S sz' => WS (mod2 n) (natToWord sz' (div2 n)) end. Fixpoint wordToN sz (w : word sz) : N := match w with | WO => 0 | WS false w' => 2 * wordToN w' | WS true w' => N.succ (2 * wordToN w') end%N. Definition Nmod2 (n : N) : bool := match n with | N0 => false | Npos (xO _) => false | _ => true end. Definition wzero sz := natToWord sz 0. Fixpoint wzero' (sz : nat) : word sz := match sz with | O => WO | S sz' => WS false (wzero' sz') end. Fixpoint posToWord (sz : nat) (p : positive) {struct p} : word sz := match sz with | O => WO | S sz' => match p with | xI p' => WS true (posToWord sz' p') | xO p' => WS false (posToWord sz' p') | xH => WS true (wzero' sz') end end. Definition NToWord (sz : nat) (n : N) : word sz := match n with | N0 => wzero' sz | Npos p => posToWord sz p end. Fixpoint Npow2 (n : nat) : N := match n with | O => 1 | S n' => 2 * Npow2 n' end%N. Ltac rethink := match goal with | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto end. Theorem mod2_S_double : forall n, mod2 (S (2 * n)) = true. induction n; simpl; intuition; rethink. Qed. Theorem mod2_double : forall n, mod2 (2 * n) = false. induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink. Qed. Local Hint Resolve mod2_S_double mod2_double. Theorem div2_double : forall n, div2 (2 * n) = n. induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink. Qed. Theorem div2_S_double : forall n, div2 (S (2 * n)) = n. induction n; simpl; intuition; f_equal; rethink. Qed. Hint Rewrite div2_double div2_S_double : div2. Theorem natToWord_wordToNat : forall sz w, natToWord sz (wordToNat w) = w. induction w; rewrite wordToNat_wordToNat'; intuition; f_equal; unfold natToWord, wordToNat'; fold natToWord; fold wordToNat'; destruct b; f_equal; autorewrite with div2; intuition. Qed. Fixpoint pow2 (n : nat) : nat := match n with | O => 1 | S n' => 2 * pow2 n' end. Theorem roundTrip_0 : forall sz, wordToNat (natToWord sz 0) = 0. induction sz; simpl; intuition. Qed. Hint Rewrite roundTrip_0 : wordToNat. Local Hint Extern 1 (@eq nat _ _) => omega. Theorem untimes2 : forall n, n + (n + 0) = 2 * n. auto. Qed. Section strong. Variable P : nat -> Prop. Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n. Lemma strong' : forall n m, m <= n -> P m. induction n; simpl; intuition; apply PH; intuition. exfalso; omega. Qed. Theorem strong : forall n, P n. intros; eapply strong'; eauto. Qed. End strong. Theorem div2_odd : forall n, mod2 n = true -> n = S (2 * div2 n). induction n using strong; simpl; intuition. destruct n; simpl in *; intuition. try discriminate. destruct n; simpl in *; intuition. do 2 f_equal. replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto. Qed. Theorem div2_even : forall n, mod2 n = false -> n = 2 * div2 n. induction n using strong; simpl; intuition. destruct n; simpl in *; intuition. destruct n; simpl in *; intuition. try discriminate. f_equal. replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto. Qed. Lemma wordToNat_natToWord' : forall sz w, exists k, wordToNat (natToWord sz w) + k * pow2 sz = w. induction sz; simpl; intuition; repeat rewrite untimes2. exists w; intuition. case_eq (mod2 w); intro Hmw. specialize (IHsz (div2 w)); firstorder. rewrite wordToNat_wordToNat' in *. exists x; intuition. rewrite mult_assoc. rewrite (mult_comm x 2). rewrite mult_comm. simpl mult at 1. rewrite (plus_Sn_m (2 * wordToNat' (natToWord sz (div2 w)))). rewrite <- mult_assoc. rewrite <- mult_plus_distr_l. rewrite H; clear H. symmetry; apply div2_odd; auto. specialize (IHsz (div2 w)); firstorder. exists x; intuition. rewrite mult_assoc. rewrite (mult_comm x 2). rewrite <- mult_assoc. rewrite mult_comm. rewrite <- mult_plus_distr_l. rewrite H; clear H. symmetry; apply div2_even; auto. Qed. Theorem wordToNat_natToWord : forall sz w, exists k, wordToNat (natToWord sz w) = w - k * pow2 sz /\ k * pow2 sz <= w. intros; destruct (wordToNat_natToWord' sz w) as [k]; exists k; intuition. Qed. Definition wone sz := natToWord sz 1. Fixpoint wones (sz : nat) : word sz := match sz with | O => WO | S sz' => WS true (wones sz') end. (** Comparisons *) Fixpoint wmsb sz (w : word sz) (a : bool) : bool := match w with | WO => a | WS b x => wmsb x b end. Definition whd sz (w : word (S sz)) : bool := match w in word sz' return match sz' with | O => unit | S _ => bool end with | WO => tt | WS b _ => b end. Definition wtl sz (w : word (S sz)) : word sz := match w in word sz' return match sz' with | O => unit | S sz'' => word sz'' end with | WO => tt | WS _ w' => w' end. Theorem WS_neq : forall b1 b2 sz (w1 w2 : word sz), (b1 <> b2 \/ w1 <> w2) -> WS b1 w1 <> WS b2 w2. intuition. apply (f_equal (@whd _)) in H0; tauto. apply (f_equal (@wtl _)) in H0; tauto. Qed. (** Shattering **) Lemma shatter_word : forall n (a : word n), match n return word n -> Prop with | O => fun a => a = WO | S _ => fun a => a = WS (whd a) (wtl a) end a. destruct a; eauto. Qed. Lemma shatter_word_S : forall n (a : word (S n)), exists b, exists c, a = WS b c. Proof. intros; repeat eexists; apply (shatter_word a). Qed. Lemma shatter_word_0 : forall a : word 0, a = WO. Proof. intros; apply (shatter_word a). Qed. Hint Resolve shatter_word_0. Require Import Coq.Logic.Eqdep_dec. Definition weq : forall sz (x y : word sz), {x = y} + {x <> y}. refine (fix weq sz (x : word sz) : forall y : word sz, {x = y} + {x <> y} := match x in word sz return forall y : word sz, {x = y} + {x <> y} with | WO => fun _ => left _ _ | WS b x' => fun y => if bool_dec b (whd y) then if weq _ x' (wtl y) then left _ _ else right _ _ else right _ _ end); clear weq. abstract (symmetry; apply shatter_word_0). abstract (subst; symmetry; apply (shatter_word y)). abstract (rewrite (shatter_word y); simpl; intro; injection H; intros; apply n0; apply inj_pair2_eq_dec in H0; [ auto | apply eq_nat_dec ]). abstract (rewrite (shatter_word y); simpl; intro; apply n0; injection H; auto). Defined. Fixpoint weqb sz (x : word sz) : word sz -> bool := match x in word sz return word sz -> bool with | WO => fun _ => true | WS b x' => fun y => if eqb b (whd y) then if @weqb _ x' (wtl y) then true else false else false end. Theorem weqb_true_iff : forall sz x y, @weqb sz x y = true <-> x = y. Proof. induction x; simpl; intros. { split; auto. } { rewrite (shatter_word y) in *. simpl in *. case_eq (eqb b (whd y)); intros. case_eq (weqb x (wtl y)); intros. split; auto; intros. rewrite eqb_true_iff in H. f_equal; eauto. eapply IHx; eauto. split; intros; try congruence. inversion H1; clear H1; subst. eapply inj_pair2_eq_dec in H4. eapply IHx in H4. congruence. eapply Peano_dec.eq_nat_dec. split; intros; try congruence. inversion H0. apply eqb_false_iff in H. congruence. } Qed. (** * Combining and splitting *) Fixpoint combine (sz1 : nat) (w : word sz1) : forall sz2, word sz2 -> word (sz1 + sz2) := match w in word sz1 return forall sz2, word sz2 -> word (sz1 + sz2) with | WO => fun _ w' => w' | WS b w' => fun _ w'' => WS b (combine w' w'') end. Fixpoint split1 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz1 := match sz1 with | O => fun _ => WO | S sz1' => fun w => WS (whd w) (split1 sz1' sz2 (wtl w)) end. Fixpoint split2 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz2 := match sz1 with | O => fun w => w | S sz1' => fun w => split2 sz1' sz2 (wtl w) end. Ltac shatterer := simpl; intuition; match goal with | [ w : _ |- _ ] => rewrite (shatter_word w); simpl end; f_equal; auto. Theorem combine_split : forall sz1 sz2 (w : word (sz1 + sz2)), combine (split1 sz1 sz2 w) (split2 sz1 sz2 w) = w. induction sz1; shatterer. Qed. Theorem split1_combine : forall sz1 sz2 (w : word sz1) (z : word sz2), split1 sz1 sz2 (combine w z) = w. induction sz1; shatterer. Qed. Theorem split2_combine : forall sz1 sz2 (w : word sz1) (z : word sz2), split2 sz1 sz2 (combine w z) = z. induction sz1; shatterer. Qed. Require Import Coq.Logic.Eqdep_dec. Theorem combine_assoc : forall n1 (w1 : word n1) n2 n3 (w2 : word n2) (w3 : word n3) Heq, combine (combine w1 w2) w3 = match Heq in _ = N return word N with | refl_equal => combine w1 (combine w2 w3) end. induction w1; simpl; intuition. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity. rewrite (IHw1 _ _ _ _ (plus_assoc _ _ _)); clear IHw1. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. generalize dependent (combine w1 (combine w2 w3)). rewrite plus_assoc; intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. Theorem split2_iter : forall n1 n2 n3 Heq w, split2 n2 n3 (split2 n1 (n2 + n3) w) = split2 (n1 + n2) n3 (match Heq in _ = N return word N with | refl_equal => w end). induction n1; simpl; intuition. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity. rewrite (IHn1 _ _ (plus_assoc _ _ _)). f_equal. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. generalize dependent w. simpl. fold plus. generalize (n1 + (n2 + n3)); clear. intros. generalize Heq e. subst. intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. Theorem combine_end : forall n1 n2 n3 Heq w, combine (split1 n2 n3 (split2 n1 (n2 + n3) w)) (split2 (n1 + n2) n3 (match Heq in _ = N return word N with | refl_equal => w end)) = split2 n1 (n2 + n3) w. induction n1; simpl; intros. rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)). apply combine_split. rewrite (shatter_word w) in *. simpl. eapply trans_eq; [ | apply IHn1 with (Heq := plus_assoc _ _ _) ]; clear IHn1. repeat f_equal. repeat match goal with | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf end. simpl. generalize dependent w. rewrite plus_assoc. intros. rewrite (UIP_dec eq_nat_dec e (refl_equal _)). rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)). reflexivity. Qed. (** * Extension operators *) Definition sext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') := if wmsb w false then combine w (wones sz') else combine w (wzero sz'). Definition zext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') := combine w (wzero sz'). (** * Arithmetic *) Definition wneg sz (x : word sz) : word sz := NToWord sz (Npow2 sz - wordToN x). Definition wordBin (f : N -> N -> N) sz (x y : word sz) : word sz := NToWord sz (f (wordToN x) (wordToN y)). Definition wplus := wordBin Nplus. Definition wmult := wordBin Nmult. Definition wmult' sz (x y : word sz) : word sz := split2 sz sz (NToWord (sz + sz) (Nmult (wordToN x) (wordToN y))). Definition wminus sz (x y : word sz) : word sz := wplus x (wneg y). Definition wnegN sz (x : word sz) : word sz := natToWord sz (pow2 sz - wordToNat x). Definition wordBinN (f : nat -> nat -> nat) sz (x y : word sz) : word sz := natToWord sz (f (wordToNat x) (wordToNat y)). Definition wplusN := wordBinN plus. Definition wmultN := wordBinN mult. Definition wmultN' sz (x y : word sz) : word sz := split2 sz sz (natToWord (sz + sz) (mult (wordToNat x) (wordToNat y))). Definition wminusN sz (x y : word sz) : word sz := wplusN x (wnegN y). (** * Notations *) Delimit Scope word_scope with word. Bind Scope word_scope with word. Notation "w ~ 1" := (WS true w) (at level 7, left associativity, format "w '~' '1'") : word_scope. Notation "w ~ 0" := (WS false w) (at level 7, left associativity, format "w '~' '0'") : word_scope. Notation "^~" := wneg. Notation "l ^+ r" := (@wplus _ l%word r%word) (at level 50, left associativity). Notation "l ^* r" := (@wmult _ l%word r%word) (at level 40, left associativity). Notation "l ^- r" := (@wminus _ l%word r%word) (at level 50, left associativity). Theorem wordToN_nat : forall sz (w : word sz), wordToN w = N_of_nat (wordToNat w). induction w; intuition. destruct b; unfold wordToN, wordToNat; fold wordToN; fold wordToNat. rewrite N_of_S. rewrite N_of_mult. rewrite <- IHw. rewrite Nmult_comm. reflexivity. rewrite N_of_mult. rewrite <- IHw. rewrite Nmult_comm. reflexivity. Qed. Theorem mod2_S : forall n k, 2 * k = S n -> mod2 n = true. induction n using strong; intros. destruct n; simpl in *. exfalso; omega. destruct n; simpl in *; auto. destruct k; simpl in *. discriminate. apply H with k; auto. Qed. Theorem wzero'_def : forall sz, wzero' sz = wzero sz. unfold wzero; induction sz; simpl; intuition. congruence. Qed. Theorem posToWord_nat : forall p sz, posToWord sz p = natToWord sz (nat_of_P p). induction p; destruct sz; simpl; intuition; f_equal; try rewrite wzero'_def in *. rewrite ZL6. destruct (ZL4 p) as [? Heq]; rewrite Heq; simpl. replace (x + S x) with (S (2 * x)) by omega. symmetry; apply mod2_S_double. rewrite IHp. rewrite ZL6. destruct (nat_of_P p); simpl; intuition. replace (n + S n) with (S (2 * n)) by omega. rewrite div2_S_double; auto. unfold nat_of_P; simpl. rewrite ZL6. replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega. symmetry; apply mod2_double. rewrite IHp. unfold nat_of_P; simpl. rewrite ZL6. replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega. rewrite div2_double. auto. auto. Qed. Theorem NToWord_nat : forall sz n, NToWord sz n = natToWord sz (nat_of_N n). destruct n; simpl; intuition; try rewrite wzero'_def in *. auto. apply posToWord_nat. Qed. Theorem wplus_alt : forall sz (x y : word sz), wplus x y = wplusN x y. unfold wplusN, wplus, wordBinN, wordBin; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nplus. repeat rewrite nat_of_N_of_nat. reflexivity. Qed. Theorem wmult_alt : forall sz (x y : word sz), wmult x y = wmultN x y. unfold wmultN, wmult, wordBinN, wordBin; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nmult. repeat rewrite nat_of_N_of_nat. reflexivity. Qed. Theorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n. induction n; simpl; intuition. rewrite <- IHn; clear IHn. case_eq (Npow2 n); intuition; rewrite untimes2; replace (Npos p~0) with (N.double (Npos p)) by reflexivity; apply nat_of_Ndouble. Qed. Theorem wneg_alt : forall sz (x : word sz), wneg x = wnegN x. unfold wnegN, wneg; intros. repeat rewrite wordToN_nat; repeat rewrite NToWord_nat. rewrite nat_of_Nminus. do 2 f_equal. apply Npow2_nat. apply nat_of_N_of_nat. Qed. Theorem wminus_Alt : forall sz (x y : word sz), wminus x y = wminusN x y. intros; unfold wminusN, wminus; rewrite wneg_alt; apply wplus_alt. Qed. Theorem wplus_unit : forall sz (x : word sz), natToWord sz 0 ^+ x = x. intros; rewrite wplus_alt; unfold wplusN, wordBinN; intros. rewrite roundTrip_0; apply natToWord_wordToNat. Qed. Theorem wplus_comm : forall sz (x y : word sz), x ^+ y = y ^+ x. intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; f_equal; auto. Qed. Theorem drop_mod2 : forall n k, 2 * k <= n -> mod2 (n - 2 * k) = mod2 n. induction n using strong; intros. do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition). destruct k; simpl in *; intuition. destruct k; simpl; intuition. rewrite <- plus_n_Sm. repeat rewrite untimes2 in *. simpl; auto. apply H; omega. Qed. Theorem div2_minus_2 : forall n k, 2 * k <= n -> div2 (n - 2 * k) = div2 n - k. induction n using strong; intros. do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *). destruct k; simpl in *; intuition. destruct k; simpl in *; intuition. rewrite <- plus_n_Sm. apply H; omega. Qed. Theorem div2_bound : forall k n, 2 * k <= n -> k <= div2 n. intros; case_eq (mod2 n); intro Heq. rewrite (div2_odd _ Heq) in H. omega. rewrite (div2_even _ Heq) in H. omega. Qed. Theorem drop_sub : forall sz n k, k * pow2 sz <= n -> natToWord sz (n - k * pow2 sz) = natToWord sz n. induction sz; simpl; intuition; repeat rewrite untimes2 in *; f_equal. rewrite mult_assoc. rewrite (mult_comm k). rewrite <- mult_assoc. apply drop_mod2. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. rewrite <- (IHsz (div2 n) k). rewrite mult_assoc. rewrite (mult_comm k). rewrite <- mult_assoc. rewrite div2_minus_2. reflexivity. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. apply div2_bound. rewrite mult_assoc. rewrite (mult_comm 2). rewrite <- mult_assoc. auto. Qed. Local Hint Extern 1 (_ <= _) => omega. Theorem wplus_assoc : forall sz (x y z : word sz), x ^+ (y ^+ z) = x ^+ y ^+ z. intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. replace (wordToNat x + wordToNat y - x1 * pow2 sz + wordToNat z) with (wordToNat x + wordToNat y + wordToNat z - x1 * pow2 sz) by auto. replace (wordToNat x + (wordToNat y + wordToNat z - x0 * pow2 sz)) with (wordToNat x + wordToNat y + wordToNat z - x0 * pow2 sz) by auto. repeat rewrite drop_sub; auto. Qed. Theorem roundTrip_1 : forall sz, wordToNat (natToWord (S sz) 1) = 1. induction sz; simpl in *; intuition. Qed. Theorem mod2_WS : forall sz (x : word sz) b, mod2 (wordToNat (WS b x)) = b. intros. rewrite wordToNat_wordToNat'. destruct b; simpl. rewrite untimes2. case_eq (2 * wordToNat x); intuition. eapply mod2_S; eauto. rewrite <- (mod2_double (wordToNat x)); f_equal; omega. Qed. Theorem div2_WS : forall sz (x : word sz) b, div2 (wordToNat (WS b x)) = wordToNat x. destruct b; rewrite wordToNat_wordToNat'; unfold wordToNat'; fold wordToNat'. apply div2_S_double. apply div2_double. Qed. Theorem wmult_unit : forall sz (x : word sz), natToWord sz 1 ^* x = x. intros; rewrite wmult_alt; unfold wmultN, wordBinN; intros. destruct sz; simpl. rewrite (shatter_word x); reflexivity. rewrite roundTrip_0; simpl. rewrite plus_0_r. rewrite (shatter_word x). f_equal. apply mod2_WS. rewrite div2_WS. apply natToWord_wordToNat. Qed. Theorem wmult_comm : forall sz (x y : word sz), x ^* y = y ^* x. intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; auto with arith. Qed. Theorem wmult_assoc : forall sz (x y z : word sz), x ^* (y ^* z) = x ^* y ^* z. intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. rewrite mult_minus_distr_l. rewrite mult_minus_distr_r. rewrite (mult_assoc (wordToNat x) x0). rewrite <- (mult_assoc x1). rewrite (mult_comm (pow2 sz)). rewrite (mult_assoc x1). repeat rewrite drop_sub; auto with arith. rewrite (mult_comm x1). rewrite <- (mult_assoc (wordToNat x)). rewrite (mult_comm (wordToNat y)). rewrite mult_assoc. rewrite (mult_comm (wordToNat x)). repeat rewrite <- mult_assoc. auto with arith. repeat rewrite <- mult_assoc. auto with arith. Qed. Theorem wmult_plus_distr : forall sz (x y z : word sz), (x ^+ y) ^* z = (x ^* z) ^+ (y ^* z). intros; repeat rewrite wmult_alt; repeat rewrite wplus_alt; unfold wmultN, wplusN, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. rewrite mult_minus_distr_r. rewrite <- (mult_assoc x0). rewrite (mult_comm (pow2 sz)). rewrite (mult_assoc x0). replace (wordToNat x * wordToNat z - x1 * pow2 sz + (wordToNat y * wordToNat z - x2 * pow2 sz)) with (wordToNat x * wordToNat z + wordToNat y * wordToNat z - x1 * pow2 sz - x2 * pow2 sz). repeat rewrite drop_sub; auto with arith. rewrite (mult_comm x0). rewrite (mult_comm (wordToNat x + wordToNat y)). rewrite <- (mult_assoc (wordToNat z)). auto with arith. generalize dependent (wordToNat x * wordToNat z). generalize dependent (wordToNat y * wordToNat z). intros. omega. Qed. Theorem wminus_def : forall sz (x y : word sz), x ^- y = x ^+ ^~ y. reflexivity. Qed. Theorem wordToNat_bound : forall sz (w : word sz), wordToNat w < pow2 sz. induction w; simpl; intuition. destruct b; simpl; omega. Qed. Theorem natToWord_pow2 : forall sz, natToWord sz (pow2 sz) = natToWord sz 0. induction sz; simpl; intuition. generalize (div2_double (pow2 sz)); simpl; intro Hr; rewrite Hr; clear Hr. f_equal. generalize (mod2_double (pow2 sz)); auto. auto. Qed. Theorem wminus_inv : forall sz (x : word sz), x ^+ ^~ x = wzero sz. intros; rewrite wneg_alt; rewrite wplus_alt; unfold wnegN, wplusN, wzero, wordBinN; intros. repeat match goal with | [ |- context[wordToNat (natToWord ?sz ?w)] ] => let Heq := fresh "Heq" in destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq end. replace (wordToNat x + (pow2 sz - wordToNat x - x0 * pow2 sz)) with (pow2 sz - x0 * pow2 sz). rewrite drop_sub; auto with arith. apply natToWord_pow2. generalize (wordToNat_bound x). omega. Qed. Definition wring (sz : nat) : ring_theory (wzero sz) (wone sz) (@wplus sz) (@wmult sz) (@wminus sz) (@wneg sz) (@eq _) := mk_rt _ _ _ _ _ _ _ (@wplus_unit _) (@wplus_comm _) (@wplus_assoc _) (@wmult_unit _) (@wmult_comm _) (@wmult_assoc _) (@wmult_plus_distr _) (@wminus_def _) (@wminus_inv _). Theorem weqb_sound : forall sz (x y : word sz), weqb x y = true -> x = y. Proof. eapply weqb_true_iff. Qed. Ltac isWcst w := match eval hnf in w with | WO => constr:(true) | WS ?b ?w' => match eval hnf in b with | true => isWcst w' | false => isWcst w' | _ => constr:(false) end | _ => constr:(false) end. Ltac wcst w := let b := isWcst w in match b with | true => w | _ => constr:(NotConstant) end. (* Here's how you can add a ring for a specific bit-width. There doesn't seem to be a polymorphic method, so this code really does need to be copied. *) (* Definition wring8 := wring 8. Add Ring wring8 : wring8 (decidable (weqb_sound 8), constants [wcst]). *) (** * Bitwise operators *) Fixpoint wnot sz (w : word sz) : word sz := match w with | WO => WO | WS b w' => WS (negb b) (wnot w') end. Fixpoint bitwp (f : bool -> bool -> bool) sz (w1 : word sz) : word sz -> word sz := match w1 with | WO => fun _ => WO | WS b w1' => fun w2 => WS (f b (whd w2)) (bitwp f w1' (wtl w2)) end. Definition wor := bitwp orb. Definition wand := bitwp andb. Definition wxor := bitwp xorb. Notation "l ^| r" := (@wor _ l%word r%word) (at level 50, left associativity). Notation "l ^& r" := (@wand _ l%word r%word) (at level 40, left associativity). Theorem wor_unit : forall sz (x : word sz), wzero sz ^| x = x. unfold wzero, wor; induction x; simpl; intuition congruence. Qed. Theorem wor_comm : forall sz (x y : word sz), x ^| y = y ^| x. unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wor_assoc : forall sz (x y z : word sz), x ^| (y ^| z) = x ^| y ^| z. unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_unit : forall sz (x : word sz), wones sz ^& x = x. unfold wand; induction x; simpl; intuition congruence. Qed. Theorem wand_kill : forall sz (x : word sz), wzero sz ^& x = wzero sz. unfold wzero, wand; induction x; simpl; intuition congruence. Qed. Theorem wand_comm : forall sz (x y : word sz), x ^& y = y ^& x. unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_assoc : forall sz (x y z : word sz), x ^& (y ^& z) = x ^& y ^& z. unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool. Qed. Theorem wand_or_distr : forall sz (x y z : word sz), (x ^| y) ^& z = (x ^& z) ^| (y ^& z). unfold wand, wor; induction x; intro y; rewrite (shatter_word y); intro z; rewrite (shatter_word z); simpl; intuition; f_equal; auto with bool. destruct (whd y); destruct (whd z); destruct b; reflexivity. Qed. Definition wbring (sz : nat) : semi_ring_theory (wzero sz) (wones sz) (@wor sz) (@wand sz) (@eq _) := mk_srt _ _ _ _ _ (@wor_unit _) (@wor_comm _) (@wor_assoc _) (@wand_unit _) (@wand_kill _) (@wand_comm _) (@wand_assoc _) (@wand_or_distr _). (** * Inequality proofs *) Ltac word_simpl := unfold sext, zext, wzero in *; simpl in *. Ltac word_eq := ring. Ltac word_eq1 := match goal with | _ => ring | [ H : _ = _ |- _ ] => ring [H] end. Theorem word_neq : forall sz (w1 w2 : word sz), w1 ^- w2 <> wzero sz -> w1 <> w2. intros; intro; subst. unfold wminus in H. rewrite wminus_inv in H. tauto. Qed. Ltac word_neq := apply word_neq; let H := fresh "H" in intro H; simpl in H; ring_simplify in H; try discriminate. Ltac word_contra := match goal with | [ H : _ <> _ |- False ] => apply H; ring end. Ltac word_contra1 := match goal with | [ H : _ <> _ |- False ] => apply H; match goal with | _ => ring | [ H' : _ = _ |- _ ] => ring [H'] end end. Open Scope word_scope. (** * Signed Logic **) Fixpoint wordToZ sz (w : word sz) : Z := if wmsb w true then (** Negative **) match wordToN (wneg w) with | N0 => 0%Z | Npos x => Zneg x end else (** Positive **) match wordToN w with | N0 => 0%Z | Npos x => Zpos x end. (** * Comparison Predicates and Deciders **) Definition wlt sz (l r : word sz) : Prop := N.lt (wordToN l) (wordToN r). Definition wslt sz (l r : word sz) : Prop := Z.lt (wordToZ l) (wordToZ r). Notation "w1 > w2" := (@wlt _ w2%word w1%word) : word_scope. Notation "w1 >= w2" := (~(@wlt _ w1%word w2%word)) : word_scope. Notation "w1 < w2" := (@wlt _ w1%word w2%word) : word_scope. Notation "w1 <= w2" := (~(@wlt _ w2%word w1%word)) : word_scope. Notation "w1 '>s' w2" := (@wslt _ w2%word w1%word) (at level 70) : word_scope. Notation "w1 '>s=' w2" := (~(@wslt _ w1%word w2%word)) (at level 70) : word_scope. Notation "w1 '<s' w2" := (@wslt _ w1%word w2%word) (at level 70) : word_scope. Notation "w1 '<s=' w2" := (~(@wslt _ w2%word w1%word)) (at level 70) : word_scope. Definition wlt_dec : forall sz (l r : word sz), {l < r} + {l >= r}. refine (fun sz l r => match N.compare (wordToN l) (wordToN r) as k return N.compare (wordToN l) (wordToN r) = k -> _ with | Lt => fun pf => left _ _ | _ => fun pf => right _ _ end (refl_equal _)); abstract congruence. Defined. Definition wslt_dec : forall sz (l r : word sz), {l <s r} + {l >s= r}. refine (fun sz l r => match Z.compare (wordToZ l) (wordToZ r) as c return Z.compare (wordToZ l) (wordToZ r) = c -> _ with | Lt => fun pf => left _ _ | _ => fun pf => right _ _ end (refl_equal _)); abstract congruence. Defined. (* Ordering Lemmas **) Lemma lt_le : forall sz (a b : word sz), a < b -> a <= b. Proof. unfold wlt, N.lt. intros. intro. rewrite <- Ncompare_antisym in H0. rewrite H in H0. simpl in *. congruence. Qed. Lemma eq_le : forall sz (a b : word sz), a = b -> a <= b. Proof. intros; subst. unfold wlt, N.lt. rewrite N.compare_refl. congruence. Qed. Lemma wordToN_inj : forall sz (a b : word sz), wordToN a = wordToN b -> a = b. Proof. induction a; intro b0; rewrite (shatter_word b0); intuition. simpl in H. destruct b; destruct (whd b0); intros. f_equal. eapply IHa. eapply N.succ_inj in H. destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence. destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H. destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H. f_equal. eapply IHa. destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence. Qed. Lemma unique_inverse : forall sz (a b1 b2 : word sz), a ^+ b1 = wzero _ -> a ^+ b2 = wzero _ -> b1 = b2. Proof. intros. transitivity (b1 ^+ wzero _). rewrite wplus_comm. rewrite wplus_unit. auto. transitivity (b1 ^+ (a ^+ b2)). congruence. rewrite wplus_assoc. rewrite (wplus_comm b1). rewrite H. rewrite wplus_unit. auto. Qed. Lemma sub_0_eq : forall sz (a b : word sz), a ^- b = wzero _ -> a = b. Proof. intros. destruct (weq (wneg b) (wneg a)). transitivity (a ^+ (^~ b ^+ b)). rewrite (wplus_comm (^~ b)). rewrite wminus_inv. rewrite wplus_comm. rewrite wplus_unit. auto. rewrite e. rewrite wplus_assoc. rewrite wminus_inv. rewrite wplus_unit. auto. unfold wminus in H. generalize (unique_inverse a (wneg a) (^~ b)). intros. exfalso. apply n. symmetry; apply H0. apply wminus_inv. auto. Qed. Lemma le_neq_lt : forall sz (a b : word sz), b <= a -> a <> b -> b < a. Proof. intros; destruct (wlt_dec b a); auto. exfalso. apply H0. unfold wlt, N.lt in *. eapply wordToN_inj. eapply Ncompare_eq_correct. case_eq ((wordToN a ?= wordToN b)%N); auto; try congruence. intros. rewrite <- Ncompare_antisym in n. rewrite H1 in n. simpl in *. congruence. Qed. Hint Resolve word_neq lt_le eq_le sub_0_eq le_neq_lt : worder. Ltac shatter_word x := match type of x with | word 0 => try rewrite (shatter_word_0 x) in * | word (S ?N) => let x' := fresh in let H := fresh in destruct (@shatter_word_S N x) as [ ? [ x' H ] ]; rewrite H in *; clear H; shatter_word x' end. (** Uniqueness of equality proofs **) Lemma rewrite_weq : forall sz (a b : word sz) (pf : a = b), weq a b = left _ pf. Proof. intros; destruct (weq a b); try solve [ exfalso; auto ]. f_equal. eapply UIP_dec. eapply weq. Qed. (** * Some more useful derived facts *) Lemma natToWord_plus : forall sz n m, natToWord sz (n + m) = natToWord _ n ^+ natToWord _ m. destruct sz; intuition. rewrite wplus_alt. unfold wplusN, wordBinN. destruct (wordToNat_natToWord (S sz) n); intuition. destruct (wordToNat_natToWord (S sz) m); intuition. rewrite H0; rewrite H2; clear H0 H2. replace (n - x * pow2 (S sz) + (m - x0 * pow2 (S sz))) with (n + m - x * pow2 (S sz) - x0 * pow2 (S sz)) by omega. repeat rewrite drop_sub; auto; omega. Qed. Lemma natToWord_S : forall sz n, natToWord sz (S n) = natToWord _ 1 ^+ natToWord _ n. intros; change (S n) with (1 + n); apply natToWord_plus. Qed. Theorem natToWord_inj : forall sz n m, natToWord sz n = natToWord sz m -> (n < pow2 sz)%nat -> (m < pow2 sz)%nat -> n = m. intros. apply (f_equal (@wordToNat _)) in H. destruct (wordToNat_natToWord sz n). destruct (wordToNat_natToWord sz m). intuition. rewrite H4 in H; rewrite H2 in H; clear H4 H2. assert (x = 0). destruct x; auto; simpl in *; generalize dependent (x * pow2 sz); intros; omega. assert (x0 = 0). destruct x0; auto; simpl in *; generalize dependent (x0 * pow2 sz); intros; omega. subst; simpl in *; omega. Qed. Lemma wordToNat_natToWord_idempotent : forall sz n, (N.of_nat n < Npow2 sz)%N -> wordToNat (natToWord sz n) = n. intros. destruct (wordToNat_natToWord sz n); intuition. destruct x. simpl in *; omega. simpl in *. apply Nlt_out in H. autorewrite with N in *. rewrite Npow2_nat in *. generalize dependent (x * pow2 sz). intros; omega. Qed. Lemma wplus_cancel : forall sz (a b c : word sz), a ^+ c = b ^+ c -> a = b. intros. apply (f_equal (fun x => x ^+ ^~ c)) in H. repeat rewrite <- wplus_assoc in H. rewrite wminus_inv in H. repeat rewrite (wplus_comm _ (wzero sz)) in H. repeat rewrite wplus_unit in H. assumption. Qed.
[STATEMENT] lemma sip_not_ip': "paodv i \<TTurnstile> (recvmsg (\<lambda>m. not_Pkt m \<longrightarrow> msg_sender m \<noteq> i) \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>(\<xi>, _). sip \<xi> \<noteq> ip \<xi>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. paodv i \<TTurnstile> (recvmsg (\<lambda>m. not_Pkt m \<longrightarrow> msg_sender m \<noteq> i) \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>(\<xi>, uu_). sip \<xi> \<noteq> ip \<xi>) [PROOF STEP] by (inv_cterms inv add: onl_invariant_sterms [OF aodv_wf received_msg_inv] onl_invariant_sterms [OF aodv_wf ip_constant [THEN invariant_restrict_inD]] simp add: clear_locals_sip_not_ip') clarsimp+
module Data.List.Predicates.Pairs import public Data.List import public Data.List.Predicates.Interleaving import public Data.List.Predicates.Unique %default total %access public export ||| Proof that the contents of the given list of pairs originate from ||| a secondary list. data PairsFromList : (pairs : List (ty,ty)) -> (origin : List ty) -> Type where NilPair : PairsFromList Nil as PairIn : Elem a as -> Elem b as -> PairsFromList abs as -> PairsFromList ((a,b) :: abs) as ||| Proof that the given list of paired elements originate from the ||| two given lists such that the following hold: ||| ||| SubList (map fst pairs) as ||| ||| and ||| ||| SubList (map snd pairs) bs ||| data UnZipPairs : (pairs : List (ty,ty)) -> (as : List ty) -> (bs : List ty) -> Type where UnZipOne : UnZipPairs Nil as bs UnZipPair : (prf_a : Elem a as) -> (prf_b : Elem b bs) -> (rest : UnZipPairs abs as bs) -> UnZipPairs ((a,b) :: abs) as bs ||| Proof that the given list of paired elements not only originate ||| from the given lists, but that all elements are unique. data UZipPairsU : (pairs : List (ty,ty)) -> (as : List ty) -> (bs : List ty) -> Type where ValidUSPU : (uniqueAs : Unique as) -> (uniqueBs : Unique bs) -> (uniqueABs : Unique (as ++ bs)) -> (vswap : UnZipPairs cs as bs) -> UZipPairsU cs as bs
# Source: https://towardsdatascience.com/tidy-anomaly-detection-using-r-82a0c776d523 # Author: AbdulMajedRaja RS - https://towardsdatascience.com/@amrwrites # See https://github.com/amrrs/anomaly_detection_tidy_way/ library(anomalize) #tidy anomaly detectiom library(tidyverse) #tidyverse packages like dplyr, ggplot, tidyr library(coindeskr) #bitcoin price extraction from coindesk btc <- get_historic_price(start = "2017-01-01") #Convert to time series btc_ts <- btc %>% rownames_to_column() %>% as_tibble() %>% mutate(date = as.Date(rowname)) %>% select(-one_of('rowname')) head(btc_ts) #Decompose time series btc_ts %>% time_decompose(Price, method = "stl", frequency = "auto", trend = "auto") %>% anomalize(remainder, method = "gesd", alpha = 0.05, max_anoms = 0.2) %>% plot_anomaly_decomposition() # Detect anomalies btc_ts %>% time_decompose(Price) %>% anomalize(remainder) %>% time_recompose() %>% plot_anomalies(time_recomposed = TRUE, ncol = 3, alpha_dots = 0.5) # Extract anomaly obervations btc_ts %>% time_decompose(Price) %>% anomalize(remainder) %>% time_recompose() %>% filter(anomaly == 'Yes')
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) zlp_c := 0.828432 *RS_FACTOR: zlp_d := 2.15509e-2 *RS_FACTOR: zlp_k := 2.047107e-3*RS_FACTOR: zlp_f := (rs, z, xt, us0, us1) -> - (zlp_c + zlp_d*t_vw(z, xt, us0, us1)) * (1 - zlp_k*log(1 + rs/zlp_k)/rs)/rs: f := (rs, z, xt, xs0, xs1, us0, us1, ts0, ts1) -> zlp_f(rs, z, xt, us0, us1):
module Instances.Notation import public Data.Vect import public Data.Rel import public Decidable.Decidable import Common.Abbrev import Common.Interfaces import Specifications.DiscreteOrderedGroup import Specifications.OrderedRing %default total %access public export specifyMonoid : Ringops s => Type specifyMonoid {s} = MonoidSpec {s} (+) Zero specifyGroup : Ringops s => Type specifyGroup {s} = GroupSpec {s} (+) Zero Ng specifyPartialOrder : Decidable [s,s] leq => Type specifyPartialOrder {leq} = PartialOrderSpec leq specifyTotalOrder : Decidable [s,s] leq => Type specifyTotalOrder {leq} = TotalOrderSpec leq specifyPartiallyOrderedMagma : (Ringops s, Decidable [s,s] leq) => Type specifyPartiallyOrderedMagma {leq} = PartiallyOrderedMagmaSpec (+) leq specifyPartiallyOrderedGroup : (Ringops s, Decidable [s,s] leq) => Type specifyPartiallyOrderedGroup {leq} = PartiallyOrderedGroupSpec (+) Zero Ng leq specifyOrderedGroup : (Ringops s, Decidable [s,s] leq) => Type specifyOrderedGroup {leq} = OrderedGroupSpec (+) Zero Ng leq specifyDiscreteOrderedGroup : (Ringops s, Decidable [s,s] leq) => Type specifyDiscreteOrderedGroup {leq} = DiscreteOrderedGroupSpec (+) Zero Ng leq One specifyRing : Ringops s => Type specifyRing {s} = RingSpec {s} (+) Zero Ng (*) specifyPartiallyOrderedRing : (Ringops s, Decidable [s,s] leq) => Type specifyPartiallyOrderedRing {leq} = PartiallyOrderedRingSpec (+) Zero Ng (*) leq specifyOrderedRing : (Ringops s, Decidable [s,s] leq) => Type specifyOrderedRing {leq} = OrderedRingSpec (+) Zero Ng (*) leq specifyDiscreteOrderedRing : (Ringops s, Decidable [s,s] leq) => Type specifyDiscreteOrderedRing {leq} = DiscreteOrderedRingSpec (+) Zero Ng (*) leq One
Formal statement is: lemma bounded_plus_comp: fixes f g::"'a \<Rightarrow> 'b::real_normed_vector" assumes "bounded (f ` S)" assumes "bounded (g ` S)" shows "bounded ((\<lambda>x. f x + g x) ` S)" Informal statement is: If $f$ and $g$ are bounded functions, then so is $f + g$.
/- Copyright (c) 2022 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import algebra.order.hom.ring import algebra.order.pointwise import analysis.special_functions.pow /-! # Conditionally complete linear ordered fields This file shows that the reals are unique, or, more formally, given a type satisfying the common axioms of the reals (field, conditionally complete, linearly ordered) that there is an isomorphism preserving these properties to the reals. This is `rat.induced_order_ring_iso`. Moreover this isomorphism is unique. We introduce definitions of conditionally complete linear ordered fields, and show all such are archimedean. We also construct the natural map from a `linear_ordered_field` to such a field. ## Main definitions * `conditionally_complete_linear_ordered_field`: A field satisfying the standard axiomatization of the real numbers, being a Dedekind complete and linear ordered field. * `linear_ordered_field.induced_map`: A (unique) map from any archimedean linear ordered field to a conditionally complete linear ordered field. Various bundlings are available. ## Main results * `unique.order_ring_hom` : Uniqueness of `order_ring_hom`s from an archimedean linear ordered field to a conditionally complete linear ordered field. * `unique.order_ring_iso` : Uniqueness of `order_ring_iso`s between two conditionally complete linearly ordered fields. ## References * https://mathoverflow.net/questions/362991/ who-first-characterized-the-real-numbers-as-the-unique-complete-ordered-field ## Tags reals, conditionally complete, ordered field, uniqueness -/ variables {F α β γ : Type*} noncomputable theory open function rat real set open_locale classical pointwise set_option old_structure_cmd true /-- A field which is both linearly ordered and conditionally complete with respect to the order. This axiomatizes the reals. -/ @[protect_proj, ancestor linear_ordered_field conditionally_complete_linear_order] class conditionally_complete_linear_ordered_field (α : Type*) extends linear_ordered_field α renaming max → sup min → inf, conditionally_complete_linear_order α /-- Any conditionally complete linearly ordered field is archimedean. -/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_ordered_field.to_archimedean [conditionally_complete_linear_ordered_field α] : archimedean α := archimedean_iff_nat_lt.2 begin by_contra' h, obtain ⟨x, h⟩ := h, have := cSup_le (range_nonempty (coe : ℕ → α)) (forall_range_iff.2 $ λ n, le_sub_iff_add_le.2 $ le_cSup ⟨x, forall_range_iff.2 h⟩ ⟨n + 1, nat.cast_succ n⟩), linarith, end /-- The reals are a conditionally complete linearly ordered field. -/ instance : conditionally_complete_linear_ordered_field ℝ := { ..real.linear_ordered_field, ..real.conditionally_complete_linear_order } namespace linear_ordered_field /-! ### Rational cut map The idea is that a conditionally complete linear ordered field is fully characterized by its copy of the rationals. Hence we define `rat.cut_map β : α → set β` which sends `a : α` to the "rationals in `β`" that are less than `a`. -/ section cut_map variables [linear_ordered_field α] section division_ring variables (β) [division_ring β] {a a₁ a₂ : α} {b : β} {q : ℚ} /-- The lower cut of rationals inside a linear ordered field that are less than a given element of another linear ordered field. -/ def cut_map (a : α) : set β := (coe : ℚ → β) '' {t | ↑t < a} lemma cut_map_mono (h : a₁ ≤ a₂) : cut_map β a₁ ⊆ cut_map β a₂ := image_subset _ $ λ _, h.trans_lt' variables {β} @[simp] lemma mem_cut_map_iff : b ∈ cut_map β a ↔ ∃ q : ℚ, (q : α) < a ∧ (q : β) = b := iff.rfl @[simp] lemma coe_mem_cut_map_iff [char_zero β] : (q : β) ∈ cut_map β a ↔ (q : α) < a := rat.cast_injective.mem_set_image lemma cut_map_self (a : α) : cut_map α a = Iio a ∩ range (coe : ℚ → α) := begin ext, split, { rintro ⟨q, h, rfl⟩, exact ⟨h, q, rfl⟩ }, { rintro ⟨h, q, rfl⟩, exact ⟨q, h, rfl⟩ } end end division_ring variables (β) [linear_ordered_field β] {a a₁ a₂ : α} {b : β} {q : ℚ} lemma cut_map_coe (q : ℚ) : cut_map β (q : α) = coe '' {r : ℚ | (r : β) < q} := by simp_rw [cut_map, rat.cast_lt] variables [archimedean α] lemma cut_map_nonempty (a : α) : (cut_map β a).nonempty := nonempty.image _ $ exists_rat_lt a lemma cut_map_bdd_above (a : α) : bdd_above (cut_map β a) := begin obtain ⟨q, hq⟩ := exists_rat_gt a, exact ⟨q, ball_image_iff.2 $ λ r hr, by exact_mod_cast (hq.trans' hr).le⟩, end lemma cut_map_add (a b : α) : cut_map β (a + b) = cut_map β a + cut_map β b := begin refine (image_subset_iff.2 $ λ q hq, _).antisymm _, { rw [mem_set_of_eq, ←sub_lt_iff_lt_add] at hq, obtain ⟨q₁, hq₁q, hq₁ab⟩ := exists_rat_btwn hq, refine ⟨q₁, q - q₁, _, _, add_sub_cancel'_right _ _⟩; try {norm_cast}; rwa coe_mem_cut_map_iff, exact_mod_cast sub_lt_comm.mp hq₁q }, { rintro _ ⟨_, _, ⟨qa, ha, rfl⟩, ⟨qb, hb, rfl⟩, rfl⟩, refine ⟨qa + qb, _, by norm_cast⟩, rw [mem_set_of_eq, cast_add], exact add_lt_add ha hb } end end cut_map /-! ### Induced map `rat.cut_map` spits out a `set β`. To get something in `β`, we now take the supremum. -/ section induced_map variables (α β γ) [linear_ordered_field α] [conditionally_complete_linear_ordered_field β] [conditionally_complete_linear_ordered_field γ] /-- The induced order preserving function from a linear ordered field to a conditionally complete linear ordered field, defined by taking the Sup in the codomain of all the rationals less than the input. -/ def induced_map (x : α) : β := Sup $ cut_map β x variables [archimedean α] lemma induced_map_mono : monotone (induced_map α β) := λ a b h, cSup_le_cSup (cut_map_bdd_above β _) (cut_map_nonempty β _) (cut_map_mono β h) lemma induced_map_rat (q : ℚ) : induced_map α β (q : α) = q := begin refine cSup_eq_of_forall_le_of_forall_lt_exists_gt (cut_map_nonempty β q) (λ x h, _) (λ w h, _), { rw cut_map_coe at h, obtain ⟨r, h, rfl⟩ := h, exact le_of_lt h }, { obtain ⟨q', hwq, hq⟩ := exists_rat_btwn h, rw cut_map_coe, exact ⟨q', ⟨_, hq, rfl⟩, hwq⟩ } end @[simp] lemma induced_map_zero : induced_map α β 0 = 0 := by exact_mod_cast induced_map_rat α β 0 @[simp] lemma induced_map_one : induced_map α β 1 = 1 := by exact_mod_cast induced_map_rat α β 1 variables {α β} {a : α} {b : β} {q : ℚ} lemma induced_map_nonneg (ha : 0 ≤ a) : 0 ≤ induced_map α β a := (induced_map_zero α _).ge.trans $ induced_map_mono _ _ ha lemma coe_lt_induced_map_iff : (q : β) < induced_map α β a ↔ (q : α) < a := begin refine ⟨λ h, _, λ hq, _⟩, { rw ←induced_map_rat α at h, exact (induced_map_mono α β).reflect_lt h }, { obtain ⟨q', hq, hqa⟩ := exists_rat_btwn hq, apply lt_cSup_of_lt (cut_map_bdd_above β a) (coe_mem_cut_map_iff.mpr hqa), exact_mod_cast hq } end lemma lt_induced_map_iff : b < induced_map α β a ↔ ∃ q : ℚ, b < q ∧ (q : α) < a := ⟨λ h, (exists_rat_btwn h).imp $ λ q, and.imp_right coe_lt_induced_map_iff.1, λ ⟨q, hbq, hqa⟩, hbq.trans $ by rwa coe_lt_induced_map_iff⟩ @[simp] lemma induced_map_self (b : β) : induced_map β β b = b := eq_of_forall_rat_lt_iff_lt $ λ q, coe_lt_induced_map_iff variables (α β) @[simp] lemma induced_map_induced_map (a : α) : induced_map β γ (induced_map α β a) = induced_map α γ a := eq_of_forall_rat_lt_iff_lt $ λ q, by rw [coe_lt_induced_map_iff, coe_lt_induced_map_iff, iff.comm, coe_lt_induced_map_iff] @[simp] lemma induced_map_add (x y : α) : induced_map α β (x + y) = induced_map α β x + induced_map α β y := begin rw [induced_map, cut_map_add], exact cSup_add (cut_map_nonempty β x) (cut_map_bdd_above β x) (cut_map_nonempty β y) (cut_map_bdd_above β y), end variables {α β} /-- Preparatory lemma for `induced_ring_hom`. -/ lemma le_induced_map_mul_self_of_mem_cut_map (ha : 0 < a) (b : β) (hb : b ∈ cut_map β (a * a)) : b ≤ induced_map α β a * induced_map α β a := begin obtain ⟨q, hb, rfl⟩ := hb, obtain ⟨q', hq', hqq', hqa⟩ := exists_rat_pow_btwn two_ne_zero hb (mul_self_pos.2 ha.ne'), transitivity (q' : β)^2, exact_mod_cast hqq'.le, rw pow_two at ⊢ hqa, exact mul_self_le_mul_self (by exact_mod_cast hq'.le) (le_cSup (cut_map_bdd_above β a) $ coe_mem_cut_map_iff.2 $ lt_of_mul_self_lt_mul_self ha.le hqa), end /-- Preparatory lemma for `induced_ring_hom`. -/ lemma exists_mem_cut_map_mul_self_of_lt_induced_map_mul_self (ha : 0 < a) (b : β) (hba : b < induced_map α β a * induced_map α β a) : ∃ c ∈ cut_map β (a * a), b < c := begin obtain hb | hb := lt_or_le b 0, { refine ⟨0, _, hb⟩, rw [←rat.cast_zero, coe_mem_cut_map_iff, rat.cast_zero], exact mul_self_pos.2 ha.ne' }, obtain ⟨q, hq, hbq, hqa⟩ := exists_rat_pow_btwn two_ne_zero hba (hb.trans_lt hba), rw ←cast_pow at hbq, refine ⟨(q^2 : ℚ), coe_mem_cut_map_iff.2 _, hbq⟩, rw pow_two at ⊢ hqa, push_cast, obtain ⟨q', hq', hqa'⟩ := lt_induced_map_iff.1 (lt_of_mul_self_lt_mul_self _ hqa), exact mul_self_lt_mul_self (by exact_mod_cast hq.le) (hqa'.trans' $ by assumption_mod_cast), exact induced_map_nonneg ha.le, end variables (α β) /-- `induced_map` as an additive homomorphism. -/ def induced_add_hom : α →+ β := ⟨induced_map α β, induced_map_zero α β, induced_map_add α β⟩ /-- `induced_map` as an `order_ring_hom`. -/ @[simps] def induced_order_ring_hom : α →+*o β := { monotone' := induced_map_mono _ _, ..(induced_add_hom α β).mk_ring_hom_of_mul_self_of_two_ne_zero -- reduce to the case of x = y begin -- reduce to the case of 0 < x suffices : ∀ x, 0 < x → induced_add_hom α β (x * x) = induced_add_hom α β x * induced_add_hom α β x, { rintro x, obtain h | rfl | h := lt_trichotomy x 0, { convert this (-x) (neg_pos.2 h) using 1, { rw [neg_mul, mul_neg, neg_neg] }, { simp_rw [add_monoid_hom.map_neg, neg_mul, mul_neg, neg_neg] } }, { simp only [mul_zero, add_monoid_hom.map_zero] }, { exact this x h } }, -- prove that the (Sup of rationals less than x) ^ 2 is the Sup of the set of rationals less -- than (x ^ 2) by showing it is an upper bound and any smaller number is not an upper bound refine λ x hx, cSup_eq_of_forall_le_of_forall_lt_exists_gt (cut_map_nonempty β _) _ _, exact le_induced_map_mul_self_of_mem_cut_map hx, exact exists_mem_cut_map_mul_self_of_lt_induced_map_mul_self hx, end two_ne_zero (induced_map_one _ _) } /-- The isomorphism of ordered rings between two conditionally complete linearly ordered fields. -/ def induced_order_ring_iso : β ≃+*o γ := { inv_fun := induced_map γ β, left_inv := induced_map_inv_self _ _, right_inv := induced_map_inv_self _ _, map_le_map_iff' := λ x y, begin refine ⟨λ h, _, λ h, induced_map_mono _ _ h⟩, simpa [induced_order_ring_hom, add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero, induced_add_hom] using induced_map_mono γ β h, end, ..induced_order_ring_hom β γ } @[simp] lemma coe_induced_order_ring_iso : ⇑(induced_order_ring_iso β γ) = induced_map β γ := rfl @[simp] lemma induced_order_ring_iso_symm : (induced_order_ring_iso β γ).symm = induced_order_ring_iso γ β := rfl @[simp] lemma induced_order_ring_iso_self : induced_order_ring_iso β β = order_ring_iso.refl β := order_ring_iso.ext induced_map_self open order_ring_iso /-- There is a unique ordered ring homomorphism from an archimedean linear ordered field to a conditionally complete linear ordered field. -/ instance : unique (α →+*o β) := unique_of_subsingleton $ induced_order_ring_hom α β /-- There is a unique ordered ring isomorphism between two conditionally complete linear ordered fields. -/ instance : unique (β ≃+*o γ) := unique_of_subsingleton $ induced_order_ring_iso β γ end induced_map end linear_ordered_field section real variables {R S : Type*} [ordered_ring R] [linear_ordered_ring S] lemma ring_hom_monotone (hR : ∀ r : R, 0 ≤ r → ∃ s : R, s^2 = r) (f : R →+* S) : monotone f := (monotone_iff_map_nonneg f).2 $ λ r h, by { obtain ⟨s, rfl⟩ := hR r h, rw map_pow, apply sq_nonneg } /-- There exists no nontrivial ring homomorphism `ℝ →+* ℝ`. -/ instance real.ring_hom.unique : unique (ℝ →+* ℝ) := { default := ring_hom.id ℝ, uniq := λ f, congr_arg order_ring_hom.to_ring_hom (subsingleton.elim ⟨f, ring_hom_monotone (λ r hr, ⟨real.sqrt r, sq_sqrt hr⟩) f⟩ default), } end real
The limit of the inverse of $x$ as $x$ approaches $0$ from the left is $-\infty$.
corollary contractible_sphere: fixes a :: "'a::euclidean_space" shows "contractible(sphere a r) \<longleftrightarrow> r \<le> 0"
In a preview of the TGS demo , Ryan Geddes of IGN was left excited as to where the game would go after completing the demo , along with enjoying the improved visuals over Valkyria Chronicles II . Kotaku 's Richard Eisenbeis was highly positive about the game , citing is story as a return to form after Valkyria Chronicles II and its gameplay being the best in the series . His main criticisms were its length and gameplay repetition , along with expressing regret that it would not be localized .
(* Property from Productive Use of Failure in Inductive Proof, Andrew Ireland and Alan Bundy, JAR 1996. This Isabelle theory is produced using the TIP tool offered at the following website: https://github.com/tip-org/tools This file was originally provided as part of TIP benchmark at the following website: https://github.com/tip-org/benchmarks Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly to make it compatible with Isabelle2017.*) theory TIP_prop_46 imports "../../Test_Base" begin datatype 'a list = nil2 | cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun y :: "Nat => Nat => bool" where "y (Z) (Z) = True" | "y (Z) (S z2) = False" | "y (S x2) (Z) = False" | "y (S x2) (S y22) = y x2 y22" fun x :: "bool => bool => bool" where "x True y2 = True" | "x False y2 = y2" fun elem :: "Nat => Nat list => bool" where "elem z (nil2) = False" | "elem z (cons2 z2 xs) = x (y z z2) (elem z xs)" fun t2 :: "Nat => Nat => bool" where "t2 (Z) y2 = True" | "t2 (S z2) (Z) = False" | "t2 (S z2) (S x2) = t2 z2 x2" fun insert :: "Nat => Nat list => Nat list" where "insert z (nil2) = cons2 z (nil2)" | "insert z (cons2 z2 xs) = (if t2 z z2 then cons2 z (cons2 z2 xs) else cons2 z2 (insert z xs))" theorem property0 : "((z = y2) ==> (elem z (insert y2 z2)))" oops end
State Before: 𝕜 : Type u inst✝⁸ : NontriviallyNormedField 𝕜 E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type uX inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F m n✝ : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F n : ℕ ⊢ ‖fderiv 𝕜 (iteratedFDeriv 𝕜 n f) x‖ = ‖iteratedFDeriv 𝕜 (n + 1) f x‖ State After: no goals Tactic: rw [iteratedFDeriv_succ_eq_comp_left, comp_apply, LinearIsometryEquiv.norm_map]
-- -------------------------------------------------------------- [ Lens.idr ] -- Description : Idris port of Control.Lens -- Copyright : (c) Huw Campbell -- --------------------------------------------------------------------- [ EOH ] module Data.Yoneda import Data.Morphisms -- | @Yoneda f a@ can be viewed as the partial application of 'fmap' to its second argument. public export data Yoneda : ( f : Type -> Type ) -> ( a : Type ) -> Type where MkYoneda : ({0 b : Type} -> (a -> b) -> f b) -> Yoneda f a -- | The natural isomorphism between @f@ and @'Yoneda' f@ given by the Yoneda lemma -- is witnessed by 'liftYoneda' and 'lowerYoneda' -- -- @ -- 'liftYoneda' . 'lowerYoneda' ≡ 'id' -- 'lowerYoneda' . 'liftYoneda' ≡ 'id' -- @ -- -- @ -- lowerYoneda (liftYoneda fa) = -- definition -- lowerYoneda (Yoneda (\f -> fmap f a)) -- definition -- (\f -> fmap f fa) id -- beta reduction -- fmap id fa -- functor law -- fa -- @ -- -- @ -- 'lift' = 'liftYoneda' -- @ public export liftYoneda : { f : Type -> Type } -> Functor f => f a -> Yoneda f a liftYoneda a = MkYoneda (flip map a) public export lowerYoneda : {0 a : Type} -> Yoneda f a -> f a lowerYoneda (MkYoneda f) = f id public export implementation Functor f => Functor (Yoneda f) where map h (MkYoneda k) = MkYoneda (flip map (k h)) public export implementation Applicative f => Applicative (Yoneda f) where pure a = MkYoneda (\f => pure (f a)) (MkYoneda m) <*> (MkYoneda n) = MkYoneda (\f => m (f .) <*> n id)
Polynomial $A(x) = \sum_{j=0}^{n-1} a_j x^j$ let coeffs $A = (a_0,...,a_{n-1})$. that $k=0,...,n-1$ $$ \begin{align} \text{DFT}(A) &= (\sum_{j=0}^{n-1} a_j e^{-\frac{2\pi i}{n} jk},...)_k \\ &= (A(\omega_n^k),...)_k,\ \ \ \omega_n^k = \exp(-\frac{2\pi i}{n} k) \end{align} $$ then consider convolution, or multiplication of $A(x)$ and $B(x)$. we wanna know coeffs of $(A*B)(x) = A(x)B(x)$. for simplicity write $F=DFT$, notice that, $F(A) = (A(\omega_n^k))_k$, that $$ \begin{align} F(A*B) &= ((A*B)(\omega_n^k))_k = (A(\omega_n^k)B(\omega_n^k))_k = F(A)\cdot F(B) \\ A*B &= F^{-1}[F(A)\cdot F(B)] \end{align} $$ so next we need is to compute $F, F^{-1}$ in $O(n\log n)$ Before continue, note the lemmas $$ \begin{align} \omega_{dn}^{dk} = \omega_n^k, n,k,d \geq 0 \\ \omega_n^{n/2} = \omega_2^1 = -1, n>0 \\ (\omega_n^{k+n/2})^2=(\omega_n^k)^2=\omega_{n/2}^k, n>0, \text{even} \\ \omega_n^{k+n/2} = -\omega_n^k, n\geq 0 \end{align} $$ then by separate odd,even, i.e. $A(x) = A_0(x^2) + xA_1(x^2)$. combine above lemmas, get $$ \begin{align} A(\omega_n^k) = A_0(\omega_{n/2}^k) + \omega_n^k A_1(\omega_{n/2}^k), 0\leq k < n/2 \\ A(\omega_n^{k+n/2}) = A_0(\omega_{n/2}^k) - \omega_n^k A_1(\omega_{n/2}^k), k+n/2 \geq n/2 \end{align} $$ Thus, by divide and conquer solved. what about $F^{-1}$. notice that matrix form $$ \begin{align} y=F(A) = W a \\ w_{k,j} = \omega_n^{kj}, k,j=0,...n-1\\ a = F^{-1}(y) = W^{-1}y \end{align} $$ by the special form of $W$ $$ \begin{align} W^{-1} = \frac{1}{n} \bar{W}\\ v_{kj} = \frac{1}{n} \bar{w_n} ^{kj} \end{align} $$ So, just conjugate and divided by $n$. then same method sovlable. ### NTT let $\alpha$ replace $\omega_n$ in integer field. DFT require $$ \begin{align} \sum_{j=0}^{n-1} \alpha^{kj} = 0, k=1,...,n-1 \end{align} $$ and $\alpha^n=1, \alpha^k \neq 1, k=1,...,n-1$ is sufficient if $n$ is power of $2$, $\alpha^{n/2} = -1$ is sufficient if we get the $\alpha$ on $Z_p$, then $p=c2^k+1$, that $\alpha^c$ can be the $\alpha'$ to express conv length $\leq 2^{k-1}$ For in place NTT, leaves' addr. are bit-reversed. (NEED rigorous proof) and if for $F^{-1}$, one way is calc $\alpha^{-1}$, for each iter. Here is another way. Notice the matrix form. suppose $a$ divided by $n$, then we reverse $[a_1,...,a_{n-1}]$. by the fact $\alpha^{k(n-j)} = \alpha^{-kj}$, thus result is exactly $F^{-1}$. #### inverse we wanna know $BA \equiv 1 (\mod x^n)$. by the step that double $B$'s size, with init $B_0=1/A_0$. wlog write $B_1$ repre. $B_n$, $B_2$ repre. $B_{2n}$. that $$ \begin{align} & (B_1 A - 1)^2 \equiv 0 (\mod x^2) \\ \Rightarrow & B_2 = 2B_1 - B_1^2 A (\mod x^2) \end{align} $$ note, in impl. $B_1^2A$ has $B_1(\mod x)$ part in there since $B_1A \equiv 1(\mod x)$. aka, $(\mod x)$ part remain $B_1$, actually, we only need modify the higher order part, $-B_1^2 A ([x\leq..<x^2])$ #### sqrt also, the double size technique $$ \begin{align} & (B_1^2 - A)^2 \equiv 0 (\mod x^2) \\ \Rightarrow & B_2 = \frac{1}{2} [B_1 + A B_1^{-1}](\mod x^2) \end{align} $$ again, notice the old part $B_1$ shall remain, we can only modify new part in impl. and careful $B_0^2=A_0$ when $\neq 1$ #### log $\log P = \int \frac{P'}{P}$ #### exponent double step, $B_2 = B_1(1 + A - \log B_1)$ ### FWHT(FHT) Hadamard transform, def, with $H_0 = 1$ $$ \begin{align} H_m = \frac{1}{\sqrt{2}} \begin{bmatrix} H_{m-1} & H_{m-1} \\ H_{m-1} & -H_{m-1} \end{bmatrix} \\ (H_m)_{i,j} = \frac{1}{2^{m/2}} (-1)^{\langle i, j \rangle_b} \end{align} $$ where $i,j= 0,1,..,2^m-1$ and $\langle .,.\rangle_b$ is bitwise dot product, aka ``` __builtin_popcount(i&j) ``` when do fwht, don't need bit reversal and generator. besides, there is good property $H_m^2= I$. One can easy show $H_1^2 = I$ by direct compute or quantum tech. $H_1 = |+\rangle \langle 0| + |-\rangle \langle 1| $. then by induction. $H_m = H_1 \otimes H_{m-1}$. that $H_m^2 = H_1^2 \otimes H_{m-1}^2 = I$. which means we can do $H^{-1}$ by direct do $H$ ! note in impl. we often omit $2^{n/2}$, that use $H' = 2^{n/2}H$. so when do inverse, we need divide by $2^n$. still, we can do multiply by $A*B = H^{-1} [H(A) \cdot H(B)]$. note $\cdot$ is element-wise mult. also, suprisingly, for solving equation $A*B = C$, if we put $H$ on each side, that $H(A) \cdot H(B) = H(C)$, since $\cdot$ is element-wised, thus we can get $A = H^{-1} [H(C) / H(B)]$, element-wise. Note. for $\sum_i B_i = 0$, aka, not linear indep. the solution may has many, notice that $R = (1,1,...,1)$, that $R*B = 0$. e.g. agc034f. so we can minus arbitral still solution, but according specific condition, we can get the right one. ### useful links https://cp-algorithms.com/algebra/fft.html https://cp-algorithms.com/algebra/polynomial.html#toc-tgt-4 https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Polynomial_multiplication https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general) https://codeforces.com/blog/entry/43499 https://codeforces.com/blog/entry/48798 https://crypto.stanford.edu/pbc/notes/numbertheory/gen.html https://csacademy.com/blog/fast-fourier-transform-and-variations-of-it ```python ```
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.semiconj import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Commuting pairs of elements in monoids We define the predicate `commute a b := a * b = b * a` and provide some operations on terms `(h : commute a b)`. E.g., if `a`, `b`, and c are elements of a semiring, and that `hb : commute a b` and `hc : commute a c`. Then `hb.pow_left 5` proves `commute (a ^ 5) b` and `(hb.pow_right 2).add_right (hb.mul_right hc)` proves `commute a (b ^ 2 + b * c)`. Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like `rw [(hb.pow_left 5).eq]` rather than just `rw [hb.pow_left 5]`. This file defines only a few operations (`mul_left`, `inv_right`, etc). Other operations (`pow_right`, field inverse etc) are in the files that define corresponding notions. ## Implementation details Most of the proofs come from the properties of `semiconj_by`. -/ /-- Two elements commute if `a * b = b * a`. -/ def commute {S : Type u_1} [Mul S] (a : S) (b : S) := semiconj_by a b b namespace commute /-- Equality behind `commute a b`; useful for rewriting. -/ protected theorem Mathlib.add_commute.eq {S : Type u_1} [Add S] {a : S} {b : S} (h : add_commute a b) : a + b = b + a := h /-- Any element commutes with itself. -/ @[simp] protected theorem refl {S : Type u_1} [Mul S] (a : S) : commute a a := Eq.refl (a * a) /-- If `a` commutes with `b`, then `b` commutes with `a`. -/ protected theorem Mathlib.add_commute.symm {S : Type u_1} [Add S] {a : S} {b : S} (h : add_commute a b) : add_commute b a := Eq.symm h protected theorem Mathlib.add_commute.symm_iff {S : Type u_1} [Add S] {a : S} {b : S} : add_commute a b ↔ add_commute b a := { mp := add_commute.symm, mpr := add_commute.symm } /-- If `a` commutes with both `b` and `c`, then it commutes with their product. -/ @[simp] theorem mul_right {S : Type u_1} [semigroup S] {a : S} {b : S} {c : S} (hab : commute a b) (hac : commute a c) : commute a (b * c) := semiconj_by.mul_right hab hac /-- If both `a` and `b` commute with `c`, then their product commutes with `c`. -/ @[simp] theorem Mathlib.add_commute.add_left {S : Type u_1} [add_semigroup S] {a : S} {b : S} {c : S} (hac : add_commute a c) (hbc : add_commute b c) : add_commute (a + b) c := add_semiconj_by.add_left hac hbc protected theorem Mathlib.add_commute.right_comm {S : Type u_1} [add_semigroup S] {b : S} {c : S} (h : add_commute b c) (a : S) : a + b + c = a + c + b := sorry protected theorem left_comm {S : Type u_1} [semigroup S] {a : S} {b : S} (h : commute a b) (c : S) : a * (b * c) = b * (a * c) := sorry protected theorem Mathlib.add_commute.all {S : Type u_1} [add_comm_semigroup S] (a : S) (b : S) : add_commute a b := add_comm a b @[simp] theorem one_right {M : Type u_1} [monoid M] (a : M) : commute a 1 := semiconj_by.one_right a @[simp] theorem Mathlib.add_commute.zero_left {M : Type u_1} [add_monoid M] (a : M) : add_commute 0 a := add_semiconj_by.zero_left a theorem Mathlib.add_commute.units_neg_right {M : Type u_1} [add_monoid M] {a : M} {u : add_units M} : add_commute a ↑u → add_commute a ↑(-u) := add_semiconj_by.units_neg_right @[simp] theorem Mathlib.add_commute.units_neg_right_iff {M : Type u_1} [add_monoid M] {a : M} {u : add_units M} : add_commute a ↑(-u) ↔ add_commute a ↑u := add_semiconj_by.units_neg_right_iff theorem Mathlib.add_commute.units_neg_left {M : Type u_1} [add_monoid M] {u : add_units M} {a : M} : add_commute (↑u) a → add_commute (↑(-u)) a := add_semiconj_by.units_neg_symm_left @[simp] theorem Mathlib.add_commute.units_neg_left_iff {M : Type u_1} [add_monoid M] {u : add_units M} {a : M} : add_commute (↑(-u)) a ↔ add_commute (↑u) a := add_semiconj_by.units_neg_symm_left_iff theorem Mathlib.add_commute.units_coe {M : Type u_1} [add_monoid M] {u₁ : add_units M} {u₂ : add_units M} : add_commute u₁ u₂ → add_commute ↑u₁ ↑u₂ := add_semiconj_by.units_coe theorem Mathlib.add_commute.units_of_coe {M : Type u_1} [add_monoid M] {u₁ : add_units M} {u₂ : add_units M} : add_commute ↑u₁ ↑u₂ → add_commute u₁ u₂ := add_semiconj_by.units_of_coe @[simp] theorem units_coe_iff {M : Type u_1} [monoid M] {u₁ : units M} {u₂ : units M} : commute ↑u₁ ↑u₂ ↔ commute u₁ u₂ := semiconj_by.units_coe_iff theorem Mathlib.add_commute.neg_right {G : Type u_1} [add_group G] {a : G} {b : G} : add_commute a b → add_commute a (-b) := add_semiconj_by.neg_right @[simp] theorem Mathlib.add_commute.neg_right_iff {G : Type u_1} [add_group G] {a : G} {b : G} : add_commute a (-b) ↔ add_commute a b := add_semiconj_by.neg_right_iff theorem inv_left {G : Type u_1} [group G] {a : G} {b : G} : commute a b → commute (a⁻¹) b := semiconj_by.inv_symm_left @[simp] theorem inv_left_iff {G : Type u_1} [group G] {a : G} {b : G} : commute (a⁻¹) b ↔ commute a b := semiconj_by.inv_symm_left_iff theorem Mathlib.add_commute.neg_neg {G : Type u_1} [add_group G] {a : G} {b : G} : add_commute a b → add_commute (-a) (-b) := add_semiconj_by.neg_neg_symm @[simp] theorem inv_inv_iff {G : Type u_1} [group G] {a : G} {b : G} : commute (a⁻¹) (b⁻¹) ↔ commute a b := semiconj_by.inv_inv_symm_iff protected theorem Mathlib.add_commute.neg_add_cancel {G : Type u_1} [add_group G] {a : G} {b : G} (h : add_commute a b) : -a + b + a = b := eq.mpr (id (Eq._oldrec (Eq.refl (-a + b + a = b)) (add_commute.eq (add_commute.neg_left h)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b + -a + a = b)) (neg_add_cancel_right b a))) (Eq.refl b)) theorem inv_mul_cancel_assoc {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) : a⁻¹ * (b * a) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * (b * a) = b)) (Eq.symm (mul_assoc (a⁻¹) b a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * b * a = b)) (commute.inv_mul_cancel h))) (Eq.refl b)) protected theorem mul_inv_cancel {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) : a * b * (a⁻¹) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (a⁻¹) = b)) (commute.eq h))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a * (a⁻¹) = b)) (mul_inv_cancel_right b a))) (Eq.refl b)) theorem mul_inv_cancel_assoc {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) : a * (b * (a⁻¹)) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b * (a⁻¹)) = b)) (Eq.symm (mul_assoc a b (a⁻¹))))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (a⁻¹) = b)) (commute.mul_inv_cancel h))) (Eq.refl b)) end commute @[simp] theorem mul_inv_cancel_comm {G : Type u_1} [comm_group G] (a : G) (b : G) : a * b * (a⁻¹) = b := commute.mul_inv_cancel (commute.all a b) @[simp] theorem add_neg_cancel_comm_assoc {G : Type u_1} [add_comm_group G] (a : G) (b : G) : a + (b + -a) = b := add_commute.add_neg_cancel_assoc (add_commute.all a b) @[simp] theorem inv_mul_cancel_comm {G : Type u_1} [comm_group G] (a : G) (b : G) : a⁻¹ * b * a = b := commute.inv_mul_cancel (commute.all a b) @[simp] theorem inv_mul_cancel_comm_assoc {G : Type u_1} [comm_group G] (a : G) (b : G) : a⁻¹ * (b * a) = b := commute.inv_mul_cancel_assoc (commute.all a b)
[STATEMENT] lemma sip_not_ip': "paodv i \<TTurnstile> (recvmsg (\<lambda>m. not_Pkt m \<longrightarrow> msg_sender m \<noteq> i) \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>(\<xi>, _). sip \<xi> \<noteq> ip \<xi>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. paodv i \<TTurnstile> (recvmsg (\<lambda>m. not_Pkt m \<longrightarrow> msg_sender m \<noteq> i) \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (\<lambda>(\<xi>, uu_). sip \<xi> \<noteq> ip \<xi>) [PROOF STEP] by (inv_cterms inv add: onl_invariant_sterms [OF aodv_wf received_msg_inv] onl_invariant_sterms [OF aodv_wf ip_constant [THEN invariant_restrict_inD]] simp add: clear_locals_sip_not_ip') clarsimp+
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro ! This file was ported from Lean 3 source module data.finset.fold ! leanprover-community/mathlib commit e04043d6bf7264a3c84bc69711dc354958ca4516 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.Order.Monoid.WithTop import Mathbin.Data.Finset.Image import Mathbin.Data.Multiset.Fold /-! # The fold operation for a commutative associative operation over a finset. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace Finset open Multiset variable {α β γ : Type _} /-! ### fold -/ section Fold variable (op : β → β → β) [hc : IsCommutative β op] [ha : IsAssociative β op] -- mathport name: op local notation a " * " b => op a b include hc ha #print Finset.fold /- /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : Finset α) : β := (s.1.map f).fold op b #align finset.fold Finset.fold -/ variable {op} {f : α → β} {b : β} {s : Finset α} {a : α} #print Finset.fold_empty /- @[simp] theorem fold_empty : (∅ : Finset α).fold op b f = b := rfl #align finset.fold_empty Finset.fold_empty -/ /- warning: finset.fold_cons -> Finset.fold_cons is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {a : α} (h : Not (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) a s)), Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Finset.cons.{u1} α a s h)) (op (f a) (Finset.fold.{u1, u2} α β op hc ha b f s)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {a : α} (h : Not (Membership.mem.{u2, u2} α (Finset.{u2} α) (Finset.instMembershipFinset.{u2} α) a s)), Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b f (Finset.cons.{u2} α a s h)) (op (f a) (Finset.fold.{u2, u1} α β op hc ha b f s)) Case conversion may be inaccurate. Consider using '#align finset.fold_cons Finset.fold_consₓ'. -/ @[simp] theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by dsimp only [fold] rw [cons_val, Multiset.map_cons, fold_cons_left] #align finset.fold_cons Finset.fold_cons /- warning: finset.fold_insert -> Finset.fold_insert is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {a : α} [_inst_1 : DecidableEq.{succ u1} α], (Not (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) a s)) -> (Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Insert.insert.{u1, u1} α (Finset.{u1} α) (Finset.hasInsert.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) a s)) (op (f a) (Finset.fold.{u1, u2} α β op hc ha b f s))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {a : α} [_inst_1 : DecidableEq.{succ u2} α], (Not (Membership.mem.{u2, u2} α (Finset.{u2} α) (Finset.instMembershipFinset.{u2} α) a s)) -> (Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b f (Insert.insert.{u2, u2} α (Finset.{u2} α) (Finset.instInsertFinset.{u2} α (fun (a : α) (b : α) => _inst_1 a b)) a s)) (op (f a) (Finset.fold.{u2, u1} α β op hc ha b f s))) Case conversion may be inaccurate. Consider using '#align finset.fold_insert Finset.fold_insertₓ'. -/ @[simp] theorem fold_insert [DecidableEq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold <;> rw [insert_val, ndinsert_of_not_mem h, Multiset.map_cons, fold_cons_left] #align finset.fold_insert Finset.fold_insert #print Finset.fold_singleton /- @[simp] theorem fold_singleton : ({a} : Finset α).fold op b f = f a * b := rfl #align finset.fold_singleton Finset.fold_singleton -/ /- warning: finset.fold_map -> Finset.fold_map is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {g : Function.Embedding.{succ u3, succ u1} γ α} {s : Finset.{u3} γ}, Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Finset.map.{u3, u1} γ α g s)) (Finset.fold.{u3, u2} γ β op hc ha b (Function.comp.{succ u3, succ u1, succ u2} γ α β f (coeFn.{max 1 (succ u3) (succ u1), max (succ u3) (succ u1)} (Function.Embedding.{succ u3, succ u1} γ α) (fun (_x : Function.Embedding.{succ u3, succ u1} γ α) => γ -> α) (Function.Embedding.hasCoeToFun.{succ u3, succ u1} γ α) g)) s) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {g : Function.Embedding.{succ u3, succ u2} γ α} {s : Finset.{u3} γ}, Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b f (Finset.map.{u3, u2} γ α g s)) (Finset.fold.{u3, u1} γ β op hc ha b (Function.comp.{succ u3, succ u2, succ u1} γ α β f (FunLike.coe.{max (succ u2) (succ u3), succ u3, succ u2} (Function.Embedding.{succ u3, succ u2} γ α) γ (fun (_x : γ) => (fun ([email protected]._hyg.19 : γ) => α) _x) (EmbeddingLike.toFunLike.{max (succ u2) (succ u3), succ u3, succ u2} (Function.Embedding.{succ u3, succ u2} γ α) γ α (Function.instEmbeddingLikeEmbedding.{succ u3, succ u2} γ α)) g)) s) Case conversion may be inaccurate. Consider using '#align finset.fold_map Finset.fold_mapₓ'. -/ @[simp] theorem fold_map {g : γ ↪ α} {s : Finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, Multiset.map_map] #align finset.fold_map Finset.fold_map /- warning: finset.fold_image -> Finset.fold_image is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} [_inst_1 : DecidableEq.{succ u1} α] {g : γ -> α} {s : Finset.{u3} γ}, (forall (x : γ), (Membership.Mem.{u3, u3} γ (Finset.{u3} γ) (Finset.hasMem.{u3} γ) x s) -> (forall (y : γ), (Membership.Mem.{u3, u3} γ (Finset.{u3} γ) (Finset.hasMem.{u3} γ) y s) -> (Eq.{succ u1} α (g x) (g y)) -> (Eq.{succ u3} γ x y))) -> (Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Finset.image.{u3, u1} γ α (fun (a : α) (b : α) => _inst_1 a b) g s)) (Finset.fold.{u3, u2} γ β op hc ha b (Function.comp.{succ u3, succ u1, succ u2} γ α β f g) s)) but is expected to have type forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} [_inst_1 : DecidableEq.{succ u3} α] {g : γ -> α} {s : Finset.{u2} γ}, (forall (x : γ), (Membership.mem.{u2, u2} γ (Finset.{u2} γ) (Finset.instMembershipFinset.{u2} γ) x s) -> (forall (y : γ), (Membership.mem.{u2, u2} γ (Finset.{u2} γ) (Finset.instMembershipFinset.{u2} γ) y s) -> (Eq.{succ u3} α (g x) (g y)) -> (Eq.{succ u2} γ x y))) -> (Eq.{succ u1} β (Finset.fold.{u3, u1} α β op hc ha b f (Finset.image.{u2, u3} γ α (fun (a : α) (b : α) => _inst_1 a b) g s)) (Finset.fold.{u2, u1} γ β op hc ha b (Function.comp.{succ u2, succ u3, succ u1} γ α β f g) s)) Case conversion may be inaccurate. Consider using '#align finset.fold_image Finset.fold_imageₓ'. -/ @[simp] theorem fold_image [DecidableEq α] {g : γ → α} {s : Finset γ} (H : ∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, Multiset.map_map] #align finset.fold_image Finset.fold_image /- warning: finset.fold_congr -> Finset.fold_congr is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {g : α -> β}, (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (Eq.{succ u2} β (f x) (g x))) -> (Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f s) (Finset.fold.{u1, u2} α β op hc ha b g s)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {g : α -> β}, (forall (x : α), (Membership.mem.{u2, u2} α (Finset.{u2} α) (Finset.instMembershipFinset.{u2} α) x s) -> (Eq.{succ u1} β (f x) (g x))) -> (Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b f s) (Finset.fold.{u2, u1} α β op hc ha b g s)) Case conversion may be inaccurate. Consider using '#align finset.fold_congr Finset.fold_congrₓ'. -/ @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr rfl H] #align finset.fold_congr Finset.fold_congr #print Finset.fold_op_distrib /- theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : (s.fold op (b₁ * b₂) fun x => f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] #align finset.fold_op_distrib Finset.fold_op_distrib -/ /- warning: finset.fold_const -> Finset.fold_const is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {b : β} {s : Finset.{u1} α} [_inst_1 : Decidable (Eq.{succ u1} (Finset.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Finset.{u1} α) (Finset.hasEmptyc.{u1} α)))] (c : β), (Eq.{succ u2} β (op c (op b c)) (op b c)) -> (Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b (fun (_x : α) => c) s) (ite.{succ u2} β (Eq.{succ u1} (Finset.{u1} α) s (EmptyCollection.emptyCollection.{u1} (Finset.{u1} α) (Finset.hasEmptyc.{u1} α))) _inst_1 b (op b c))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {b : β} {s : Finset.{u2} α} [_inst_1 : Decidable (Eq.{succ u2} (Finset.{u2} α) s (EmptyCollection.emptyCollection.{u2} (Finset.{u2} α) (Finset.instEmptyCollectionFinset.{u2} α)))] (c : β), (Eq.{succ u1} β (op c (op b c)) (op b c)) -> (Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b (fun (_x : α) => c) s) (ite.{succ u1} β (Eq.{succ u2} (Finset.{u2} α) s (EmptyCollection.emptyCollection.{u2} (Finset.{u2} α) (Finset.instEmptyCollectionFinset.{u2} α))) _inst_1 b (op b c))) Case conversion may be inaccurate. Consider using '#align finset.fold_const Finset.fold_constₓ'. -/ theorem fold_const [Decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : Finset.fold op b (fun _ => c) s = if s = ∅ then b else op b c := by classical induction' s using Finset.induction_on with x s hx IH · simp · simp only [Finset.fold_insert hx, IH, if_false, Finset.insert_ne_empty] split_ifs · rw [hc.comm] · exact h #align finset.fold_const Finset.fold_const /- warning: finset.fold_hom -> Finset.fold_hom is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {op' : γ -> γ -> γ} [_inst_1 : IsCommutative.{u3} γ op'] [_inst_2 : IsAssociative.{u3} γ op'] {m : β -> γ}, (forall (x : β) (y : β), Eq.{succ u3} γ (m (op x y)) (op' (m x) (m y))) -> (Eq.{succ u3} γ (Finset.fold.{u1, u3} α γ op' _inst_1 _inst_2 (m b) (fun (x : α) => m (f x)) s) (m (Finset.fold.{u1, u2} α β op hc ha b f s))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {op' : γ -> γ -> γ} [_inst_1 : IsCommutative.{u3} γ op'] [_inst_2 : IsAssociative.{u3} γ op'] {m : β -> γ}, (forall (x : β) (y : β), Eq.{succ u3} γ (m (op x y)) (op' (m x) (m y))) -> (Eq.{succ u3} γ (Finset.fold.{u2, u3} α γ op' _inst_1 _inst_2 (m b) (fun (x : α) => m (f x)) s) (m (Finset.fold.{u2, u1} α β op hc ha b f s))) Case conversion may be inaccurate. Consider using '#align finset.fold_hom Finset.fold_homₓ'. -/ theorem fold_hom {op' : γ → γ → γ} [IsCommutative γ op'] [IsAssociative γ op'] {m : β → γ} (hm : ∀ x y, m (op x y) = op' (m x) (m y)) : (s.fold op' (m b) fun x => m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, Multiset.map_map] #align finset.fold_hom Finset.fold_hom /- warning: finset.fold_disj_union -> Finset.fold_disjUnion is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {s₁ : Finset.{u1} α} {s₂ : Finset.{u1} α} {b₁ : β} {b₂ : β} (h : Disjoint.{u1} (Finset.{u1} α) (Finset.partialOrder.{u1} α) (Finset.orderBot.{u1} α) s₁ s₂), Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha (op b₁ b₂) f (Finset.disjUnion.{u1} α s₁ s₂ h)) (op (Finset.fold.{u1, u2} α β op hc ha b₁ f s₁) (Finset.fold.{u1, u2} α β op hc ha b₂ f s₂)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {s₁ : Finset.{u2} α} {s₂ : Finset.{u2} α} {b₁ : β} {b₂ : β} (h : Disjoint.{u2} (Finset.{u2} α) (Finset.partialOrder.{u2} α) (Finset.instOrderBotFinsetToLEToPreorderPartialOrder.{u2} α) s₁ s₂), Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha (op b₁ b₂) f (Finset.disjUnion.{u2} α s₁ s₂ h)) (op (Finset.fold.{u2, u1} α β op hc ha b₁ f s₁) (Finset.fold.{u2, u1} α β op hc ha b₂ f s₂)) Case conversion may be inaccurate. Consider using '#align finset.fold_disj_union Finset.fold_disjUnionₓ'. -/ theorem fold_disjUnion {s₁ s₂ : Finset α} {b₁ b₂ : β} (h) : (s₁.disjUnion s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f := (congr_arg _ <| Multiset.map_add _ _ _).trans (Multiset.fold_add _ _ _ _ _) #align finset.fold_disj_union Finset.fold_disjUnion /- warning: finset.fold_disj_Union -> Finset.fold_disjUnionᵢ is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {ι : Type.{u3}} {s : Finset.{u3} ι} {t : ι -> (Finset.{u1} α)} {b : ι -> β} {b₀ : β} (h : Set.PairwiseDisjoint.{u1, u3} (Finset.{u1} α) ι (Finset.partialOrder.{u1} α) (Finset.orderBot.{u1} α) ((fun (a : Type.{u3}) (b : Type.{u3}) [self : HasLiftT.{succ u3, succ u3} a b] => self.0) (Finset.{u3} ι) (Set.{u3} ι) (HasLiftT.mk.{succ u3, succ u3} (Finset.{u3} ι) (Set.{u3} ι) (CoeTCₓ.coe.{succ u3, succ u3} (Finset.{u3} ι) (Set.{u3} ι) (Finset.Set.hasCoeT.{u3} ι))) s) t), Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha (Finset.fold.{u3, u2} ι β op hc ha b₀ b s) f (Finset.disjUnionₓ.{u3, u1} ι α s t h)) (Finset.fold.{u3, u2} ι β op hc ha b₀ (fun (i : ι) => Finset.fold.{u1, u2} α β op hc ha (b i) f (t i)) s) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {ι : Type.{u3}} {s : Finset.{u3} ι} {t : ι -> (Finset.{u2} α)} {b : ι -> β} {b₀ : β} (h : Set.PairwiseDisjoint.{u2, u3} (Finset.{u2} α) ι (Finset.partialOrder.{u2} α) (Finset.instOrderBotFinsetToLEToPreorderPartialOrder.{u2} α) (Finset.toSet.{u3} ι s) t), Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha (Finset.fold.{u3, u1} ι β op hc ha b₀ b s) f (Finset.disjUnionᵢ.{u3, u2} ι α s t h)) (Finset.fold.{u3, u1} ι β op hc ha b₀ (fun (i : ι) => Finset.fold.{u2, u1} α β op hc ha (b i) f (t i)) s) Case conversion may be inaccurate. Consider using '#align finset.fold_disj_Union Finset.fold_disjUnionᵢₓ'. -/ theorem fold_disjUnionᵢ {ι : Type _} {s : Finset ι} {t : ι → Finset α} {b : ι → β} {b₀ : β} (h) : (s.disjUnionₓ t h).fold op (s.fold op b₀ b) f = s.fold op b₀ fun i => (t i).fold op (b i) f := (congr_arg _ <| Multiset.map_bind _ _ _).trans (Multiset.fold_bind _ _ _ _ _) #align finset.fold_disj_Union Finset.fold_disjUnionᵢ /- warning: finset.fold_union_inter -> Finset.fold_union_inter is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} [_inst_1 : DecidableEq.{succ u1} α] {s₁ : Finset.{u1} α} {s₂ : Finset.{u1} α} {b₁ : β} {b₂ : β}, Eq.{succ u2} β (op (Finset.fold.{u1, u2} α β op hc ha b₁ f (Union.union.{u1} (Finset.{u1} α) (Finset.hasUnion.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) s₁ s₂)) (Finset.fold.{u1, u2} α β op hc ha b₂ f (Inter.inter.{u1} (Finset.{u1} α) (Finset.hasInter.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) s₁ s₂))) (op (Finset.fold.{u1, u2} α β op hc ha b₂ f s₁) (Finset.fold.{u1, u2} α β op hc ha b₁ f s₂)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} [_inst_1 : DecidableEq.{succ u2} α] {s₁ : Finset.{u2} α} {s₂ : Finset.{u2} α} {b₁ : β} {b₂ : β}, Eq.{succ u1} β (op (Finset.fold.{u2, u1} α β op hc ha b₁ f (Union.union.{u2} (Finset.{u2} α) (Finset.instUnionFinset.{u2} α (fun (a : α) (b : α) => _inst_1 a b)) s₁ s₂)) (Finset.fold.{u2, u1} α β op hc ha b₂ f (Inter.inter.{u2} (Finset.{u2} α) (Finset.instInterFinset.{u2} α (fun (a : α) (b : α) => _inst_1 a b)) s₁ s₂))) (op (Finset.fold.{u2, u1} α β op hc ha b₂ f s₁) (Finset.fold.{u2, u1} α β op hc ha b₁ f s₂)) Case conversion may be inaccurate. Consider using '#align finset.fold_union_inter Finset.fold_union_interₓ'. -/ theorem fold_union_inter [DecidableEq α] {s₁ s₂ : Finset α} {b₁ b₂ : β} : ((s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f) = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold <;> rw [← fold_add op, ← Multiset.map_add, union_val, inter_val, union_add_inter, Multiset.map_add, hc.comm, fold_add] #align finset.fold_union_inter Finset.fold_union_inter /- warning: finset.fold_insert_idem -> Finset.fold_insert_idem is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {a : α} [_inst_1 : DecidableEq.{succ u1} α] [hi : IsIdempotent.{u2} β op], Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Insert.insert.{u1, u1} α (Finset.{u1} α) (Finset.hasInsert.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) a s)) (op (f a) (Finset.fold.{u1, u2} α β op hc ha b f s)) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {a : α} [_inst_1 : DecidableEq.{succ u2} α] [hi : IsIdempotent.{u1} β op], Eq.{succ u1} β (Finset.fold.{u2, u1} α β op hc ha b f (Insert.insert.{u2, u2} α (Finset.{u2} α) (Finset.instInsertFinset.{u2} α (fun (a : α) (b : α) => _inst_1 a b)) a s)) (op (f a) (Finset.fold.{u2, u1} α β op hc ha b f s)) Case conversion may be inaccurate. Consider using '#align finset.fold_insert_idem Finset.fold_insert_idemₓ'. -/ @[simp] theorem fold_insert_idem [DecidableEq α] [hi : IsIdempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by by_cases a ∈ s · rw [← insert_erase h] simp [← ha.assoc, hi.idempotent] · apply fold_insert h #align finset.fold_insert_idem Finset.fold_insert_idem /- warning: finset.fold_image_idem -> Finset.fold_image_idem is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} [_inst_1 : DecidableEq.{succ u1} α] {g : γ -> α} {s : Finset.{u3} γ} [hi : IsIdempotent.{u2} β op], Eq.{succ u2} β (Finset.fold.{u1, u2} α β op hc ha b f (Finset.image.{u3, u1} γ α (fun (a : α) (b : α) => _inst_1 a b) g s)) (Finset.fold.{u3, u2} γ β op hc ha b (Function.comp.{succ u3, succ u1, succ u2} γ α β f g) s) but is expected to have type forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} [_inst_1 : DecidableEq.{succ u3} α] {g : γ -> α} {s : Finset.{u2} γ} [hi : IsIdempotent.{u1} β op], Eq.{succ u1} β (Finset.fold.{u3, u1} α β op hc ha b f (Finset.image.{u2, u3} γ α (fun (a : α) (b : α) => _inst_1 a b) g s)) (Finset.fold.{u2, u1} γ β op hc ha b (Function.comp.{succ u2, succ u3, succ u1} γ α β f g) s) Case conversion may be inaccurate. Consider using '#align finset.fold_image_idem Finset.fold_image_idemₓ'. -/ theorem fold_image_idem [DecidableEq α] {g : γ → α} {s : Finset γ} [hi : IsIdempotent β op] : (image g s).fold op b f = s.fold op b (f ∘ g) := by induction' s using Finset.cons_induction with x xs hx ih · rw [fold_empty, image_empty, fold_empty] · haveI := Classical.decEq γ rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih] #align finset.fold_image_idem Finset.fold_image_idem #print Finset.fold_ite' /- /-- A stronger version of `finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ theorem fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [DecidablePred p] : Finset.fold op b (fun i => ite (p i) (f i) (g i)) s = op (Finset.fold op b f (s.filterₓ p)) (Finset.fold op b g (s.filterₓ fun i => ¬p i)) := by classical induction' s using Finset.induction_on with x s hx IH · simp [hb] · simp only [[anonymous], Finset.fold_insert hx] split_ifs with h h · have : x ∉ Finset.filter p s := by simp [hx] simp [Finset.filter_insert, h, Finset.fold_insert this, ha.assoc, IH] · have : x ∉ Finset.filter (fun i => ¬p i) s := by simp [hx] simp [Finset.filter_insert, h, Finset.fold_insert this, IH, ← ha.assoc, hc.comm] #align finset.fold_ite' Finset.fold_ite' -/ #print Finset.fold_ite /- /-- A weaker version of `finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ theorem fold_ite [IsIdempotent β op] {g : α → β} (p : α → Prop) [DecidablePred p] : Finset.fold op b (fun i => ite (p i) (f i) (g i)) s = op (Finset.fold op b f (s.filterₓ p)) (Finset.fold op b g (s.filterₓ fun i => ¬p i)) := fold_ite' (IsIdempotent.idempotent _) _ #align finset.fold_ite Finset.fold_ite -/ /- warning: finset.fold_op_rel_iff_and -> Finset.fold_op_rel_iff_and is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {r : β -> β -> Prop}, (forall {x : β} {y : β} {z : β}, Iff (r x (op y z)) (And (r x y) (r x z))) -> (forall {c : β}, Iff (r c (Finset.fold.{u1, u2} α β op hc ha b f s)) (And (r c b) (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (r c (f x))))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {r : β -> β -> Prop}, (forall {x : β} {y : β} {z : β}, Iff (r x (op y z)) (And (r x y) (r x z))) -> (forall {c : β}, Iff (r c (Finset.fold.{u2, u1} α β op hc ha b f s)) (And (r c b) (forall (x : α), (Membership.mem.{u2, u2} α (Finset.{u2} α) (Finset.instMembershipFinset.{u2} α) x s) -> (r c (f x))))) Case conversion may be inaccurate. Consider using '#align finset.fold_op_rel_iff_and Finset.fold_op_rel_iff_andₓ'. -/ theorem fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ r x y ∧ r x z) {c : β} : r c (s.fold op b f) ↔ r c b ∧ ∀ x ∈ s, r c (f x) := by classical apply Finset.induction_on s · simp clear s intro a s ha IH rw [Finset.fold_insert ha, hr, IH, ← and_assoc', and_comm' (r c (f a)), and_assoc'] apply and_congr Iff.rfl constructor · rintro ⟨h₁, h₂⟩ intro b hb rw [Finset.mem_insert] at hb rcases hb with (rfl | hb) <;> solve_by_elim · intro h constructor · exact h a (Finset.mem_insert_self _ _) · intro b hb apply h b rw [Finset.mem_insert] right exact hb #align finset.fold_op_rel_iff_and Finset.fold_op_rel_iff_and /- warning: finset.fold_op_rel_iff_or -> Finset.fold_op_rel_iff_or is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {op : β -> β -> β} [hc : IsCommutative.{u2} β op] [ha : IsAssociative.{u2} β op] {f : α -> β} {b : β} {s : Finset.{u1} α} {r : β -> β -> Prop}, (forall {x : β} {y : β} {z : β}, Iff (r x (op y z)) (Or (r x y) (r x z))) -> (forall {c : β}, Iff (r c (Finset.fold.{u1, u2} α β op hc ha b f s)) (Or (r c b) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) => r c (f x)))))) but is expected to have type forall {α : Type.{u2}} {β : Type.{u1}} {op : β -> β -> β} [hc : IsCommutative.{u1} β op] [ha : IsAssociative.{u1} β op] {f : α -> β} {b : β} {s : Finset.{u2} α} {r : β -> β -> Prop}, (forall {x : β} {y : β} {z : β}, Iff (r x (op y z)) (Or (r x y) (r x z))) -> (forall {c : β}, Iff (r c (Finset.fold.{u2, u1} α β op hc ha b f s)) (Or (r c b) (Exists.{succ u2} α (fun (x : α) => And (Membership.mem.{u2, u2} α (Finset.{u2} α) (Finset.instMembershipFinset.{u2} α) x s) (r c (f x)))))) Case conversion may be inaccurate. Consider using '#align finset.fold_op_rel_iff_or Finset.fold_op_rel_iff_orₓ'. -/ theorem fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ r x y ∨ r x z) {c : β} : r c (s.fold op b f) ↔ r c b ∨ ∃ x ∈ s, r c (f x) := by classical apply Finset.induction_on s · simp clear s intro a s ha IH rw [Finset.fold_insert ha, hr, IH, ← or_assoc', or_comm' (r c (f a)), or_assoc'] apply or_congr Iff.rfl constructor · rintro (h₁ | ⟨x, hx, h₂⟩) · use a simp [h₁] · refine' ⟨x, by simp [hx], h₂⟩ · rintro ⟨x, hx, h⟩ rw [mem_insert] at hx cases hx · left rwa [hx] at h · right exact ⟨x, hx, h⟩ #align finset.fold_op_rel_iff_or Finset.fold_op_rel_iff_or omit hc ha #print Finset.fold_union_empty_singleton /- @[simp] theorem fold_union_empty_singleton [DecidableEq α] (s : Finset α) : Finset.fold (· ∪ ·) ∅ singleton s = s := by apply Finset.induction_on s · simp only [fold_empty] · intro a s has ih rw [fold_insert has, ih, insert_eq] #align finset.fold_union_empty_singleton Finset.fold_union_empty_singleton -/ /- warning: finset.fold_sup_bot_singleton -> Finset.fold_sup_bot_singleton is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (s : Finset.{u1} α), Eq.{succ u1} (Finset.{u1} α) (Finset.fold.{u1, u1} α (Finset.{u1} α) (Sup.sup.{u1} (Finset.{u1} α) (SemilatticeSup.toHasSup.{u1} (Finset.{u1} α) (Lattice.toSemilatticeSup.{u1} (Finset.{u1} α) (Finset.lattice.{u1} α (fun (a : α) (b : α) => _inst_1 a b))))) (Finset.hasUnion.Union.isCommutative.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) (Finset.hasUnion.Union.isAssociative.{u1} α (fun (a : α) (b : α) => _inst_1 a b)) (Bot.bot.{u1} (Finset.{u1} α) (GeneralizedBooleanAlgebra.toHasBot.{u1} (Finset.{u1} α) (Finset.generalizedBooleanAlgebra.{u1} α (fun (a : α) (b : α) => _inst_1 a b)))) (Singleton.singleton.{u1, u1} α (Finset.{u1} α) (Finset.hasSingleton.{u1} α)) s) s but is expected to have type forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (s : Finset.{u1} α), Eq.{succ u1} (Finset.{u1} α) (Finset.fold.{u1, u1} α (Finset.{u1} α) (fun ([email protected]._hyg.2814 : Finset.{u1} α) ([email protected]._hyg.2816 : Finset.{u1} α) => Sup.sup.{u1} (Finset.{u1} α) (SemilatticeSup.toSup.{u1} (Finset.{u1} α) (Lattice.toSemilatticeSup.{u1} (Finset.{u1} α) (Finset.instLatticeFinset.{u1} α (fun (a : α) (b : α) => _inst_1 a b)))) [email protected]._hyg.2814 [email protected]._hyg.2816) (instIsCommutativeSupToSup.{u1} (Finset.{u1} α) (Lattice.toSemilatticeSup.{u1} (Finset.{u1} α) (Finset.instLatticeFinset.{u1} α (fun (a : α) (b : α) => _inst_1 a b)))) (instIsAssociativeSupToSup.{u1} (Finset.{u1} α) (Lattice.toSemilatticeSup.{u1} (Finset.{u1} α) (Finset.instLatticeFinset.{u1} α (fun (a : α) (b : α) => _inst_1 a b)))) (Bot.bot.{u1} (Finset.{u1} α) (GeneralizedBooleanAlgebra.toBot.{u1} (Finset.{u1} α) (Finset.instGeneralizedBooleanAlgebraFinset.{u1} α (fun (a : α) (b : α) => _inst_1 a b)))) (Singleton.singleton.{u1, u1} α (Finset.{u1} α) (Finset.instSingletonFinset.{u1} α)) s) s Case conversion may be inaccurate. Consider using '#align finset.fold_sup_bot_singleton Finset.fold_sup_bot_singletonₓ'. -/ theorem fold_sup_bot_singleton [DecidableEq α] (s : Finset α) : Finset.fold (· ⊔ ·) ⊥ singleton s = s := fold_union_empty_singleton s #align finset.fold_sup_bot_singleton Finset.fold_sup_bot_singleton section Order variable [LinearOrder β] (c : β) /- warning: finset.le_fold_min -> Finset.le_fold_min is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (Finset.fold.{u1, u2} α β (LinearOrder.min.{u2} β _inst_1) (inf_isCommutative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (inf_isAssociative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s)) (And (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c b) (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (f x)))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (Finset.fold.{u1, u2} α β (Min.min.{u2} β (LinearOrder.toMin.{u2} β _inst_1)) (instIsCommutativeMinToMin.{u2} β _inst_1) (instIsAssociativeMinToMin.{u2} β _inst_1) b f s)) (And (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c b) (forall (x : α), (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) -> (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (f x)))) Case conversion may be inaccurate. Consider using '#align finset.le_fold_min Finset.le_fold_minₓ'. -/ theorem le_fold_min : c ≤ s.fold min b f ↔ c ≤ b ∧ ∀ x ∈ s, c ≤ f x := fold_op_rel_iff_and fun x y z => le_min_iff #align finset.le_fold_min Finset.le_fold_min /- warning: finset.fold_min_le -> Finset.fold_min_le is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (Finset.fold.{u1, u2} α β (LinearOrder.min.{u2} β _inst_1) (inf_isCommutative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (inf_isAssociative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s) c) (Or (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) b c) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) => LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (f x) c)))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (Finset.fold.{u1, u2} α β (Min.min.{u2} β (LinearOrder.toMin.{u2} β _inst_1)) (instIsCommutativeMinToMin.{u2} β _inst_1) (instIsAssociativeMinToMin.{u2} β _inst_1) b f s) c) (Or (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) b c) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (f x) c)))) Case conversion may be inaccurate. Consider using '#align finset.fold_min_le Finset.fold_min_leₓ'. -/ theorem fold_min_le : s.fold min b f ≤ c ↔ b ≤ c ∨ ∃ x ∈ s, f x ≤ c := by show _ ≥ _ ↔ _ apply fold_op_rel_iff_or intro x y z show _ ≤ _ ↔ _ exact min_le_iff #align finset.fold_min_le Finset.fold_min_le /- warning: finset.lt_fold_min -> Finset.lt_fold_min is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (Finset.fold.{u1, u2} α β (LinearOrder.min.{u2} β _inst_1) (inf_isCommutative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (inf_isAssociative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s)) (And (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c b) (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (f x)))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (Finset.fold.{u1, u2} α β (Min.min.{u2} β (LinearOrder.toMin.{u2} β _inst_1)) (instIsCommutativeMinToMin.{u2} β _inst_1) (instIsAssociativeMinToMin.{u2} β _inst_1) b f s)) (And (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c b) (forall (x : α), (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) -> (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (f x)))) Case conversion may be inaccurate. Consider using '#align finset.lt_fold_min Finset.lt_fold_minₓ'. -/ theorem lt_fold_min : c < s.fold min b f ↔ c < b ∧ ∀ x ∈ s, c < f x := fold_op_rel_iff_and fun x y z => lt_min_iff #align finset.lt_fold_min Finset.lt_fold_min /- warning: finset.fold_min_lt -> Finset.fold_min_lt is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (Finset.fold.{u1, u2} α β (LinearOrder.min.{u2} β _inst_1) (inf_isCommutative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (inf_isAssociative.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s) c) (Or (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) b c) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) => LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (f x) c)))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (Finset.fold.{u1, u2} α β (Min.min.{u2} β (LinearOrder.toMin.{u2} β _inst_1)) (instIsCommutativeMinToMin.{u2} β _inst_1) (instIsAssociativeMinToMin.{u2} β _inst_1) b f s) c) (Or (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) b c) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (f x) c)))) Case conversion may be inaccurate. Consider using '#align finset.fold_min_lt Finset.fold_min_ltₓ'. -/ theorem fold_min_lt : s.fold min b f < c ↔ b < c ∨ ∃ x ∈ s, f x < c := by show _ > _ ↔ _ apply fold_op_rel_iff_or intro x y z show _ < _ ↔ _ exact min_lt_iff #align finset.fold_min_lt Finset.fold_min_lt /- warning: finset.fold_max_le -> Finset.fold_max_le is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (Finset.fold.{u1, u2} α β (LinearOrder.max.{u2} β _inst_1) (sup_isCommutative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (sup_isAssociative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s) c) (And (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) b c) (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (f x) c))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (Finset.fold.{u1, u2} α β (Max.max.{u2} β (LinearOrder.toMax.{u2} β _inst_1)) (instIsCommutativeMaxToMax.{u2} β _inst_1) (instIsAssociativeMaxToMax.{u2} β _inst_1) b f s) c) (And (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) b c) (forall (x : α), (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) -> (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (f x) c))) Case conversion may be inaccurate. Consider using '#align finset.fold_max_le Finset.fold_max_leₓ'. -/ theorem fold_max_le : s.fold max b f ≤ c ↔ b ≤ c ∧ ∀ x ∈ s, f x ≤ c := by show _ ≥ _ ↔ _ apply fold_op_rel_iff_and intro x y z show _ ≤ _ ↔ _ exact max_le_iff #align finset.fold_max_le Finset.fold_max_le /- warning: finset.le_fold_max -> Finset.le_fold_max is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (Finset.fold.{u1, u2} α β (LinearOrder.max.{u2} β _inst_1) (sup_isCommutative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (sup_isAssociative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s)) (Or (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c b) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) => LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (f x))))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (Finset.fold.{u1, u2} α β (Max.max.{u2} β (LinearOrder.toMax.{u2} β _inst_1)) (instIsCommutativeMaxToMax.{u2} β _inst_1) (instIsAssociativeMaxToMax.{u2} β _inst_1) b f s)) (Or (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c b) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (f x))))) Case conversion may be inaccurate. Consider using '#align finset.le_fold_max Finset.le_fold_maxₓ'. -/ theorem le_fold_max : c ≤ s.fold max b f ↔ c ≤ b ∨ ∃ x ∈ s, c ≤ f x := fold_op_rel_iff_or fun x y z => le_max_iff #align finset.le_fold_max Finset.le_fold_max /- warning: finset.fold_max_lt -> Finset.fold_max_lt is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (Finset.fold.{u1, u2} α β (LinearOrder.max.{u2} β _inst_1) (sup_isCommutative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (sup_isAssociative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s) c) (And (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) b c) (forall (x : α), (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) -> (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) (f x) c))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (Finset.fold.{u1, u2} α β (Max.max.{u2} β (LinearOrder.toMax.{u2} β _inst_1)) (instIsCommutativeMaxToMax.{u2} β _inst_1) (instIsAssociativeMaxToMax.{u2} β _inst_1) b f s) c) (And (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) b c) (forall (x : α), (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) -> (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) (f x) c))) Case conversion may be inaccurate. Consider using '#align finset.fold_max_lt Finset.fold_max_ltₓ'. -/ theorem fold_max_lt : s.fold max b f < c ↔ b < c ∧ ∀ x ∈ s, f x < c := by show _ > _ ↔ _ apply fold_op_rel_iff_and intro x y z show _ < _ ↔ _ exact max_lt_iff #align finset.fold_max_lt Finset.fold_max_lt /- warning: finset.lt_fold_max -> Finset.lt_fold_max is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (Finset.fold.{u1, u2} α β (LinearOrder.max.{u2} β _inst_1) (sup_isCommutative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) (sup_isAssociative.{u2} β (Lattice.toSemilatticeSup.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))) b f s)) (Or (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c b) (Exists.{succ u1} α (fun (x : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) (fun (H : Membership.Mem.{u1, u1} α (Finset.{u1} α) (Finset.hasMem.{u1} α) x s) => LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))) c (f x))))) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {b : β} {s : Finset.{u1} α} [_inst_1 : LinearOrder.{u2} β] (c : β), Iff (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (Finset.fold.{u1, u2} α β (Max.max.{u2} β (LinearOrder.toMax.{u2} β _inst_1)) (instIsCommutativeMaxToMax.{u2} β _inst_1) (instIsAssociativeMaxToMax.{u2} β _inst_1) b f s)) (Or (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c b) (Exists.{succ u1} α (fun (x : α) => And (Membership.mem.{u1, u1} α (Finset.{u1} α) (Finset.instMembershipFinset.{u1} α) x s) (LT.lt.{u2} β (Preorder.toLT.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) c (f x))))) Case conversion may be inaccurate. Consider using '#align finset.lt_fold_max Finset.lt_fold_maxₓ'. -/ theorem lt_fold_max : c < s.fold max b f ↔ c < b ∨ ∃ x ∈ s, c < f x := fold_op_rel_iff_or fun x y z => lt_max_iff #align finset.lt_fold_max Finset.lt_fold_max /- warning: finset.fold_max_add -> Finset.fold_max_add is a dubious translation: lean 3 declaration is forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} [_inst_1 : LinearOrder.{u2} β] [_inst_2 : Add.{u2} β] [_inst_3 : CovariantClass.{u2, u2} β β (Function.swap.{succ u2, succ u2, succ u2} β β (fun (ᾰ : β) (ᾰ : β) => β) (HAdd.hAdd.{u2, u2, u2} β β β (instHAdd.{u2} β _inst_2))) (LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (LinearOrder.toLattice.{u2} β _inst_1))))))] (n : WithBot.{u2} β) (s : Finset.{u1} α), Eq.{succ u2} (WithBot.{u2} β) (Finset.fold.{u1, u2} α (WithBot.{u2} β) (LinearOrder.max.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (sup_isCommutative.{u2} (WithBot.{u2} β) (Lattice.toSemilatticeSup.{u2} (WithBot.{u2} β) (WithBot.lattice.{u2} β (LinearOrder.toLattice.{u2} β _inst_1)))) (sup_isAssociative.{u2} (WithBot.{u2} β) (Lattice.toSemilatticeSup.{u2} (WithBot.{u2} β) (WithBot.lattice.{u2} β (LinearOrder.toLattice.{u2} β _inst_1)))) (Bot.bot.{u2} (WithBot.{u2} β) (WithBot.hasBot.{u2} β)) (fun (x : α) => HAdd.hAdd.{u2, u2, u2} (WithBot.{u2} β) (WithBot.{u2} β) (WithBot.{u2} β) (instHAdd.{u2} (WithBot.{u2} β) (WithBot.hasAdd.{u2} β _inst_2)) ((fun (a : Type.{u2}) (b : Type.{u2}) [self : HasLiftT.{succ u2, succ u2} a b] => self.0) β (WithBot.{u2} β) (HasLiftT.mk.{succ u2, succ u2} β (WithBot.{u2} β) (CoeTCₓ.coe.{succ u2, succ u2} β (WithBot.{u2} β) (WithBot.hasCoeT.{u2} β))) (f x)) n) s) (HAdd.hAdd.{u2, u2, u2} (WithBot.{u2} β) (WithBot.{u2} β) (WithBot.{u2} β) (instHAdd.{u2} (WithBot.{u2} β) (WithBot.hasAdd.{u2} β _inst_2)) (Finset.fold.{u1, u2} α (WithBot.{u2} β) (LinearOrder.max.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (sup_isCommutative.{u2} (WithBot.{u2} β) (Lattice.toSemilatticeSup.{u2} (WithBot.{u2} β) (WithBot.lattice.{u2} β (LinearOrder.toLattice.{u2} β _inst_1)))) (sup_isAssociative.{u2} (WithBot.{u2} β) (Lattice.toSemilatticeSup.{u2} (WithBot.{u2} β) (WithBot.lattice.{u2} β (LinearOrder.toLattice.{u2} β _inst_1)))) (Bot.bot.{u2} (WithBot.{u2} β) (WithBot.hasBot.{u2} β)) (Function.comp.{succ u1, succ u2, succ u2} α β (WithBot.{u2} β) ((fun (a : Type.{u2}) (b : Type.{u2}) [self : HasLiftT.{succ u2, succ u2} a b] => self.0) β (WithBot.{u2} β) (HasLiftT.mk.{succ u2, succ u2} β (WithBot.{u2} β) (CoeTCₓ.coe.{succ u2, succ u2} β (WithBot.{u2} β) (WithBot.hasCoeT.{u2} β)))) f) s) n) but is expected to have type forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} [_inst_1 : LinearOrder.{u2} β] [_inst_2 : Add.{u2} β] [_inst_3 : CovariantClass.{u2, u2} β β (Function.swap.{succ u2, succ u2, succ u2} β β (fun (ᾰ : β) (ᾰ : β) => β) (fun ([email protected]._hyg.3739 : β) ([email protected]._hyg.3741 : β) => HAdd.hAdd.{u2, u2, u2} β β β (instHAdd.{u2} β _inst_2) [email protected]._hyg.3739 [email protected]._hyg.3741)) (fun ([email protected]._hyg.3754 : β) ([email protected]._hyg.3756 : β) => LE.le.{u2} β (Preorder.toLE.{u2} β (PartialOrder.toPreorder.{u2} β (SemilatticeInf.toPartialOrder.{u2} β (Lattice.toSemilatticeInf.{u2} β (DistribLattice.toLattice.{u2} β (instDistribLattice.{u2} β _inst_1)))))) [email protected]._hyg.3754 [email protected]._hyg.3756)] (n : WithBot.{u2} β) (s : Finset.{u1} α), Eq.{succ u2} (WithBot.{u2} β) (Finset.fold.{u1, u2} α (WithBot.{u2} β) (Max.max.{u2} (WithBot.{u2} β) (LinearOrder.toMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1))) (instIsCommutativeMaxToMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (instIsAssociativeMaxToMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (Bot.bot.{u2} (WithBot.{u2} β) (WithBot.bot.{u2} β)) (fun (x : α) => HAdd.hAdd.{u2, u2, u2} (WithBot.{u2} β) (WithBot.{u2} β) (WithBot.{u2} β) (instHAdd.{u2} (WithBot.{u2} β) (WithBot.add.{u2} β _inst_2)) (WithBot.some.{u2} β (f x)) n) s) (HAdd.hAdd.{u2, u2, u2} (WithBot.{u2} β) (WithBot.{u2} β) (WithBot.{u2} β) (instHAdd.{u2} (WithBot.{u2} β) (WithBot.add.{u2} β _inst_2)) (Finset.fold.{u1, u2} α (WithBot.{u2} β) (Max.max.{u2} (WithBot.{u2} β) (LinearOrder.toMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1))) (instIsCommutativeMaxToMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (instIsAssociativeMaxToMax.{u2} (WithBot.{u2} β) (WithBot.linearOrder.{u2} β _inst_1)) (Bot.bot.{u2} (WithBot.{u2} β) (WithBot.bot.{u2} β)) (Function.comp.{succ u1, succ u2, succ u2} α β (WithBot.{u2} β) (WithBot.some.{u2} β) f) s) n) Case conversion may be inaccurate. Consider using '#align finset.fold_max_add Finset.fold_max_addₓ'. -/ theorem fold_max_add [Add β] [CovariantClass β β (Function.swap (· + ·)) (· ≤ ·)] (n : WithBot β) (s : Finset α) : (s.fold max ⊥ fun x : α => ↑(f x) + n) = s.fold max ⊥ (coe ∘ f) + n := by classical apply s.induction_on <;> simp (config := { contextual := true }) [max_add_add_right] #align finset.fold_max_add Finset.fold_max_add end Order end Fold end Finset