Datasets:
AI4M
/

text
stringlengths
0
3.34M
open import Relation.Binary.Core module InsertSort.Impl2 {A : Set} (_≤_ : A → A → Set) (tot≤ : Total _≤_) where open import Bound.Lower A open import Bound.Lower.Order _≤_ open import Data.List open import Data.Sum open import OList _≤_ insert : {b : Bound}{x : A} → LeB b (val x) → OList b → OList b insert {b} {x} b≤x onil = :< b≤x onil insert {b} {x} b≤x (:< {x = y} b≤y ys) with tot≤ x y ... | inj₁ x≤y = :< b≤x (:< (lexy x≤y) ys) ... | inj₂ y≤x = :< b≤y (insert (lexy y≤x) ys) insertSort : List A → OList bot insertSort [] = onil insertSort (x ∷ xs) = insert {bot} {x} lebx (insertSort xs)
lemma vector_eq_ldot: "(\<forall>x. x \<bullet> y = x \<bullet> z) \<longleftrightarrow> y = z"
[STATEMENT] lemma mono_lex1: "mono (\<lambda>r. lex_prod r s)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. mono (\<lambda>r. r <*lex*> s) [PROOF STEP] by (auto simp add: mono_def)
# This function does the core add-in work. increment <- function(delta) { # Get information about the current document context <- rstudioapi::getActiveDocumentContext() # Loop over all of the selected text regions in the document for (sel in context$selection) { # Attempt to coerce the selected text to a number; skip if it's not a # number. suppressWarnings(int <- as.integer(sel$text)) if (is.na(int)) next # Replace the selection with the the updated number. rstudioapi::modifyRange(sel$range, as.character(int+delta), context$id) break } } # This is an exposed add-in function; it increments the selected number by 1. incrementr <- function() { increment(1) } # This is an exposed add-in function; it decrements the selected number by 1. decrementr <- function() { increment(-1) }
(* Title: ZF/Induct/PropLog.thy Author: Tobias Nipkow & Lawrence C Paulson Copyright 1993 University of Cambridge *) section \<open>Meta-theory of propositional logic\<close> theory PropLog imports ZF begin text \<open> Datatype definition of propositional logic formulae and inductive definition of the propositional tautologies. Inductive definition of propositional logic. Soundness and completeness w.r.t.\ truth-tables. Prove: If \<open>H |= p\<close> then \<open>G |= p\<close> where \<open>G \<in> Fin(H)\<close> \<close> subsection \<open>The datatype of propositions\<close> consts propn :: i datatype propn = Fls | Var ("n \<in> nat") (\<open>#_\<close> [100] 100) | Imp ("p \<in> propn", "q \<in> propn") (infixr \<open>\<Rightarrow>\<close> 90) subsection \<open>The proof system\<close> consts thms :: "i \<Rightarrow> i" abbreviation thms_syntax :: "[i,i] \<Rightarrow> o" (infixl \<open>|-\<close> 50) where "H |- p \<equiv> p \<in> thms(H)" inductive domains "thms(H)" \<subseteq> "propn" intros H: "\<lbrakk>p \<in> H; p \<in> propn\<rbrakk> \<Longrightarrow> H |- p" K: "\<lbrakk>p \<in> propn; q \<in> propn\<rbrakk> \<Longrightarrow> H |- p\<Rightarrow>q\<Rightarrow>p" S: "\<lbrakk>p \<in> propn; q \<in> propn; r \<in> propn\<rbrakk> \<Longrightarrow> H |- (p\<Rightarrow>q\<Rightarrow>r) \<Rightarrow> (p\<Rightarrow>q) \<Rightarrow> p\<Rightarrow>r" DN: "p \<in> propn \<Longrightarrow> H |- ((p\<Rightarrow>Fls) \<Rightarrow> Fls) \<Rightarrow> p" MP: "\<lbrakk>H |- p\<Rightarrow>q; H |- p; p \<in> propn; q \<in> propn\<rbrakk> \<Longrightarrow> H |- q" type_intros "propn.intros" declare propn.intros [simp] subsection \<open>The semantics\<close> subsubsection \<open>Semantics of propositional logic.\<close> consts is_true_fun :: "[i,i] \<Rightarrow> i" primrec "is_true_fun(Fls, t) = 0" "is_true_fun(Var(v), t) = (if v \<in> t then 1 else 0)" "is_true_fun(p\<Rightarrow>q, t) = (if is_true_fun(p,t) = 1 then is_true_fun(q,t) else 1)" definition is_true :: "[i,i] \<Rightarrow> o" where "is_true(p,t) \<equiv> is_true_fun(p,t) = 1" \<comment> \<open>this definition is required since predicates can't be recursive\<close> lemma is_true_Fls [simp]: "is_true(Fls,t) \<longleftrightarrow> False" by (simp add: is_true_def) lemma is_true_Var [simp]: "is_true(#v,t) \<longleftrightarrow> v \<in> t" by (simp add: is_true_def) lemma is_true_Imp [simp]: "is_true(p\<Rightarrow>q,t) \<longleftrightarrow> (is_true(p,t)\<longrightarrow>is_true(q,t))" by (simp add: is_true_def) subsubsection \<open>Logical consequence\<close> text \<open> For every valuation, if all elements of \<open>H\<close> are true then so is \<open>p\<close>. \<close> definition logcon :: "[i,i] \<Rightarrow> o" (infixl \<open>|=\<close> 50) where "H |= p \<equiv> \<forall>t. (\<forall>q \<in> H. is_true(q,t)) \<longrightarrow> is_true(p,t)" text \<open> A finite set of hypotheses from \<open>t\<close> and the \<open>Var\<close>s in \<open>p\<close>. \<close> consts hyps :: "[i,i] \<Rightarrow> i" primrec "hyps(Fls, t) = 0" "hyps(Var(v), t) = (if v \<in> t then {#v} else {#v\<Rightarrow>Fls})" "hyps(p\<Rightarrow>q, t) = hyps(p,t) \<union> hyps(q,t)" subsection \<open>Proof theory of propositional logic\<close> lemma thms_mono: "G \<subseteq> H \<Longrightarrow> thms(G) \<subseteq> thms(H)" unfolding thms.defs apply (rule lfp_mono) apply (rule thms.bnd_mono)+ apply (assumption | rule univ_mono basic_monos)+ done lemmas thms_in_pl = thms.dom_subset [THEN subsetD] inductive_cases ImpE: "p\<Rightarrow>q \<in> propn" lemma thms_MP: "\<lbrakk>H |- p\<Rightarrow>q; H |- p\<rbrakk> \<Longrightarrow> H |- q" \<comment> \<open>Stronger Modus Ponens rule: no typechecking!\<close> apply (rule thms.MP) apply (erule asm_rl thms_in_pl thms_in_pl [THEN ImpE])+ done lemma thms_I: "p \<in> propn \<Longrightarrow> H |- p\<Rightarrow>p" \<comment> \<open>Rule is called \<open>I\<close> for Identity Combinator, not for Introduction.\<close> apply (rule thms.S [THEN thms_MP, THEN thms_MP]) apply (rule_tac [5] thms.K) apply (rule_tac [4] thms.K) apply simp_all done subsubsection \<open>Weakening, left and right\<close> lemma weaken_left: "\<lbrakk>G \<subseteq> H; G|-p\<rbrakk> \<Longrightarrow> H|-p" \<comment> \<open>Order of premises is convenient with \<open>THEN\<close>\<close> by (erule thms_mono [THEN subsetD]) lemma weaken_left_cons: "H |- p \<Longrightarrow> cons(a,H) |- p" by (erule subset_consI [THEN weaken_left]) lemmas weaken_left_Un1 = Un_upper1 [THEN weaken_left] lemmas weaken_left_Un2 = Un_upper2 [THEN weaken_left] lemma weaken_right: "\<lbrakk>H |- q; p \<in> propn\<rbrakk> \<Longrightarrow> H |- p\<Rightarrow>q" by (simp_all add: thms.K [THEN thms_MP] thms_in_pl) subsubsection \<open>The deduction theorem\<close> theorem deduction: "\<lbrakk>cons(p,H) |- q; p \<in> propn\<rbrakk> \<Longrightarrow> H |- p\<Rightarrow>q" apply (erule thms.induct) apply (blast intro: thms_I thms.H [THEN weaken_right]) apply (blast intro: thms.K [THEN weaken_right]) apply (blast intro: thms.S [THEN weaken_right]) apply (blast intro: thms.DN [THEN weaken_right]) apply (blast intro: thms.S [THEN thms_MP [THEN thms_MP]]) done subsubsection \<open>The cut rule\<close> lemma cut: "\<lbrakk>H|-p; cons(p,H) |- q\<rbrakk> \<Longrightarrow> H |- q" apply (rule deduction [THEN thms_MP]) apply (simp_all add: thms_in_pl) done lemma thms_FlsE: "\<lbrakk>H |- Fls; p \<in> propn\<rbrakk> \<Longrightarrow> H |- p" apply (rule thms.DN [THEN thms_MP]) apply (rule_tac [2] weaken_right) apply (simp_all add: propn.intros) done lemma thms_notE: "\<lbrakk>H |- p\<Rightarrow>Fls; H |- p; q \<in> propn\<rbrakk> \<Longrightarrow> H |- q" by (erule thms_MP [THEN thms_FlsE]) subsubsection \<open>Soundness of the rules wrt truth-table semantics\<close> theorem soundness: "H |- p \<Longrightarrow> H |= p" unfolding logcon_def apply (induct set: thms) apply auto done subsection \<open>Completeness\<close> subsubsection \<open>Towards the completeness proof\<close> lemma Fls_Imp: "\<lbrakk>H |- p\<Rightarrow>Fls; q \<in> propn\<rbrakk> \<Longrightarrow> H |- p\<Rightarrow>q" apply (frule thms_in_pl) apply (rule deduction) apply (rule weaken_left_cons [THEN thms_notE]) apply (blast intro: thms.H elim: ImpE)+ done lemma Imp_Fls: "\<lbrakk>H |- p; H |- q\<Rightarrow>Fls\<rbrakk> \<Longrightarrow> H |- (p\<Rightarrow>q)\<Rightarrow>Fls" apply (frule thms_in_pl) apply (frule thms_in_pl [of concl: "q\<Rightarrow>Fls"]) apply (rule deduction) apply (erule weaken_left_cons [THEN thms_MP]) apply (rule consI1 [THEN thms.H, THEN thms_MP]) apply (blast intro: weaken_left_cons elim: ImpE)+ done lemma hyps_thms_if: "p \<in> propn \<Longrightarrow> hyps(p,t) |- (if is_true(p,t) then p else p\<Rightarrow>Fls)" \<comment> \<open>Typical example of strengthening the induction statement.\<close> apply simp apply (induct_tac p) apply (simp_all add: thms_I thms.H) apply (safe elim!: Fls_Imp [THEN weaken_left_Un1] Fls_Imp [THEN weaken_left_Un2]) apply (blast intro: weaken_left_Un1 weaken_left_Un2 weaken_right Imp_Fls)+ done lemma logcon_thms_p: "\<lbrakk>p \<in> propn; 0 |= p\<rbrakk> \<Longrightarrow> hyps(p,t) |- p" \<comment> \<open>Key lemma for completeness; yields a set of assumptions satisfying \<open>p\<close>\<close> apply (drule hyps_thms_if) apply (simp add: logcon_def) done text \<open> For proving certain theorems in our new propositional logic. \<close> lemmas propn_SIs = propn.intros deduction and propn_Is = thms_in_pl thms.H thms.H [THEN thms_MP] text \<open> The excluded middle in the form of an elimination rule. \<close> lemma thms_excluded_middle: "\<lbrakk>p \<in> propn; q \<in> propn\<rbrakk> \<Longrightarrow> H |- (p\<Rightarrow>q) \<Rightarrow> ((p\<Rightarrow>Fls)\<Rightarrow>q) \<Rightarrow> q" apply (rule deduction [THEN deduction]) apply (rule thms.DN [THEN thms_MP]) apply (best intro!: propn_SIs intro: propn_Is)+ done lemma thms_excluded_middle_rule: "\<lbrakk>cons(p,H) |- q; cons(p\<Rightarrow>Fls,H) |- q; p \<in> propn\<rbrakk> \<Longrightarrow> H |- q" \<comment> \<open>Hard to prove directly because it requires cuts\<close> apply (rule thms_excluded_middle [THEN thms_MP, THEN thms_MP]) apply (blast intro!: propn_SIs intro: propn_Is)+ done subsubsection \<open>Completeness -- lemmas for reducing the set of assumptions\<close> text \<open> For the case \<^prop>\<open>hyps(p,t)-cons(#v,Y) |- p\<close> we also have \<^prop>\<open>hyps(p,t)-{#v} \<subseteq> hyps(p, t-{v})\<close>. \<close> lemma hyps_Diff: "p \<in> propn \<Longrightarrow> hyps(p, t-{v}) \<subseteq> cons(#v\<Rightarrow>Fls, hyps(p,t)-{#v})" by (induct set: propn) auto text \<open> For the case \<^prop>\<open>hyps(p,t)-cons(#v \<Rightarrow> Fls,Y) |- p\<close> we also have \<^prop>\<open>hyps(p,t)-{#v\<Rightarrow>Fls} \<subseteq> hyps(p, cons(v,t))\<close>. \<close> lemma hyps_cons: "p \<in> propn \<Longrightarrow> hyps(p, cons(v,t)) \<subseteq> cons(#v, hyps(p,t)-{#v\<Rightarrow>Fls})" by (induct set: propn) auto text \<open>Two lemmas for use with \<open>weaken_left\<close>\<close> lemma cons_Diff_same: "B-C \<subseteq> cons(a, B-cons(a,C))" by blast lemma cons_Diff_subset2: "cons(a, B-{c}) - D \<subseteq> cons(a, B-cons(c,D))" by blast text \<open> The set \<^term>\<open>hyps(p,t)\<close> is finite, and elements have the form \<^term>\<open>#v\<close> or \<^term>\<open>#v\<Rightarrow>Fls\<close>; could probably prove the stronger \<^prop>\<open>hyps(p,t) \<in> Fin(hyps(p,0) \<union> hyps(p,nat))\<close>. \<close> lemma hyps_finite: "p \<in> propn \<Longrightarrow> hyps(p,t) \<in> Fin(\<Union>v \<in> nat. {#v, #v\<Rightarrow>Fls})" by (induct set: propn) auto lemmas Diff_weaken_left = Diff_mono [OF _ subset_refl, THEN weaken_left] text \<open> Induction on the finite set of assumptions \<^term>\<open>hyps(p,t0)\<close>. We may repeatedly subtract assumptions until none are left! \<close> lemma completeness_0_lemma [rule_format]: "\<lbrakk>p \<in> propn; 0 |= p\<rbrakk> \<Longrightarrow> \<forall>t. hyps(p,t) - hyps(p,t0) |- p" apply (frule hyps_finite) apply (erule Fin_induct) apply (simp add: logcon_thms_p Diff_0) txt \<open>inductive step\<close> apply safe txt \<open>Case \<^prop>\<open>hyps(p,t)-cons(#v,Y) |- p\<close>\<close> apply (rule thms_excluded_middle_rule) apply (erule_tac [3] propn.intros) apply (blast intro: cons_Diff_same [THEN weaken_left]) apply (blast intro: cons_Diff_subset2 [THEN weaken_left] hyps_Diff [THEN Diff_weaken_left]) txt \<open>Case \<^prop>\<open>hyps(p,t)-cons(#v \<Rightarrow> Fls,Y) |- p\<close>\<close> apply (rule thms_excluded_middle_rule) apply (erule_tac [3] propn.intros) apply (blast intro: cons_Diff_subset2 [THEN weaken_left] hyps_cons [THEN Diff_weaken_left]) apply (blast intro: cons_Diff_same [THEN weaken_left]) done subsubsection \<open>Completeness theorem\<close> lemma completeness_0: "\<lbrakk>p \<in> propn; 0 |= p\<rbrakk> \<Longrightarrow> 0 |- p" \<comment> \<open>The base case for completeness\<close> apply (rule Diff_cancel [THEN subst]) apply (blast intro: completeness_0_lemma) done lemma logcon_Imp: "\<lbrakk>cons(p,H) |= q\<rbrakk> \<Longrightarrow> H |= p\<Rightarrow>q" \<comment> \<open>A semantic analogue of the Deduction Theorem\<close> by (simp add: logcon_def) lemma completeness: "H \<in> Fin(propn) \<Longrightarrow> p \<in> propn \<Longrightarrow> H |= p \<Longrightarrow> H |- p" apply (induct arbitrary: p set: Fin) apply (safe intro!: completeness_0) apply (rule weaken_left_cons [THEN thms_MP]) apply (blast intro!: logcon_Imp propn.intros) apply (blast intro: propn_Is) done theorem thms_iff: "H \<in> Fin(propn) \<Longrightarrow> H |- p \<longleftrightarrow> H |= p \<and> p \<in> propn" by (blast intro: soundness completeness thms_in_pl) end
\section{API} \label{api} One of our goals in this project was to provide a flexible API that decouples the user application from the underlying peer-to-peer routing and lookup system. The Chimera API follows the syntax defined in "Towards a Common API for Structured Peer-to-Peer Overlays" \cite{commonapi}. Use of this API eases substitution of underlying routing with minimum effort and facilitates user level application testing based on different routings. The Chimera interface consists of two main parts: the routing state access and the message upcall interface. The routing state access interface allows an application to directly access to routing state information. These calls can be used to access routing information and make application level routing decisions. The message upcall system interfaces with the application based on the events in routing layer. We will describe the message upcall interfaces and routing state access in detail in sections \ref{upcall-api} and \ref{routing-api}. The functions describe the core interface to the Chimera systems. Other functions to exist to fine tune Chimera performance and behavior, but those functions are left to technical documentation. \subsection{Message Upcalls} \label{upcall-api} All the upcall functions take a function pointer as their only argument. This variable points to a function provided by the application that is declared as described. This system allows the user to respond to events that occur in the routing layer. They also allow the applications to make changes to some of the decisions made by Chimera. There are three upcalls, and they are described here. {\noindent \bf typedef void (*chimera\_update\_upcall\_t)(Key *key, ChimeraHost *host, int joined);}\\ {\noindent \bf void chimera\_update(chimera\_update\_upcall\_t func);} The update upcall function is called when a {\em host} with a given {\em key} leaves or joins local node's leaf set. The {\em joined} integer is 0 if the node leaves the leaf set and 1 if it joins the leaf set. {\noindent \bf typedef void (*chimera\_forward\_upcall\_t)(Key **key, Message **msg, ChimeraHost **host);}\\ {\noindent \bf void chimera\_forward(chimera\_forward\_upcall\_t func);} The forward upcall informs application that routing layer is about to forward a message {\em msg} towards the destination {\em key} via a {\em host}. This upcall allows the application to modify any of the parameters to override the routing decisions made by the Chimera routing layer. This allows the application to change the next hope, the message, or the destination key. {\noindent \bf typedef void (*chimera\_deliver\_upcall\_t)(Key *key, Message *msg);}\\ {\noindent \bf void chimera\_deliver(chimera\_deliver\_upcall\_t func);} This upcall occurs when the current node receives a message {\em msg} destined for a {\em key} that is responsible for. This upcall indicates that the message has reached its final destination. \subsection{Routing} \label{routing-api} This API allows the application to access routing state and pass down application routing preferences. Application layer feedback to the routing layer provides the application with the flexibility to enforce its policy on the underlying peer-to-peer routing and lookup system without needing to modify the routing mechanism. {\noindent \bf ChimeraHost **route\_lookup(Key key, int count, int is\_safe)} This call returns an array of at least {\em count} ChimeraHost structures that represent acceptable next hops on a route toward a {\em key}. This version of Chimera ignores {\em is\_safe} and {\em count} variables, but we keep them in the syntax for future compatibility. The current version of Chimera returns only the best next hop based on routing protocol that we described in section \ref{routing-api}. If there is no hop closer than the local host, and the message has reached its destination, this function returns NULL. {\noindent \bf void chimera\_route(Key *key, Message *msg, ChimeraHost *hint)} The chimera\_route function will send a message {\em msg} through the Chimera routing layer to the destination {\em key}. If the {\em hint} option is not NULL, the system will use the provided host as its next hop. This call will cause either a chimera\_deliver or a chimera\_forward upcall, described in section \ref{upcall-api}. This will eventually route the message to the key root in the existing overlay. {\noindent \bf ChimeraHost **route\_neighbors(int count)} This call will return an array of the {\em count} closest nodes in the leaf set of the local node. The returned array is NULL terminated, so that if there are not enough hosts in the leaf set to service the request the array will be terminated early.
State Before: ι : Sort ?u.35598 α : Type u β : Type v inst✝¹ : PseudoEMetricSpace α inst✝ : PseudoEMetricSpace β x y : α s t u : Set α Φ : α → β ⊢ hausdorffEdist s t = hausdorffEdist t s State After: ι : Sort ?u.35598 α : Type u β : Type v inst✝¹ : PseudoEMetricSpace α inst✝ : PseudoEMetricSpace β x y : α s t u : Set α Φ : α → β ⊢ ((⨆ (x : α) (_ : x ∈ s), infEdist x t) ⊔ ⨆ (y : α) (_ : y ∈ t), infEdist y s) = (⨆ (y : α) (_ : y ∈ t), infEdist y s) ⊔ ⨆ (x : α) (_ : x ∈ s), infEdist x t Tactic: simp only [hausdorffEdist_def] State Before: ι : Sort ?u.35598 α : Type u β : Type v inst✝¹ : PseudoEMetricSpace α inst✝ : PseudoEMetricSpace β x y : α s t u : Set α Φ : α → β ⊢ ((⨆ (x : α) (_ : x ∈ s), infEdist x t) ⊔ ⨆ (y : α) (_ : y ∈ t), infEdist y s) = (⨆ (y : α) (_ : y ∈ t), infEdist y s) ⊔ ⨆ (x : α) (_ : x ∈ s), infEdist x t State After: no goals Tactic: apply sup_comm
SUBROUTINE forces USE vmec_main, p5 => cp5 USE realspace USE vforces IMPLICIT NONE C----------------------------------------------- C L o c a l P a r a m e t e r s C----------------------------------------------- REAL(rprec), PARAMETER :: p25 = p5*p5, dphids=p25 C----------------------------------------------- C L o c a l V a r i a b l e s C----------------------------------------------- INTEGER :: l, ndim REAL(rprec), DIMENSION(:), POINTER :: lv_e, lu_e, lu_o, 1 bsqr, gvvs, guvs, guus C----------------------------------------------- ndim = 1+nrzt ! ! POINTER ALIASES ! ! gcon => z1(:,0) lv_e => crmn_e; lu_e => czmn_e; lu_o => czmn_o bsqr => extra1(:,1); gvvs => extra2(:,1) guvs => extra3(:,1); guus => extra4(:,1) ! ! ON ENTRY, ARMN=ZU,BRMN=ZS,AZMN=RU,BZMN=RS,LU=R*BSQ,LV = BSQ*SQRT(G)/R12 ! HERE, XS (X=Z,R) DO NOT INCLUDE DERIVATIVE OF EXPLICIT SQRT(S) ! BSQ = |B|**2/2 + p ! GIJ = (BsupI * BsupJ) * SQRT(G) (I,J = U,V) ! IT IS ESSENTIAL THAT LU,LV AT j=1 ARE ZERO INITIALLY ! ! SOME OF THE BIGGER LOOPS WERE SPLIT TO FACILITATE CACHE ! HITS, PIPELINING ON RISCS ! ! FOR OPTIMIZATION ON CRAY, MUST USE COMPILER DIRECTIVES TO ! GET VECTORIZATION OF LOOPS INVOLVING POINTERS! ! ! ! ORIGIN OF VARIOUS TERMS ! ! LU : VARIATION OF DOMINANT .5*(RU-odd*Zodd - ZU-odd*Rodd) TERM ! IN JACOBIAN ! ! LV : VARIATION OF R-TERM IN JACOBIAN ! ! GVV: VARIATION OF R**2-TERM AND Rv**2,Zv**2 IN gvv ! ! GUU, GUV: VARIATION OF Ru, Rv, Zu, Zv IN guu, guv ! lu_e(1:ndim:ns) = 0; lv_e(1:ndim:ns) = 0 guu(1:ndim:ns) = 0; guv(1:ndim:ns) = 0; gvv(1:ndim:ns) = 0 guus = guu*shalf; guvs = guv*shalf; gvvs = gvv*shalf armn_e = ohs*armn_e * lu_e azmn_e =-ohs*azmn_e * lu_e brmn_e = brmn_e * lu_e bzmn_e =-bzmn_e * lu_e bsqr = dphids*lu_e/shalf armn_o(1:ndim) = armn_e(1:ndim) *shalf azmn_o(1:ndim) = azmn_e(1:ndim) *shalf brmn_o(1:ndim) = brmn_e(1:ndim) *shalf bzmn_o(1:ndim) = bzmn_e(1:ndim) *shalf ! ! CONSTRUCT CYLINDRICAL FORCE KERNELS ! NOTE: presg(ns+1) == 0, AND WILL BE "FILLED IN" AT EDGE ! FOR FREE-BOUNDARY BY RBSQ ! !DIR$ IVDEP DO l = 1, nrzt guu(l) = p5*(guu(l) + guu(l+1)) gvv(l) = p5*(gvv(l) + gvv(l+1)) bsqr(l) = bsqr(l) + bsqr(l+1) guus(l) = p5*(guus(l) + guus(l+1)) gvvs(l) = p5*(gvvs(l) + gvvs(l+1)) END DO !DIR$ IVDEP DO l = 1, nrzt armn_e(l) = armn_e(l+1) - armn_e(l) + p5*(lv_e(l) + lv_e(l+1)) azmn_e(l) = azmn_e(l+1) - azmn_e(l) brmn_e(l) = p5*(brmn_e(l) + brmn_e(l+1)) bzmn_e(l) = p5*(bzmn_e(l) + bzmn_e(l+1)) END DO armn_e(:nrzt) = armn_e(:nrzt) - (gvvs(:nrzt)*r1(:nrzt,1) 1 + gvv(:nrzt)*r1(:nrzt,0)) brmn_e(:nrzt) = brmn_e(:nrzt) + bsqr(:nrzt)*z1(:nrzt,1) 1 -(guus(:nrzt)*ru(:nrzt,1) + guu(:nrzt)*ru(:nrzt,0)) bzmn_e(:nrzt) = bzmn_e(:nrzt) - (bsqr(:nrzt)*r1(:nrzt,1) 1 + guus(:nrzt)*zu(:nrzt,1) + guu(:nrzt)*zu(:nrzt,0)) lv_e(1:ndim) = lv_e(1:ndim)*shalf(1:ndim) lu_o(1:ndim) = dphids*lu_e(1:ndim) !DIR$ IVDEP DO l = 1, nrzt armn_o(l) = armn_o(l+1) - armn_o(l) - zu(l,0)*bsqr(l) 1 + p5*(lv_e(l) + lv_e(l+1)) azmn_o(l) = azmn_o(l+1) - azmn_o(l) + ru(l,0)*bsqr(l) brmn_o(l) = p5*(brmn_o(l) + brmn_o(l+1)) bzmn_o(l) = p5*(bzmn_o(l) + bzmn_o(l+1)) lu_o(l) = lu_o(l) + lu_o(l+1) END DO guu(1:nrzt) = guu(1:nrzt) * sqrts(1:nrzt)**2 bsqr(1:nrzt) = gvv(1:nrzt) * sqrts(1:nrzt)**2 armn_o(:nrzt) = armn_o(:nrzt) - (zu(:nrzt,1)*lu_o(:nrzt) 1 + bsqr(:nrzt)*r1(:nrzt,1) + gvvs(:nrzt)*r1(:nrzt,0)) azmn_o(:nrzt) = azmn_o(:nrzt) + ru(:nrzt,1)*lu_o(:nrzt) brmn_o(:nrzt) = brmn_o(:nrzt) + z1(:nrzt,1)*lu_o(:nrzt) 1 -(guu(:nrzt)*ru(:nrzt,1) + guus(:nrzt)*ru(:nrzt,0)) bzmn_o(:nrzt) = bzmn_o(:nrzt) - (r1(:nrzt,1)*lu_o(:nrzt) 1 + guu(:nrzt)*zu(:nrzt,1) + guus(:nrzt)*zu(:nrzt,0)) IF (lthreed) THEN !DIR$ IVDEP DO l = 1, nrzt guv(l) = p5*(guv(l) + guv(l+1)) guvs(l) = p5*(guvs(l) + guvs(l+1)) END DO brmn_e(:nrzt) = brmn_e(:nrzt) 1 - (guv(:nrzt)*rv(:nrzt,0) + guvs(:nrzt)*rv(:nrzt,1)) bzmn_e(:nrzt) = bzmn_e(:nrzt) 1 - (guv(:nrzt)*zv(:nrzt,0) + guvs(:nrzt)*zv(:nrzt,1)) crmn_e(:nrzt) = guv(:nrzt) *ru(:nrzt,0) 1 + gvv(:nrzt) *rv(:nrzt,0) 2 + gvvs(:nrzt)*rv(:nrzt,1) + guvs(:nrzt)*ru(:nrzt,1) czmn_e(:nrzt) = guv(:nrzt) *zu(:nrzt,0) 1 + gvv(:nrzt) *zv(:nrzt,0) 2 + gvvs(:nrzt)*zv(:nrzt,1) + guvs(:nrzt)*zu(:nrzt,1) guv(:nrzt) = guv(:nrzt) *sqrts(:nrzt)*sqrts(:nrzt) brmn_o(:nrzt) = brmn_o(:nrzt) 1 - (guvs(:nrzt)*rv(:nrzt,0) + guv(:nrzt)*rv(:nrzt,1)) bzmn_o(:nrzt) = bzmn_o(:nrzt) 1 - (guvs(:nrzt)*zv(:nrzt,0) + guv(:nrzt)*zv(:nrzt,1)) crmn_o(:nrzt) = guvs(:nrzt)*ru(:nrzt,0) 1 + gvvs(:nrzt)*rv(:nrzt,0) 2 + bsqr(:nrzt)*rv(:nrzt,1) + guv(:nrzt) *ru(:nrzt,1) czmn_o(:nrzt) = guvs(:nrzt)*zu(:nrzt,0) 1 + gvvs(:nrzt)*zv(:nrzt,0) 2 + bsqr(:nrzt)*zv(:nrzt,1) + guv(:nrzt) *zu(:nrzt,1) ENDIF ! ! ASSIGN EDGE FORCES (JS = NS) FOR FREE BOUNDARY CALCULATION ! IF (ivac .ge. 1) THEN armn_e(ns:nrzt:ns) = armn_e(ns:nrzt:ns) 1 + zu0(ns:nrzt:ns)*rbsq(1:nznt) armn_o(ns:nrzt:ns) = armn_o(ns:nrzt:ns) 1 + zu0(ns:nrzt:ns)*rbsq(1:nznt) azmn_e(ns:nrzt:ns) = azmn_e(ns:nrzt:ns) 1 - ru0(ns:nrzt:ns)*rbsq(1:nznt) azmn_o(ns:nrzt:ns) = azmn_o(ns:nrzt:ns) 1 - ru0(ns:nrzt:ns)*rbsq(1:nznt) ! fz00_edge = SUM(wint(ns:nrzt:ns)*ru0(ns:nrzt:ns)*rbsq(1:nznt)) ENDIF 100 CONTINUE ! ! COMPUTE CONSTRAINT FORCE KERNELS ! rcon(:nrzt,0) = (rcon(:nrzt,0) - rcon0(:nrzt)) * gcon(:nrzt) zcon(:nrzt,0) = (zcon(:nrzt,0) - zcon0(:nrzt)) * gcon(:nrzt) brmn_e(:nrzt) = brmn_e(:nrzt) + rcon(:nrzt,0) bzmn_e(:nrzt) = bzmn_e(:nrzt) + zcon(:nrzt,0) brmn_o(:nrzt) = brmn_o(:nrzt)+ rcon(:nrzt,0)*sqrts(:nrzt) bzmn_o(:nrzt) = bzmn_o(:nrzt)+ zcon(:nrzt,0)*sqrts(:nrzt) rcon(:nrzt,0) = ru0(:nrzt) * gcon(:nrzt) zcon(:nrzt,0) = zu0(:nrzt) * gcon(:nrzt) rcon(:nrzt,1) = rcon(:nrzt,0) * sqrts(:nrzt) zcon(:nrzt,1) = zcon(:nrzt,0) * sqrts(:nrzt) END SUBROUTINE forces
{-# OPTIONS --no-termination-check #-} module RunTests where open import Prelude.Bool open import Prelude.Char open import Prelude.Nat open import Prelude.List open import Prelude.IO open import Prelude.String open import Prelude.Unit open import Prelude.Product postulate Stream : Set popen : String -> String -> IO Stream pclose : Stream -> IO Unit readChar : Stream -> IO Char strLen : String -> Nat charAt : (s : String) -> Nat -> Char _`_`_ : {A B C : Set}(x : A)(f : A -> B -> C)(y : B) -> C x ` f ` y = f x y infixr 9 _∘_ _∘_ : {A : Set}{B : A -> Set}{C : (x : A) -> B x -> Set} (f : {a : A}(b : B a)-> C a b) (g : (a : A) -> B a)(x : A) -> C x (g x) f ∘ g = λ x -> f (g x) infixr 1 _$_ _$_ : {A : Set}{B : A -> Set}(f : (x : A) -> B x)(x : A) -> B x f $ x = f x {-# COMPILED_EPIC popen (s : String, m : String, u : Unit) -> Ptr = foreign Ptr "popen" (mkString(s) : String, mkString(m) : String) #-} {-# COMPILED_EPIC pclose (s : Ptr, u : Unit) -> Unit = foreign Int "pclose" (s : Ptr) ; u #-} {-# COMPILED_EPIC readChar (s : Ptr, u : Unit) -> Int = foreign Int "fgetc" (s : Ptr) #-} {-# COMPILED_EPIC strLen (s : Any) -> BigInt = foreign BigInt "intToBig" (foreign Int "strlen" (mkString(s) : String) : Int) #-} {-# COMPILED_EPIC charAt (s : Any, n : BigInt) -> Int = foreign Int "charAtBig" (mkString(s) : String, n : BigInt) #-} readStream : Stream -> IO (List Char) readStream stream = c <- readChar stream , if' charEq eof c then pclose stream ,, return [] else ( cs <- readStream stream , return (c :: cs)) system : String -> IO (List Char) system s = putStrLn $ "system " +S+ s ,, x <- popen s "r" , y <- readStream x , return y span : {A : Set} -> (p : A -> Bool) -> List A -> List A × List A span p [] = [] , [] span p (a :: as) with p a ... | false = [] , a :: as ... | true with span p as ... | xs , ys = (a :: xs) , ys groupBy : {A : Set} -> (A -> A -> Bool) -> List A -> List (List A) groupBy _ [] = [] groupBy eq (x :: xs) with span (eq x) xs ... | ys , zs = (x :: ys) :: groupBy eq zs comparing : {A B : Set} -> (A -> B) -> (B -> B -> Bool) -> A -> A -> Bool comparing f _==_ x y = f x == f y FilePath : Set FilePath = String and : List Bool -> Bool and [] = true and (true :: xs) = and xs and (false :: _) = false sequence : {A : Set} -> List (IO A) -> IO (List A) sequence [] = return [] sequence (x :: xs) = r <- x , rs <- sequence xs , return (r :: rs) mapM : {A B : Set} -> (A -> IO B) -> List A -> IO (List B) mapM f xs = sequence (map f xs) printList : List Char -> IO Unit printList xs = mapM printChar xs ,, printChar '\n' printResult : FilePath -> List Char -> List Char -> IO Unit printResult filename l1 l2 with l1 ` listEq charEq ` l2 ... | true = putStrLn (filename +S+ ": Success!") ... | false = putStrLn (filename +S+ ": Fail!") ,, putStrLn "Expected:" ,, printList l2 ,, putStrLn "Got:" ,, printList l1 compile : FilePath -> FilePath -> IO Unit compile dir file = system $ "agda --epic --compile-dir=" +S+ dir +S+ "bin/ " +S+ dir +S+ file ,, return unit readFile : FilePath -> IO (List Char) readFile file = system $ "cat " +S+ file -- This won't work because of a bug in Epic... {- validFile : List Char -> Bool validFile f with span (not ∘ charEq '.') f ... | _ , ('.' :: 'a' :: 'g' :: 'd' :: 'a' :: []) = true ... | _ , ('.' :: 'o' :: 'u' :: 't' :: []) = true ... | _ = false -} stripFileEnding : FilePath -> FilePath stripFileEnding fp = fromList $ fst $ span (not ∘ charEq '.') (fromString fp) testFile : FilePath -> FilePath -> FilePath -> IO Bool testFile outdir agdafile outfile = compile outdir (agdafile) ,, out <- system $ outdir +S+ "bin/" +S+ stripFileEnding agdafile , expected <- readFile (outdir +S+ outfile) , printResult agdafile out expected ,, return (out ` listEq charEq ` expected) testFile' : FilePath -> List (List Char) -> IO Bool testFile' outdir (agdafile :: outfile :: _) = testFile outdir (fromList agdafile) (fromList outfile) testFile' _ _ = return true isNewline : Char -> Bool isNewline '\n' = true isNewline _ = false lines : List Char -> List (List Char) lines list with span (not ∘ isNewline) list ... | l , [] = l :: [] ... | l , _ :: s' = l :: lines s' getFiles : FilePath -> IO (List (List Char)) getFiles dir = out <- system $ "ls " +S+ dir , putStrLn "getFiles after ls" ,, -- mapM (printList ∘ snd) $ map (span (not ∘ charEq '.')) $ lines out ,, return $ lines out -- filter validFile $ lines out isDot : Char -> Bool isDot '.' = true isDot _ = false testFiles : FilePath -> IO Bool testFiles dir = files <- getFiles dir , putStrLn "Found the following files in the tests directory:" ,, mapM printList files ,, res <- mapM (testFile' dir) (groupBy (comparing (fst ∘ span (not ∘ isDot)) (listEq charEq)) files) , return $ and res getCurrentDirectory : IO FilePath getCurrentDirectory = fromList <$> system "pwd" main : IO Unit main = dir' <- getCurrentDirectory , putStrLn (fromList (fromString dir')) ,, putStrLn "hello" ,, putStrLn (fromList (tail ('h' :: 'e' :: 'j' :: []))) ,, printList (fromString "hej igen") ,, putStrLn (fromList (tail (fromString "hello"))) ,, dir <- fromList ∘ init ∘ fromString <$> getCurrentDirectory , putStrLn dir ,, system ("rm " +S+ dir +S+ "/tests/*.agdai") ,, res <- testFiles (dir +S+ "/tests/") , (if res then putStrLn "All tests succeeded! " else putStrLn "Not all tests succeeded ")
theory Memory_Allocation_Invariant imports Memory_Allocation_Model begin subsection \<open>def and proof of inv_different_ids\<close> definition id_set :: "Block \<Rightarrow> ID set" where "id_set b \<equiv> set (tree_map snd b)" lemma id_set_node: "id_set (Node b1 b2 b3 b4) = id_set b1 \<union> id_set b2 \<union> id_set b3 \<union> id_set b4" unfolding id_set_def by auto lemma id_set_notempty: "id_set B \<noteq> {}" apply(induct B) unfolding id_set_def apply auto[1] using id_set_node unfolding id_set_def by auto inductive diff_ids:: "Block \<Rightarrow> bool" where diff1: "diff_ids (Leaf a)" | diff2: "(id_set b1) \<inter> (id_set b2) = {} \<and> (id_set b1) \<inter> (id_set b3) = {} \<and> (id_set b1) \<inter> (id_set b4) = {} \<and> (id_set b2) \<inter> (id_set b3) = {} \<and> (id_set b2) \<inter> (id_set b4) = {} \<and> (id_set b3) \<inter> (id_set b4) = {} \<and> diff_ids b1 \<and> diff_ids b2 \<and> diff_ids b3 \<and> diff_ids b4 \<Longrightarrow> diff_ids (Node b1 b2 b3 b4)" inductive_cases diff_ids_leaf_node: "diff_ids (Leaf a)" "diff_ids (Node ll lr rl rr)" lemma diff_leaf1: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> (L l) \<in> set b1 \<Longrightarrow> (L l) \<notin> set b2 \<and> (L l) \<notin> set b3 \<and> (L l) \<notin> set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "(L l) \<in> set b1" have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have l_id: "snd (L l) \<in> id_set b1" unfolding id_set_def using a1 by (simp add: tree.set_map) have n1: "snd (L l) \<notin> id_set b2" using diff_ab l_id by auto have n2: "snd (L l) \<notin> id_set b3" using diff_ac l_id by auto have n3: "snd (L l) \<notin> id_set b4" using diff_ad l_id by auto show ?thesis using n1 n2 n3 using id_set_def tree.set_map by fastforce qed lemma diff_leaf2: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> (L l) \<in> set b2 \<Longrightarrow> (L l) \<notin> set b1 \<and> (L l) \<notin> set b3 \<and> (L l) \<notin> set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "(L l) \<in> set b2" have diff_ab: "(id_set b2) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have l_id: "snd (L l) \<in> id_set b2" unfolding id_set_def using a1 by (simp add: tree.set_map) have n1: "snd (L l) \<notin> id_set b1" using diff_ab l_id by auto have n2: "snd (L l) \<notin> id_set b3" using diff_bc l_id by auto have n3: "snd (L l) \<notin> id_set b4" using diff_bd l_id by auto show ?thesis using n1 n2 n3 using id_set_def tree.set_map by fastforce qed lemma diff_leaf3: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> (L l) \<in> set b3 \<Longrightarrow> (L l) \<notin> set b1 \<and> (L l) \<notin> set b2 \<and> (L l) \<notin> set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "(L l) \<in> set b3" have diff_ac: "(id_set b3) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b3) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have l_id: "snd (L l) \<in> id_set b3" unfolding id_set_def using a1 by (simp add: tree.set_map) have n1: "snd (L l) \<notin> id_set b1" using diff_ac l_id by auto have n2: "snd (L l) \<notin> id_set b2" using diff_bc l_id by auto have n3: "snd (L l) \<notin> id_set b4" using diff_cd l_id by auto show ?thesis using n1 n2 n3 using id_set_def tree.set_map by fastforce qed lemma diff_leaf4: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> (L l) \<in> set b4 \<Longrightarrow> (L l) \<notin> set b1 \<and> (L l) \<notin> set b2 \<and> (L l) \<notin> set b3" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "(L l) \<in> set b4" have diff_ad: "(id_set b4) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b4) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b4) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have l_id: "snd (L l) \<in> id_set b4" unfolding id_set_def using a1 by (simp add: tree.set_map) have n1: "snd (L l) \<notin> id_set b1" using diff_ad l_id by auto have n2: "snd (L l) \<notin> id_set b2" using diff_bd l_id by auto have n3: "snd (L l) \<notin> id_set b3" using diff_cd l_id by auto show ?thesis using n1 n2 n3 using id_set_def tree.set_map by fastforce qed lemma diff_node1: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> tree.set subbtr \<subseteq> tree.set b1 \<Longrightarrow> \<not> tree.set subbtr \<subseteq> tree.set b2 \<and> \<not> tree.set subbtr \<subseteq> tree.set b3 \<and> \<not> tree.set subbtr \<subseteq> tree.set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "tree.set subbtr \<subseteq> tree.set b1" have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have subbtr_id: "id_set subbtr \<subseteq> id_set b1" unfolding id_set_def using a1 by (metis subset_image_iff tree.set_map) have n1: "\<not> id_set subbtr \<subseteq> id_set b2" using diff_ab subbtr_id id_set_notempty by fastforce have n2: "\<not> id_set subbtr \<subseteq> id_set b3" using diff_ac subbtr_id id_set_notempty by fastforce have n3: "\<not> id_set subbtr \<subseteq> id_set b4" using diff_ad subbtr_id id_set_notempty by fastforce show ?thesis using n1 n2 n3 unfolding id_set_def by (metis subset_image_iff tree.set_map) qed lemma diff_node2: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> tree.set subbtr \<subseteq> tree.set b2 \<Longrightarrow> \<not> tree.set subbtr \<subseteq> tree.set b1 \<and> \<not> tree.set subbtr \<subseteq> tree.set b3 \<and> \<not> tree.set subbtr \<subseteq> tree.set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "tree.set subbtr \<subseteq> tree.set b2" have diff_ab: "(id_set b2) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have subbtr_id: "id_set subbtr \<subseteq> id_set b2" unfolding id_set_def using a1 by (metis subset_image_iff tree.set_map) have n1: "\<not> id_set subbtr \<subseteq> id_set b1" using diff_ab subbtr_id id_set_notempty by fastforce have n2: "\<not> id_set subbtr \<subseteq> id_set b3" using diff_bc subbtr_id id_set_notempty by fastforce have n3: "\<not> id_set subbtr \<subseteq> id_set b4" using diff_bd subbtr_id id_set_notempty by fastforce show ?thesis using n1 n2 n3 unfolding id_set_def by (metis subset_image_iff tree.set_map) qed lemma diff_node3: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> tree.set subbtr \<subseteq> tree.set b3 \<Longrightarrow> \<not> tree.set subbtr \<subseteq> tree.set b1 \<and> \<not> tree.set subbtr \<subseteq> tree.set b2 \<and> \<not> tree.set subbtr \<subseteq> tree.set b4" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "tree.set subbtr \<subseteq> tree.set b3" have diff_ac: "(id_set b3) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b3) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using a0 diff_ids_leaf_node(2) by blast have subbtr_id: "id_set subbtr \<subseteq> id_set b3" unfolding id_set_def using a1 by (metis subset_image_iff tree.set_map) have n1: "\<not> id_set subbtr \<subseteq> id_set b1" using diff_ac subbtr_id id_set_notempty by fastforce have n2: "\<not> id_set subbtr \<subseteq> id_set b2" using diff_bc subbtr_id id_set_notempty by fastforce have n3: "\<not> id_set subbtr \<subseteq> id_set b4" using diff_cd subbtr_id id_set_notempty by fastforce show ?thesis using n1 n2 n3 unfolding id_set_def by (metis subset_image_iff tree.set_map) qed lemma diff_node4: "diff_ids (Node b1 b2 b3 b4) \<Longrightarrow> tree.set subbtr \<subseteq> tree.set b4 \<Longrightarrow> \<not> tree.set subbtr \<subseteq> tree.set b1 \<and> \<not> tree.set subbtr \<subseteq> tree.set b2 \<and> \<not> tree.set subbtr \<subseteq> tree.set b3" proof- assume a0: "diff_ids (Node b1 b2 b3 b4)" and a1: "tree.set subbtr \<subseteq> tree.set b4" have diff_ad: "(id_set b4) \<inter> (id_set b1) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b4) \<inter> (id_set b2) = {}" using a0 diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b4) \<inter> (id_set b3) = {}" using a0 diff_ids_leaf_node(2) by blast have subbtr_id: "id_set subbtr \<subseteq> id_set b4" unfolding id_set_def using a1 by (metis subset_image_iff tree.set_map) have n1: "\<not> id_set subbtr \<subseteq> id_set b1" using diff_ad subbtr_id id_set_notempty by fastforce have n2: "\<not> id_set subbtr \<subseteq> id_set b2" using diff_bd subbtr_id id_set_notempty by fastforce have n3: "\<not> id_set subbtr \<subseteq> id_set b3" using diff_cd subbtr_id id_set_notempty by fastforce show ?thesis using n1 n2 n3 unfolding id_set_def by (metis subset_image_iff tree.set_map) qed definition "diff_ids_valid bset \<equiv> (\<forall>b \<in> bset. diff_ids b) \<and> (\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" lemma same_ids_replace: "diff_ids B \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b t \<Longrightarrow> id_set B = id_set (replace B b b')" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(2) by auto have leaf_b': "b' = Leaf (t, snd x)" using Leaf.prems(3) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (t, snd x)" using leaf_b leaf_b' unfolding replace_def by auto then show ?case unfolding id_set_def by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have same_b1': "id_set b1 = id_set (replace b1 b b')" using Node.hyps(1) diff_b1 a0 Node.prems(3) by auto have ?case using replace_re id_set_node same_b1' by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have same_b2': "id_set b2 = id_set (replace b2 b b')" using Node.hyps(2) diff_b2 a1 Node.prems(3) by auto have ?case using replace_re id_set_node same_b2' by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have same_b3': "id_set b3 = id_set (replace b3 b b')" using Node.hyps(3) diff_b3 a2 Node.prems(3) by auto have ?case using replace_re id_set_node same_b3' by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) by auto have same_b4': "id_set b4 = id_set (replace b4 b b')" using Node.hyps(4) diff_b4 a3 Node.prems(3) by auto have ?case using replace_re id_set_node same_b4' by auto } ultimately have ?case using Node.prems(2) by fastforce then show ?case by auto qed lemma diff_ids_replace: "diff_ids B \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b t \<Longrightarrow> diff_ids (replace B b b')" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(2) by fastforce have leaf_b': "b' = Leaf (t, snd x)" using Leaf.prems(3) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (t, snd x)" using leaf_b leaf_b' unfolding replace_def by auto then show ?case using diff1 by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have diff_b1': "diff_ids (replace b1 b b')" using Node.hyps(1) diff_b1 a0 Node.prems(3) by auto have diff_ab': "id_set (replace b1 b b') \<inter> id_set b2 = {}" using same_ids_replace diff_b1 a0 Node.prems(3) diff_ab by auto have diff_ac': "id_set (replace b1 b b') \<inter> id_set b3 = {}" using same_ids_replace diff_b1 a0 Node.prems(3) diff_ac by auto have diff_ad': "id_set (replace b1 b b') \<inter> id_set b4 = {}" using same_ids_replace diff_b1 a0 Node.prems(3) diff_ad by auto have ?case using replace_re diff_b1' diff_b2 diff_b3 diff_b4 diff_ab' diff_ac' diff_ad' diff_bc diff_bd diff_cd diff2 by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have diff_b2': "diff_ids (replace b2 b b')" using Node.hyps(2) diff_b2 a1 Node.prems(3) by auto have diff_ab': "id_set (replace b2 b b') \<inter> id_set b1 = {}" using same_ids_replace diff_b2 a1 Node.prems(3) diff_ab by auto have diff_bc': "id_set (replace b2 b b') \<inter> id_set b3 = {}" using same_ids_replace diff_b2 a1 Node.prems(3) diff_bc by auto have diff_bd': "id_set (replace b2 b b') \<inter> id_set b4 = {}" using same_ids_replace diff_b2 a1 Node.prems(3) diff_bd by auto have ?case using replace_re diff_b1 diff_b2' diff_b3 diff_b4 diff_ab' diff_ac diff_ad diff_bc' diff_bd' diff_cd diff2 by (simp add: inf_commute) } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b4 Node.prems(3) by auto have diff_b3': "diff_ids (replace b3 b b')" using Node.hyps(3) diff_b3 a2 Node.prems(3) by auto have diff_ac': "id_set (replace b3 b b') \<inter> id_set b1 = {}" using same_ids_replace diff_b3 a2 Node.prems(3) diff_ac by auto have diff_bc': "id_set (replace b3 b b') \<inter> id_set b2 = {}" using same_ids_replace diff_b3 a2 Node.prems(3) diff_bc by auto have diff_cd': "id_set (replace b3 b b') \<inter> id_set b4 = {}" using same_ids_replace diff_b3 a2 Node.prems(3) diff_cd by auto have ?case using replace_re diff_b1 diff_b2 diff_b3' diff_b4 diff_ab diff_ac' diff_ad diff_bc' diff_bd diff_cd' diff2 by (simp add: inf_commute) } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(3) apply auto[1] using no_replace no_belong_b2 Node.prems(3) apply auto[1] using no_replace no_belong_b3 Node.prems(3) by auto have diff_b4': "diff_ids (replace b4 b b')" using Node.hyps(4) diff_b4 a3 Node.prems(3) by auto have diff_ad': "id_set (replace b4 b b') \<inter> id_set b1 = {}" using same_ids_replace diff_b4 a3 Node.prems(3) diff_ad by auto have diff_bd': "id_set (replace b4 b b') \<inter> id_set b2 = {}" using same_ids_replace diff_b4 a3 Node.prems(3) diff_bd by auto have diff_cd': "id_set (replace b4 b b') \<inter> id_set b3 = {}" using same_ids_replace diff_b4 a3 Node.prems(3) diff_cd by auto have ?case using replace_re diff_b1 diff_b2 diff_b3 diff_b4' diff_ab diff_ac diff_ad' diff_bc diff_bd' diff_cd' diff2 by (simp add: inf_commute) } ultimately have ?case using Node.prems(2) by fastforce then show ?case by auto qed lemma diff_ids_alloc_fail: "diff_ids_valid bset \<Longrightarrow> \<not> (exists_freelevel bset lv) \<Longrightarrow> diff_ids_valid (fst (alloc bset lv ids))" unfolding alloc_def Let_def by auto lemma the_P: "\<exists>!x. P x \<Longrightarrow> y = (THE x. P x) \<Longrightarrow> P y" by (auto intro: theI) lemma diff_ids_alloc_branch1: "diff_ids_valid bset \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax = lv \<Longrightarrow> (newbset, newids, re, reid) = alloc1 bset lv ids \<Longrightarrow> diff_ids_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "exists_freelevel bset lv" and a2: "lmax = freesets_maxlevel bset lv" and a3: "lmax = lv" and a4: "(newbset, newids, re, reid) = alloc1 bset lv ids" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a1 by auto have eq_lv: "lv = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a2 a3 unfolding freesets_maxlevel_def by auto have the_lv: "lv \<le> lv \<and> freesets_level_pool bset lv \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lv)" using the_P[OF exi_lmax eq_lv] by auto have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" using the_lv unfolding freesets_level_pool_def by auto let ?blo = "SOME b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" have diff_blo: "diff_ids ?blo" using diff_bset1 exi_b by (metis (mono_tags, lifting) some_eq_ex) have exi_l: "\<exists>l. l \<in> freesets_level ?blo lv" using someI_ex[OF exi_b] by auto let ?l = "SOME l. l \<in> freesets_level ?blo lv" have leaf_belong: "L ?l \<in> set ?blo" using exi_l unfolding freesets_level_def freesets_def by (metis (no_types, lifting) CollectD someI_ex) have exi_newb: "\<exists>newb. newb = replace ?blo ?l (set_state_type ?l ALLOC)" by simp let ?newb = "SOME newb. newb = replace ?blo ?l (set_state_type ?l ALLOC)" have diff_newblo: "diff_ids ?newb" using diff_ids_replace diff_blo leaf_belong by simp have alloc1_re: "(newbset, newids, re, reid) = (((bset - {?blo}) \<union> {?newb}), ids, True, {snd (L ?l)})" using a4 unfolding alloc1_def by (metis some_eq_trivial) have diff_newbset1: "\<forall>b \<in> newbset. diff_ids b" using alloc1_re diff_bset1 diff_blo diff_newblo by blast have same_ids_newblo: "id_set ?blo = id_set ?newb" using same_ids_replace diff_blo leaf_belong by simp have step1: "(\<forall>b1 b2. b1 \<in> (bset - {?blo}) \<and> b2 \<in> (bset - {?blo}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using diff_bset2 by auto have step2: "\<forall>b \<in> (bset - {?blo}). id_set b \<inter> id_set ?blo = {}" using diff_bset2 by (metis (mono_tags, lifting) DiffE exi_b insertCI some_eq_ex) have newstep1: "(\<forall>b1 b2. b1 \<in> (newbset - {?newb}) \<and> b2 \<in> (newbset - {?newb}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using step1 alloc1_re by auto have newstep2: "\<forall>b \<in> (newbset - {?newb}). id_set b \<inter> id_set ?newb = {}" using step2 alloc1_re same_ids_newblo by auto have diff_newbset2: "(\<forall>b1 b2. b1 \<in> newbset \<and> b2 \<in> newbset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using newstep1 newstep2 by auto show ?thesis using diff_newbset1 diff_newbset2 diff_ids_valid_def by auto qed lemma ids_overlap_empty: "id_set oth \<subseteq> ids \<Longrightarrow> snd (L x) \<in> ids \<Longrightarrow> id_set oth \<inter> {snd (L x)} = {} \<Longrightarrow> lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> id_set oth \<inter> id_set (fst (split x ids (lv - lmax))) = {}" proof(induct "lv - lmax" arbitrary: oth x ids lmax) case 0 then show ?case by linarith next case (Suc xa) obtain ll lr rl rr where pdivide: "fst (divide x ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" unfolding divide_def Let_def by auto have notbelong_ll: "snd ll \<notin> ids" using divide_notbelong Suc(7) pdivide by auto have ll_empty_oth: "id_set oth \<inter> {snd ll} = {}" using Suc(3) notbelong_ll by auto have notbelong_lr: "snd lr \<notin> ids" using divide_notbelong Suc(7) pdivide by auto have notbelong_rl: "snd rl \<notin> ids" using divide_notbelong Suc(7) pdivide by auto have notbelong_rr: "snd rr \<notin> ids" using divide_notbelong Suc(7) pdivide by auto have notbelong: "id_set oth \<inter> {snd ll, snd lr, snd rl, snd rr} = {}" using Suc(3) notbelong_ll notbelong_lr notbelong_rl notbelong_rr by auto let ?newids = "snd (divide x ids)" have step': "fst (split x ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)" using split_induct Suc(6) pdivide by (meson zero_less_diff) have belong_ll: "snd ll \<in> ?newids" using divide_belong pdivide by auto {assume xa_eq_1: "Suc xa = 1" have lv_suc_lmax: "lv = Suc lmax" using Suc(2) xa_eq_1 by linarith have split_ll: "fst (split (Leaf ll) ?newids (lv - lmax - 1)) = Leaf ll" using lv_suc_lmax by auto have step1: "fst (split x ids (lv - lmax)) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" using step' split_ll by auto have co: "id_set (Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)) = {snd ll, snd lr, snd rl, snd rr}" unfolding id_set_def by auto have ?case using step1 co notbelong by auto } moreover {assume xa_gr_1: "Suc xa > 1" have xa_lv_suc_lmax: "xa = lv - Suc lmax" using Suc(2) by linarith have suc_lmax_less_lv: "Suc lmax < lv" using Suc(3) xa_gr_1 xa_lv_suc_lmax by linarith have co1: "id_set (Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)) = id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<union> id_set (Leaf lr) \<union> id_set (Leaf rl) \<union> id_set (Leaf rr)" using id_set_node by auto have co2: "id_set (Leaf lr) \<union> id_set (Leaf rl) \<union> id_set (Leaf rr) = {snd lr, snd rl, snd rr}" unfolding id_set_def by auto have co: "id_set (Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)) = id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<union> {snd lr, snd rl, snd rr}" using co1 co2 by auto have ids_belong: "ids \<subseteq> snd (divide x ids)" unfolding divide_def Let_def using getnewid_inc by auto have oth_belong: "id_set oth \<subseteq> snd (divide x ids)" using Suc(3) ids_belong by auto have split_ll_empty_oth: "id_set oth \<inter> id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) = {}" using Suc(1) xa_lv_suc_lmax oth_belong belong_ll ll_empty_oth suc_lmax_less_lv divide_finite Suc(7) by auto have notbelong: "id_set oth \<inter> id_set (Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)) = {}" using split_ll_empty_oth notbelong co by auto have ?case using step' notbelong by auto } ultimately have ?case by linarith then show ?case by auto qed lemma diff_ids_split: "lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> snd (L b) \<in> ids \<Longrightarrow> diff_ids (fst (split b ids (lv - lmax)))" proof(induct "lv - lmax" arbitrary: lmax b ids) case 0 then show ?case by auto next case (Suc xa) obtain ll lr rl rr where pdivide: "fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" unfolding divide_def Let_def by auto have diff_ab: "id_set (Leaf ll) \<inter> id_set (Leaf lr) = {}" unfolding id_set_def using divide_diff Suc(4) pdivide by auto have diff_ab': "{snd ll} \<inter> id_set (Leaf lr) = {}" using diff_ab unfolding id_set_def by auto have diff_ac: "id_set (Leaf ll) \<inter> id_set (Leaf rl) = {}" unfolding id_set_def using divide_diff Suc(4) pdivide by auto have diff_ac': "{snd ll} \<inter> id_set (Leaf rl) = {}" using diff_ac unfolding id_set_def by auto have diff_ad: "id_set (Leaf ll) \<inter> id_set (Leaf rr) = {}" unfolding id_set_def using divide_diff Suc(4) pdivide by auto have diff_ad': "{snd ll} \<inter> id_set (Leaf rr) = {}" using diff_ad unfolding id_set_def by auto have diff_bc: "id_set (Leaf lr) \<inter> id_set (Leaf rl) = {}" unfolding id_set_def using divide_diff2 Suc(4) pdivide by auto have diff_bd: "id_set (Leaf lr) \<inter> id_set (Leaf rr) = {}" unfolding id_set_def using divide_diff2 Suc(4) pdivide by auto have diff_cd: "id_set (Leaf rl) \<inter> id_set (Leaf rr) = {}" unfolding id_set_def using divide_diff2 Suc(4) pdivide by auto let ?newids = "snd (divide b ids)" have belong_ll: "snd ll \<in> ?newids" using divide_belong pdivide by auto have belong_lr: "id_set (Leaf lr) \<subseteq> ?newids" unfolding id_set_def using divide_belong pdivide by auto have belong_rl: "id_set (Leaf rl) \<subseteq> ?newids" unfolding id_set_def using divide_belong pdivide by auto have belong_rr: "id_set (Leaf rr) \<subseteq> ?newids" unfolding id_set_def using divide_belong pdivide by auto have step': "fst (split b ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)" using split_induct Suc(3) pdivide by (meson zero_less_diff) {assume xa_eq_1: "Suc xa = 1" have lv_suc_lmax: "lv = Suc lmax" using Suc(2) xa_eq_1 by linarith have split_ll: "fst (split (Leaf ll) ?newids (lv - lmax - 1)) = Leaf ll" using lv_suc_lmax by auto have step1: "fst (split b ids (lv - lmax)) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" using step' split_ll by auto have diff_node: "diff_ids (Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr))" using diff2 diff1 using diff_ab diff_ac diff_ad diff_bc diff_bd diff_cd by auto have ?case using step1 diff_node by auto } moreover {assume xa_gr_1: "Suc xa > 1" have xa_lv_suc_lmax: "xa = lv - Suc lmax" using Suc(2) by linarith have suc_lmax_less_lv: "Suc lmax < lv" using Suc(3) xa_gr_1 xa_lv_suc_lmax by linarith have split2: "diff_ids (fst (split (Leaf ll) ?newids (lv - Suc lmax)))" using Suc(1) xa_lv_suc_lmax suc_lmax_less_lv divide_finite Suc(4) belong_ll pdivide by auto have diff_ll_lr: "id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<inter> id_set (Leaf lr) = {}" using ids_overlap_empty belong_lr belong_ll diff_ab' suc_lmax_less_lv divide_finite Suc(4) by (metis inf_commute tree.sel(1)) have diff_ll_rl: "id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<inter> id_set (Leaf rl) = {}" using ids_overlap_empty belong_rl belong_ll diff_ac' suc_lmax_less_lv divide_finite Suc(4) by (metis inf_commute tree.sel(1)) have diff_ll_rr: "id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<inter> id_set (Leaf rr) = {}" using ids_overlap_empty belong_rr belong_ll diff_ad' suc_lmax_less_lv divide_finite Suc(4) by (metis inf_commute tree.sel(1)) have diff_node: "diff_ids (Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr))" using diff2 diff1 using split2 diff_ll_lr diff_ll_rl diff_ll_rr diff_bc diff_bd diff_cd by auto have ?case using step' diff_node by auto } ultimately have ?case by linarith then show ?case by auto qed lemma ids_split: "lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> snd (L b) \<in> ids \<Longrightarrow> id_set (fst (split b ids (lv - lmax))) \<inter> ids = {}" proof(induct "lv - lmax" arbitrary: lmax b ids) case 0 then show ?case by auto next case (Suc xa) obtain ll lr rl rr where pdivide: "fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" unfolding divide_def Let_def by auto have notbelong_ll: "snd ll \<notin> ids" using divide_notbelong Suc(4) pdivide by auto have notbelong_lr: "snd lr \<notin> ids" using divide_notbelong Suc(4) pdivide by auto have notbelong_rl: "snd rl \<notin> ids" using divide_notbelong Suc(4) pdivide by auto have notbelong_rr: "snd rr \<notin> ids" using divide_notbelong Suc(4) pdivide by auto let ?newids = "snd (divide b ids)" have belong_ll: "snd ll \<in> ?newids" using divide_belong pdivide by auto have belong_ids: "ids \<subseteq> ?newids" unfolding divide_def Let_def using getnewid_inc by auto have step': "fst (split b ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)" using split_induct Suc(3) pdivide by (meson zero_less_diff) {assume xa_eq_1: "Suc xa = 1" have lv_suc_lmax: "lv = Suc lmax" using Suc(2) xa_eq_1 by linarith have split_ll: "fst (split (Leaf ll) ?newids (lv - lmax - 1)) = Leaf ll" using lv_suc_lmax by auto have step1: "fst (split b ids (lv - lmax)) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" using step' split_ll by auto have ids_step1: "id_set (Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)) \<inter> ids = {}" using notbelong_ll notbelong_lr notbelong_rl notbelong_rr unfolding id_set_def by auto have ?case using step1 ids_step1 by auto } moreover {assume xa_gr_1: "Suc xa > 1" have xa_lv_suc_lmax: "xa = lv - Suc lmax" using Suc(2) by linarith have suc_lmax_less_lv: "Suc lmax < lv" using Suc(3) xa_gr_1 xa_lv_suc_lmax by linarith have co1: "id_set (Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)) = id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<union> id_set (Leaf lr) \<union> id_set (Leaf rl) \<union> id_set (Leaf rr)" using id_set_node by auto have co2: "id_set (Leaf lr) \<union> id_set (Leaf rl) \<union> id_set (Leaf rr) = {snd lr, snd rl, snd rr}" unfolding id_set_def by auto have co: "id_set (Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)) = id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<union> {snd lr, snd rl, snd rr}" using co1 co2 by auto have split2': "id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<inter> ?newids = {}" using Suc(1) xa_lv_suc_lmax suc_lmax_less_lv divide_finite Suc(4) belong_ll pdivide by auto have split2: "id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<inter> ids = {}" using split2' belong_ids by auto have ids_step2: "(id_set (fst (split (Leaf ll) ?newids (lv - Suc lmax))) \<union> {snd lr, snd rl, snd rr}) \<inter> ids = {}" using split2 notbelong_lr notbelong_rl notbelong_rr by auto have ?case using step' co ids_step2 by auto } ultimately have ?case by linarith then show ?case by auto qed lemma ids_replace_leaf: "diff_ids blo \<Longrightarrow> id_set blo \<subseteq> ids \<Longrightarrow> L b \<in> tree.set blo \<Longrightarrow> id_set subbtr \<inter> ids = {} \<Longrightarrow> id_set (replace_leaf blo b subbtr) = id_set blo - {snd (L b)} \<union> id_set subbtr" proof(induct blo) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(3) by fastforce have replace_leaf_step: "replace_leaf (Leaf x) b subbtr = subbtr" using leaf_b replace_leaf.simps(1) by auto show ?case using replace_leaf_step leaf_b unfolding id_set_def by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a0 diff_ab id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a0 diff_ac id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a0 diff_ad id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node (replace_leaf b1 b subbtr) b2 b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b2 no_belong_b3 no_belong_b4 by auto have step: "id_set (replace_leaf b1 b subbtr) = id_set b1 - {snd (L b)} \<union> id_set subbtr" using Node.hyps(1) diff_b1 Node.prems(2) a0 Node.prems(4) unfolding id_set_def by auto have step_node': "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set b1 - {snd (L b)} \<union> id_set subbtr \<union> id_set b2 \<union> id_set b3 \<union> id_set b4" using replace_leaf_step id_set_node step by auto have step_node'': "id_set b1 - {snd (L b)} \<union> id_set subbtr \<union> id_set b2 \<union> id_set b3 \<union> id_set b4 = id_set b1 \<union> id_set b2 \<union> id_set b3 \<union> id_set b4 - {snd (L b)} \<union> id_set subbtr" using b_empty_b2 b_empty_b3 b_empty_b4 by auto have step_node: "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set (Node b1 b2 b3 b4) - {snd (L b)} \<union> id_set subbtr" using step_node' step_node'' id_set_node by auto have ?case using replace_leaf_step step_node by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a1 diff_ab id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a1 diff_bc id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a1 diff_bd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 (replace_leaf b2 b subbtr) b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b3 no_belong_b4 by auto have step: "id_set (replace_leaf b2 b subbtr) = id_set b2 - {snd (L b)} \<union> id_set subbtr" using Node.hyps(2) diff_b2 Node.prems(2) a1 Node.prems(4) unfolding id_set_def by auto have step_node': "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set b1 \<union> id_set b2 - {snd (L b)} \<union> id_set subbtr \<union> id_set b3 \<union> id_set b4" using replace_leaf_step id_set_node step using b_empty_b1 by auto have step_node'': "id_set b1 \<union> id_set b2 - {snd (L b)} \<union> id_set subbtr \<union> id_set b3 \<union> id_set b4 = id_set b1 \<union> id_set b2 \<union> id_set b3 \<union> id_set b4 - {snd (L b)} \<union> id_set subbtr" using b_empty_b3 b_empty_b4 by auto have step_node: "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set (Node b1 b2 b3 b4) - {snd (L b)} \<union> id_set subbtr" using step_node' step_node'' id_set_node by auto have ?case using replace_leaf_step step_node by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a2 diff_ac id_set_def tree.set_map by fastforce have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a2 diff_bc id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a2 diff_cd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 b2 (replace_leaf b3 b subbtr) b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b4 by auto have step: "id_set (replace_leaf b3 b subbtr) = id_set b3 - {snd (L b)} \<union> id_set subbtr" using Node.hyps(3) diff_b3 Node.prems(2) a2 Node.prems(4) unfolding id_set_def by auto have step_node': "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set b1 \<union> id_set b2 \<union> id_set b3 - {snd (L b)} \<union> id_set subbtr \<union> id_set b4" using replace_leaf_step id_set_node step using b_empty_b1 b_empty_b2 by auto have step_node'': "id_set b1 \<union> id_set b2 \<union> id_set b3 - {snd (L b)} \<union> id_set subbtr \<union> id_set b4 = id_set b1 \<union> id_set b2 \<union> id_set b3 \<union> id_set b4 - {snd (L b)} \<union> id_set subbtr" using b_empty_b4 by auto have step_node: "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set (Node b1 b2 b3 b4) - {snd (L b)} \<union> id_set subbtr" using step_node' step_node'' id_set_node by auto have ?case using replace_leaf_step step_node by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a3 diff_ad id_set_def tree.set_map by fastforce have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a3 diff_bd id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a3 diff_cd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 b2 b3 (replace_leaf b4 b subbtr)" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b3 by auto have step: "id_set (replace_leaf b4 b subbtr) = id_set b4 - {snd (L b)} \<union> id_set subbtr" using Node.hyps(4) diff_b4 Node.prems(2) a3 Node.prems(4) unfolding id_set_def by auto have step_node': "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set b1 \<union> id_set b2 \<union> id_set b3 \<union> id_set b4 - {snd (L b)} \<union> id_set subbtr" using replace_leaf_step id_set_node step using b_empty_b1 b_empty_b2 b_empty_b3 by auto have step_node: "id_set (replace_leaf (Node b1 b2 b3 b4) b subbtr) = id_set (Node b1 b2 b3 b4) - {snd (L b)} \<union> id_set subbtr" using step_node' id_set_node by auto have ?case using replace_leaf_step step_node by auto } ultimately have ?case using Node.prems(3) by auto then show ?case by auto qed lemma diff_ids_replace_leaf: "diff_ids blo \<Longrightarrow> lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> id_set blo \<subseteq> ids \<Longrightarrow> L b \<in> tree.set blo \<Longrightarrow> diff_ids (replace_leaf blo b (fst (split b ids (lv - lmax))))" proof(induct blo) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(5) by fastforce have b_belong: "snd (L b) \<in> ids" using Leaf.prems(4) leaf_b unfolding id_set_def by auto have diff_b_split: "diff_ids (fst (split b ids (lv - lmax)))" using diff_ids_split Leaf.prems(2,3) b_belong by auto have replace_leaf_step: "replace_leaf (Leaf x) b (fst (split b ids (lv - lmax))) = fst (split b ids (lv - lmax))" using leaf_b replace_leaf.simps(1) by auto show ?case using replace_leaf_step diff_b_split by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have b_belong: "snd (L b) \<in> ids" using Node.prems(4,5) unfolding id_set_def by (metis contra_subsetD image_eqI tree.set_map) have ids_subbtr: "id_set (fst (split b ids (lv - lmax))) \<inter> ids = {}" using ids_split Node.prems(2,3) b_belong by auto {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node (replace_leaf b1 b (fst (split b ids (lv - lmax)))) b2 b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b2 no_belong_b3 no_belong_b4 by auto have diff_b1': "diff_ids (replace_leaf b1 b (fst (split b ids (lv - lmax))))" using Node.hyps(1) diff_b1 Node.prems(2,3,4) a0 unfolding id_set_def by fastforce have ids_replace_leaf: "id_set (replace_leaf b1 b (fst (split b ids (lv - lmax)))) = id_set b1 - {snd (L b)} \<union> id_set (fst (split b ids (lv - lmax)))" using ids_replace_leaf diff_b1 Node.prems(4) a0 ids_subbtr unfolding id_set_def by fastforce have diff_ab': "id_set (replace_leaf b1 b (fst (split b ids (lv - lmax)))) \<inter> id_set b2 = {}" using Node.prems(4) diff_ab ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_ac': "id_set (replace_leaf b1 b (fst (split b ids (lv - lmax)))) \<inter> id_set b3 = {}" using Node.prems(4) diff_ac ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_ad': "id_set (replace_leaf b1 b (fst (split b ids (lv - lmax)))) \<inter> id_set b4 = {}" using Node.prems(4) diff_ad ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_replace_leaf_step: "diff_ids (Node (replace_leaf b1 b (fst (split b ids (lv - lmax)))) b2 b3 b4)" using diff1 diff2 diff_b1' diff_b2 diff_b3 diff_b4 using diff_ab' diff_ac' diff_ad' diff_bc diff_bd diff_cd by auto have ?case using replace_leaf_step diff_replace_leaf_step by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 (replace_leaf b2 b (fst (split b ids (lv - lmax)))) b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b3 no_belong_b4 by auto have diff_b2': "diff_ids (replace_leaf b2 b (fst (split b ids (lv - lmax))))" using Node.hyps(2) diff_b2 Node.prems(2,3,4) a1 unfolding id_set_def by fastforce have ids_replace_leaf: "id_set (replace_leaf b2 b (fst (split b ids (lv - lmax)))) = id_set b2 - {snd (L b)} \<union> id_set (fst (split b ids (lv - lmax)))" using ids_replace_leaf diff_b2 Node.prems(4) a1 ids_subbtr unfolding id_set_def by fastforce have diff_ab': "id_set (replace_leaf b2 b (fst (split b ids (lv - lmax)))) \<inter> id_set b1 = {}" using Node.prems(4) diff_ab ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_bc': "id_set (replace_leaf b2 b (fst (split b ids (lv - lmax)))) \<inter> id_set b3 = {}" using Node.prems(4) diff_bc ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_bd': "id_set (replace_leaf b2 b (fst (split b ids (lv - lmax)))) \<inter> id_set b4 = {}" using Node.prems(4) diff_bd ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_replace_leaf_step: "diff_ids (Node b1 (replace_leaf b2 b (fst (split b ids (lv - lmax)))) b3 b4)" using diff1 diff2 diff_b1 diff_b2' diff_b3 diff_b4 using diff_ab' diff_ac diff_ad diff_bc' diff_bd' diff_cd by (simp add: inf_sup_aci(1)) have ?case using replace_leaf_step diff_replace_leaf_step by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 b2 (replace_leaf b3 b (fst (split b ids (lv - lmax)))) b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b4 by auto have diff_b3': "diff_ids (replace_leaf b3 b (fst (split b ids (lv - lmax))))" using Node.hyps(3) diff_b3 Node.prems(2,3,4) a2 unfolding id_set_def by fastforce have ids_replace_leaf: "id_set (replace_leaf b3 b (fst (split b ids (lv - lmax)))) = id_set b3 - {snd (L b)} \<union> id_set (fst (split b ids (lv - lmax)))" using ids_replace_leaf diff_b3 Node.prems(4) a2 ids_subbtr unfolding id_set_def by fastforce have diff_ac': "id_set (replace_leaf b3 b (fst (split b ids (lv - lmax)))) \<inter> id_set b1 = {}" using Node.prems(4) diff_ac ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_bc': "id_set (replace_leaf b3 b (fst (split b ids (lv - lmax)))) \<inter> id_set b2 = {}" using Node.prems(4) diff_bc ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_cd': "id_set (replace_leaf b3 b (fst (split b ids (lv - lmax)))) \<inter> id_set b4 = {}" using Node.prems(4) diff_cd ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_replace_leaf_step: "diff_ids (Node b1 b2 (replace_leaf b3 b (fst (split b ids (lv - lmax)))) b4)" using diff1 diff2 diff_b1 diff_b2 diff_b3' diff_b4 using diff_ab diff_ac' diff_ad diff_bc' diff_bd diff_cd' by (simp add: inf_sup_aci(1)) have ?case using replace_leaf_step diff_replace_leaf_step by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 b2 b3 (replace_leaf b4 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b3 by auto have diff_b4': "diff_ids (replace_leaf b4 b (fst (split b ids (lv - lmax))))" using Node.hyps(4) diff_b4 Node.prems(2,3,4) a3 unfolding id_set_def by fastforce have ids_replace_leaf: "id_set (replace_leaf b4 b (fst (split b ids (lv - lmax)))) = id_set b4 - {snd (L b)} \<union> id_set (fst (split b ids (lv - lmax)))" using ids_replace_leaf diff_b4 Node.prems(4) a3 ids_subbtr unfolding id_set_def by fastforce have diff_ad': "id_set (replace_leaf b4 b (fst (split b ids (lv - lmax)))) \<inter> id_set b1 = {}" using Node.prems(4) diff_ad ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_bd': "id_set (replace_leaf b4 b (fst (split b ids (lv - lmax)))) \<inter> id_set b2 = {}" using Node.prems(4) diff_bd ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_cd': "id_set (replace_leaf b4 b (fst (split b ids (lv - lmax)))) \<inter> id_set b3 = {}" using Node.prems(4) diff_cd ids_subbtr ids_replace_leaf unfolding id_set_def using insert_disjoint(2) by auto have diff_replace_leaf_step: "diff_ids (Node b1 b2 b3 (replace_leaf b4 b (fst (split b ids (lv - lmax)))))" using diff1 diff2 diff_b1 diff_b2 diff_b3 diff_b4' using diff_ab diff_ac diff_ad' diff_bc diff_bd' diff_cd' by (simp add: inf_sup_aci(1)) have ?case using replace_leaf_step diff_replace_leaf_step by auto } ultimately have ?case using Node.prems(5) by fastforce then show ?case by auto qed lemma diff_ids_alloc_branch2: "diff_ids_valid bset \<Longrightarrow> finite ids \<Longrightarrow> \<forall>b\<in>bset. id_set b \<subseteq> ids \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax \<noteq> lv \<Longrightarrow> blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}) \<Longrightarrow> b = (SOME l. l \<in> freesets_level blo lmax) \<Longrightarrow> (subbtr, ids') = split b ids (lv - lmax) \<Longrightarrow> newbtr = replace_leaf blo b subbtr \<Longrightarrow> newbset = bset - {blo} \<union> {newbtr} \<Longrightarrow> diff_ids_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "finite ids" and a2: "\<forall>b\<in>bset. id_set b \<subseteq> ids" and a3: "exists_freelevel bset lv" and a4: "lmax = freesets_maxlevel bset lv" and a5: "lmax \<noteq> lv" and a6: "blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {})" and a7: "b = (SOME l. l \<in> freesets_level blo lmax)" and a8: "(subbtr, ids') = split b ids (lv - lmax)" and a9: "newbtr = replace_leaf blo b subbtr" and a10: "newbset = bset - {blo} \<union> {newbtr}" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a3 by auto have eq_lmax: "lmax = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a4 unfolding freesets_maxlevel_def by auto have the_lmax: "lmax < lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using the_P[OF exi_lmax eq_lmax] a5 by auto have lmax_le_lv: "lmax < lv" using the_lmax by auto (*------------------------------------------------------------------------------------------------*) have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}" using the_lmax unfolding freesets_level_pool_def by auto have exi_blo: "blo \<in> bset \<and> freesets_level blo lmax \<noteq> {}" using someI_ex[OF exi_b] a6 by auto have diff_blo: "diff_ids blo" using diff_bset1 exi_blo by auto have ids_blo: "id_set blo \<subseteq> ids" using a2 exi_blo by auto have exi_l: "\<exists>l. l \<in> freesets_level blo lmax" using exi_blo by auto have exi_b: "b \<in> freesets_level blo lmax" using someI_ex[OF exi_l] a7 by auto have b_belong_blo: "L b \<in> tree.set blo" using exi_b unfolding freesets_level_def freesets_def by auto have ids_b: "snd (L b) \<in> ids" using exi_b unfolding freesets_level_def freesets_def using ids_blo unfolding id_set_def using tree.set_map by fastforce (*------------------------------------------------------------------------------------------------*) have ids_subbtr: "id_set subbtr \<inter> ids = {}" using ids_split lmax_le_lv a1 ids_b a8 fst_conv by metis have ids_newbtr: "id_set newbtr = id_set blo - {snd (L b)} \<union> id_set subbtr" using ids_replace_leaf diff_blo ids_blo b_belong_blo ids_subbtr a9 by auto have diff_newbtr: "diff_ids newbtr" using diff_ids_replace_leaf diff_blo lmax_le_lv a1 ids_blo b_belong_blo a8 a9 fst_conv by metis have diff_newbset1: "\<forall>b \<in> newbset. diff_ids b" using a10 diff_bset1 diff_blo diff_newbtr by blast have step1: "(\<forall>b1 b2. b1 \<in> (bset - {blo}) \<and> b2 \<in> (bset - {blo}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using diff_bset2 by auto have step2: "\<forall>b \<in> (bset - {blo}). id_set b \<inter> id_set blo = {}" using diff_bset2 by (metis (mono_tags, lifting) DiffE exi_blo insertCI) have newstep1: "(\<forall>b1 b2. b1 \<in> (newbset - {newbtr}) \<and> b2 \<in> (newbset - {newbtr}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using step1 a10 by auto have newstep2: "\<forall>b \<in> (newbset - {newbtr}). id_set b \<inter> id_set newbtr = {}" using step2 ids_newbtr ids_subbtr a2 a10 disjoint_iff_not_equal by blast have diff_newbset2: "(\<forall>b1 b2. b1 \<in> newbset \<and> b2 \<in> newbset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using newstep1 newstep2 by auto have diff_newbset: "diff_ids_valid newbset" using diff_newbset1 diff_newbset2 diff_ids_valid_def by auto then show ?thesis by auto qed lemma diff_ids_free_branch1: "diff_ids_valid bset \<Longrightarrow> \<not> (\<exists>btree \<in> bset. (L b) \<in> set btree) \<Longrightarrow> diff_ids_valid (fst (free bset b ids))" unfolding free_def Let_def by auto lemma diff_ids_free_branch2: "diff_ids_valid bset \<Longrightarrow> \<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> diff_ids_valid (fst (free bset b ids))" unfolding free_def Let_def by auto lemma combine_id: "id_set b \<subseteq> ids \<Longrightarrow> id_set (fst (combine b ids)) \<subseteq> snd (combine b ids)" unfolding id_set_def combine_def Let_def apply auto using newid_in_getnewid2 by auto lemma combine_anot: "finite ids \<Longrightarrow> b = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)) \<Longrightarrow> id_set (fst (combine b ids)) \<inter> ids = {}" unfolding id_set_def combine_def Let_def apply auto using getnewid2_anot by auto lemma ids_merge: "id_set B \<subseteq> ids \<Longrightarrow> ids \<subseteq> snd (merge B ids)" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) have ids_b1: "id_set b1 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b2: "id_set b2 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b3: "id_set b3 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b4: "id_set b4 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto have ids_com: "ids \<subseteq> snd (combine (Node b1 b2 b3 b4) ids)" using combine_ids by blast then have ?case using step by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have ids_belong_m1: "ids \<subseteq> snd ?m1" using Node.hyps(1) ids_b1 by auto have b2_belong_m1: "id_set b2 \<subseteq> snd ?m1" using ids_b2 ids_belong_m1 by auto let ?m2 = "merge b2 (snd ?m1)" have m1_belong_m2: "snd ?m1 \<subseteq> snd ?m2" using Node.hyps(2) b2_belong_m1 by auto have b3_belong_m2: "id_set b3 \<subseteq> snd ?m2" using ids_b3 ids_belong_m1 m1_belong_m2 by auto let ?m3 = "merge b3 (snd ?m2)" have m2_belong_m3: "snd ?m2 \<subseteq> snd ?m3" using Node.hyps(3) b3_belong_m2 by auto have b4_belong_m3: "id_set b4 \<subseteq> snd ?m3" using ids_b4 ids_belong_m1 m1_belong_m2 m2_belong_m3 by auto let ?m4 = "merge b4 (snd ?m3)" have m3_belong_m4: "snd ?m3 \<subseteq> snd ?m4" using Node.hyps(4) b4_belong_m3 by auto have ids_belong_m4: "ids \<subseteq> snd ?m4" using ids_belong_m1 m1_belong_m2 m2_belong_m3 m3_belong_m4 by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have m4_belong_com: "snd ?m4 \<subseteq> snd (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))" using combine_ids by blast have ?case using step ids_belong_m4 m4_belong_com by auto } ultimately have ?case by blast then show ?case by auto qed lemma ids_merge2: "id_set B \<subseteq> ids \<Longrightarrow> id_set (fst (merge B ids)) \<subseteq> snd (merge B ids)" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) have ids_b1: "id_set b1 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b2: "id_set b2 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b3: "id_set b3 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) have ids_b4: "id_set b4 \<subseteq> ids" using Node.prems(1) by (simp add: id_set_node) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto have ids_com: "id_set (fst (combine (Node b1 b2 b3 b4) ids)) \<subseteq> snd (combine (Node b1 b2 b3 b4) ids)" using combine_id Node.prems(1) by auto then have ?case using step by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have induct1: "id_set (fst ?m1) \<subseteq> snd ?m1" using Node.hyps(1) ids_b1 by auto have ids_belong_m1: "ids \<subseteq> snd ?m1" using ids_merge ids_b1 by auto have b2_belong_m1: "id_set b2 \<subseteq> snd ?m1" using ids_b2 ids_belong_m1 by auto let ?m2 = "merge b2 (snd ?m1)" have induct2: "id_set (fst ?m2) \<subseteq> snd ?m2" using Node.hyps(2) b2_belong_m1 by auto have m1_belong_m2: "snd ?m1 \<subseteq> snd ?m2" using ids_merge b2_belong_m1 by auto have b3_belong_m2: "id_set b3 \<subseteq> snd ?m2" using ids_b3 ids_belong_m1 m1_belong_m2 by auto let ?m3 = "merge b3 (snd ?m2)" have induct3: "id_set (fst ?m3) \<subseteq> snd ?m3" using Node.hyps(3) b3_belong_m2 by auto have m2_belong_m3: "snd ?m2 \<subseteq> snd ?m3" using ids_merge b3_belong_m2 by auto have b4_belong_m3: "id_set b4 \<subseteq> snd ?m3" using ids_b4 ids_belong_m1 m1_belong_m2 m2_belong_m3 by auto let ?m4 = "merge b4 (snd ?m3)" have induct4: "id_set (fst ?m4) \<subseteq> snd ?m4" using Node.hyps(4) b4_belong_m3 by auto have m3_belong_m4: "snd ?m3 \<subseteq> snd ?m4" using ids_merge b4_belong_m3 by auto have induct5: "id_set (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) \<subseteq> snd ?m4" using induct1 induct2 induct3 induct4 m1_belong_m2 m2_belong_m3 m3_belong_m4 id_set_node by blast have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have ids_com: "id_set (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))) \<subseteq> snd (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))" using combine_id induct5 by auto have ?case using step ids_com by auto } ultimately have ?case by blast then show ?case by auto qed lemma finite_merge: "finite ids \<Longrightarrow> finite (snd (merge B ids))" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto have ?case using combine_finite Node.prems(1) step by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have finite_m1: "finite (snd ?m1)" using Node.hyps(1) Node.prems(1) by auto let ?m2 = "merge b2 (snd ?m1)" have finite_m2: "finite (snd ?m2)" using Node.hyps(2) finite_m1 by auto let ?m3 = "merge b3 (snd ?m2)" have finite_m3: "finite (snd ?m3)" using Node.hyps(3) finite_m2 by auto let ?m4 = "merge b4 (snd ?m3)" have finite_m4: "finite (snd ?m4)" using Node.hyps(4) finite_m3 by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have ?case using combine_finite finite_m4 step by auto } ultimately have ?case by blast then show ?case by auto qed lemma overlap_merge: "finite ids \<Longrightarrow> id_set oth \<subseteq> ids \<Longrightarrow> id_set B \<subseteq> ids \<Longrightarrow> id_set oth \<inter> id_set B = {} \<Longrightarrow> id_set oth \<inter> id_set (fst (merge B ids)) = {}" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) have ids_b1: "id_set b1 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b2: "id_set b2 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b3: "id_set b3 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b4: "id_set b4 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have oth_b1: "id_set oth \<inter> id_set b1 = {}" using Node.prems(4) id_set_node by auto have oth_b2: "id_set oth \<inter> id_set b2 = {}" using Node.prems(4) id_set_node by auto have oth_b3: "id_set oth \<inter> id_set b3 = {}" using Node.prems(4) id_set_node by auto have oth_b4: "id_set oth \<inter> id_set b4 = {}" using Node.prems(4) id_set_node by auto {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto have com_ids_empty: "id_set (fst (combine (Node b1 b2 b3 b4) ids)) \<inter> ids = {}" using combine_anot Node.prems(1) a0 by blast have ?case using step com_ids_empty Node.prems(2) by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have over_m1: "id_set oth \<inter> id_set (fst ?m1) = {}" using Node.hyps(1) Node.prems(1,2) ids_b1 oth_b1 by auto have finite_m1: "finite (snd ?m1)" using finite_merge Node.prems(1) by auto have ids_belong_m1: "ids \<subseteq> snd ?m1" using ids_merge ids_b1 by auto have oth_belong_m1: "id_set oth \<subseteq> snd ?m1" using Node.prems(2) ids_belong_m1 by auto have b2_belong_m1: "id_set b2 \<subseteq> snd ?m1" using ids_b2 ids_belong_m1 by auto let ?m2 = "merge b2 (snd ?m1)" have over_m2: "id_set oth \<inter> id_set (fst ?m2) = {}" using Node.hyps(2) finite_m1 oth_belong_m1 b2_belong_m1 oth_b2 by auto have finite_m2: "finite (snd ?m2)" using finite_merge finite_m1 by auto have m1_belong_m2: "snd ?m1 \<subseteq> snd ?m2" using ids_merge b2_belong_m1 by auto have oth_belong_m2: "id_set oth \<subseteq> snd ?m2" using oth_belong_m1 m1_belong_m2 by auto have b3_belong_m2: "id_set b3 \<subseteq> snd ?m2" using ids_b3 ids_belong_m1 m1_belong_m2 by auto let ?m3 = "merge b3 (snd ?m2)" have over_m3: "id_set oth \<inter> id_set (fst ?m3) = {}" using Node.hyps(3) finite_m2 oth_belong_m2 b3_belong_m2 oth_b3 by auto have finite_m3: "finite (snd ?m3)" using finite_merge finite_m2 by auto have m2_belong_m3: "snd ?m2 \<subseteq> snd ?m3" using ids_merge b3_belong_m2 by auto have oth_belong_m3: "id_set oth \<subseteq> snd ?m3" using oth_belong_m1 m1_belong_m2 m2_belong_m3 by auto have b4_belong_m3: "id_set b4 \<subseteq> snd ?m3" using ids_b4 ids_belong_m1 m1_belong_m2 m2_belong_m3 by auto let ?m4 = "merge b4 (snd ?m3)" have over_m4: "id_set oth \<inter> id_set (fst ?m4) = {}" using Node.hyps(4) finite_m3 oth_belong_m3 b4_belong_m3 oth_b4 by auto have finite_m4: "finite (snd ?m4)" using finite_merge finite_m3 by auto have m3_belong_m4: "snd ?m3 \<subseteq> snd ?m4" using ids_merge b4_belong_m3 by auto have oth_belong_m4: "id_set oth \<subseteq> snd ?m4" using oth_belong_m1 m1_belong_m2 m2_belong_m3 m3_belong_m4 by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have oth_com: "id_set oth \<inter> id_set (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))) = {}" proof(cases "\<exists>xa xb xc xd. Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))") case True have com_m4: "id_set (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))) \<inter> (snd ?m4) = {}" using combine_anot finite_m4 True by blast show ?thesis using oth_belong_m4 com_m4 by auto next case False have step': "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)" unfolding combine_def using False by auto have oth_node: "id_set oth \<inter> id_set (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) = {}" using over_m1 over_m2 over_m3 over_m4 unfolding id_set_def by auto show ?thesis using step' oth_node by auto qed have ?case using step oth_com by auto } ultimately have ?case by blast then show ?case by auto qed lemma diff_ids_merge: "diff_ids B \<Longrightarrow> finite ids \<Longrightarrow> id_set B \<subseteq> ids \<Longrightarrow> diff_ids (fst (merge B ids))" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have ids_b1: "id_set b1 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b2: "id_set b2 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b3: "id_set b3 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) have ids_b4: "id_set b4 \<subseteq> ids" using Node.prems(3) by (simp add: id_set_node) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto obtain newid where com: "fst (combine (Node b1 b2 b3 b4) ids) = Leaf (FREE, newid)" unfolding combine_def Let_def using fst_conv a0 by auto then have ?case using step diff1 by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have diff_m1: "diff_ids (fst ?m1)" using Node.hyps(1) diff_b1 Node.prems(2) ids_b1 by auto have finite_m1: "finite (snd ?m1)" using finite_merge Node.prems(2) by auto have ids_m1: "id_set (fst ?m1) \<subseteq> snd ?m1" using ids_merge2 ids_b1 by auto have ids_belong_m1: "ids \<subseteq> snd ?m1" using ids_merge diff_b1 ids_b1 by auto have b2_belong_m1: "id_set b2 \<subseteq> snd ?m1" using ids_b2 ids_belong_m1 by auto have b3_belong_m1: "id_set b3 \<subseteq> snd ?m1" using ids_b3 ids_belong_m1 by auto have b4_belong_m1: "id_set b4 \<subseteq> snd ?m1" using ids_b4 ids_belong_m1 by auto have b2_m1: "id_set b2 \<inter> id_set (fst ?m1) = {}" using overlap_merge Node.prems(2) ids_b2 ids_b1 diff_ab by (simp add: Int_commute) have b3_m1: "id_set b3 \<inter> id_set (fst ?m1) = {}" using overlap_merge Node.prems(2) ids_b3 ids_b1 diff_ac by (simp add: Int_commute) have b4_m1: "id_set b4 \<inter> id_set (fst ?m1) = {}" using overlap_merge Node.prems(2) ids_b4 ids_b1 diff_ad by (simp add: Int_commute) let ?m2 = "merge b2 (snd ?m1)" have diff_m2: "diff_ids (fst ?m2)" using Node.hyps(2) diff_b2 finite_m1 b2_belong_m1 by auto have finite_m2: "finite (snd ?m2)" using finite_merge finite_m1 by auto have ids_m2: "id_set (fst ?m2) \<subseteq> snd ?m2" using ids_merge2 b2_belong_m1 by auto have m1_belong_m2: "snd ?m1 \<subseteq> snd ?m2" using ids_merge diff_b2 b2_belong_m1 by auto have b3_belong_m2: "id_set b3 \<subseteq> snd ?m2" using ids_b3 ids_belong_m1 m1_belong_m2 by auto have b4_belong_m2: "id_set b4 \<subseteq> snd ?m2" using ids_b4 ids_belong_m1 m1_belong_m2 by auto have m1_m2: "id_set (fst ?m1) \<inter> id_set (fst ?m2) = {}" using overlap_merge finite_m1 ids_m1 b2_belong_m1 b2_m1 by (simp add: Int_commute) have b3_m2: "id_set b3 \<inter> id_set (fst ?m2) = {}" using overlap_merge finite_m1 b3_belong_m1 b2_belong_m1 diff_bc by (simp add: Int_commute) have b4_m2: "id_set b4 \<inter> id_set (fst ?m2) = {}" using overlap_merge finite_m1 b4_belong_m1 b2_belong_m1 diff_bd by (simp add: Int_commute) let ?m3 = "merge b3 (snd ?m2)" have diff_m3: "diff_ids (fst ?m3)" using Node.hyps(3) diff_b3 finite_m2 b3_belong_m2 by auto have finite_m3: "finite (snd ?m3)" using finite_merge finite_m2 by auto have ids_m3: "id_set (fst ?m3) \<subseteq> snd ?m3" using ids_merge2 b3_belong_m2 by auto have m2_belong_m3: "snd ?m2 \<subseteq> snd ?m3" using ids_merge diff_b3 b3_belong_m2 by auto have b4_belong_m3: "id_set b4 \<subseteq> snd ?m3" using ids_b4 ids_belong_m1 m1_belong_m2 m2_belong_m3 by auto have m1_m3: "id_set (fst ?m1) \<inter> id_set (fst ?m3) = {}" using overlap_merge finite_m2 ids_m1 m1_belong_m2 b3_belong_m2 b3_m1 by (simp add: Int_commute) have m2_m3: "id_set (fst ?m2) \<inter> id_set (fst ?m3) = {}" using overlap_merge finite_m2 ids_m2 b3_belong_m2 b3_m2 by (simp add: Int_commute) have b4_m3: "id_set b4 \<inter> id_set (fst ?m3) = {}" using overlap_merge finite_m2 b4_belong_m2 b3_belong_m2 diff_cd by (simp add: Int_commute) let ?m4 = "merge b4 (snd ?m3)" have diff_m4: "diff_ids (fst ?m4)" using Node.hyps(4) diff_b4 finite_m3 b4_belong_m3 by auto have finite_m4: "finite (snd ?m4)" using finite_merge finite_m3 by auto have ids_m4: "id_set (fst ?m4) \<subseteq> snd ?m4" using ids_merge2 b4_belong_m3 by auto have m3_belong_m4: "snd ?m3 \<subseteq> snd ?m4" using ids_merge diff_b4 b4_belong_m3 by auto have ids_belong_m4: "ids \<subseteq> snd ?m4" using ids_belong_m1 m1_belong_m2 m2_belong_m3 m3_belong_m4 by auto have m1_m4: "id_set (fst ?m1) \<inter> id_set (fst ?m4) = {}" using overlap_merge finite_m3 ids_m1 m1_belong_m2 m2_belong_m3 b4_belong_m3 b4_m1 by (simp add: Int_commute) have m2_m4: "id_set (fst ?m2) \<inter> id_set (fst ?m4) = {}" using overlap_merge finite_m3 ids_m2 m2_belong_m3 b4_belong_m3 b4_m2 by (simp add: Int_commute) have m3_m4: "id_set (fst ?m3) \<inter> id_set (fst ?m4) = {}" using overlap_merge finite_m3 ids_m3 b4_belong_m3 b4_m3 by (simp add: Int_commute) have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have diff_com: "diff_ids (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)))" proof(cases "\<exists>xa xb xc xd. Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))") case True obtain newid where step1: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Leaf (FREE, newid)" unfolding combine_def Let_def using True by auto show ?thesis using step1 diff1 by auto next case False have step2: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)" unfolding combine_def using False by auto show ?thesis using step2 diff_m1 diff_m2 diff_m3 diff_m4 using m1_m2 m1_m3 m1_m4 m2_m3 m2_m4 m3_m4 diff2 by simp qed have ?case using step diff_com by auto } ultimately have ?case by blast then show ?case by auto qed lemma diff_ids_free_branch3: "diff_ids_valid bset \<Longrightarrow> finite ids \<Longrightarrow> \<forall>b\<in>bset. id_set b \<subseteq> ids \<Longrightarrow> \<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) \<noteq> FREE \<Longrightarrow> (newbset, newids, re) = free bset b ids \<Longrightarrow> diff_ids_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "finite ids" and a2: "\<forall>b\<in>bset. id_set b \<subseteq> ids" and a3: "\<exists>btree \<in> bset. (L b) \<in> set btree" and a4: "fst (L b) \<noteq> FREE" and a5: "(newbset, newids, re) = free bset b ids" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_btree: "\<exists>!btree \<in> bset. (L b) \<in> set btree" using a3 diff_bset2 proof - { fix tt :: "(block_state_type \<times> nat) tree" and tta :: "(block_state_type \<times> nat) tree \<Rightarrow> (block_state_type \<times> nat) tree" have "\<And>t ta n. t \<notin> bset \<or> ta \<notin> bset \<or> n \<notin> tree.set (tree_map snd t) \<or> n \<notin> tree.set (tree_map snd ta) \<or> ta = t" using diff_bset2 id_set_def by auto then have "\<exists>t. tt \<notin> bset \<or> tta t \<notin> bset \<or> L b \<notin> tree.set tt \<or> t \<in> bset \<and> tta t = t \<and> L b \<in> tree.set t \<or> t \<in> bset \<and> L b \<in> tree.set t \<and> L b \<notin> tree.set (tta t)" by (metis (no_types) image_eqI tree.set_map) } then have "\<forall>t. \<exists>ta. \<forall>tb. t \<notin> bset \<or> tb \<notin> bset \<or> L b \<notin> tree.set t \<or> ta \<in> bset \<and> tb = ta \<and> L b \<in> tree.set ta \<or> ta \<in> bset \<and> L b \<in> tree.set ta \<and> L b \<notin> tree.set tb" by (metis (no_types)) then show ?thesis by (metis a3) qed let ?btree = "THE t. t \<in> bset \<and> (L b) \<in> set t" have the_btree: "?btree \<in> bset \<and> (L b) \<in> set ?btree" using the_P[OF exi_btree] by blast have diff_btree: "diff_ids ?btree" using the_btree diff_bset1 by auto have ids_btree: "id_set ?btree \<subseteq> ids" using the_btree a2 by auto have exi_newb: "\<exists>newb. newb = replace ?btree b (set_state_type b FREE)" by simp let ?freeblo = "SOME newb. newb = replace ?btree b (set_state_type b FREE)" have diff_freeblo: "diff_ids ?freeblo" using diff_ids_replace diff_btree the_btree by simp have same_ids: "id_set ?btree = id_set ?freeblo" using same_ids_replace diff_btree the_btree by simp have exi_re: "\<exists>re. re = merge ?freeblo ids" by simp let ?re = "SOME re. re = merge ?freeblo ids" have diff_newblo: "diff_ids (fst ?re)" using diff_ids_merge diff_freeblo a1 ids_btree same_ids by auto have overlap_btree: "\<forall>b \<in> bset. b \<noteq> ?btree \<longrightarrow> id_set b \<inter> id_set ?btree = {}" using diff_bset2 the_btree by auto let ?tembset = "(bset - {?btree}) \<union> {?freeblo}" have ids_tembset: "\<forall>b\<in>?tembset. id_set b \<subseteq> ids" using a2 ids_btree same_ids by auto have overlap_freeblo: "\<forall>b \<in> ?tembset. b \<noteq> ?freeblo \<longrightarrow> id_set b \<inter> id_set ?freeblo = {}" using overlap_btree same_ids by auto have ids_merge_freeblo: "\<forall>b \<in> ?tembset. b \<noteq> ?freeblo \<longrightarrow> id_set b \<inter> id_set (fst ?re) = {}" using overlap_merge a1 ids_tembset overlap_freeblo by auto (*------------------------------------------------------------------------------------------------*) have free_re: "(newbset, newids, re) = ((bset - {?btree}) \<union> {fst ?re}, snd ?re, True)" using a4 a5 unfolding free_def Let_def using exi_btree by auto have diff_newbset1: "\<forall>b \<in> newbset. diff_ids b" using free_re diff_bset1 diff_btree diff_newblo by blast have step1: "(\<forall>b1 b2. b1 \<in> (bset - {?btree}) \<and> b2 \<in> (bset - {?btree}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using diff_bset2 by auto have newstep1: "(\<forall>b1 b2. b1 \<in> (newbset - {fst ?re}) \<and> b2 \<in> (newbset - {fst ?re}) \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using step1 free_re by auto have newstep2: "\<forall>b \<in> (newbset - {fst ?re}). id_set b \<inter> id_set (fst ?re) = {}" using ids_merge_freeblo free_re by (metis (no_types, lifting) DiffE Int_left_absorb UnCI UnE fst_conv id_set_notempty ids_btree inf.orderE overlap_btree same_ids singletonI) have diff_newbset2: "(\<forall>b1 b2. b1 \<in> newbset \<and> b2 \<in> newbset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using newstep1 newstep2 by auto show ?thesis using diff_newbset1 diff_newbset2 diff_ids_valid_def by auto qed subsection \<open>def and proof of inv_block_free\<close> inductive block_free :: "Block \<Rightarrow> bool" where free1: "block_free (Leaf a)" | free2: "block_free ll \<and> block_free lr \<and> block_free rl \<and> block_free rr \<and> \<not> (\<exists>xa xb xc xd. (Node ll lr rl rr) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))) \<Longrightarrow> block_free (Node ll lr rl rr)" inductive_cases block_free_leaf_node: "block_free (Leaf a)" "block_free (Node ll lr rl rr)" definition "block_free_valid bset \<equiv> (\<forall>b \<in> bset. block_free b)" lemma block_free_free_branch1: "block_free_valid bset \<Longrightarrow> \<not> (\<exists>btree \<in> bset. (L b) \<in> set btree) \<Longrightarrow> block_free_valid (fst (free bset b ids))" unfolding free_def Let_def by auto lemma block_free_free_branch2: "block_free_valid bset \<Longrightarrow> \<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> block_free_valid (fst (free bset b ids))" unfolding free_def Let_def by auto lemma block_free_merge: "block_free (fst (merge B ids))" proof(induct B arbitrary: ids) case (Leaf x) then show ?case using free1 by auto next case (Node b1 b2 b3 b4) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto obtain newid where com: "fst (combine (Node b1 b2 b3 b4) ids) = Leaf (FREE, newid)" unfolding combine_def Let_def using fst_conv a0 by auto then have ?case using step free1 by auto } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have free_m1: "block_free (fst ?m1)" using Node.hyps(1) by auto let ?m2 = "merge b2 (snd ?m1)" have free_m2: "block_free (fst ?m2)" using Node.hyps(2) by auto let ?m3 = "merge b3 (snd ?m2)" have free_m3: "block_free (fst ?m3)" using Node.hyps(3) by auto let ?m4 = "merge b4 (snd ?m3)" have free_m4: "block_free (fst ?m4)" using Node.hyps(4) by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have free_com: "block_free (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)))" proof(cases "\<exists>xa xb xc xd. Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))") case True obtain newid where step1: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Leaf (FREE, newid)" unfolding combine_def Let_def using True by auto show ?thesis using step1 free1 by auto next case False have step2: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)" unfolding combine_def using False by auto show ?thesis using step2 free_m1 free_m2 free_m3 free_m4 False free2 by auto qed have ?case using step free_com by auto } ultimately have ?case by blast then show ?case by auto qed lemma block_free_free_branch3: "diff_ids_valid bset \<Longrightarrow> block_free_valid bset \<Longrightarrow> \<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) \<noteq> FREE \<Longrightarrow> (newbset, newids, re) = free bset b ids \<Longrightarrow> block_free_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "block_free_valid bset" and a2: "\<exists>btree \<in> bset. (L b) \<in> set btree" and a3: "fst (L b) \<noteq> FREE" and a4: "(newbset, newids, re) = free bset b ids" have diff_bset: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have free_bset: "(\<forall>b \<in> bset. block_free b)" using a1 block_free_valid_def by auto have exi_btree: "\<exists>!btree \<in> bset. (L b) \<in> set btree" using a1 diff_bset proof - { fix tt :: "(block_state_type \<times> nat) tree" and tta :: "(block_state_type \<times> nat) tree \<Rightarrow> (block_state_type \<times> nat) tree" have "\<And>t ta n. t \<notin> bset \<or> ta \<notin> bset \<or> n \<notin> tree.set (tree_map snd t) \<or> n \<notin> tree.set (tree_map snd ta) \<or> ta = t" using diff_bset id_set_def by auto then have "\<exists>t. tt \<notin> bset \<or> tta t \<notin> bset \<or> L b \<notin> tree.set tt \<or> t \<in> bset \<and> tta t = t \<and> L b \<in> tree.set t \<or> t \<in> bset \<and> L b \<in> tree.set t \<and> L b \<notin> tree.set (tta t)" by (metis (no_types) image_eqI tree.set_map) } then have "\<forall>t. \<exists>ta. \<forall>tb. t \<notin> bset \<or> tb \<notin> bset \<or> L b \<notin> tree.set t \<or> ta \<in> bset \<and> tb = ta \<and> L b \<in> tree.set ta \<or> ta \<in> bset \<and> L b \<in> tree.set ta \<and> L b \<notin> tree.set tb" by (metis (no_types)) then show ?thesis by (metis a2) qed let ?btree = "THE t. t \<in> bset \<and> (L b) \<in> set t" have the_btree: "?btree \<in> bset \<and> (L b) \<in> set ?btree" using the_P[OF exi_btree] by blast have free_btree: "block_free ?btree" using the_btree free_bset by auto have exi_newb: "\<exists>newb. newb = replace ?btree b (set_state_type b FREE)" by simp let ?freeblo = "SOME newb. newb = replace ?btree b (set_state_type b FREE)" have exi_re: "\<exists>re. re = merge ?freeblo ids" by simp let ?re = "SOME re. re = merge ?freeblo ids" have free_newblo: "block_free (fst ?re)" using block_free_merge by auto have free_re: "(newbset, newids, re) = ((bset - {?btree}) \<union> {fst ?re}, snd ?re, True)" using a3 a4 unfolding free_def Let_def using exi_btree by auto have free_newbset: "(\<forall>b \<in> newbset. block_free b)" using free_re free_bset free_btree free_newblo by auto show ?thesis using free_newbset block_free_valid_def by auto qed lemma block_free_alloc_fail: "block_free_valid bset \<Longrightarrow> \<not> (exists_freelevel bset lv) \<Longrightarrow> block_free_valid (fst (alloc bset lv ids))" unfolding alloc_def Let_def by auto lemma block_free_replace_alloc: "diff_ids B \<Longrightarrow> block_free B \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b ALLOC \<Longrightarrow> block_free (replace B b b')" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(3) by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Leaf.prems(4) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto then show ?case using free1 by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have free_b1: "block_free b1" using Node.prems(2) block_free_leaf_node(2) by blast have free_b2: "block_free b2" using Node.prems(2) block_free_leaf_node(2) by blast have free_b3: "block_free b3" using Node.prems(2) block_free_leaf_node(2) by blast have free_b4: "block_free b4" using Node.prems(2) block_free_leaf_node(2) by blast have free_node: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" using Node.prems(2) block_free_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(4) apply auto[1] using no_replace no_belong_b3 Node.prems(4) apply auto[1] using no_replace no_belong_b4 Node.prems(4) by auto have free_b1': "block_free (replace b1 b b')" using Node.hyps(1) diff_b1 free_b1 a0 Node.prems(4) by auto have free_node': "\<not> (\<exists>xa xb xc xd. (Node (replace b1 b b') b2 b3 b4) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" proof- {assume c10: "leaf b1" obtain x where c11: "b1 = Leaf x" using c10 by (metis tree.collapse(1)) have leaf_b: "L b = x" using a0 c11 by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Node.prems(4) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have ?thesis using leaf_B' by (simp add: c11) }moreover {assume c20: "\<not> leaf b1" have node_b1: "node b1" using c20 tree.exhaust_disc by auto obtain m1 m2 m3 m4 where c21: "b1 = Node m1 m2 m3 m4" using node_b1 by (metis tree.collapse(2)) have node_replace: "node (replace (Node m1 m2 m3 m4) b b')" unfolding replace_def by auto have ?thesis using node_replace c21 by auto } ultimately have ?thesis by auto then show ?thesis by auto qed have ?case using replace_re free_b1' free_b2 free_b3 free_b4 free_node' free2 by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(4) apply auto[1] using no_replace no_belong_b3 Node.prems(4) apply auto[1] using no_replace no_belong_b4 Node.prems(4) by auto have free_b2': "block_free (replace b2 b b')" using Node.hyps(2) diff_b2 free_b2 a1 Node.prems(4) by auto have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 (replace b2 b b') b3 b4) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" proof- {assume c10: "leaf b2" obtain x where c11: "b2 = Leaf x" using c10 by (metis tree.collapse(1)) have leaf_b: "L b = x" using a1 c11 by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Node.prems(4) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have ?thesis using leaf_B' by (simp add: c11) }moreover {assume c20: "\<not> leaf b2" have node_b1: "node b2" using c20 tree.exhaust_disc by auto obtain m1 m2 m3 m4 where c21: "b2 = Node m1 m2 m3 m4" using node_b1 by (metis tree.collapse(2)) have node_replace: "node (replace (Node m1 m2 m3 m4) b b')" unfolding replace_def by auto have ?thesis using node_replace c21 by auto } ultimately have ?thesis by auto then show ?thesis by auto qed have ?case using replace_re free_b1 free_b2' free_b3 free_b4 free_node' free2 by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(4) apply auto[1] using no_replace no_belong_b2 Node.prems(4) apply auto[1] using no_replace no_belong_b4 Node.prems(4) by auto have free_b3': "block_free (replace b3 b b')" using Node.hyps(3) diff_b3 free_b3 a2 Node.prems(4) by auto have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 b2 (replace b3 b b') b4) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" proof- {assume c10: "leaf b3" obtain x where c11: "b3 = Leaf x" using c10 by (metis tree.collapse(1)) have leaf_b: "L b = x" using a2 c11 by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Node.prems(4) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have ?thesis using leaf_B' by (simp add: c11) }moreover {assume c20: "\<not> leaf b3" have node_b1: "node b3" using c20 tree.exhaust_disc by auto obtain m1 m2 m3 m4 where c21: "b3 = Node m1 m2 m3 m4" using node_b1 by (metis tree.collapse(2)) have node_replace: "node (replace (Node m1 m2 m3 m4) b b')" unfolding replace_def by auto have ?thesis using node_replace c21 by auto } ultimately have ?thesis by auto then show ?thesis by auto qed have ?case using replace_re free_b1 free_b2 free_b3' free_b4 free_node' free2 by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(4) apply auto[1] using no_replace no_belong_b2 Node.prems(4) apply auto[1] using no_replace no_belong_b3 Node.prems(4) by auto have free_b4': "block_free (replace b4 b b')" using Node.hyps(4) diff_b4 free_b4 a3 Node.prems(4) by auto have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 (replace b4 b b')) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" proof- {assume c10: "leaf b4" obtain x where c11: "b4 = Leaf x" using c10 by (metis tree.collapse(1)) have leaf_b: "L b = x" using a3 c11 by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Node.prems(4) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have ?thesis using leaf_B' by (simp add: c11) }moreover {assume c20: "\<not> leaf b4" have node_b1: "node b4" using c20 tree.exhaust_disc by auto obtain m1 m2 m3 m4 where c21: "b4 = Node m1 m2 m3 m4" using node_b1 by (metis tree.collapse(2)) have node_replace: "node (replace (Node m1 m2 m3 m4) b b')" unfolding replace_def by auto have ?thesis using node_replace c21 by auto } ultimately have ?thesis by auto then show ?thesis by auto qed have ?case using replace_re free_b1 free_b2 free_b3 free_b4' free_node' free2 by auto } ultimately have ?case using Node.prems(3) by fastforce then show ?case by auto qed lemma block_free_alloc_branch1: "diff_ids_valid bset \<Longrightarrow> block_free_valid bset \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax = lv \<Longrightarrow> (newbset, newids, re, reid) = alloc1 bset lv ids \<Longrightarrow> block_free_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "block_free_valid bset" and a2: "exists_freelevel bset lv" and a3: "lmax = freesets_maxlevel bset lv" and a4: "lmax = lv" and a5: "(newbset, newids, re, reid) = alloc1 bset lv ids" have diff_bset: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have free_bset: "(\<forall>b \<in> bset. block_free b)" using a1 block_free_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a2 by auto have eq_lv: "lv = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a3 a4 unfolding freesets_maxlevel_def by auto have the_lv: "lv \<le> lv \<and> freesets_level_pool bset lv \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lv)" using the_P[OF exi_lmax eq_lv] by auto have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" using the_lv unfolding freesets_level_pool_def by auto let ?blo = "SOME b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" have diff_blo: "diff_ids ?blo" using diff_bset exi_b by (metis (mono_tags, lifting) some_eq_ex) have free_blo: "block_free ?blo" using free_bset exi_b by (metis (mono_tags, lifting) some_eq_ex) have exi_l: "\<exists>l. l \<in> freesets_level ?blo lv" using someI_ex[OF exi_b] by auto let ?l = "SOME l. l \<in> freesets_level ?blo lv" have leaf_belong: "L ?l \<in> set ?blo" using exi_l unfolding freesets_level_def freesets_def by (metis (no_types, lifting) CollectD someI_ex) have exi_newb: "\<exists>newb. newb = replace ?blo ?l (set_state_type ?l ALLOC)" by simp let ?newb = "SOME newb. newb = replace ?blo ?l (set_state_type ?l ALLOC)" have free_newblo: "block_free ?newb" using block_free_replace_alloc diff_blo free_blo leaf_belong by simp have alloc1_re: "(newbset, newids, re, reid) = (((bset - {?blo}) \<union> {?newb}), ids, True, {snd (L ?l)})" using a5 unfolding alloc1_def by (metis some_eq_trivial) have free_newbset: "\<forall>b \<in> newbset. block_free b" using alloc1_re free_bset free_blo free_newblo by blast show ?thesis using free_newbset block_free_valid_def by auto qed lemma block_free_split: "lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> snd (L b) \<in> ids \<Longrightarrow> block_free (fst (split b ids (lv - lmax)))" proof(induct "lv - lmax" arbitrary: lmax b ids) case 0 then show ?case by auto next case (Suc xa) obtain ll lr rl rr where pdivide: "fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" and alloc_ll: "fst ll = ALLOC" unfolding divide_def Let_def by auto let ?newids = "snd (divide b ids)" have belong_ll: "snd ll \<in> ?newids" using divide_belong pdivide by auto have step': "fst (split b ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)" using split_induct Suc(3) pdivide by (meson zero_less_diff) {assume xa_eq_1: "Suc xa = 1" have lv_suc_lmax: "lv = Suc lmax" using Suc(2) xa_eq_1 by linarith have split_ll: "fst (split (Leaf ll) ?newids (lv - lmax - 1)) = Leaf ll" using lv_suc_lmax by auto have step1: "fst (split b ids (lv - lmax)) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" using step' split_ll by auto have free_node': "\<not> (\<exists>xa xb xc xd. (Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)) = (Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))))" using alloc_ll by auto have free_node: "block_free (Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr))" using free1 free2 free_node' by auto have ?case using step1 free_node by auto } moreover {assume xa_gr_1: "Suc xa > 1" have xa_lv_suc_lmax: "xa = lv - Suc lmax" using Suc(2) by linarith have suc_lmax_less_lv: "Suc lmax < lv" using Suc(3) xa_gr_1 xa_lv_suc_lmax by linarith have split2: "block_free (fst (split (Leaf ll) ?newids (lv - Suc lmax)))" using Suc(1) xa_lv_suc_lmax suc_lmax_less_lv divide_finite Suc(4) belong_ll pdivide by auto have node_split: "node (fst (split (Leaf ll) ?newids (lv - Suc lmax)))" using split.simps suc_lmax_less_lv by (metis diff_is_0_eq fst_conv leD tree.disc(4)) have free_node': "\<not> (\<exists>xa xb xc xd. (Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" using node_split by auto have free_node: "block_free (Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr))" using free1 free2 split2 free_node' by auto have ?case using step' free_node by auto } ultimately have ?case by linarith then show ?case by auto qed lemma block_free_replace_leaf: "diff_ids blo \<Longrightarrow> block_free blo \<Longrightarrow> lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> id_set blo \<subseteq> ids \<Longrightarrow> L b \<in> tree.set blo \<Longrightarrow> block_free (replace_leaf blo b (fst (split b ids (lv - lmax))))" proof(induct blo) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(6) by fastforce have b_belong: "snd (L b) \<in> ids" using Leaf.prems(5) leaf_b unfolding id_set_def by auto have free_b_split: "block_free (fst (split b ids (lv - lmax)))" using block_free_split Leaf.prems(3,4) b_belong by auto have replace_leaf_step: "replace_leaf (Leaf x) b (fst (split b ids (lv - lmax))) = fst (split b ids (lv - lmax))" using leaf_b replace_leaf.simps(1) by auto show ?case using replace_leaf_step free_b_split by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have free_b1: "block_free b1" using Node.prems(2) block_free_leaf_node(2) by blast have free_b2: "block_free b2" using Node.prems(2) block_free_leaf_node(2) by blast have free_b3: "block_free b3" using Node.prems(2) block_free_leaf_node(2) by blast have free_b4: "block_free b4" using Node.prems(2) block_free_leaf_node(2) by blast have node_split: "node (fst (split b ids (lv - lmax)))" using split.simps Node.prems(3) by (metis diff_is_0_eq fst_conv leD tree.disc(4)) {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node (replace_leaf b1 b (fst (split b ids (lv - lmax)))) b2 b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b2 no_belong_b3 no_belong_b4 by auto have free_b1': "block_free (replace_leaf b1 b (fst (split b ids (lv - lmax))))" using Node.hyps(1) diff_b1 free_b1 Node.prems(3,4,5) a0 unfolding id_set_def by fastforce have node_replace_leaf: "node (replace_leaf b1 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps node_split by (metis Node.prems(1) a0 diff_node4 order_refl replace_subbtr_belong tree.discI(2) tree.exhaust) have free_node': "\<not> (\<exists>xa xb xc xd. (Node (replace_leaf b1 b (fst (split b ids (lv - lmax)))) b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" using node_replace_leaf by auto have free_node: "block_free (Node (replace_leaf b1 b (fst (split b ids (lv - lmax)))) b2 b3 b4)" using free1 free2 free_b1' free_b2 free_b3 free_b4 free_node' by auto have ?case using replace_leaf_step free_node by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 (replace_leaf b2 b (fst (split b ids (lv - lmax)))) b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b3 no_belong_b4 by auto have free_b2': "block_free (replace_leaf b2 b (fst (split b ids (lv - lmax))))" using Node.hyps(2) diff_b2 free_b2 Node.prems(3,4,5) a1 unfolding id_set_def by fastforce have node_replace_leaf: "node (replace_leaf b2 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps node_split by (metis Node.prems(1) a1 diff_node4 order_refl replace_subbtr_belong tree.discI(2) tree.exhaust) have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 (replace_leaf b2 b (fst (split b ids (lv - lmax)))) b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" using node_replace_leaf by auto have free_node: "block_free (Node b1 (replace_leaf b2 b (fst (split b ids (lv - lmax)))) b3 b4)" using free1 free2 free_b1 free_b2' free_b3 free_b4 free_node' by auto have ?case using replace_leaf_step free_node by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 b2 (replace_leaf b3 b (fst (split b ids (lv - lmax)))) b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b4 by auto have free_b3': "block_free (replace_leaf b3 b (fst (split b ids (lv - lmax))))" using Node.hyps(3) diff_b3 free_b3 Node.prems(3,4,5) a2 unfolding id_set_def by fastforce have node_replace_leaf: "node (replace_leaf b3 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps node_split by (metis Node.prems(1) a2 diff_node4 order_refl replace_subbtr_belong tree.discI(2) tree.exhaust) have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 b2 (replace_leaf b3 b (fst (split b ids (lv - lmax)))) b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" using node_replace_leaf by auto have free_node: "block_free (Node b1 b2 (replace_leaf b3 b (fst (split b ids (lv - lmax)))) b4)" using free1 free2 free_b1 free_b2 free_b3' free_b4 free_node' by auto have ?case using replace_leaf_step free_node by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b (fst (split b ids (lv - lmax))) = Node b1 b2 b3 (replace_leaf b4 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b3 by auto have free_b4': "block_free (replace_leaf b4 b (fst (split b ids (lv - lmax))))" using Node.hyps(4) diff_b4 free_b4 Node.prems(3,4,5) a3 unfolding id_set_def by fastforce have node_replace_leaf: "node (replace_leaf b4 b (fst (split b ids (lv - lmax))))" using replace_leaf.simps node_split by (metis Node.prems(1) a3 diff_node4 order_refl replace_subbtr_belong tree.discI(2) tree.exhaust) have free_node': "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 (replace_leaf b4 b (fst (split b ids (lv - lmax))))) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" using node_replace_leaf by auto have free_node: "block_free (Node b1 b2 b3 (replace_leaf b4 b (fst (split b ids (lv - lmax)))))" using free1 free2 free_b1 free_b2 free_b3 free_b4' free_node' by auto have ?case using replace_leaf_step free_node by auto } ultimately have ?case using Node.prems(6) by fastforce then show ?case by auto qed lemma block_free_alloc_branch2: "diff_ids_valid bset \<Longrightarrow> block_free_valid bset \<Longrightarrow> finite ids \<Longrightarrow> \<forall>b\<in>bset. id_set b \<subseteq> ids \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax \<noteq> lv \<Longrightarrow> blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}) \<Longrightarrow> b = (SOME l. l \<in> freesets_level blo lmax) \<Longrightarrow> (subbtr, ids') = split b ids (lv - lmax) \<Longrightarrow> newbtr = replace_leaf blo b subbtr \<Longrightarrow> newbset = bset - {blo} \<union> {newbtr} \<Longrightarrow> block_free_valid newbset" proof- assume a0: "diff_ids_valid bset" and a1: "block_free_valid bset" and a2: "finite ids" and a3: "\<forall>b\<in>bset. id_set b \<subseteq> ids" and a4: "exists_freelevel bset lv" and a5: "lmax = freesets_maxlevel bset lv" and a6: "lmax \<noteq> lv" and a7: "blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {})" and a8: "b = (SOME l. l \<in> freesets_level blo lmax)" and a9: "(subbtr, ids') = split b ids (lv - lmax)" and a10: "newbtr = replace_leaf blo b subbtr" and a11: "newbset = bset - {blo} \<union> {newbtr}" have diff_bset: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have free_bset: "(\<forall>b \<in> bset. block_free b)" using a1 block_free_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a4 by auto have eq_lmax: "lmax = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a5 unfolding freesets_maxlevel_def by auto have the_lmax: "lmax < lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using the_P[OF exi_lmax eq_lmax] a6 by auto have lmax_le_lv: "lmax < lv" using the_lmax by auto (*------------------------------------------------------------------------------------------------*) have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}" using the_lmax unfolding freesets_level_pool_def by auto have exi_blo: "blo \<in> bset \<and> freesets_level blo lmax \<noteq> {}" using someI_ex[OF exi_b] a7 by auto have diff_blo: "diff_ids blo" using diff_bset exi_blo by auto have free_blo: "block_free blo" using free_bset exi_blo by auto have ids_blo: "id_set blo \<subseteq> ids" using a3 exi_blo by auto have exi_l: "\<exists>l. l \<in> freesets_level blo lmax" using exi_blo by auto have exi_b: "b \<in> freesets_level blo lmax" using someI_ex[OF exi_l] a8 by auto have b_belong_blo: "L b \<in> tree.set blo" using exi_b unfolding freesets_level_def freesets_def by auto (*------------------------------------------------------------------------------------------------*) have free_newbtr: "block_free newbtr" using block_free_replace_leaf diff_blo free_blo lmax_le_lv a2 ids_blo b_belong_blo a9 a10 fst_conv by metis have free_newbset': "\<forall>b \<in> newbset. block_free b" using a11 free_bset free_blo free_newbtr by blast have free_newbset: "block_free_valid newbset" using free_newbset' block_free_valid_def by auto then show ?thesis by auto qed subsection \<open>def and proof of inv_block_leak\<close> fun get_node :: "Block \<Rightarrow> Block set" where "get_node (Leaf x) = {}" | "get_node (Node n1 n2 n3 n4) = get_node n1 \<union> get_node n2 \<union> get_node n3 \<union> get_node n4 \<union> {(Node n1 n2 n3 n4)}" definition quadtree :: "Block \<Rightarrow> bool" where "quadtree b \<equiv> card (set b) = Suc (card (get_node b) * 3)" lemma get_node_set: "x \<in> get_node b \<Longrightarrow> set x \<subseteq> set b" apply(induct b) by auto lemma get_node_notbelong: "set oth \<inter> set (Node b1 b2 b3 b4) = {} \<Longrightarrow> get_node oth \<noteq> {} \<Longrightarrow> (Node b1 b2 b3 b4) \<notin> get_node oth" proof(induct oth arbitrary: b1 b2 b3 b4) case (Leaf x) then show ?case by auto next case (Node oth1 oth2 oth3 oth4) have oth1_node: "set oth1 \<inter> set (Node b1 b2 b3 b4) = {}" using Node.prems(1) by auto have oth2_node: "set oth2 \<inter> set (Node b1 b2 b3 b4) = {}" using Node.prems(1) by auto have oth3_node: "set oth3 \<inter> set (Node b1 b2 b3 b4) = {}" using Node.prems(1) by auto have oth4_node: "set oth4 \<inter> set (Node b1 b2 b3 b4) = {}" using Node.prems(1) by auto have oth_node: "(Node b1 b2 b3 b4) \<notin> {(Node oth1 oth2 oth3 oth4)}" using Node.prems(1) by (metis Int_absorb Node.hyps(1) UnCI all_not_in_conv get_node.elims insert_not_empty singletonD tree.set_intros(2) tree.simps(15)) have not_belong_oth1: "(Node b1 b2 b3 b4) \<notin> get_node oth1" proof(cases "get_node oth1 = {}") case True then show ?thesis by auto next case False then show ?thesis using Node.hyps(1) oth1_node by auto qed have not_belong_oth2: "(Node b1 b2 b3 b4) \<notin> get_node oth2" proof(cases "get_node oth2 = {}") case True then show ?thesis by auto next case False then show ?thesis using Node.hyps(2) oth2_node by auto qed have not_belong_oth3: "(Node b1 b2 b3 b4) \<notin> get_node oth3" proof(cases "get_node oth3 = {}") case True then show ?thesis by auto next case False then show ?thesis using Node.hyps(3) oth3_node by auto qed have not_belong_oth4: "(Node b1 b2 b3 b4) \<notin> get_node oth4" proof(cases "get_node oth4 = {}") case True then show ?thesis by auto next case False then show ?thesis using Node.hyps(4) oth4_node by auto qed have step: "get_node (Node oth1 oth2 oth3 oth4) = get_node oth1 \<union> get_node oth2 \<union> get_node oth3 \<union> get_node oth4 \<union> {(Node oth1 oth2 oth3 oth4)}" using get_node.simps(2) by auto have not_belong_step: "(Node b1 b2 b3 b4) \<notin> (get_node oth1 \<union> get_node oth2 \<union> get_node oth3 \<union> get_node oth4 \<union> {(Node oth1 oth2 oth3 oth4)})" using oth_node not_belong_oth1 not_belong_oth2 not_belong_oth3 not_belong_oth4 by auto show ?case using step not_belong_step by auto qed lemma get_node_overlap: "set oth \<inter> set B = {} \<Longrightarrow> get_node oth \<noteq> {} \<Longrightarrow> get_node B \<noteq> {} \<Longrightarrow> get_node oth \<inter> get_node B = {}" proof(induct B arbitrary: oth) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) have oth_b1: "set oth \<inter> set b1 = {}" using Node.prems(1) by auto have oth_b2: "set oth \<inter> set b2 = {}" using Node.prems(1) by auto have oth_b3: "set oth \<inter> set b3 = {}" using Node.prems(1) by auto have oth_b4: "set oth \<inter> set b4 = {}" using Node.prems(1) by auto have oth_node: "oth \<noteq> Node b1 b2 b3 b4" using Node.prems(1) by (metis Node.hyps(4) empty_iff equals0I get_node.simps(2) inf.idem insert_not_empty sup_eq_bot_iff tree.exhaust tree.set_intros(5) tree.simps(15)) have oth_b1_overlap: "get_node oth \<inter> get_node b1 = {}" proof(cases "get_node b1 = {}") case True then show ?thesis using Node.prems(2) by auto next case False then show ?thesis using Node.hyps(1) oth_b1 Node.prems(2) by auto qed have oth_b2_overlap: "get_node oth \<inter> get_node b2 = {}" proof(cases "get_node b2 = {}") case True then show ?thesis using Node.prems(2) by auto next case False then show ?thesis using Node.hyps(2) oth_b2 Node.prems(2) by auto qed have oth_b3_overlap: "get_node oth \<inter> get_node b3 = {}" proof(cases "get_node b3 = {}") case True then show ?thesis using Node.prems(2) by auto next case False then show ?thesis using Node.hyps(3) oth_b3 Node.prems(2) by auto qed have oth_b4_overlap: "get_node oth \<inter> get_node b4 = {}" proof(cases "get_node b4 = {}") case True then show ?thesis using Node.prems(2) by auto next case False then show ?thesis using Node.hyps(4) oth_b4 Node.prems(2) by auto qed have oth_node_overlap: "get_node oth \<inter> {Node b1 b2 b3 b4} = {}" using get_node_notbelong Node.prems(1,2) by auto have step: "get_node (Node b1 b2 b3 b4) = get_node b1 \<union> get_node b2 \<union> get_node b3 \<union> get_node b4 \<union> {(Node b1 b2 b3 b4)}" using get_node.simps(2) by auto have step_overlap: "get_node oth \<inter> (get_node b1 \<union> get_node b2 \<union> get_node b3 \<union> get_node b4 \<union> {(Node b1 b2 b3 b4)}) = {}" using oth_b1_overlap oth_b2_overlap oth_b3_overlap oth_b4_overlap oth_node_overlap by auto show ?case using step step_overlap by auto qed lemma get_node_card: "set b1 \<inter> set b2 = {} \<Longrightarrow> finite (get_node b1) \<Longrightarrow> finite (get_node b2) \<Longrightarrow> card (get_node b1 \<union> get_node b2) = card (get_node b1) + card (get_node b2)" proof- assume a0: "set b1 \<inter> set b2 = {}" and a1: "finite (get_node b1)" and a2: "finite (get_node b2)" {assume b0: "get_node b1 = {} \<and> get_node b2 = {}" then have ?thesis by auto } moreover {assume b1: "get_node b1 = {} \<and> get_node b2 \<noteq> {}" then have ?thesis by simp } moreover {assume b2: "get_node b1 \<noteq> {} \<and> get_node b2 = {}" then have ?thesis by simp } moreover {assume b3: "get_node b1 \<noteq> {} \<and> get_node b2 \<noteq> {}" have b1_b2_overlap: "get_node b1 \<inter> get_node b2 = {}" using get_node_overlap a0 b3 by auto have ?thesis using b3 a1 a2 b1_b2_overlap by (simp add: card_Un_disjoint) } ultimately have ?thesis by blast then show ?thesis by auto qed lemma is_quadtree: "diff_ids B \<Longrightarrow> quadtree B" proof(induct B) case (Leaf x) then show ?case unfolding quadtree_def by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have set_ab: "set b1 \<inter> set b2 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf1 disjoint_iff_not_equal tree.sel(1)) have set_ac: "set b1 \<inter> set b3 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf1 disjoint_iff_not_equal tree.sel(1)) have set_ad: "set b1 \<inter> set b4 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf1 disjoint_iff_not_equal tree.sel(1)) have set_bc: "set b2 \<inter> set b3 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf2 disjoint_iff_not_equal tree.sel(1)) have set_bd: "set b2 \<inter> set b4 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf2 disjoint_iff_not_equal tree.sel(1)) have set_cd: "set b3 \<inter> set b4 = {}" using diff_ab unfolding id_set_def by (metis Node.prems diff_leaf3 disjoint_iff_not_equal tree.sel(1)) have quad_b1': "quadtree b1" using Node.hyps(1) diff_b1 by auto have quad_b1: "card (set b1) = Suc (card (get_node b1) * 3)" using quad_b1' unfolding quadtree_def by auto have quad_b2': "quadtree b2" using Node.hyps(2) diff_b2 by auto have quad_b2: "card (set b2) = Suc (card (get_node b2) * 3)" using quad_b2' unfolding quadtree_def by auto have quad_b3': "quadtree b3" using Node.hyps(3) diff_b3 by auto have quad_b3: "card (set b3) = Suc (card (get_node b3) * 3)" using quad_b3' unfolding quadtree_def by auto have quad_b4': "quadtree b4" using Node.hyps(4) diff_b4 by auto have quad_b4: "card (set b4) = Suc (card (get_node b4) * 3)" using quad_b4' unfolding quadtree_def by auto have card_set_step: "card (set (Node b1 b2 b3 b4)) = card (set b1) + card (set b2) + card (set b3) + card (set b4)" using set_ab set_ac set_ad set_bc set_bd set_cd proof - have f1: "\<forall>P. (tree.set b1 \<union> P) \<inter> tree.set b3 = {} \<union> P \<inter> tree.set b3" by (simp add: Int_Un_distrib2 set_ac) have f2: "\<forall>P. (P \<union> tree.set b3) \<inter> tree.set b4 = P \<inter> tree.set b4" by (metis Int_Un_distrib2 set_cd sup_bot.right_neutral) have f3: "\<forall>P. (tree.set b1 \<union> P) \<inter> tree.set b4 = {} \<union> P \<inter> tree.set b4" by (metis Int_Un_distrib2 set_ad) have "((finite (tree.set b2) \<and> finite (tree.set b1)) \<and> finite (tree.set b4)) \<and> finite (tree.set b3)" by (metis (no_types) card.infinite nat.distinct(1) quad_b1 quad_b2 quad_b3 quad_b4) then show ?thesis using f3 f2 f1 by (simp add: card_Un_disjoint set_ab set_bc set_bd) qed have f_node_b1: "finite (get_node b1)" apply(induct b1) by auto have f_node_b2: "finite (get_node b2)" apply(induct b2) by auto have f_node_b3: "finite (get_node b3)" apply(induct b3) by auto have f_node_b4: "finite (get_node b4)" apply(induct b4) by auto have card_node_step: "get_node (Node b1 b2 b3 b4) = get_node b1 \<union> get_node b2 \<union> get_node b3 \<union> get_node b4 \<union> {(Node b1 b2 b3 b4)}" using get_node.simps(2) by auto have card_node': "card (get_node b1 \<union> get_node b2 \<union> get_node b3 \<union> get_node b4) = card (get_node b1) + card (get_node b2) + card (get_node b3) + card (get_node b4)" using get_node_card set_ab set_ac set_ad set_bc set_bd set_cd f_node_b1 f_node_b2 f_node_b3 f_node_b4 proof - have f1: "get_node b4 = {} \<or> get_node b3 = {} \<or> get_node b3 \<inter> get_node b4 = {}" by (meson get_node_overlap set_cd) have f2: "get_node b4 = {} \<or> get_node b1 = {} \<or> get_node b1 \<inter> get_node b4 = {}" using get_node_overlap set_ad by auto have f3: "get_node b3 = {} \<or> get_node b1 = {} \<or> get_node b1 \<inter> get_node b3 = {}" by (metis get_node_overlap set_ac) have f4: "({}::(block_state_type \<times> nat) tree set) \<union> {} = {}" by blast have f5: "\<And>T. get_node b4 = {} \<or> get_node b2 = {} \<or> (T \<union> get_node b2) \<inter> get_node b4 = T \<inter> get_node b4 \<union> {}" by (metis (no_types) Int_Un_distrib2 get_node_overlap set_bd) have f6: "\<And>T. get_node b3 = {} \<or> get_node b2 = {} \<or> (T \<union> get_node b2) \<inter> get_node b3 = T \<inter> get_node b3 \<union> {}" by (metis (no_types) Int_Un_distrib2 get_node_overlap set_bc) moreover { assume "get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {}" moreover { assume "get_node b2 \<noteq> {} \<and> get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {}" then have "get_node b1 \<noteq> {} \<and> get_node b2 \<noteq> {} \<and> get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {} \<or> get_node b1 \<inter> get_node b4 \<union> {} \<union> {} = {} \<and> get_node b1 \<inter> get_node b3 \<union> {} = {} \<and> get_node b2 \<noteq> {} \<and> get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {}" by force then have "get_node b1 \<inter> get_node b4 \<union> {} \<union> {} = {} \<and> get_node b1 \<inter> get_node b3 \<union> {} = {} \<and> get_node b2 \<noteq> {} \<and> get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {}" using f3 f2 by force then have "(get_node b1 \<union> get_node b2) \<inter> get_node b4 \<union> {} = {} \<and> (get_node b1 \<union> get_node b2) \<inter> get_node b3 = {} \<and> get_node b4 \<noteq> {} \<and> get_node b3 \<noteq> {}" using f6 f5 by presburger } ultimately have "(get_node b1 \<union> get_node b2 \<union> get_node b3) \<inter> get_node b4 = {} \<and> (get_node b1 \<union> get_node b2) \<inter> get_node b3 = {}" using f4 f3 f2 f1 by (metis (no_types) Int_Un_distrib2 inf_bot_left) } ultimately have "(get_node b1 \<union> get_node b2 \<union> get_node b3) \<inter> get_node b4 = {} \<and> (get_node b1 \<union> get_node b2) \<inter> get_node b3 = {}" using f5 f3 f2 by (metis (no_types) Int_Un_distrib2 inf_bot_left inf_bot_right) then show ?thesis by (simp add: card_Un_disjoint f_node_b1 f_node_b2 f_node_b3 f_node_b4 get_node_card set_ab) qed have node_notbelong_b1': "\<not> set (Node b1 b2 b3 b4) \<subseteq> set b1" using Node.prems diff_node2 by auto have node_notbelong_b1: "(Node b1 b2 b3 b4) \<notin> get_node b1" using node_notbelong_b1' get_node_set by blast have node_notbelong_b2': "\<not> set (Node b1 b2 b3 b4) \<subseteq> set b2" using Node.prems diff_node1 by auto have node_notbelong_b2: "(Node b1 b2 b3 b4) \<notin> get_node b2" using node_notbelong_b2' get_node_set by blast have node_notbelong_b3': "\<not> set (Node b1 b2 b3 b4) \<subseteq> set b3" using Node.prems diff_node1 by auto have node_notbelong_b3: "(Node b1 b2 b3 b4) \<notin> get_node b3" using node_notbelong_b3' get_node_set by blast have node_notbelong_b4': "\<not> set (Node b1 b2 b3 b4) \<subseteq> set b4" using Node.prems diff_node1 by auto have node_notbelong_b4: "(Node b1 b2 b3 b4) \<notin> get_node b4" using node_notbelong_b4' get_node_set by blast have card_node: "card (get_node (Node b1 b2 b3 b4)) = card (get_node b1) + card (get_node b2) + card (get_node b3) + card (get_node b4) + 1" using card_node_step card_node' node_notbelong_b1 node_notbelong_b2 node_notbelong_b3 node_notbelong_b4 by (simp add: f_node_b1 f_node_b2 f_node_b3 f_node_b4) have card_set_node: "card (set (Node b1 b2 b3 b4)) = Suc (card (get_node (Node b1 b2 b3 b4)) * 3)" using card_set_step quad_b1 quad_b2 quad_b3 quad_b4 card_node by linarith then show ?case unfolding quadtree_def by auto qed subsection \<open>def and proof of inv_exact_block and inv_exact_level\<close> type_synonym blocksize = nat definition mapping_size_level :: "blocksize list \<Rightarrow> nat \<Rightarrow> nat" where "mapping_size_level bli rsize \<equiv> THE l. l < length bli \<and> rsize \<le> bli!l \<and> ((length bli > 1 \<and> l < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc l))" lemma le_and_eq: "length (bli:: blocksize list) > 1 \<Longrightarrow> \<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n \<Longrightarrow> x1 < length bli \<Longrightarrow> x2 < length bli \<Longrightarrow> x1 \<le> x2 \<Longrightarrow> bli!x1 \<ge> bli!x2" proof- assume a0: "length (bli:: blocksize list) > 1" and a1: "\<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n" and a2: "x1 < length bli" and a3: "x2 < length bli" and a4: "x1 \<le> x2" {assume "x1 < x2" then have "bli!x1 > bli!x2" using a0 a1 a2 a3 by auto }moreover {assume "x1 = x2" then have "bli!x1 = bli!x2" by auto } ultimately have ?thesis using a4 by linarith then show ?thesis by auto qed lemma middle_rsize: "length (bli:: blocksize list) > 1 \<Longrightarrow> \<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n \<Longrightarrow> rsize \<le> bli!0 \<Longrightarrow> rsize > bli!(length bli - 1) \<Longrightarrow> \<exists>!l. l \<ge> 0 \<and> l < length bli - 1 \<and> rsize \<le> bli!l \<and> rsize > bli!(Suc l)" proof(induct "length bli - 1" arbitrary: bli) case 0 then show ?case by auto next case (Suc xa) have suc_xa_gr_1: "Suc xa \<ge> 1" by simp {assume suc_xa_eq_1: "Suc xa = 1" have len_eq_2: "length bli = 2" using suc_xa_eq_1 Suc(2) by auto have n_eq_0: "rsize \<le> bli!0 \<and> rsize > bli!(Suc 0)" using Suc.hyps(2) Suc.prems(3) Suc.prems(4) suc_xa_eq_1 by auto then have ?case using Suc.hyps(2) suc_xa_eq_1 by auto } moreover {assume suc_xa_gr_1: "Suc xa > 1" have xa_val: "xa = length (butlast bli) - 1" using Suc(2) nth_butlast by auto have butlast_gr_1: "length (butlast bli) > 1" using suc_xa_gr_1 xa_val by auto have bli_imp: "\<forall>m<length (butlast bli). \<forall>n<length (butlast bli). m < n \<longrightarrow> (butlast bli) ! m > (butlast bli) ! n" using Suc(4) by (simp add: nth_butlast) have rsize_le_butlast: "rsize \<le> (butlast bli) ! 0" using Suc(5) by (metis Suc.hyps(2) length_butlast nth_butlast zero_less_Suc) {assume rsize_case0: "rsize > (butlast bli)!(length (butlast bli) - 1)" have step_case0: "\<exists>!l. l \<ge> 0 \<and> l < (length (butlast bli)) - 1 \<and> rsize \<le> (butlast bli)!l \<and> rsize > (butlast bli)!(Suc l)" using Suc(1) xa_val butlast_gr_1 bli_imp rsize_le_butlast rsize_case0 by presburger have last_case0: "(butlast bli)!(length (butlast bli) - 1) > bli!(length bli - 1)" by (metis (no_types, hide_lams) Suc.hyps(2) Suc.prems(2) diff_le_self length_butlast less_le less_trans n_not_Suc_n nth_butlast xa_val) have "\<exists>!l. 0 \<le> l \<and> l < length bli - 1 \<and> rsize \<le> bli ! l \<and> rsize > bli ! Suc l" using step_case0 last_case0 rsize_case0 by (metis (no_types, lifting) Suc.hyps(2) Suc_mono length_butlast less_Suc_eq not_less nth_butlast xa_val) }moreover {assume rsize_case1: "rsize \<le> (butlast bli)!(length (butlast bli) - 1)" have "rsize \<le> bli!((length bli - 1) - 1) \<and> rsize > bli!(length bli - 1)" using rsize_case1 Suc(6) by (metis Suc.hyps(2) diff_Suc_1 length_butlast lessI nth_butlast) then have "\<exists>!l. 0 \<le> l \<and> l < length bli - 1 \<and> rsize \<le> bli ! l \<and> rsize > bli ! Suc l" using Suc(2,4) Suc.prems(1) nth_butlast butlast_gr_1 calculation by (smt One_nat_def Suc_lessD diff_Suc_1 diff_less_Suc length_butlast lessI less_SucE less_imp_le_nat less_trans_Suc) } ultimately have ?case by linarith } ultimately have ?case by linarith then show ?case by auto qed lemma the_level: "length (bli:: blocksize list) > 0 \<Longrightarrow> \<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n \<Longrightarrow> rsize \<le> bli!0 \<Longrightarrow> \<exists>!l. l < length bli \<and> rsize \<le> bli!l \<and> ((length bli > 1 \<and> l < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc l))" proof(cases "length (bli:: blocksize list) > 1") case True assume a0: "length (bli:: blocksize list) > 0" and a1: "\<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n" and a2: "rsize \<le> bli!0" {assume b0: "rsize \<le> bli!(length bli - 1)" have b1: "length bli - 1 < length bli" using a0 by auto moreover have "rsize \<le> bli!(length bli - 1)" using b0 by auto moreover have "((length bli > 1 \<and> (length bli - 1) < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc (length bli - 1)))" by auto ultimately have exist_l: "\<exists>l. l < length bli \<and> rsize \<le> bli!l \<and> ((length bli > 1 \<and> l < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc l))" by auto then obtain l where obtain_l: "l < length bli \<and> rsize \<le> bli!l \<and> ((length bli > 1 \<and> l < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc l))" by auto {assume "l \<ge> length bli" then have ?thesis using obtain_l by auto } then have s0: "\<not> l \<ge> length bli" using obtain_l by linarith moreover {assume b2: "l < length bli - 1" then have b3: "rsize > bli!(Suc l)" using True obtain_l by auto have "Suc l \<le> length bli - 1" using b2 by auto then have "bli!(Suc l) \<ge> bli!(length bli - 1)" using le_and_eq True a1 b1 b2 obtain_l by (metis Suc_lessI le_antisym less_or_eq_imp_le) then have "bli!(Suc l) \<ge> rsize" using b0 by auto then have ?thesis using b3 by auto } then have s1: "\<not> l < length bli - 1" using b1 b0 obtain_l by blast ultimately have "l = length bli - 1" using obtain_l by linarith then have ?thesis using obtain_l True a0 a1 by (smt Suc_diff_1 Suc_leI less_SucE less_imp_le_nat less_trans_Suc not_less_eq_eq) } moreover {assume c0: "rsize > bli!(length bli - 1)" have c1: "\<exists>!l. l \<ge> 0 \<and> l < length bli - 1 \<and> rsize \<le> bli!l \<and> rsize > bli!(Suc l)" using middle_rsize True a1 a2 c0 by auto obtain l where middle_l: "l \<ge> 0 \<and> l < length bli - 1 \<and> rsize \<le> bli!l \<and> rsize > bli!(Suc l)" using c1 by auto then have "l < length bli \<and> rsize \<le> bli!l \<and> ((length bli > 1 \<and> l < (length bli - 1)) \<longrightarrow> rsize > bli!(Suc l))" by auto then have ?thesis by (metis (no_types, lifting) Suc_diff_1 True a0 c1 calculation le0 less_SucE) } ultimately have ?thesis by linarith then show ?thesis by auto next case False assume d0: "length bli > 0" and d1: "rsize \<le> bli!0" have "length bli = 1" using d0 False by linarith then show ?thesis using d0 d1 hd_conv_nth by force qed lemma exact_level1: "length (bli:: blocksize list) > 0 \<Longrightarrow> \<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n \<Longrightarrow> rsize \<le> bli!(length bli - 1) \<Longrightarrow> mapping_size_level bli rsize = length bli - 1" proof- assume a0: "length (bli:: blocksize list) > 0" and a1: "\<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n" and a2: "rsize \<le> bli!(length bli - 1)" then have "bli!0 \<ge> bli!(length bli - 1)" by (metis One_nat_def Suc_lessI diff_less diff_self_eq_0 less_numeral_extra(1) less_or_eq_imp_le zero_less_diff) then have a3: "rsize \<le> bli!0" using a2 by auto have exist_l: "\<exists>!l. l < length bli \<and> rsize \<le> bli ! l \<and> (1 < length bli \<and> l < length bli - 1 \<longrightarrow> rsize > bli ! Suc l)" using the_level a0 a1 a3 by auto obtain l where obtain_l: "l < length bli \<and> rsize \<le> bli ! l \<and> (1 < length bli \<and> l < length bli - 1 \<longrightarrow> rsize > bli ! Suc l)" using exist_l by auto {assume len_gr_1: "length (bli:: blocksize list) > 1" {assume "l \<ge> length bli" then have ?thesis unfolding mapping_size_level_def using obtain_l by auto } then have s0: "\<not> l \<ge> length bli" using obtain_l by linarith moreover {assume l_le_len_sub: "l < length bli - 1" then have rsize_gr_suc: "rsize > bli!(Suc l)" using obtain_l len_gr_1 by auto have "Suc l \<le> length bli - 1" using l_le_len_sub by auto then have "bli!(Suc l) \<ge> bli!(length bli - 1)" using le_and_eq len_gr_1 a0 a1 a2 obtain_l exist_l by (metis diff_less less_numeral_extra(1) l_le_len_sub nat_neq_iff) then have "rsize \<le> bli!(Suc l)" using a2 by auto then have ?thesis using rsize_gr_suc by auto } then have s1: "\<not> l < length bli - 1" using a0 a2 obtain_l exist_l by (metis diff_less less_irrefl zero_less_one) ultimately have "l = length bli - 1" using obtain_l by linarith then have ?thesis unfolding mapping_size_level_def using obtain_l exist_l by (metis (no_types, lifting) the_equality) } moreover {assume "\<not> (length (bli:: blocksize list) > 1)" then have "length bli = 1" using a0 by linarith then have ?thesis unfolding mapping_size_level_def using obtain_l a3 by force } ultimately have ?thesis by linarith then show ?thesis by auto qed lemma exact_level2: "length (bli:: blocksize list) > 1 \<Longrightarrow> \<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n \<Longrightarrow> l < length bli - 1 \<Longrightarrow> rsize \<le> bli!l \<Longrightarrow> rsize > bli!(Suc l) \<Longrightarrow> mapping_size_level bli rsize = l" proof- assume a0: "length (bli:: blocksize list) > 1" and a1: "\<forall>m < length bli. \<forall>n < length bli. m < n \<longrightarrow> bli!m > bli!n" and a2: "l < length bli - 1 " and a3: "rsize \<le> bli!l" and a4: "rsize > bli!(Suc l)" have "l \<ge> 0" using a0 a2 by auto then have "bli!l \<le> bli!0" using le_and_eq a0 a1 a2 by (metis (no_types, hide_lams) less_imp_diff_less neq0_conv not_less not_less_eq order.asym) then have rsize_le_fst: "rsize \<le> bli!0" using a3 by auto have rsize_gr_last: "rsize > bli!(length bli - 1)" using a2 a4 by (smt Suc_lessD Suc_lessI a0 a1 diff_less less_numeral_extra(1) less_trans_Suc) have exist_n: "\<exists>!l. l \<ge> 0 \<and> l < length bli - 1 \<and> rsize \<le> bli!l \<and> rsize > bli!(Suc l)" using middle_rsize a0 a1 rsize_le_fst rsize_gr_last by auto then have ?thesis unfolding mapping_size_level_def using a0 a2 a3 a4 proof - have f1: "\<And>n. \<not> length bli - 1 < n \<or> length bli \<le> n" by (metis (no_types) One_nat_def Suc_diff_1 Suc_leI a0 less_trans zero_less_Suc) have "\<forall>p n. \<exists>na. \<forall>nb. \<not> (nb::nat) < nb \<and> (na::nat) \<noteq> n \<and> (\<not> p n \<or> p na \<or> The p = n)" by (metis (full_types) less_not_refl n_not_Suc_n theI_unique) then obtain nn :: "(nat \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> nat" where f2: "\<And>n p na. \<not> (n::nat) < n \<and> nn p na \<noteq> na \<and> (\<not> p na \<or> p (nn p na) \<or> The p = na)" by moura have f3: "\<not> rsize \<le> bli ! (length bli - 1)" using rsize_gr_last by linarith have "l < length bli" using a2 by linarith then show "(THE l. l < length bli \<and> rsize \<le> bli ! l \<and> (1 < length bli \<and> l < length bli - 1 \<longrightarrow> rsize > bli ! Suc l)) = l" using f3 f2 f1 by (metis (lifting) a0 a3 a4 exist_n le0 nat_neq_iff not_less) qed then show ?thesis by auto qed subsection \<open>def and proof of pre-post conditions\<close> definition freesets_pool :: "Block set \<Rightarrow> Block set" where "freesets_pool bset= {l. \<exists>b \<in> bset. l \<in> freesets b}" definition allocsets :: "Block \<Rightarrow> Block set" where "allocsets b = {l. leaf l \<and> L l \<in> set b \<and> fst (L l) = ALLOC}" definition allocsets_pool :: "Block set \<Rightarrow> Block set" where "allocsets_pool bset= {l. \<exists>b \<in> bset. l \<in> allocsets b}" lemma freesets_node: "freesets (Node b1 b2 b3 b4) = freesets b1 \<union> freesets b2 \<union> freesets b3 \<union> freesets b4" unfolding freesets_def by auto lemma allocsets_node: "allocsets (Node b1 b2 b3 b4) = allocsets b1 \<union> allocsets b2 \<union> allocsets b3 \<union> allocsets b4" unfolding allocsets_def by auto lemma alloc_fail_branch: "\<not> (exists_freelevel bset lv) \<Longrightarrow> fst (alloc bset lv ids) = bset" unfolding alloc_def Let_def by auto lemma notbelong_freesets_after_replace: "diff_ids B \<Longrightarrow> leaf b \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b ALLOC \<Longrightarrow> b \<notin> freesets (replace B b b')" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(4) by fastforce have leaf_b': "b' = Leaf (ALLOC, snd x)" using Leaf.prems(5) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B: "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have empty_freesets: "freesets (Leaf (ALLOC, snd x)) = {}" unfolding freesets_def by auto then show ?case using leaf_B by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have not_free_b1: "b \<notin> freesets (replace b1 b b')" using Node.hyps(1) diff_b1 Node.prems(2) Node.prems(3) a0 Node.prems(5) by auto have not_free_b2: "b \<notin> freesets b2" using no_belong_b2 unfolding freesets_def by auto have not_free_b3: "b \<notin> freesets b3" using no_belong_b3 unfolding freesets_def by auto have not_free_b4: "b \<notin> freesets b4" using no_belong_b4 unfolding freesets_def by auto have not_free_node: "b \<notin> freesets (Node (replace b1 b b') b2 b3 b4)" using not_free_b1 not_free_b2 not_free_b3 not_free_b4 unfolding freesets_def by auto have ?case using replace_re not_free_node by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have not_free_b2: "b \<notin> freesets (replace b2 b b')" using Node.hyps(2) diff_b2 Node.prems(2) Node.prems(3) a1 Node.prems(5) by auto have not_free_b1: "b \<notin> freesets b1" using no_belong_b1 unfolding freesets_def by auto have not_free_b3: "b \<notin> freesets b3" using no_belong_b3 unfolding freesets_def by auto have not_free_b4: "b \<notin> freesets b4" using no_belong_b4 unfolding freesets_def by auto have not_free_node: "b \<notin> freesets (Node b1 (replace b2 b b') b3 b4)" using not_free_b1 not_free_b2 not_free_b3 not_free_b4 unfolding freesets_def by auto have ?case using replace_re not_free_node by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have not_free_b3: "b \<notin> freesets (replace b3 b b')" using Node.hyps(3) diff_b3 Node.prems(2) Node.prems(3) a2 Node.prems(5) by auto have not_free_b1: "b \<notin> freesets b1" using no_belong_b1 unfolding freesets_def by auto have not_free_b2: "b \<notin> freesets b2" using no_belong_b2 unfolding freesets_def by auto have not_free_b4: "b \<notin> freesets b4" using no_belong_b4 unfolding freesets_def by auto have not_free_node: "b \<notin> freesets (Node b1 b2 (replace b3 b b') b4)" using not_free_b1 not_free_b2 not_free_b3 not_free_b4 unfolding freesets_def by auto have ?case using replace_re not_free_node by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) by auto have not_free_b4: "b \<notin> freesets (replace b4 b b')" using Node.hyps(4) diff_b4 Node.prems(2) Node.prems(3) a3 Node.prems(5) by auto have not_free_b1: "b \<notin> freesets b1" using no_belong_b1 unfolding freesets_def by auto have not_free_b2: "b \<notin> freesets b2" using no_belong_b2 unfolding freesets_def by auto have not_free_b3: "b \<notin> freesets b3" using no_belong_b3 unfolding freesets_def by auto have not_free_node: "b \<notin> freesets (Node b1 b2 b3 (replace b4 b b'))" using not_free_b1 not_free_b2 not_free_b3 not_free_b4 unfolding freesets_def by auto have ?case using replace_re not_free_node by auto } ultimately have ?case using Node.prems(4) by fastforce then show ?case by auto qed lemma alloc_direct_sub_freesets: "diff_ids B \<Longrightarrow> leaf b \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b ALLOC \<Longrightarrow> freesets B = freesets (replace B b b') \<union> {b}" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(4) by fastforce have value_b: "b = Leaf x" using Leaf.prems(2) leaf_b by auto have one_freesets: "freesets (Leaf x) = {Leaf x}" unfolding freesets_def using Leaf.prems(2,3) value_b by auto have leaf_b': "b' = Leaf (ALLOC, snd x)" using Leaf.prems(5) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B: "replace (Leaf x) b b' = Leaf (ALLOC, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have empty_freesets: "freesets (Leaf (ALLOC, snd x)) = {}" unfolding freesets_def by auto show ?case using one_freesets leaf_B empty_freesets value_b by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b1: "freesets b1 = freesets (replace b1 b b') \<union> {b}" using Node.hyps(1) diff_b1 Node.prems(2) Node.prems(3) a0 Node.prems(5) by auto have ?case using replace_re sub_b1 freesets_node by simp } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b2: "freesets b2 = freesets (replace b2 b b') \<union> {b}" using Node.hyps(2) diff_b2 Node.prems(2) Node.prems(3) a1 Node.prems(5) by auto have ?case using replace_re sub_b2 freesets_node by simp } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b3: "freesets b3 = freesets (replace b3 b b') \<union> {b}" using Node.hyps(3) diff_b3 Node.prems(2) Node.prems(3) a2 Node.prems(5) by auto have ?case using replace_re sub_b3 freesets_node by simp } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) by auto have sub_b4: "freesets b4 = freesets (replace b4 b b') \<union> {b}" using Node.hyps(4) diff_b4 Node.prems(2) Node.prems(3) a3 Node.prems(5) by auto have ?case using replace_re sub_b4 freesets_node by simp } ultimately have ?case using Node.prems(4) by fastforce then show ?case by auto qed lemma alloc_direct_branch_freesets: "diff_ids_valid bset \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax = lv \<Longrightarrow> (newbset, newids, re, reid) = alloc1 bset lv ids \<Longrightarrow> \<exists>l. l \<in> freesets_pool bset \<and> l \<notin> freesets_pool newbset \<and> freesets_pool bset = freesets_pool newbset \<union> {l}" proof- assume a0: "diff_ids_valid bset" and a1: "exists_freelevel bset lv" and a2: "lmax = freesets_maxlevel bset lv" and a3: "lmax = lv" and a4: "(newbset, newids, re, reid) = alloc1 bset lv ids" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a1 by auto have eq_lv: "lv = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a2 a3 unfolding freesets_maxlevel_def by auto have the_lv: "lv \<le> lv \<and> freesets_level_pool bset lv \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lv)" using the_P[OF exi_lmax eq_lv] by auto (*------------------------------------------------------------------------------------------------*) have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" using the_lv unfolding freesets_level_pool_def by auto let ?blo = "SOME b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" have the_blo: "?blo \<in> bset \<and> freesets_level ?blo lv \<noteq> {}" using someI_ex[OF exi_b] by auto have diff_blo: "diff_ids ?blo" using diff_bset1 exi_b by (metis (mono_tags, lifting) some_eq_ex) have exi_l: "\<exists>l. l \<in> freesets_level ?blo lv" using someI_ex[OF exi_b] by auto let ?l = "SOME l. l \<in> freesets_level ?blo lv" have the_l: "?l \<in> freesets_level ?blo lv" using someI_ex[OF exi_l] by auto have leaf_freesets: "?l \<in> freesets ?blo" using the_l unfolding freesets_level_def by auto have leaf_l: "leaf ?l" using leaf_freesets unfolding freesets_def by simp have leaf_free: "fst (L ?l) = FREE" using leaf_freesets unfolding freesets_def by simp have leaf_belong: "L ?l \<in> set ?blo" using leaf_freesets unfolding freesets_def by simp have leaf_notbelong: "\<forall>b. b \<in> bset \<and> b \<noteq> ?blo \<longrightarrow> L ?l \<notin> set b" using diff_bset2 leaf_belong unfolding id_set_def by (metis (no_types, lifting) IntI emptyE image_eqI the_blo tree.set_map) have leaf_freesets_pool: "?l \<in> freesets_pool bset" using the_l the_blo unfolding freesets_level_def freesets_pool_def by auto have not_leaf_freesets_pool: "?l \<notin> freesets_pool (bset - {?blo})" using leaf_notbelong unfolding freesets_pool_def freesets_def by blast (*------------------------------------------------------------------------------------------------*) let ?newb = "replace ?blo ?l (set_state_type ?l ALLOC)" have not_free_newblo: "?l \<notin> freesets ?newb" using notbelong_freesets_after_replace diff_blo leaf_l leaf_free leaf_belong by simp have change_freesets: "freesets ?blo = freesets ?newb \<union> {?l}" using alloc_direct_sub_freesets diff_blo leaf_l leaf_free leaf_belong by simp (*------------------------------------------------------------------------------------------------*) have alloc1_re: "(newbset, newids, re, reid) = (((bset - {?blo}) \<union> {?newb}), ids, True, {snd (L ?l)})" using a4 unfolding alloc1_def by metis have leaf_not_freesets_pool: "?l \<notin> freesets_pool newbset" using alloc1_re not_leaf_freesets_pool not_free_newblo unfolding freesets_pool_def by blast have step1: "freesets_pool bset = freesets_pool (bset - {?blo}) \<union> freesets ?blo" unfolding freesets_pool_def using the_blo by auto have step2: "freesets_pool newbset = freesets_pool (bset - {?blo}) \<union> freesets ?newb" unfolding freesets_pool_def using alloc1_re by auto have change_freesets_pool: "freesets_pool bset = freesets_pool newbset \<union> {?l}" using step1 step2 change_freesets by auto show ?thesis using leaf_freesets_pool leaf_not_freesets_pool change_freesets_pool by auto qed lemma notbelong_allocsets_before_replace: "diff_ids B \<Longrightarrow> leaf b \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b ALLOC \<Longrightarrow> b' \<notin> allocsets B" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(4) by fastforce have free_b: "fst x = FREE" using Leaf.prems(3) leaf_b by auto have empty_allocsets: "allocsets (Leaf x) = {}" unfolding allocsets_def using free_b by auto have leaf_b': "b' = Leaf (ALLOC, snd x)" using Leaf.prems(5) leaf_b unfolding set_state_type_def Let_def by auto show ?case using empty_allocsets by auto next case (Node b1 b2 b3 b4) have same_id: "snd (L b') = snd (L b)" using Node.prems(5) unfolding set_state_type_def Let_def by auto have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have not_allocsets_b1: "b' \<notin> allocsets b1" using Node.hyps(1) diff_b1 Node.prems(2) Node.prems(3) a0 Node.prems(5) by auto have not_set_b2: "L b' \<notin> set b2" using a0 diff_ab same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b2: "b' \<notin> allocsets b2" using not_set_b2 unfolding allocsets_def by auto have not_set_b3: "L b' \<notin> set b3" using a0 diff_ac same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b3: "b' \<notin> allocsets b3" using not_set_b3 unfolding allocsets_def by auto have not_set_b4: "L b' \<notin> set b4" using a0 diff_ad same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b4: "b' \<notin> allocsets b4" using not_set_b4 unfolding allocsets_def by auto have not_free_node: "b' \<notin> allocsets (Node b1 b2 b3 b4)" using not_allocsets_b1 not_allocsets_b2 not_allocsets_b3 not_allocsets_b4 unfolding allocsets_def using allocsets_node by auto have ?case using not_free_node by auto } moreover {assume a1: "L b \<in> set b2" have not_allocsets_b2: "b' \<notin> allocsets b2" using Node.hyps(2) diff_b2 Node.prems(2) Node.prems(3) a1 Node.prems(5) by auto have not_set_b1: "L b' \<notin> set b1" using a1 diff_ab same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b1: "b' \<notin> allocsets b1" using not_set_b1 unfolding allocsets_def by auto have not_set_b3: "L b' \<notin> set b3" using a1 diff_bc same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b3: "b' \<notin> allocsets b3" using not_set_b3 unfolding allocsets_def by auto have not_set_b4: "L b' \<notin> set b4" using a1 diff_bd same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b4: "b' \<notin> allocsets b4" using not_set_b4 unfolding allocsets_def by auto have not_free_node: "b' \<notin> allocsets (Node b1 b2 b3 b4)" using not_allocsets_b1 not_allocsets_b2 not_allocsets_b3 not_allocsets_b4 unfolding allocsets_def using allocsets_node by auto have ?case using not_free_node by auto } moreover {assume a2: "L b \<in> set b3" have not_allocsets_b3: "b' \<notin> allocsets b3" using Node.hyps(3) diff_b3 Node.prems(2) Node.prems(3) a2 Node.prems(5) by auto have not_set_b1: "L b' \<notin> set b1" using a2 diff_ac same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b1: "b' \<notin> allocsets b1" using not_set_b1 unfolding allocsets_def by auto have not_set_b2: "L b' \<notin> set b2" using a2 diff_bc same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b2: "b' \<notin> allocsets b2" using not_set_b2 unfolding allocsets_def by auto have not_set_b4: "L b' \<notin> set b4" using a2 diff_cd same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b4: "b' \<notin> allocsets b4" using not_set_b4 unfolding allocsets_def by auto have not_free_node: "b' \<notin> allocsets (Node b1 b2 b3 b4)" using not_allocsets_b1 not_allocsets_b2 not_allocsets_b3 not_allocsets_b4 unfolding allocsets_def using allocsets_node by auto have ?case using not_free_node by auto } moreover {assume a3: "L b \<in> set b4" have not_allocsets_b4: "b' \<notin> allocsets b4" using Node.hyps(4) diff_b4 Node.prems(2) Node.prems(3) a3 Node.prems(5) by auto have not_set_b1: "L b' \<notin> set b1" using a3 diff_ad same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b1: "b' \<notin> allocsets b1" using not_set_b1 unfolding allocsets_def by auto have not_set_b2: "L b' \<notin> set b2" using a3 diff_bd same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b2: "b' \<notin> allocsets b2" using not_set_b2 unfolding allocsets_def by auto have not_set_b3: "L b' \<notin> set b3" using a3 diff_cd same_id unfolding id_set_def by (metis IntI emptyE image_eqI tree.set_map) have not_allocsets_b3: "b' \<notin> allocsets b3" using not_set_b3 unfolding allocsets_def by auto have not_free_node: "b' \<notin> allocsets (Node b1 b2 b3 b4)" using not_allocsets_b1 not_allocsets_b2 not_allocsets_b3 not_allocsets_b4 unfolding allocsets_def using allocsets_node by auto have ?case using not_free_node by auto } ultimately have ?case using Node.prems(4) by fastforce then show ?case by auto qed lemma alloc_direct_sub_allocsets: "diff_ids B \<Longrightarrow> leaf b \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b ALLOC \<Longrightarrow> allocsets (replace B b b') = allocsets B \<union> {b'}" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(4) by fastforce have free_b: "fst x = FREE" using Leaf.prems(3) leaf_b by auto have empty_allocsets: "allocsets (Leaf x) = {}" unfolding allocsets_def using free_b by auto have leaf_b': "b' = Leaf (ALLOC, snd x)" using Leaf.prems(5) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B: "replace (Leaf x) b b' = b'" using leaf_b leaf_b' unfolding replace_def by auto have b1: "leaf b'" using leaf_b' by simp have b2: "L b' \<in> tree.set b'" using leaf_b' by auto have b3: "fst (L b') = ALLOC" using leaf_b' by simp have one_allocsets: "allocsets b' = {b'}" unfolding allocsets_def using b1 b2 b3 apply auto by (metis singletonD tree.collapse(1) tree.simps(15)) show ?case using leaf_B one_allocsets empty_allocsets by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b1: "allocsets (replace b1 b b') = allocsets b1 \<union> {b'}" using Node.hyps(1) diff_b1 Node.prems(2) Node.prems(3) a0 Node.prems(5) by auto have ?case using replace_re sub_b1 allocsets_node by simp } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b2: "allocsets (replace b2 b b') = allocsets b2 \<union> {b'}" using Node.hyps(2) diff_b2 Node.prems(2) Node.prems(3) a1 Node.prems(5) by auto have ?case using replace_re sub_b2 allocsets_node by simp } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b3: "allocsets (replace b3 b b') = allocsets b3 \<union> {b'}" using Node.hyps(3) diff_b3 Node.prems(2) Node.prems(3) a2 Node.prems(5) by auto have ?case using replace_re sub_b3 allocsets_node by simp } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) by auto have sub_b4: "allocsets (replace b4 b b') = allocsets b4 \<union> {b'}" using Node.hyps(4) diff_b4 Node.prems(2) Node.prems(3) a3 Node.prems(5) by auto have ?case using replace_re sub_b4 allocsets_node by simp } ultimately have ?case using Node.prems(4) by fastforce then show ?case by auto qed lemma alloc_direct_branch_allocsets: "diff_ids_valid bset \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax = lv \<Longrightarrow> (newbset, newids, re, reid) = alloc1 bset lv ids \<Longrightarrow> \<exists>l. l \<notin> allocsets_pool bset \<and> l \<in> allocsets_pool newbset \<and> allocsets_pool newbset = allocsets_pool bset \<union> {l}" proof- assume a0: "diff_ids_valid bset" and a1: "exists_freelevel bset lv" and a2: "lmax = freesets_maxlevel bset lv" and a3: "lmax = lv" and a4: "(newbset, newids, re, reid) = alloc1 bset lv ids" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a1 by auto have eq_lv: "lv = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a2 a3 unfolding freesets_maxlevel_def by auto have the_lv: "lv \<le> lv \<and> freesets_level_pool bset lv \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lv)" using the_P[OF exi_lmax eq_lv] by auto (*------------------------------------------------------------------------------------------------*) have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" using the_lv unfolding freesets_level_pool_def by auto let ?blo = "SOME b. b \<in> bset \<and> freesets_level b lv \<noteq> {}" have the_blo: "?blo \<in> bset \<and> freesets_level ?blo lv \<noteq> {}" using someI_ex[OF exi_b] by auto have diff_blo: "diff_ids ?blo" using diff_bset1 exi_b by (metis (mono_tags, lifting) some_eq_ex) have exi_l: "\<exists>l. l \<in> freesets_level ?blo lv" using someI_ex[OF exi_b] by auto let ?l = "SOME l. l \<in> freesets_level ?blo lv" have the_l: "?l \<in> freesets_level ?blo lv" using someI_ex[OF exi_l] by auto have leaf_freesets: "?l \<in> freesets ?blo" using the_l unfolding freesets_level_def by auto have leaf_l: "leaf ?l" using leaf_freesets unfolding freesets_def by simp have leaf_free: "fst (L ?l) = FREE" using leaf_freesets unfolding freesets_def by simp have leaf_belong: "L ?l \<in> set ?blo" using leaf_freesets unfolding freesets_def by simp (*------------------------------------------------------------------------------------------------*) let ?l' = "set_state_type ?l ALLOC" have leaf_notbelong: "?l' \<notin> allocsets ?blo" using notbelong_allocsets_before_replace diff_blo leaf_l leaf_free leaf_belong by simp have same_id: "snd (L ?l') = snd (L ?l)" unfolding set_state_type_def Let_def by auto have leaf_notbelong_ids': "\<forall>b. b \<in> bset \<and> b \<noteq> ?blo \<longrightarrow> snd (L ?l) \<notin> id_set b" using diff_bset2 leaf_belong unfolding id_set_def by (metis (no_types, lifting) IntI emptyE image_eqI the_blo tree.set_map) have leaf_notbelong_ids: "\<forall>b. b \<in> bset \<and> b \<noteq> ?blo \<longrightarrow> snd (L ?l') \<notin> id_set b" using leaf_notbelong_ids' same_id by auto have leaf_notbelong_set: "\<forall>b. b \<in> bset \<and> b \<noteq> ?blo \<longrightarrow> L ?l' \<notin> set b" using leaf_notbelong_ids unfolding id_set_def using tree.set_map by fastforce have leat_notbelong_allocsets: "?l' \<notin> allocsets_pool bset" using leaf_notbelong leaf_notbelong_set unfolding allocsets_pool_def allocsets_def by blast let ?newb = "replace ?blo ?l ?l'" have change_allocsets: "allocsets ?newb = allocsets ?blo \<union> {?l'}" using alloc_direct_sub_allocsets diff_blo leaf_l leaf_free leaf_belong by simp have leaf_allocsets: "?l' \<in> allocsets ?newb" using change_allocsets by auto (*------------------------------------------------------------------------------------------------*) have alloc1_re: "(newbset, newids, re, reid) = (((bset - {?blo}) \<union> {?newb}), ids, True, {snd (L ?l)})" using a4 unfolding alloc1_def by metis have leaf_allocsets_pool: "?l' \<in> allocsets_pool newbset" using alloc1_re leaf_allocsets unfolding allocsets_pool_def by blast have step1: "allocsets_pool bset = allocsets_pool (bset - {?blo}) \<union> allocsets ?blo" unfolding allocsets_pool_def using the_blo by auto have step2: "allocsets_pool newbset = allocsets_pool (bset - {?blo}) \<union> allocsets ?newb" unfolding allocsets_pool_def using alloc1_re by auto have change_allocsets_pool: "allocsets_pool newbset = allocsets_pool bset \<union> {?l'}" using step1 step2 change_allocsets by auto show ?thesis using leat_notbelong_allocsets leaf_allocsets_pool change_allocsets_pool by auto qed lemma allocated_leaf_after_split: "lmax < lv \<Longrightarrow> finite ids \<Longrightarrow> snd (L b) \<in> ids \<Longrightarrow> \<exists>!l. leaf l \<and> allocsets (fst (split b ids (lv - lmax))) = {l}" proof(induct "lv - lmax" arbitrary: lmax b ids) case 0 then show ?case by auto next case (Suc xa) obtain ll lr rl rr where pdivide: "fst (divide b ids) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" and pll_alloc: "fst ll = ALLOC" and pll_leaf: "leaf (Leaf ll)" and plr_free: "fst lr = FREE" and plr_leaf: "leaf (Leaf lr)" and prl_free: "fst rl = FREE" and prl_leaf: "leaf (Leaf rl)" and prr_free: "fst rr = FREE" and prr_leaf: "leaf (Leaf rr)" unfolding divide_def Let_def by auto have allocsets_lr: "allocsets (Leaf lr) = {}" unfolding allocsets_def using plr_leaf plr_free by auto have allocsets_rl: "allocsets (Leaf rl) = {}" unfolding allocsets_def using prl_leaf prl_free by auto have allocsets_rr: "allocsets (Leaf rr) = {}" unfolding allocsets_def using prr_leaf prr_free by auto let ?newids = "snd (divide b ids)" have belong_ll: "snd ll \<in> ?newids" using divide_belong pdivide by auto have step': "fst (split b ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - lmax - 1))) (Leaf lr) (Leaf rl) (Leaf rr)" using split_induct Suc(3) pdivide by (meson zero_less_diff) {assume xa_eq_1: "Suc xa = 1" have lv_suc_lmax: "lv = Suc lmax" using Suc(2) xa_eq_1 by linarith have lv_sub_lmax: "lv - lmax = Suc 0" using lv_suc_lmax by auto have split_ll: "fst (split (Leaf ll) ?newids (lv - lmax - 1)) = Leaf ll" using lv_suc_lmax by auto have step1: "fst (split b ids (lv - lmax)) = Node (Leaf ll) (Leaf lr) (Leaf rl) (Leaf rr)" using step' split_ll by auto have allocsets_ll: "allocsets (Leaf ll) = {Leaf ll}" unfolding allocsets_def using pll_leaf pll_alloc by auto have ?case using step1 allocsets_ll allocsets_lr allocsets_rl allocsets_rr allocsets_node by auto } moreover {assume xa_gr_1: "Suc xa > 1" have xa_lv_suc_lmax: "xa = lv - Suc lmax" using Suc(2) by linarith have suc_lmax_less_lv: "Suc lmax < lv" using Suc(3) xa_gr_1 xa_lv_suc_lmax by linarith have step2: "fst (split b ids (lv - lmax)) = Node (fst (split (Leaf ll) ?newids (lv - Suc lmax))) (Leaf lr) (Leaf rl) (Leaf rr)" using step' by auto have allocsets_ll: "\<exists>!l. leaf l \<and> allocsets (fst (split (Leaf ll) ?newids (lv - Suc lmax))) = {l}" using Suc(1) xa_lv_suc_lmax suc_lmax_less_lv divide_finite Suc(4) belong_ll pdivide by auto have ?case using step2 allocsets_ll allocsets_lr allocsets_rl allocsets_rr allocsets_node by auto } ultimately have ?case by linarith then show ?case by auto qed lemma allocsets_after_replace_leaf: "diff_ids blo \<Longrightarrow> leaf b \<Longrightarrow> L b \<in> tree.set blo \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> allocsets (replace_leaf blo b subbtr) = allocsets blo \<union> allocsets subbtr" proof(induct blo) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(3) by fastforce have value_b: "b = Leaf x" using Leaf.prems(2) leaf_b by auto have empty_allocsets: "allocsets (Leaf x) = {}" unfolding allocsets_def using value_b Leaf.prems(4) by auto have replace_leaf_step: "replace_leaf (Leaf x) b subbtr = subbtr" using leaf_b replace_leaf.simps(1) by auto show ?case using replace_leaf_step empty_allocsets by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a0 diff_ab id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a0 diff_ac id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a0 diff_ad id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node (replace_leaf b1 b subbtr) b2 b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b2 no_belong_b3 no_belong_b4 by auto have step: "allocsets (replace_leaf b1 b subbtr) = allocsets b1 \<union> allocsets subbtr" using Node.hyps(1) diff_b1 Node.prems(2) a0 Node.prems(4) by auto have ?case using replace_leaf_step step allocsets_node by auto } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a1 diff_ab id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a1 diff_bc id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a1 diff_bd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 (replace_leaf b2 b subbtr) b3 b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b3 no_belong_b4 by auto have step: "allocsets (replace_leaf b2 b subbtr) = allocsets b2 \<union> allocsets subbtr" using Node.hyps(2) diff_b2 Node.prems(2) a1 Node.prems(4) by auto have ?case using replace_leaf_step step allocsets_node by auto } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a2 diff_ac id_set_def tree.set_map by fastforce have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a2 diff_bc id_set_def tree.set_map by fastforce have b_empty_b4: "{snd (L b)} \<inter> id_set b4 = {}" using no_belong_b4 unfolding id_set_def using a2 diff_cd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 b2 (replace_leaf b3 b subbtr) b4" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b4 by auto have step: "allocsets (replace_leaf b3 b subbtr) = allocsets b3 \<union> allocsets subbtr" using Node.hyps(3) diff_b3 Node.prems(2) a2 Node.prems(4) by auto have ?case using replace_leaf_step step allocsets_node by auto } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have b_empty_b1: "{snd (L b)} \<inter> id_set b1 = {}" using no_belong_b1 unfolding id_set_def using a3 diff_ad id_set_def tree.set_map by fastforce have b_empty_b2: "{snd (L b)} \<inter> id_set b2 = {}" using no_belong_b2 unfolding id_set_def using a3 diff_bd id_set_def tree.set_map by fastforce have b_empty_b3: "{snd (L b)} \<inter> id_set b3 = {}" using no_belong_b3 unfolding id_set_def using a3 diff_cd id_set_def tree.set_map by fastforce have replace_leaf_step: "replace_leaf (Node b1 b2 b3 b4) b subbtr = Node b1 b2 b3 (replace_leaf b4 b subbtr)" using replace_leaf.simps(2) no_replace_leaf no_belong_b1 no_belong_b2 no_belong_b3 by auto have step: "allocsets (replace_leaf b4 b subbtr) = allocsets b4 \<union> allocsets subbtr" using Node.hyps(4) diff_b4 Node.prems(2) a3 Node.prems(4) by auto have ?case using replace_leaf_step step allocsets_node by auto } ultimately have ?case using Node.prems(3) by auto then show ?case by auto qed lemma alloc_split_branch_allocsets: "diff_ids_valid bset \<Longrightarrow> finite ids \<Longrightarrow> \<forall>b\<in>bset. id_set b \<subseteq> ids \<Longrightarrow> exists_freelevel bset lv \<Longrightarrow> lmax = freesets_maxlevel bset lv \<Longrightarrow> lmax \<noteq> lv \<Longrightarrow> blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}) \<Longrightarrow> b = (SOME l. l \<in> freesets_level blo lmax) \<Longrightarrow> (subbtr, ids') = split b ids (lv - lmax) \<Longrightarrow> newblo = replace_leaf blo b subbtr \<Longrightarrow> newbset = bset - {blo} \<union> {newblo} \<Longrightarrow> \<exists>l. l \<notin> allocsets_pool bset \<and> l \<in> allocsets_pool newbset \<and> allocsets_pool newbset = allocsets_pool bset \<union> {l}" proof- assume a0: "diff_ids_valid bset" and a1: "finite ids" and a2: "\<forall>b\<in>bset. id_set b \<subseteq> ids" and a3: "exists_freelevel bset lv" and a4: "lmax = freesets_maxlevel bset lv" and a5: "lmax \<noteq> lv" and a6: "blo = (SOME b. b \<in> bset \<and> freesets_level b lmax \<noteq> {})" and a7: "b = (SOME l. l \<in> freesets_level blo lmax)" and a8: "(subbtr, ids') = split b ids (lv - lmax)" and a9: "newblo = replace_leaf blo b subbtr" and a10: "newbset = bset - {blo} \<union> {newblo}" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_lmax: "\<exists>!lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using exist_lmax a3 by auto have eq_lmax: "lmax = (THE lmax. lmax \<le> lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax))" using a4 unfolding freesets_maxlevel_def by auto have the_lmax: "lmax < lv \<and> freesets_level_pool bset lmax \<noteq> {} \<and> (\<forall>l. l \<le> lv \<and> freesets_level_pool bset l \<noteq> {} \<longrightarrow> l \<le> lmax)" using the_P[OF exi_lmax eq_lmax] a5 by auto have lmax_le_lv: "lmax < lv" using the_lmax by auto have value_lmax: "lmax \<ge> 0" by simp have value_lv: "lv > 0" using the_lmax by auto have lmax_le_lv: "lmax < lv" using the_lmax by auto (*------------------------------------------------------------------------------------------------*) have exi_b: "\<exists>b. b \<in> bset \<and> freesets_level b lmax \<noteq> {}" using the_lmax unfolding freesets_level_pool_def by auto have exi_blo: "blo \<in> bset \<and> freesets_level blo lmax \<noteq> {}" using someI_ex[OF exi_b] a6 by auto have diff_blo: "diff_ids blo" using diff_bset1 exi_blo by auto have ids_blo: "id_set blo \<subseteq> ids" using a2 exi_blo by auto have exi_l: "\<exists>l. l \<in> freesets_level blo lmax" using exi_blo by auto have exi_b: "b \<in> freesets_level blo lmax" using someI_ex[OF exi_l] a7 by auto have leaf_b: "leaf b" using exi_b unfolding freesets_level_def freesets_def by auto have b_belong_blo: "L b \<in> tree.set blo" using exi_b unfolding freesets_level_def freesets_def by auto have free_b: "fst (L b) = FREE" using exi_b unfolding freesets_level_def freesets_def by auto have ids_b: "snd (L b) \<in> ids" using exi_b unfolding freesets_level_def freesets_def using ids_blo unfolding id_set_def using tree.set_map by fastforce (*------------------------------------------------------------------------------------------------*) have exi_allocated_leaf: "\<exists>!l. leaf l \<and> allocsets subbtr = {l}" using allocated_leaf_after_split lmax_le_lv a1 ids_b a8 fst_conv by metis obtain le where allocated_leaf: "leaf le \<and> allocsets subbtr = {le}" using exi_allocated_leaf by auto have allocsets_newblo': "allocsets newblo = allocsets blo \<union> allocsets subbtr" using allocsets_after_replace_leaf diff_blo leaf_b b_belong_blo free_b a9 by auto have allocsets_newblo: "allocsets newblo = allocsets blo \<union> {le}" using allocsets_newblo' allocated_leaf by auto have le_treeset_subbtr: "L le \<in> tree.set subbtr" using allocated_leaf unfolding allocsets_def by auto have le_alloc: "fst (L le) = ALLOC" using allocated_leaf unfolding allocsets_def by auto have le_allocsets_newblo: "le \<in> allocsets newblo" using replace_leaf_belong b_belong_blo le_treeset_subbtr a9 unfolding allocsets_def using le_alloc allocated_leaf by simp have ids_subbtr: "id_set subbtr \<inter> ids = {}" using ids_split lmax_le_lv a1 ids_b a8 fst_conv by metis have leaf_notbelong_ids: "\<forall>b. b \<in> bset \<longrightarrow> snd (L le) \<notin> id_set b" using a2 ids_subbtr le_treeset_subbtr unfolding id_set_def using tree.set_map by fastforce have leaf_notbelong_set: "\<forall>b. b \<in> bset \<longrightarrow> L le \<notin> set b" using leaf_notbelong_ids unfolding id_set_def using tree.set_map by fastforce have le_allocsets_pool: "le \<notin> allocsets_pool bset" using leaf_notbelong_set unfolding allocsets_pool_def allocsets_def by blast have step1: "allocsets_pool bset = allocsets_pool (bset - {blo}) \<union> allocsets blo" unfolding allocsets_pool_def using exi_blo by auto have step2: "allocsets_pool newbset = allocsets_pool (bset - {blo}) \<union> allocsets newblo" unfolding allocsets_pool_def using a10 by auto have con1: "allocsets_pool newbset = allocsets_pool bset \<union> {le}" using step1 step2 allocsets_newblo by auto have con2: "le \<in> allocsets_pool newbset" using le_allocsets_newblo step2 unfolding allocsets_pool_def by auto show ?thesis using con1 con2 le_allocsets_pool by auto qed lemma free_fail_branch1: "\<not> (\<exists>btree \<in> bset. (L b) \<in> set btree) \<Longrightarrow> fst (free bset b ids) = bset" unfolding free_def Let_def by auto lemma free_fail_branch2: "\<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) = FREE \<Longrightarrow> fst (free bset b ids) = bset" unfolding free_def Let_def by auto lemma free_success_sub_allocsets: "diff_ids B \<Longrightarrow> leaf b \<Longrightarrow> fst (L b) = ALLOC \<Longrightarrow> L b \<in> set B \<Longrightarrow> b' = set_state_type b FREE \<Longrightarrow> allocsets B = allocsets (replace B b b') \<union> {b}" proof(induct B) case (Leaf x) have leaf_b: "L b = x" using Leaf.prems(4) by fastforce have value_b: "b = Leaf x" using Leaf.prems(2) leaf_b by auto have one_allocsets: "allocsets (Leaf x) = {Leaf x}" unfolding allocsets_def using Leaf.prems(2,3) value_b by auto have leaf_b': "b' = Leaf (FREE, snd x)" using Leaf.prems(5) leaf_b unfolding set_state_type_def Let_def by auto have leaf_B': "replace (Leaf x) b b' = Leaf (FREE, snd x)" using leaf_b leaf_b' unfolding replace_def by auto have empty_allocsets: "allocsets (Leaf (FREE, snd x)) = {}" unfolding allocsets_def by auto show ?case using one_allocsets leaf_B' empty_allocsets value_b by auto next case (Node b1 b2 b3 b4) have diff_b1: "diff_ids b1" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b2: "diff_ids b2" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b3: "diff_ids b3" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_b4: "diff_ids b4" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ab: "(id_set b1) \<inter> (id_set b2) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ac: "(id_set b1) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_ad: "(id_set b1) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bc: "(id_set b2) \<inter> (id_set b3) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_bd: "(id_set b2) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast have diff_cd: "(id_set b3) \<inter> (id_set b4) = {}" using Node.prems(1) diff_ids_leaf_node(2) by blast {assume a0: "L b \<in> set b1" have no_belong_b2: "L b \<notin> set b2" using a0 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a0 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a0 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node (replace b1 b b') b2 b3 b4" using a0 unfolding replace_def apply auto using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b1: "allocsets b1 = allocsets (replace b1 b b') \<union> {b}" using Node.hyps(1) diff_b1 Node.prems(2) Node.prems(3) a0 Node.prems(5) by auto have ?case using replace_re sub_b1 allocsets_node by simp } moreover {assume a1: "L b \<in> set b2" have no_belong_b1: "L b \<notin> set b1" using a1 diff_ab unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a1 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a1 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 (replace b2 b b') b3 b4" using a1 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b2: "allocsets b2 = allocsets (replace b2 b b') \<union> {b}" using Node.hyps(2) diff_b2 Node.prems(2) Node.prems(3) a1 Node.prems(5) by auto have ?case using replace_re sub_b2 allocsets_node by simp } moreover {assume a2: "L b \<in> set b3" have no_belong_b1: "L b \<notin> set b1" using a2 diff_ac unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a2 diff_bc unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b4: "L b \<notin> set b4" using a2 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 (replace b3 b b') b4" using a2 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b4 Node.prems(5) by auto have sub_b3: "allocsets b3 = allocsets (replace b3 b b') \<union> {b}" using Node.hyps(3) diff_b3 Node.prems(2) Node.prems(3) a2 Node.prems(5) by auto have ?case using replace_re sub_b3 allocsets_node by simp } moreover {assume a3: "L b \<in> set b4" have no_belong_b1: "L b \<notin> set b1" using a3 diff_ad unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b2: "L b \<notin> set b2" using a3 diff_bd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have no_belong_b3: "L b \<notin> set b3" using a3 diff_cd unfolding id_set_def by (metis disjoint_iff_not_equal image_eqI tree.set_map) have replace_re: "replace (Node b1 b2 b3 b4) b b' = Node b1 b2 b3 (replace b4 b b')" using a3 unfolding replace_def apply auto using no_replace no_belong_b1 Node.prems(5) apply auto[1] using no_replace no_belong_b2 Node.prems(5) apply auto[1] using no_replace no_belong_b3 Node.prems(5) by auto have sub_b4: "allocsets b4 = allocsets (replace b4 b b') \<union> {b}" using Node.hyps(4) diff_b4 Node.prems(2) Node.prems(3) a3 Node.prems(5) by auto have ?case using replace_re sub_b4 allocsets_node by simp } ultimately have ?case using Node.prems(4) by fastforce then show ?case by auto qed lemma free_success_same_allocsets: "allocsets (fst (merge B ids)) = allocsets B" proof(induct B arbitrary: ids) case (Leaf x) then show ?case by auto next case (Node b1 b2 b3 b4) {assume a0: "\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))" have empty_allocsets: "allocsets (Node b1 b2 b3 b4) = {}" using a0 unfolding allocsets_def by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node b1 b2 b3 b4) ids" using merge.simps(2) a0 by auto obtain newid where com: "fst (combine (Node b1 b2 b3 b4) ids) = Leaf (FREE, newid)" unfolding combine_def Let_def using fst_conv a0 by auto have still_empty_allocsets: "allocsets (Leaf (FREE, newid)) = {}" unfolding allocsets_def by auto have ?case using empty_allocsets step com still_empty_allocsets by simp } moreover {assume a1: "\<not> (\<exists>xa xb xc xd. (Node b1 b2 b3 b4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd)))" let ?m1 = "merge b1 ids" have allocsets_m1: "allocsets (fst (merge b1 ids)) = allocsets b1" using Node.hyps(1) by auto let ?m2 = "merge b2 (snd ?m1)" have allocsets_m2: "allocsets (fst (merge b2 (snd ?m1))) = allocsets b2" using Node.hyps(2) by auto let ?m3 = "merge b3 (snd ?m2)" have allocsets_m3: "allocsets (fst (merge b3 (snd ?m2))) = allocsets b3" using Node.hyps(3) by auto let ?m4 = "merge b4 (snd ?m3)" have allocsets_m4: "allocsets (fst (merge b4 (snd ?m3))) = allocsets b4" using Node.hyps(4) by auto have step: "merge (Node b1 b2 b3 b4) ids = combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)" using merge.simps(2) a1 by meson have allocsets_com: "allocsets (fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4))) = allocsets (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4))" proof(cases "\<exists>xa xb xc xd. Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4) = Node (Leaf (FREE, xa)) (Leaf (FREE, xb)) (Leaf (FREE, xc)) (Leaf (FREE, xd))") case True have empty_allocsets: "allocsets (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) = {}" using True unfolding allocsets_def by auto obtain newid where step1: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Leaf (FREE, newid)" unfolding combine_def Let_def using True by auto have still_empty_allocsets: "allocsets (Leaf (FREE, newid)) = {}" unfolding allocsets_def by auto show ?thesis by (simp add: empty_allocsets step1 still_empty_allocsets) next case False have step2: "fst (combine (Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)) (snd ?m4)) = Node (fst ?m1) (fst ?m2) (fst ?m3) (fst ?m4)" unfolding combine_def using False by auto show ?thesis by (simp add: step2) qed have ?case using step allocsets_com by (simp add: allocsets_m1 allocsets_m2 allocsets_m3 allocsets_m4 allocsets_node) } ultimately have ?case by blast then show ?case by auto qed lemma free_success_branch_allocsets: "diff_ids_valid bset \<Longrightarrow> leaf b \<Longrightarrow> \<exists>btree \<in> bset. (L b) \<in> set btree \<Longrightarrow> fst (L b) \<noteq> FREE \<Longrightarrow> (newbset, newids, re) = free bset b ids \<Longrightarrow> allocsets_pool bset = allocsets_pool newbset \<union> {b}" proof- assume a0: "diff_ids_valid bset" and a1: "leaf b" and a2: "\<exists>btree \<in> bset. (L b) \<in> set btree" and a3: "fst (L b) \<noteq> FREE" and a4: "(newbset, newids, re) = free bset b ids" have diff_bset1: "(\<forall>b \<in> bset. diff_ids b)" using a0 diff_ids_valid_def by auto have diff_bset2: "(\<forall>b1 b2. b1 \<in> bset \<and> b2 \<in> bset \<and> b1 \<noteq> b2 \<longrightarrow> id_set b1 \<inter> id_set b2 = {})" using a0 diff_ids_valid_def by auto have exi_btree: "\<exists>!btree \<in> bset. (L b) \<in> set btree" using a3 diff_bset2 proof - { fix tt :: "(block_state_type \<times> nat) tree" and tta :: "(block_state_type \<times> nat) tree \<Rightarrow> (block_state_type \<times> nat) tree" have "\<And>t ta n. t \<notin> bset \<or> ta \<notin> bset \<or> n \<notin> tree.set (tree_map snd t) \<or> n \<notin> tree.set (tree_map snd ta) \<or> ta = t" using diff_bset2 id_set_def by auto then have "\<exists>t. tt \<notin> bset \<or> tta t \<notin> bset \<or> L b \<notin> tree.set tt \<or> t \<in> bset \<and> tta t = t \<and> L b \<in> tree.set t \<or> t \<in> bset \<and> L b \<in> tree.set t \<and> L b \<notin> tree.set (tta t)" by (metis (no_types) image_eqI tree.set_map) } then have "\<forall>t. \<exists>ta. \<forall>tb. t \<notin> bset \<or> tb \<notin> bset \<or> L b \<notin> tree.set t \<or> ta \<in> bset \<and> tb = ta \<and> L b \<in> tree.set ta \<or> ta \<in> bset \<and> L b \<in> tree.set ta \<and> L b \<notin> tree.set tb" by (metis (no_types)) then show ?thesis by (metis a2) qed let ?btree = "THE t. t \<in> bset \<and> (L b) \<in> set t" have the_btree: "?btree \<in> bset \<and> (L b) \<in> set ?btree" using the_P[OF exi_btree] by blast have diff_btree: "diff_ids ?btree" using the_btree diff_bset1 by auto have exi_newb: "\<exists>newb. newb = replace ?btree b (set_state_type b FREE)" by simp let ?freeblo = "SOME newb. newb = replace ?btree b (set_state_type b FREE)" have sub_allocsets: "allocsets ?btree = allocsets ?freeblo \<union> {b}" using free_success_sub_allocsets diff_btree a1 a3 the_btree proof - have "fst (L b) = ALLOC" by (metis a3 block_state_type.exhaust) then show ?thesis using a1 diff_btree free_success_sub_allocsets the_btree by auto qed have exi_re: "\<exists>re. re = merge ?freeblo ids" by simp let ?re = "SOME re. re = merge ?freeblo ids" have same_allocsets: "allocsets ?btree = allocsets (fst ?re) \<union> {b}" using free_success_same_allocsets sub_allocsets by auto (*------------------------------------------------------------------------------------------------*) have free_re: "(newbset, newids, re) = ((bset - {?btree}) \<union> {fst ?re}, snd ?re, True)" using a3 a4 unfolding free_def Let_def using exi_btree by auto have step1: "allocsets_pool bset = allocsets_pool (bset - {?btree}) \<union> allocsets ?btree" unfolding allocsets_pool_def using the_btree by auto have step2: "allocsets_pool newbset = allocsets_pool (bset - {?btree}) \<union> allocsets (fst ?re)" unfolding allocsets_pool_def using free_re by auto have change_allocsets_pool: "allocsets_pool bset = allocsets_pool newbset \<union> {b}" using step1 step2 same_allocsets by auto then show ?thesis by auto qed end
In 1997 , Fey and other members of The Second City provided voices for the pinball game Medieval Madness .
! ! Octree derived type supporting 3D radius neighbor search for RBF and other applications ! ! Based on: ! J. Behley, V. Steinhage, A.B. Cremers. Efficient Radius Neighbor Search in Three-dimensional Point Clouds, ! Proc. of the IEEE International Conference on Robotics and Automation (ICRA), 2015 ! ! @author Eric Wolf ! @date 08/25/2017 ! module type_octree use mod_kinds, only: ik, rk use mod_constants, only: ZERO, ONE, HALF, TWO use type_octree_box, only: octree_box_t use type_box_vector, only: box_vector_t use type_octree_parameters, only: octree_parameters_t use type_ivector, only: ivector_t implicit none type, public :: octree_t type(octree_parameters_t) :: params type(box_vector_t) :: boxes integer(ik) :: root_box_ID real(rk), allocatable :: global_nodes(:, :) logical :: has_nodes = .false. integer(ik), allocatable :: successors(:) integer(ik) :: num_nodes_in_leaves = 0 contains procedure :: init procedure :: build_octree_depth_first procedure :: create_octant procedure :: radius_search end type contains subroutine init(self, bucket_size, min_extent, refine_dir, copy_points) class(octree_t), intent(inout) :: self integer(ik), intent(in), optional :: bucket_size real(rk), intent(in), optional :: min_extent integer(ik), intent(in), optional :: refine_dir(3) logical, intent(in), optional :: copy_points call self%params%init(bucket_size, min_extent, refine_dir, copy_points) end subroutine init !> Depth-first octree construction !! !! !! @author Eric M. Wolf !! @date 08/17/2018 !! !-------------------------------------------------------------------------------- subroutine build_octree_depth_first(self, global_nodes) class(octree_t), intent(inout) :: self real(rk), intent(in) :: global_nodes(:,:) real(rk) :: center(3), extent(3) real(rk) :: coord_min(3), coord_max(3), bounding_box_len(3) integer(ik) :: ibox, ichild, current_level_ID, next_level_ID, current_box_ID, total_number_boxes, number_boxes, & current_level, child_box_ID, inode, level_counter, root_box_ID, start_index, end_index, num_points ! Copy the nodes if requested !if (self%params%copy_points) then self%global_nodes = global_nodes self%has_nodes = .true. !end if !---------------------------------------------------------------------------------------------------- ! ! Create the root level (bounding box) ! ! ! Determine a bounding box for all nodes to construct the root box of the tree ! coord_min(1) = minval(global_nodes(:,1)) coord_min(2) = minval(global_nodes(:,2)) coord_min(3) = minval(global_nodes(:,3)) coord_max(1) = maxval(global_nodes(:,1)) coord_max(2) = maxval(global_nodes(:,2)) coord_max(3) = maxval(global_nodes(:,3)) extent = 1.05_rk*HALF*(coord_max - coord_min) center = HALF*(coord_min + coord_max) num_points = size(global_nodes(:,1)) start_index = 1 end_index = num_points if (allocated(self%successors)) deallocate(self%successors) allocate(self%successors(num_points)) do inode = 1, num_points self%successors(inode) = inode+1 end do !---------------------------------------------------------------------------------------------------- ! ! Now recursively subdivide boxes until the no box contains more than the max number of nodes per box ! ! print *, 'call create octant' !call self%create_octant(center, extent, start_index, end_index, num_points, global_nodes, root_box_ID) call self%create_octant(center, extent, start_index, end_index, num_points, root_box_ID) self%root_box_ID = root_box_ID !print *, 'num nodes in leaves: ', self%num_nodes_in_leaves !print *, 'num nodes total: ', num_points end subroutine build_octree_depth_first !> !! !! !! @author Eric M. Wolf !! @date 08/17/2018 !! !-------------------------------------------------------------------------------- !recursive subroutine create_octant(self, center, extent, start_index, end_index, num_points, global_nodes, my_box_ID) recursive subroutine create_octant(self, center, extent, start_index, end_index, num_points, my_box_ID) class(octree_t), intent(inout) :: self real(rk), intent(in) :: center(3), extent(3) integer(ik), intent(in) :: num_points, start_index, end_index !real(rk), intent(in) :: global_nodes(:,:) integer(ik), intent(inout) :: my_box_ID integer(ik) :: box_ID, child_box_ID, idx, morton_code,last_child_box_ID, ichild, num_children, ipt integer(ik) :: child_starts(8), child_ends(8), child_sizes(8) type(octree_box_t) :: temp_box logical :: is_leaf, firsttime real(rk) :: node(3), factor(2), child_center(3), child_extent(3) is_leaf = .true. !print *, 'a' call temp_box%init(center, extent, start_index, end_index, num_points, is_leaf) !print *, 'b' call self%boxes%push_back(temp_box, box_ID) my_box_ID = box_ID !print *, 'c' if (num_points > self%params%bucket_size) then ! Box is flagged for refinement self%boxes%data(box_ID)%is_leaf = .false. ! Loop over the points contained in current octant box and divide them into the child boxes idx = start_index !print *, 'd' child_sizes = 0 child_starts = 1 child_ends = 1 do ipt = 1, num_points node = self%global_nodes(idx,:) ! Morton code trickery morton_code = 0 if (node(1) > center(1)) morton_code = ior(morton_code, 1) if (node(2) > center(2)) morton_code = ior(morton_code, 2) if (node(3) > center(3)) morton_code = ior(morton_code, 4) morton_code = morton_code + 1 ! set child starts and update successors... if (child_sizes(morton_code) == 0) then child_starts(morton_code) = idx else self%successors(child_ends(morton_code)) = idx end if child_sizes(morton_code) = child_sizes(morton_code) + 1 child_ends(morton_code) = idx idx = self%successors(idx) end do !print *, 'e' ! Loop over the non-empty child octants and create boxes child_extent = 0.5_rk*extent firsttime = .true. !last_child_idx = 1 last_child_box_ID = 0 factor = (/ -0.5_rk, 0.5_rk/) do ichild = 1, 8 if (child_sizes(ichild) > 0) then ! Get the child center using some Morton code trickery... ! transfer(logical, int) converts the logical argument into integer ! transfer(.false., 1) = 0, transfer(.true., 1) = 1 child_center(1) = center(1) + factor(transfer((iand(ichild-1,1)>0),1)+1)*extent(1) child_center(2) = center(2) + factor(transfer((iand(ichild-1,2)>0),1)+1)*extent(2) child_center(3) = center(3) + factor(transfer((iand(ichild-1,4)>0),1)+1)*extent(3) ! Recursively call create_octant to create the child octant box !print *, 'f' !call self%create_octant(child_center, child_extent, child_starts(ichild), child_ends(ichild), child_sizes(ichild), global_nodes, child_box_ID) call self%create_octant(child_center, child_extent, child_starts(ichild), child_ends(ichild), child_sizes(ichild), child_box_ID) !print *, 'g' ! Store the child_box_ID in the current box self%boxes%data(box_ID)%child_ID(ichild) = child_box_ID !print *, 'g2' if (firsttime) then ! Reset the start index of the current box to the start index of the first child !print *, 'g3' self%boxes%data(box_ID)%start_index = self%boxes%data(child_box_ID)%start_index !print *, 'g4' else !successors_[octant->child[lastChildIdx]->end] = ! octant->child[i]->start; // we have to ensure that also the child ends link to the next child start. !print *, 'g5' self%successors(self%boxes%data(last_child_box_ID)%end_index) = self%boxes%data(child_box_ID)%start_index !print *, 'g6' end if !print *, 'h' last_child_box_ID = child_box_ID !lastChildIdx = i !octant->end = octant->child[i]->end; self%boxes%data(box_ID)%end_index = self%boxes%data(child_box_ID)%end_index firsttime = .false. end if end do else !print *, 'leaf box' self%num_nodes_in_leaves = self%num_nodes_in_leaves+num_points end if end subroutine create_octant !> !! !! !! @author Eric M. Wolf !! @date 08/21/2018 !! !-------------------------------------------------------------------------------- recursive subroutine radius_search(self, global_nodes, box_ID, query_point, query_radius, hit_list) class(octree_t), intent(inout) :: self real(rk), intent(in) :: global_nodes(:,:) integer(ik), intent(in) :: box_ID real(rk), intent(in) :: query_point(3), query_radius(3) type(ivector_t), intent(inout) :: hit_list real(rk) :: corner(3), center(3), extent(3), factor(2), point(3), child_center(3), child_extent(3) logical :: box_is_contained, corner_is_contained, point_included, child_overlaps integer(ik) :: icorner, idx, ipt, child_ID, ichild center = self%boxes%data(box_ID)%center extent = self%boxes%data(box_ID)%extent !print *, 'num_points' !print *, self%boxes%data(box_ID)%num_points ! Check if the current box is entirely contained in the searchoid ! If so, add all of the points in the box to the hit list factor = (/-1.0_rk, 1.0_rk/) box_is_contained = .true. do icorner = 1, 8 corner(1) = center(1) + factor(transfer((iand(icorner-1,1)>0),1)+1)*extent(1) corner(2) = center(2) + factor(transfer((iand(icorner-1,2)>0),1)+1)*extent(2) corner(3) = center(3) + factor(transfer((iand(icorner-1,4)>0),1)+1)*extent(3) corner_is_contained = check_point_inclusion(corner, query_point, 1.05_rk*query_radius) ! corner_is_contained = & ! ((((corner(1)-query_point(1))/query_radius(1))**TWO+ & ! ((corner(2)-query_point(2))/query_radius(2))**TWO+ & ! ((corner(3)-query_point(3))/query_radius(3))**TWO)<=ONE) if (.not. (corner_is_contained)) box_is_contained = .false. end do if (box_is_contained) then ! Add all points to the hit list idx = self%boxes%data(box_ID)%start_index do ipt = 1, self%boxes%data(box_ID)%num_points call hit_list%push_back(idx) idx = self%successors(idx) end do ! Check if the current box is a leaf ! If so, individually check each point to see if it is contained in the searchoid ! and add contained points to the hit list ! Note: there should be just a small number points, at most the bucket size, in a leaf box else if (self%boxes%data(box_ID)%is_leaf) then ! Loop over all points in the present leaf box and test them for inclusion idx = self%boxes%data(box_ID)%start_index do ipt = 1, self%boxes%data(box_ID)%num_points point = global_nodes(idx,:) point_included = check_point_inclusion(point, query_point, 1.05_rk*query_radius) if (point_included) call hit_list%push_back(idx) idx = self%successors(idx) end do ! Else, cycle over the child boxes of the current box, ! check for overlap with the searchoid, and if overlap is detected ! recursively launch this subroutine on the child box else do ichild = 1,8 child_ID = self%boxes%data(box_ID)%child_ID(ichild) if (child_ID /= -1) then ! Check overlap by putting bounding box around the searchoid ! Then it's trivial to check whether the BB overlaps with the octree child box child_center = self%boxes%data(child_ID)%center child_extent = self%boxes%data(child_ID)%extent child_overlaps = check_box_overlaps(child_center, child_extent, query_point, 1.05_rk*query_radius) if (child_overlaps) call self%radius_search(global_nodes, child_ID, query_point, 1.05_rk*query_radius, hit_list) end if end do end if end subroutine radius_search !> !! !! !! @author Eric M. Wolf !! @date 08/21/2018 !! !-------------------------------------------------------------------------------- function check_point_inclusion(point, query_point, query_radius) result(point_included) real(rk), intent(in) :: point(3), query_point(3), query_radius(3) logical :: point_included point_included = & ((((point(1)-query_point(1))/query_radius(1))**TWO+ & ((point(2)-query_point(2))/query_radius(2))**TWO+ & ((point(3)-query_point(3))/query_radius(3))**TWO)<=ONE) end function check_point_inclusion !> !! !! !! @author Eric M. Wolf !! @date 08/21/2018 !! !-------------------------------------------------------------------------------- function check_box_overlaps(center, extent, query_point, query_radius) result(box_overlaps) real(rk) :: center(3), extent(3), query_point(3), query_radius(3) logical :: box_overlaps real(rk) :: box_min(3), box_max(3), bbox_min(3), bbox_max(3) integer(ik) :: idir logical :: bo(3) box_min = center - extent box_max = center + extent bbox_min = query_point - query_radius bbox_max = query_point + query_radius box_overlaps = .false. bo = .false. do idir = 1,3 if (((bbox_min(idir)<=box_max(idir)) .and. (box_min(idir)<=bbox_min(idir))) .or. & ((box_min(idir)<=bbox_max(idir)) .and. (bbox_min(idir)<=box_min(idir)))) bo(idir) = .true. end do if ((bo(1)) .and. (bo(2)) .and. (bo(3))) box_overlaps = .true. end function check_box_overlaps end module type_octree
In one of Adorján 's books , GM Lajos Portisch opined that " at least two @-@ thirds of all ' tested ' openings give White an apparent advantage . " According to Portisch , for Black , " The root of the problem is that very few people know which are the openings where Black is really OK . Those who find these lines have nothing to fear , as Black is indeed OK , but only in those variations ! " Rowson considers this an important point , noting that " 1.d4 players struggle to get anywhere against main @-@ line Slavs and 1.e4 players find the Najdorf and Sveshnikov Sicilians particularly tough . "
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import data.zmod.quotient import group_theory.noncomm_pi_coprod import group_theory.order_of_element import algebra.gcd_monoid.finset import data.nat.factorization.basic import tactic.by_contra /-! # Exponent of a group This file defines the exponent of a group, or more generally a monoid. For a group `G` it is defined to be the minimal `n≥1` such that `g ^ n = 1` for all `g ∈ G`. For a finite group `G`, it is equal to the lowest common multiple of the order of all elements of the group `G`. ## Main definitions * `monoid.exponent_exists` is a predicate on a monoid `G` saying that there is some positive `n` such that `g ^ n = 1` for all `g ∈ G`. * `monoid.exponent` defines the exponent of a monoid `G` as the minimal positive `n` such that `g ^ n = 1` for all `g ∈ G`, by convention it is `0` if no such `n` exists. * `add_monoid.exponent_exists` the additive version of `monoid.exponent_exists`. * `add_monoid.exponent` the additive version of `monoid.exponent`. ## Main results * `monoid.lcm_order_eq_exponent`: For a finite left cancel monoid `G`, the exponent is equal to the `finset.lcm` of the order of its elements. * `monoid.exponent_eq_supr_order_of(')`: For a commutative cancel monoid, the exponent is equal to `⨆ g : G, order_of g` (or zero if it has any order-zero elements). ## TODO * Refactor the characteristic of a ring to be the exponent of its underlying additive group. -/ universe u variable {G : Type u} open_locale classical namespace monoid section monoid variables (G) [monoid G] /--A predicate on a monoid saying that there is a positive integer `n` such that `g ^ n = 1` for all `g`.-/ @[to_additive "A predicate on an additive monoid saying that there is a positive integer `n` such that `n • g = 0` for all `g`."] def exponent_exists := ∃ n, 0 < n ∧ ∀ g : G, g ^ n = 1 /--The exponent of a group is the smallest positive integer `n` such that `g ^ n = 1` for all `g ∈ G` if it exists, otherwise it is zero by convention.-/ @[to_additive "The exponent of an additive group is the smallest positive integer `n` such that `n • g = 0` for all `g ∈ G` if it exists, otherwise it is zero by convention."] noncomputable def exponent := if h : exponent_exists G then nat.find h else 0 variable {G} @[to_additive] lemma exponent_exists_iff_ne_zero : exponent_exists G ↔ exponent G ≠ 0 := begin rw [exponent], split_ifs, { simp [h, @not_lt_zero' ℕ] }, --if this isn't done this way, `to_additive` freaks { tauto }, end @[to_additive] lemma exponent_eq_zero_iff : exponent G = 0 ↔ ¬ exponent_exists G := by simp only [exponent_exists_iff_ne_zero, not_not] @[to_additive] lemma exponent_eq_zero_of_order_zero {g : G} (hg : order_of g = 0) : exponent G = 0 := exponent_eq_zero_iff.mpr $ λ ⟨n, hn, hgn⟩, order_of_eq_zero_iff'.mp hg n hn $ hgn g @[to_additive exponent_nsmul_eq_zero] lemma pow_exponent_eq_one (g : G) : g ^ exponent G = 1 := begin by_cases exponent_exists G, { simp_rw [exponent, dif_pos h], exact (nat.find_spec h).2 g }, { simp_rw [exponent, dif_neg h, pow_zero] } end @[to_additive] lemma pow_eq_mod_exponent {n : ℕ} (g : G): g ^ n = g ^ (n % exponent G) := calc g ^ n = g ^ (n % exponent G + exponent G * (n / exponent G)) : by rw [nat.mod_add_div] ... = g ^ (n % exponent G) : by simp [pow_add, pow_mul, pow_exponent_eq_one] @[to_additive] lemma exponent_pos_of_exists (n : ℕ) (hpos : 0 < n) (hG : ∀ g : G, g ^ n = 1) : 0 < exponent G := begin have h : ∃ n, 0 < n ∧ ∀ g : G, g ^ n = 1 := ⟨n, hpos, hG⟩, rw [exponent, dif_pos], exact (nat.find_spec h).1, end @[to_additive] @[to_additive] lemma exponent_min (m : ℕ) (hpos : 0 < m) (hm : m < exponent G) : ∃ g : G, g ^ m ≠ 1 := begin by_contra' h, have hcon : exponent G ≤ m := exponent_min' m hpos h, linarith, end @[simp, to_additive] lemma exp_eq_one_of_subsingleton [subsingleton G] : exponent G = 1 := begin apply le_antisymm, { apply exponent_min' _ nat.one_pos, simp }, { apply nat.succ_le_of_lt, apply exponent_pos_of_exists 1 (nat.one_pos), simp }, end @[to_additive add_order_dvd_exponent] lemma order_dvd_exponent (g : G) : (order_of g) ∣ exponent G := order_of_dvd_of_pow_eq_one $ pow_exponent_eq_one g variable (G) @[to_additive] lemma exponent_dvd_of_forall_pow_eq_one (G) [monoid G] (n : ℕ) (hG : ∀ g : G, g ^ n = 1) : exponent G ∣ n := begin rcases n.eq_zero_or_pos with rfl | hpos, { exact dvd_zero _ }, apply nat.dvd_of_mod_eq_zero, by_contradiction h, have h₁ := nat.pos_of_ne_zero h, have h₂ : n % exponent G < exponent G := nat.mod_lt _ (exponent_pos_of_exists n hpos hG), have h₃ : exponent G ≤ n % exponent G, { apply exponent_min' _ h₁, simp_rw ←pow_eq_mod_exponent, exact hG }, linarith, end @[to_additive lcm_add_order_of_dvd_exponent] lemma lcm_order_of_dvd_exponent [fintype G] : (finset.univ : finset G).lcm order_of ∣ exponent G := begin apply finset.lcm_dvd, intros g hg, exact order_dvd_exponent g end @[to_additive exists_order_of_eq_pow_padic_val_nat_add_exponent] lemma _root_.nat.prime.exists_order_of_eq_pow_factorization_exponent {p : ℕ} (hp : p.prime) : ∃ g : G, order_of g = p ^ (exponent G).factorization p := begin haveI := fact.mk hp, rcases eq_or_ne ((exponent G).factorization p) 0 with h | h, { refine ⟨1, by rw [h, pow_zero, order_of_one]⟩ }, have he : 0 < exponent G := ne.bot_lt (λ ht, by {rw ht at h, apply h, rw [bot_eq_zero, nat.factorization_zero, finsupp.zero_apply] }), rw ← finsupp.mem_support_iff at h, obtain ⟨g, hg⟩ : ∃ (g : G), g ^ (exponent G / p) ≠ 1, { suffices key : ¬ exponent G ∣ exponent G / p, { simpa using mt (exponent_dvd_of_forall_pow_eq_one G (exponent G / p)) key }, exact λ hd, hp.one_lt.not_le ((mul_le_iff_le_one_left he).mp $ nat.le_of_dvd he $ nat.mul_dvd_of_dvd_div (nat.dvd_of_mem_factorization h) hd) }, obtain ⟨k, hk : exponent G = p ^ _ * k⟩ := nat.ord_proj_dvd _ _, obtain ⟨t, ht⟩ := nat.exists_eq_succ_of_ne_zero (finsupp.mem_support_iff.mp h), refine ⟨g ^ k, _⟩, rw ht, apply order_of_eq_prime_pow, { rwa [hk, mul_comm, ht, pow_succ', ←mul_assoc, nat.mul_div_cancel _ hp.pos, pow_mul] at hg }, { rw [←nat.succ_eq_add_one, ←ht, ←pow_mul, mul_comm, ←hk], exact pow_exponent_eq_one g }, end variable {G} @[to_additive] lemma exponent_ne_zero_iff_range_order_of_finite (h : ∀ g : G, 0 < order_of g) : exponent G ≠ 0 ↔ (set.range (order_of : G → ℕ)).finite := begin refine ⟨λ he, _, λ he, _⟩, { by_contra h, obtain ⟨m, ⟨t, rfl⟩, het⟩ := set.infinite.exists_nat_lt h (exponent G), exact pow_ne_one_of_lt_order_of' he het (pow_exponent_eq_one t) }, { lift (set.range order_of) to finset ℕ using he with t ht, have htpos : 0 < t.prod id, { refine finset.prod_pos (λ a ha, _), rw [←finset.mem_coe, ht] at ha, obtain ⟨k, rfl⟩ := ha, exact h k }, suffices : exponent G ∣ t.prod id, { intro h, rw [h, zero_dvd_iff] at this, exact htpos.ne' this }, refine exponent_dvd_of_forall_pow_eq_one _ _ (λ g, _), rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd, pow_zero g], apply finset.dvd_prod_of_mem, rw [←finset.mem_coe, ht], exact set.mem_range_self g }, end @[to_additive] lemma exponent_eq_zero_iff_range_order_of_infinite (h : ∀ g : G, 0 < order_of g) : exponent G = 0 ↔ (set.range (order_of : G → ℕ)).infinite := have _ := exponent_ne_zero_iff_range_order_of_finite h, by rwa [ne.def, not_iff_comm, iff.comm] at this @[to_additive lcm_add_order_eq_exponent] lemma lcm_order_eq_exponent [fintype G] : (finset.univ : finset G).lcm order_of = exponent G := begin apply nat.dvd_antisymm (lcm_order_of_dvd_exponent G), refine exponent_dvd_of_forall_pow_eq_one G _ (λ g, _), obtain ⟨m, hm⟩ : order_of g ∣ finset.univ.lcm order_of := finset.dvd_lcm (finset.mem_univ g), rw [hm, pow_mul, pow_order_of_eq_one, one_pow] end end monoid section left_cancel_monoid variable [left_cancel_monoid G] @[to_additive] lemma exponent_ne_zero_of_finite [finite G] : exponent G ≠ 0 := by { casesI nonempty_fintype G, simpa [←lcm_order_eq_exponent, finset.lcm_eq_zero_iff] using λ x, (order_of_pos x).ne' } end left_cancel_monoid section comm_monoid variable [comm_monoid G] @[to_additive] lemma exponent_eq_supr_order_of (h : ∀ g : G, 0 < order_of g) : exponent G = ⨆ g : G, order_of g := begin rw supr, rcases eq_or_ne (exponent G) 0 with he | he, { rw [he, set.infinite.nat.Sup_eq_zero $ (exponent_eq_zero_iff_range_order_of_infinite h).1 he] }, have hne : (set.range (order_of : G → ℕ)).nonempty := ⟨1, 1, order_of_one⟩, have hfin : (set.range (order_of : G → ℕ)).finite, { rwa [← exponent_ne_zero_iff_range_order_of_finite h] }, obtain ⟨t, ht⟩ := hne.cSup_mem hfin, apply nat.dvd_antisymm _, { rw ←ht, apply order_dvd_exponent }, refine nat.dvd_of_factors_subperm he _, rw list.subperm_ext_iff, by_contra' h, obtain ⟨p, hp, hpe⟩ := h, replace hp := nat.prime_of_mem_factors hp, simp only [nat.factors_count_eq] at hpe, set k := (order_of t).factorization p with hk, obtain ⟨g, hg⟩ := hp.exists_order_of_eq_pow_factorization_exponent G, suffices : order_of t < order_of (t ^ (p ^ k) * g), { rw ht at this, exact this.not_le (le_cSup hfin.bdd_above $ set.mem_range_self _) }, have hpk : p ^ k ∣ order_of t := nat.ord_proj_dvd _ _, have hpk' : order_of (t ^ p ^ k) = order_of t / p ^ k, { rw [order_of_pow' t (pow_ne_zero k hp.ne_zero), nat.gcd_eq_right hpk] }, obtain ⟨a, ha⟩ := nat.exists_eq_add_of_lt hpe, have hcoprime : (order_of (t ^ p ^ k)).coprime (order_of g), { rw [hg, nat.coprime_pow_right_iff (pos_of_gt hpe), nat.coprime_comm], apply or.resolve_right (nat.coprime_or_dvd_of_prime hp _), nth_rewrite 0 ←pow_one p, convert nat.pow_succ_factorization_not_dvd (h $ t ^ p ^ k).ne' hp, rw [hpk', nat.factorization_div hpk], simp [hp] }, rw [(commute.all _ g).order_of_mul_eq_mul_order_of_of_coprime hcoprime, hpk', hg, ha, ←ht, ←hk, pow_add, pow_add, pow_one, ←mul_assoc, ←mul_assoc, nat.div_mul_cancel, mul_assoc, lt_mul_iff_one_lt_right $ h t, ←pow_succ'], exact one_lt_pow hp.one_lt a.succ_ne_zero, exact hpk end @[to_additive] lemma exponent_eq_supr_order_of' : exponent G = if ∃ g : G, order_of g = 0 then 0 else ⨆ g : G, order_of g := begin split_ifs, { obtain ⟨g, hg⟩ := h, exact exponent_eq_zero_of_order_zero hg }, { have := not_exists.mp h, exact exponent_eq_supr_order_of (λ g, ne.bot_lt $ this g) } end end comm_monoid section cancel_comm_monoid variables [cancel_comm_monoid G] @[to_additive] lemma exponent_eq_max'_order_of [fintype G] : exponent G = ((@finset.univ G _).image order_of).max' ⟨1, by simp⟩ := begin rw [←finset.nonempty.cSup_eq_max', finset.coe_image, finset.coe_univ, set.image_univ, ← supr], exact exponent_eq_supr_order_of order_of_pos end end cancel_comm_monoid end monoid section comm_group open subgroup open_locale big_operators variables (G) [comm_group G] [group.fg G] @[to_additive] lemma card_dvd_exponent_pow_rank : nat.card G ∣ monoid.exponent G ^ group.rank G := begin obtain ⟨S, hS1, hS2⟩ := group.rank_spec G, rw [←hS1, ←fintype.card_coe, ←finset.card_univ, ←finset.prod_const], let f : (Π g : S, zpowers (g : G)) →* G := noncomm_pi_coprod (λ s t h x y hx hy, mul_comm x y), have hf : function.surjective f, { rw [←monoid_hom.range_top_iff_surjective, eq_top_iff, ←hS2, closure_le], exact λ g hg, ⟨pi.mul_single ⟨g, hg⟩ ⟨g, mem_zpowers g⟩, noncomm_pi_coprod_mul_single _ _⟩ }, replace hf := nat_card_dvd_of_surjective f hf, rw nat.card_pi at hf, refine hf.trans (finset.prod_dvd_prod_of_dvd _ _ (λ g hg, _)), rw ← order_eq_card_zpowers', exact monoid.order_dvd_exponent (g : G), end @[to_additive] lemma card_dvd_exponent_pow_rank' {n : ℕ} (hG : ∀ g : G, g ^ n = 1) : nat.card G ∣ n ^ group.rank G := (card_dvd_exponent_pow_rank G).trans (pow_dvd_pow_of_dvd (monoid.exponent_dvd_of_forall_pow_eq_one G n hG) (group.rank G)) end comm_group
\documentclass[9pt,pdftex]{beamer} \usepackage{amsmath, amsthm, amssymb} \usepackage{color} \usepackage{hyperref} \usepackage{subfigure} \usepackage{tabularx} \usepackage{ragged2e} \usepackage{booktabs} \usepackage{multirow} \usepackage{natbib} \usecolortheme{dolphin} \linespread{1.3} \definecolor{nblue}{RGB}{0,0,128} \bibliographystyle{ecta} \setbeamercovered{transparent} \newcolumntype{Y}{>{\RaggedRight\arraybackslash}X} %\setbeamerfont{alerted text}{series=\bfseries} \hypersetup{colorlinks=true, linkcolor=nblue, citecolor=nblue, urlcolor=nblue, bookmarks=false, pdfpagemode=UseNone, pdfstartview={XYZ null null 1.25}, pdftitle={Quantifying the Losses from International Trade}, pdfauthor={Spencer G. Lyon, Michael E. Waugh}, pdfkeywords={economics, trade, dynamics, quant econ, lyon, waugh, incomplete markets, taxes, redistribution, progressivity, inequality, Ricardo, julia, migration, taxation, social insurance, China, global savings glut}} \setbeamertemplate{navigation symbols}{} \setbeamertemplate{footline}[frame number] \setbeamertemplate{theorems}[numbered] \setbeamertemplate{itemize subitem}[circle] \setbeamertemplate{enumerate items}[default] \setbeamerfont{frametitle}{size= \large} \setbeamerfont{ framesubtitle }{size = \footnotesize} \setbeamertemplate{frametitle} { \medskip \smallskip {\textsf{\underline{\insertframetitle\phantom{))))))))}}}}} \setbeamertemplate{items}[circle] \setbeamertemplate{itemize subitem}[circle] \theoremstyle{definition} \newtheorem{as}{Assumption} \newtheorem{df}{Definition} \newtheorem{lm}{Lemma} \newtheorem{prp}{Proposition} \usepackage[normalem]{ulem} \newcommand\redout{\bgroup\markoverwith {\textcolor{red}{\rule[.5ex]{1pt}{1pt}}}\ULon} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \title{\Large The Welfare Consequences of International Trade\\ and Policy Responses} \institute[Foo and Bar]{\normalsize\begin{tabular}[h]{c} Michael E. Waugh \\ NYU and NBER \end{tabular}} \date{\today} \begin{document} %\begin{frame} %\titlepage %\setcounter{framenumber}{0} %\section{} %\end{frame} % % %\begin{frame}[t] %\vspace{-.5cm} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.55]{wsj_photo.pdf}} % %\end{figure} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t]{Today's Talk} %Background evidence on trade exposure and its effects.\\ %\bigskip %Overview of work I've done with Spencer Lyon (Stern 2018 PhD) which essentially asks two questions\ldots\\ %\medskip %\textbf{1.} \textbf{\textcolor{red}{How Much Do the Losers Lose From Trade?}} %\begin{itemize} %\item From our paper ``Quantifying the Losses from International Trade'' %\end{itemize} %\bigskip %\textbf{2.} \textbf{\textcolor{red}{Should a nation's tax system be more progressive as it opens to trade?}} %\begin{itemize} %\item From our paper ``Redistributing the Gains From Trade through Progressive Taxation'' %\end{itemize} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame} %\vspace{1cm} %\begin{center} %\textbf{\textcolor{blue}{\large Background Evidence}} %\end{center} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{US Data: Rising Import Penetration\ldots Almost all from China} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/us_imports.pdf}} % %\end{figure} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{US Data: Deteriorating Trade Deficit} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/us_trade_deficit.pdf}} %\end{figure} %\end{frame} % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{ADH Evidence: Trade Exposure $\Rightarrow$ Bad Labor Market Outcomes} %\footnotesize %\begin{table}[t] %\setlength {\tabcolsep}{2.5mm} %\renewcommand{\arraystretch}{2.00} %\begin{center} %\begin{tabular}{l c c c} %\multicolumn{4}{c}{\normalsize \textbf{Labor Market Outcomes and Trade Exposure}}\\ %\hline %\hline %& \small $\Delta$ Labor Earnings & \small $\Delta$ NILF & \small $\Delta$ Population\\ %\cmidrule(lr){2-4} % \small Standardized $\Delta$ IPW & $\begin{array}{c}-4.30 \vspace{-.45cm}\\ \scriptstyle [-6.62, \ \ -2.00 ]\end{array}$ & $\begin{array}{c}1.11 \vspace{-.45cm}\\ \scriptstyle [0.52 ,\ \ 1.72 ]\end{array}$ & $\begin{array}{c}-1.43 \vspace{-.45cm}\\ \scriptstyle [-3.33 ,\ \ 0.48]\end{array}$\\ %\hline %\end{tabular} %\parbox[c]{4.0in}{\vspace{.2cm} %{\scriptsize \textbf{Note:} Values in brackets report 95-5 confidence intervals. $\Delta$ Labor Earnings is average household ``wage and salary`` income per adult; units are in decadal, percent changes. $\Delta$ NILF corresponds to the change in the not in labor force share. $\Delta$ IPW is standardized by neting out the mean and dividing by the standard deviation.}} %\end{center} %\bigskip %\end{table} %\end{frame} %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% %%\begin{frame}[t] %%\frametitle{Trade Exposure $\Rightarrow$ Limited Migration} %%\footnotesize %%\begin{table}[t] %%\setlength {\tabcolsep}{2.5mm} %%\renewcommand{\arraystretch}{2.00} %%\begin{center} %%%\textbf{\caption{ADH and GLM Evidence: Migration and Trade Exposure}\label{tb:glm_fact}} %% \vspace{0.3cm} %%\begin{tabular}{l c c} %%\multicolumn{3}{c}{\normalsize \textbf{Migration and Trade Exposure}}\\ %%\hline %%\hline %%& \small ADH $\Delta$ Population & \small GLM, $\Delta$ Population \\ %%\cmidrule(lr){2-3} %% \small Standardized $\Delta$ IPW & $\begin{array}{c}-0.05 \vspace{-.45cm}\\ \scriptstyle [-1.51 ,\ \ 1.41 ]\end{array}$ & $\begin{array}{c}-1.43 \vspace{-.45cm}\\ \scriptstyle [-3.33 ,\ \ 0.48]\end{array}$\\ %%\hline %%\end{tabular} %%\parbox[c]{3.5in}{\vspace{.1cm} %%{\footnotesize \textbf{Note:} Values in brackets report 95-5 confidence intervals. \citet{greenland2017import} (GLM) replace ADH regional controls with agged population growth at the commute zone level.}} %%\end{center} %%\bigskip %%\end{table} %%\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame} %\vspace{1cm} %\begin{center} %\textbf{\textcolor{blue}{\large Lyon and Waugh (2018): ``Quantifying the Losses from International Trade''}} %\end{center} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t]{High-level Overview of Model\ldots} %A bunch of labor markets on which %\begin{itemize} %\item Households who live within that labor market, %\smallskip %\item Competitive producers on an island produce a differentiated good, %\smallskip %\item Producers are subject local and world productivity shocks. %\end{itemize} %\smallskip %Shocks $+$ actions of households determine the pattern of comparative advantage and, thus, a labor market's trade exposure. \\ %\bigskip % %Households have some options\ldots %\begin{itemize} %\item Work or not %\smallskip %\item Stay or move to a new labor market, at some cost. %\smallskip %\item Consume and save or borrow in a simple risk free asset. %\end{itemize} % %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{Model Matches Aggregate $\Delta$ in Trade} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/us_imports_model.pdf}} %\end{figure} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t]{Model Matches Micro Evidence} %\footnotesize %\begin{table}[!t] %\setlength {\tabcolsep}{0.95mm} %\renewcommand{\arraystretch}{2.00} %\begin{center} %%\textbf{\caption{Calibration: Micro Moments and Parameters}\label{ta:cal_micro}} % \vspace{0.3cm} %\begin{tabular}{l c c c} %\hline %\hline %& \small $\Delta$ Labor Earnings & \small $\Delta$ NILF & \small GLM $\Delta$ Population \\ %\cmidrule(lr){2-4} % \small Data & $\begin{array}{c}-4.30 \vspace{-.45cm}\\ \scriptstyle [-6.62, \ \ -2.00 ]\end{array}$ & $\begin{array}{c}1.11 \vspace{-.45cm}\\ \scriptstyle [0.52 ,\ \ 1.72 ]\end{array}$ & $\begin{array}{c}-1.43 \vspace{-.45cm}\\ \scriptstyle [-3.33 ,\ \ 0.48]\end{array}$\\ % \small Model & $\begin{array}{c}-4.10\end{array}$ & $\begin{array}{c}1.24\end{array}$ & $\begin{array}{c}-1.92\end{array}$\\ %\cmidrule(lr){2-4} %& \small Demand elasticity $\theta$ & \small Home production $w_h$ & \small $\nu$ shock $\sigma_{\nu}$\\ %\small Parameter Values & $\begin{array}{c}10.15\end{array}$ & $\begin{array}{c}0.20\end{array}$ & $\begin{array}{c}0.96\end{array}$\\ %\hline %\end{tabular} %\parbox[c]{4.15in}{\vspace{.1cm} %{\footnotesize \textbf{Note:} Values in brackets report 95-5 confidence intervals. \citet{greenland2017import} (GLM) replace ADH regional controls with lagged population growth at the commute zone level. }} %\end{center} %\end{table} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{Surprise I: Trade with China Generated a BOOM!} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/cons_labor_model_no_R8.pdf}} %\end{figure} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{Surprise II: Trade with China IMPROVED the Trade Deficit!} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/us_deficit_model_no_R8.pdf}} %\end{figure} %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t]{Surprise III: Harsh Labor Market; Welfare? Most Gain, Few Loose} %\footnotesize %\begin{table}[t] %\setlength {\tabcolsep}{1.25mm} %\renewcommand{\arraystretch}{2.00} %\begin{center} %\begin{tabular}{l l c c} %\multicolumn{4}{c}{\textbf{\normalsize Welfare and Real Wages}}\\ %\hline %\hline %&& Welfare & $\Delta$ Log Wages \\ %\cmidrule(lr){3-4} %\multirow{4}{*}{\rotatebox{90}{Initial Exposure}} &Import Exposed & $\begin{array}{c}0.18 \vspace{-.45cm}\\ \scriptstyle [ \ 0.07 \ ]\end{array}$ & $\begin{array}{c}-2.32\vspace{-.45cm}\\ \scriptstyle \phantom{-}[ \ 0.07 \ ]\end{array}$ \\ %&Non-Traded & $\begin{array}{c}0.74 \vspace{-.45cm}\\ \scriptstyle [ \ 0.68 \ ]\end{array}$ & $\begin{array}{c}\phantom{-}0.23\vspace{-.45cm}\\ \scriptstyle \phantom{-}[ \ 0.68 \ ]\end{array}$\\ %&Export Exposed & $\begin{array}{c}1.65\vspace{-.45cm}\\ \scriptstyle [ \ 0.25 \ ]\end{array}$ & $\begin{array}{c}\phantom{-}4.38 \vspace{-.45cm}\\ \scriptstyle \phantom{-}[ \ 0.25\ ]\end{array}$\\ %\hline %&Average & 0.94 & 0.94 \\ %\hline %\end{tabular} %\parbox[c]{2.15in}{\vspace{.1cm} %{\footnotesize \textbf{Note:} Welfare values are lifetime consumption equivalents; values in brackets report the initial share of the population in that category.}} %\end{center} %\end{table} % %\end{frame} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %\begin{frame}[t] %\frametitle{Surprise III: Most Gain, Few Loose} %\begin{figure}[t] %\centerline{\includegraphics[scale = 0.50]{../../figures/welfare_trade_shock.pdf}} %\end{figure} %\end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame} \vspace{1cm} \begin{center} \textbf{\textcolor{blue}{\large Lyon and Waugh (2018): ``Redistributing the Gains From Trade through Progressive Taxation''}} \end{center} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t]{High-level Overview of Model\ldots} A bunch of labor markets on which \begin{itemize} \item Households who live within that labor market, \smallskip \item Competitive producers on an island produce a differentiated good, \smallskip \item Producers are subject local and world productivity shocks. \end{itemize} \smallskip Shocks $+$ actions of households determine the pattern of comparative advantage and, thus, a labor market's trade exposure. \\ \bigskip Households have some options\ldots \begin{itemize} \item Work or not \smallskip \item Stay or move to a new labor market, at some cost. \smallskip \item Consume and save or borrow in a simple risk free asset. \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t]{Everything A-OK? \ Not quite.} In our model, the competitive equilibrium does not correspond with the socially optimal outcome.\\ \begin{itemize} \item Households would like insurance against privately uninsurable shocks. \smallskip \item Some of these shocks are trade related, so tariffs might help! \begin{itemize} \smallskip \item \small \citet{Corden_74}, \citet{baldwin1982political}, \citet{newbery1984pareto}, \citet{Eaton85}, \citet{dixit1987trade, Dixit_89, dixit1989trade}. \end{itemize} \end{itemize} \bigskip Our idea: Rather than use tariffs, use the tax system. \begin{itemize} \item That is, the government could use a progressive tax system to provide social insurance. \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t]{Use Progressive Taxation to Insure the Losers from Trade?} One motive for progressive taxation: provide social insurance for privately uninsurable shocks (possibly trade related). \begin{itemize} \item \citet{varian1980redistributive} and \citet{eaton1980optimal}. \end{itemize} \bigskip But theses polices come with costs\ldots \begin{itemize} \item Reductions in labor supply; reductions in migration\ldots \smallskip \item $\Rightarrow$ Losses in economic efficiency. \end{itemize} \bigskip Our question:\\ \smallskip \textbf{How does openness to trade change this cost-benefit calculation?} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t] \frametitle{Social Welfare and Progressivity} \begin{figure}[t] \centerline{\includegraphics[scale = 0.50]{C:/github/TradeExposure/figures/social_welfare_baseline.pdf}} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t] \frametitle{Optimal Progressivity Increases with Openness!} \begin{figure}[t] \centerline{\includegraphics[scale = 0.53]{C:/github/TradeExposure/figures/social_welfare_prog_diff_tau_fine.pdf}} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t] \frametitle{Optimal Progressivity Increases with Openness!} \begin{table}[t] \small \setlength {\tabcolsep}{1.25mm} \renewcommand{\arraystretch}{1.5} \begin{center} \begin{tabular}{c c c c c c} \multicolumn{6}{c}{\textbf{\normalsize Openness and Optimal Progressivity }}\\ \hline \hline & & \multicolumn{2}{c}{Welfare} &\multicolumn{2}{c}{$\Delta$ Marginal Tax Rate} \\ Imports/GDP & \small $\tau_p^*$ & \small Gains from $\tau_p^*$ & \small Losses from Flat & 90th Prct. & 10th Prct.\\ \cmidrule(lr){3-4} \cmidrule(lr){5-6} 0.10 & 0.27 & 0.10 & -0.83& --- & --- \\ 0.20 & 0.32 & 0.34 & -1.39& 4.8 & -1.5 \\ 0.30 & 0.37 & 0.72 & -1.94& 8.8 & -1.9 \\ 0.40 & 0.45 & 1.38 & -2.62& 15.5 & -3.2 \\ \hline \end{tabular} \parbox[c]{4in}{\vspace{.1cm} {\footnotesize \textbf{Note:} 90th Prct is the 90th percentile of the labor income distribution; 10th is the 10th percentile. Gains are consumption equivalent values between living in the baseline economy and an economy with an alternative progressivity parameter $\tau_p^*$.} } \end{center} \end{table} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t] \frametitle{Are Tariffs Welfare Improving? No} \vspace{-.56cm} \begin{figure}[p] \centerline{\includegraphics[scale = 0.48]{C:/github/TradeExposure/figures/tariff_low_trade.pdf}} \end{figure} \small \vspace{-1.0cm} \textbf{This Economy, Imports/GDP = 0.20} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\begin{frame}[t] %\frametitle{Are Tariffs Welfare Improving? No} %\vspace{-.56cm} %\begin{figure}[p] %\centerline{\includegraphics[scale = 0.48]{../../figures/tariff_high_trade.pdf}} %\end{figure} %\small %\vspace{-1.0cm} %\textbf{This Economy, Imports/GDP = 0.40} %\end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[t]{Final Thoughts} Hard to deny that the benefits of globalization have been under attack\ldots\\ And motivating this attack is the idea that trade has imposed hardship on some segments of the population.\\ \bigskip The goals of our work are too\ldots \begin{itemize} \item Understand and evaluate these hardships in an interpretable way \smallskip \item Provide sensible policy responses. \end{itemize} \bigskip \smallskip Bonus idea: Concerns about automation are directly related to our work. \begin{itemize} \item Like trade, automation is a labor saving technology that helps many, but harms those exposed to it. \smallskip \item Increasing progressivity as automation increases may improve welfare. \end{itemize} \bigskip \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \appendix \newcounter{finalframe} \setcounter{finalframe}{\value{framenumber}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[allowframebreaks] \frametitle{References} \footnotesize \bibliography{C:/github/TradeExposure/BIB/micro_price_bibtex} \end{frame} \end{document}
Formal statement is: lemma subset_translation_eq [simp]: fixes a :: "'a::real_vector" shows "(+) a ` s \<subseteq> (+) a ` t \<longleftrightarrow> s \<subseteq> t" Informal statement is: For any real vector space $V$ and any $a \in V$, the set $a + S$ is a subset of $a + T$ if and only if $S$ is a subset of $T$.
[STATEMENT] lemma ex_gt_count_imp_le_multiset: "(\<forall>y :: 'a :: order. y \<in># M + N \<longrightarrow> y \<le> x) \<Longrightarrow> count M x < count N x \<Longrightarrow> M < N" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>y. y \<in># M + N \<longrightarrow> y \<le> x; count M x < count N x\<rbrakk> \<Longrightarrow> M < N [PROOF STEP] unfolding less_multiset\<^sub>H\<^sub>O [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>y. y \<in># M + N \<longrightarrow> y \<le> x; count M x < count N x\<rbrakk> \<Longrightarrow> M \<noteq> N \<and> (\<forall>y. count N y < count M y \<longrightarrow> (\<exists>x>y. count M x < count N x)) [PROOF STEP] by (metis count_greater_zero_iff le_imp_less_or_eq less_imp_not_less not_gr_zero union_iff)
[GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hab : a ≤ b hcd : c ≤ d ⊢ a * d + b * c ≤ a * c + b * d [PROOFSTEP] obtain ⟨b, rfl⟩ := exists_add_of_le hab [GOAL] case intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c d : α inst✝ : ExistsAddOfLE α hcd : c ≤ d b : α hab : a ≤ a + b ⊢ a * d + (a + b) * c ≤ a * c + (a + b) * d [PROOFSTEP] obtain ⟨d, rfl⟩ := exists_add_of_le hcd [GOAL] case intro.intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c : α inst✝ : ExistsAddOfLE α b : α hab : a ≤ a + b d : α hcd : c ≤ c + d ⊢ a * (c + d) + (a + b) * c ≤ a * c + (a + b) * (c + d) [PROOFSTEP] rw [mul_add, add_right_comm, mul_add, ← add_assoc] [GOAL] case intro.intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c : α inst✝ : ExistsAddOfLE α b : α hab : a ≤ a + b d : α hcd : c ≤ c + d ⊢ a * c + (a + b) * c + a * d ≤ a * c + (a + b) * c + (a + b) * d [PROOFSTEP] exact add_le_add_left (mul_le_mul_of_nonneg_right hab <| (le_add_iff_nonneg_right _).1 hcd) _ [GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hba : b ≤ a hdc : d ≤ c ⊢ a • d + b • c ≤ a • c + b • d [PROOFSTEP] rw [add_comm (a • d), add_comm (a • c)] [GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hba : b ≤ a hdc : d ≤ c ⊢ b • c + a • d ≤ b • d + a • c [PROOFSTEP] exact mul_add_mul_le_mul_add_mul hba hdc [GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hab : a < b hcd : c < d ⊢ a * d + b * c < a * c + b * d [PROOFSTEP] obtain ⟨b, rfl⟩ := exists_add_of_le hab.le [GOAL] case intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c d : α inst✝ : ExistsAddOfLE α hcd : c < d b : α hab : a < a + b ⊢ a * d + (a + b) * c < a * c + (a + b) * d [PROOFSTEP] obtain ⟨d, rfl⟩ := exists_add_of_le hcd.le [GOAL] case intro.intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c : α inst✝ : ExistsAddOfLE α b : α hab : a < a + b d : α hcd : c < c + d ⊢ a * (c + d) + (a + b) * c < a * c + (a + b) * (c + d) [PROOFSTEP] rw [mul_add, add_right_comm, mul_add, ← add_assoc] [GOAL] case intro.intro α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a c : α inst✝ : ExistsAddOfLE α b : α hab : a < a + b d : α hcd : c < c + d ⊢ a * c + (a + b) * c + a * d < a * c + (a + b) * c + (a + b) * d [PROOFSTEP] exact add_lt_add_left (mul_lt_mul_of_pos_right hab <| (lt_add_iff_pos_right _).1 hcd) _ [GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hba : b < a hdc : d < c ⊢ a • d + b • c < a • c + b • d [PROOFSTEP] rw [add_comm (a • d), add_comm (a • c)] [GOAL] α : Type u β : Type u_1 inst✝¹ : StrictOrderedSemiring α a b c d : α inst✝ : ExistsAddOfLE α hba : b < a hdc : d < c ⊢ b • c + a • d < b • d + a • c [PROOFSTEP] exact mul_add_mul_lt_mul_add_mul hba hdc [GOAL] α : Type u β : Type u_1 inst✝ : CanonicallyOrderedCommSemiring α a b : α ⊢ CovariantClass α α (fun x x_1 => x * x_1) fun x x_1 => x ≤ x_1 [PROOFSTEP] refine' ⟨fun a b c h => _⟩ [GOAL] α : Type u β : Type u_1 inst✝ : CanonicallyOrderedCommSemiring α a✝ b✝ a b c : α h : b ≤ c ⊢ a * b ≤ a * c [PROOFSTEP] rcases exists_add_of_le h with ⟨c, rfl⟩ [GOAL] case intro α : Type u β : Type u_1 inst✝ : CanonicallyOrderedCommSemiring α a✝ b✝ a b c : α h : b ≤ b + c ⊢ a * b ≤ a * (b + c) [PROOFSTEP] rw [mul_add] [GOAL] case intro α : Type u β : Type u_1 inst✝ : CanonicallyOrderedCommSemiring α a✝ b✝ a b c : α h : b ≤ b + c ⊢ a * b ≤ a * b + a * c [PROOFSTEP] apply self_le_add_right [GOAL] α : Type u β : Type u_1 inst✝ : CanonicallyOrderedCommSemiring α a b : α ⊢ 0 < a * b ↔ 0 < a ∧ 0 < b [PROOFSTEP] simp only [pos_iff_ne_zero, ne_eq, mul_eq_zero, not_or] [GOAL] α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (a * c) ⊢ a * (b - c) = a * b - a * c [PROOFSTEP] cases' total_of (· ≤ ·) b c with hbc hcb [GOAL] case inl α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (a * c) hbc : b ≤ c ⊢ a * (b - c) = a * b - a * c [PROOFSTEP] rw [tsub_eq_zero_iff_le.2 hbc, mul_zero, tsub_eq_zero_iff_le.2 (mul_le_mul_left' hbc a)] [GOAL] case inr α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (a * c) hcb : c ≤ b ⊢ a * (b - c) = a * b - a * c [PROOFSTEP] apply h.eq_tsub_of_add_eq [GOAL] case inr α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (a * c) hcb : c ≤ b ⊢ a * (b - c) + a * c = a * b [PROOFSTEP] rw [← mul_add, tsub_add_cancel_of_le hcb] [GOAL] α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (b * c) ⊢ (a - b) * c = a * c - b * c [PROOFSTEP] simp only [mul_comm _ c] at * [GOAL] α : Type u β : Type u_1 inst✝³ : CanonicallyOrderedCommSemiring α a b c : α inst✝² : Sub α inst✝¹ : OrderedSub α inst✝ : IsTotal α fun x x_1 => x ≤ x_1 h : AddLECancellable (c * b) ⊢ c * (a - b) = c * a - c * b [PROOFSTEP] exact h.mul_tsub
theory NielsonSchreier imports "UniversalProperty" "HOL.Nat" "Conjugacy" begin lemma one_list:"length xs = 1 \<Longrightarrow> \<exists>x. xs = [x]" by (metis Cons_eq_append_conv append_butlast_last_id le_numeral_extra(4) length_0_conv length_butlast subtract_greater zero_neq_one) lemma inverse_neq:"x \<noteq> inverse x" by (metis inverse.elims prod.inject) lemma red_repelem: assumes "w \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>))" shows "\<exists>x \<in> w. reduced x \<and> ((reln_tuple \<langle>S\<rangle>)`` {x} = w)" proof- obtain c where c: "w = (reln_tuple \<langle>S\<rangle>) `` {c}" by (meson assms quotientE) then have cs: "c \<in> \<langle>S\<rangle>" using assms by (metis proj_def proj_in_iff reln_equiv) obtain rc where rc: "rc = (iter (length c) reduce c)" by simp then have "reduced rc" by (simp add: reduced_iter_length) then have "c ~ rc" using rc cancels_imp_rel iter_cancels_to by auto moreover then have "rc \<in> \<langle>S\<rangle>" using cs rc using cancels_to_preserves iter_cancels_to by blast ultimately have crc: "(c, rc) \<in> reln_tuple \<langle>S\<rangle>" using cs reln_tuple_def by auto then have "((reln_tuple \<langle>S\<rangle>)`` {rc} = w)"using c by (smt (verit, ccfv_SIG) equiv_class_eq_iff reln_equiv) moreover then have "rc \<in> w" using c crc by simp ultimately show ?thesis using \<open>reduced rc\<close> by auto qed lemma redelem_unique : assumes "w \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>))" shows "\<exists>!x \<in> w. reduced x \<and> ((reln_tuple \<langle>S\<rangle>)`` {x} = w)" proof(rule classical) assume 1:"\<not>(\<exists>!x \<in> w. reduced x \<and> ((reln_tuple \<langle>S\<rangle>)`` {x} = w))" have "\<exists>x \<in> w. reduced x \<and> ((reln_tuple \<langle>S\<rangle>)`` {x} = w)" using assms red_repelem by auto then obtain x where x:"x \<in> w \<and> reduced x" by auto obtain y where y:"(y \<in> w \<and> reduced y \<and> (reln_tuple \<langle>S\<rangle>)`` {x} = w) \<and> y \<noteq> x " using 1 x by (smt (verit, best) assms equiv_class_eq_iff equiv_class_self quotientE quotient_eq_iff reln_equiv) then have "(x, y) \<in> reln_tuple \<langle>S\<rangle>" using x y by blast then have "x ~ y" using reln_tuple_def by auto then have "y = x" using x y 1 reduced_cancel_eq reln_imp_cancels by blast moreover then have "(reln_tuple \<langle>S\<rangle>)`` {x} = (reln_tuple \<langle>S\<rangle>)`` {y}" by simp ultimately have False by (simp add: y) then show "\<exists>!x \<in> w. reduced x \<and> ((reln_tuple \<langle>S\<rangle>)`` {x} = w)" by simp qed definition red_rep :: "('a, 'b) monoidgentype set \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a, 'b) word" where "red_rep S w = (THE x. x \<in> w \<and> reduced x \<and> (w = reln_tuple \<langle>S\<rangle> `` {x}))" lemma red_rep_the: assumes "w \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>))" shows "((red_rep S w) \<in> w) \<and> reduced ((red_rep S w)) \<and> (w = reln_tuple \<langle>S\<rangle> `` {(red_rep S w)})" unfolding red_rep_def proof(rule theI') show "\<exists>!x. x \<in> w \<and> reduced x \<and> w = reln_tuple \<langle>S\<rangle> `` {x}" using redelem_unique[of "w" "S"] assms by metis qed lemma equivred_equiv: assumes "w \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>))" shows "\<forall>x\<in>w. (reln_tuple \<langle>S\<rangle>) `` {x} = (reln_tuple \<langle>S\<rangle>) `` {red_rep S w}" proof- obtain x where x:"x \<in> w" using assms red_repelem by auto then have xs: "x \<in> \<langle>S\<rangle>" using append_congruent assms equiv_2f_clos reln_equiv rightappend_span freewords_on_def by fastforce have rw: "red_rep S w \<in> w" using x red_rep_def redelem_unique red_rep_the assms by blast then have rs: "red_rep S w \<in> \<langle>S\<rangle>" using assms by (meson quotient_eq_iff refl_onD1 reln_equiv reln_refl) then have "(x,red_rep S w)\<in>(reln_tuple \<langle>S\<rangle>)" using xs x rs rw by (meson assms quotient_eq_iff reln_equiv) then have "(reln_tuple \<langle>S\<rangle>) `` {x} = (reln_tuple \<langle>S\<rangle>) `` {red_rep S w}" by (meson equiv_class_eq_iff reln_equiv) then show ?thesis using x assms by (smt (verit, best) equiv_class_eq_iff quotient_eq_iff reln_equiv) qed definition equivinv :: "('a, 'b) monoidgentype set \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a, 'b) word set" where "equivinv S w = (reln_tuple \<langle>S\<rangle> `` {wordinverse (red_rep S w)})" (* definition equal_equiv where "equal_equiv S x y = (red_rep S x = red_rep S y)" definition inv_equiv where "inv_equiv S x y = (x = equivinv S y)" fun nielson_reln :: "('a, 'b) monoidgentype set \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a, 'b) word set \<Rightarrow> bool" where "nielson_reln S x y = (equal_equiv S x y \<or> inv_equiv S x y)" definition nielson_set :: "('a, 'b) monoidgentype set \<Rightarrow>(('a,'b) word \<times> ('a,'b) word) set" where "nielson_set S = {(w,z). \<exists>x y . x \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>)) \<and> w = red_rep S x \<and> y \<in> (\<langle>S\<rangle> // (reln_tuple \<langle>S\<rangle>)) \<and> z = red_rep S y \<and> nielson_reln S x y}" lemma refl_nielson : "\<forall> x. nielson_reln S x x" using nielson_reln.simps equal_equiv_def by blast lemma sym_nielson : "\<forall> x y. nielson_reln S x y \<Longrightarrow> nielson_reln S y x" using nielson_reln.simps equal_equiv_def by blast lemma trans_nielson : "\<forall> x y z. nielson_reln S x y \<Longrightarrow> nielson_reln S y z \<Longrightarrow> nielson_reln S x z" using nielson_reln.simps equal_equiv_def by blast fun compare :: "(('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow>('a, 'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> bool" where "compare r x y = (if x = [] \<or> ((hd x \<noteq> hd y) \<and> (hd x, hd y) \<in> r) then True else (if \<not>((hd x \<noteq> hd y) \<and> (hd y, hd x) \<in> r) then compare r (tl x) (tl y) else False))" fun compare_alt :: "(('a, 'b) groupgentype \<times> ('a, 'b) groupgentype) set \<Rightarrow> ('a, 'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> bool" where "compare_alt r x y = (x = y \<or> (\<exists> a b c. x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r))" definition compare_set where "compare_set A r = {(x, y). x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> compare r x y }" lemma refl_compare : assumes "well_order_on (invgen A) r"v shows "\<forall> x \<in> \<langle>A\<rangle>. compare r x x" proof fix x assume "x \<in> \<langle>A\<rangle>" then show "compare r x x" proof (induction x) case Nil then show ?case by simp next case (Cons a x) have "x \<in> \<langle>A\<rangle>" using Cons.prems span_cons freewords_on_def by blast then have "compare r (tl (a # x)) (tl (a # x))" using compare.simps using Cons.IH \<open>x \<in> \<langle>A\<rangle>\<close> by auto then show ?case by simp qed qed lemma reflon_comp : assumes "well_order_on (invgen A) r" shows "refl_on \<langle>A\<rangle> (compare_set A r)" proof- have "\<forall>(x,y) \<in> (compare_set A r). x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle>" using compare_set_def using Pair_inject by blast then have "(compare_set A r) \<subseteq> (\<langle>A\<rangle> \<times> \<langle>A\<rangle>)" using compare_set_def by auto moreover have "\<forall> x \<in> \<langle>A\<rangle>. compare r x x" using assms refl_compare by blast moreover have "(\<forall> x \<in> \<langle>A\<rangle>. (x, x) \<in> (compare_set A r))" using compare_set_def using calculation(2) by blast ultimately show ?thesis using refl_on_def by blast qed lemma comp_compalt : assumes "length x = length y" and "well_order_on (invgen S) r" and "x \<in> \<langle>S\<rangle>" and "y \<in> \<langle>S\<rangle>" and "compare r x y" shows "compare_alt r x y" using assms proof(induct x y rule: compare.induct) case (1 r x y) then show ?case proof(cases "x = []") case True then have "x = y" using "1.prems"(1) by auto then show ?thesis by auto next case False then show ?thesis proof(cases "hd x = hd y") case True then have T2: "hd x = hd y" by simp have y:"y \<noteq> []" using False "1.prems"(1) by auto then have A:"(\<not> (x = [] \<or> hd x \<noteq> hd y \<and> (hd x, hd y) \<in> r))" using False True by simp moreover have "\<not> (hd x \<noteq> hd y \<and> (hd y, hd x) \<in> r)" by (simp add: True) moreover have "length (tl x) = length (tl y)" using False "1.prems"(1) by auto moreover have "(tl x) \<in> \<langle>S\<rangle>" using False "1.prems"(3) span_cons freewords_on_def by (metis list.exhaust_sel) moreover have "(tl y) \<in> \<langle>S\<rangle>" using y "1.prems"(4) span_cons freewords_on_def by (metis list.exhaust_sel) moreover have "compare r x y = compare r (tl x) (tl y)" using True False y by simp ultimately have tlc:"compare_alt r (tl x) (tl y)" using "1.hyps" "1.prems"(2) "1.prems"(5) by blast then show ?thesis proof(cases "(tl x) = (tl y)") case True have "x = y" using T2 by (simp add: True False list.expand y) then show ?thesis by auto next case False then obtain a b c where "tl x = (a @ b) \<and> tl y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using tlc by auto then have "x = (hd x#(a @ b)) \<and> y = (hd x#(a @ c)) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using T2 by (metis A list.exhaust_sel y) then have "x = ((hd x#a) @ b) \<and> y = ((hd x#a) @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" by auto then show ?thesis using compare_alt.simps by blast qed next case False then have F2:"hd x \<noteq> hd y" by simp then show ?thesis proof(cases "(hd x, hd y) \<in> r") case True then have "x = ([] @ x) \<and> y = ([] @ y) \<and> (hd x) \<noteq> (hd y) \<and> (hd x, hd y) \<in> r" using False True by simp then show ?thesis using compare_alt.simps by force next case False have "hd x \<in> (invgen S)" using "1.prems"(3) by (metis "1.prems"(1) F2 append_eq_append_conv append_self_conv2 gen_spanset freewords_on_def) moreover have "hd y \<in> (invgen S)" using "1.prems"(4) by (metis "1.prems"(1) F2 append_eq_append_conv append_self_conv gen_spanset freewords_on_def) ultimately have "(hd y, hd x) \<in> r" using False F2 "1.prems"(2) unfolding well_order_on_def linear_order_on_def total_on_def by blast then have "compare r x y = False" using F2 "1.prems"(1) False by force then show ?thesis using "1.prems"(5) by blast qed qed qed qed lemma compare_subword: assumes "length x = length y" and "well_order_on (invgen S) r" and "x \<in> \<langle>S\<rangle>" and "y \<in> \<langle>S\<rangle>" and "a \<in> \<langle>S\<rangle>" shows "compare r (a@x) (a@y) = compare r x y" using assms proof(induction "(a@x)" "(a@y)" arbitrary: a rule: compare.induct) case (1 r) then show ?case proof(cases "a = []") case True then show ?thesis by simp next case False have A:"hd (a @ x) = hd (a @ y)" using False by simp moreover then have "\<not> (a @ x = [] \<or> hd (a @ x) \<noteq> hd (a @ y) \<and> (hd (a @ x), hd (a @ y)) \<in> r)" by (simp add: False) moreover then have "\<not> (hd (a @ x) \<noteq> hd (a @ y) \<and> (hd (a @ y), hd (a @ x)) \<in> r)" by (simp add: A) moreover have B:"tl (a @ x) = (tl a) @ x" by (simp add: False) moreover have C:"tl (a @ y) = (tl a) @ y" by (simp add: False) moreover have "tl a \<in> \<langle>S\<rangle>" using "1.prems" span_cons freewords_on_def False by (metis list.collapse) ultimately have "compare r ((tl a) @ x) ((tl a) @ y) = compare r x y" using "1.hyps" "1.prems"(2) assms(1) assms(3) assms(4) by presburger then have "compare r (tl (a @ x)) (tl (a @ y)) = compare r x y" using B C by presburger moreover have "compare r (tl (a @ x)) (tl (a @ y)) = compare r (a @ x) (a @ y)" by (simp add: A) ultimately show ?thesis by blast qed qed lemma compalt_comp : assumes "length x = length y" and "well_order_on (invgen S) r" and "x \<in> \<langle>S\<rangle>" and "y \<in> \<langle>S\<rangle>" and "compare_alt r x y" shows "compare r x y" using assms proof(cases "x=y") case True then show ?thesis using refl_compare assms(1) assms(2) assms(4) by metis next case False then have "(\<exists>a b c. x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r)" using assms(5) by auto then obtain a b c where "x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and>(hd b, hd c) \<in> r" by blast moreover have "b \<in> \<langle>S\<rangle>" using assms(3) freewords_on_def using calculation rightappend_span by blast moreover have "c \<in> \<langle>S\<rangle>" using assms(4) freewords_on_def using calculation rightappend_span by blast moreover have "compare r b c" by (simp add: calculation(1)) moreover have "compare r x y = compare r b c" using compare_subword by (metis add_left_imp_eq assms(1) assms(2) assms(4) calculation(1) calculation(2) calculation(3) leftappend_span length_append freewords_on_def) ultimately show ?thesis by blast qed lemma antisym_compare : assumes "well_order_on (invgen A) r" shows "(\<forall>x y. (length x = length y) \<longrightarrow> (x, y) \<in> compare_set A r \<longrightarrow> (y, x) \<in> compare_set A r \<longrightarrow> x = y)" apply (rule allI)+ apply (rule impI)+ proof- fix x y assume l: "length x = length y" and xy: "(x, y) \<in> compare_set A r" and yx: "(y, x) \<in> compare_set A r" then show "x = y" using assms proof(induct x y rule : compare.induct) case (1 r x y) then show ?case proof (cases "x = []") case True have "y = []" using "1.prems"(1) True by auto then show ?thesis using True by simp next case False then show ?thesis proof (cases "hd x = hd y") case True have a: "x \<noteq> []" using False by simp then have b: "y \<noteq> []" using 1 by auto have "x \<in> \<langle>A\<rangle>" using "1.prems"(2) unfolding compare_set_def by simp then have tlx:"tl x \<in> \<langle>A\<rangle>" using a freewords_on_def span_cons by (metis list.collapse) have "y \<in> \<langle>A\<rangle>" using "1.prems"(2) unfolding compare_set_def by simp then have tly:"tl y \<in> \<langle>A\<rangle>" using b freewords_on_def span_cons by (metis list.collapse) have "compare r x y" using "1.prems"(2) unfolding compare_set_def by blast then have rxy: "compare r (tl x) (tl y)" using True by (simp add: a) have c:"((tl x), (tl y)) \<in> compare_set A r" using tlx tly rxy unfolding compare_set_def by blast have "compare r y x" using "1.prems"(3) unfolding compare_set_def by blast then have ryx:"compare r (tl y) (tl x)" using True by (simp add: b) have d:"((tl y), (tl x)) \<in> compare_set A r" using tlx tly ryx unfolding compare_set_def by blast have "length x = length y" using 1 by auto then have "length (tl x) = length (tl y)" using a b by fastforce then have "(tl x) = (tl y)" using 1 a b True c d by blast then show ?thesis using True using a b list.expand by blast next case False then have A: "hd x \<noteq> hd y" by simp have "x \<in> \<langle>A\<rangle>" using "1.prems"(2) unfolding compare_set_def by simp then have B:"hd x \<in> (invgen A)" by (metis "1.prems"(1) False append.left_neutral append_eq_append_conv gen_spanset freewords_on_def) have "y \<in> \<langle>A\<rangle>" using "1.prems"(2) unfolding compare_set_def by simp then have C:"hd y \<in> (invgen A)" by (metis "1.prems"(1) False append_eq_append_conv append_self_conv2 gen_spanset freewords_on_def) then show ?thesis proof(cases "(hd x, hd y) \<in> r") case True then have D: "(hd x, hd y) \<in> r" by simp then show ?thesis proof(cases "(hd y, hd x) \<in> r") case True have "(\<forall>x y. (x, y) \<in> r \<longrightarrow> (y, x) \<in> r \<longrightarrow> x = y)" using "1.prems"(4) unfolding well_order_on_def linear_order_on_def partial_order_on_def antisym_def by blast then have "hd x = hd y" using D True by blast then show ?thesis using A by blast next case False then have "compare r y x = False" using A using "1.prems"(1) True by auto then have "(y, x) \<notin> compare_set A r" unfolding compare_set_def by simp then show ?thesis using "1.prems"(3) by simp qed next case False then have "(hd y, hd x) \<in> r" using A B C "1.prems"(4) unfolding well_order_on_def linear_order_on_def total_on_def by auto then have "compare r x y = False" using A using "1.prems"(1) False by auto then have "(x, y) \<notin> compare_set A r" unfolding compare_set_def by simp then show ?thesis using "1.prems"(2) by simp qed qed qed qed qed lemma eq_lenless: assumes "(a @ b = c @ d)" and "length a \<le> length c" shows "\<exists>x. c = a@x" proof(rule classical) assume 1: "\<not>(\<exists>x. c = a@x)" then have "\<nexists>x. c = a@x" by auto then have "length a \<ge> length c" using assms(2) by (metis append_eq_append_conv2 append_eq_append_conv_if append_take_drop_id assms(1)) then have "length a = length c" using assms(2) by simp then have "c = a @ []" using assms(1) by auto then have False using "1" by auto then show "\<exists>x. c = a@x" by auto qed lemma eq_lengr : assumes "(a @ b = c @ d)" and "length a > length c" shows "\<exists>s. a = (c @ s)" proof(rule classical) assume 1: "(\<not> (\<exists>s. a = (c @ s)))" then have "\<nexists>s. a = (c@s)" by auto then have "length a \<le> length c" using assms(2) by (metis assms(1) eq_lenless nat_le_linear) then have "length a = length c" using assms(2) by simp then have "a = (c@[])" using assms(2) nat_neq_iff by blast then have False using 1 by simp then show "\<exists>s. a = (c@s)" by auto qed lemma trans_r: assumes "well_order_on (invgen A) r" and "x \<in> (invgen A)" and "y \<in> (invgen A)" and "z \<in> (invgen A)" and "(x\<noteq>y) \<and> (x,y) \<in> r" and "(y\<noteq>z) \<and> (y,z) \<in> r" shows "(x \<noteq> z) \<and> (x, z) \<in> r" proof- have "linear_order_on (invgen A) r" using assms(1) by (metis well_order_on_Well_order wo_rel.LIN wo_rel.intro) then have par: "partial_order_on (invgen A) r" by (simp add: linear_order_on_def) then have "preorder_on (invgen A) r" by (simp add: partial_order_on_def) then have 1:"trans r" by (simp add: preorder_on_def) have "x \<noteq> z" using assms(5,6) par antisymD assms(5) assms(6) partial_order_onD(3) by fastforce then show ?thesis using 1 by (meson assms(5) assms(6) transD) qed lemma "noteq_eqlength": assumes "a \<noteq> b" and "length a = length b" shows "a \<noteq> [] \<and> b \<noteq> [] \<and> (\<exists>x y z. a = (x @ y) \<and> b = (x @ z) \<and> (hd y \<noteq> hd z))" using assms proof(induction a arbitrary: b) case Nil then have "b = []" by force then show ?case using Nil.prems by simp next case (Cons a1 a2) then have A:"length a2 = length (tl b)" by fastforce have 1:"(a1#a2) \<noteq> []" by simp then have 2:"b \<noteq> []" using "Cons.prems"(2) by (metis length_0_conv) show ?case proof(cases "a2 = tl b") case True then have "a1 \<noteq> hd b" using Cons.prems(1) using 2 by auto then have "(a1#a2) = ([] @ (a1#a2)) \<and> b = ([] @ b) \<and> (hd (a1#a2) \<noteq> hd b)" by simp then show ?thesis using 1 2 by blast next case False then have "a2 \<noteq> [] \<and> (tl b) \<noteq> [] \<and> (\<exists>x y z. a2 = x @ y \<and> (tl b)= x @ z \<and> hd y \<noteq> hd z)" using A Cons.IH by presburger then obtain x y z where "(a2 = x @ y \<and> (tl b)= x @ z \<and> hd y \<noteq> hd z)" by blast then have "((a1#a2) = (a1#(x @ y)) \<and> b = (hd b#(x @ z)) \<and> hd y \<noteq> hd z)" using 2 list.collapse by force then have 3:"((a1#a2) = ((a1#x) @ y) \<and> b = ((hd b#x) @ z) \<and> hd y \<noteq> hd z)" by auto then show ?thesis proof(cases "a1 = hd b") case True then show ?thesis using 1 2 3 by blast next case False then have "(a1#a2) = ([] @ (a1#a2)) \<and> b = ([] @ b) \<and> (hd (a1#a2) \<noteq> hd b)" by simp then show ?thesis using 1 2 by blast qed qed qed lemma total_on_compare: assumes "well_order_on (invgen A) r" shows "(\<forall>x\<in>\<langle>A\<rangle>. \<forall>y\<in>\<langle>A\<rangle>. (length x = length y) \<longrightarrow> x \<noteq> y \<longrightarrow> (x, y) \<in> compare_set A r \<or> (y, x) \<in> compare_set A r)" apply(rule ballI)+ apply(rule impI)+ proof- fix x y assume x: "x \<in> \<langle>A\<rangle>" and y: "y \<in> \<langle>A\<rangle>" and lxy: "length x = length y" and xy:"x \<noteq> y" then have 2:"x \<noteq> [] \<and> y \<noteq> [] \<and> (\<exists>a b c. x = (a @ b) \<and> y = (a @ c) \<and> (hd b \<noteq> hd c))" using noteq_eqlength by auto then obtain a b c where 1:"x = (a @ b) \<and> y = (a @ c) \<and> (hd b \<noteq> hd c)" by auto then show "(x, y) \<in> compare_set A r \<or> (y, x) \<in> compare_set A r" proof(cases "(hd b, hd c) \<in> r") case True then have "compare_alt r x y" using compare_alt.simps 1 by auto then have "compare r x y" using lxy assms compalt_comp x y by blast then show ?thesis unfolding compare_set_def using x y by blast next case False then have bc: "(hd b, hd c) \<notin> r" by simp then show ?thesis proof(cases "b = []") case True then have "c = []" using 1 lxy by auto then have "x = y" using 1 by (simp add: True) then have "compare_alt r x y" using compare_alt.simps by auto then have "compare r x y" using lxy assms compalt_comp x y by blast then show ?thesis unfolding compare_set_def using x y by blast next case False then have "c \<noteq> []" using 1 lxy by force moreover have "c \<in> \<langle>A\<rangle>" using y 1 rightappend_span unfolding freewords_on_def by auto ultimately have c:"hd c \<in> (invgen A)" by (simp add: gen_spanset freewords_on_def) have "b \<in> \<langle>A\<rangle>" using x 1 rightappend_span unfolding freewords_on_def by auto then have "hd b \<in> (invgen A)" using False by (simp add: gen_spanset freewords_on_def) then have "(hd c, hd b) \<in> r" using assms c bc 1 2 unfolding well_order_on_def linear_order_on_def total_on_def by blast then have "compare_alt r y x" using compare_alt.simps 1 by fastforce then have "compare r y x" using lxy assms compalt_comp x y by metis then show ?thesis unfolding compare_set_def using x y by blast qed qed qed lemma trans_compare: assumes "well_order_on (invgen A) r" shows "(\<forall>x y z. (length x = length y) \<longrightarrow> (length y = length z) \<longrightarrow>(x, y) \<in> compare_set A r \<longrightarrow> (y, z) \<in> compare_set A r \<longrightarrow> (x, z) \<in> compare_set A r)" apply (rule allI)+ apply (rule impI)+ proof fix x y z assume lxy: "length x = length y" and lyz: "length y = length z" and xy: "(x, y) \<in> compare_set A r" and yz: "(y, z) \<in> compare_set A r" have cxy: "x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> compare r x y" using xy compare_set_def by blast then have "compare r x y" by blast then have "compare_alt r x y" using comp_compalt assms lxy cxy by auto then have 1:"(x = y \<or> (\<exists> a b c. x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r))" using compare_alt.cases by simp then show "(x, z) \<in> compare_set A r" proof (cases "x = y") case True note T1 = this have cyz: "y \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle> \<and> compare r y z" using yz compare_set_def case_prod_conv by blast then have "compare r y z" by blast then have "compare_alt r y z" using comp_compalt assms lyz cyz by blast then have 2: "(y = z \<or> (\<exists> d e f. y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r))" using compare_alt.cases by simp then show ?thesis proof (cases "y = z") case True then show ?thesis using T1 xy by auto next case False then have "(\<exists> d e f. y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r)" using False "2" by auto then obtain d e f where "y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" by auto then have "x = (d @ e) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using T1 by simp then show ?thesis using True yz by auto qed next case False note xny = this then have "(\<exists> a b c. x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r)" using 1 by auto then obtain a b c where abc: " x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" by auto have cyz: "y \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle> \<and> compare r y z" using yz compare_set_def case_prod_conv by blast then have "compare r y z" by blast then have "compare_alt r y z" using comp_compalt assms lyz cyz by blast then have 2: "(y = z \<or> (\<exists> d e f. y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r))" using compare_alt.cases by simp then show ?thesis proof(cases "y = z") case True then have "y = z" by auto have "y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using False abc by auto then have "z = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using True by auto then show ?thesis using True xy by auto next case False note ynz = this then have "(\<exists> d e f. y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r)" using 2 by auto then obtain d e f where def :"y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" by auto have "x = (a @ b) \<and> y = (a @ c) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using abc by auto have "y = (d @ e) \<and> z = (d @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using def by auto then show ?thesis proof(cases "length a \<le> length d") case True have y1:"y = (a @ c) \<and> y = (d @ e)" using abc def by blast then have "\<exists>s. d = a@s" using True eq_lenless by blast then obtain s where s: "d = (a @ s)" by auto then have "d = (a @ s)" by auto then have y:"y = (a @ s @ e) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using def by (simp add: def) have z:"z = (a @ s @ f) \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using def by (simp add: \<open>d = a @ s\<close>) have x:"x = (a @ b) \<and> (hd b) \<noteq> (hd c) \<and> (hd b, hd c) \<in> r" using abc by auto have y2: "y = (a@c)" using abc by auto have A:"x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle>" using xy yz compare_set_def by (simp add: cxy cyz) then show ?thesis proof(cases "s = []") case True then have ad: "a = d" using s by auto then have "y = a@e \<and> z = a@f \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using def by simp have "(a@c) = (a@e)"using y2 y True by simp then have "c = e" by simp then have "hd c = hd e" by simp then have t1: "(hd b \<noteq> hd e) \<and> (hd b, hd e) \<in> r" using x by auto have t2: "(hd e \<noteq> hd f) \<and> (hd e, hd f) \<in> r" using y by auto moreover have "(x = (a@b)) \<and> (y = (d@e)) \<and> (z = (d@f))" using abc def by auto ultimately have "b \<in> \<langle>A\<rangle> \<and> e \<in> \<langle>A\<rangle> \<and> f \<in> \<langle>A\<rangle>" using A rightappend_span freewords_on_def by blast then have 3:"((hd b) \<in> (invgen A)) \<and> ((hd e) \<in> (invgen A)) \<and> ((hd f) \<in> (invgen A))" by (meson assms t1 t2 well_order_on_domain) then have 4:"(hd b \<noteq> hd f) \<and> (hd b, hd f) \<in> r" using assms 3 t1 t2 trans_r by blast moreover have "x = (a@b) \<and> z = (a@f)" using def ad by (simp add: x) ultimately have "\<exists> a b f. x = (a@b) \<and> z = (a@f) \<and> (hd b \<noteq> hd f) \<and> (hd b, hd f) \<in> r" by auto then have "compare_alt r x z" by simp then have "compare r x z" using compalt_comp by (metis assms cxy cyz lxy lyz) then have "x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> (compare r x z)" using A by auto then have "(x, z) \<in> compare_set A r" using A compare_set_def by blast then show ?thesis by simp next case False then have "(a@c) = (a@s@e)"using y y1 by simp then have "c = (s @ e)" by simp then have "(hd c) = (hd s)" using False by auto then have "(hd b) \<noteq> (hd s) \<and> (hd b, hd s) \<in> r" using abc by auto moreover have "x = (a@b) \<and> z = (a@s@f)" using abc by (simp add: z) ultimately have "\<exists> a b s f. x = (a@b) \<and> z = (a@s@f) \<and> (hd b \<noteq> hd s) \<and> (hd b, hd s) \<in> r" by auto then have "compare_alt r x z" by (metis (no_types, lifting) False \<open>hd c = hd s\<close> abc compare_alt.simps hd_append2 z) then have "compare r x z" using compalt_comp by (metis assms cxy cyz lxy lyz) then have "x \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle> \<and> (compare r x z)" using A by auto then have "(x, z) \<in> compare_set A r" using A compare_set_def by blast then show ?thesis by simp qed next case False then have "length a > length d" by auto moreover have y1:"y = (a @ c) \<and> y = (d @ e)" using abc def by blast ultimately have "\<exists>s. a = (d@s)" using eq_lengr by blast then obtain s where s: "a = d@s" by auto then have xy1: "x = (d@s@b) \<and> y= (d@s@c)" using abc by simp then show ?thesis proof(cases "s = []") case True then have ad: "a = d" using s by auto then have "y = a@e \<and> z = a@f \<and> (hd e) \<noteq> (hd f) \<and> (hd e, hd f) \<in> r" using def by simp have "(d@c) = (d@e)" using y1 ad by blast then have "c = e" by simp then have "hd c = hd e" by simp then have t1: "(hd b \<noteq> hd e) \<and> (hd b, hd e) \<in> r" using abc by auto have t2: "(hd e \<noteq> hd f) \<and> (hd e, hd f) \<in> r" by (simp add: def) moreover have "(x = (a@b)) \<and> (y = (d@e)) \<and> (z = (d@f))" using abc def by auto ultimately have "b \<in> \<langle>A\<rangle> \<and> e \<in> \<langle>A\<rangle> \<and> f \<in> \<langle>A\<rangle>" using False ad by auto then have 3:"((hd b) \<in> (invgen A)) \<and> ((hd e) \<in> (invgen A)) \<and> ((hd f) \<in> (invgen A))" by (meson assms t1 t2 well_order_on_domain) then have 4:"(hd b \<noteq> hd f) \<and> (hd b, hd f) \<in> r" using assms 3 t1 t2 trans_r by blast moreover have "x = (a@b) \<and> z = (a@f)" using False ad by auto ultimately have "\<exists> a b f. x = (a@b) \<and> z = (a@f) \<and> (hd b \<noteq> hd f) \<and> (hd b, hd f) \<in> r" by auto then have "compare_alt r x z" by simp then have "compare r x z" using compalt_comp by (metis assms cxy cyz lxy lyz) then have "x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> (compare r x z)" using cxy by auto then have "(x, z) \<in> compare_set A r" using False ad by blast then show ?thesis by simp next case False then have "s \<noteq> []" by auto then have "(hd b \<noteq> hd c) \<and> (hd b, hd c) \<in> r" using abc by auto have "d@s@c = d@e" using xy1 def by simp then have "hd s = hd e" using False by fastforce moreover have "(hd e \<noteq> hd f) \<and> (hd e, hd f) \<in> r" using def by auto ultimately have "(hd s \<noteq> hd f) \<and> (hd s, hd f) \<in> r" by simp then have "\<exists> d s f b. x = (d@s@b) \<and> z = (d@f) \<and> (hd s \<noteq> hd f) \<and> (hd s, hd f) \<in> r" using def xy1 by blast then have "compare_alt r x z" by (metis (no_types, lifting) False \<open>hd s = hd e\<close> compare_alt.simps def hd_append2 xy1) then have cxz: "compare r x z" using compalt_comp by (metis assms cxy cyz lxy lyz) have "x \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle>" by (simp add: cxy cyz) then have "(x,z) \<in> compare_set A r" using cxz compare_set_def by auto then show ?thesis by simp qed qed qed qed qed(simp) fun lex :: "((('a,'b) groupgentype \<times> ('a,'b) groupgentype)) set \<Rightarrow> ('a, 'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> bool" where "lex r x y = (if length x < length y then True else (if \<not> (length x > length y) then compare r x y else False))" definition lex_set where "lex_set A r = {(x, y). x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> lex r x y}" lemma lex_refl_on: assumes "well_order_on (invgen A) r" shows "refl_on \<langle>A\<rangle> (lex_set A r)" proof- have "\<forall>(x,y) \<in> (lex_set A r). x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle>" using lex_set_def using case_prod_conv by blast then have 1:"(lex_set A r) \<subseteq> \<langle>A\<rangle> \<times>\<langle>A\<rangle>" by auto have "\<forall>x\<in>\<langle>A\<rangle>. lex r x x" by (metis assms lex.elims(3) refl_compare) then have 2:"(\<forall>x\<in>\<langle>A\<rangle>. (x, x) \<in> (lex_set A r))" using lex_set_def by blast then have "refl_on \<langle>A\<rangle> (lex_set A r)" by (simp add: "1" refl_onI) then show ?thesis by auto qed lemma antisymm_lex : assumes "well_order_on (invgen A) r" shows "(\<forall>x y. (x, y) \<in> lex_set A r \<longrightarrow> (y, x) \<in> lex_set A r \<longrightarrow> x = y)" apply (rule allI)+ apply (rule impI)+ proof- fix x y assume xy: "(x, y) \<in> lex_set A r" and yx: "(y, x) \<in> lex_set A r" have lexy:"lex r x y" using xy yx assms lex_set_def using case_prodD by blast then show "x = y" proof(cases "length x < length y") case True have lxy: "length x < length y" using True by auto have "lex r y x" using yx assms lex_set_def using case_prodD by blast then show ?thesis proof(cases "length x > length y") case True then have "length x = length y" using True lxy by simp then show ?thesis using True nat_neq_iff by blast next case False then have "length x < length y" using lxy by blast then have "\<not>(length y > length x)" using \<open>NielsonSchreier.lex r y x\<close> by auto then show ?thesis by (simp add: lxy) qed next case False then have glxy: "length x \<ge> length y" by auto have lyx:"lex r y x" using yx assms lex_set_def using case_prodD by blast then show ?thesis proof (cases "length x = length y") case True then have "length x = length y" using glxy by simp moreover then have cryx: "compare r y x" using lex_def False lyx by force moreover have crxy : "compare r x y" using xy False lexy by (metis lex.elims(2)) have cxy: "(x,y) \<in> compare_set A r" using crxy compare_set_def lexy assms refl_on_domain lex_refl_on xy by fastforce have cyx: "(y,x) \<in> compare_set A r" using cryx compare_set_def lyx using assms cxy refl_on_domain reflon_comp by fastforce then show ?thesis using antisym_compare True cyx cxy compare_set_def using assms by blast next case False then have "\<not>(lex r x y)" by (metis glxy leD lex.elims(2) order_le_imp_less_or_eq) then show ?thesis using lexy by simp qed qed qed lemma lex_antisym: assumes "well_order_on (invgen A) r" shows "antisym (lex_set A r)" using antisymm_lex by (metis antisymI assms) lemma lex_trans: assumes "well_order_on (invgen A) r" shows "trans (lex_set A r)" unfolding trans_def apply(rule allI)+ apply(rule impI)+ proof- fix x y z assume xy:"(x, y) \<in> (lex_set A r)" and yz: "(y, z) \<in> (lex_set A r)" then show "(x, z) \<in> lex_set A r" proof(cases "length x < length y") case True then have lxy: "length x < length y" by simp then show ?thesis proof(cases "length y < length z") case True then have "length x < length z" using lxy less_trans by blast then show ?thesis using lex.simps xy yz unfolding lex_set_def by auto next case False then have "length y = length z" using yz lex.simps unfolding lex_set_def using linorder_neqE_nat by force then have "length x < length z" using lxy by auto then show ?thesis using lex.simps xy yz unfolding lex_set_def by auto qed next case False then have exy: "length x = length y" using xy lex.simps unfolding lex_set_def by (metis (no_types, lifting) case_prodD linorder_neqE_nat mem_Collect_eq) then show ?thesis proof(cases "length y < length z") case True then have "length x < length z" by (simp add: True exy) then show ?thesis using lex.simps xy yz unfolding lex_set_def by auto next case False then have eyz:"length y = length z" using yz lex.simps unfolding lex_set_def using linorder_neqE_nat by force then have "lex r y z = compare r y z" using lex.simps by auto moreover have "lex r x y = compare r x y" using exy lex.simps by auto moreover have "y \<in> \<langle>A\<rangle> \<and> z \<in> \<langle>A\<rangle> \<and> lex r y z" using yz unfolding lex_set_def by blast moreover have "x \<in> \<langle>A\<rangle> \<and> lex r x y" using xy unfolding lex_set_def by blast ultimately have "(x,y) \<in> compare_set A r \<and> (y, z) \<in> compare_set A r" unfolding compare_set_def by blast then have "compare r x z" using exy eyz assms trans_compare[of "A" "r"] unfolding compare_set_def using case_prodD mem_Collect_eq by blast moreover have "lex r x z = compare r x z" using exy eyz lex.simps by auto ultimately show ?thesis using xy yz unfolding lex_set_def by fastforce qed qed qed lemma lex_total_on: assumes "well_order_on (invgen A) r" shows "total_on \<langle>A\<rangle> (lex_set A r)" unfolding total_on_def apply(rule ballI)+ apply(rule impI) proof- fix x y assume x: "x \<in> \<langle>A\<rangle>" and y: "y \<in> \<langle>A\<rangle>" and xy: "x \<noteq> y" then show "(x, y) \<in> lex_set A r \<or> (y, x) \<in> lex_set A r" proof(cases "length x = length y") case True then have "lex r x y = compare r x y" using lex.simps by simp moreover have "lex r y x = compare r y x" using True lex.simps by simp moreover have "(x, y) \<in> compare_set A r \<or> (y, x) \<in> compare_set A r" using x y xy True total_on_compare[of "A" "r"] assms by blast ultimately show ?thesis using x y unfolding lex_set_def compare_set_def by fastforce next case False then have lxy: "length x \<noteq> length y" by simp then show ?thesis proof(cases "length x < length y") case True then have "lex r x y" by simp then show ?thesis using x y unfolding lex_set_def by blast next case False then have "length x > length y" using lxy by auto then have "lex r y x" by simp then show ?thesis using x y unfolding lex_set_def by blast qed qed qed fun lex_lift :: "('a,'b) monoidgentype set \<Rightarrow> ((('a,'b) groupgentype \<times> ('a,'b) groupgentype)) set \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a,'b) word set \<Rightarrow> bool" where "lex_lift S r a b = (lex r (red_rep S a) (red_rep S b))" definition lexlift_set :: "('a,'b) monoidgentype set \<Rightarrow> (('a,'b) word set) set \<Rightarrow> (('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow> ((('a,'b) word set \<times> ('a,'b) word set)) set" where "lexlift_set S A r = {(a,b). a \<in> A \<and> b \<in> A \<and> lex_lift S r a b}" definition least :: "('a \<times> 'a) set \<Rightarrow> 'a set \<Rightarrow> 'a" where "least r A = (THE x. x \<in> A \<and> (\<forall>w \<in> A. (x,w) \<in> r))" (*least (nat_eq_less) (length ` S) \<le> (length ` S)*) definition least_hd :: "(('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a,'b) groupgentype" where "least_hd r A = least r (hd ` A)" lemma hd_sub_span: assumes "[] \<notin> S" and "S \<subseteq> \<llangle>A\<rrangle>" shows "hd ` S \<subseteq> A" proof(rule subsetI) fix x assume x: "x \<in> hd ` S" moreover then have "x \<in> hd ` \<llangle>A\<rrangle>" using assms(2) by blast ultimately show "x \<in> A" by (metis (no_types, lifting) assms(1) assms(2) gen_spanset image_iff in_mono) qed lemma least_exists: assumes "well_order_on (invgen A) r" and "[] \<notin> S" and "S \<noteq> {}" and "S \<subseteq> \<langle>A\<rangle>" shows "\<exists>x \<in> hd ` S. \<forall>w \<in> hd ` S. (x,w) \<in> r" proof- have 1:"hd ` S \<subseteq> (invgen A)" using assms(2) assms(4) unfolding freewords_on_def by (simp add: hd_sub_span) obtain x where "x \<in> S" using assms(3) by auto then obtain hx where "hx \<in> hd ` S" by blast then show ?thesis using assms(1) assms(3) unfolding well_order_on_def by (metis Linear_order_wf_diff_Id 1 assms(1) image_is_empty well_order_on_Field) qed lemma least_unique: assumes "well_order_on (invgen A) r" and "[] \<notin> S" and "S \<noteq> {}" and "S \<subseteq> \<langle>A\<rangle>" shows "\<exists>!x \<in> hd ` S. \<forall>w \<in> hd ` S. (x,w) \<in> r" proof(rule classical) have "\<exists>x \<in> hd ` S. \<forall>w \<in> hd ` S. (x,w) \<in> r" using least_exists assms by auto then obtain x where x:"x \<in> hd ` S \<and> (\<forall>w \<in> hd ` S. (x,w) \<in> r)" by blast assume "\<not>(\<exists>!x \<in> hd ` S. \<forall>w \<in> hd ` S. (x,w) \<in> r)" then obtain y where y:"y \<in> hd ` S \<and> (\<forall>w \<in> hd ` S. (y,w) \<in> r) \<and> y \<noteq> x" using x by metis then have "(x,y) \<in> r \<and> (y, x) \<in> r" using x y by blast then have "x = y" by (metis assms(1) trans_r well_order_on_domain) then have False using y by auto then show "\<exists>!x \<in> hd ` S. \<forall>w \<in> hd ` S. (x,w) \<in> r" by simp qed lemma least_hd_the: assumes "well_order_on (invgen A) r" and "[] \<notin> S" and "S \<noteq> {}" and "S \<subseteq> \<langle>A\<rangle>" shows "(least_hd r S) \<in> hd ` S \<and> (\<forall>x \<in> hd ` S. ((least_hd r S),x) \<in> r)" unfolding least_hd_def least_def proof(rule theI') show "\<exists>!x. x \<in> hd ` S \<and> (\<forall>w\<in>hd ` S. (x, w) \<in> r)" using assms least_unique[of "A" "r" "S"] by auto qed fun leastcons_comp :: "(('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow> (('a, 'b) word \<times> (('a, 'b) word set)) \<Rightarrow> (('a, 'b) word \<times> ('a, 'b) word set)" where "leastcons_comp r (xs, A) = (xs@[(least_hd r A)], {w \<in> tl ` A. ([least_hd r A]@w \<in> A)})" fun tuple_appendset :: "('a list \<times> 'a list set) \<Rightarrow> ('a list set)" where "tuple_appendset (xs, S) = (append xs) ` S" lemma tuple_append: assumes "a \<in> tuple_appendset (xs, S)" shows "\<exists>ys \<in> S. a = (xs @ ys)" proof- have "a \<in> (append xs) ` S" using assms tuple_appendset.simps by blast then show ?thesis by (simp add: image_iff) qed lemma least_consappend_in: assumes "leastcons_comp r (xs, S) = (ys, T)" and "zs \<in> T" shows "[(least_hd r S)]@zs \<in> S" proof- have "T = {w \<in> tl ` S. [least_hd r S] @ w \<in> S}" using assms(1) leastcons_comp.simps[of "r" "xs" "S"] by force then show ?thesis using assms(2) using assms(1) by fastforce qed lemma least_consappend_sub: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "leastcons_comp r (xs, S) = (ys, T)" shows "tuple_appendset (ys, T) \<subseteq> tuple_appendset (xs, S)" proof(rule subsetI) fix x assume x: "x \<in> tuple_appendset (ys, T)" then obtain zs where zs:"zs \<in> T \<and> x = ys@zs" using tuple_append by blast moreover have "ys = xs@[(least_hd r S)]" using leastcons_comp.simps assms(3) by force moreover have "[(least_hd r S)]@zs \<in> S" using zs assms(3) least_consappend_in by blast ultimately show "x \<in> tuple_appendset (xs, S)" using tuple_appendset.simps by simp qed lemma least_cons_lesshd: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "leastcons_comp r (xs, S) = (ys, T)" and "[] \<notin> S" and "x \<in> tuple_appendset (xs, S) \<and> x = (xs@x1)" and "x \<notin> tuple_appendset (ys, T)" shows "hd x1 \<noteq> (least_hd r S)" proof(rule ccontr) assume "\<not> (hd x1 \<noteq> (least_hd r S))" then have c:"hd x1 = (least_hd r S)" by simp moreover have 1:"x1 \<in> S" using assms(5) by auto ultimately have "x = xs@([(least_hd r S)]@(tl x1))" using assms(4) by (metis append_Cons append_self_conv2 assms(5) list.collapse) moreover have "ys = xs @ [(least_hd r S)]" using assms(3) leastcons_comp.simps[of "r" "xs" "S"] by auto ultimately have 2:"x = ys@(tl x1)" by simp have "tl x1 \<in> {w \<in> tl ` S. [least_hd r S] @ w \<in> S}" using c 1 by (metis (no_types, lifting) append_Cons append_Nil assms(4) image_eqI list.collapse mem_Collect_eq) then have "tl x1 \<in> T" using assms(3) leastcons_comp.simps[of "r" "xs" "S"] by auto then have "x \<in> tuple_appendset (ys, T)" using 2 tuple_appendset.simps[of "ys" "T"] by simp then show False using assms(6) by blast qed lemma length_decrease: assumes "leastcons_comp r (xs, S) = (ys, T)" and "\<forall>x \<in> S. length x = n" and "n > 0" shows "\<forall>x \<in> T. length x = n - 1" proof(rule ballI) fix x assume x:"x \<in> T" then have "x \<in> {w \<in> tl ` S. ([least_hd r S]@w \<in> S)}" using assms(1) leastcons_comp.simps by auto then obtain x1 where "x1 \<in> S \<and> x = tl x1" by blast moreover then have "length x1 = n" using assms(2) by simp ultimately show "length x = n - 1" using assms(3) by simp qed lemma length_increase: assumes "leastcons_comp r (xs, S) = (ys, T)" and "\<forall>x \<in> S. length x = n" and "n > 0" shows "length ys = length xs + 1" proof- have "ys = xs @ [least_hd r S]" using assms(1) leastcons_comp.simps by simp then show ?thesis by simp qed lemma length_invariant: assumes "leastcons_comp r (xs, S) = (ys, T)" and "\<forall>x \<in> S. length x = n" and "n > 0" shows "\<forall>x y. (x \<in> tuple_appendset (xs, S) \<and> y \<in> tuple_appendset (ys, T)) \<longrightarrow> length x = length y" apply(rule allI)+ apply(rule impI) proof- fix x y assume xy: "x \<in> tuple_appendset (xs, S) \<and> y \<in> tuple_appendset (ys, T)" obtain x1 where x:"x1 \<in> S \<and> x = xs @ x1" using xy tuple_append by blast then have x1: "length x1 = n" using assms(2) by auto then have lx:"length x = length xs + n" using x by simp obtain y1 where "y1 \<in> T \<and> y = ys @ y1" using xy tuple_append by blast moreover then have "length y1 = (n - 1)" using assms length_decrease by auto moreover have "length ys = length xs + 1" using assms length_increase by auto ultimately have "length y = length xs + n" by (simp add: assms(3)) then show "length x = length y" using lx by simp qed lemma least_cons_less: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "[] \<notin> S" and "leastcons_comp r (xs, S) = (ys, T)" and "\<forall>x \<in> S. length x = n" and "n > 0" and "xs \<in> \<langle>A\<rangle>" shows "\<forall>x y. (x \<in> tuple_appendset (xs, S) \<and> x \<notin> tuple_appendset (ys, T)) \<longrightarrow> y \<in> tuple_appendset (ys, T) \<longrightarrow> (y, x) \<in> compare_set A r" apply(rule allI)+ apply(rule impI)+ proof- fix x y assume x:"x \<in> tuple_appendset (xs, S) \<and> x \<notin> tuple_appendset (ys, T)" and y: "y \<in> tuple_appendset (ys, T)" obtain x1 where x1:"x1 \<in> S \<and> x = xs@x1" using tuple_append x by blast then have 1:"hd x1 \<noteq> (least_hd r S)" using assms(1) assms(2) assms(3) assms(4) least_cons_lesshd x by blast have "hd x1 \<in> hd ` S" using x1 by simp then have 2:"((least_hd r S),hd x1) \<in> r" using least_hd_the[of "A" "r" "S"] assms by blast have "ys = xs @ [(least_hd r S)]" using assms(4) leastcons_comp.simps by fastforce moreover obtain y1 where y1:"y1 \<in> T \<and> y = ys@y1" using tuple_append y by blast ultimately have ya:"y = xs @ ([(least_hd r S)] @ y1)" by simp moreover have "hd ([(least_hd r S)] @ y1) = (least_hd r S)" by simp ultimately have "x = xs@x1 \<and> y = xs @ ([(least_hd r S)] @ y1) \<and> hd ([(least_hd r S)] @ y1) \<noteq> hd x1 \<and> (hd ([(least_hd r S)] @ y1), hd x1) \<in> r" using x1 1 2 compare_alt.simps by auto then have "compare_alt r y x" using compare_alt.simps[of "r" "x" "y"] by force moreover have "length x = length y" using assms(4) assms(5) assms(6) length_invariant x y by auto moreover have xA: "x \<in> \<langle>A\<rangle>" using assms(2) assms(7) span_append freewords_on_def x1 by blast moreover have yA: "y \<in> \<langle>A\<rangle>" using ya assms(2) assms(4) assms(7) least_consappend_in span_append freewords_on_def y1 by blast ultimately have "compare r y x" using compalt_comp assms(1) by metis then show "(y, x) \<in> compare_set A r" using compare_set_def xA yA by blast qed fun leastn_comp :: "(('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow> nat \<Rightarrow> (('a, 'b) word \<times> (('a, 'b) word set)) \<Rightarrow> (('a, 'b) word \<times> (('a, 'b) word set))" where "leastn_comp r 0 (xs, A) = (xs, A)"| "leastn_comp r n (xs, A) = leastn_comp r (n - 1) (leastcons_comp r (xs, A))" definition least_comp :: "(('a,'b) groupgentype \<times> ('a,'b) groupgentype) set \<Rightarrow> nat \<Rightarrow> ('a, 'b) word set \<Rightarrow> ('a, 'b) word" where "least_comp r n A = fst (leastn_comp r n ([], A))" lemma leastcons_comp_fstsub: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "leastcons_comp r (xs, S) = (ys, T)" shows "T \<subseteq> \<langle>A\<rangle>" proof(rule subsetI) fix x assume x:"x \<in> T" then have "x \<in> {w \<in> tl ` S. [least_hd r S] @ w \<in> S}" using assms(3) leastcons_comp.simps by simp then show "x \<in> \<langle>A\<rangle>" using assms(2) span_cons by (metis (no_types, lifting) x append_Cons append_Nil2 append_eq_append_conv2 assms(3) in_mono least_consappend_in same_append_eq freewords_on_def) qed lemma leastcons_notempty: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "S \<noteq> {}" and "leastcons_comp r (xs, S) = (ys, T)" shows "T \<noteq> {}" proof- have 1:"[] \<notin> S" using assms(3) assms(4) by auto then have "(least_hd r S) \<in> hd ` S"using assms using least_hd_the by blast moreover then obtain x where "x \<in> S \<and> hd x = (least_hd r S)" by auto then have "tl x \<in> {w \<in> tl ` S. [least_hd r S] @ w \<in> S}" using 1 assms(6) by (metis (no_types, lifting) append_Cons append_self_conv2 hd_Cons_tl image_eqI mem_Collect_eq) then show ?thesis using leastcons_comp.simps[of "r" "xs" "S"] using assms(6) by fastforce qed lemma nil_set: assumes "S \<noteq> {}" and "\<forall>x \<in> S. length x = n" and "n = 0" shows "S = {[]}" proof- have A:"[] \<in> S" proof- obtain x where 1:"x \<in> S" using subsetI assms(1) by blast then have "length x = 0" using assms(2) assms(3) by simp then have "x = []" by simp then show ?thesis using 1 by simp qed then have "{[]} \<subseteq> S" by simp moreover have "S \<subseteq> {[]}" proof(rule subsetI) fix x assume "x \<in> S" then have "length x = 0" using assms(2) assms(3) by simp then have "x = []" by simp then show "x \<in> {[]}" by simp qed ultimately show ?thesis by auto qed lemma leastn_comp_empty: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "leastn_comp r n (x, S) = (xs, T)" and "S \<noteq> {}" shows "T = {[]}" using assms proof(induction n arbitrary:x S) case 0 then show ?case by simp next case (Suc n) let ?ys = "fst (leastcons_comp r (x, S))" let ?U = "snd (leastcons_comp r (x, S))" have "leastn_comp r (Suc n) (x, S) = leastn_comp r n (leastcons_comp r (x, S))" using leastn_comp.simps(2) by simp then have "leastn_comp r (Suc n) (x, S) = leastn_comp r n (?ys, ?U)" by simp then have 1:"leastn_comp r n (?ys, ?U) = (xs, T)" using Suc.prems by argo have "\<forall>x \<in> ?U. length x = (Suc n) - 1" using Suc.prems length_decrease[of "r" "x" "S" "?ys" "?U" "Suc n"] using surjective_pairing by blast then have U:"\<forall>x \<in> ?U. length x = n" by simp have "leastcons_comp r (x, S) = (fst (leastcons_comp r (x, S)), snd (leastcons_comp r (x, S)))" by simp then have US: "?U \<noteq> {}" using Suc.prems leastcons_notempty[of "A" "r" "S" "n" "x" "?ys" "?U"] using leastcons_notempty by blast show ?case proof(cases "n > 0") case True have "(leastcons_comp r (x, S)) = (?ys, ?U)" by simp then have "?U \<subseteq> \<langle>A\<rangle>" using Suc.prems leastcons_comp_fstsub[of "A" "r" "S" "x" "?ys" "?U"] by auto then show ?thesis using US Suc.prems Suc.IH[of "?U"] 1 U True by blast next case False then have n:"n = 0" by auto then have "leastn_comp r n (?ys, ?U) = (?ys, ?U)" using leastn_comp.simps(1) by fast then have "?U = T" by (metis "1" prod.inject) moreover have "?U = {[]}" using U n US nil_set[of "?U" "n"] by linarith ultimately show ?thesis by simp qed qed lemma leastn_comp_fst: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "leastn_comp r n (x, S) = (xs, T)" and "S \<noteq> {}" shows "\<forall>y \<in> tuple_appendset (xs, T). y = fst (xs, T)" proof- have "T = {[]}" using leastn_comp_empty assms by blast then have "tuple_appendset (xs, T) = {xs}" using tuple_appendset.simps by (simp add: image_is_empty) then show ?thesis by auto qed lemma leastn_comp_sub: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "leastn_comp r n (xs, S) = (ys, T)" and "S \<noteq> {}" shows "tuple_appendset (ys, T) \<subseteq> tuple_appendset (xs, S)" using assms proof(induction n arbitrary: ys S xs T) case 0 then show ?case by blast next case (Suc n) let ?ys = "fst (leastcons_comp r (xs, S))" let ?U = "snd (leastcons_comp r (xs, S))" have "leastn_comp r (Suc n) (xs, S) = leastn_comp r n (leastcons_comp r (xs, S))" using leastn_comp.simps(2) by simp then have "leastn_comp r (Suc n) (xs, S) = leastn_comp r n (?ys, ?U)" by simp then have 1:"leastn_comp r n (?ys, ?U) = (ys, T)" using Suc.prems by argo have A:"tuple_appendset (?ys, ?U) \<subseteq> tuple_appendset (xs, S)" by auto have "\<forall>x \<in> ?U. length x = (Suc n) - 1" using Suc.prems length_decrease[of "r" "xs" "S" "?ys" "?U" "Suc n"] using surjective_pairing by blast then have U:"\<forall>x \<in> ?U. length x = n" by simp have "leastcons_comp r (xs, S) = (fst (leastcons_comp r (xs, S)), snd (leastcons_comp r (xs, S)))" by simp then have US: "?U \<noteq> {}" using Suc.prems leastcons_notempty[of "A" "r" "S" "n" "xs" "?ys" "?U"] using leastcons_notempty by blast have "tuple_appendset (ys, T) \<subseteq> tuple_appendset (?ys, ?U)" proof(cases "n > 0") case True have "(leastcons_comp r (xs, S)) = (?ys, ?U)" by simp then have "?U \<subseteq> \<langle>A\<rangle>" using Suc.prems leastcons_comp_fstsub[of "A" "r" "S" "xs" "?ys" "?U"] by auto then show ?thesis using 1 U US Suc.prems(1) True Suc.IH[of "?U" "?ys" "ys" "T"] by blast next case False then have "(?ys, ?U) = (ys, T)" using 1 leastn_comp.simps by auto then show ?thesis by simp qed then show ?case using A by blast qed lemma least_hd_span: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "[] \<notin> S" and "S \<noteq> {}" and "xs \<in> \<langle>A\<rangle>" shows "[(least_hd r S)] \<in> \<langle>A\<rangle>" proof- have "least_hd r S \<in> hd ` S" using assms(1) assms(2) assms(3) assms(4) least_hd_the by auto moreover have "hd ` S \<subseteq> invgen A" by (metis assms(2) assms(3) hd_sub_span freewords_on_def) ultimately show ?thesis unfolding freewords_on_def using group_spanset.empty group_spanset.gen subsetD by blast qed lemma leastn_comp_less: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "leastn_comp r n (xs, S) = (ys, T)" and "S \<noteq> {}" and "xs \<in> \<langle>A\<rangle>" shows "\<forall>x y. (x \<in> tuple_appendset (xs, S) \<and> x \<notin> tuple_appendset (ys, T)) \<longrightarrow> y \<in> tuple_appendset (ys, T) \<longrightarrow> (y, x) \<in> compare_set A r" using assms proof(induction n arbitrary: xs S ys T) case 0 then show ?case by blast next case (Suc n) let ?ys = "fst (leastcons_comp r (xs, S))" let ?U = "snd (leastcons_comp r (xs, S))" have "leastn_comp r (Suc n) (xs, S) = leastn_comp r n (leastcons_comp r (xs, S))" using leastn_comp.simps(2) by simp then have "leastn_comp r (Suc n) (xs, S) = leastn_comp r n (?ys, ?U)" by simp then have 1:"leastn_comp r n (?ys, ?U) = (ys, T)" using Suc.prems by argo have A:"tuple_appendset (?ys, ?U) \<subseteq> tuple_appendset (xs, S)" by auto have L:"(leastcons_comp r (xs, S)) = (?ys, ?U)" by simp have eS: "[] \<notin> S" using Suc.prems(3) by (metis Suc.prems(4) bot_nat_0.not_eq_extremum list.size(3)) have C:"\<forall>x y. (x \<in> tuple_appendset (xs, S) \<and> x \<notin> tuple_appendset (?ys, ?U)) \<longrightarrow> y \<in> tuple_appendset (?ys, ?U) \<longrightarrow> (y, x) \<in> compare_set A r" using L Suc.prems eS least_cons_less[of "A" "r" "S" "xs" "?ys" "?U" "Suc n"] by fastforce have "\<forall>x \<in> ?U. length x = (Suc n) - 1" using Suc.prems length_decrease[of "r" "xs" "S" "?ys" "?U" "Suc n"] using surjective_pairing by blast then have U:"\<forall>x \<in> ?U. length x = n" by simp have "leastcons_comp r (xs, S) = (fst (leastcons_comp r (xs, S)), snd (leastcons_comp r (xs, S)))" by simp then have US: "?U \<noteq> {}" using Suc.prems leastcons_notempty[of "A" "r" "S" "n" "xs" "?ys" "?U"] using leastcons_notempty by blast then show ?case proof(cases "n > 0") case True then have n: "n > 0" by simp then have eU:"[] \<notin> ?U" using U by fastforce have "[(least_hd r S)] \<in> \<langle>A\<rangle>" using least_hd_span by (metis Suc.prems(2) Suc.prems(3) Suc.prems(6) Zero_not_Suc assms(1) assms(7) list.size(3)) then have yA: "?ys \<in> \<langle>A\<rangle>" using Suc.prems(7) leastcons_comp.simps freewords_on_def span_append by fastforce then have UA:"?U \<subseteq> \<langle>A\<rangle>" using Suc.prems leastcons_comp_fstsub[of "A" "r" "S" "xs" "?ys" "?U"] by auto then have A:"\<forall>x y. x \<in> tuple_appendset (?ys, ?U) \<and> x \<notin> tuple_appendset (ys, T) \<longrightarrow> y \<in> tuple_appendset (ys, T) \<longrightarrow> (y, x) \<in> compare_set A r" using yA 1 U US Suc.prems(1) True Suc.IH[of "?U" "?ys" "ys" "T"] by blast then have B: "\<forall>x y. x \<in> tuple_appendset (?ys, ?U) \<and> y \<in> tuple_appendset (ys, T) \<longrightarrow> (y, x) \<in> compare_set A r \<or> x \<in> tuple_appendset (ys, T)" by blast show ?thesis apply(rule allI)+ apply(rule impI)+ proof- fix x y assume x: "x \<in> tuple_appendset (xs, S) \<and> x \<notin> tuple_appendset (ys, T)" and y: "y \<in> tuple_appendset (ys, T) " then have yy:"y \<in> tuple_appendset (?ys, ?U)" using Suc.prems(1) UA U True US 1 leastn_comp_sub[of "A" "r" "?U" "n" "?ys" "ys" "T"] by blast show "(y, x) \<in> compare_set A r" proof(cases "x \<in> tuple_appendset (?ys, ?U)") case True then show ?thesis using x B y by blast next case False then show ?thesis using C yy x by blast qed qed next case False then have "n = 0" by simp then have "(ys, T) = (?ys, ?U)" using 1 by auto then show ?thesis using C by blast qed qed lemma leastn_comp_single: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "S \<noteq> {}" shows "tuple_appendset (leastn_comp r n ([], S)) = {least_comp r n S}" proof- let ?ys = "fst (leastn_comp r n ([], S))" and ?T = "snd (leastn_comp r n ([], S))" have a:"(leastn_comp r n ([], S)) = (?ys, ?T)" by simp then have T: "?T = {[]}" using assms leastn_comp_empty by blast then have b:"tuple_appendset (?ys, ?T) = {fst(?ys, ?T)}" using T tuple_appendset.simps by force have "fst (leastn_comp r n ([], S)) = fst (?ys, ?T)" using a by simp then have c:"{least_comp r n S} = {fst (?ys, ?T)}" using least_comp_def by auto then show ?thesis using a b c by presburger qed lemma least_comp_least: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "S \<noteq> {}" shows "\<forall>x \<in> S. ((least_comp r n S), x) \<in> compare_set A r" apply(rule ballI) proof- fix x assume x: "x \<in> S" have 1:"tuple_appendset (leastn_comp r n ([], S)) = {(least_comp r n S)}" using assms leastn_comp_single by blast have 2:"tuple_appendset ([], S) = S" using tuple_appendset.simps by simp have 3:"x \<in> \<langle>A\<rangle>" using assms(2) x by blast then show "(least_comp r n S, x) \<in> compare_set A r" proof(cases "x = (least_comp r n S)") case True have "compare r (least_comp r n S) x" using refl_compare assms(1) 3 True by blast then show ?thesis using 3 unfolding compare_set_def True by blast next case False let ?T = "snd (leastn_comp r n ([], S))" have A:"leastn_comp r n ([], S) = ((least_comp r n S), ?T)" by (simp add: least_comp_def) then have B:"tuple_appendset ((least_comp r n S), ?T) = {(least_comp r n S)}" using 1 by auto then have "x \<notin> tuple_appendset ((least_comp r n S), ?T)" using 1 False by auto moreover have "least_comp r n S \<in> tuple_appendset ((least_comp r n S), ?T)" using 1 B by auto moreover have "x \<in> tuple_appendset ([], S)" using x 2 by auto moreover have "[] \<in> \<langle>A\<rangle>" unfolding freewords_on_def using empty by auto ultimately show ?thesis using assms A leastn_comp_less by blast qed qed lemma least_comp_in: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "S \<noteq> {}" shows "(least_comp r n S) \<in> S" proof- let ?ys = "fst (leastn_comp r n ([], S))" let ?T = "snd (leastn_comp r n ([], S))" have "tuple_appendset (?ys, ?T) = {least_comp r n S}" using assms leastn_comp_single by (metis prod.collapse) moreover have "[] \<in> \<langle>A\<rangle>" unfolding freewords_on_def using empty by auto ultimately have "{least_comp r n S} \<subseteq> tuple_appendset ([], S)" using leastn_comp_sub[of "A" "r" "S" "n" "[]" "?ys" "?T"] assms by simp moreover have "tuple_appendset ([], S) = S" using tuple_appendset.simps by auto ultimately show ?thesis by blast qed lemma least_comp_least_lex: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "\<forall>x \<in> S. length x = n" and "n > 0" and "S \<noteq> {}" shows "\<forall>x \<in> S.((least_comp r n S), x) \<in> lex_set A r" proof fix x assume x: "x \<in> S" then have "((least_comp r n S), x) \<in> compare_set A r" using least_comp_least assms by blast then have 1:"(least_comp r n S) \<in> \<langle>A\<rangle> \<and> x \<in> \<langle>A\<rangle> \<and> compare r (least_comp r n S) x" unfolding compare_set_def by fastforce have S:"(least_comp r n S) \<in> S" unfolding least_comp_def using assms least_comp_in least_comp_def by metis have "length (least_comp r n S) \<le> length x" using S assms(3) x by force then have "lex r (least_comp r n S) x" using lex.simps 1 x S assms(3) by force then show "((least_comp r n S), x) \<in> lex_set A r" unfolding lex_set_def using 1 by blast qed definition nat_leq_less :: "(nat \<times> nat) set" where "nat_leq_less = {(x,y). x \<le> y}" definition belongs where "belongs S x = (x \<in> S)" lemma nat_least_exists: assumes "(S:: nat set) \<noteq> {}" shows "\<exists>x\<in>S.\<forall>y\<in>S. (x, y) \<in> nat_leq_less" proof- obtain x where x:"x \<in> S" using assms by auto then show ?thesis proof(cases "0 \<in> S") case True have "\<forall>y \<in> S. 0\<le>y" using True by simp then have "\<forall>y \<in> S.(0,y) \<in> nat_leq_less" unfolding nat_leq_less_def by auto then show ?thesis using True by auto next case False then obtain k where k:"(belongs S k) \<and> (\<forall>i<k. (\<not> (belongs S i))) \<and> k \<le> x" using assms x ex_least_nat_le[of "belongs S" x] belongs_def by metis have "\<forall>y \<in> S. (k, y) \<in> nat_leq_less" proof(rule ballI) fix y assume y:"y \<in> S" then show "(k, y) \<in> nat_leq_less" proof(cases "k \<le> y") case True then show ?thesis unfolding nat_leq_less_def by simp next case False then have "k > y" by auto then have "y \<notin> S" using k belongs_def by metis then show ?thesis using y by auto qed qed then show ?thesis using belongs_def k by force qed qed lemma nat_unique_least: assumes "(S:: nat set) \<noteq> {}" shows "\<exists>!x\<in>S.\<forall>y\<in>S. (x, y) \<in> nat_leq_less" proof(rule classical) assume assm: "\<not>(\<exists>!x\<in>S.\<forall>y\<in>S. (x, y) \<in> nat_leq_less)" have least:"\<exists>x\<in>S.\<forall>y\<in>S. (x, y) \<in> nat_leq_less" using nat_least_exists assms by simp then obtain x where x:"(x\<in> S) \<and> (\<forall>y\<in>S. (x, y) \<in> nat_leq_less)" by auto then obtain z where z: "(z \<in> S) \<and> (\<forall>y\<in>S. (z, y) \<in> nat_leq_less) \<and> (z \<noteq> x)" using assm least by metis then have "(z \<in> S) \<and> (x \<in> S)" using x by auto then have "((x, z) \<in> nat_leq_less) \<and> ((z, x) \<in> nat_leq_less)" using x z by simp then have "x = z" unfolding nat_leq_less_def using mem_Collect_eq by auto then show ?thesis using z by linarith qed definition least_length :: "'a list set \<Rightarrow> 'a list set" where "least_length S = {x \<in> S. length x = (least (nat_leq_less) (length ` S))}" lemma least_length_the: assumes "S \<noteq> {}" shows "((least (nat_leq_less) (length ` S)) \<in> (length ` S)) \<and> (\<forall>y\<in>(length ` S). ((least (nat_leq_less) (length ` S)), y) \<in> nat_leq_less)" unfolding least_def proof(rule theI') have "(length ` S) \<noteq> {}" using assms by auto then show "\<exists>!y. y \<in> length ` S \<and> (\<forall>w\<in>length ` S. (y, w) \<in> nat_leq_less)" using nat_unique_least[of "(length ` S)"] by linarith qed lemma least_length_least: assumes "S \<noteq> {}" shows "\<forall>y \<in> (length ` S). ((least (nat_leq_less) (length ` S)), y) \<in> nat_leq_less" proof- have l:"(length ` S) \<noteq> {}" using assms by force then have 1:"\<exists>!x\<in>(length ` S).\<forall>y\<in>(length ` S). (x, y) \<in> nat_leq_less" using nat_unique_least assms by presburger moreover have "(least (nat_leq_less) (length ` S)) \<in> (length ` S)" using least_def l nat_least_exists nat_unique_least by (smt (verit, del_insts) assms image_is_empty theI) ultimately show ?thesis unfolding least_def assms nat_least_exists nat_unique_least by (smt (verit, ccfv_threshold) "1" theI) qed lemma least_length_lesser: assumes "well_order_on (invgen A) r" and "[] \<notin> S" and "S \<noteq> {}" and "S \<subseteq> \<langle>A\<rangle>" and "x \<in> S" and "x \<notin> least_length S" shows "\<forall>y \<in> least_length S. (lex r y x)" proof- have y:"\<forall>y \<in> least_length S. length y = least (nat_leq_less) (length ` S)" unfolding least_length_def assms(3) by fastforce then have 1:"\<forall>y \<in> least_length S. \<forall>w \<in> (length ` S). (length y, w) \<in> nat_leq_less" using least_length_least assms(3) by (metis (no_types, lifting)) have "(length x) \<in> (length ` S)" using assms(5) by auto then have "\<forall>y \<in> least_length S.(length y, length x) \<in> nat_leq_less" using 1 by fast then have l:"\<forall>y \<in> least_length S. length y \<le> length x" using nat_leq_less_def by blast have "length x \<noteq> least (nat_leq_less) (length ` S)" using least_length_def assms(5,6) by blast then have "\<forall>y \<in> least_length S. length y \<noteq> length x" using y by simp then have "\<forall>y \<in> least_length S. length y < length x" using l using le_neq_implies_less by blast then show ?thesis using lex.simps by fastforce qed (*1. nat least is unique 2. x : S and x \<notin> least_length S \<Rightarrow> x > y. \<forall>y : least_length S (*least_hd_the*) 3. least_length S \<subseteq> S*) (*least (nat_eq_less) (length ` S) \<le> (length ` S)*) lemma preorder_words : assumes "well_order_on (invgen A) r" shows "preorder_on \<langle>A\<rangle> (lex_set A r)" unfolding preorder_on_def using lex_refl_on lex_trans assms by blast lemma partial_order_words : assumes "well_order_on (invgen A) r" shows "partial_order_on \<langle>A\<rangle> (lex_set A r)" unfolding partial_order_on_def using lex_antisym preorder_words assms by blast lemma linear_order_words : assumes "well_order_on (invgen A) r" shows "linear_order_on \<langle>A\<rangle> (lex_set A r)" unfolding linear_order_on_def using partial_order_words lex_total_on assms by fast definition tuple_set where "tuple_set r Q = {x \<in> Q. (\<exists>y\<in>Q. ((x, y) \<in> r \<or> (y, x) \<in> r))}" lemma tuple_set_subset : "tuple_set r Q \<subseteq> Q" unfolding tuple_set_def by simp lemma tuple_set_reln : "tuple_set (lex_set A r) Q \<subseteq> \<langle>A\<rangle>" unfolding tuple_set_def lex_set_def by fastforce lemma tuple_set_not: "\<forall>x \<in> Q. \<forall> y \<in> Q. x \<notin> tuple_set (lex_set A r) Q \<longrightarrow> (x, y) \<notin> (lex_set A r) \<and> (y, x) \<notin> (lex_set A r)" apply(rule ballI)+ apply(rule impI) proof(rule ccontr) fix x y assume x: "x \<in> Q" and y:"y \<in> Q" and nx: "x \<notin> tuple_set (lex_set A r) Q" and "\<not> ((x, y) \<notin> lex_set A r \<and> (y, x) \<notin> lex_set A r)" then have c:"(x, y) \<in> lex_set A r \<or> (y, x) \<in> lex_set A r" by blast then show False proof(cases "(x, y) \<in> lex_set A r") case True then have "x \<in> tuple_set (lex_set A r) Q" using x y unfolding tuple_set_def by blast then show ?thesis using nx by blast next case False then have "(y, x) \<in> lex_set A r" using c by simp then have "x \<in> tuple_set (lex_set A r) Q" using x y unfolding tuple_set_def by blast then show ?thesis using nx by blast qed qed lemma least_length_subset: "(least_length S) \<subseteq> S" unfolding least_length_def by simp lemma least_lex: assumes "well_order_on (invgen A) r" and "S \<subseteq> \<langle>A\<rangle>" and "S \<noteq> {}" and "[] \<notin> S" shows "\<forall>x \<in> S. ((least_comp r ((least (nat_leq_less) (length ` S))) (least_length S)),x) \<in> lex_set A r" proof fix x assume x: "x \<in> S" then show "((least_comp r ((least (nat_leq_less) (length ` S))) (least_length S)),x) \<in> lex_set A r" proof(cases "x \<in> least_length S") case True have "0 \<notin> (length ` S)" using assms(4) by auto have 1:"(length ` S) \<noteq> {}" using assms(3) by auto then have "(least (nat_leq_less) (length ` S)) \<in> (length ` S)" using least_def nat_unique_least by (smt (verit, del_insts) assms image_is_empty theI) then have 2:"(least (nat_leq_less) (length ` S)) > 0" using assms(4) by fastforce then have 3:"\<forall>x \<in>(least_length S). length x = (least (nat_leq_less) (length ` S))" using least_length_the least_length_def leastn_comp_less mem_Collect_eq by blast moreover have "(least_length S) \<subseteq> \<langle>A\<rangle>" using assms(2) least_length_subset by blast ultimately show ?thesis using assms 1 2 least_comp_least_lex[of "A" "r" "least_length S" "(least (nat_leq_less) (length ` S))"] True by blast next case False have LS: "(least_length S) \<subseteq> \<langle>A\<rangle>" using assms(2) least_length_subset by blast have 1:"(length ` S) \<noteq> {}" using assms(3) by auto then have l:"(least (nat_leq_less) (length ` S)) \<in> (length ` S)" using least_def nat_unique_least by (smt (verit, del_insts) assms image_is_empty theI) then have S:"least_length S \<noteq> {}" unfolding least_length_def using assms empty_iff image_iff mem_Collect_eq by force then obtain a where a:"a \<in> least_length S" by blast then have "(lex r a x)" using False assms least_length_lesser[of "A" "r" "S" "x"] x by blast then have ax:"(a,x) \<in> lex_set A r" unfolding lex_set_def using x assms(2) a LS by blast then have "(least (nat_leq_less) (length ` S)) \<in> (length ` S)" using 1 least_def nat_unique_least l by auto then have 2:"(least (nat_leq_less) (length ` S)) > 0" using assms(4) by fastforce then have 3:"\<forall>x \<in>(least_length S). length x = (least (nat_leq_less) (length ` S))" using least_length_the least_length_def leastn_comp_less mem_Collect_eq by blast moreover have "(least_length S) \<subseteq> \<langle>A\<rangle>" using assms(2) least_length_subset by blast ultimately have "((least_comp r ((least (nat_leq_less) (length ` S))) (least_length S)), a) \<in> lex_set A r" using assms S 1 2 least_comp_least_lex[of "A" "r" "least_length S" "(least (nat_leq_less) (length ` S))"] a by fastforce then show ?thesis using ax assms(1) lex_trans unfolding trans_def by fast qed qed lemma minimalelem_words: assumes "well_order_on (invgen A) r" shows"\<And>x Q. x \<in> Q \<Longrightarrow> \<exists>z\<in>Q. \<forall>y. (y, z) \<in> (lex_set A r - Id) \<longrightarrow> y \<notin> Q" proof- fix x Q assume x: "x \<in> (Q :: (('a \<times> 'b) \<times> bool) list set)" then show "\<exists>z\<in>Q. \<forall>y. (y, z) \<in> (lex_set A r - Id) \<longrightarrow> y \<notin> Q" proof(cases "[] \<in> Q") case True then have "\<nexists>z. (z, []) \<in> (lex_set A r - Id)" unfolding lex_set_def using lex.simps[of "r" "z" "[]"] by auto then show ?thesis using True by blast next case False then have nQ:"[] \<notin> Q" by simp then show ?thesis proof(cases "tuple_set (lex_set A r) Q = {}") case True have "\<forall>y. (y, x) \<in> (lex_set A r - Id) \<longrightarrow> y \<notin> Q" apply(rule allI) apply(rule impI) proof- fix y assume y:"(y, x) \<in> (lex_set A r - Id)" show "y \<notin> Q" proof(rule ccontr) assume "\<not> y \<notin> Q" then have cont :"y \<in> Q" by blast then have 1:"y \<in> tuple_set (lex_set A r) Q" using x tuple_set_def lex_set_def using DiffD1 tuple_set_not y by fastforce then show False using True by blast qed qed then show ?thesis using x by blast next case False moreover have 1:"tuple_set (lex_set A r) Q \<subseteq> \<langle>A\<rangle>" using tuple_set_reln by fast moreover have nN: "[] \<notin> tuple_set (lex_set A r) Q" using nQ tuple_set_subset[of "(lex_set A r)" "Q"] by blast ultimately have lst:"\<forall>x \<in> tuple_set (lex_set A r) Q. ((least_comp r ((least (nat_leq_less) (length ` tuple_set (lex_set A r) Q))) (least_length (tuple_set (lex_set A r) Q))),x) \<in> lex_set A r" using assms least_lex[of "A" "r" "(tuple_set (lex_set A r) Q)"] by blast let ?z = "(least_comp r ((least (nat_leq_less) (length ` tuple_set (lex_set A r) Q))) (least_length (tuple_set (lex_set A r) Q)))" have "(length ` tuple_set (lex_set A r) Q) \<noteq> {}" using False by auto then have lste:"(least (nat_leq_less) (length ` tuple_set (lex_set A r) Q)) \<in> (length ` tuple_set (lex_set A r) Q)" using least_length_the[of "tuple_set (lex_set A r) Q"] by blast then have 2:"(least (nat_leq_less) (length ` (tuple_set (lex_set A r) Q))) > 0" using nN by fastforce then have 3:"\<forall>x \<in>(least_length (tuple_set (lex_set A r) Q)). length x = (least (nat_leq_less) (length ` (tuple_set (lex_set A r) Q)))" using least_length_the least_length_def leastn_comp_less mem_Collect_eq by blast have "least_length (tuple_set (lex_set A r) Q) \<subseteq> \<langle>A\<rangle>" using 1 least_length_subset by fastforce moreover have "least_length (tuple_set (lex_set A r) Q) \<noteq> {}" using False lste unfolding least_length_def by fastforce ultimately have "?z \<in> (least_length (tuple_set (lex_set A r) Q))" using least_comp_in[of "A" "r" "(least_length (tuple_set (lex_set A r) Q))" "((least (nat_leq_less) (length ` tuple_set (lex_set A r) Q)))"] assms 2 3 by blast then have zQ:"?z \<in> Q" using least_length_subset[of "(tuple_set (lex_set A r) Q)"] tuple_set_subset[of "(lex_set A r)" "Q"] by fast have "\<forall>y. (y, ?z) \<in> (lex_set A r - Id) \<longrightarrow> y \<notin> Q" apply(rule allI) apply(rule impI) proof- fix y assume y:"(y, ?z) \<in> lex_set A r - Id" show "y \<notin> Q" proof(rule ccontr) assume "\<not> y \<notin> Q" then have cy:"y \<in> Q" by blast show False proof(cases "y \<in> tuple_set (lex_set A r) Q") case True then have yt:"y \<in> tuple_set (lex_set A r) Q" by simp then show ?thesis proof(cases "y = ?z") case True then show ?thesis using y by simp next case False then have "(?z, y) \<in> lex_set A r" using lst yt by simp moreover have "(y, ?z) \<in> lex_set A r" using y by blast ultimately show ?thesis using lex_antisym assms False unfolding antisym_def by blast qed next case False then have "((x, ?z) \<notin> lex_set A r \<and> (y, ?z) \<notin> lex_set A r)" using tuple_set_not[of "Q" "A" "r"] cy zQ y by blast then show ?thesis using y by fast qed qed qed moreover have "?z \<in> Q" using zQ . ultimately show ?thesis by blast qed qed qed (*fix x, x\<in>Q Cases: 1: [] \<in> Q Not 1: 1.1:tuple_set (lex_set A r) Q = {}, then x is the z (proof by contradiction: if (y,x) and y \<in> Q then x \<in> tuple_set (lex_set A r) Q)" Not 1.1: use least_lex and Id, contradiction *) lemma wf_words : assumes "well_order_on (invgen A) r" shows "wf (lex_set A r - Id)" using minimalelem_words assms wf_eq_minimal by fastforce lemma well_order_words : assumes "well_order_on (invgen A) r" shows "well_order_on \<langle>A\<rangle> (lex_set A r)" unfolding well_order_on_def using linear_order_words wf_words assms by blast definition left_subword :: "('a, 'b) word \<Rightarrow> ('a, 'b) word" ("L") where "left_subword xs = take (((length xs+1) div 2)) xs" value "((((6::nat)) div 2))" lemma left_subword_word: "xs = (left_subword xs) @ (drop (((length xs+1) div 2)) xs)" unfolding left_subword_def by auto definition left_lex_set where "left_lex_set A r = {(x,y). x \<in> L ` \<langle>A\<rangle> \<and> y \<in> L ` \<langle>A\<rangle> \<and> lex r x y}" definition invleft_lex_set where "invleft_lex_set A r = {(x, y). x \<in> L` (wordinverse ` \<langle>A\<rangle>) \<and> y \<in> L` (wordinverse ` \<langle>A\<rangle>) \<and> lex r x y}" definition L_lex where "L_lex A r = ((left_lex_set A r) - Id) <*lex*> ((invleft_lex_set A r) - Id)" definition left_tuple ("L2") where "left_tuple x = (L x, L (wordinverse x))" definition L_lex_set where "L_lex_set A r = {(x,y). x \<in> \<langle>A\<rangle> \<and> y \<in> \<langle>A\<rangle> \<and> (L2 x, L2 y) \<in> L_lex A r}" lemma half_n:assumes "n > 0" shows "(((((n::nat) + n-1)+1) div 2)) = n" using assms by linarith lemma left_span: "\<langle>A\<rangle> = L ` \<langle>A\<rangle>" proof show "\<langle>A\<rangle> \<subseteq> L ` \<langle>A\<rangle>" proof(rule subsetI) fix x assume x: "x \<in> \<langle>A\<rangle>" show "x \<in> L ` \<langle>A\<rangle>" proof(cases "x = []") case True then have "x \<in> \<langle>A\<rangle>" using empty unfolding freewords_on_def by auto moreover have "L x = x" using True unfolding left_subword_def by fastforce ultimately show ?thesis by force next case False then have "tl x \<in> \<langle>A\<rangle>" using freewords_on_def x by (metis hd_Cons_tl span_cons) then have A:"x @ (tl x) \<in> \<langle>A\<rangle>" using span_append x unfolding freewords_on_def by blast have "length (tl x) = length x - 1" by fastforce moreover have "length x > 0" using False by simp moreover have "length (x @ tl x) = length x + length x - 1" by auto ultimately have "length x = (length (x @ tl x) + 1) div 2" using half_n[of "length x"] by simp then have "L (x @ (tl x)) = x" unfolding left_subword_def by auto then show ?thesis using A by force qed qed next show "L ` \<langle>A\<rangle> \<subseteq> \<langle>A\<rangle>" proof(rule subsetI) fix x assume x: "x \<in> L ` \<langle>A\<rangle>" then obtain a where a:"a \<in> \<langle>A\<rangle> \<and> L a = x" by blast have "a = (L a) @ (drop ((((length a)+1) div 2)) a)" using left_subword_word by blast then show "x\<in> \<langle>A\<rangle>" using leftappend_span a unfolding freewords_on_def by metis qed qed lemma inv_span: "\<langle>A\<rangle> = wordinverse ` \<langle>A\<rangle>" proof show "\<langle>A\<rangle> \<subseteq> wordinverse ` \<langle>A\<rangle>" proof(rule subsetI) fix x assume x: "x \<in> \<langle>A\<rangle>" then have "wordinverse x \<in> \<langle>A\<rangle>" by (simp add: span_wordinverse) moreover have "wordinverse (wordinverse x) = x" by (metis wordinverse_symm) ultimately show "x \<in> wordinverse ` \<langle>A\<rangle>" by (metis image_eqI) qed next show "wordinverse ` \<langle>A\<rangle> \<subseteq> \<langle>A\<rangle>" proof(rule subsetI) fix x assume x: "x \<in> wordinverse ` \<langle>A\<rangle>" then obtain a where "a \<in> \<langle>A\<rangle> \<and> wordinverse a = x" by blast then show "x \<in> \<langle>A\<rangle>" using span_wordinverse by auto qed qed lemma wf_L_lex: assumes "well_order_on (invgen A) r" shows "wf (L_lex A r)" proof- have "left_lex_set A r = lex_set A r" unfolding left_lex_set_def lex_set_def using left_span[of "A"] by fastforce then have 1:"wf (left_lex_set A r - Id)" using wf_words assms(1) by auto have "invleft_lex_set A r = lex_set A r" unfolding invleft_lex_set_def lex_set_def using left_span[of "A"] inv_span[of "A"] by fastforce then have "wf (invleft_lex_set A r - Id)" using wf_words assms(1) by auto then show ?thesis unfolding L_lex_def using 1 by (simp add: wf_lex_prod) qed lemma wf_L_lex_set: assumes "well_order_on (invgen A) r" shows "wf (L_lex_set A r)" proof(rule wfI_min) fix x Q assume x: "x \<in> (Q :: (('a \<times> 'b) \<times> bool) list set)" show "\<exists>z\<in>Q. \<forall>y. (y, z) \<in> L_lex_set A r \<longrightarrow> y \<notin> Q" proof(cases "tuple_set (L_lex A r) (L2 ` Q) = {}") case True have "\<forall>y. (y, x) \<in> L_lex_set A r \<longrightarrow> y \<notin> Q" apply (rule allI) apply (rule impI) proof- fix y assume y: "(y, x) \<in> L_lex_set A r" then have "(L2 y, L2 x) \<in> L_lex A r" unfolding L_lex_set_def by fastforce then show "y \<notin> Q" using True x unfolding tuple_set_def by blast qed then show ?thesis using x by blast next case False then obtain x where "x \<in> tuple_set (L_lex A r) (L2 ` Q)" by auto then obtain z where z: "z \<in> tuple_set (L_lex A r) (L2 ` Q) \<and> (\<forall>y. (y, z) \<in> (L_lex A r) \<longrightarrow> y \<notin> tuple_set (L_lex A r) (L2 ` Q))" using wfE_min wf_L_lex by (metis assms) then have z1: "z \<in> (L2 ` Q)" using tuple_set_subset[of "(L_lex A r)" "(L2 ` Q)"] by auto then obtain w where w: "w \<in> Q \<and> L2 w = z" by auto moreover have "\<forall>y. (y, w) \<in> L_lex_set A r \<longrightarrow> y \<notin> Q" apply(rule allI) apply (rule impI) proof- fix y assume a: "(y, w) \<in> L_lex_set A r" then have contr: "(L2 y, L2 w) \<in> L_lex A r" unfolding L_lex_set_def by auto show "y \<notin> Q" proof(rule ccontr) assume "\<not> y \<notin> Q" then have y:"y \<in> Q" by blast then show False proof(cases "L2 y \<notin> tuple_set (L_lex A r) (L2 ` Q)") case True have "(L2 y, L2 w) \<notin> L_lex A r" proof(rule ccontr) assume assm: "\<not> (L2 y, L2 w) \<notin> L_lex A r" then have "(L2 y, L2 w) \<in> L_lex A r" by blast then have "L2 y \<in> tuple_set (L_lex A r) (L2 ` Q)" unfolding tuple_set_def using w y by auto then show False using True by blast qed then show ?thesis using contr by blast next case False have "L2 y \<notin> tuple_set (L_lex A r) (L2 ` Q)" using z contr w by blast then show ?thesis using False by blast qed qed qed ultimately show ?thesis by blast qed qed definition L_lex_set' where "L_lex_set' A r = {(x,y). x \<in> \<langle>A\<rangle> // reln_tuple \<langle>A\<rangle> \<and> x \<in> \<langle>A\<rangle> // reln_tuple \<langle>A\<rangle> \<and>(red_rep A x, red_rep A y) \<in> L_lex_set A r}" lemma wf_L_lex_set': assumes "well_order_on (invgen A) r" shows "wf (L_lex_set' A r)" proof(rule wfI_min) fix x Q assume x: "x \<in> (Q :: (('a \<times> 'b) \<times> bool) list set set)" show "\<exists>z\<in>Q. \<forall>y. (y, z) \<in> L_lex_set' A r \<longrightarrow> y \<notin> Q" proof(cases "tuple_set (L_lex_set A r) (red_rep A ` Q) = {}") case True have "\<forall>y. (y, x) \<in> L_lex_set' A r \<longrightarrow> y \<notin> Q" apply (rule allI) apply (rule impI) proof- fix y assume y: "(y, x) \<in> L_lex_set' A r" then have "(red_rep A y, red_rep A x) \<in> L_lex_set A r" unfolding L_lex_set'_def by fast then show "y \<notin> Q" using True x unfolding tuple_set_def by blast qed then show ?thesis using x by blast next case False then obtain x where "x \<in> tuple_set (L_lex_set A r) (red_rep A ` Q)" by auto then obtain z where z: "z \<in> tuple_set (L_lex_set A r) (red_rep A ` Q) \<and> (\<forall>y. (y, z) \<in> (L_lex_set A r) \<longrightarrow> y \<notin> tuple_set (L_lex_set A r) (red_rep A ` Q))" using wfE_min wf_L_lex_set assms by metis then have z1: "z \<in> (red_rep A ` Q)" using tuple_set_subset[of "(L_lex_set A r)" "(red_rep A ` Q)"] by auto then obtain w where w: "w \<in> Q \<and> (red_rep A w) = z" by auto moreover have "\<forall>y. (y, w) \<in> L_lex_set' A r \<longrightarrow> y \<notin> Q" apply(rule allI) apply (rule impI) proof- fix y assume a: "(y, w) \<in> L_lex_set' A r" then have contr: "(red_rep A y, red_rep A w) \<in> L_lex_set A r" unfolding L_lex_set'_def by auto show "y \<notin> Q" proof(rule ccontr) assume "\<not> y \<notin> Q" then have y:"y \<in> Q" by blast then show False proof(cases "red_rep A y \<notin> tuple_set (L_lex_set A r) (red_rep A ` Q)") case True have "(red_rep A y, red_rep A w) \<notin> L_lex_set A r" proof(rule ccontr) assume assm: "\<not> (red_rep A y, red_rep A w) \<notin> L_lex_set A r" then have "(red_rep A y, red_rep A w) \<in> L_lex_set A r" by blast then have "red_rep A y \<in> tuple_set (L_lex_set A r) (red_rep A ` Q)" unfolding tuple_set_def using w y by auto then show False using True by blast qed then show ?thesis using contr by blast next case False have "red_rep A y \<notin> tuple_set (L_lex_set A r) (red_rep A ` Q)" using z contr w by blast then show ?thesis using False by blast qed qed qed ultimately show ?thesis by blast qed qed *) definition left_subword :: "('a, 'b) word \<Rightarrow> ('a, 'b) word" ("L") where "left_subword xs = take (((length xs+1) div 2)) xs" definition left_tuple ("L2") where "left_tuple x = (L x, L (wordinverse x))" definition r_gen where "r_gen = (SOME r :: ('a, 'b) groupgentype rel. Well_order r \<and> Field r = UNIV)" lemma r_gen: "Well_order r_gen \<and> Field r_gen = UNIV" unfolding r_gen_def using someI_ex[of "\<lambda> r. Well_order r \<and> Field r = UNIV"] well_ordering by (simp add: \<open>\<exists>x. Well_order x \<and> Field x = UNIV \<Longrightarrow> Well_order (SOME x. Well_order x \<and> Field x = UNIV) \<and> Field (SOME x. Well_order x \<and> Field x = UNIV) = UNIV\<close> well_ordering) lemma wf_r_gen: "wf (r_gen - Id)" using r_gen well_order_on_def by auto definition lex_word where "lex_word = lenlex (r_gen - Id)" lemma wf_lex_word: "wf lex_word" unfolding lex_word_def by (simp add: wf_r_gen wf_lenlex) lemma wf_inv1: assumes "wf r" shows "wf {(x,y). (f x, f y) \<in> r}" by (metis assms inv_image_def wf_inv_image) fun min where "min r (x, y) = (if (x, y) \<in> r then x else y)" definition lex_min_L2_word where "lex_min_L2_word = {(x,y). (min lex_word x, min lex_word y) \<in> lex_word}" lemma wf_lex_min_L2_word: "wf (lex_min_L2_word)" unfolding lex_min_L2_word_def by (simp add: wf_inv1 wf_lex_word) fun max where "max r (x, y) = (if (x, y) \<in> r then y else x)" definition lex_max_L2_word where "lex_max_L2_word = {(x,y). (max lex_word x, max lex_word y) \<in> lex_word}" lemma wf_lex_max_L2_word: "wf (lex_max_L2_word)" unfolding lex_max_L2_word_def by (simp add: wf_inv1 wf_lex_word) definition lex_L2_word' where "lex_L2_word' A = {(x,y). x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> ((\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) x , (\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) y) \<in> (lex_word <*lex*> lex_word)}" lemma wf_lex_word_prod: "wf (lex_word <*lex*> lex_word)" by (simp add: wf_lex_prod wf_lex_word) lemma wf_lex_L2_word': "wf (lex_L2_word' A)" proof- have "wf {(x,y) . ((\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) x , (\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) y) \<in> (lex_word <*lex*> lex_word)}" using wf_inv1 wf_lex_word_prod by fast moreover have "lex_L2_word' A \<subseteq> {(x,y) . ((\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) x , (\<lambda>x. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) y) \<in> (lex_word <*lex*> lex_word)}" unfolding lex_L2_word'_def by auto ultimately show ?thesis using wf_subset by blast qed definition nat_less :: "(nat \<times> nat) set" where "nat_less = {(x,y). x < y}" lemma wf_nat_less: "wf nat_less" proof- have "nat_less = less_than" unfolding nat_less_def less_than_def using less_eq by blast then show ?thesis using wf_less_than by argo qed lemma wf_lex_L2_word'_prod: "wf (nat_less <*lex*> lex_L2_word' A)" by (simp add: wf_lex_L2_word' wf_lex_prod wf_nat_less) definition lex_L2_word where "lex_L2_word A = {(x,y). x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> ((\<lambda>x. (length (red_rep A x), x)) x, (\<lambda>x. (length (red_rep A x), x)) y) \<in> (nat_less <*lex*> lex_L2_word' A)}" lemma wf_lex_L2_word: "wf (lex_L2_word A)" proof- have "wf {(x,y). ((\<lambda>x. (length (red_rep A x), x)) x, (\<lambda>x. (length (red_rep A x), x)) y) \<in> (nat_less <*lex*> lex_L2_word' A)}" using wf_inv1 wf_lex_L2_word'_prod by fast moreover have "lex_L2_word A \<subseteq>{(x,y). ((\<lambda>x. (length (red_rep A x), x)) x, (\<lambda>x. (length (red_rep A x), x)) y) \<in> (nat_less <*lex*> lex_L2_word' A)}" unfolding lex_L2_word_def by auto ultimately show ?thesis using wf_subset by blast qed lemma lex_L2_word_length: assumes "x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>))" and "length ((red_rep A) x) = length ((red_rep A) y)" shows "(x,y) \<in> (lex_L2_word A) \<longleftrightarrow> (x,y) \<in> (lex_L2_word' A)" unfolding lex_L2_word_def by (simp add: assms(1) assms(2) wf_nat_less) lemma lex_L2_word_length_conv: assumes "x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>))" and "length ((red_rep A) x) = length ((red_rep A) y)" shows "(x,y) \<in> (lex_L2_word' A) \<Longrightarrow> (x,y) \<in> (lex_L2_word A)" unfolding lex_L2_word_def by (simp add: assms(1) assms(2)) lemma total_Id: "total r \<Longrightarrow> total (r - Id)" by simp lemma total_r_gen_Id: "total (r_gen - Id)" using r_gen total_Id unfolding well_order_on_def linear_order_on_def by metis lemma lex_word_total: "\<not> (x,y) \<in> (lex_word) \<Longrightarrow> \<not> (y,x) \<in> (lex_word) \<Longrightarrow> x = y" proof- assume "\<not> (x,y) \<in> (lex_word)" and "\<not> (y,x) \<in> (lex_word) " then show "x = y" using total_r_gen_Id unfolding lex_word_def by (metis UNIV_I total_lenlex total_on_def) qed lemma lex_L2_word_total1: assumes "x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>))" and "length ((red_rep A) x) = length ((red_rep A) y)" shows "\<not> (x,y) \<in> (lex_L2_word A) \<Longrightarrow> \<not> (y,x) \<in> (lex_L2_word A) \<Longrightarrow> min lex_word (L2 (red_rep A x)) = min lex_word (L2 (red_rep A y)) \<and> max lex_word (L2 (red_rep A x)) = max lex_word (L2 (red_rep A y))" proof- assume "\<not> (x,y) \<in> (lex_L2_word A)" and "\<not> (y,x) \<in> (lex_L2_word A)" then have 1: "\<not> (x,y) \<in> (lex_L2_word' A) \<and> \<not> (y,x) \<in> (lex_L2_word' A)" using assms lex_L2_word_length by auto have "\<not> (min lex_word (L2 (red_rep A x)), min lex_word (L2 (red_rep A y))) \<in> lex_word" proof(rule ccontr) assume "\<not> (min lex_word (L2 (red_rep A x)), min lex_word (L2 (red_rep A y))) \<notin> lex_word" then have "(min lex_word (L2 (red_rep A x)), min lex_word (L2 (red_rep A y))) \<in> lex_word" by blast then have "(x,y) \<in> (lex_L2_word' A)" unfolding lex_L2_word'_def lex_prod_def using assms(1) by simp then show False using 1 by blast qed moreover have "\<not> (min lex_word (L2 (red_rep A y)), min lex_word (L2 (red_rep A x))) \<in> lex_word" proof(rule ccontr) assume "\<not> (min lex_word (L2 (red_rep A y)), min lex_word (L2 (red_rep A x))) \<notin> lex_word" then have "(min lex_word (L2 (red_rep A y)), min lex_word (L2 (red_rep A x))) \<in> lex_word" by blast then have "(y,x) \<in> (lex_L2_word' A)" unfolding lex_L2_word'_def lex_prod_def using assms(1) by simp then show False using 1 by blast qed ultimately have min: "min lex_word (L2 (red_rep A x)) = min lex_word (L2 (red_rep A y))" using lex_word_total by blast have "\<not> (max lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A y))) \<in> lex_word" proof(rule ccontr) assume "\<not> (max lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A y))) \<notin> lex_word" then have "(max lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A y))) \<in> lex_word" by blast then have "(x,y) \<in> (lex_L2_word' A)" unfolding lex_L2_word'_def lex_prod_def using assms(1) min by simp then show False using 1 by blast qed moreover have "\<not> (max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A x))) \<in> lex_word" proof(rule ccontr) assume "\<not> (max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A x))) \<notin> lex_word" then have "(max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A x))) \<in> lex_word" by blast then have "(y,x) \<in> (lex_L2_word' A)" unfolding lex_L2_word'_def lex_prod_def using assms(1) min by simp then show False using 1 by blast qed ultimately show "min lex_word (L2 (red_rep A x)) = min lex_word (L2 (red_rep A y)) \<and> max lex_word (L2 (red_rep A x)) = max lex_word (L2 (red_rep A y))" using min lex_word_total by blast qed fun rev_tuple ("\<down>") where "\<down> (x,y) = (y,x)" lemma lex_L2_word_total2: "min lex_word (L2 x) = min lex_word (L2 y) \<and> max lex_word (L2 x) = max lex_word (L2 y) \<Longrightarrow> (L2 x = L2 y) \<or> (\<down> (L2 x) = L2 y)" by (metis left_tuple_def max.simps min.simps rev_tuple.simps) lemma "(L2 x = L2 y) \<or> (\<down> (L2 x) = L2 y) \<Longrightarrow> min lex_word (L2 x) = min lex_word (L2 y) \<and> max lex_word (L2 x) = max lex_word (L2 y)" by (metis (no_types, hide_lams) left_tuple_def lex_word_total max.simps min.simps rev_tuple.simps wf_asym wf_lex_word) (* lemma "even (length x) \<Longrightarrow> take ((length (a#x) + 1) div 2) (a#x) = a#take ((length x + 1) div 2) x" by simp lemma "odd (length x) \<Longrightarrow> take ((length (a#x) + 1) div 2) (a#x) = a#take ((length x) div 2) x" by simp lemma "(odd (length x) \<and> L (wordinverse x) = wordinverse (drop ((length x + 1) div 2) x)) \<or> (even (length x) \<and> L (wordinverse x) = wordinverse (drop ((length x) div 2) x))" unfolding left_subword_def proof(induction x) case Nil then show ?case by simp next case (Cons a x) then show ?case sorry qed *) definition right_subword ("R") where "right_subword xs = drop (((length xs+1) div 2)) xs" lemma length_wordinverse:"length xs = length (wordinverse xs)" by (simp add: wordinverse_redef1) lemma even_div2: "even (x :: nat) \<Longrightarrow> x - ((x + 1) div 2) = ((x + 1) div 2)" by fastforce lemma odd_div2: "odd (x :: nat) \<Longrightarrow> x - ((x + 1) div 2) = ((x + 1) div 2) - 1" by (metis (no_types, lifting) add_diff_cancel_right add_diff_cancel_right' even_div2 odd_even_add odd_one odd_succ_div_two odd_two_times_div_two_succ) lemma even_R: "even (length xs) \<Longrightarrow> L (wordinverse xs) = wordinverse (R xs)" unfolding right_subword_def left_subword_def proof- assume "even (length xs)" then have 1:"length xs - (length xs + 1) div 2 = (length xs + 1) div 2" using even_div2 by blast have "take ((length (wordinverse xs) + 1) div 2) (wordinverse xs) = take ((length xs + 1) div 2) (rev ((map inverse) xs))" by (simp add: wordinverse_redef1) moreover then have "... = rev (drop ((length xs + 1) div 2) ((map inverse) xs))" using 1 length_map take_rev by metis moreover then have "... = wordinverse (drop ((length xs + 1) div 2) xs)" by (simp add: drop_map wordinverse_redef1) ultimately show "take ((length (wordinverse xs) + 1) div 2) (wordinverse xs) = wordinverse (drop ((length xs + 1) div 2) xs)" by presburger qed lemma take_length: "n \<le> length xs \<Longrightarrow>length (take n xs) = n" by simp lemma drop_odd_length: "odd (length xs) \<Longrightarrow> (length (drop ((length xs + 1) div 2 - 1) xs) = ((length xs + 1) div 2))" proof- assume odd:"odd (length xs)" then have "length xs > 0" using odd by force then have 1:"((length xs + 1) div 2) \<le> length xs" by simp have "drop ((length xs + 1) div 2 - 1) (rev xs) = rev (take ((length xs + 1) div 2) xs)" using odd rev_take odd_div2 by metis moreover have "length (rev (take ((length xs + 1) div 2) xs)) = ((length xs + 1) div 2)" using 1 take_length length_rev by metis moreover have "length (drop ((length xs + 1) div 2 - 1) (rev xs)) = length (drop ((length xs + 1) div 2 - 1) xs)" by simp ultimately show "(length (drop ((length xs + 1) div 2 - 1) xs) = ((length xs + 1) div 2))" by presburger qed lemma odd_R: "odd (length xs) \<Longrightarrow> take (((length xs+1) div 2) - 1) (L (wordinverse xs)) = wordinverse (R xs)" unfolding right_subword_def left_subword_def proof- assume odd:"odd (length xs)" then have 1:"length xs - (length xs + 1) div 2 = (length xs + 1) div 2 - 1" using odd_div2 by blast have "take ((length xs + 1) div 2 - 1) (take ((length (wordinverse xs) + 1) div 2) (wordinverse xs)) = take ((length xs + 1) div 2 - 1) (take ((length xs + 1) div 2) (rev (map inverse xs)))" by (simp add: wordinverse_redef1) moreover then have "... = take ((length xs + 1) div 2 - 1) (rev (drop ((length xs + 1) div 2 - 1) ((map inverse) xs)))" using 1 length_map take_rev by metis moreover then have "... = rev (drop (length (drop ((length xs + 1) div 2 - 1) ((map inverse) xs)) - ((length xs + 1) div 2 - 1)) (drop ((length xs + 1) div 2 - 1) ((map inverse) xs)))" using take_rev by blast moreover then have "... = rev (drop (((length xs + 1) div 2) - ((length xs + 1) div 2 - 1)) (drop ((length xs + 1) div 2 - 1) ((map inverse) xs)))" using drop_odd_length length_map odd by metis moreover then have "... = rev (drop 1 (drop ((length xs + 1) div 2 - 1) ((map inverse) xs)))" by (simp add: odd) moreover then have "... = rev ((drop ((length xs + 1) div 2) ((map inverse) xs)))" by (simp add: odd) moreover then have "... = rev ((map inverse) (drop ((length xs + 1) div 2) xs))" using drop_map by blast moreover then have "... = wordinverse (drop ((length xs + 1) div 2) xs)" by (simp add: wordinverse_redef1) ultimately show "take ((length xs + 1) div 2 - 1) (take ((length (wordinverse xs) + 1) div 2) (wordinverse xs)) = wordinverse (drop ((length xs + 1) div 2) xs)" by presburger qed lemma LR_eq: assumes "L x = L y" and "R x = R y" shows "x = y" proof- have "L x @ R x = x" unfolding left_subword_def right_subword_def by simp moreover have "L y @ R y = y" unfolding left_subword_def right_subword_def by simp ultimately show ?thesis using assms(1,2) by argo qed lemma L2_eq: assumes "length x = length y" and "(L2 x = L2 y)" shows "L x = L y \<and> R x = R y" proof(cases "odd (length x)") case True have 1: "L x = L y" using assms(2) left_tuple_def by (metis prod.inject) have "L (wordinverse x) = L (wordinverse y)" using assms(2) left_tuple_def by (metis prod.inject) then have "take (((length x+1) div 2) - 1) (L (wordinverse x)) = take (((length y+1) div 2) - 1) (L (wordinverse y))" using assms(1) by presburger then have "wordinverse (R x) = wordinverse (R y)" using True assms(1) odd_R by metis then have "R x = R y" using wordinverse_of_wordinverse by metis then show ?thesis using 1 by blast next case False have 1: "L x = L y" using assms(2) left_tuple_def by (metis prod.inject) have "L (wordinverse x) = L (wordinverse y)" using assms(2) left_tuple_def by (metis prod.inject) then have "wordinverse (R x) = wordinverse (R y)" using False assms(1) even_R by metis then have "R x = R y" using wordinverse_of_wordinverse by metis then show ?thesis using 1 by blast qed lemma eq_L2_eq: assumes "length x = length y" and "(L2 x = L2 y)" shows "x = y" using L2_eq LR_eq assms(1) assms(2) by auto lemma rev_L2_inv: assumes "length x = length y" and "((\<down> (L2 x)) = L2 y)" shows "x = wordinverse y" proof(cases "odd (length x)") case True have 1: "L x = L (wordinverse y)" using assms(2) left_tuple_def old.prod.inject rev_tuple.simps by metis have "L (wordinverse x) = L y" using assms(2) left_tuple_def old.prod.inject rev_tuple.simps by metis then have "take (((length x+1) div 2) - 1) (L (wordinverse x)) = take (((length y+1) div 2) - 1) (L y)" using assms(1) by presburger then have "take (((length x+1) div 2) - 1) (L (wordinverse x)) = take (((length y+1) div 2) - 1) (L (wordinverse (wordinverse y)))" using wordinverse_of_wordinverse by metis then have "take (((length x+1) div 2) - 1) (L (wordinverse x)) = take (((length (wordinverse (wordinverse y))+1) div 2) - 1) (L (wordinverse (wordinverse y)))" using length_wordinverse by metis then have "wordinverse (R x) = wordinverse (R (wordinverse y))" using True assms(1) odd_R length_wordinverse by metis then have "R x = R (wordinverse y)" using wordinverse_of_wordinverse by metis then show ?thesis using 1 LR_eq by blast next case False then have even: "even (length x)" by auto have 1:"L x = L (wordinverse y)" using assms(2) left_tuple_def old.prod.inject rev_tuple.simps by metis have "L (wordinverse x) = L y" using assms(2) left_tuple_def old.prod.inject rev_tuple.simps by metis then have "L (wordinverse x) = L (wordinverse (wordinverse y))" by (simp add: wordinverse_of_wordinverse) then have "wordinverse (R x) = wordinverse (R (wordinverse y))" using even_R assms(1) even by (metis length_wordinverse) then have "R x = (R (wordinverse y))" using wordinverse_of_wordinverse by metis then show ?thesis using 1 LR_eq by blast qed lemma assumes "x \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>)) \<and> y \<in> (\<langle>A\<rangle> // (reln_tuple \<langle>A\<rangle>))" and "length ((red_rep A) x) = length ((red_rep A) y)" shows "\<not> (x,y) \<in> (lex_L2_word A) \<Longrightarrow> \<not> (y,x) \<in> (lex_L2_word A) \<Longrightarrow> (red_rep A x) = (red_rep A y) \<or> (red_rep A x) = wordinverse (red_rep A y)" using assms lex_L2_word_total1 lex_L2_word_total2 eq_L2_eq rev_L2_inv by blast+ lemma red_rep_wordinv: assumes "x ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" shows "red_rep A ((reln_tuple ⟨A⟩) `` {wordinverse (red_rep A x)}) = wordinverse (red_rep A x)" proof- have "reduced (wordinverse (red_rep A x))" using red_rep_def[of "A" "x"] reduced_wordinverse[of "red_rep A x"] red_rep_the assms by blast moreover have "wordinverse (red_rep A x) ∈ ((reln_tuple ⟨A⟩) `` {wordinverse (red_rep A x)})" using assms eq_equiv_class_iff2 in_quotient_imp_subset red_rep_the reln_equiv span_wordinverse by fastforce ultimately show ?thesis using red_rep_def[of "A" "((reln_tuple ⟨A⟩) `` {wordinverse (red_rep A x)})"] assms group.wordinverse_inv by (smt (verit, best) Image_singleton_iff quotientI red_rep_the redelem_unique refl_onD2 reln_refl) qed lemma red_rep_inv: assumes "x ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" shows "(red_rep A (inv⇘freegroup A⇙ x)) = wordinverse (red_rep A x)" proof- have grpA:"group (freegroup A)" by (simp add: freegroup_is_group) then have "x∈ carrier (freegroup A)" using assms freegroup_def by (metis partial_object.select_convs(1)) moreover have "x = (reln_tuple ⟨A⟩) `` {red_rep A x}" using assms by (simp add: red_rep_the) ultimately have "inv⇘(freegroup A)⇙ x = (reln_tuple ⟨A⟩) `` {wordinverse (red_rep A x)}" using group.wordinverse_inv grpA by blast then have "(red_rep A (inv⇘freegroup A⇙ x)) = red_rep A ((reln_tuple ⟨A⟩) `` {wordinverse (red_rep A x)})" by auto then show ?thesis unfolding red_rep_def red_rep_wordinv using assms by (metis equivinv_def red_rep_def red_rep_wordinv) qed lemma L2_wordinv: "L2 (wordinverse x) = (snd (L2 x), fst (L2 x))" by (simp add: FreeGroupMain.wordinverse_of_wordinverse left_tuple_def) lemma lex_L2_inv: assumes "(y,x) ∈ lex_L2_word A" shows "(y,inv⇘freegroup A⇙ x) ∈ lex_L2_word A" proof- have 1:"x ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using assms(1) unfolding lex_L2_word_def by blast then obtain invx where "invx = (inv⇘freegroup A⇙ x)" using freegroup_is_group by simp then have x:"(inv⇘freegroup A⇙ x) ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using m_inv_def[of "freegroup A" "x"] freegroup_def by (metis (no_types, lifting) freegroup_is_group group.inv_closed partial_object.select_convs(1) 1) have y: "y ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using assms(1) unfolding lex_L2_word_def by blast have 2:"(length (red_rep A y) < length (red_rep A x)) ∨ ((length (red_rep A y) = length (red_rep A x) ∧ (y,x) ∈ lex_L2_word' A))" using nat_less_def assms unfolding lex_L2_word_def lex_prod_def by fastforce then show ?thesis proof(cases "(length (red_rep A y) < length (red_rep A x))") case True then have "length (red_rep A y) < length (wordinverse (red_rep A x))" using length_wordinverse by metis then have "length (red_rep A y) < length (red_rep A (inv⇘freegroup A⇙ x))" using 1 red_rep_inv by metis then show ?thesis using x y by (simp add: lex_L2_word_def nat_less_def) next case False then have 3:"((length (red_rep A y) = length (red_rep A x) ∧ (y,x) ∈ lex_L2_word' A))" using 2 by blast then have 4:"length (red_rep A y) = length (red_rep A (inv⇘freegroup A⇙ x))" using 1 red_rep_inv by (metis length_wordinverse) then have "((λx. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) y , (λx. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) x) ∈ (lex_word <*lex*> lex_word)" using 3 unfolding lex_L2_word'_def by fastforce then have 5:"((min lex_word (L2 (red_rep A y))), (min lex_word (L2 (red_rep A x)))) ∈ lex_word ∨ (min lex_word (L2 (red_rep A y))) = (min lex_word (L2 (red_rep A x))) ∧ (max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A x))) ∈ lex_word" using lex_prod_def[of "lex_word" "lex_word"] by simp have "L2 (wordinverse (red_rep A x)) = (snd (L2 (red_rep A x)), fst (L2 (red_rep A x)))" using L2_wordinv by blast then have L2_winv:"min lex_word (L2 (red_rep A x)) = min lex_word (L2 (wordinverse (red_rep A x))) ∧ max lex_word (L2 (red_rep A x)) = max lex_word (L2 (wordinverse (red_rep A x)))" using wf_lex_word min.simps by (metis (no_types, lifting) lex_word_total max.simps prod.exhaust_sel wf_asym) then have "((min lex_word (L2 (red_rep A y))), (min lex_word (L2 (wordinverse(red_rep A x))))) ∈ lex_word ∨ (min lex_word (L2 (red_rep A y))) = (min lex_word (L2 (wordinverse(red_rep A x)))) ∧ (max lex_word (L2 (red_rep A y)), max lex_word (L2 (wordinverse(red_rep A x)))) ∈ lex_word" using 5 by auto then have "((min lex_word (L2 (red_rep A y))), (min lex_word (L2 (red_rep A (inv⇘freegroup A⇙ x))))) ∈ lex_word ∨ (min lex_word (L2 (red_rep A y))) = (min lex_word (L2 (red_rep A (inv⇘freegroup A⇙ x)))) ∧ (max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A (inv⇘freegroup A⇙ x)))) ∈ lex_word" using red_rep_inv 1 by force then have "(y,(inv⇘freegroup A⇙ x)) ∈ lex_L2_word' A" unfolding lex_L2_word'_def using x y by auto then show ?thesis using x y 2 4 lex_L2_word_length by blast qed qed lemma reduced_tl:"reduced (x#xs) \<Longrightarrow> reduced xs" by (metis append_Nil assoc_Cons reduced_leftappend) definition l_concat :: "'a list list \<Rightarrow> 'a list" where "l_concat l \<equiv> (foldr (@) l [])" fun m_concat where "m_concat H [] = \<one>\<^bsub>H\<^esub>"| "m_concat H (x#xs) = x \<otimes>\<^bsub>H\<^esub> (m_concat H xs)" lemma append_equivred_span: assumes "set l \<subseteq> carrier (freegroup S)" shows "l_concat (map (red_rep S) l) \<in> \<langle>S\<rangle>" proof- have "\<forall>x\<in> set l. \<forall>n\<in>x. n \<in> \<langle>S\<rangle>" using assms in_quotient_imp_subset reln_equiv unfolding freegroup_def by fastforce then have 1:"\<forall>x\<in> set l. x \<subseteq> \<langle>S\<rangle>" by auto then have "\<forall>x\<in> set l. x \<in> \<langle>S\<rangle> // reln_tuple \<langle>S\<rangle> " using assms freegroup_def by (metis partial_object.select_convs(1) subset_code(1)) moreover then have "\<forall>x\<in> set l. (red_rep S x \<in> x)" by (simp add: red_rep_the) ultimately have "\<forall>x\<in> set l. (red_rep S x \<in> \<langle>S\<rangle>)" using 1 by auto then have "set(map (red_rep S) l) \<subseteq> \<langle>S\<rangle>" by auto then show ?thesis unfolding l_concat_def proof(induction l) case Nil then show ?case using span_append freewords_on_def[of "S"] words_on.empty by auto next case (Cons a l) then have "set (map (red_rep S) l) \<subseteq> \<langle>S\<rangle>" by simp then have 1:"foldr (@) (map (red_rep S) l) [] \<in> \<langle>S\<rangle>" using Cons.IH by auto have "[(foldr (@) (map (red_rep S) (a # l)) [])] = [foldr (@) [((foldr (@) (map (red_rep S) [a]) [])@(foldr (@) (map (red_rep S) l) []))] []]" by simp then show ?case using span_append freewords_on_def 1 by (metis (no_types, lifting) Cons.prems concat.simps(2) concat_conv_foldr list.set_intros(1) list.simps(9) subset_code(1)) qed qed lemma assumes "set l \<subseteq> carrier (freegroup S)" shows "m_concat (freegroup S) l = (reln_tuple \<langle>S\<rangle>) `` {(l_concat (map(red_rep S) l))}" using assms proof(induction l) case Nil have "m_concat (freegroup S) [] = \<one>\<^bsub>freegroup S\<^esub>" unfolding m_concat.simps(2) by simp moreover have "l_concat (map (red_rep S) []) = []" unfolding l_concat_def by simp moreover have "reln_tuple \<langle>S\<rangle> `` {[]} = \<one>\<^bsub>freegroup S\<^esub>" using freegroup_def[of "S"] by simp ultimately show ?case by simp next case (Cons a l) then have "set l \<subseteq> carrier (freegroup S)" by simp then have I:"m_concat (freegroup S) l = reln_tuple \<langle>S\<rangle> `` {l_concat (map (red_rep S) l)}" using Cons.IH by auto have 1:"reln_tuple \<langle>S\<rangle> `` {l_concat (map (red_rep S) (a # l))} = reln_tuple \<langle>S\<rangle> `` {((red_rep S) a @ l_concat (map (red_rep S) l))}" unfolding l_concat_def by simp have a1:"a \<in> carrier (freegroup S)" using Cons by simp then have a:"(red_rep S) a \<in> \<langle>S\<rangle>" unfolding freegroup_def using red_rep_the in_quotient_imp_subset reln_equiv by fastforce have "l_concat (map (red_rep S) l) \<in> \<langle>S\<rangle>" using Cons.prems append_equivred_span unfolding freegroup_def by auto then have "reln_tuple \<langle>S\<rangle> `` {l_concat (map (red_rep S) (a # l))} = reln_tuple \<langle>S\<rangle> `` {(red_rep S) a} \<otimes>\<^bsub>freegroup S\<^esub> reln_tuple \<langle>S\<rangle> `` {(l_concat (map (red_rep S) l))}" using proj_append_wd[of "(red_rep S) a" "S" " l_concat (map (red_rep S) l)"] 1 a unfolding freegroup_def by auto moreover have "m_concat (freegroup S) (a # l) = a \<otimes>\<^bsub>freegroup S\<^esub> m_concat (freegroup S) l" unfolding m_concat.simps(2) by blast moreover have "a = reln_tuple \<langle>S\<rangle> `` {(red_rep S) a}" using red_rep_the a1 freegroup_def by (metis partial_object.select_convs(1)) ultimately show ?case using I by simp qed lemma reducedE: "\<exists>w. a ~ w \<and> reduced w" proof- have "a ~ (iter (length a) reduce) a" by (simp add: cancels_imp_rel iter_cancels_to) moreover have "reduced ((iter (length a) reduce) a)" by (simp add: reduced_iter_length) ultimately show ?thesis by blast qed lemma "\<exists>! w. a ~ w \<and> reduced w" proof(rule ex_ex1I) show "\<exists>w. a ~ w \<and> reduced w" using reducedE by blast next show "\<And>w y. a ~ w \<and> reduced w \<Longrightarrow> a ~ y \<and> reduced y \<Longrightarrow> w = y " proof- fix w y assume "a ~ w \<and> reduced w" and "a ~ y \<and> reduced y" moreover then have "w ~ y" using reln.sym reln.trans by blast ultimately show "w = y" by (simp add: reduced_cancel_eq reln_imp_cancels) qed qed fun a2 where "a2 (x,y,z) = x" fun b2 where "b2 (x,y,z) = z" fun p2 where "p2 (x,y,z) = y" lemma cancel2E: assumes "reduced x" and "reduced y" shows "\<exists>w. x = (a2 w) @ (p2 w) \<and> y = (wordinverse (p2 w)) @ (b2 w) \<and> reduced ((a2 w) @ (b2 w))" using assms proof(induction x) case Nil have "[] = [] @ []" by simp moreover have "y = wordinverse [] @ y" by simp moreover have "reduced ([] @ y)" using Nil.prems(2) by simp ultimately show ?case by simp next case (Cons z zs) have "reduced zs" using Cons.prems(1) reduced_tl by blast then obtain w where w:"zs = a2 w @ p2 w \<and> y = wordinverse (p2 w) @ b2 w \<and> reduced (a2 w @ b2 w)" using Cons.IH Cons.prems(2) by blast then show ?case proof(cases "a2 w = []") case True note a2 = this then show ?thesis proof(cases "b2 w = []") case True have "(z#zs) = [z] @ p2 w" using a2 w by simp moreover have "reduced ([z] @ b2 w)" using True by simp moreover define w' where w':"w' = ([z], p2 w, b2 w)" moreover have "a2 w' = [z]" using w' by simp moreover have "b2 w' = b2 w" using w' by simp moreover have "p2 w' = p2 w" using w' by simp ultimately show ?thesis using w by metis next case False then obtain b bs where b2:"b#bs = b2 w" using list.exhaust by metis have rb2: "reduced (b2 w)" using w reduced_leftappend by blast then have rbs: "reduced bs" using b2 using reduced_tl by metis then show ?thesis proof(cases "z = inverse b") case True then have 1:"wordinverse ([z]@(p2 w)) = (wordinverse (p2 w)) @ [b]" using inverse_of_inverse by fastforce define w' where w':"w' = (([]::('a,'b) word), ([z]@(p2 w)), bs)" moreover then have "(z#zs) = a2 w' @ p2 w'" using w a2 by simp moreover have "y = wordinverse (p2 w') @ (b2 w')" using w w' 1 b2 by auto moreover have "reduced (a2 w' @ b2 w')" using w' rbs by simp ultimately show ?thesis by blast next case False define w' where w': "w' = ([z], (p2 w),b#bs)" moreover then have "(z#zs) = a2 w' @ p2 w'" using w a2 by simp moreover have "y = wordinverse (p2 w') @ (b2 w')" using w w' b2 by auto moreover have "(a2 w' @ b2 w') = (z#b#bs)" using b2 w' by simp moreover then have "reduced (a2 w' @ b2 w')" using rb2 b2 False reduced.simps(3) by metis ultimately show ?thesis by blast qed qed next case False then obtain a as where a2:"a2 w = a#as" using list.exhaust by metis then have za:"z \<noteq> inverse a" using Cons.prems(1) w by auto define w' where w':"w' = ((z#a#as), p2 w, b2 w)" moreover have zzs:"(z#zs) = a2 w' @ p2 w'" using w w' a2 by simp moreover have "y = wordinverse (p2 w') @ (b2 w')" using w w' by simp moreover have "reduced ((a2 w') @ (b2 w'))" using Cons.prems(1) za w w' zzs reduced.simps(3) by auto ultimately show ?thesis by blast qed qed lemma cancel2E': assumes "reduced x" and "reduced y" shows "\<exists>! w. x = (a2 w) @ (p2 w) \<and> y = (wordinverse (p2 w)) @ (b2 w) \<and> reduced ((a2 w) @ (b2 w))" proof(rule ex_ex1I) show "\<exists>w. x = a2 w @ p2 w \<and> y = wordinverse (p2 w) @ b2 w \<and> reduced (a2 w @ b2 w)" using cancel2E assms by blast next fix w v assume w:"x = a2 w @ p2 w \<and> y = wordinverse (p2 w) @ b2 w \<and> reduced (a2 w @ b2 w)" and v: "x = a2 v @ p2 v \<and> y = wordinverse (p2 v) @ b2 v \<and> reduced (a2 v @ b2 v)" then obtain c where c:"p2 w = c @ p2 v \<and> (a2 v = a2 w @ c) \<or> p2 v = c @ p2 w \<and> (a2 w = a2 v @ c)" using append_eq_append_conv2[of "a2 w" "p2 w" "a2 v" "p2 v"] by metis have wd: "w = (a2 w, p2 w, b2 w)" by (metis a2.simps b2.elims p2.simps) have vd: "v = (a2 v, p2 v, b2 v)" by (metis a2.simps b2.elims p2.simps) then show "w = v" proof(cases "c = []") case True then have "p2 w = p2 v" using c by auto moreover then have "a2 w = a2 v" using w v by simp moreover then have "b2 w = b2 v" using v w by auto ultimately show ?thesis using wd vd by simp next case False note cn = this then show ?thesis proof(cases "p2 w = c @ p2 v \<and> (a2 v = a2 w @ c)") case True then have "wordinverse (p2 w) = wordinverse (p2 v) @ wordinverse c" using c wordinverse_append by metis then have "wordinverse c @ b2 w = b2 v" using w v by auto then have 1:"a2 v @ b2 v = a2 w @ c @ wordinverse c @ b2 w" using True by simp then have "(a2 v @ b2 v) ~ a2 w @ c @ wordinverse c @ b2 w" using reln.refl by simp moreover have "(c @ wordinverse c) ~ []" by (simp add: wordinverse_inverse) ultimately have "(a2 v @ b2 v) ~ a2 w @ b2 w" using 1 by (metis (no_types, lifting) append_Nil2 append_assoc mult reln.refl) then have "(a2 v @ b2 v) = a2 w @ b2 w" using w v by (simp add: reduced_cancel_eq reln_imp_cancels) moreover have "(a2 v @ b2 v) \<noteq> a2 w @ b2 w" using 1 cn by simp ultimately show ?thesis by blast next case False then have F:"p2 v = c @ p2 w \<and> (a2 w = a2 v @ c)" using c by blast then have "wordinverse (p2 v) = wordinverse (p2 w) @ wordinverse c" using c wordinverse_append by metis then have "wordinverse c @ b2 v = b2 w" using w v by auto then have 1:"a2 w @ b2 w = a2 v @ c @ wordinverse c @ b2 v" using F by simp then have "(a2 w @ b2 w) ~ a2 v @ c @ wordinverse c @ b2 v" using reln.refl by simp moreover have "(c @ wordinverse c) ~ []" by (simp add: wordinverse_inverse) ultimately have "(a2 w @ b2 w) ~ a2 v @ b2 v" using 1 by (metis (no_types, lifting) append_Nil2 append_assoc mult reln.refl) then have "(a2 w @ b2 w) = a2 v @ b2 v" using w v by (simp add: reduced_cancel_eq reln_imp_cancels) moreover have "(a2 w @ b2 w) \<noteq> a2 v @ b2 v" using 1 cn by simp ultimately show ?thesis by blast qed qed qed definition cancel2 :: "('a,'b) word \<Rightarrow> ('a,'b) word \<Rightarrow> (('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word)" (infix "\<oslash>\<^bsub>2\<^esub>" 65) where "cancel2 x y = (THE w. x = a2 w @ p2 w \<and> y = (wordinverse (p2 w)) @ b2 w \<and> reduced (a2 w@b2 w))" lemma cancel2_the: assumes "reduced x" and "reduced y" shows "x = a2 (x\<oslash>\<^bsub>2\<^esub>y) @ p2 (x\<oslash>\<^bsub>2\<^esub>y) \<and> y = (wordinverse (p2 (x\<oslash>\<^bsub>2\<^esub>y))) @ b2 (x\<oslash>\<^bsub>2\<^esub>y) \<and> reduced (a2 (x\<oslash>\<^bsub>2\<^esub>y)@b2 (x\<oslash>\<^bsub>2\<^esub>y))" unfolding cancel2_def by(rule theI', simp add: assms cancel2E') definition N1 :: "('a,'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> bool" where "N1 x y = ((x \<noteq> wordinverse y) \<longrightarrow> (less_eq (length (p2 (x\<oslash>\<^bsub>2\<^esub>y))) (length (a2 (x\<oslash>\<^bsub>2\<^esub>y))) \<and> less_eq (length (p2 (x\<oslash>\<^bsub>2\<^esub>y))) (length (b2 (x\<oslash>\<^bsub>2\<^esub>y)))))" lemma red_rep_proj_app: assumes "k ∈ (⟨A⟩ // reln_tuple ⟨A⟩) ∧ m ∈ (⟨A⟩ // reln_tuple ⟨A⟩)" shows "((red_rep A (proj_append ⟨A⟩ k m))) = iter (length ((red_rep A k) @ (red_rep A m))) reduce ((red_rep A k) @ (red_rep A m))" proof- let ?rk = "red_rep A k" let ?rm = "red_rep A m" let ?rkm = "((iter (length (?rk@?rm)) reduce (?rk@?rm)))" have appA:"(?rk@?rm) ∈ ⟨A⟩" using red_rep_def assms(1) by (smt (verit) append_congruent equiv_2f_clos red_rep_the reln_equiv) have 1:"equiv ⟨A⟩ (reln_tuple ⟨A⟩)" by (simp add: reln_equiv) moreover have "(red_rep A k) ∈ ⟨A⟩ ∧ (red_rep A m) ∈ ⟨A⟩" using red_rep_def assms calculation in_quotient_imp_subset red_rep_the by blast moreover have "proj_append ⟨A⟩ (reln_tuple ⟨A⟩ `` {red_rep A k}) (reln_tuple ⟨A⟩ `` {red_rep A m}) = reln_tuple ⟨A⟩ `` {red_rep A k @ red_rep A m}" unfolding proj_append_def using assms append_congruent[of "A"] proj_append_wd[of "red_rep A k" "A" "red_rep A m"] calculation(2) proj_append_def by blast ultimately have 2:"proj_append ⟨A⟩ k m = reln_tuple ⟨A⟩ `` {red_rep A k @ red_rep A m}" using assms by (metis (no_types, opaque_lifting) red_rep_the) then have "(?rkm) ~ (?rk@?rm)" using cancels_imp_rel iter_cancels_to reln.sym by blast moreover then have "(?rkm) ∈ ⟨A⟩" using appA cancels_to_preserves iter_cancels_to by blast ultimately have crc: "((?rk@?rm), ?rkm) ∈ reln_tuple ⟨A⟩" using appA reln_tuple_def by (smt (z3) case_prodI mem_Collect_eq reln.sym) then have "(reln_tuple ⟨A⟩`` {?rkm}) = (reln_tuple ⟨A⟩ `` {?rk@?rm})" using "1" equiv_class_eq_iff by fastforce moreover then have a:"?rkm ∈ (reln_tuple ⟨A⟩ `` {?rk@?rm})" using crc by simp moreover have "reduced ?rkm" using reduced_iter_length by blast ultimately have "red_rep A (reln_tuple ⟨A⟩ `` {?rk@?rm}) = ?rkm" using red_rep_def assms(1) 2 by (metis (no_types, lifting) proj_append_clos red_rep_the redelem_unique) then show ?thesis unfolding proj_append_def using 1 2 assms append_congruent[of "A"] proj_append_wd[of "red_rep A k" "A" "red_rep A m"] red_rep_def equiv_2f_wd[of "(freewords_on A)" "(reln_tuple (freewords_on A))" "append" "red_rep A k" "red_rep A m"] by (simp add: proj_append_def) qed lemma iter_wordinv: assumes "(k @ m) = (a@b@(wordinverse b)@c)" "reduced (a@c)" shows "(iter (length (k@m)) reduce (k@m)) = (a@c)" proof- have "(iter (length (b@(wordinverse b))) reduce (b@(wordinverse b))) = []" using FreeGroupMain.wordinverse_inverse cancels_imp_iter reln_imp_cancels by fastforce then show ?thesis using assms by (metis (no_types, opaque_lifting) append.assoc append.left_neutral cancels_eq_leftappend cancels_eq_rightappend cancels_imp_iter iter_imp_cancels reduced_iter_eq reduced_iter_length) qed lemma N1_length: assumes "k ∈ (⟨A⟩ // reln_tuple ⟨A⟩) ∧ m ∈ (⟨A⟩ // reln_tuple ⟨A⟩)" "N1 (red_rep A k) (red_rep A m)" "((red_rep A k) ≠ wordinverse (red_rep A m))" "(length ((red_rep A (proj_append ⟨A⟩ k m)))) = b" "length (red_rep A k) = a" "length (red_rep A m) = c" shows "(greater_eq b a) ∧ (greater_eq b c)" proof- let ?rk = "red_rep A k" let ?rm = "red_rep A m" have N1:"(less_eq (length (p2 (?rk⊘⇘2⇙?rm))) (length (a2 (?rk⊘⇘2⇙?rm)))) ∧ less_eq (length (p2 (?rk⊘⇘2⇙?rm))) (length (b2 (?rk⊘⇘2⇙?rm)))" using assms(2,3) N1_def by blast then have x:"?rk = ((a2 (?rk⊘⇘2⇙?rm)) @ (p2 (?rk⊘⇘2⇙?rm)))" using cancel2_def[of "?rk" "?rm"] cancel2_the red_rep_def assms(1) red_rep_the by blast have y:"?rm = ((wordinverse(p2 (?rk⊘⇘2⇙?rm))) @ (b2 (?rk⊘⇘2⇙?rm)))" using cancel2_def[of "?rk" "?rm"] cancel2_the red_rep_def assms(1) red_rep_the by blast have rac:"reduced ((a2 (?rk⊘⇘2⇙?rm))@(b2 (?rk⊘⇘2⇙?rm)))" using cancel2_def[of "?rk" "?rm"] cancel2_the red_rep_def assms(1) red_rep_the by blast have a:"length(p2 (?rk⊘⇘2⇙?rm)) ≤ length (a2 (?rk⊘⇘2⇙?rm))" using x y rac N1_def assms(2) using N1 by blast have b:"length(p2 (?rk⊘⇘2⇙?rm)) ≤ length (b2 (?rk⊘⇘2⇙?rm))" using x y rac N1_def assms(2) using N1 by blast have 1:"((red_rep A (proj_append ⟨A⟩ k m))) = (iter (length (?rk @ ?rm)) reduce (?rk @ ?rm))" using assms(1) red_rep_proj_app by blast then have "(?rk @ ?rm) = ((a2 (?rk⊘⇘2⇙?rm)) @ (p2 (?rk⊘⇘2⇙?rm))@(wordinverse(p2 (?rk⊘⇘2⇙?rm))) @ (b2 (?rk⊘⇘2⇙?rm)))" using x y by auto then have 2:"(iter (length (?rk @ ?rm)) reduce (?rk @ ?rm)) = ((a2 (?rk⊘⇘2⇙?rm)) @ (b2 (?rk⊘⇘2⇙?rm)))" using rac iter_wordinv by blast have "(length (iter (length (?rk @ ?rm)) reduce (?rk @ ?rm))) ≤ length (?rk @ ?rm)" using length_reduce_iter by blast have "(b ≥ (length ?rk)) ∧ (b ≥ (length ?rm))" using a b 1 2 by (metis (no_types, lifting) add_le_mono1 assms(4) length_append length_wordinverse nat_add_left_cancel_le x y) then show ?thesis using assms(3,4,5,6) a b by auto qed lemma reduced_reln_eq: "a ~ b \<Longrightarrow> reduced a \<Longrightarrow> reduced b \<Longrightarrow> a = b" by (simp add: reduced_cancel_eq reln_imp_cancels) lemma cancel2_reln: assumes "x = a @ p \<and> y = (wordinverse p) @ b" shows "(x@y) ~ (a@b)" proof- have "(p @ wordinverse p) ~ []" by (simp add: wordinverse_inverse) then show ?thesis using assms mult reln.refl by (metis append_Nil2 append.assoc) qed lemma reln_eq: assumes "reln_tuple ⟨A⟩ `` {a} = reln_tuple ⟨A⟩ `` {b}" "a ∈ ⟨A⟩" "b ∈ ⟨A⟩" shows "a ~ b" using assms unfolding reln_tuple_def by blast lemma redrep_in: assumes "x ∈ carrier (freegroup A)" shows "red_rep A x ∈ ⟨A⟩" using assms red_rep_def red_rep_the unfolding freegroup_def using Union_quotient reln_equiv by fastforce lemma mult_reln: assumes "x ∈ carrier (freegroup A)" "y ∈ carrier (freegroup A)" shows "(red_rep A (x ⊗⇘F⇘A⇙⇙ y)) ~ ((red_rep A x) @ (red_rep A y))" proof- have "x = reln_tuple ⟨A⟩ `` {red_rep A x}" using red_rep_def red_rep_the assms(1) unfolding freegroup_def by fastforce moreover have 1:"red_rep A x ∈ ⟨A⟩" using assms(1) redrep_in by blast moreover have "y = reln_tuple ⟨A⟩ `` {red_rep A y}" using red_rep_def red_rep_the assms(2) unfolding freegroup_def by fastforce moreover have 2: "red_rep A y ∈ ⟨A⟩" using assms(2) redrep_in by blast ultimately have "reln_tuple ⟨A⟩ `` {(red_rep A (x ⊗⇘F⇘A⇙⇙ y))} = reln_tuple ⟨A⟩ `` {((red_rep A x) @ (red_rep A y))}" using proj_append_wd unfolding freegroup_def by (metis assms(1) assms(2) freegroup_def monoid.select_convs(1) partial_object.select_convs(1) proj_append_clos red_rep_the) moreover have "((red_rep A x) @ (red_rep A y)) ∈ ⟨A⟩" using 1 2 unfolding freewords_on_def by (simp add: span_append) moreover have "(red_rep A (x ⊗⇘F⇘A⇙⇙ y)) ∈ ⟨A⟩" by (simp add: assms(1) assms(2) freegroup_is_group group.subgroup_self redrep_in subgroup.m_closed) ultimately show ?thesis using reln_eq by auto qed lemma length_N1: assumes "x ∈ carrier (freegroup A)" "y ∈ carrier (freegroup A)" "length (red_rep A (x ⊗⇘F⇘A⇙⇙ y)) ≥ length (red_rep A x) ∧ length (red_rep A (x ⊗⇘F⇘A⇙⇙ y)) ≥ length (red_rep A y)" shows "N1 (red_rep A x) (red_rep A y)" proof- let ?x = "(red_rep A x)" let ?y = "(red_rep A y)" let ?xy = "(cancel2 ?x ?y)" have xy: "(x ⊗⇘F⇘A⇙⇙ y) ∈ carrier (freegroup A)" by (simp add: assms(1) assms(2) freegroup_is_group group.subgroupE(4) group.subgroup_self) have 1:"reduced ?x" using assms(1) red_rep_def red_rep_the unfolding freegroup_def by fastforce moreover have 2:"reduced ?y" using assms(2) red_rep_def red_rep_the unfolding freegroup_def by fastforce ultimately have "((red_rep A x) @ (red_rep A y)) ~ ((a2 ?xy) @ (b2 ?xy))" by (metis cancel2_reln cancel2_the) then have "(red_rep A (x ⊗⇘F⇘A⇙⇙ y)) ~ ((a2 ?xy) @ (b2 ?xy))" using assms mult_reln using reln.trans by blast moreover have "reduced ((a2 ?xy) @ (b2 ?xy))" by (simp add: "1" "2" cancel2_the) moreover have "reduced (red_rep A (x ⊗⇘F⇘A⇙⇙ y))" using xy red_rep_def red_rep_the unfolding freegroup_def by fastforce ultimately have 3: "(red_rep A (x ⊗⇘F⇘A⇙⇙ y)) = ((a2 ?xy) @ (b2 ?xy))" by (simp add: reduced_reln_eq) have "?x = (a2 ?xy) @ (p2 ?xy)" using 1 2 by (simp add: cancel2_the) then have "length ((a2 ?xy) @ (b2 ?xy)) ≥ length ((a2 ?xy) @ (p2 ?xy))" using assms(3) 3 by auto then have A:"length (b2 ?xy) ≥ length (p2 ?xy)" by auto have "?y = wordinverse (p2 ?xy) @ (b2 ?xy)" using 1 2 by (simp add: cancel2_the) then have "length ((a2 ?xy) @ (b2 ?xy)) ≥ length (wordinverse (p2 ?xy) @ (b2 ?xy))" using 3 assms(3) by auto then have "length (a2 ?xy) ≥ length (wordinverse (p2 ?xy))" by auto then have "length (a2 ?xy) ≥ length (p2 ?xy)" by (metis length_wordinverse) then show ?thesis unfolding N1_def using A by blast qed fun a3 where "a3 (v,w,x,y,z) = v" fun b3 where "b3 (v,w,x,y,z) = x" fun c3 where "c3 (v,w,x,y,z) = z" fun p3 where "p3 (v,w,x,y,z) = w" fun q3 where "q3 (v,w,x,y,z) = y" definition cancel3 :: "('a,'b) word \<Rightarrow> ('a,'b) word \<Rightarrow> ('a,'b) word \<Rightarrow> (('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word)" ("\<oslash>\<^bsub>3\<^esub>") where "cancel3 x y z = (THE w. x = a3 w @ (p3 w) \<and> y = wordinverse (p3 w) @ b3 w @ (q3 w) \<and> z = (wordinverse (q3 w)) @ (c3 w) \<and> reduced (a3 w@b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w))" lemma tuple3: "\<forall>v. v = (a3 v, p3 v, b3 v, q3 v, c3 v)" by simp lemma appendeq_length1: assumes "a@b = c@d" and "length a < length b" and "length d < length c" shows "length a < length c" using assms by (metis (no_types, lifting) length_append less_add_eq_less linorder_neqE_nat order.strict_trans) lemma appendeq_length2: assumes "a@b = c@d" and "length a < length b" and "length d < length c" shows "length d < length b" using assms by (metis (no_types, lifting) length_append less_add_eq_less linorder_neqE_nat order.strict_trans) lemma appendeq_length3: assumes "a@b = c@d" and "length a < length b" and "length d = length c" shows "length a < length c" using assms by (metis (no_types, lifting) length_append less_add_eq_less linorder_neqE_nat order.strict_trans) lemma appendeq_length4: assumes "a@b = c@d" and "length a < length b" and "length d = length c" shows "length d < length b" using assms by (metis (no_types, lifting) length_append less_add_eq_less linorder_neqE_nat order.strict_trans) lemma appendeq_length5: assumes "a@b = c@d" and "length a = length b" and "length d < length c" shows "length a < length c" using assms by (metis (no_types, lifting) append_eq_append_conv dual_order.strict_trans length_append less_add_eq_less linorder_neqE_nat) lemma appendeq_length6: assumes "a@b = c@d" and "length a = length b" and "length d < length c" shows "length d < length b" using assms by (metis (no_types, lifting) append_eq_append_conv dual_order.strict_trans length_append less_add_eq_less linorder_neqE_nat) lemma overlap_middle_exists: assumes "a@b = c@d" and "length a \<le> length b" and "length d \<le> length c" shows "\<exists>x. a@x@d = a@b" proof(cases "length a < length b") case True note ab = this then show ?thesis proof(cases "length d < length c") case True from assms(1) have "length a < length c" using ab True appendeq_length1 by auto hence y:"\<exists>y. a@y = c" using assms(1) overlapleftexist by blast from assms(1) have "length d < length b" using ab True appendeq_length2 by auto hence x:"\<exists>x. x@d = b" using assms(1) overlaprightexist by metis from x y assms(1) show ?thesis by auto next case False then have l:"length d = length c" using assms(3) by simp then have "length a < length c" using assms(1) ab appendeq_length3 by blast hence y:"\<exists>y. a@y = c" using assms(1) overlapleftexist by blast from assms(1) have "length d < length b" using ab l appendeq_length4 by blast hence x:"\<exists>x. x@d = b" using assms(1) overlaprightexist by metis from x y assms(1) show ?thesis by auto qed next case False then have la:"length a = length b" using assms(2) by auto then show ?thesis proof(cases "length d < length c") case True from assms(1) have "length a < length c" using True la appendeq_length5 by blast hence y:"\<exists>y. a@y = c" using assms(1) overlapleftexist by blast from assms(1) have "length d < length b" using True la appendeq_length6 by blast hence x:"\<exists>x. x@d = b" using assms(1) overlaprightexist by metis from x y assms(1) show ?thesis by auto next case False then have l:"length d = length c" using assms(3) by simp then have "length a = length c" using assms(1) la by (metis (mono_tags, lifting) "appendeq_length1" length_append less_add_eq_less nat_neq_iff) then show ?thesis using assms(1) by auto qed qed lemma cancel3E: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "\<exists>w. x = a3 w @ (p3 w) \<and> y = wordinverse (p3 w) @ b3 w @ (q3 w) \<and> z = (wordinverse (q3 w)) @ (c3 w) \<and> reduced (a3 w @ b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w)" proof- have xy:"x = a2 (x\<oslash>\<^bsub>2\<^esub>y) @ p2 (x\<oslash>\<^bsub>2\<^esub>y) \<and> y = (wordinverse (p2 (x\<oslash>\<^bsub>2\<^esub>y))) @ b2 (x\<oslash>\<^bsub>2\<^esub>y) \<and> reduced (a2 (x\<oslash>\<^bsub>2\<^esub>y)@b2 (x\<oslash>\<^bsub>2\<^esub>y))" using assms(1,2) cancel2_the by fastforce then have 1:"(less_eq (length (p2 (x\<oslash>\<^bsub>2\<^esub>y))) (length (a2 (x\<oslash>\<^bsub>2\<^esub>y))) \<and> less_eq (length (p2 (x\<oslash>\<^bsub>2\<^esub>y))) (length (b2 (x\<oslash>\<^bsub>2\<^esub>y))))" using assms(4,6) unfolding N1_def by blast have yz:"y = a2 (y\<oslash>\<^bsub>2\<^esub>z) @ p2 (y\<oslash>\<^bsub>2\<^esub>z) \<and> z = (wordinverse (p2 (y\<oslash>\<^bsub>2\<^esub>z))) @ b2 (y\<oslash>\<^bsub>2\<^esub>z) \<and> reduced (a2 (y\<oslash>\<^bsub>2\<^esub>z)@b2 (y\<oslash>\<^bsub>2\<^esub>z))" using assms(2,3) cancel2_the by fastforce then have 2:"(less_eq (length (p2 (y\<oslash>\<^bsub>2\<^esub>z))) (length (a2 (y\<oslash>\<^bsub>2\<^esub>z))) \<and> less_eq (length (p2 (y\<oslash>\<^bsub>2\<^esub>z))) (length (b2 (y\<oslash>\<^bsub>2\<^esub>z))))" using assms(5,7) unfolding N1_def by blast let ?a = "a2 (x\<oslash>\<^bsub>2\<^esub>y)" let ?b1 = "b2 (x\<oslash>\<^bsub>2\<^esub>y)" let ?b2 = "a2 (y\<oslash>\<^bsub>2\<^esub>z)" let ?c = "b2 (y\<oslash>\<^bsub>2\<^esub>z)" let ?p = "p2 (x\<oslash>\<^bsub>2\<^esub>y)" let ?q = "p2 (y\<oslash>\<^bsub>2\<^esub>z)" have "wordinverse (p2 (x \<oslash>\<^bsub>2\<^esub> y)) @ b2 (x \<oslash>\<^bsub>2\<^esub> y) = a2 (y \<oslash>\<^bsub>2\<^esub> z) @ p2 (y \<oslash>\<^bsub>2\<^esub> z)" using xy yz by simp moreover have "(length ?p) = (length (wordinverse ?p))" using length_wordinverse by blast moreover then have "length (wordinverse (p2 (x \<oslash>\<^bsub>2\<^esub> y))) \<le> length (b2 (x \<oslash>\<^bsub>2\<^esub> y))" using 1 by auto moreover have "length (p2 (y \<oslash>\<^bsub>2\<^esub> z)) \<le> length (a2 (y \<oslash>\<^bsub>2\<^esub> z))" using 2 by simp ultimately obtain b where b:"(wordinverse ?p)@b@(?q) = y" using 1 2 xy yz overlap_middle_exists[of "(wordinverse ?p)" "?b1" "?b2" "?q"] by auto define w where w:"w = (?a, ?p, b, ?q, ?c)" then have "x = a3 w @ (p3 w)" using xy by auto moreover have "y = wordinverse (p3 w) @ b3 w @ (q3 w)" using w b by auto moreover have "z = (wordinverse (q3 w)) @ (c3 w)" using w yz by auto moreover have "reduced (a3 w @ b3 w @ q3 w)" using xy yz w b a3.simps b3.simps q3.simps by (metis same_append_eq) moreover have "reduced (wordinverse (p3 w) @ b3 w @ c3 w)" using xy yz w b p3.simps b3.simps c3.simps by (metis (no_types, lifting) append.assoc append_same_eq) ultimately show ?thesis using w by blast qed lemma cancel3E': assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "\<exists>!w. x = a3 w @ (p3 w) \<and> y = wordinverse (p3 w) @ b3 w @ (q3 w) \<and> z = (wordinverse (q3 w)) @ (c3 w) \<and> reduced (a3 w@b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w)" proof(rule ex_ex1I) show "\<exists>w. x = a3 w @ p3 w \<and> y = wordinverse (p3 w) @ b3 w @ q3 w \<and> z = wordinverse (q3 w) @ c3 w \<and> reduced (a3 w @ b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w)" using cancel3E assms by blast next fix v w assume v:"x = a3 (v::(('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word)) @ p3 v \<and> y = wordinverse (p3 v) @ b3 v @ q3 v \<and> z = wordinverse (q3 v) @ c3 v \<and> reduced (a3 v @ b3 v @ q3 v) \<and> reduced (wordinverse (p3 v) @ b3 v @ c3 v)" and w: "x = a3 (w::(('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word \<times> ('a,'b) word)) @ p3 w \<and> y = wordinverse (p3 w) @ b3 w @ q3 w \<and> z = wordinverse (q3 w) @ c3 w \<and> reduced (a3 w @ b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w)" define v1 where v1:"v1 = (a3 v, p3 v, (b3 v @ q3 v))" define w1 where w1:"w1 = (a3 w, p3 w, (b3 w @ q3 w))" have "x = a2 v1 @ p2 v1 \<and> y = wordinverse (p2 v1) @ b2 v1 \<and> reduced (a2 v1 @ b2 v1)" using v v1 by simp moreover have "x = a2 w1 @ p2 w1 \<and> y = wordinverse (p2 w1) @ b2 w1 \<and> reduced (a2 w1 @ b2 w1)" using w w1 by simp ultimately have 1:"v1 = w1" using cancel2E' assms(1,2) by blast define v2 where v2:"v2 = (wordinverse (p3 v) @ b3 v, q3 v, c3 v)" define w2 where w2:"w2 = (wordinverse (p3 w) @ b3 w, q3 w, c3 w)" have "y = a2 v2 @ p2 v2 \<and> z = wordinverse (p2 v2) @ b2 v2 \<and> reduced (a2 v2 @ b2 v2)" using v v2 by simp moreover have "y = a2 w2 @ p2 w2 \<and> z = wordinverse (p2 w2) @ b2 w2 \<and> reduced (a2 w2 @ b2 w2)" using w w2 by simp ultimately have "v2 = w2" using cancel2E' assms(2,3) by blast then have 2:"a3 v = a3 w \<and> p3 v = p3 w \<and> q3 v = q3 w \<and> c3 v = c3 w" using 1 v1 v2 w1 w2 by fast then moreover have "b3 v = b3 w" using v w by simp moreover have "v = (a3 v, p3 v, b3 v, q3 v, c3 v)" using tuple3 by blast moreover have "w = (a3 w, p3 w, b3 w, q3 w, c3 w)" using tuple3 by blast ultimately show "v = w" by presburger qed lemma cancel3_the: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "x = a3 (\<oslash>\<^bsub>3\<^esub> x y z) @ (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> y = wordinverse (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) @ b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ (q3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> z = (wordinverse (q3 (\<oslash>\<^bsub>3\<^esub> x y z))) @ (c3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> reduced (a3 (\<oslash>\<^bsub>3\<^esub> x y z)@b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ q3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> reduced (wordinverse (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) @ b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ c3 (\<oslash>\<^bsub>3\<^esub> x y z))" unfolding cancel3_def by(rule theI', simp add: assms cancel3E') lemma cancel3_reln: assumes "x = a @ p \<and> y = (wordinverse p) @ b @ q \<and> z = (wordinverse q) @ c" shows "(x@y@z) ~ (a@b@c)" proof- have "(p @ wordinverse p) ~ []" by (simp add: wordinverse_inverse) then have 1:"(x@y@z) ~ (a@b@q@(wordinverse q)@c)" using assms cancel2_reln by auto have "(q @ wordinverse q) ~ []" by (simp add: wordinverse_inverse) then have "(a@b@q@(wordinverse q)@c) ~ (a@b@c)" by (metis append_assoc cancel2_reln) then show ?thesis using trans 1 by fast qed definition N2 :: "('a,'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> ('a, 'b) word \<Rightarrow> bool" where "N2 x y z = ((x \<noteq> wordinverse y \<and> y \<noteq> wordinverse z) \<longrightarrow> (b3 (\<oslash>\<^bsub>3\<^esub> x y z) \<noteq> []))" lemma reduced_overlap: assumes "reduced (a@b)" and "reduced (b@c)" and "b \<noteq> []" shows "reduced (a@b@c)" using assms proof(induction a) case Nil then show ?case by simp next case (Cons a1 a2) then moreover have "reduced (a2 @ b)" by (metis assoc_Cons reduced_tl) ultimately have r:"reduced (a2@b@c)" by simp obtain b1 b2 where b:"b = b1#b2" using Cons.prems(3) list.exhaust by blast show ?case proof(cases "a2 = []") case True then have "a1 \<noteq> inverse b1" using Cons.prems(1) b by auto then show ?thesis using b True r by auto next case False then obtain a3 a4 where "a2 = a3#a4" using list.exhaust by blast moreover then have "a1 \<noteq> inverse a3" using Cons.prems(1) by auto ultimately show ?thesis using r by auto qed qed lemma cancel3_b: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "N2 x y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "reduced (a3 (\<oslash>\<^bsub>3\<^esub> x y z) @ b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ c3 (\<oslash>\<^bsub>3\<^esub> x y z))" proof- have 1:"x = a3 (\<oslash>\<^bsub>3\<^esub> x y z) @ (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> y = wordinverse (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) @ b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ (q3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> z = (wordinverse (q3 (\<oslash>\<^bsub>3\<^esub> x y z))) @ (c3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> reduced (a3 (\<oslash>\<^bsub>3\<^esub> x y z)@b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ q3 (\<oslash>\<^bsub>3\<^esub> x y z)) \<and> reduced (wordinverse (p3 (\<oslash>\<^bsub>3\<^esub> x y z)) @ b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ c3 (\<oslash>\<^bsub>3\<^esub> x y z))" using assms cancel3_the by blast then have "reduced (b3 (\<oslash>\<^bsub>3\<^esub> x y z) @ c3 (\<oslash>\<^bsub>3\<^esub> x y z))" using reduced_leftappend by auto moreover have "reduced (a3 (\<oslash>\<^bsub>3\<^esub> x y z)@b3 (\<oslash>\<^bsub>3\<^esub> x y z))" using reduced_rightappend 1 by (metis append.assoc) moreover have "(b3 (\<oslash>\<^bsub>3\<^esub> x y z) \<noteq> [])" using assms(6,7,8) unfolding N2_def by blast ultimately show ?thesis using reduced_overlap by blast qed lemma cancel_a2_pb3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "a2 (cancel2 y z) = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z)" proof- have 1:"x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z)) \<and> y = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ (q3 (cancel3 x y z)) \<and> z = (wordinverse (q3 (cancel3 x y z))) @ (c3 (cancel3 x y z)) \<and> reduced (a3 (cancel3 x y z) @ b3 (cancel3 x y z) @ q3 (cancel3 x y z)) \<and> reduced (wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ c3 (cancel3 x y z))" using assms cancel3_the by blast have 2:"y = (a2 (cancel2 y z)) @ (p2 (cancel2 y z)) \<and> z = (wordinverse (p2 (cancel2 y z))) @ (b2 (cancel2 y z)) \<and> reduced ((a2 (cancel2 y z)) @ (b2 (cancel2 y z)))" using assms(2,3) by (simp add: cancel2_the) define w2 where 3:"w2 = ((wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z)), (q3 (cancel3 x y z)), (c3 (cancel3 x y z)))" then have "y = (a2 w2) @ (p2 w2) \<and> z = (wordinverse (p2 w2)) @ (b2 w2) \<and> reduced ((a2 w2) @ (b2 w2))" using 1 by auto then have "w2 = (cancel2 y z)" using 2 assms(2,3) cancel2E' by blast then have "a2 w2 = a2 (cancel2 y z)" by simp then show ?thesis using 3 by simp qed lemma cancel_a2_a3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x \<noteq> wordinverse y" and "y \<noteq> wordinverse z" shows "a2 (cancel2 x y) = a3 (cancel3 x y z)" proof- have 1:"x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z)) \<and> y = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ (q3 (cancel3 x y z)) \<and> z = (wordinverse (q3 (cancel3 x y z))) @ (c3 (cancel3 x y z)) \<and> reduced (a3 (cancel3 x y z) @ b3 (cancel3 x y z) @ q3 (cancel3 x y z)) \<and> reduced (wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ c3 (cancel3 x y z))" using assms cancel3_the by blast have 2:"x = (a2 (cancel2 x y)) @ (p2 (cancel2 x y)) \<and> y = (wordinverse (p2 (cancel2 x y))) @ (b2 (cancel2 x y)) \<and> reduced ((a2 (cancel2 x y)) @ (b2 (cancel2 x y)))" using assms(1,2) by (simp add: cancel2_the) define w2 where 3:"w2 = (a3 (cancel3 x y z), (p3 (cancel3 x y z)), b3 (cancel3 x y z) @ (q3 (cancel3 x y z)))" then have "x = (a2 w2) @ (p2 w2) \<and> y = (wordinverse (p2 w2)) @ (b2 w2) \<and> reduced ((a2 w2) @ (b2 w2))" using 1 by auto then have "w2 = (cancel2 x y)" using 2 assms(1,2) cancel2E' by blast then have "a2 w2 = a2 (cancel2 x y)" by simp then show ?thesis using 3 by simp qed definition G where "G H A g = \<langle>{h \<in> carrier H. (h,g) \<in> (lex_L2_word A)}\<rangle>\<^bsub>H\<^esub>" (* G g := {<g'>. g' < g} *) definition X where "X H A = {g \<in> carrier H. g \<notin> (G H A g)}" (*y <lex x and xy <lex x = = > x not in X and x-1 not in X = = > x not in X U X-1*) lemma subset_span: assumes "A \<subseteq> \<langle>S\<rangle>\<^bsub>H\<^esub>" shows "\<langle>A\<rangle>\<^bsub>H\<^esub> \<subseteq> \<langle>S\<rangle>\<^bsub>H\<^esub>" proof fix x assume "x \<in> \<langle>A\<rangle>\<^bsub>H\<^esub>" then show "x \<in> \<langle>S\<rangle>\<^bsub>H\<^esub>" proof(induction rule: gen_span.induct) case gen_one then show ?case by simp next case (gen_gens x) then show ?case using assms by blast next case (gen_inv x) then show ?case by (simp add: gen_span.gen_inv) next case (gen_mult x y) then show ?case by (simp add: gen_span.gen_mult) qed qed lemma subgroup_is_group: assumes "group A" and "subgroup H A" shows "group (A\<lparr>carrier := H\<rparr>)" by (simp add: assms(1) assms(2) subgroup.subgroup_is_group) definition SG where "SG A H = (A\<lparr>carrier := H\<rparr>)" lemma assumes "H \<le> freegroup A" shows "\<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub> = carrier (SG (freegroup A) H)" proof(rule ccontr) assume a:"\<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub> \<noteq> carrier (SG (freegroup A) H)" have "X (SG (freegroup A) H) A \<subseteq> carrier (SG (freegroup A) H)" unfolding X_def SG_def by fastforce moreover have "group (SG (freegroup A) H)" using assms freegroup_is_group subgroup_is_group unfolding SG_def by blast ultimately have "\<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub> \<subseteq> carrier (SG (freegroup A) H)" using group.gen_span_closed by blast then have "carrier (SG (freegroup A) H) - \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub> \<noteq> {}" using a by blast then obtain x where "x \<in> (carrier (SG (freegroup A) H) - \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>)" by blast then obtain x' where 1:"x'\<in> (carrier (SG (freegroup A) H) - \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>) \<and> (\<forall>y. (y, x') \<in> lex_L2_word A \<longrightarrow> y \<notin> (carrier (SG (freegroup A) H) - \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>))" using wfE_min[of "(lex_L2_word A)" "x" "(carrier (SG (freegroup A) H) - \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>)"] wf_lex_L2_word by metis then have "\<forall>y \<in> (carrier (SG (freegroup A) H)). (y,x') \<in> (lex_L2_word A) \<longrightarrow> y \<in> \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>" by blast then have "{h \<in> (carrier (SG (freegroup A) H)). (h,x') \<in> (lex_L2_word A)} \<subseteq> \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>" by blast then have "\<langle>{h \<in> (carrier (SG (freegroup A) H)). (h,x') \<in> (lex_L2_word A)}\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub> \<subseteq> \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>" using subset_span by blast moreover have 2: "x' \<notin> \<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>" using 1 by blast ultimately have "x' \<notin> G (SG (freegroup A) H) A x'" unfolding G_def X_def by blast moreover have "x' \<in> (carrier (SG (freegroup A) H))" using 1 by blast ultimately have "x' \<in> X (SG (freegroup A) H) A" unfolding X_def by blast then have "x' \<in> (\<langle>X (SG (freegroup A) H) A\<rangle>\<^bsub>(SG (freegroup A) H)\<^esub>)" by (simp add: gen_span.gen_gens) then show False using 2 by blast qed definition N0 where "N0 x = (x \<noteq> [])" lemma sublist_inverse: "\<forall>n < (length (x#xs) - 1). ((x#xs)!n) \<noteq> (wordinverse ((x#xs)!(n+1))) \<Longrightarrow> \<forall>n < (length (xs) - 1). ((xs)!n) \<noteq> (wordinverse ((xs)!(n+1)))" proof- assume assm:"\<forall>n < (length (x#xs) - 1). ((x#xs)!n) \<noteq> (wordinverse ((x#xs)!(n+1)))" show "\<forall>n < (length (xs) - 1). ((xs)!n) \<noteq> (wordinverse ((xs)!(n+1)))" apply(rule allI) apply(rule impI) proof- fix n assume n:"n < length xs - 1" have 1:"((x#xs)!(n+1)) = (xs!n)" by auto have 2: "((x#xs)!(n+2)) = (xs!(n+1))" by simp have 3:"(n+1) < length (x#xs) - 1" using n by simp show "((xs)!n) \<noteq> (wordinverse ((xs)!(n+1)))" proof(rule ccontr) assume " \<not> xs ! n \<noteq> wordinverse (xs ! (n + 1))" then have "xs ! n = wordinverse (xs ! (n + 1))" by blast then have "((x#xs)!(n+1)) = wordinverse ((x#xs)!(n+2))" using 1 2 by argo then show False using 3 assm by fastforce qed qed qed lemma hd_notempty: assumes "B \<subseteq> (red_rep A ` carrier (freegroup A))" and "\<forall>x \<in> B. N0 x" and "\<forall>x \<in> B. \<forall>y \<in> B. N1 x y" and "\<forall>x \<in> B. \<forall>y \<in> B. \<forall>z \<in> B. N2 x y z" and "set (x#xs) \<subseteq> B" and "\<forall>n < (length (x#xs) - 1). ((x#xs)!n) \<noteq> (wordinverse ((x#xs)!(n+1)))" shows "\<exists>a b c. x = a@b \<and> l_concat (x#xs) ~ a@c \<and> reduced (a@c) \<and> a \<noteq> [] \<and> ((xs \<noteq> []) \<longrightarrow> a = a2 (cancel2 x (hd xs)))" using assms proof(induction "(x#xs)" arbitrary: x xs) case (Cons y z) have y: "y \<in> B" using Cons.prems(5) by auto moreover then obtain Y where "Y \<in> carrier (freegroup A) \<and> y = red_rep A Y" using Cons.prems(1) by blast ultimately have ry:"reduced y" using Cons.prems(1) unfolding freegroup_def by (simp add: red_rep_the) have y0:"y \<noteq> []" using N0_def y assms(2) by auto then show ?case proof(cases "z = []") case True have "l_concat (y # z) = y" using True unfolding l_concat_def by simp moreover have "y = y@[]" by simp moreover then have "y ~ y" using refl by fast ultimately show ?thesis using ry y0 True by metis next case False then obtain z1 z2 where z:"z = (z1#z2)" using list.exhaust by blast have z1:"z1 \<in> B" using Cons.prems(5) z by auto then have z10:"z1 \<noteq> []" using N0_def assms(2) by auto obtain Z1 where "Z1 \<in> carrier (freegroup A) \<and> z1 = red_rep A Z1" using Cons.prems(1) z1 by blast then have rz1: "reduced z1" using z1 using Cons.prems(1) unfolding freegroup_def by (simp add: red_rep_the) then show ?thesis proof(cases "z2 = []") case True then have 1:"l_concat (y#z) = (y@z1)" using z unfolding l_concat_def by simp have N1:"N1 y z1" using Cons.prems(3) y z1 by simp have yz1:"y \<noteq> wordinverse z1" using z True Cons.prems(6) by force define w where w:"w = cancel2 y z1" then have w':"y = a2 w @ p2 w \<and> z1 = (wordinverse (p2 w)) @ b2 w \<and> reduced (a2 w@b2 w)" unfolding cancel2_def using cancel2_the ry rz1 w by fastforce moreover then have "(y@z1) ~ (a2 w@b2 w)" using cancel2_reln by blast moreover have "a2 w \<noteq> []" proof(rule ccontr) assume "\<not> a2 w \<noteq> []" then have a2w:"a2 w = []" by blast have "p2 w = []" using w a2w N1 yz1 unfolding N1_def by simp then have "y = []" using w' a2w by simp then show False using y0 by blast qed moreover have "hd z = z1" using z by simp ultimately show ?thesis using 1 w by force next case False then obtain z3 z4 where z2:"z2 = (z3#z4)" using list.exhaust by auto then have "set (z1#z3#z4) \<subseteq> B" using z using Cons.prems(5) by auto moreover have "\<forall>n < (length (z1#z3#z4) - 1). ((z1#z3#z4)!n) \<noteq> (wordinverse ((z1#z3#z4)!(n+1)))" using z2 z Cons.prems(6) sublist_inverse by blast ultimately obtain a b c where 1:"z1 = a @ b \<and> l_concat (z1 # z3 # z4) ~ a @ c \<and> reduced (a @ c) \<and> a \<noteq> [] \<and> ((z3#z4 \<noteq> []) \<longrightarrow> (a = a2 (z1 \<oslash>\<^bsub>2\<^esub> hd (z3#z4))))" using Cons z2 z by blast then have a:"a = a2 (z1 \<oslash>\<^bsub>2\<^esub> z3)" using False z2 by fastforce have N2:"N2 y z1 z3" using Cons.prems(1,4,5) z z2 by auto have 11:"N1 y z1" using Cons.prems(1,3,5) z z2 by fastforce have 12:"N1 z1 z3" using Cons.prems(1,3,5) z z2 by fastforce obtain Z3 where "Z3 \<in> carrier (freegroup A) \<and> z3 = red_rep A Z3" using Cons.prems(1,5) z z2 by auto then have rz3: "reduced z3" using z1 using Cons.prems(1) unfolding freegroup_def by (simp add: red_rep_the) define w where w:"w = cancel3 y z1 z3" have "(y#z) = (y#z1#z3#z4)"using z z2 by auto then have inv:"y \<noteq> wordinverse z1 \<and> z1 \<noteq> wordinverse z3" using Cons.prems(6) Ex_list_of_length by auto then have 2:"y = a3 w @ (p3 w) \<and> z1 = wordinverse (p3 w) @ b3 w @ (q3 w) \<and> z3 = (wordinverse (q3 w)) @ (c3 w) \<and> reduced (a3 w @ b3 w @ q3 w) \<and> reduced (wordinverse (p3 w) @ b3 w @ c3 w)" using N2 11 12 ry rz1 rz3 w by (simp add: cancel3_the) have apb:"a = wordinverse (p3 w) @ b3 w" using N2 11 12 ry rz1 rz3 w a cancel_a2_pb3 inv by blast have "l_concat (y # z) ~ a3 w @ (b3 w @ c)" proof- have "l_concat (y # z) = y@ l_concat (z1 # z3 # z4)" unfolding l_concat_def using z z2 by auto then have "l_concat (y # z) ~ y@a@c" using 1 mult reln.refl by metis moreover have "y@a@c = a3 w @ (p3 w) @ wordinverse (p3 w) @ b3 (w)@c" using 2 apb by simp moreover have "(a3 w @ (p3 w) @ wordinverse (p3 w) @ b3 w @ c) ~ (a3 w @ (b3 w @ c))" using cancel2_reln by auto ultimately show ?thesis using reln.trans by auto qed moreover have "reduced (a3 w @ (b3 w @ c))" proof- have A:"reduced (wordinverse (p3 w) @ b3 w @ c)" using 1 apb by force then have "reduced (b3 w @ c)" using reduced_leftappend by blast moreover have "reduced (a3 w @ b3 w)" using 2 reduced_rightappend by (metis append.assoc) ultimately show ?thesis using N2 N2_def inv reduced_overlap w by blast qed moreover have "a3 w \<noteq> [] \<and> a3 w = a2 (cancel2 y (hd z))" proof- have "hd z = z1" using z by force then have A:"a3 w = a2 (cancel2 y (hd z))" using w N2 11 12 ry rz1 rz3 inv cancel_a2_a3 by metis define v where v:"v = cancel2 y z1" then have vv:"y = a2 v @ p2 v \<and> z1 = (wordinverse (p2 v)) @ b2 v \<and> reduced (a2 v@b2 v)" using cancel2_the ry rz1 w by fastforce have B: "a3 w \<noteq> []" proof(rule ccontr) assume "\<not> a3 w \<noteq> []" then have "a3 w = []" by simp then have "a2 v = []" using v w N2 11 12 ry rz1 rz3 inv cancel_a2_a3 by metis moreover then have "p2 v = []" using v 11 inv unfolding N1_def by simp ultimately have "y = []" using vv by simp then show "False" using y0 by blast qed then show ?thesis using A B by blast qed ultimately show ?thesis using 2 by blast qed qed qed lemma n_reduced_cancel: assumes "B \<subseteq> (red_rep A ` carrier (freegroup A))" and "\<forall>x \<in> B. N0 x" and "\<forall>x \<in> B. \<forall>y \<in> B. N1 x y" and "\<forall>x \<in> B. \<forall>y \<in> B. \<forall>z \<in> B. N2 x y z" and "set l \<subseteq> B" and "\<forall>n < (length l - 1). (l!n) \<noteq> (wordinverse (l!(n+1)))" and "l \<noteq> []" shows "\<not> (l_concat l ~ [])" proof- obtain x xs where l:"l = (x#xs)" using assms(7) list.exhaust by blast then obtain a b c where A:"x = a@b \<and> l_concat (x#xs) ~ a@c \<and> reduced (a@c) \<and> a \<noteq> [] \<and> ((xs \<noteq> []) \<longrightarrow> a = a2 (cancel2 x (hd xs)))" using assms hd_notempty[of "B" "A"] by presburger show ?thesis proof(rule ccontr) assume "\<not> \<not> l_concat l ~ []" then have "l_concat l ~ []" by blast moreover have "l_concat l ~ (a@c)" using l A by blast ultimately have "(a@c) ~ []" using reln.sym reln.trans by blast moreover have "reduced (a@c)" using A by blast moreover have "reduced []" by simp ultimately have "(a@c) = []" using reduced_reln_eq by blast moreover have "(a@c) \<noteq> []" using A by blast ultimately show False by blast qed qed definition union_inv where "union_inv S A \<equiv> S \<union> (m_inv (freegroup A) ` S)" lemma span_subset: assumes "A ⊆ B" shows "⟨A⟩⇘H⇙ ⊆ ⟨B⟩⇘H⇙" using assms gen_span.gen_gens subset_iff subset_span by metis lemma one_SG: "𝟭⇘H⇙ = 𝟭⇘SG H K⇙" unfolding SG_def by simp lemma mult_SG: "x ⊗⇘H⇙ y = x ⊗⇘SG H K⇙ y" by (simp add: SG_def) lemma inv_SG: "group H ⟹ y ∈ K ⟹ subgroup K H ⟹ inv⇘H⇙ y = inv⇘SG H K⇙ y" unfolding SG_def by (simp add: group.m_inv_consistent) lemma lex_cont1: assumes "(y,x) ∈ lex_L2_word A" and "(x ⊗⇘SG F⇘A⇙ H⇙ y, x) ∈ lex_L2_word A" and "x ∈ H" and "y ∈ H" and "H ≤ F⇘A⇙" shows "x ∉ X (SG (F⇘A⇙) H) A" proof- have "group F⇘A⇙" by (simp add: freegroup_is_group) then have 1: "group (SG (F⇘A⇙) H)" unfolding SG_def by (simp add: subgroup_is_group assms(5)) have xH:"x ⊗⇘SG F⇘A⇙ H⇙ y ∈ H" by (metis assms(3) assms(4) assms(5) mult_SG subgroup_def) then have "{y, x ⊗⇘SG F⇘A⇙ H⇙ y} ⊆ {h ∈ H. (h,x) ∈ (lex_L2_word A)}" using assms(1) assms(2) assms(4) by auto moreover have H:"H = carrier (SG F⇘A⇙ H)" unfolding SG_def by simp ultimately have 2:"⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙ ⊆ G (SG (F⇘A⇙) H) A x" unfolding G_def using span_subset by (metis (no_types, lifting) Collect_cong) have "inv ⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens gen_span.gen_inv) moreover have 3: "x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens) ultimately have "x ⊗⇘SG F⇘A⇙ H⇙ y ⊗⇘SG F⇘A⇙ H⇙ inv ⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_mult) then have "x ⊗⇘SG F⇘A⇙ H⇙ 𝟭⇘SG F⇘A⇙ H⇙ ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 3 xH H assms(3) assms(4) gen_span.gen_mult gen_span.gen_one by (metis group.inv_solve_right') then have "x ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(3) group.is_monoid by force then have "x ∈ G (SG (F⇘A⇙) H) A x" using 2 by auto then show ?thesis by (simp add: X_def) qed lemma lex_cont1_inv: assumes "(y,x) ∈ lex_L2_word A" and "(x ⊗⇘SG F⇘A⇙ H⇙ y, x) ∈ lex_L2_word A" and "x ∈ H" and "y ∈ H" and "H ≤ F⇘A⇙" shows "inv⇘SG F⇘A⇙ H⇙ x ∉ X (SG (F⇘A⇙) H) A" proof- have "group F⇘A⇙" by (simp add: freegroup_is_group) then have 1: "group (SG (F⇘A⇙) H)" unfolding SG_def by (simp add: subgroup_is_group assms(5)) have y:"(y,inv⇘SG F⇘A⇙ H⇙ x) ∈ lex_L2_word A" using freegroup_is_group assms(1) assms(3) assms(5) inv_SG lex_L2_inv by metis have xy: "(x ⊗⇘SG F⇘A⇙ H⇙ y, inv⇘SG F⇘A⇙ H⇙ x) ∈ lex_L2_word A" using freegroup_is_group assms(2) assms(3) assms(5) inv_SG lex_L2_inv by metis have xH:"x ⊗⇘SG F⇘A⇙ H⇙ y ∈ H" by (metis assms(3) assms(4) assms(5) mult_SG subgroup_def) then have "{y, x ⊗⇘SG F⇘A⇙ H⇙ y} ⊆ {h ∈ H. (h,inv⇘SG F⇘A⇙ H⇙ x) ∈ (lex_L2_word A)}" using y xy assms(4) by auto moreover have H:"H = carrier (SG F⇘A⇙ H)" unfolding SG_def by simp ultimately have 2:"⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙ ⊆ G (SG (F⇘A⇙) H) A (inv⇘SG F⇘A⇙ H⇙ x)" unfolding G_def using span_subset by (metis (no_types, lifting) Collect_cong) have "inv ⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens gen_span.gen_inv) moreover have 3: "x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens) ultimately have "x ⊗⇘SG F⇘A⇙ H⇙ y ⊗⇘SG F⇘A⇙ H⇙ inv ⇘SG F⇘A⇙ H⇙ y ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_mult) then have "x ⊗⇘SG F⇘A⇙ H⇙ 𝟭⇘SG F⇘A⇙ H⇙ ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 3 xH H assms(3) assms(4) gen_span.gen_mult gen_span.gen_one by (metis group.inv_solve_right') then have "x ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(3) group.is_monoid by force then have "(inv⇘SG F⇘A⇙ H⇙ x) ∈ ⟨{y, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_inv) then have "(inv⇘SG F⇘A⇙ H⇙ x) ∈ G (SG (F⇘A⇙) H) A (inv⇘SG F⇘A⇙ H⇙ x)" using 2 by blast then show ?thesis by (simp add: X_def) qed lemma lex_cont2_inv: assumes "(x,y) ∈ lex_L2_word A" and "(x ⊗⇘SG F⇘A⇙ H⇙ y, y) ∈ lex_L2_word A" and "x ∈ H" and "y ∈ H" and "H ≤ F⇘A⇙" shows "inv⇘SG F⇘A⇙ H⇙ y ∉ X (SG (F⇘A⇙) H) A" proof- have "group F⇘A⇙" by (simp add: freegroup_is_group) then have 1: "group (SG (F⇘A⇙) H)" unfolding SG_def by (simp add: subgroup_is_group assms(5)) have x:"(x,inv⇘SG F⇘A⇙ H⇙ y) ∈ lex_L2_word A" using freegroup_is_group assms(1) assms(4) assms(5) inv_SG lex_L2_inv by metis have xy: "(x ⊗⇘SG F⇘A⇙ H⇙ y, inv⇘SG F⇘A⇙ H⇙ y) ∈ lex_L2_word A" using freegroup_is_group assms(2) assms(4) assms(5) inv_SG lex_L2_inv by metis have xH:"x ⊗⇘SG F⇘A⇙ H⇙ y ∈ H" by (metis assms(3) assms(4) assms(5) mult_SG subgroup_def) then have "{x, x ⊗⇘SG F⇘A⇙ H⇙ y} ⊆ {h ∈ H. (h,inv⇘SG F⇘A⇙ H⇙ y) ∈ (lex_L2_word A)}" using x xy assms(3) by auto moreover have H:"H = carrier (SG F⇘A⇙ H)" unfolding SG_def by simp ultimately have 2:"⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙ ⊆ G (SG (F⇘A⇙) H) A (inv⇘SG F⇘A⇙ H⇙ y)" unfolding G_def using span_subset by (metis (no_types, lifting) Collect_cong) have "inv ⇘SG F⇘A⇙ H⇙ x ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens gen_span.gen_inv) moreover have 3: "x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens) ultimately have "inv ⇘SG F⇘A⇙ H⇙ x ⊗⇘SG F⇘A⇙ H⇙ x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(3) assms(4) gen_span.gen_mult group.inv_closed group.is_monoid monoid.m_assoc by fastforce then have "𝟭⇘SG F⇘A⇙ H⇙ ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 3 xH H assms(3) assms(4) group.l_inv by fastforce then have "y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(4) group.is_monoid by force then have "inv⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_inv) then have "inv⇘SG F⇘A⇙ H⇙ y ∈ G (SG (F⇘A⇙) H) A (inv⇘SG F⇘A⇙ H⇙ y)" using 2 by auto then show ?thesis by (simp add: X_def) qed lemma lex_cont2: assumes "(x,y) ∈ lex_L2_word A" and "(x ⊗⇘SG F⇘A⇙ H⇙ y, y) ∈ lex_L2_word A" and "x ∈ H" and "y ∈ H" and "H ≤ F⇘A⇙" shows "y ∉ X (SG (F⇘A⇙) H) A" proof- have "group F⇘A⇙" by (simp add: freegroup_is_group) then have 1: "group (SG (F⇘A⇙) H)" unfolding SG_def by (simp add: subgroup_is_group assms(5)) have xH:"x ⊗⇘SG F⇘A⇙ H⇙ y ∈ H" by (metis assms(3) assms(4) assms(5) mult_SG subgroup_def) then have "{x, x ⊗⇘SG F⇘A⇙ H⇙ y} ⊆ {h ∈ H. (h,y) ∈ (lex_L2_word A)}" using assms(1) assms(2) assms(3) by auto moreover have H:"H = carrier (SG F⇘A⇙ H)" unfolding SG_def by simp ultimately have 2:"⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙ ⊆ G (SG (F⇘A⇙) H) A y" unfolding G_def using span_subset by (metis (no_types, lifting) Collect_cong) have "inv ⇘SG F⇘A⇙ H⇙ x ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens gen_span.gen_inv) moreover have 3: "x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" by (simp add: gen_span.gen_gens) ultimately have "inv ⇘SG F⇘A⇙ H⇙ x ⊗⇘SG F⇘A⇙ H⇙ x ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(3) assms(4) gen_span.gen_mult group.inv_closed group.is_monoid monoid.m_assoc by fastforce then have "𝟭⇘SG F⇘A⇙ H⇙ ⊗⇘SG F⇘A⇙ H⇙ y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 3 xH H assms(3) assms(4) group.l_inv by fastforce then have "y ∈ ⟨{x, x ⊗⇘SG F⇘A⇙ H⇙ y}⟩⇘SG F⇘A⇙ H⇙" using 1 H assms(4) group.is_monoid by force then have "y ∈ G (SG (F⇘A⇙) H) A y" using 2 by auto then show ?thesis by (simp add: X_def) qed lemma length_lex: assumes "length (red_rep A a) < length (red_rep A b)" "a \<in> carrier (freegroup A) \<and> b \<in> carrier (freegroup A)" shows "(a,b) \<in> lex_L2_word A" proof- have "(length (red_rep A a), length (red_rep A b)) \<in> nat_less" unfolding nat_less_def using assms by blast then show ?thesis unfolding lex_L2_word_def lex_prod_def using assms(2) unfolding freegroup_def by simp qed lemma inv_X_clos: assumes "H \<le> freegroup A" shows "m_inv F\<^bsub>A\<^esub> ` {g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g} \<subseteq> carrier F\<^bsub>A\<^esub>" proof fix x assume "x \<in> m_inv F\<^bsub>A\<^esub> ` {g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g}" then obtain y where y: "m_inv F\<^bsub>A\<^esub> y = x \<and> y \<in> {g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g}" by blast then have "y \<in> carrier F\<^bsub>A\<^esub>" using assms freegroup_is_group group.subgroupE(1) by auto then have "m_inv F\<^bsub>A\<^esub> y \<in> carrier F\<^bsub>A\<^esub>" using y assms subgroup.m_inv_closed subgroup.mem_carrier by fastforce then show "x \<in> carrier F\<^bsub>A\<^esub>" using y by blast qed lemma union_inv_clos: assumes "H \<le> freegroup A" shows "(union_inv (X (SG (freegroup A) H) A) A) \<subseteq> carrier (freegroup A)" unfolding X_def union_inv_def SG_def proof- have "{g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g} \<subseteq> carrier (freegroup A)" using assms subgroup.subset by auto moreover have "m_inv F\<^bsub>A\<^esub> ` {g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g} \<subseteq> carrier F\<^bsub>A\<^esub>" using assms inv_X_clos by blast ultimately show "{g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g} \<union> m_inv F\<^bsub>A\<^esub> ` {g \<in> carrier (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>). g \<notin> G (F\<^bsub>A\<^esub>\<lparr>carrier := H\<rparr>) A g} \<subseteq> carrier F\<^bsub>A\<^esub>" by blast qed lemma union_inv_sub_H: assumes "H ≤ freegroup A" "x1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" shows "x1 ∈ H" proof- have 1:"x1 ∈ (X (SG (freegroup A) H) A) ∪ (m_inv (freegroup A) ` (X (SG (freegroup A) H) A))" using union_inv_def using assms(2) by auto then show ?thesis proof(cases "x1 ∈ (X (SG (freegroup A) H) A)") case True then have "x1 ∈ {g ∈ carrier (SG (freegroup A) H). g ∉ (G (SG (freegroup A) H) A g)}" using X_def by auto then have "x1 ∈ carrier (SG (freegroup A) H)" by simp then have "x1 ∈ carrier ((freegroup A)⦇carrier := H⦈)" using SG_def by metis then show ?thesis using assms(1) by auto next case False then have "x1 ∈ (m_inv (freegroup A) ` (X (SG (freegroup A) H) A))" using 1 by auto moreover then have "x1 ∈ carrier ((freegroup A)⦇carrier := H⦈)" using m_inv_def assms(1) SG_def X_def union_inv_clos by (smt (verit) image_iff mem_Collect_eq partial_object.select_convs(1) partial_object.surjective partial_object.update_convs(1) subgroup.m_inv_closed) ultimately show ?thesis using assms(1) by auto qed qed lemma min_L2_inv: assumes "x ∈ carrier (freegroup A) ∧ xy ∈ carrier (freegroup A)" shows "min lex_word (L2(red_rep A x)) = min lex_word( L2(wordinverse (red_rep A x)))" unfolding left_tuple_def min.simps by (metis FreeGroupMain.wordinverse_of_wordinverse lex_word_total wf_lex_word wf_not_sym) lemma length_eq: assumes "x = a@c" "y = b@c" "length a = length b" shows "length x = length y" using assms by simp lemma lex_word_one: "(x,y) ∈ lex_word ⟹ x ≠ y ⟹ ¬ (y,x) ∈ lex_word" by (metis wf_lex_word wf_not_sym) lemma trans_lex_word:"trans lex_word" proof- have 1: "trans (r_gen - Id)" using r_gen strict_linear_order_on_def strict_linear_order_on_diff_Id well_order_on_def by blast show ?thesis by (simp add: 1 lenlex_transI lex_word_def) qed lemma trans_lex_L2_word': "trans (lex_L2_word' A)" unfolding lex_L2_word'_def using trans_lex_word by (smt (z3) case_prodD case_prodI mem_Collect_eq trans_def trans_lex_prod) lemma trans_nat_less: "trans nat_less" unfolding nat_less_def by (metis (no_types, lifting) less_than_iff mem_Collect_eq old.prod.case transD transI trans_less_than) lemma trans_lex_L2_word: "trans (lex_L2_word A)" unfolding lex_L2_word_def using trans_lex_L2_word' trans_nat_less by (smt (z3) case_prodD case_prodI mem_Collect_eq trans_def trans_lex_prod) lemma lex_L2_word_total_1: assumes "x ∈ carrier (freegroup A)" and "y ∈ carrier (freegroup A)" and "length (red_rep A x) = length (red_rep A y)" shows "¬ (x,y) ∈ lex_L2_word A ∧ ¬ (y, x) ∈ lex_L2_word A ⟹ red_rep A x = red_rep A y ∨ red_rep A x = wordinverse (red_rep A y)" using assms unfolding freegroup_def using lex_L2_word_total1 lex_L2_word_total2 eq_L2_eq rev_L2_inv by (metis partial_object.select_convs(1)) lemma lex_L2_word_total_2: assumes "x ∈ carrier (freegroup A)" and "y ∈ carrier (freegroup A)" and "length (red_rep A x) = length (red_rep A y)" shows "red_rep A x ≠ red_rep A y ∧ red_rep A x ≠ wordinverse (red_rep A y) ⟹ (x,y) ∈ lex_L2_word A ∨ (y, x) ∈ lex_L2_word A" using assms lex_L2_word_total_1 by blast lemma lex_total: assumes "x ∈ carrier (freegroup A)" and "y ∈ carrier (freegroup A)" and "red_rep A x ≠ wordinverse (red_rep A y)" and "red_rep A x ≠ (red_rep A y)" shows "(x,y) ∈ lex_L2_word A ∨ (y, x) ∈ lex_L2_word A" proof(cases "length (red_rep A x) > length (red_rep A y)") case True then have "(y,x) ∈ lex_L2_word A" using assms(1) assms(2) length_lex by blast then show ?thesis by blast next case False note F = this then show ?thesis proof(cases "length (red_rep A x) < length (red_rep A y)") case True then have "(x,y) ∈ lex_L2_word A" using assms(1) assms(2) length_lex by blast then show ?thesis by blast next case False then have "length (red_rep A x) = length (red_rep A y)" using F by simp then show ?thesis using assms(1,2,3,4) lex_L2_word_total_2 by blast qed qed lemma reduced_inv_eq_imp_nil: "xs = wordinverse xs ⟹ reduced xs ⟹ xs = []" proof- assume xs:"xs = wordinverse xs " and rxs:"reduced xs" then show "xs = []" proof(cases "odd (length xs)") case True then have 1:"length xs > 0" using True by fastforce then have 2:"length xs > (length xs div 2)" by simp have "length (drop (length xs div 2) xs) = length xs - (length xs div 2) " by simp then have "length (drop (length xs div 2) xs) > 0" using 2 by simp then have "(drop (length xs div 2) xs) ≠ []" by fast moreover have "drop ((length xs div 2)+1) xs = tl (drop ((length xs div 2)) xs)" using drop_Suc tl_drop by (simp add: drop_Suc tl_drop) ultimately have "[hd (drop (length xs div 2) xs)] @ drop ((length xs div 2)+1) xs = (drop (length xs div 2) xs)" by simp moreover have "xs = take (length xs div 2) xs @ drop (length xs div 2) xs" by simp ultimately have 3:"xs = take (length xs div 2) xs @ [hd (drop (length xs div 2) xs)] @ drop ((length xs div 2)+1) xs" by presburger then have "wordinverse xs = (map inverse) (rev (take (length xs div 2) xs @ [hd (drop (length xs div 2) xs)] @ drop ((length xs div 2)+1) xs))" using wordinverse_redef2 by auto then have "wordinverse xs = (map inverse) (rev (drop ((length xs div 2)+1) xs) @ rev [hd (drop (length xs div 2) xs)] @ rev (take (length xs div 2) xs))" by simp then have "wordinverse xs = ((map inverse) (rev (drop ((length xs div 2)+1) xs)) @ [inverse (hd (drop (length xs div 2) xs))] @ (map inverse) (rev (take (length xs div 2) xs)))" by simp moreover have "length (take (length xs div 2) xs) = length ((map inverse)(rev (drop ((length xs div 2)+1) xs)))" using True drop_odd_length by fastforce ultimately have "[inverse (hd (drop (length xs div 2) xs))] = [hd (drop (length xs div 2) xs)]" using 3 xs by (metis (no_types, lifting) append_eq_append_conv hd_append2 list.sel(1) not_Cons_self2) then show ?thesis by (metis inverse_neq list.sel(1)) next case False then have "even (length xs)" by blast then have x:"xs = L xs @ R xs" unfolding left_subword_def right_subword_def by simp moreover then have "wordinverse xs = wordinverse (R xs) @ wordinverse (L xs)" using wordinverse_append by metis moreover have "length (L xs) = length (wordinverse (R xs))" using False even_R xs by force ultimately have "(L xs) = wordinverse (R xs)" by (metis append_eq_append_conv xs) then have "xs = wordinverse (R xs) @ (R xs)" using x by auto then have "¬ reduced xs ∨ xs = []" by (metis inverse_wordinverse reduced.simps(1) reduced_reln_eq) then show ?thesis using rxs by blast qed qed lemma square_length: assumes "x ∈ carrier (freegroup A)" shows "length (red_rep A (x ⊗⇘ F⇘A⇙⇙ x)) ≥ length (red_rep A x)" proof- let ?x = "(red_rep A x)" let ?xx = "(cancel2 ?x ?x)" have xx: "(x ⊗⇘F⇘A⇙⇙ x) ∈ carrier (freegroup A)" by (simp add: assms(1) freegroup_is_group group.subgroupE(4) group.subgroup_self) have 1:"reduced ?x" using assms(1) red_rep_def red_rep_the unfolding freegroup_def by fastforce then have "((red_rep A x) @ (red_rep A x)) ~ ((a2 ?xx) @ (b2 ?xx))" by (metis cancel2_reln cancel2_the) then have "(red_rep A (x ⊗⇘F⇘A⇙⇙ x)) ~ ((a2 ?xx) @ (b2 ?xx))" using assms mult_reln using reln.trans by blast moreover have "reduced ((a2 ?xx) @ (b2 ?xx))" by (simp add: "1" cancel2_the) moreover have "reduced (red_rep A (x ⊗⇘F⇘A⇙⇙ x))" using xx red_rep_def red_rep_the unfolding freegroup_def by fastforce ultimately have 3: "(red_rep A (x ⊗⇘F⇘A⇙⇙ x)) = ((a2 ?xx) @ (b2 ?xx))" by (simp add: reduced_reln_eq) have A:"?x = (a2 ?xx) @ (p2 ?xx)" using 1 by (simp add: cancel2_the) then have rp:"reduced (p2 ?xx)" using "1" reduced_leftappend by metis have B:"?x = wordinverse (p2 ?xx) @ (b2 ?xx)" using 1 by (simp add: cancel2_the) have C:"length (p2 ?xx) = length (wordinverse (p2 ?xx))" using length_wordinverse by blast then have D:"length (a2 ?xx) = length (b2 ?xx)" using A B by (metis add_diff_cancel_left' add_diff_cancel_right' length_append) show ?thesis proof(cases "length (b2 ?xx) > length (p2 ?xx)") case True then have "length ((a2 ?xx) @ (p2 ?xx)) ≤ length ((a2 ?xx) @ (b2 ?xx))" by simp then show ?thesis using 3 A by auto next case False then have F:"length (b2 ?xx) ≤ length (p2 ?xx)" by auto then show ?thesis proof(cases "length (b2 ?xx) = length (p2 ?xx)") case True then have "?x = wordinverse (p2 ?xx) @ (p2 ?xx)" by (metis A B D append_eq_append_conv) then have "¬ reduced ?x ∨ ?x = []" by (metis inverse_wordinverse reduced.simps(1) reduced_reln_eq) then show ?thesis by (simp add: 1) next case False then have cont:"length (b2 ?xx) < length (p2 ?xx)" using F by auto then obtain c where c:"?x = (a2 ?xx) @ c @ (b2 ?xx)" using A B by (metis D overlaprightexist) then have pc:"p2 ?xx = (c @ b2 ?xx)" using A by (metis same_append_eq) moreover have "wordinverse (p2 ?xx) = (a2 ?xx) @ c" using c B by (metis append.assoc append_same_eq) ultimately have "(c @ b2 ?xx) = (wordinverse c) @ (wordinverse (a2 ?xx))" by (simp add: wordinverse_append wordinverse_symm) then have "c = wordinverse c" using append_eq_append_conv length_wordinverse by fast moreover have "reduced c" using rp pc using reduced_rightappend by auto ultimately have "c = []" using reduced_inv_eq_imp_nil by blast then have "length (b2 ?xx) = length (p2 ?xx)" using pc by auto then show ?thesis using cont by auto qed qed qed lemma neq_N1: assumes "x ∈ carrier (freegroup A)" and " y ∈ carrier (freegroup A)" and "length (red_rep A (x ⊗⇘ F⇘A⇙⇙ y)) < length (red_rep A x) ∨ length (red_rep A (x ⊗⇘ F⇘A⇙⇙ y)) < length (red_rep A y)" shows "red_rep A x ≠ red_rep A y" proof(rule ccontr) assume "¬ red_rep A x ≠ red_rep A y" then have a: "red_rep A x = red_rep A y" by blast then have "x = y" using red_rep_the assms(1,2) unfolding freegroup_def by (metis partial_object.select_convs(1)) then have "length (red_rep A (x ⊗⇘ F⇘A⇙⇙ y)) ≥ length (red_rep A x) ∧ length (red_rep A (x ⊗⇘ F⇘A⇙⇙ y)) ≥ length (red_rep A y)" using assms(1) square_length by auto then show False using assms(3) by auto qed lemma SG_subgroup: assumes "H ≤ (freegroup A)" shows "group (SG (freegroup A) H)" unfolding SG_def using freegroup_is_group assms group.subgroup_imp_group by blast lemma notin_union_inv: assumes "H ≤ (freegroup A)" "x ∉ S" "m_inv (SG (freegroup A) H) x ∉ S" "S ⊆ H" shows "x ∉ union_inv S A" proof(rule ccontr) assume "¬ x ∉ union_inv S A" then have "x ∈ union_inv S A" by blast then have "x ∈ S ∨ x ∈ m_inv F⇘A⇙ ` S" unfolding union_inv_def by auto then have c:"x ∈ S ∨ x ∈ m_inv (SG (freegroup A) H) ` S" using inv_SG freegroup_is_group assms(1,4) by (metis (no_types, lifting) image_cong subset_eq) show False proof(cases "x ∈ S") case True then show ?thesis using assms(2) by blast next case False then have "x ∈ m_inv (SG (freegroup A) H) ` S" using c by blast then obtain y where y:"x = m_inv (SG (freegroup A) H) y ∧ y ∈ S" by blast moreover then have "y ∈ H" using assms(4) by auto moreover then have "y ∈ carrier (SG (freegroup A) H)" unfolding SG_def by simp ultimately have "y = m_inv (SG (freegroup A) H) x" using assms(1) by (simp add: SG_subgroup) then show ?thesis using y assms(3) by blast qed qed lemma N1: assumes "H ≤ freegroup A" shows "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀y ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N1 x y" apply(rule ballI)+ proof- fix x y assume x: "x ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" and y: "y ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" show "N1 x y" proof(rule ccontr) assume N1: "¬ N1 x y" then have nxiy:"x ≠ wordinverse y" using N1_def by auto obtain x1 where x1:"red_rep A x1 = x ∧ x1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using x by blast then have x1A: "x1 ∈ carrier (freegroup A)" using assms union_inv_clos by blast obtain y1 where y1:"red_rep A y1 = y ∧ y1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using y by blast then have y1A: "y1 ∈ carrier (freegroup A)" using assms union_inv_clos by blast have H:"x1 ∈ H ∧ y1 ∈ H" using assms x1 x1A y1 using union_inv_sub_H by blast have "¬ (length (red_rep A (x1 ⊗⇘ F⇘A⇙⇙ y1)) ≥ length (red_rep A x1) ∧ length (red_rep A (x1 ⊗⇘ F⇘A⇙⇙ y1)) ≥ length (red_rep A y1))" using N1 x1 y1 y1A x1A length_N1 by blast then have t:"length (red_rep A (x1 ⊗⇘ F⇘A⇙⇙ y1)) < length (red_rep A x1) ∨ length (red_rep A (x1 ⊗⇘ F⇘A⇙⇙ y1)) < length (red_rep A y1)" by auto moreover have "(x1 ⊗⇘ F⇘A⇙⇙ y1) ∈ carrier (freegroup A)" using x1A y1A by (simp add: freegroup_is_group group.subgroupE(4) group.subgroup_self) ultimately have cases:"((x1 ⊗⇘ F⇘A⇙⇙ y1), x1) ∈ lex_L2_word A ∨ ((x1 ⊗⇘ F⇘A⇙⇙ y1), y1) ∈ lex_L2_word A" using x1A y1A length_lex by blast have nxy:"x ≠ y" using neq_N1 t x1A y1A x1 y1 by auto have XH: "(X (SG F⇘A⇙ H) A) ⊆ H" unfolding X_def SG_def by simp have "x1 ∉ (union_inv (X (SG (freegroup A) H) A) A) ∨ y1 ∉ (union_inv (X (SG (freegroup A) H) A) A)" proof(cases "((x1 ⊗⇘F⇘A⇙⇙ y1), x1) ∈ lex_L2_word A") case True note xy_x = this then have subcases: "(x1,y1) ∈ lex_L2_word A ∨ (y1, x1) ∈ lex_L2_word A" using lex_total nxy nxiy x1 y1 x1A y1A by auto then show ?thesis proof (cases "(x1,y1) ∈ lex_L2_word A") case True then have xy_y:"((x1 ⊗⇘F⇘A⇙⇙ y1), y1) ∈ lex_L2_word A" using xy_x trans_lex_L2_word unfolding trans_def by blast then have "y1 ∉ X (SG (F⇘A⇙) H) A" using True assms H lex_cont2 by (metis mult_SG) moreover have "m_inv ((SG (F⇘A⇙) H)) y1 ∉ (X (SG (F⇘A⇙) H) A)" using True xy_y H assms lex_cont2_inv by (metis mult_SG) ultimately have "y1 ∉ (union_inv (X (SG (F⇘A⇙) H) A) A)" using notin_union_inv XH assms by blast then show ?thesis by meson next case False then have yx:"(y1, x1) ∈ lex_L2_word A" using subcases by auto then have "x1 ∉ X (SG (F⇘A⇙) H) A" using xy_x H assms lex_cont1 by (metis mult_SG) moreover have "m_inv ((SG (F⇘A⇙) H)) x1 ∉ (X (SG (F⇘A⇙) H) A)" using yx xy_x H assms lex_cont1_inv by (metis mult_SG) ultimately have "x1 ∉ (union_inv (X (SG (F⇘A⇙) H) A) A)" using notin_union_inv XH assms by blast then show ?thesis by blast qed next case False then have xyy:"((x1 ⊗⇘F⇘A⇙⇙ y1), y1) ∈ lex_L2_word A" using cases by auto then have subcases: "(x1,y1) ∈ lex_L2_word A ∨ (y1, x1) ∈ lex_L2_word A" using lex_total nxy nxiy x1 y1 x1A y1A by auto then show ?thesis proof (cases "(x1,y1) ∈ lex_L2_word A") case True have "y1 ∉ X (SG (F⇘A⇙) H) A" using True xyy H assms lex_cont2 by (metis mult_SG) moreover have "m_inv ((SG (F⇘A⇙) H)) y1 ∉ (X (SG (F⇘A⇙) H) A)" using True xyy H assms lex_cont2_inv by (metis mult_SG) ultimately have "y1 ∉ (union_inv (X (SG (F⇘A⇙) H) A) A)" using notin_union_inv XH assms by blast then show ?thesis by meson next case False then have yx:"(y1, x1) ∈ lex_L2_word A" using subcases by simp then have xy_x: "((x1 ⊗⇘F⇘A⇙⇙ y1), x1) ∈ lex_L2_word A" using xyy trans_lex_L2_word unfolding trans_def by blast then have "x1 ∉ X (SG (F⇘A⇙) H) A" using yx H assms lex_cont1 by (metis mult_SG) moreover have "m_inv ((SG (F⇘A⇙) H)) x1 ∉ (X (SG (F⇘A⇙) H) A)" using yx xy_x H assms lex_cont1_inv by (metis mult_SG) ultimately have "x1 ∉ (union_inv (X (SG (F⇘A⇙) H) A) A)" using notin_union_inv XH assms by blast then show ?thesis by blast qed qed then show False using y1 x1 by blast qed qed lemma L_inv_eq: "L(xs) = L(wordinverse xs) ⟹ xs ≠ [] ⟹ ¬ (reduced xs)" proof- assume xs: "L(xs) = L(wordinverse xs)" and rxs:"xs ≠ []" then show "¬ (reduced xs)" proof- have "L2 xs = ↓ (L2 xs)" unfolding left_tuple_def rev_tuple.simps using xs by simp moreover have "length xs = length xs" by simp ultimately have "xs = wordinverse xs" using rev_L2_inv by force then show ?thesis using rxs reduced_inv_eq_imp_nil by blast qed qed lemma lex_word_init: "(x, y) ∈ lex_word ⟹ (length a = length b) ⟹ (x@a, y@b) ∈ lex_word" unfolding lex_word_def by (simp add: lenlex_append1) lemma left_includes: "a = x @ y ⟹ length x ≤ length y ⟹ ∃z. L a = x @ z" unfolding left_subword_def by (simp add: take_append take_length) lemma take_bigger_half:"length a ≥ length b ⟹ take (((length (a@b)+1) div 2)) (a@b) = take (((length (a@b)+1) div 2)) a" by simp lemma lex_word_rightappend: assumes "(x,y) ∈ lex_word" shows "(x@c, y@c) ∈ lex_word" using lex_word_def lenlex_def assms lenlex_append1 by blast lemma L_inverse_eq: assumes "x = (p @ (wordinverse a))" and "y = (q @ (wordinverse a))" and "length p = length q" and "length p ≤ length (wordinverse a)" and "length q ≤ length (wordinverse a)" shows "L (wordinverse x) = L (wordinverse y)" proof- have "wordinverse x = a @ wordinverse p" using assms(1) by (metis FreeGroupMain.wordinverse_append FreeGroupMain.wordinverse_of_wordinverse) moreover have "length (wordinverse p) ≤ length a" by (metis assms(4) length_wordinverse) ultimately have 1:"L (wordinverse x) = take (((length (wordinverse x)+1) div 2)) a" unfolding left_subword_def using take_bigger_half by auto have "wordinverse y = a @ wordinverse q" using assms(2) by (metis FreeGroupMain.wordinverse_append FreeGroupMain.wordinverse_of_wordinverse) moreover have "length (wordinverse q) ≤ length a" by (metis assms(5) length_wordinverse) ultimately have "L (wordinverse y) = take (((length (wordinverse y)+1) div 2)) a" unfolding left_subword_def using take_bigger_half by auto then show ?thesis using 1 assms(3) length_wordinverse by (metis assms(1) assms(2) length_append) qed lemma neq_left_neq: "p ≠ q ⟹ length p = length q ⟹ length p ≤ length r ⟹ L (p @ r) ≠ L (q @ r)" unfolding left_subword_def by simp lemma lex_L2_inv2: assumes "(y,x) ∈ lex_L2_word A" shows "(inv⇘freegroup A⇙ y, x) ∈ lex_L2_word A" proof- have 1:"y ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using assms(1) unfolding lex_L2_word_def by blast then obtain invx where "invx = (inv⇘freegroup A⇙ y)" using freegroup_is_group by simp then have x:"(inv⇘freegroup A⇙ y) ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using m_inv_def[of "freegroup A" "y"] freegroup_def by (metis (no_types, lifting) freegroup_is_group group.inv_closed partial_object.select_convs(1) 1) have y: "x ∈ (⟨A⟩ // (reln_tuple ⟨A⟩))" using assms(1) unfolding lex_L2_word_def by blast have 2:"(length (red_rep A y) < length (red_rep A x)) ∨ ((length (red_rep A y) = length (red_rep A x) ∧ (y,x) ∈ lex_L2_word' A))" using nat_less_def assms unfolding lex_L2_word_def lex_prod_def by fastforce then show ?thesis proof(cases "(length (red_rep A y) < length (red_rep A x))") case True then have "length (wordinverse (red_rep A y)) < length (red_rep A x)" using length_wordinverse by metis then have "length (red_rep A (inv⇘freegroup A⇙ y)) < length (red_rep A x)" using 1 red_rep_inv by metis then show ?thesis using x y by (simp add: lex_L2_word_def nat_less_def) next case False then have 3:"((length (red_rep A y) = length (red_rep A x) ∧ (y,x) ∈ lex_L2_word' A))" using 2 by blast then have 4:"length (red_rep A (inv⇘freegroup A⇙ y)) = length (red_rep A x)" using 1 red_rep_inv by (metis length_wordinverse) then have "((λx. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) y , (λx. (min lex_word (L2 (red_rep A x)), max lex_word (L2 (red_rep A x)))) x) ∈ (lex_word <*lex*> lex_word)" using 3 unfolding lex_L2_word'_def by fastforce then have 5:"((min lex_word (L2 (red_rep A y))), (min lex_word (L2 (red_rep A x)))) ∈ lex_word ∨ (min lex_word (L2 (red_rep A y))) = (min lex_word (L2 (red_rep A x))) ∧ (max lex_word (L2 (red_rep A y)), max lex_word (L2 (red_rep A x))) ∈ lex_word" using lex_prod_def[of "lex_word" "lex_word"] by simp have "L2 (wordinverse (red_rep A y)) = (snd (L2 (red_rep A y)), fst (L2 (red_rep A y)))" using L2_wordinv by blast then have L2_winv:"min lex_word (L2 (red_rep A y)) = min lex_word (L2 (wordinverse (red_rep A y))) ∧ max lex_word (L2 (red_rep A y)) = max lex_word (L2 (wordinverse (red_rep A y)))" using wf_lex_word min.simps by (metis (no_types, lifting) lex_word_total max.simps prod.exhaust_sel wf_asym) then have "((min lex_word (L2 (wordinverse(red_rep A y)))), (min lex_word (L2 (red_rep A x)))) ∈ lex_word ∨ (min lex_word (L2 (wordinverse(red_rep A y)))) = (min lex_word (L2 (red_rep A x))) ∧ (max lex_word (L2 (wordinverse(red_rep A y))), max lex_word (L2 (red_rep A x))) ∈ lex_word" using 5 by auto then have "((min lex_word (L2 (red_rep A(inv⇘freegroup A⇙ y)))), (min lex_word (L2 (red_rep A x)))) ∈ lex_word ∨ (min lex_word (L2 (red_rep A(inv⇘freegroup A⇙ y)))) = (min lex_word (L2 (red_rep A x))) ∧ (max lex_word (L2 (red_rep A(inv⇘freegroup A⇙ y))), max lex_word (L2 (red_rep A x))) ∈ lex_word" using red_rep_inv 1 by force then have "((inv⇘freegroup A⇙ y),x) ∈ lex_L2_word' A" unfolding lex_L2_word'_def using x y by auto then show ?thesis using x y 2 4 lex_L2_word_length by blast qed qed lemma three_point_six: assumes "x ∈ carrier (freegroup A) ∧ xy ∈ carrier (freegroup A)" "red_rep A x = p@c ∧ red_rep A xy = q@c" "length p = length q" "length p ≤ length c" "length q ≤ length c" "(p,q) ∈ lex_word" "p ≠ q" "N0 (red_rep A x)" "N0 (red_rep A xy)" shows "(x, xy) ∈ lex_L2_word A" proof- let ?X = "(red_rep A x)" let ?XY = "(red_rep A xy)" have rx:"reduced ?X" using freegroup_def[of "A"] assms(1) red_rep_the[of "x" "A"] by (simp add: red_rep_def) have rxy:"reduced ?XY" using freegroup_def[of "A"] assms(1) red_rep_the[of "xy" "A"] by (simp add: red_rep_def) have "L(?X) ≠ L (?XY)" using assms(2,3,4,7) neq_left_neq by fastforce obtain r where r:"L(?X) = (p @ r)" using assms(2,4) left_includes by blast obtain s where s:"L(?XY) = (q @ s)" using assms(2,5) left_includes by blast have lxxy:"length (L(?X)) = length (L(?XY))" using assms(2,3) rx rxy unfolding left_subword_def by auto then have "length (p@r) = length (q@s)" using r s by simp moreover then have "length r = length s" using assms(3) by simp ultimately have "((p@r), (q@s)) ∈ lex_word" using assms(6) lex_word_def lenlex_append1 by blast then have L_lex:"(L(?X), L(?XY)) ∈ lex_word" using r s by simp have L_eq:"L(wordinverse ?X) = L(wordinverse ?XY)" using L_inverse_eq assms(2,3,5) by (metis (no_types, lifting) wordinverse_symm) have length:"length (?X) = length (?XY)" using assms(2,3) length_eq by simp show ?thesis proof(cases "(L(wordinverse ?X), L(?X)) ∈ lex_word") case True then have "min lex_word (L2 (wordinverse ?X)) = L(wordinverse ?X)" unfolding left_tuple_def min.simps by (simp add: wordinverse_of_wordinverse) then have min1:"min lex_word (L2 (?X)) = L(wordinverse ?X)" using min_L2_inv using assms(1) by fastforce moreover then have max1:"max lex_word (L2 (?X)) = L (?X)" by (metis lex_word_one True left_tuple_def max.simps) ultimately have "min lex_word (L2 ?XY) = L(wordinverse ?XY)" using L_eq L_lex transD lex_word_one trans_lex_word left_tuple_def min.simps by metis then have 1:"(L(wordinverse ?XY), L(?XY)) ∈ lex_word" unfolding left_tuple_def min.simps using L_eq L_lex True lex_word_one lex_word_total by fastforce then have "min lex_word (L2 (wordinverse ?XY)) = L(wordinverse ?XY)" unfolding left_tuple_def min.simps by (simp add: wordinverse_of_wordinverse) then have min2:"min lex_word (L2 (?XY)) = L(wordinverse ?XY)" using min_L2_inv using assms(1) by fastforce then have max2:"max lex_word (L2 (wordinverse ?XY)) = L(?XY)" by (metis FreeGroupMain.wordinverse_symm 1 left_tuple_def max.simps) have "x ∈ ⟨A⟩ // reln_tuple ⟨A⟩ ∧ xy ∈ ⟨A⟩ // reln_tuple ⟨A⟩" using assms(1) freegroup_def[of "A"] by auto moreover have "(min lex_word (L2 (?X))) = (min lex_word (L2 (?XY)))" using min1 min2 L_eq by auto moreover have "((max lex_word (L2 (wordinverse (?X))), max lex_word (L2 (wordinverse (?XY))))) ∈ lex_word" using max1 max2 L_lex by (metis FreeGroupMain.wordinverse_symm True left_tuple_def max.simps) ultimately have "(x, xy) ∈ lex_L2_word' A" unfolding lex_L2_word'_def lex_prod_def left_tuple_def using wordinverse_symm left_tuple_def by (smt (z3) case_prod_conv max.simps max1 mem_Collect_eq min.simps min1) then show ?thesis by (simp add: ‹x ∈ ⟨A⟩ // reln_tuple ⟨A⟩ ∧ xy ∈ ⟨A⟩ // reln_tuple ⟨A⟩› length lex_L2_word_length) next case False then have "(L(?X),L(wordinverse ?X)) ∈ lex_word" using L_inv_eq N0_def assms(8) lex_word_total rx by auto then have "min lex_word (L2 (wordinverse ?X)) = L(?X)" unfolding left_tuple_def min.simps by (simp add: False FreeGroupMain.wordinverse_of_wordinverse) then have min1:"min lex_word (L2 (?X)) = L(?X)" using min_L2_inv using assms(1) by fastforce then have max1:"max lex_word (L2 (wordinverse ?X)) = L (wordinverse ?X)" by (metis FreeGroupMain.wordinverse_symm False left_tuple_def max.simps) then show ?thesis proof(cases "(L(wordinverse ?XY), L(?XY)) ∈ lex_word") case True then have "min lex_word (L2 (wordinverse ?XY)) = L(wordinverse ?XY)" unfolding left_tuple_def min.simps by (simp add: wordinverse_of_wordinverse) then have min2:"min lex_word (L2 (?XY)) = L(wordinverse ?XY)" using min_L2_inv using assms(1) by fastforce then have max2:"max lex_word (L2 (wordinverse ?XY)) = L(?XY)" by (metis FreeGroupMain.wordinverse_symm True left_tuple_def max.simps) have "x ∈ ⟨A⟩ // reln_tuple ⟨A⟩ ∧ xy ∈ ⟨A⟩ // reln_tuple ⟨A⟩" using assms(1) freegroup_def[of "A"] by auto moreover have "((min lex_word (L2 (red_rep A x))),(min lex_word (L2 (red_rep A xy)))) ∈ lex_word" using min1 min2 max2 L_eq using ‹(L (red_rep A x), L (wordinverse (red_rep A x))) ∈ lex_word› by auto ultimately have "(x, xy) ∈ lex_L2_word' A" unfolding lex_L2_word'_def lex_prod_def left_tuple_def using wordinverse_symm left_tuple_def by (smt (z3) case_prod_conv max.simps max1 mem_Collect_eq min.simps min1) then show ?thesis unfolding lex_L2_word'_def using assms(1,6,7) freegroup_def length ‹(x, xy) ∈ lex_L2_word' A› lex_L2_word_length by blast next case False then have subcases:"(L(wordinverse ?XY) = L(?XY)) ∨ (L(?XY),(L(wordinverse ?XY))) ∈ lex_word" using lex_word_total by blast then show ?thesis proof(cases "(L(wordinverse ?XY) = L(?XY))") case True then have "reduced ?XY" using assms(1) freegroup_def red_rep_the by (metis partial_object.select_convs(1)) then have "?XY = []" using L_inv_eq True by metis then have "(red_rep A xy) = []" by blast then show ?thesis using assms(9) N0_def by auto next case False then have false:"(L(?XY),(L(wordinverse ?XY))) ∈ lex_word" using subcases by simp then have 2:"min lex_word (L2 ?XY) = L(?XY)" unfolding left_tuple_def min.simps by (simp add: wordinverse_of_wordinverse) have 1:"(L ?XY, L (wordinverse ?X)) ∈ lex_word" using false L_eq by simp have "x ∈ ⟨A⟩ // reln_tuple ⟨A⟩ ∧ xy ∈ ⟨A⟩ // reln_tuple ⟨A⟩" using assms(1) freegroup_def[of "A"] by auto moreover have "((min lex_word (L2 (red_rep A x))),(min lex_word (L2 (red_rep A xy)))) ∈ lex_word" using 1 2 false L_eq min1 using L_lex by auto ultimately have "(x, xy) ∈ lex_L2_word' A" unfolding lex_L2_word'_def lex_prod_def left_tuple_def using wordinverse_symm left_tuple_def by (smt (z3) case_prod_conv max.simps max1 mem_Collect_eq min.simps min1) then show ?thesis unfolding lex_L2_word'_def using assms(1,6,7) freegroup_def length ‹(x, xy) ∈ lex_L2_word' A› lex_L2_word_length by blast qed qed qed qed lemma three_point_seven:assumes "x ∈ (carrier (freegroup A))" and "xy ∈ (carrier (freegroup A))" and "red_rep A x = (a @ (wordinverse p))" and "red_rep A xy = (a @ (wordinverse q))" and "length (wordinverse p) = length (wordinverse q)" and "length (wordinverse p) ≤ length a" and "length (wordinverse q) ≤ length a" and "(q, p) ∈ lex_word" and "p ≠ q" and "(red_rep A x) ≠ []" and "(red_rep A xy) ≠ []" shows "(xy, x) ∈ lex_L2_word A" proof- let ?X = "(red_rep A (m_inv (freegroup A) x))" have 1:"(red_rep A (m_inv (freegroup A) x)) = wordinverse (red_rep A x)" using assms(1) unfolding freegroup_def using red_rep_inv by (metis freegroup_def partial_object.select_convs(1)) then have x:"?X = (p @ (wordinverse a))" using assms(3) wordinverse_append wordinverse_of_wordinverse by metis let ?XY = "(red_rep A (m_inv (freegroup A) xy))" have 2:"(red_rep A (m_inv (freegroup A) xy)) = wordinverse (red_rep A xy)" using assms(2) unfolding freegroup_def using red_rep_inv by (metis freegroup_def partial_object.select_convs(1)) then have xy:"?XY = (q @ (wordinverse a))" using assms(4) wordinverse_append wordinverse_of_wordinverse by metis have "L (?XY) ≠ L (?X)" using xy x neq_left_neq assms(5,9) assms(7) by (metis length_wordinverse) have pq:"length p = length q" using assms(5) by (metis length_wordinverse) have p:"length p ≤ length (wordinverse a)" by (metis assms(6) length_wordinverse) then obtain r where r:"p @ r = L (?X)" using x left_includes by metis have "length q ≤ length (wordinverse a)" by (metis assms(7) length_wordinverse) then obtain s where s:"q @ s = L (?XY)" using xy left_includes by metis have "length (L ?X) = length (L ?XY)" using x xy pq unfolding left_subword_def by simp then have "length (p @ r) = length (q @ s)" using r s by simp moreover then have "length r = length s" using pq by simp ultimately have "((q@s), (p@r)) ∈ lex_word" by (simp add: lex_word_init assms(8)) then have L:"((L ?XY),(L ?X)) ∈ lex_word" by (simp add: r s) have R:"L (wordinverse ?X) = L (wordinverse ?XY)" using L_inverse_eq x xy pq assms(6) assms(7) p by fastforce have Xneq: "L (?X) ≠ L (wordinverse ?X)" proof(rule ccontr) assume "¬ L (red_rep A (inv⇘F⇘A⇙⇙ x)) ≠ L (wordinverse (red_rep A (inv⇘F⇘A⇙⇙ x)))" then have "L (red_rep A (inv⇘F⇘A⇙⇙ x)) = L (wordinverse (red_rep A (inv⇘F⇘A⇙⇙ x)))" by blast moreover have "reduced ?X" unfolding red_rep_def using red_rep_the assms(1) unfolding freegroup_def by (metis "1" freegroup_def partial_object.select_convs(1) red_rep_def reduced_wordinverse) ultimately have "?X = []" using L_inv_eq by blast then have "(red_rep A x) = []" by (metis "1" FreeGroupMain.wordinverse_symm wordinverse.simps(1)) then show False using assms(10) by blast qed have XYneq: "L (?XY) ≠ L (wordinverse ?XY)" proof(rule ccontr) assume "¬ L (red_rep A (inv⇘F⇘A⇙⇙ xy)) ≠ L (wordinverse (red_rep A (inv⇘F⇘A⇙⇙ xy)))" then have "L (red_rep A (inv⇘F⇘A⇙⇙ xy)) = L (wordinverse (red_rep A (inv⇘F⇘A⇙⇙ xy)))" by blast moreover have "reduced ?XY" unfolding red_rep_def using red_rep_the assms(2) unfolding freegroup_def by (metis "2" freegroup_def partial_object.select_convs(1) red_rep_def reduced_wordinverse) ultimately have "?XY = []" using L_inv_eq by blast then have "(red_rep A xy) = []" by (metis "2" FreeGroupMain.wordinverse_symm wordinverse.simps(1)) then show False using assms(11) by blast qed have xyin:"(inv⇘F⇘A⇙⇙ xy) ∈ ⟨A⟩ // reln_tuple ⟨A⟩" using assms(2) freegroup_is_group unfolding freegroup_def using group.inv_closed by fastforce have xin: "(inv⇘F⇘A⇙⇙ x) ∈ ⟨A⟩ // reln_tuple ⟨A⟩" using assms(1) freegroup_is_group unfolding freegroup_def using group.inv_closed by fastforce have "length ?XY = length ?X" using x xy pq by simp then have "((m_inv (freegroup A) xy, m_inv (freegroup A) x) ∈ lex_L2_word A) = ((m_inv (freegroup A) xy, m_inv (freegroup A) x) ∈ lex_L2_word' A)" using lex_L2_word_def lex_L2_word_length mem_Collect_eq xin xyin by fastforce moreover have "((m_inv (freegroup A) xy, m_inv (freegroup A) x) ∈ lex_L2_word' A)" proof(cases "(L (?XY), L (wordinverse ?XY)) ∈ lex_word") case True note first = this then have 1:"(min lex_word (L2 ?XY)) = L (?XY)" unfolding left_tuple_def min.simps by simp then show ?thesis proof(cases "(L (?X), L (wordinverse ?X)) ∈ lex_word") case True then have "(min lex_word (L2 ?X)) = L ((?X))" unfolding left_tuple_def min.simps by simp then have "((min lex_word (L2 ?XY)), min lex_word (L2 ?X)) ∈ lex_word" using L 1 by fastforce then show ?thesis unfolding lex_L2_word'_def lex_prod_def using xin xyin by fast next case False then have "(min lex_word (L2 ?X)) = L (wordinverse ?X)" unfolding left_tuple_def min.simps by simp moreover have "(L ?XY, L (wordinverse ?X)) ∈ lex_word" using R first by simp ultimately have "((min lex_word (L2 ?XY)), min lex_word (L2 ?X)) ∈ lex_word" using R 1 by fastforce then show ?thesis unfolding lex_L2_word'_def lex_prod_def using xin xyin by fast qed next case False then have 1: "(L (wordinverse ?XY),L ?XY) ∈ lex_word" using XYneq lex_word_total by auto have A:"(min lex_word (L2 ?XY)) = L (wordinverse ?XY)" unfolding left_tuple_def min.simps using False by simp have 2:"(L (wordinverse ?X),L (?X)) ∈ lex_word" using 1 L R trans_lex_word transD by fastforce then have "(min lex_word (L2 ?X)) = L (wordinverse ?X)" unfolding left_tuple_def min.simps using lex_word_one by auto then have min:"(min lex_word (L2 ?X)) = (min lex_word (L2 ?XY))" using A R by simp have "max lex_word (L2 ?XY) = L (?XY)" by (simp add: False left_tuple_def) moreover have "max lex_word (L2 ?X) = L (?X)" using 2 lex_word_one unfolding left_tuple_def max.simps by force ultimately have "((max lex_word (L2 ?XY)), max lex_word (L2 ?X)) ∈ lex_word" using L by simp then show ?thesis unfolding lex_L2_word'_def lex_prod_def using xin xyin min by auto qed ultimately have "((m_inv (freegroup A) xy, m_inv (freegroup A) x) ∈ lex_L2_word A)" by simp then have "(m_inv (freegroup A) (m_inv (freegroup A) xy), m_inv (freegroup A) x) ∈ lex_L2_word A" by (simp add: lex_L2_inv2) then have "(m_inv (freegroup A) (m_inv (freegroup A) xy), m_inv (freegroup A) (m_inv (freegroup A) x)) ∈ lex_L2_word A" by (simp add: lex_L2_inv) then show ?thesis using assms(1,2) by (simp add: freegroup_is_group) qed lemma N0: assumes "H ≤ freegroup A" shows "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N0 x" proof fix x assume x:"x ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" show "N0 x" proof(rule ccontr) assume "¬ N0 x" then have "x = []" unfolding N0_def by simp moreover obtain x1 where x1:"red_rep A x1 = x ∧ x1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using x by blast moreover then have xin:"x1 ∈ carrier(freegroup A)" using assms assms union_inv_clos by blast ultimately have 1:"x1 = 𝟭⇘freegroup A⇙" unfolding red_rep_def freegroup_def using red_rep_the x1 by force then have "x1 ∈ (X (SG (freegroup A) H) A) " proof(cases "x1 ∈ (X (SG (freegroup A) H) A)") case True then show ?thesis by simp next case False then have "x1 ∈ m_inv (freegroup A) ` (X (SG (freegroup A) H) A)" using x1 unfolding union_inv_def by simp then obtain x2 where x2:"m_inv (freegroup A) x2 = x1 ∧ x2 ∈ (X (SG (freegroup A) H) A)" by blast moreover then have "x2 ∈ carrier(freegroup A)" using assms union_inv_clos union_inv_def by fastforce ultimately have "m_inv (freegroup A) x1 = x2" using freegroup_is_group group.inv_inv by fast then have "x2 = 𝟭⇘freegroup A⇙" using 1 freegroup_is_group by (metis group.inv_eq_1_iff xin) then show ?thesis using x2 1 by simp qed moreover have "𝟭⇘freegroup A⇙ ∈ G (SG (freegroup A) H) A (𝟭⇘freegroup A⇙)" unfolding G_def by (metis (no_types, lifting) gen_span.simps one_SG) ultimately show False unfolding X_def using 1 by blast qed qed lemma cancel_p2_q3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x ≠ wordinverse y" and "y ≠ wordinverse z" shows "p2 (cancel2 y z) = q3 (cancel3 x y z)" proof- have 1:"x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z)) ∧ y = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ (q3 (cancel3 x y z)) ∧ z = (wordinverse (q3 (cancel3 x y z))) @ (c3 (cancel3 x y z)) ∧ reduced (a3 (cancel3 x y z) @ b3 (cancel3 x y z) @ q3 (cancel3 x y z)) ∧ reduced (wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ c3 (cancel3 x y z))" using assms cancel3_the by blast have 2:"y = (a2 (cancel2 y z)) @ (p2 (cancel2 y z)) ∧ z = (wordinverse (p2 (cancel2 y z))) @ (b2 (cancel2 y z)) ∧ reduced ((a2 (cancel2 y z)) @ (b2 (cancel2 y z)))" using assms(2,3) by (simp add: cancel2_the) define w2 where 3:"w2 = ((wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z)), (q3 (cancel3 x y z)), (c3 (cancel3 x y z)))" then have "y = (a2 w2) @ (p2 w2) ∧ z = (wordinverse (p2 w2)) @ (b2 w2) ∧ reduced ((a2 w2) @ (b2 w2))" using 1 by auto then have "w2 = (cancel2 y z)" using 2 assms(2,3) cancel2E' by blast then have "p2 w2 = p2 (cancel2 y z)" by simp then show ?thesis using 3 by simp qed lemma cancel_b2_c3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x ≠ wordinverse y" and "y ≠ wordinverse z" shows "b2 (cancel2 y z) = c3 (cancel3 x y z)" proof- have 1:"x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z)) ∧ y = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ (q3 (cancel3 x y z)) ∧ z = (wordinverse (q3 (cancel3 x y z))) @ (c3 (cancel3 x y z)) ∧ reduced (a3 (cancel3 x y z) @ b3 (cancel3 x y z) @ q3 (cancel3 x y z)) ∧ reduced (wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ c3 (cancel3 x y z))" using assms cancel3_the by blast have 2:"y = (a2 (cancel2 y z)) @ (p2 (cancel2 y z)) ∧ z = (wordinverse (p2 (cancel2 y z))) @ (b2 (cancel2 y z)) ∧ reduced ((a2 (cancel2 y z)) @ (b2 (cancel2 y z)))" using assms(2,3) by (simp add: cancel2_the) define w2 where 3:"w2 = ((wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z)), (q3 (cancel3 x y z)), (c3 (cancel3 x y z)))" then have "y = (a2 w2) @ (p2 w2) ∧ z = (wordinverse (p2 w2)) @ (b2 w2) ∧ reduced ((a2 w2) @ (b2 w2))" using 1 by auto then have "w2 = (cancel2 y z)" using 2 assms(2,3) cancel2E' by blast then have "b2 w2 = b2 (cancel2 y z)" by simp then show ?thesis using 3 by simp qed lemma cancel_b2_bq3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x ≠ wordinverse y" and "y ≠ wordinverse z" shows "b2 (cancel2 x y) = (b3 (cancel3 x y z)) @ q3 (cancel3 x y z)" proof- have 1:"x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z)) ∧ y = wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ (q3 (cancel3 x y z)) ∧ z = (wordinverse (q3 (cancel3 x y z))) @ (c3 (cancel3 x y z)) ∧ reduced (a3 (cancel3 x y z) @ b3 (cancel3 x y z) @ q3 (cancel3 x y z)) ∧ reduced (wordinverse (p3 (cancel3 x y z)) @ b3 (cancel3 x y z) @ c3 (cancel3 x y z))" using assms cancel3_the by blast have 2:"y = (a2 (cancel2 y z)) @ (p2 (cancel2 y z)) ∧ z = (wordinverse (p2 (cancel2 y z))) @ (b2 (cancel2 y z)) ∧ reduced ((a2 (cancel2 y z)) @ (b2 (cancel2 y z)))" using assms(2,3) by (simp add: cancel2_the) define w2 where 3:"w2 = ((a3 (cancel3 x y z)), ((p3 (cancel3 x y z))), b3 (cancel3 x y z)@ (q3 (cancel3 x y z)))" then have "y = (wordinverse (p2 w2)) @ (b2 w2) ∧ x = ((a2 w2)) @ (p2 w2) ∧ reduced ((a2 w2) @ (b2 w2))" using 1 by auto then have "w2 = (cancel2 x y)" using 2 3 assms(1,2,3) cancel2E' cancel2_the[of "x" "y"] by blast then have "b2 w2 = b2 (cancel2 x y)" by simp then show ?thesis using 3 by simp qed lemma cancel_p2_p3: assumes "reduced x" and "reduced y" and "reduced z" and "N1 x y" and "N1 y z" and "x ≠ wordinverse y" and "y ≠ wordinverse z" shows "p2 (cancel2 x y) = p3 (cancel3 x y z)" proof- have "x = a3 (cancel3 x y z) @ (p3 (cancel3 x y z))" using assms cancel3_the by blast moreover have "x = (a2 (cancel2 x y)) @ (p2 (cancel2 x y))" using assms(1,2) by (simp add: cancel2_the) ultimately show ?thesis using cancel_a2_a3 assms by (metis same_append_eq) qed lemma neq_imp_invneq: "p ≠ q ⟹ wordinverse p ≠ wordinverse q" by (metis FreeGroupMain.wordinverse_symm) lemma reln_eq_image: assumes "x ∈ ⟨S⟩ ∧ y ∈ ⟨S⟩ ∧ x~y" shows "((reln_tuple ⟨S⟩)`` {x}) =( (reln_tuple ⟨S⟩)`` {y})" using assms reln_tuple_def[of "⟨S⟩"] equiv_class_eq reln_equiv by fastforce lemma red_repI: assumes "x1 ∈ ⟨A⟩ // reln_tuple ⟨A⟩" "x1 = reln_tuple ⟨A⟩ `` {x}" "reduced x" shows "red_rep A x1 = x" proof- have "x ∈ x1" by (metis Image_singleton_iff assms(1) assms(2) equiv_class_eq_iff red_rep_the reln_equiv) then have "x ∈ x1 ∧ reduced x ∧ x1 = reln_tuple ⟨A⟩ `` {x}" using assms by auto then show ?thesis using assms(1) red_rep_the[of "x1" "A"] unfolding red_rep_def using redelem_unique by fastforce qed lemma N2: assumes "H ≤ freegroup A" and "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N0 x" and "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀y ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N1 x y" shows "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀y ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀z ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N2 x y z" apply(rule ballI)+ proof- fix x y z assume x: "x ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" and y: "y ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" and z:"z ∈ red_rep A ` union_inv (X (SG F⇘A⇙ H) A) A" show "N2 x y z" proof(rule ccontr) assume N2: "¬ N2 x y z" then have invxyz:"x ≠ wordinverse y ∧ y ≠ wordinverse z" using N2_def by auto obtain x1 where x1:"red_rep A x1 = x ∧ x1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using x by blast moreover then have x1A: "x1 ∈ carrier (freegroup A)" using assms union_inv_clos by blast ultimately have rx:"reduced x" using red_rep_the unfolding red_rep_def freegroup_def by auto have xA: "x \<in> ⟨A⟩" using redrep_in x1 x1A by fastforce obtain y1 where y1:"red_rep A y1 = y ∧ y1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using y by blast moreover then have y1A: "y1 ∈ carrier (freegroup A)" using assms union_inv_clos by blast ultimately have ry:"reduced y" using red_rep_the unfolding red_rep_def freegroup_def by auto have yA: "y \<in> ⟨A⟩" using redrep_in y1 y1A by fastforce obtain z1 where z1:"red_rep A z1 = z ∧ z1 ∈ (union_inv (X (SG (freegroup A) H) A) A)" using z by blast moreover then have z1A: "z1 ∈ carrier (freegroup A)" using assms union_inv_clos by blast ultimately have rz:"reduced z" using red_rep_the unfolding red_rep_def freegroup_def by auto have zA: "z \<in> ⟨A⟩" using redrep_in z1 z1A by fastforce have H:"x1 ∈ H ∧ y1 ∈ H ∧ z1 ∈ H" using assms x1 x1A y1 z1 z1A using union_inv_sub_H by blast have b:"(b3 (⊘⇘3⇙ x y z) = [])" using N2 unfolding N2_def by fastforce then have xyz:"x = a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) ∧ y = wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z) ∧ z = wordinverse (q3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z) ∧ reduced (a3 (⊘⇘3⇙ x y z) @ q3 (⊘⇘3⇙ x y z)) ∧ reduced (wordinverse (p3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z))" using assms(3) rx ry rz x y z cancel3_the invxyz by (metis append.left_neutral) then have neq:"(p3 (⊘⇘3⇙ x y z)) ≠ q3 (⊘⇘3⇙ x y z)" using y assms(2) ry by (metis FreeGroupMain.inverse_wordinverse N0_def reduced.simps(1) reduced_reln_eq) have pa:"length (p3 (⊘⇘3⇙ x y z)) ≤ length (a3 (⊘⇘3⇙ x y z))" using assms(3) xyz rx ry rz x y z invxyz cancel2_the cancel_a2_a3 unfolding N1_def by (metis (no_types, lifting) same_append_eq) have "length (p2 (y ⊘⇘2⇙ z)) ≤ length (b2 (y ⊘⇘2⇙ z))" using assms(3) ry rz y z xyz invxyz cancel2_the N1_def by blast then have qc: "length (q3 (⊘⇘3⇙ x y z)) ≤ length (c3 (⊘⇘3⇙ x y z))" using assms(3) xyz rx ry rz x y z invxyz cancel_b2_c3 cancel_p2_q3 by (metis (no_types, lifting)) have "length (p2 (x ⊘⇘2⇙ y)) ≤ length (b2 (x ⊘⇘2⇙ y))" using assms(3) rx ry x y xyz invxyz cancel2_the N1_def by blast then have pq: "length (p3 (⊘⇘3⇙ x y z)) ≤ length (q3 (⊘⇘3⇙ x y z))" using assms(3) xyz rx ry rz x y z invxyz cancel_b2_bq3 cancel_p2_p3 b by (metis append.left_neutral) have "length (p2 (y ⊘⇘2⇙ z)) ≤ length (b2 (y ⊘⇘2⇙ z))" using assms(3) ry rz y z xyz invxyz cancel2_the N1_def by blast then have qp: "length (q3 (⊘⇘3⇙ x y z)) ≤ length (p3 (⊘⇘3⇙ x y z))" using assms(3) xyz rx ry rz x y z invxyz cancel_p2_q3 b by (metis N1_def append_Nil2 cancel_a2_pb3 length_wordinverse) then have leq:"length (q3 (⊘⇘3⇙ x y z)) = length (p3 (⊘⇘3⇙ x y z))" using pq by simp then have pc: "length (p3 (⊘⇘3⇙ x y z)) ≤ length (c3 (⊘⇘3⇙ x y z))" using qc by simp have qa: "length (q3 (⊘⇘3⇙ x y z)) ≤ length (a3 (⊘⇘3⇙ x y z))" using pa leq by simp have xneqy: "x ≠ y" using xyz neq by (metis append_eq_append_conv leq) have yneqz: "y ≠ z" using xyz neq leq neq_imp_invneq by (metis append_eq_conv_conj length_wordinverse) have x1y1in:"x1 ⊗⇘freegroup A⇙ y1 ∈ carrier (freegroup A)" by (meson H assms(1) subgroup.m_closed subgroup.mem_carrier) have "(a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) @ wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z)) ~ (a3 (⊘⇘3⇙ x y z) @ q3 (⊘⇘3⇙ x y z)) ∧ x1 ⊗⇘freegroup A⇙ y1 = reln_tuple ⟨A⟩ `` {a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) @ wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z)}" unfolding freegroup_def by (metis (no_types, lifting) append_assoc cancel2_reln freegroup_def monoid.select_convs(1) partial_object.select_convs(1) proj_append_wd red_rep_the redrep_in x1 x1A xyz y1 y1A) moreover have "(a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) @ wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z)) \<in> \<langle>A\<rangle>" proof- have "x @ y \<in> \<langle>A\<rangle>" using xA yA unfolding freewords_on_def by (simp add: span_append) moreover have "x = a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) \<and> y = wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z)" using xyz by blast ultimately show ?thesis by (metis append.assoc) qed moreover have "(a3 (⊘⇘3⇙ x y z) @ q3 (⊘⇘3⇙ x y z)) \<in> \<langle>A\<rangle>" proof- have 1:"x = a3 (⊘⇘3⇙ x y z) @ p3 (⊘⇘3⇙ x y z) \<and> y = wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z)" using xyz by blast then have "a3 (⊘⇘3⇙ x y z) \<in> \<langle>A\<rangle>" unfolding freewords_on_def by (metis freewords_on_def leftappend_span xA) moreover have "q3 (⊘⇘3⇙ x y z) \<in> \<langle>A\<rangle>" unfolding freewords_on_def by (metis freewords_on_def rightappend_span 1 yA) ultimately show ?thesis unfolding freewords_on_def by (simp add: span_append) qed ultimately have "x1 ⊗⇘freegroup A⇙ y1 = reln_tuple ⟨A⟩ `` {a3 (⊘⇘3⇙ x y z) @ q3 (⊘⇘3⇙ x y z)}" by (simp add: reln_eq_image) then have x1y1:"red_rep A (x1 ⊗⇘freegroup A⇙ y1) = (a3 (⊘⇘3⇙ x y z) @ q3 (⊘⇘3⇙ x y z))" using x1y1in unfolding freegroup_def using red_repI xyz by auto have y1z1in:"y1 ⊗⇘freegroup A⇙ z1 ∈ carrier (freegroup A)" by (meson H assms(1) subgroup.m_closed subgroup.mem_carrier) moreover have "(wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z) @ wordinverse (q3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z)) ~ (wordinverse (p3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z)) ∧ y1 ⊗⇘freegroup A⇙ z1 = reln_tuple ⟨A⟩ `` {(wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z) @ wordinverse (q3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z))}" unfolding freegroup_def by (metis append_assoc cancel2_reln freegroup_def monoid.select_convs(1) partial_object.select_convs(1) proj_append_wd red_rep_the redrep_in xyz y1 y1A z1 z1A) moreover have "(wordinverse (p3 (⊘⇘3⇙ x y z)) @ q3 (⊘⇘3⇙ x y z) @ wordinverse (q3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z)) \<in> \<langle>A\<rangle> \<and> (wordinverse (p3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z)) \<in> \<langle>A\<rangle>" using xyz xA yA unfolding freewords_on_def by (metis freewords_on_def rightappend_span span_append span_wordinverse zA) ultimately have "y1 ⊗⇘freegroup A⇙ z1 = reln_tuple ⟨A⟩ `` {(wordinverse (p3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z))}" by (simp add: reln_eq_image) then have y1z1:"red_rep A (y1 ⊗⇘freegroup A⇙ z1) = (wordinverse (p3 (⊘⇘3⇙ x y z)) @ c3 (⊘⇘3⇙ x y z))" using y1z1in unfolding freegroup_def using red_repI xyz by auto have ineq:"wordinverse (p3 (⊘⇘3⇙ x y z)) ≠ wordinverse (q3 (⊘⇘3⇙ x y z))" by (simp add: neq neq_imp_invneq) then have cases:"(wordinverse (p3 (⊘⇘3⇙ x y z)), wordinverse (q3 (⊘⇘3⇙ x y z))) ∈ lex_word ∨ (wordinverse (q3 (⊘⇘3⇙ x y z)), wordinverse ( p3 (⊘⇘3⇙ x y z))) ∈ lex_word" unfolding lex_word_def using lex_word_def lex_word_total by auto show False proof(cases "(wordinverse (p3 (⊘⇘3⇙ x y z)), wordinverse (q3 (⊘⇘3⇙ x y z))) ∈ lex_word") case True let ?p = "wordinverse (p3 (⊘⇘3⇙ x y z))" let ?q = "wordinverse (q3 (⊘⇘3⇙ x y z))" let ?c = "c3 (⊘⇘3⇙ x y z)" have "red_rep A z1 = ?q @ ?c" using xyz z1 by force moreover have "red_rep A (y1 ⊗⇘freegroup A⇙ z1) = ?p @ ?c" by (simp add: y1z1) moreover have "length ?p = length ?q" using leq by (metis length_wordinverse) moreover have "?p ≠ ?q" using ineq . moreover have "length ?p ≤ length ?c" by (metis length_wordinverse pc) moreover have "length ?q ≤ length ?c" by (metis length_wordinverse qc) moreover have "red_rep A (y1 ⊗⇘freegroup A⇙ z1) ≠ []" using y1z1 FreeGroupMain.wordinverse_symm invxyz xyz by fastforce moreover have "red_rep A z1 ≠ []" using N0_def assms(2) z1 by auto ultimately have cont:"((y1 ⊗⇘freegroup A⇙ z1), z1) ∈ lex_L2_word A" using True z1A y1z1in xyz z three_point_six[of "z1" "A" "(y1 ⊗⇘freegroup A⇙ z1)" "?p" "?c" "?q"] by (metis N0_def three_point_six) have subcases:"(y1, z1) ∈ lex_L2_word A ∨ (z1, y1) ∈ lex_L2_word A" by (simp add: invxyz lex_total y1 y1A yneqz z1 z1A) then show ?thesis proof(cases "(y1, z1) ∈ lex_L2_word A") case True then have "z1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont2[of "y1" "z1" "A" "H"] H assms(1) cont by (metis mult_SG) moreover have "inv⇘SG F⇘A⇙ H⇙ z1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont2_inv[of "y1" "z1" "A" "H"] H assms(1) cont True by (metis mult_SG) moreover have "X (SG (F⇘A⇙) H) A ⊆ H" unfolding X_def SG_def by simp ultimately have "z1 ∉ (union_inv (X (SG (freegroup A) H) A) A)" using notin_union_inv[of "H" "A" "z1" "X (SG F⇘A⇙ H) A"] assms(1) by simp then show ?thesis using z1 by blast next case False then have F:"(z1, y1) ∈ lex_L2_word A" using subcases by blast moreover then have trans:"(y1 ⊗⇘F⇘A⇙⇙ z1, y1) ∈ lex_L2_word A" using cont trans_lex_L2_word transD by fast ultimately have "y1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont1[of "z1" "y1" "A" "H"] H assms(1) cont by (metis mult_SG) moreover have "inv⇘SG F⇘A⇙ H⇙ y1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont1_inv[of "z1" "y1" "A" "H"] H assms(1) cont F trans by (metis mult_SG) moreover have "X (SG (F⇘A⇙) H) A ⊆ H" unfolding X_def SG_def by simp ultimately have "y1 ∉ (union_inv (X (SG (freegroup A) H) A) A)" using notin_union_inv[of "H" "A" "y1" "X (SG F⇘A⇙ H) A"] assms(1) by simp then show ?thesis using y1 by blast qed next case False then have F:"(wordinverse (q3 (⊘⇘3⇙ x y z)), wordinverse ( p3 (⊘⇘3⇙ x y z))) ∈ lex_word" using cases by simp let ?p = "wordinverse (p3 (⊘⇘3⇙ x y z))" let ?q = "wordinverse (q3 (⊘⇘3⇙ x y z))" let ?a = "a3 (⊘⇘3⇙ x y z)" have "red_rep A x1 = ?a @ wordinverse ?p" using xyz x1 by (metis FreeGroupMain.wordinverse_of_wordinverse) moreover have "red_rep A (x1 ⊗⇘freegroup A⇙ y1) = ?a @ wordinverse ?q" using x1y1 FreeGroupMain.wordinverse_of_wordinverse by metis moreover have "length (wordinverse ?p) = length (wordinverse ?q)" using leq by (metis length_wordinverse) moreover have "?p ≠ ?q" using ineq . moreover have "length (wordinverse ?p) ≤ length ?a" by (metis length_wordinverse pa) moreover have "length (wordinverse ?q) ≤ length ?a" by (metis length_wordinverse qa) moreover have "red_rep A (x1 ⊗⇘freegroup A⇙ y1) ≠ []" using x1y1 FreeGroupMain.wordinverse_symm invxyz xyz by fastforce moreover have "red_rep A x1 ≠ []" using N0_def assms(2) x1 by auto ultimately have cont:"((x1 ⊗⇘freegroup A⇙ y1), x1) ∈ lex_L2_word A" using F x1A x1y1in xyz three_point_seven[of "x1" "A" "(x1 ⊗⇘freegroup A⇙ y1)" "?p" "?a" "?q"] by (metis three_point_seven) have subcases:"(x1, y1) ∈ lex_L2_word A ∨ (y1, x1) ∈ lex_L2_word A" by (simp add: invxyz lex_total x1 x1A xneqy y1 y1A) then show ?thesis proof(cases "(x1, y1) ∈ lex_L2_word A") case True then have trans:"((x1 ⊗⇘freegroup A⇙ y1), y1) ∈ lex_L2_word A" using cont trans_lex_L2_word transD by fast then have "y1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont2[of "x1" "y1" "A" "H"] H assms(1) True by (metis mult_SG) moreover then have "inv⇘SG F⇘A⇙ H⇙ y1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont2_inv[of "x1" "y1" "A" "H"] H assms(1) trans True by (metis mult_SG) moreover have "X (SG (F⇘A⇙) H) A ⊆ H" unfolding X_def SG_def by simp ultimately have "y1 ∉ (union_inv (X (SG (freegroup A) H) A) A)" using notin_union_inv[of "H" "A" "y1" "X (SG F⇘A⇙ H) A"] assms(1) by simp then show ?thesis using y1 by blast next case False then have F:"(y1, x1) ∈ lex_L2_word A" using subcases by simp then have "x1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont1[of "y1" "x1" "A" "H"] cont H assms(1) by (metis mult_SG) moreover have "inv⇘SG F⇘A⇙ H⇙ x1 ∉ X (SG (F⇘A⇙) H) A" using lex_cont1_inv[of "y1" "x1" "A" "H"] H assms(1) F cont by (metis mult_SG) moreover have "X (SG (F⇘A⇙) H) A ⊆ H" unfolding X_def SG_def by simp ultimately have "x1 ∉ (union_inv (X (SG (freegroup A) H) A) A)" using notin_union_inv[of "H" "A" "x1" "X (SG F⇘A⇙ H) A"] assms(1) by simp then show ?thesis using x1 by blast qed qed qed qed definition N_reduced ("N") where "N_reduced S A = ((\<forall>x \<in> (red_rep A) ` (union_inv S A). N0 x) \<and> (\<forall>x \<in> (red_rep A) ` (union_inv S A). \<forall>y \<in> (red_rep A) ` (union_inv S A). N1 x y) \<and> (\<forall>x \<in> (red_rep A) ` (union_inv S A). \<forall>y \<in> (red_rep A) ` (union_inv S A). \<forall>z \<in> (red_rep A) ` (union_inv S A). N2 x y z))" lemma N_reduced_X: assumes "H \<le> freegroup A" shows "N_reduced (X (SG (freegroup A) H) A) A" proof- have N0: "((\<forall>x \<in> (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N0 x))" using assms N0 by blast moreover have N1: "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀y ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N1 x y" using assms N1 by blast moreover have "∀x ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀y ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). ∀z ∈ (red_rep A) ` (union_inv (X (SG (freegroup A) H) A) A). N2 x y z" using N0 N1 N2 assms by blast ultimately show ?thesis unfolding N_reduced_def by blast qed definition minimal_set where "minimal_set S A = (SOME X. X \<subseteq> S \<and> X \<inter> (m_inv (freegroup A) ` X) = {} \<and> union_inv S A = union_inv X A)" lemma "\<exists>X. X \<subseteq> S \<and> X \<inter> (m_inv (freegroup A) ` X) = {} \<and> union_inv S A = union_inv X A" sorry lemma "(\<forall>x \<in> (red_rep A) ` (union_inv (X H A) A). N0 x)" sorry lemma "(\<forall>x \<in> (red_rep A) ` (union_inv S A). \<forall>y \<in> (red_rep A) ` (union_inv S A). N1 x y)" sorry definition (in group) free :: "('a, 'b) monoid_scheme \<Rightarrow> bool" where "free H \<equiv> (\<exists>X. H \<cong> (freegroup X))" lemma LS: assumes "subgroup S H" "S \<inter> (m_inv H ` S) = {}" shows "(free (SG H \<langle>S\<rangle>\<^bsub>H\<^esub>)) \<longleftrightarrow> set l \<subseteq> S \<union> (m_inv H ` S) \<Longrightarrow> l \<noteq> [] \<Longrightarrow> (\<forall>n < (length l - 1). (l!n) \<otimes>\<^bsub>H\<^esub> (l!(n+1)) \<noteq> \<one>\<^bsub>H\<^esub>) \<Longrightarrow> m_concat H l \<noteq> \<one>\<^bsub>H\<^esub>" sorry lemma assumes "x \<in> carrier (freegroup S)" shows "inv\<^bsub>(freegroup S)\<^esub> x = x \<Longrightarrow> x = \<one>\<^bsub>(freegroup S)\<^esub>" sorry end
lemma collinear_subset: "\<lbrakk>collinear T; S \<subseteq> T\<rbrakk> \<Longrightarrow> collinear S"
%% Magic command to compile root document % !TEX root = ../../thesis.tex %% Reset glossary to show long gls names \glsresetall \graphicspath{{./Sections/Methodology/Resources/}} In this section we specify all the hyperparameters needed to execute the process explained on chapter \ref{ch:dataset}. This contemplates the raw data processing, the quality control, the \gls{tfds} creation, the image preprocessing, as well as data augmentation. \subsection{Data preprocessing} As we explained in section \ref{sec:dataset:data_pp}, the data preprocessing consist of 4 main steps; 1) the raw data processing, 2) the quality control, 3) the creation of the dataset and 4) the image preprocessing. A complementary explanation of the data preprocessing parameters, as well as implementation references, can be found in the appendices \ref{sec:appendix:raw_data} and \ref{sec:appendix:tfds}. \subsubsection{Raw data processing} As we explained in section \ref{sec:dataset:data_pp:dataset_creation}, to build the \gls{tfds} it is necessary to specify the perturbations that will be included in the dataset. For this reason, all the available wells were processed and transformed into images. This included wells exposed to pharmacological and metabolic perturbations, control wells and unperturbed wells. This allows the user to easily create new datasets without having to run the raw data processing first. Table \ref{table:methodology:dataset:raw_data} shows the processed wells separated by perturbation. \begin{table}[!ht] \centering \begin{tabular}{>{\centering\arraybackslash}m{0.35\linewidth} | >{\centering\arraybackslash}m{0.2\linewidth} | >{\centering\arraybackslash}m{0.3\linewidth}} \hline Perturbation type & Perturbation name & Well names \\ \hline \multirow{5}{*}{pharmacological/metabolic} & CX5461 & I18, J22, J09 \\ \cline{2-3} & AZD4573 & I13, J21, J14, I17, J18 \\ \cline{2-3} & meayamycin & I12, I20 \\ \cline{2-3} & triptolide & I10, J15 \\ \cline{2-3} & TSA & J20, I16, J13 \\ \hline control & DMSO & J16, I14 \\ \hline unperturbed & normal & J10, I09, I11, J18, J12 \\ \hline \end{tabular} \caption{Well names divided by perturbation name and type.} \label{table:methodology:dataset:raw_data} \end{table} Another hyperparameter that needs to be specified during the raw data processing, is the size of the output images $I_s$. This size applies to both, the width and height of the image (square images). Since some prebuilt architectures use a standard image size of 224 by 224, we define $I_s$ as 224. \subsubsection{Quality control} As it is mentioned in section \ref{sec:dataset:data_pp:qc}, the quality control is meant to exclude cells with undesirable features. In our case we discriminate mitotic and border cells. The information used by the quality control is contained in the metadata of each well. Table \ref{table:methodology:dataset:qc} shows the metadata columns and the discriminated values. If a cell has any of these values, then it is excluded. \begin{table}[!ht] \centering \begin{tabular}{>{\centering\arraybackslash}m{0.3\linewidth} | >{\centering\arraybackslash}m{0.3\linewidth} | >{\centering\arraybackslash}m{0.2\linewidth}} \hline Feature & Metadata column name & Discriminated value \\ \hline \multirow{3}{*}{Cell in mitosis phace} & \texttt{is\_polynuclei\_HeLa} & 1 \\ \cline{2-3} & \texttt{is\_polynuclei\_184A1} & 1 \\ \cline{2-3} & \texttt{cell\_cycle} & \texttt{NaN} \\ \hline Border cell & \texttt{is\_border\_cell} & 1 \\ \hline \end{tabular} \caption{Discrimination characteristics for quality control.} \label{table:methodology:dataset:qc} \end{table} \subsubsection{Dataset creation and image preprocessing} As it is explained in section \ref{sec:dataset:data_pp:dataset_creation}, in this work we decided to use a custom \gls{tfds}. Table \ref{table:methodology:dataset:tfds} shows the parameters used to build the dataset employed in this work, together with the image preprocessing parameters. % set table lengths \setlength{\mylinewidth}{\linewidth-7pt}% \setlength{\mylengtha}{0.25\mylinewidth-2\arraycolsep}% \setlength{\mylengthb}{0.65\mylinewidth-2\arraycolsep}% \begin{longtable}{>{\centering\arraybackslash}m{\mylengtha} | >{\centering\arraybackslash}m{\mylengthb}} \hline Parameter & Description \\ \hline Perturbations to be included in the dataset & \hl{normal} and \hl{DMSO} \\ \hline Cell phases to be included in the dataset & $G_1$, $S$, $G_2$ \\ \hline Training set split fraction & 0.8 \\ \hline Validation set split fraction & 0.1 \\ \hline Seed & 123 (for reproducibility of the train, val and test split) \\ \hline Percentile & 98 (for clipping / linear scaling / standardization) \\ \hline Clipping flag & 1 \\ \hline Mean extraction flag & 0 \\ \hline Linear scaling flag & 0 \\ \hline Standardization (z-score) flag & 1 \\ \hline Model input channels & All of them except for channel \texttt{00\_EU} (see table \ref{table:tfds_in:channels}) \\ \hline Channel used to compute target variable (output channel) & \texttt{00\_EU} (channel id 35, see table \ref{table:tfds_in:channels}) \\ \hline \caption{Parameters used to biuld \gls{tfds} and image preprocessing.} \label{table:methodology:dataset:tfds} \end{longtable} The custom \gls{tfds} created with the parameters specified in table \ref{table:methodology:dataset:tfds} is called \\ \texttt{mpp\_ds\_normal\_dmso\_z\_score}. \newpage The Python script that builds the custom \gls{tfds}, also returns a file with the image preprocessing parameters (\texttt{channels\_df.cvs}) (as this is applied at a per-channel level) and information about the channels (channel name, id, etc.). It also returns another file with the metadata of each cell included in the \gls{tfds} (\texttt{metadata\_df.csv}). These files are stored in the same directory as the \gls{tfds} files. In table \ref{table:methodology:dataset:tfds} we also specify the channel used to compute the target variable (ground truth), which is the channel corresponding to the marker \hl{EU} (channel id 35, see tables \ref{table:tfds_in:channels} and \ref{table:apendix:if_markers}). Recall that this channel contains nuclear readouts of nascent RNA (\gls{pmrna}) in a given period of time. For the data provided, this time period was the same for all the cells (30 minutes) and is specified in the \hl{duration} columns of the metadata. Since channel 35 is used to compute the target variable (ground truth), it is removed from the prediction/input channels. \subsection{Data augmentation} \label{sec:methodology:data:augm} In this section we specify the data augmentation techniques (see section \ref{sec:dataset:data_augmentation}) and its hyperparameters used to train all the models of this work. Recall that the techniques are either aimed to remove non-relevant characteristics of the data (color shifting, central zoom in/out) or to improve model generalization (horizontal flipping, 90 degree rotations). Table \ref{table:methodology:dataset:augm} shows this techniques and its hyperparameters grouped by objective and technique. In practice, the augmentation techniques are applied as shown in table \ref{table:methodology:dataset:augm} from top to bottom. % set table lengths \setlength{\mylinewidth}{\linewidth-7pt}% \setlength{\mylengtha}{0.2\mylinewidth-2\arraycolsep}% \setlength{\mylengthb}{0.2\mylinewidth-2\arraycolsep}% \setlength{\mylengthc}{0.25\mylinewidth-2\arraycolsep}% \setlength{\mylengthd}{0.22\mylinewidth-2\arraycolsep}% \begin{longtable}{>{\centering\arraybackslash}m{\mylengtha} | >{\centering\arraybackslash}m{\mylengthb} | >{\centering\arraybackslash}m{\mylengthc} | >{\centering\arraybackslash}m{\mylengthd}} \hline Objective & Technique & Hyperparameter & Description \\ \hline \multirow{2}{\mylengtha}{\centering Remove non-relevant features} & random color shifting & distribution & $U(-3,3)$ \\ \cline{2-4} & random central zoom in/out & distribution\footnotemark & $N(\mu=0.6, \sigma=0.1)$ \\ \hline \multirow{2}{\mylengtha}{\centering Improve generalization} & random horizontal flipping & NA & NA \\ \cline{2-4} & random 90 degrees rotations & NA & NA \\ \hline \caption{Parameters used for data augmentation techniques. The NA means that there are no hyperparameters for this technique or that there is no further description.} \label{table:methodology:dataset:augm} \end{longtable} \footnotetext{This distribution is used to sample the \hl{cell nucleus size ratio} $S_{ratio}$ (see section \ref{sec:dataset:data_aug:zoom}) of each cell. However, the parameters for this distribution (mean and standard deviation) were not provided by us. Instead, they were estimated using the information in column \texttt{cell\_size\_ratio} of the \gls{tfds} metadata file. Therefore, the \texttt{return\_cell\_size\_ratio} flag must be set to 1 (True) during raw data processing, so this column is created (see section \ref{sec:dataset:data_pp:raw_data_p} and appendix \ref{sec:appendix:raw_data}).} Even thought we specify the data augmentation hyperparameters here, in practice these are selected for each model and applied during training. However, all the models showed in this work were trained using the techniques and values shown in table \ref{table:methodology:dataset:augm}. A complementary explanation can be found in appendix \ref{sec:appendix:Model_training_IN}. In section \ref{sec:dataset:data_augmentation} we mentioned that data augmentation techniques can be applied to both the training set and the validation set. However, we also mentioned that only horizontal flips and 90 degree rotations are applied for the validation set. Furthermore, for the training set these techniques are applied randomly, while for the validation set they are applied deterministically. Therefore, table \ref{table:methodology:dataset:augm} only applies to the training set.
from math import pi import pandas as pd import numpy as np import os, json from sklearn.decomposition import PCA import plotly.express as px from bokeh.models import Legend, LegendItem, HoverTool, TapTool from bokeh.resources import CDN from bokeh.transform import factor_cmap, factor_mark from bokeh.embed import json_item, file_html from bokeh.plotting import figure from bokeh.palettes import Category10_3 from bokeh.io import show from bokeh.palettes import magma from bokeh.models import CustomJS, ColumnDataSource from bokeh.embed import components from flask import Flask, render_template from bokeh.events import Tap from pyproj import Transformer import umap def pixel_to_latlng(x, y): transformer = Transformer.from_crs("EPSG:3857", "EPSG:4326", always_xy=True) pxToMeter = 10 # Constanpixel_to_latlngt,defined when preprocessing the TIF image x_coord = x # Variable, your coordinates in pixel units y_coord = y # Variable, your coordinates in pixel units lon, lat = transformer.transform(x_coord * pxToMeter, y_coord * pxToMeter) return ("{},{}").format(lat, lon) def process_data_for_umap(): spatial_count = pd.read_csv("libraries/data/ROI_spatial_features_pretrained.csv") gene_count = pd.read_csv( "libraries/data/Kidney_Raw_TargetCountMatrix.txt", delimiter="\t" ) roi_meta = pd.read_csv("libraries/data/Kidney_Sample_Annotations.csv") gene_count = gene_count.set_index("TargetName").T.reset_index() gene_count["ROI"] = ( gene_count["index"].str.split("|").apply(lambda p: "-".join(p[:-1])).str.strip() + ".png" ) # Aggregate gene count for biomarkers in same roi gene_count = gene_count.groupby("ROI").sum().reset_index() # Normalization as each ROI had the same total amount of genes count gene_count = ( gene_count.set_index("ROI") .apply(lambda p: p * 10000 / p.sum(), axis=1) .reset_index() ) # Roi_metadata roi_meta["ROI"] = ( roi_meta["SegmentDisplayName"] .str.split("|") .apply(lambda p: "-".join(p[:-1])) .str.strip() + ".png" ) # roi_meta = roi_meta.groupby("ROI").disease_status.first() roi_meta = roi_meta.groupby("ROI").agg( { "disease_status": "first", "region": "first", "RoiReportX": "first", "RoiReportY": "first", } ) roi_meta["coordinates"] = roi_meta.apply( lambda row: pixel_to_latlng(row["RoiReportX"], row["RoiReportY"]), axis=1 ) roi_meta = roi_meta.drop(["RoiReportX", "RoiReportY"], axis=1) all_features = pd.merge( gene_count.set_index("ROI").T.sample(10000).T, spatial_count.set_index("ROI").T.sample(2000).T, left_index=True, right_index=True, ) all_features /= all_features.to_numpy().max() pca_reducer = PCA(n_components=50) umap_reducer = umap.UMAP() low_dim = pca_reducer.fit_transform(all_features) low_dim = umap_reducer.fit_transform(low_dim) low_df = pd.DataFrame(data=low_dim, columns=["x", "y"]) low_df = low_df.set_index(all_features.index) df = low_df.merge(roi_meta, left_index=True, right_index=True) df.to_csv(r"libraries/data/tmp/umap.csv", index=True, header=True) return df def umap_plot(): if os.path.exists(r"libraries/data/tmp/umap.csv"): df = pd.read_csv(r"libraries/data/tmp/umap.csv") print("Reading file") else: df = process_data_for_umap() colors = list(Category10_3)[:-1] disease_status = ["DKD", "normal"] markers = ["x", "circle"] region = ["glomerulus", "tubule"] source = ColumnDataSource(df) on_change = CustomJS( args=dict(source=source), code=""" var inds = source.selected.indices; var all_images = ['disease1B', 'disease2B', 'disease3', 'disease4', 'normal2B', 'normal3', 'normal4']; var selected_values = []; for (var i = 0; i < inds.length; i++) { var coordinates = source.data['coordinates'][i].split(","); var roi = source.data['ROI'][i].split("_"); var str = `${roi[0]},${coordinates[0]},${coordinates[1]}`; selected_values.push(str); } var response = {'images':all_images,'selected_values':selected_values}; window.top.postMessage(response,'*'); """, ) tooltips = [ ("index", "$index"), ("(x,y)", "($x, $y)"), ("disease_status", "@disease_status"), ("region", "@region"), ("(lng,lat)", "@coordinates"), ] p = figure( plot_width=700, plot_height=600, tools="hover, tap, pan, box_select, box_zoom, reset", title="DKD vs Normal", tooltips=tooltips, toolbar_location="above", ) r = p.scatter( "x", "y", source=source, fill_alpha=0.4, size=12, marker=factor_mark("region", markers, region), color=factor_cmap("disease_status", colors, disease_status), ) p.xaxis.axis_label = "x" p.yaxis.axis_label = "y" # we are going to add "dummy" renderers for the legends, restrict auto-ranging # to only the "real" renderer above p.x_range.renderers = [r] p.y_range.renderers = [r] # create an invisible renderer to drive color legend rc = p.rect(x=0, y=0, height=1, width=1, color=colors) rc.visible = False # add a color legend with explicit index, set labels to fit your need legend = Legend( items=[ LegendItem(label=disease_status[i], renderers=[rc], index=i) for i, c in enumerate(colors) ], location="top_right", ) p.add_layout(legend) # create an invisible renderer to drive shape legend rs = p.scatter(x=0, y=0, color="grey", marker=markers) rs.visible = False # add a shape legend with explicit index, set labels to fit your needs legend = Legend( items=[ LegendItem(label=region[i], renderers=[rs], index=i) for i, s in enumerate(markers) ], location="top_left", ) p.add_layout(legend) source.selected.js_on_change("indices", on_change) script, div = components(p) return render_template( "plot.html", title="DKD vs Normal(Umap)", script=script, div=div )
corollary\<^marker>\<open>tag unimportant\<close> independent_card_le: fixes S :: "'a::euclidean_space set" assumes "independent S" shows "card S \<le> DIM('a)"
-- ----------------------------- -- Demostrar que -- s \ (t ∪ u) ⊆ (s \ t) \ u -- ----------------------------- import data.set.basic open set variable {α : Type} variables s t u : set α example : s \ (t ∪ u) ⊆ (s \ t) \ u := sorry
library(ggplot2) library(gridExtra) library(reshape2) library(RColorBrewer) source(paste(getwd(), "../../", "sir-functions/StocSSIR.r", sep="/")) greypal <- rev( brewer.pal(9, "Greys")[-1] ) T <- 100 N <- 500 i_infec <- 5 nloc <- 8 steps <- 7 sigma <- 10 pars <- c( R0 = 3.0, # new infected people per infected person r = 0.1, # recovery rate N = 500, # population size eta = 0.5, # geometric random walk berr = 0.5, # Beta geometric walk noise phi = 0.1) # degree of interconnectivity initcond <- matrix(NA, nloc, 3) colnames(initcond) <- c("S","I","R") ## default (everyone susceptible) initcond[,"S"] <- N initcond[,"I"] <- 0 initcond[,"R"] <- 0 ## one region infected initcond[2,] <- c(N - i_infec, i_infec, 0); ## set up number of neighbors vector and neighbor index matrix ## ring topology: neinum <- rep(2,nloc) neibmat <- matrix(NA, nloc, 3) neibmat[,1] <- c( ((0:(nloc-1)-1)%%nloc)+1 ) neibmat[,2] <- c( ((0:(nloc-1)+1)%%nloc)+1 ) ssdeout <- StocSSIR(initcond, pars, T, steps, neinum, neibmat) df <- data.frame(time = 0:T, loc = t(ssdeout[,'I',])) plotdata <- melt(df, id = "time") ## full q <- qplot(data = plotdata, x = time, y = value, geom = "line", color = variable, xlab = "Time", ylab = "Infection Count") + scale_colour_manual(values = greypal, labels = paste(1:8), name = "Location") + theme_bw() ggsave(q, filename="dataplot.pdf", height=4, width=6.5) infec_counts_raw <- t(ssdeout[,'I',]) + matrix( rnorm( rep(NA, (T+1)*nloc) , 0, sigma), T+1, nloc) infec_counts <- ifelse(infec_counts_raw < 0, 0, infec_counts_raw) df2 <- data.frame(time = 0:T, loc = infec_counts) plotdata2 <- melt(df2, id = "time") qd <- qplot(data = plotdata2, x = time, y = value, geom = "line", color = variable, xlab = "Time", ylab = "Infection Count") + scale_colour_manual(values = greypal, labels = paste(1:8), name = "Location") + theme_bw() ggsave(qd, filename="dataplot2.pdf", height=4, width=6.5) ## 1 v. 6, no bridge q2 <- qplot(0:T, ssdeout[1,'I',], geom = "line") + geom_line(aes(y = ssdeout[6,'I',])) + theme_bw() print(q2) ## 1 v. 6 bridge ## add some extra connections neinum[1] <- neinum[1] + 1 neibmat[1,3] <- 6 ssdeout <- StocSSIR(initcond, pars, T, steps, neinum, neibmat) q3 <- qplot(0:T, ssdeout[1,'I',], geom = "line") + geom_line(aes(y = ssdeout[6,'I',])) + theme_bw() print(q3)
SUBROUTINE SECBD1(SY1,SY2,SY3,CIY) C IMPLICIT REAL*8(A-H,O-Z) C COMMON/CSECBD/SECM,SECI(3,3),ZBAR2(3),YI02(3),ZZ2(3,3),ZZ2Y(3,3) 1 ,YZ2(3),YZT(3),ZB(3),YIZ02(3) C COMMON/DEBUG2/IOUT,JOUT,KLUGE C COMMON/ISECBD/I2BDY,NDOF2,IRAST,NDEP2,IARST(3),IRSCY(3) C COMMON/RPOOL1/DUMV1(80),YBCM(3),DUMV2(42) C COMMON/SBDOUT/ANG2(3),ANG2D(3),ANG2DD(3),B(3,3),B0B(3,3) 1 ,OM2(3),SALP,CALP,SBET,CBET,H2B(3),Y2D(3) C COMMON/SECBDW/GAMMA2(3,6),DELTA2(3,3),DELT2(3,3),DELT2I(3,3) 1 ,COMQ(3,3),QGAM(3,6),DIQGM(3,6),DALP(6,6) 2 ,VP(3),VPS(6) C COMMON/SECICS/GAM20,ALP20,BET20,B0(3,3) C COMMON/VARBLS/DEP(150),DER(150) C C EQUIVALENCE (ANG2(1),GAM2),(ANG2(2),ALP2),(ANG2(3),BET2) EQUIVALENCE (ANG2D(1),GAM2D),(ANG2D(2),ALP2D),(ANG2D(3),BET2D) C C DIMENSION CIY(3,3) DIMENSION DUM1(3,3),YYZ2(3,3) DIMENSION DUM2(3,3),DUM3(3,3),II(3),JJ(3) DIMENSION C(6),MT(6) DIMENSION PV(3) DIMENSION V1(3),V2(3) C DATA II/2,3,1/,JJ/3,1,2/ DATA MAXD/3/ C C C SECBD1 IS CALLED FROM FNDALP TO INCLUDE SECONDARY BODY C C-G OFFSET AND INERTIA PROPERTIES IN SYSTEM PROPERTIES C IF(I2BDY.EQ.0) RETURN C DO 5 I=1,3 ANG2(I)=0.0D0 ANG2D(I)=0.0D0 ANG2DD(I)=0.0D0 ZB(I)=SECM*ZBAR2(I) 5 CONTINUE C IF(IRAST.EQ.0) GO TO 10 C CALL RAST2(ANG2,ANG2D,ANG2DD) C GO TO 15 C 10 CONTINUE C C EXTRACT SECONDARY STATE VARIABLES FROM DEP C IF(NDOF2.EQ.0) GO TO 15 C I1=NDEP2 I2=I1+NDOF2 BET2=DEP(I1) BET2D=DEP(I2) C IF(NDOF2.EQ.1) GO TO 15 C I1=I1+1 I2=I2+1 GAM2=DEP(I1) GAM2D=DEP(I2) C IF(NDOF2.EQ.2) GO TO 15 C I1=I1+1 I2=I2+1 ALP2=DEP(I1) ALP2D=DEP(I2) C 15 CONTINUE C CALL DTR312(GAM2,ALP2,BET2,B) C CALL MPYMAT(B0,B,DUM1,1,1,B0B,DUM1) C C CONSTRUCT ANGULAR RATES C SBET=DSIN(BET2) CBET=DCOS(BET2) SALP=DSIN(ALP2) CALP=DCOS(ALP2) WS=GAM2D*CALP OM2(1)=-WS*SBET+ALP2D*CBET OM2(2)=BET2D+GAM2D*SALP OM2(3)=WS*CBET+ALP2D*SBET C V1(1)=OM2(2)*ZBAR2(3)-OM2(3)*ZBAR2(2) V1(2)=OM2(3)*ZBAR2(1)-OM2(1)*ZBAR2(3) V1(3)=OM2(1)*ZBAR2(2)-OM2(2)*ZBAR2(1) C CALL MATV(1,B0B,V1,V2) C IF(IOUT.EQ.1) GO TO 16 WRITE(6,5999) 5999 FORMAT('0',10X,'DEBUGGING OUTPUT FROM SECBD1'/) WRITE(6,6000) GAM2,ALP2,BET2,GAM2D,ALP2D,BET2D,OM2 6000 FORMAT(' ',1P10E13.5) 16 CONTINUE C C TRANSFORM INERTIA PROPERTIES TO BODY FRAME C CALL MPYMAT(B0B,ZZ2,B0B,2,2,DUM1,ZZ2Y) C C CALCULATE C-G OFFSET OF SECONDARY BODY C CALL MATV(1,B0B,ZBAR2,YZ2) C CALL ADDV(YI02,YZ2,YZT) C SY1=SECM*YZT(1) SY2=SECM*YZT(2) SY3=SECM*YZT(3) C DO 20 I=1,3 YBCM(I)=YBCM(I)+SECM*YZT(I) Y2D(I)=SECM*V2(I) DO 20 J=1,3 YYZ2(I,J)=SECM*(YI02(I)*YI02(J)+YI02(I)*YZ2(J)+YI02(J)*YZ2(I)) 1 +ZZ2Y(I,J) CIY(I,J)=CIY(I,J)+YYZ2(I,J) 20 CONTINUE C IF(IOUT.EQ.1) GO TO 21 WRITE(6,6000) SY1,SY2,SY3,YBCM WRITE(6,6000) CIY 21 CONTINUE C C C COUPLING WITH SYSTEM TRANSLATION EQUATIONS C DO 25 I=1,3 I1=II(I) J1=JJ(I) DO 25 J=1,3 GAMMA2(I,J)=ZB(I1)*B0B(J,J1)-ZB(J1)*B0B(J,I1) 25 CONTINUE C C COUPLING WITH SYSTEM ROTATION EQUATION C CALL MATV(2,B0B,YI02,YIZ02) C TRAO2=0.0D0 C DO 30 I=1,3 TRAO2=TRAO2+YIZ02(I)*ZB(I)+ZZ2(I,I) DO 30 J=1,3 DUM2(I,J)=-YIZ02(I)*ZB(J)-ZZ2(I,J) 30 CONTINUE C DO 35 I=1,3 DUM2(I,I)=DUM2(I,I)+TRAO2 35 CONTINUE C DO 37 I=1,3 DO 37 J=1,3 WS=0.0D0 DO 36 K=1,3 WS=WS+DUM2(I,K)*B0B(J,K) 36 CONTINUE DUM3(I,J)=WS 37 CONTINUE C C LOAD INTO GAMMA2 C DO 40 I=1,3 H2B(I)=0.0D0 DO 40 J=1,3 J1=J+3 GAMMA2(I,J1)=DUM3(I,J) H2B(I)=H2B(I)+DUM3(J,I)*OM2(J) 40 CONTINUE C IF(NDOF2.EQ.0) GO TO 100 C C DO 42 I=1,3 DO 42 J=1,3 COMQ(I,J)=0.0D0 42 CONTINUE C COMQ(1,2)=1.0D0 COMQ(2,1)=-CALP*SBET COMQ(2,2)=SALP COMQ(2,3)=CALP*CBET COMQ(3,1)=CBET COMQ(3,3)=SBET C DO 45 I=1,3 DO 45 J=1,6 WS=0.0D0 DO 44 K=1,3 WS=WS+COMQ(I,K)*GAMMA2(K,J) 44 CONTINUE QGAM(I,J)=WS DIQGM(I,J)=0.0D0 45 CONTINUE C DO 47 I=1,3 DO 47 J=1,3 WS=0.0D0 DO 46 K=1,3 WS=WS+COMQ(I,K)*DELTA2(K,J) 46 CONTINUE DUM1(I,J)=WS 47 CONTINUE C DO 50 I=1,3 DO 50 J=1,3 WS=0.0D0 DO 49 K=1,3 WS=WS+DUM1(I,K)*COMQ(J,K) 49 CONTINUE DELT2(I,J)=WS DELT2I(I,J)=WS 50 CONTINUE C CALL INVERT(DELT2I,NDOF2,MAXD,ID,C,MT) C DO 55 I=1,NDOF2 DO 55 J=1,6 WS=0.0D0 DO 54 K=1,NDOF2 WS=WS+DELT2I(I,K)*QGAM(K,J) 54 CONTINUE DIQGM(I,J)=WS 55 CONTINUE C WS1=GAM2D*ALP2D WS2=GAM2D*BET2D*CALP WS3=ALP2D*BET2D C PV(2)=WS1*CALP WS1=WS1*SALP PV(1)=WS1*SBET-WS2*CBET-WS3*SBET PV(3)=-WS1*CBET-WS2*SBET+WS3*CBET C DO 60 I=1,3 I3=I+3 WS1=0.0D0 WS2=0.0D0 WS3=0.0D0 DO 59 J=1,3 WS1=WS1+DUM1(I,J)*PV(J) WS2=WS2+GAMMA2(J,I)*PV(J) WS3=WS3+GAMMA2(J,I3)*PV(J) 59 CONTINUE VP(I)=WS1 VPS(I)=WS2 VPS(I3)=WS3 60 CONTINUE C DO 65 I=1,6 DO 65 J=1,6 WS=0.0D0 DO 64 K=1,NDOF2 WS=WS+QGAM(K,I)*DIQGM(K,J) 64 CONTINUE DALP(I,J)=WS 65 CONTINUE C IF(IOUT.EQ.1) GO TO 70 WRITE(6,6001) ((GAMMA2(I,J),J=1,6),I=1,3) 6001 FORMAT(' ',1P6E14.6) WRITE(6,6000) DELTA2 WRITE(6,6000) DELT2 WRITE(6,6000) DELT2I WRITE(6,6000) COMQ WRITE(6,6001) (( QGAM(I,J),J=1,6),I=1,3) WRITE(6,6001) ((DIQGM(I,J),J=1,6),I=1,3) WRITE(6,6001) (( DALP(I,J),J=1,6),I=1,6) 70 CONTINUE C C 100 CONTINUE C C RETURN C END
%% Import data from text file. % Script for importing data from the following text file: % % C:\ArizCU12.5m.dat % % To extend the code to different selected data or a different text file, % generate a function instead of a script. % Auto-generated by MATLAB on 2013/01/03 09:36:00 % David Willingham February 2013 % Copyright 2013 The MathWorks, Inc %% Initialize variables. filename = 'ArizCU12.5m.dat'; delimiter = '\t'; startRow = 7; %% Format string for each line of text: % column1: double (%f) % column2: double (%f) % column3: double (%f) % column4: double (%f) % For more information, see the TEXTSCAN documentation. formatSpec = '%f%f%f%f%[^\n\r]'; %% Open the text file. fileID = fopen(filename,'r'); %% Read columns of data according to format string. % This call is based on the structure of the file used to generate this % code. If an error occurs for a different file, try regenerating the code % from the Import Tool. dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false); %% Close the text file. fclose(fileID); %% Post processing for unimportable data. % No unimportable data rules were applied during the import, so no post % processing code is included. To generate code which works for % unimportable data, select unimportable cells in a file and regenerate the % script. %% Allocate imported array to column variable names x = dataArray{:, 1}; y = dataArray{:, 2}; z = dataArray{:, 3}; c = dataArray{:, 4}; %% Clear temporary variables clearvars filename delimiter startRow formatSpec fileID dataArray ans;
import numpy as np import matplotlib.pyplot as mat def remove_zero(recall,prec,thresh): last_ind=len(recall) non_zero=last_ind for i in range(last_ind-1,0,-1): if recall[i]!=0 and prec[i]!=0: non_zero=i break recall=recall[:non_zero+1] prec=prec[:non_zero+1] thresh=thresh[:non_zero+1] #del recall[non_zero+1:last_ind] return recall,prec,thresh recall,prec,thresh=np.loadtxt("./single/roc_0.csv",delimiter=',') recall,prec,thresh=remove_zero(recall,prec,thresh) recall2,prec2,thresh2=np.loadtxt("./dense/roc_0.csv",delimiter=',') recall2,prec2,thresh2=remove_zero(recall2,prec2,thresh2) recall3,prec3,thresh3=np.loadtxt("./fused_90/roc_0.csv",delimiter=',') recall3,prec3,thresh3=remove_zero(recall3,prec3,thresh3) recall4,prec4,thresh4=np.loadtxt("./fused_facing/roc_0.csv",delimiter=',') recall4,prec4,thresh4=remove_zero(recall4,prec4,thresh4) recall5,prec5,thresh5=np.loadtxt("./fused_full/roc_0.csv",delimiter=',') recall5,prec5,thresh5=remove_zero(recall5,prec5,thresh5) #recall4,prec4,thresh4=np.loadtxt("./all0.5/roc_0.csv",delimiter=',') #recall4,prec4,thresh4=remove_zero(recall4,prec4,thresh4) mat.plot(recall,prec) mat.plot(recall2,prec2) mat.plot(recall3,prec3) mat.plot(recall4,prec4) mat.plot(recall5,prec5) #mat.plot(recall4,prec4) mat.title("Precision-Recall Curves, Crossroads") mat.xlabel("Recall") mat.ylabel("Precision") mat.legend(["single (1)","dense single (1)","perp (1,2)","opposite (1,3)","4 fused (1,2,3,4)"]) mat.show()
State Before: α : Type u_1 β : Type u_2 γ : Type ?u.156251 f g : α → β c c₁ c₂ x : α inst✝¹ : AddGroup α inst✝ : InvolutiveNeg β h : Antiperiodic f c ⊢ Antiperiodic f (-c) State After: no goals Tactic: simpa only [sub_eq_add_neg, Antiperiodic] using h.sub_eq
# Vector Spaces * What is a vector? * Vectors are not lists of numbers (necessarily) * Children have an intuitive idea of what vectors are * A first definition of a vector * Vectors are a quantity with direction and length * Examples: 5 meters (length) to your left (direction). 20 miles (length) north (direction) ```python %matplotlib inline from matplotlib import pyplot as plt import matplotlib as mpl import numpy as np from ipywidgets import interact from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import ConnectionPatch def create_func_vis(num_funcs=1): fig, axs = plt.subplots(1, num_funcs+1) for ax in axs: ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_xticks([]) ax.set_yticks([]) ax.set_aspect('equal', adjustable='box') for i in range(num_funcs): con = ConnectionPatch(xyA=(0,0), xyB=(0,0), coordsA="data", coordsB="data", axesA=axs[i], axesB=axs[i+1], arrowstyle="->", alpha=0.5) axs[i+1].add_artist(con) return fig, axs def plot_vec(x, y, u, v, ax=plt, **kwargs): return ax.quiver(x, y, u, v, angles='xy', units="xy", scale=1, scale_units="xy", **kwargs) def plot_vec3(x, y, z, u, v, w, **kwargs): return plt.quiver(x, y, z, u, v, w, **kwargs) def plot_vec_at_origin(vecs: np.ndarray, color='black', ax=plt): if len(vecs.shape) == 1: vecs = vecs.reshape(1, 2) o = np.zeros(vecs.shape[0]) return ax.quiver(o, o, vecs[:, 0], vecs[:, 1], color=color, angles='xy', units="xy", scale=1, scale_units="xy") def plot_vec3_at_origin(ax, vecs: np.ndarray, color='black'): if len(vecs.shape) == 1: vecs = vecs.reshape(1, 3) o = np.zeros(vecs.shape[0]) return ax.quiver(o, o, o, vecs[:, 0], vecs[:, 1], vecs[:, 2], color=color) def rotation(theta): c, s = np.cos(np.radians(theta)), np.sin(np.radians(theta)) return np.array(((c, -s), (s, c))) def get_vec(angle, length): return rotation(angle)@np.array((length,0)) @interact(angle=(0, 360, 10)) def demonstrate_no_coord_grid(angle): plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') rot = rotation(angle) vecs = np.array((rot @ np.array([1, 1]), rot @ np.array([0, -1]))) plot_vec_at_origin(vecs) plt.plot(0, 0, 'o', color="black") ``` interactive(children=(IntSlider(value=180, description='angle', max=360, step=10), Output()), _dom_classes=('w… * Coordinate grids are extra structure that we will add in shortly. They are not necessarily part of vectors * Because vectors have a length, they can be scaled up or down by an arbitrary real number * Negative scaling corresponds to opposite direction ```python @interact(len=(-2, 2, 0.1)) def demonstrate_scaling(len): plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vecs = len * np.array([1, 1]) plot_vec_at_origin(vecs) plt.plot(0, 0, 'o', color="black") ``` interactive(children=(FloatSlider(value=0.0, description='len', max=2.0, min=-2.0), Output()), _dom_classes=('… * Vectors can also be added together. * Adding a vector $a$ to a vector $b$ produces a new vector $a+b$ by putting the tail of the second vector at the tip of the first vector * This can be done in either order, producing a sort of parallelogram * This is called the commutative law * Example: ```python print("Control the angle and size of the red arrow") @interact(angle=(0, 360, 10), length=(0.1, 2, 0.1)) def demonstrate_vector_addition(angle, length): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') rot = rotation(angle) vecs = np.array((get_vec(angle, length), [1, 1])) plot_vec_at_origin(vecs, color=['red', "blue"]) plot_vec_at_origin(vecs[0]+vecs[1]) plot_vec(vecs[:, 0], vecs[:, 1], vecs[::-1, 0], vecs[::-1, 1], color=["blue", 'red']) plt.plot(0, 0, 'o', color="black") ``` Control the angle and size of the red arrow interactive(children=(IntSlider(value=180, description='angle', max=360, step=10), FloatSlider(value=1.0, desc… * There are other operations on vectors I won't be covering in detail today * Dot product, cross product, tensor product, outer product, clifford product, determinant, etc... * I claim that anything which has an addition and a scaling operation can be thought of as a vector * In other words, given a real number, like $\pi=3.1415\dots$, you must be able to form the vector $\pi v$ * And you must be able to add $u$ to $v$ to get $u+v$ * Anything with these two operations we will call a **vector space** * Some examples: * The set of arrows in the 2d plane, without any coordinate grid forms a vector space as we saw above * The set of lists of 3 numbers, called $\mathbb{R}^3$ is a vector space $$\begin{bmatrix}1 \\2 \\3\end{bmatrix} +\begin{bmatrix}4 \\5 \\6\end{bmatrix} =\begin{bmatrix}5 \\7 \\9\end{bmatrix}$$ * More generally, the set of lists of $n$ numbers is called $\mathbb{R}^n$ * The set of polynomials in a single variable is a vector space $(x^2+2x+3)+(4x^2+5x+6)=5x^2+7x+9$ # Linear Independence, Span, and Bases * Now that we have a working definition of a vector (an element of some vector space), we can begin to introduce coordinate grids to things in the form of a basis * In order to define a basis we need to define some other terms first * Linear combinations * A linear combination of a set of vectors is a sum of the vectors, each with a scale factor applied. * A linear combination of the vectors $u$ and $v$ is written as $au+by$. * An example of a linear combination of vectors in $\mathbb{R}^3$: $$3\begin{bmatrix}1 \\0 \\0\end{bmatrix} +2\begin{bmatrix}0 \\1 \\0\end{bmatrix} +5\begin{bmatrix}0\\0\\1\end{bmatrix}=\begin{bmatrix}3 \\2 \\5\end{bmatrix}$$ * Linear independence * A set of vectors is **linearly independent** if it contains no redundant vectors * In other words, no vector in the set can be written as a linear combination of the others * Examples: ```python def demonstrate_linear_independence_1(): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vecs = np.array(((1,0), (0, 1))) plot_vec_at_origin(vecs) return plt.gcf() demonstrate_linear_independence_1() def demonstrate_linear_independence_2(): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vecs = np.array(((1,1), (0, 1))) plot_vec_at_origin(vecs) return plt.gcf() demonstrate_linear_independence_2() def demonstrate_linear_independence_3(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) plot_vec3_at_origin(ax, np.array(((0, 1, 0), (1,0,0), (0, 0, 1)))) return fig demonstrate_linear_independence_3(); def demonstrate_linear_independence_4(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) plot_vec3_at_origin(ax, np.array(((0, 1, 1), (1,0,0), (0, 0, 1)))) return fig demonstrate_linear_independence_4(); ``` * A set of vectors is linearly dependent if it contains extra, redundant vectors * In other words, some vector can be written as a linear combination of the other vectors * Examples: ```python def demonstrate_linear_dependence_1(): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vecs = np.array(((2,0), (1,0))) plot_vec_at_origin(vecs, color=["red", "blue"]) return plt.gcf() demonstrate_linear_dependence_1(); def demonstrate_linear_dependence_2(): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vecs = np.array((get_vec(0, 1), [1, 1])) plot_vec_at_origin(vecs) plot_vec_at_origin(vecs[0]+vecs[1]) plt.plot(0, 0, 'o', color="black") demonstrate_linear_dependence_2(); def demonstrate_linear_dependence_3(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) plot_vec3_at_origin(ax, np.array(((1, 1, 0), (1,0,0), (0, 1, 0)))) return fig demonstrate_linear_dependence_3(); ``` * Span * The next notion we need to define is that of a span of a set of vectors * Every vector in the plane can be written as a linear combination of the following two vectors: ```python demonstrate_linear_independence_1(); ``` * Next we demonstrate why this happens. * Note how you can stretch the blue and red vectors to reach any vector on the plane: ```python @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_span(l1, l2): plt.figure() plt.xlim(-2, 2) plt.ylim(-2, 2) plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') vec1 = l1 * np.array((1,0)) vec2 = l2 * np.array((1,1)) plot_vec_at_origin(vec1, color='red') plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue") plt.plot(0, 0, 'o', color="black") ``` interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… * Given a set of vectors, the set of all linear combinations of those vectors is called the **span** of that set * Example: * The span of the two vectors visualized on the next slide is the entire green plane ```python @interact(angle=(0, 80, 10)) def demonstrate_span(angle): vec1 = np.array((1, 0, 0)) vec2 = np.array((0, np.cos(np.radians(angle)), np.sin(np.radians(angle)))) normal = np.cross(vec1, vec2) x, y = np.meshgrid(np.arange(-2, 2, 0.1), np.arange(-2, 2, 0.1)) z = (-normal[0] * x - normal[1] * y) * 1. /normal[2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim([-2, 2]) ax.set_ylim([-2, 2]) ax.set_zlim([-2, 2]) # display(np.stack(vec1, vec2)) plot_vec3_at_origin(ax, np.stack((vec1, vec2))) art = ax.plot_surface(x, y, z, color = 'g') art.set_alpha(0.5) return fig ``` interactive(children=(IntSlider(value=40, description='angle', max=80, step=10), Output()), _dom_classes=('wid… * Basis * If a set of vectors is linearly independent, then it is said to be the basis for its span * We say that a basis is a linearly independent spanning set * Examples: * The two vectors above are a basis for the green plane * Any of the examples of linearly independent sets are also basis for the plane/space * Rephrasing the definition: * A set of vectors is a basis for a vector space if *every vector* can be written *uniquely* as a linear combination of the basis vectors * A stray definition * We won't use this definition today, but the number of vectors in every basis of a vector space is the same * This number is called the dimension of the vector space * The dimension of the vector space of arrows in the plane is 2, as you would expect * The dimension of $\mathbb{R}^n$ is $n$, as you would expect * The dimension of the set of all polynomials is infinite * Basis: $1, x, x^2, x^3, x^4, x^5, \dots$ * All of this together shows us that there are a lot of different bases for the same vector space * Bases are arbitrary, and our vector space of arrows doesn't come with a default choice * $\mathbb{R}^3$ does come with a canonical choice of basis though: $$\begin{bmatrix}1 \\0 \\0\end{bmatrix},\begin{bmatrix}0 \\1 \\0\end{bmatrix},\begin{bmatrix}0\\0\\1\end{bmatrix}$$ # Linear transformations - Recall the definition of a function in math: - a function $f$ takes a vector $v$ and produces an output vector $f(v)$. The vector it produces is always the same given the same input vector - Functions have a **domain** and a **codomain**, representing the vector spaces that the input and output are in. - If the input space is $V$ and the output space is $W$ we write this as $f: V \to W$. We read this as "f is a function from V to W". - A linear transform is a function satisfying an additional property: linearity - Preservation of addition: $f(u+v)=f(u)+f(v)$ - Preservation of scaling: $f(cv)=cf(v)$ - Linearity is sort of like the distributive law and commutative law combined. - Examples: ```python @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_linear_transform_1(l1, l2): fig, ax = create_func_vis() vec1 = l1 * np.array((1,0.5)) vec2 = l2 * np.array((1,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") vec1 = 2 * vec1 vec2 = 2 * vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_linear_transform_2(l1, l2): fig, ax = create_func_vis() vec1 = l1 * np.array((1,0.5)) vec2 = l2 * np.array((1,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") rot = rotation(30) vec1 = rot @ vec1 vec2 = rot @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_linear_transform_3(l1, l2): fig, ax = create_func_vis() vec1 = l1 * np.array((1,0)) vec2 = l2 * np.array((0,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") skew = np.array(((1,0), (1,1))).T vec1 = skew @ vec1 vec2 = skew @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_linear_transform_4(l1, l2): fig, ax = create_func_vis() vec1 = l1 * np.array((1,0)) vec2 = l2 * np.array((0,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") ref = np.array(((-1,0), (0,1))).T vec1 = ref @ vec1 vec2 = ref @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") ``` interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… - Freshman's dream - A common error by young or inexperience mathematical discipuli is to assume a nonlinear operation is linear. As an example: - assuming $(x+y)^n=x^n+y^n$ - Why is linearity important? - Lots of reasons: first of all a lot of important functions are linear - Rotations - Scaling - Skewing - Reflections - Second of all, they are simpler to deal with, as we shall soon see - Third, many functions can be approximated by linear functions. Ask if you want further details on this - Composition of linear functions - Given any two functions, $f$ and $g$, you can form the composition of them: $f(g(v))$. - This means, first apply the transform $g$, then apply the transform $f$ to the output of it - Note that in order for functions to be composable their domains and codomains must match up like $f: V \to W$ and $g: U \to V$ - The composition of two linear functions is linear: $$\begin{align}f(g(au+bv))&=f(g(au)+g(bv))\\&= f(ag(u)+bg(v)) \\&= af(g(u))+bf(g(v))\end{align}$$ - Examples: ```python @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_composition(l1, l2): fig, ax = create_func_vis(num_funcs=2) vec1 = l1 * np.array((1,0)) vec2 = l2 * np.array((0,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") rot = rotation(30) vec1 = rot @ vec1 vec2 = rot @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") skew = np.array(((1,0), (1,1))).T vec1 = skew @ vec1 vec2 = skew @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[2]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[2]) ax[2].plot(0, 0, 'o', color="black") ``` interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… - Isomorphism - If every vector in the codomain comes from a unique vector in the domain, we call this an isomorphism - Equivalently, an isomorphism is an invertible linear transform: - There exists an inverse function $f^{-1}$ such that $f(f^{-1}(v))=v$ - Example: - The inverse of a 30 deg rotation is a -30 deg rotation ```python @interact(l1=(-2, 2, 0.1), l2=(-2, 2, 0.1)) def demonstrate_inverse(l1, l2): fig, ax = create_func_vis(num_funcs=2) vec1 = l1 * np.array((1,0)) vec2 = l2 * np.array((0,1)) plot_vec_at_origin(vec1, color='red', ax=ax[0]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[0]) ax[0].plot(0, 0, 'o', color="black") rot = rotation(30) vec1 = rot @ vec1 vec2 = rot @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[1]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[1]) ax[1].plot(0, 0, 'o', color="black") rot = rotation(-30) vec1 = rot @ vec1 vec2 = rot @ vec2 plot_vec_at_origin(vec1, color='red', ax=ax[2]) plot_vec(vec1[0], vec1[1], vec2[0], vec2[1], color="blue", ax=ax[2]) ax[2].plot(0, 0, 'o', color="black") ``` interactive(children=(FloatSlider(value=0.0, description='l1', max=2.0, min=-2.0), FloatSlider(value=0.0, desc… - A choice of a basis for a vector space is the same as choosing an isomorphism to $\mathbb{R}^n$ (where $n$ is the dimension). - We can think of this function as assigning coordinates to every vector in our domain - Example: - Assign the vectors $\begin{bmatrix} 1 \\ 0 \end{bmatrix}, \begin{bmatrix} 0 \\ 1 \end{bmatrix}$ to the basis below ```python demonstrate_linear_independence_1(); ``` # Matrices - Matrices are to basis as coordinates are to vector spaces - Linear transforms are uniquely determined by their value on a basis - **Very Important** - Proof: - Let $x_1, x_2$ be a basis - Every vector $v$ can be written as $v=ax_1+bx_2$ - We know this is possible since $x_1, x_2$ is a basis - Now, $f(v)=af(x_1)+bf(x_2)$ - Therefore we can define any linear transform by just listing what the output of the basis vectors should be - So, if $f(x_1)=x_3$ and $f(x_2)=x_4$ then we write the linear transform as just $[x_3, x_4]$ - Remember that choosing a basis gives vectors coordinates - If we choose a basis, we can write the output vectors in that basis - So, if, in coordinates, $x_3=\begin{bmatrix}2 \\ 3 \end{bmatrix}$ and $x_4=\begin{bmatrix} 1 \\ 2 \end{bmatrix}$ - then our matrix becomes $\begin{bmatrix} 2 & 1 \\ 3 & 2 \end{bmatrix}$ - If we work soley in $\mathbb{R}^n$ then there is another way to say this: - The first column of the matrix is the output of $\begin{bmatrix}1\\0\end{bmatrix}$ under the linear transform - The second column of the matrix is the output of $\begin{bmatrix}0\\1\end{bmatrix}$ under the linear transform - Composition of linear transforms corresponds to matrix multiplication - I won't go through all the details, but - If you have two linear transforms, both of which have the same domain and codomain, then you may choose a basis and get a matrix for each of them - You may compose them, you get another linear transform - Hence, the composition has a matrix too - If you work through the details of this, it turns out that the matrix of the composition corresponds to the matrix multiplication of the matrices of the two transforms - Example: - Suppose we want to compose the linear transform whose matrix is $\begin{bmatrix} 2 & 1 \\ 3 & 2 \end{bmatrix}$ with $\begin{bmatrix} 3 & 7 \\ 1 & 1 \end{bmatrix}$ - Well, we know that $\begin{bmatrix} 1\\0\end{bmatrix}$ goes to $\begin{bmatrix} 2 \\ 3 \end{bmatrix}$ - And we know that $\begin{bmatrix} 2 \\ 3 \end{bmatrix}$ goes to $2\begin{bmatrix} 3\\1 \end{bmatrix}+3\begin{bmatrix} 7 \\ 1 \end{bmatrix}$ - Hence the top left entry is $2*3+3*7$ - But this is the same as what you get when you matrix multiply the above two matrices - To be continued: - Further topics - Change of basis formula - Gauss-Jordan - Inner products, orthonormality - Gram-Schimdt - Interpolation formula for quaternions - The first isomorphism theorem for inner product spaces - Eigenvalues - Determinants - Duality - Tensors - Further material - [Essense of linear algebra](https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab) by 3blue1brown - Linear algebra done right by Axler - http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
classdef specimenSymmetry < symmetry % defines a specimen symmetry % % usually specimen symmetry is either % triclinic or orthorhombic % properties axes = [xvector,yvector,zvector]; plotOptions = {} end methods function s = specimenSymmetry(varargin) % defines a specimen symmetry % % usually specimen symmetry is either triclinic or orthorhombic % axes = getClass(varargin,'vector3d',[xvector,yvector,zvector]); if nargin == 0 id = 1; rot = rotation.id; elseif isa(varargin{1},'quaternion') % define the symmetry just by rotations rot = varargin{1}; if check_option(varargin,'pointId') id = get_option(varargin,'pointId'); else id = symmetry.rot2pointId(rot,axes); end else id = symmetry.extractPointId(varargin{:}); rot = symmetry.calcQuat(id,axes); end s = s@symmetry(id,rot); s.axes = axes; end function display(s) disp(' '); disp([inputname(1) ' = ' char(s.lattice) ' ' doclink(s) ' ' docmethods(inputname(1))]); disp(' '); end end methods (Static = true) function cs = loadobj(s) % called by Matlab when an object is loaded from an .mat file % this overloaded method ensures compatibility with older MTEX % versions % maybe there is nothing to do if isa(s,'specimenSymmetry'), cs = s; return; end if isfield(s,'rot') rot = s.rot; else rot = rotation(s.a,s.b,s.c,s.d,s.i); end if isfield(s,'axes') axes = s.axes; else axes = []; end if isfield(s,'id') id = {'pointId',s.id}; else id = {}; end cs = specimenSymmetry(rot,id{:},axes); if isfield(s,'opt'), cs.opt = s.opt; end if isfield(s,'plotOptions'), cs.plotOptions = s.plotOptions; end end end end
We are one of the most popular conference centres in south Dublin’s business district with 2 large conference venues to choose from. These suites can cater for 160 delegates theatre style, and with an excellent location and transport options, Clayton Hotel Leopardstown is the perfect venue for your next conference. The dedicated conference and banqueting department will guarantee a prompt response to your conference enquiry, as well as detailed co-ordination of your event. The Power Suite is an excellent choice for small to large conferences that can facilitate up to 160 delegates. The flexible layout makes it a fantastic venue for large meetings or training events. The Power Suite can also cater for private functions, private dining and a variety of other events. Clayton hotel Leopardstown is located near the South County Business Park and Sandyford Business Park. The perfect location to host a conference in Dublin.
function [T, score_mat] = learn_struct_mwst(data, discrete, node_sizes, node_type, scoring_fn, root) % LEARN_STRUCT_MWST Learn an oriented tree using the MSWT algorithm % T = learn_struct_mwst(data, discrete, node_sizes, node_type, scoring_fn, root) % % Input : % data(i,m) is the node i in the case m, % discrete = [ 1 if discret-node 0 if not ], % node_sizes = 1 if gaussian node, % node_type = {'tabular','gaussian',...}, % score = 'bic' (for complete data and any node types) or 'mutual_info' (tabular nodes), % root is the futur root-node of the tree T. % % Output : % T = adjacency matrix of the tree % % V1.2 : 17 feb 2003 (O. Francois - [email protected], Ph. Leray - [email protected]) % % % See Chow&Liu 1968 for the original algorithm using Mutual Information scoring. % Or Heckerman 1994. if nargin <4 error('Requires at least 4 arguments.') end if nargin == 4 scoring_fn='bic'; root=1; end; if nargin == 5 root=1; end; N=size(data,1); score_mat=zeros(N,N); switch scoring_fn case 'bic', for i=1:(N-1) score2 = score_family(i, [], node_type{i}, scoring_fn, node_sizes, discrete, data,[]); for j=(i+1):N score1 = score_family(i, [j], node_type{i}, scoring_fn, node_sizes, discrete, data,[]); score = score2-score1; score_mat(i,j)=score; score_mat(j,i)=score; end end case 'mutual_info', for i=1:(N-1) for j=(i+1):N score_mat(i,j)= -mutual_info_score(i,node_sizes(i),j,node_sizes(j),data); score_mat(j,i)=score_mat(i,j); end end otherwise, error(['unrecognized scoring fn ' scoring_fn]); end G = minimum_spanning_tree(score_mat); T = mk_rooted_tree(G, root); T=full(T);
The series also aims to provide support for additional drivers. “We realize that competition in Spec MX-5 Challenge is very tough: our top 3 championship finishers last year were separated by 0.1 seconds at the finish of the deciding race,” observed Tom Martin, series co-director. “Drivers have repeatedly told us how much they have learned during the Spec MX-5 Challenge season. So, we have added prize money for P2 and P3 to assist those drivers in coming back to Spec MX-5 Challenge in 2020 to continue up the curve and take another shot at the overall championship,” said Martin. The Spec MX-5 Challenge Series is open to more drivers than ever in 2019. In addition to the previous full arrive & drive offering — which includes use of a series-owned car — the series now offers the option for drivers to own their own cars and to provide their own services. A complete rundown on Spec MX-5 Challenge packages is available at SpecMX-5.com. Individual race entry is being encouraged in 2019 as well. “We want as many drivers as possible to get a taste of Spec MX-5 competition, so we are providing slots for drivers who own T4-class NC MX-5s to run with us, likely when we come to a convenient track,” said Lamb. “We have special pricing for the single-event entrants, and Mazda is providing race-by-race contingency funds to provide additional encouragement,” he noted. The Spec MX-5 Challenge Series is an entry-level professional sports car racing option with over $100,000 in prizes. The series runs specially-prepared Mazda MX-5 race cars at pro tracks like Circuit of The Americas, Sonoma Raceway, VIRginia International Raceway, Road America, Watkins Glen, and Road Atlanta. The series offers challenging competition, expert driver coaching and multiple sponsorship opportunities for aspiring professional drivers.
#include <err.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #define X y[0] #define V_X y[1] #define Y y[2] #define V_Y y[3] const double g = 9.81; /* m/s^2 */ const double v_0 = 700.0; /* m/s */ const double B2_m = 4.0e-5; /* 1/m */ const double y_d = 1.0e4; /* m */ int func(double t, const double y[], double f[], void *params); int main(int argc, char *argv[]) { gsl_odeiv2_system sys = {func, NULL, 4, NULL}; gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new( &sys, gsl_odeiv2_step_rkf45, 1.0e-6, 1.0e-6, 0.0 ); int i = 1; double t = 0.0; double alpha = argc > 1 ? strtod(argv[1], NULL) : 1.0; double y[4]; X = Y = 0.0; V_X = v_0*cos(alpha); V_Y = v_0*sin(alpha); while (Y >= 0.0) { double t_i = i/50.0; int status = gsl_odeiv2_driver_apply(driver, &t, t_i, y); if (status != GSL_SUCCESS) { warnx("apply status = %d", status); break; } printf("%.12le %.12le %.12le %.12le %.12le\n", t, X, Y, V_X, V_Y); i++; } gsl_odeiv2_driver_free(driver); return EXIT_SUCCESS; } #define DX_DT f[0] #define DVX_DT f[1] #define DY_DT f[2] #define DVY_DT f[3] int func(double t, const double y[], double f[], void *params) { double v = sqrt(V_X*V_X + V_Y*V_Y); double corr = exp(-Y/y_d); DX_DT = V_X; DVX_DT = -B2_m*corr*v*V_X; DY_DT = V_Y; DVY_DT = -g - B2_m*corr*v*V_Y; return GSL_SUCCESS; }
Formal statement is: lemma strict_mono_compose: "strict_mono r \<Longrightarrow> strict_mono s \<Longrightarrow> strict_mono (\<lambda>x. r (s x))" Informal statement is: If $r$ and $s$ are strictly monotone functions, then so is $r \circ s$.
-- ----------------------------------------------------------------- [ ABE.idr ] -- Module : ABE -- Description : Types for Attribute Based Encryption -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOF ] module Crypto.Adv.ABE import Crypto.Adv.Key data ABEKeyType = CipherTextPolicy | KeyPolicy
open import slots.imports open import slots.defs module slots.packed {cfg : config}(g : game cfg) where open config cfg open game g LineCombinations = Vec ℕ n ReelCombinations = Vec LineCombinations m PackedLine = Fruit × ReelNo PackedReel = Vec ℕ m PackedReels = Vec PackedReel n packReel : Reel → PackedReel packReel = L.foldl (λ r f → V.zipWith _+_ r (z V.[ f ]≔ 1)) z where z = V.replicate 0 packReels : Reels → PackedReels packReels = V.map packReel packedLength : PackedReel → ℕ packedLength = V.foldl _ _+_ 0 packedTotal : PackedReels → ℕ packedTotal = V.foldl _ (λ i r → i * packedLength r) 1 packedLineWin : PackedLine → WinTable → ℕ packedLineWin (f , r) = V.lookup r ∘ V.lookup f rproducts : ∀ {n} → Vec ℕ n → Vec ℕ n rproducts = V.foldr (Vec ℕ) (λ k ks → k ∷ V.map (k N.*_) ks) [] lproducts : ∀ {n} → Vec ℕ n → Vec ℕ n lproducts = V.foldl (Vec ℕ) (λ ks k → k ∷ V.map (k N.*_) ks) [] fruitLineCombinations : PackedReels → Fruit → LineCombinations fruitLineCombinations rs f = {!!} where g′ : PackedReel → ℕ × ℕ g′ r = #f , #f̅ where #f : ℕ #f = V.lookup f r #f̅ : ℕ #f̅ = V.sum r N.∸ #f fs,f̅s = V.unzip (V.map g′ rs) fs : Vec ℕ n fs = rproducts (proj₁ fs,f̅s) -- ts = lproducts f̅s : Vec ℕ n f̅s = proj₂ fs,f̅s -- f₀ f₁ f₂ f₃ -- f̅₀ f̅₁ f̅₂ f̅₃ -- t₀ t₁ t₂ t₃ -- f₀ f̅₁ t₂ t₃ | 1 -- f₀ f₁ f̅₂ t₃ | 2 -- f₀ f₁ f₂ f̅₃ | 3 -- f₀ f₁ f₂ f₃ | 4 fruitReelCombinations : PackedReels → ReelCombinations fruitReelCombinations rs = V.tabulate (fruitLineCombinations rs) sum2 : ∀ {n}{A : Set}{B : Set} → (A → B → ℕ) → Vec A n → Vec B n → ℕ sum2 f as bs = V.sum (V.zipWith f as bs) rtp : WinTable → ReelCombinations → ℕ rtp = sum2 (sum2 _*_)
fileName <- "rounds.txt" rounds <- as.numeric(readChar(fileName, file.info(fileName)$size)) x = 1.0 pi = 1.0 for (i in 2:(rounds + 2)){ x = x * -1 pi = pi + (x / (2 * i - 1)) } pi = pi * 4 printf <- function(...) cat(sprintf(...)) printf("%.16f\n", pi)
{-# OPTIONS --safe #-} module Squaring where open import Relation.Binary.PropositionalEquality open import Data.Nat open import Data.Product open import Data.Bool hiding (_≤_;_<_) open import Data.Nat.Properties open ≡-Reasoning div-mod2 : ℕ → ℕ × Bool div-mod2 0 = 0 , false div-mod2 (suc 0) = 0 , true div-mod2 (suc (suc n)) = let q , r = div-mod2 n in suc q , r -- The first argument (k) helps Agda to prove -- that the function terminates pow-sqr-aux : ℕ → ℕ → ℕ → ℕ pow-sqr-aux 0 _ _ = 1 pow-sqr-aux _ _ 0 = 1 pow-sqr-aux (suc k) b e with div-mod2 e ... | e' , false = pow-sqr-aux k (b * b) e' ... | e' , true = b * pow-sqr-aux k (b * b) e' pow-sqr : ℕ → ℕ → ℕ pow-sqr b e = pow-sqr-aux e b e div-mod2-spec : ∀ n → let q , r = div-mod2 n in 2 * q + (if r then 1 else 0) ≡ n div-mod2-spec 0 = refl div-mod2-spec 1 = refl div-mod2-spec (suc (suc n)) with div-mod2 n | div-mod2-spec n ... | q , r | eq rewrite +-suc q (q + 0) | eq = refl div-mod2-lt : ∀ n → 0 < n → proj₁ (div-mod2 n) < n div-mod2-lt 0 lt = lt div-mod2-lt 1 lt = lt div-mod2-lt 2 lt = s≤s (s≤s z≤n) div-mod2-lt (suc (suc (suc n))) lt with div-mod2 (suc n) | div-mod2-lt (suc n) (s≤s z≤n) ... | q , r | ih = ≤-step (s≤s ih) pow-lemma : ∀ b e → (b * b) ^ e ≡ b ^ (2 * e) pow-lemma b e = begin (b * b) ^ e ≡⟨ cong (λ t → (b * t) ^ e) (sym (*-identityʳ b)) ⟩ (b ^ 2) ^ e ≡⟨ ^-*-assoc b 2 e ⟩ b ^ (2 * e) ∎ pow-sqr-lemma : ∀ k b e → e ≤ k → pow-sqr-aux k b e ≡ b ^ e pow-sqr-lemma 0 _ 0 _ = refl pow-sqr-lemma (suc k) _ 0 _ = refl pow-sqr-lemma (suc k) b (suc e) (s≤s le) with div-mod2 (suc e) | div-mod2-spec (suc e) | div-mod2-lt (suc e) (s≤s z≤n) ... | e' , false | eq | lt = begin pow-sqr-aux k (b * b) e' ≡⟨ pow-sqr-lemma k (b * b) e' (≤-trans (≤-pred lt) le) ⟩ (b * b) ^ e' ≡⟨ pow-lemma b e' ⟩ b ^ (2 * e') ≡⟨ cong (b ^_) (trans (sym (+-identityʳ (e' + (e' + 0)))) eq) ⟩ b ^ suc e ∎ ... | e' , true | eq | lt = cong (b *_) (begin pow-sqr-aux k (b * b) e' ≡⟨ pow-sqr-lemma k (b * b) e' (≤-trans (≤-pred lt) le) ⟩ (b * b) ^ e' ≡⟨ pow-lemma b e' ⟩ b ^ (2 * e') ≡⟨ cong (b ^_) (suc-injective (trans (+-comm 1 _) eq)) ⟩ b ^ e ∎)
Deportivo is finally responding the questions regarding the polemic case with Vecindario; the lawyers of the club aren’t only saying that the suspension of Oltra’s license is unfair, but also accused the RFEF of been attacking Depor. Deportivo is now open to negotiate with UD Vecindario in order to solve once and for all the conflict with the Canarian club. Vecindario is asking for €700,000 as part of a polemic collaboration deal that was cancelled on the past year. The conflict between Deportivo and Vecindario is now threatening Deportivo. A debt of €100,000 with Vecindario has turned into a loss of €700,000. For this conflict Oltra wasn’t on the bench for the Copa clash. One of the few positive news after the relegation to Segunda is the surprising reaction of Depor’s fans; a clear example is the number of socios, which is about to reach the mark of 20,000, the highest since the years of the Champions League. Deportivo can’t inscribe players due to a legal demand of UD Vecindario, while Adrian is doing everything in order to join Atletico Madrid. Those are the two current problems that are focusing the attention of president Lendoiro. Lendoiro travelled to Madrid in order to solve several pending issues and to participate in the draw of the liga calendar; before travelling he talked to reporters. The season 2011/12 will bring some changes to the structure of base football at Deportivo; the most notorious modification is the appearance of the Benjamin squad, the ninth team at the youth system composed by 10-year-old kids. Lendoiro is on war against the clubs that haven’t paid their obligations to Deportivo; there’s a well-known battle against Real Zaragoza, and since Friday the war was extended to Racing Santander; all for the transfer of Sergio Canales. Depor’s president continues his battle against the bankruptcy law and Zaragoza, while he announced that the club will make six or seven signings ahead of next season.
(* Contribution to the Coq Library V6.3 (July 1999) *) Require Import securite. Lemma POinv1rel8 : forall (l l0 : list C) (k k0 k1 k2 : K) (c c0 c1 c2 : C) (d d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19 d20 : D), inv0 (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0) (MABNaNbKeyK d d0 d1 d2 d3) l) -> inv1 (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0) (MABNaNbKeyK d d0 d1 d2 d3) l) -> rel8 (ABSI (MBNaKab d7 d8 d9 k0) (MANbKabCaCb d4 d5 d6 k c c0) (MABNaNbKeyK d d0 d1 d2 d3) l) (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2) (MABNaNbKeyK d10 d11 d12 d13 d14) l0) -> inv1 (ABSI (MBNaKab d18 d19 d20 k2) (MANbKabCaCb d15 d16 d17 k1 c1 c2) (MABNaNbKeyK d10 d11 d12 d13 d14) l0). Proof. do 32 intro. unfold rel8 in |- *; intros Inv0 Inv1 and1. elim and1; intros t1 and2; elim and2; intros t2 and3; elim and3; intros t3 and4; elim and4; intros eq_l0 t4. elim eq_l0; assumption. Qed.
Require Import Bool Arith Max List. Import List.ListNotations. Require Import Omega. Require Import Cecoa.Lib. Set Implicit Arguments. Unset Strict Implicit. Section Syntax. (* AST *) Variables variable function constructor : Type. Variable max_arity : nat. Inductive value : Type := | c_capply : constructor -> list value -> value. Inductive term : Type := | var : variable -> term | capply : constructor -> list term -> term | fapply : function -> list term -> term. Inductive pattern : Type := | p_var : variable -> pattern | p_capply : constructor -> list pattern -> pattern. Inductive rule : Type := | rule_intro : function -> list pattern -> term -> rule. (* Smarter induction principles than the ones automatically generated *) Lemma value_ind2_gen : forall (P : value -> Type)(Q : list value -> Type), Q nil -> (forall v l, P v -> Q l -> Q (v :: l)) -> (forall c l, Q l -> P (c_capply c l)) -> forall v, P v. Proof. fix H1 6; intros P Q H2 H3 H4 [c l]; apply H4; revert l; fix H5 1; intros [ | v l]. - apply H2. - apply H3. + apply H1 with (Q:=Q). * apply H2. * apply H3. * apply H4. + apply H5. Qed. Lemma term_ind2_gen : forall (P : term -> Prop)(Q : list term -> Prop), Q nil -> (forall t l, P t -> Q l -> Q (t :: l)) -> (forall x, P (var x)) -> (forall c l, Q l -> P (capply c l)) -> (forall f l, Q l -> P (fapply f l)) -> forall t, P t. Proof. fix H1 8; intros P Q H2 H3 H4 H5 H6 [ x | c l | f l ]. - apply H4. - apply H5; revert l; fix H7 1; intros [ | t l]. + apply H2. + apply H3. * { apply H1 with (Q:=Q). - apply H2. - apply H3. - apply H4. - apply H5. - apply H6. } * apply H7. - apply H6; revert l; fix H7 1; intros [ | t l]. + apply H2. + apply H3. * { apply H1 with (Q:=Q). - apply H2. - apply H3. - apply H4. - apply H5. - apply H6. } * apply H7. Qed. Lemma term_ind2 : forall (P : term -> Prop), (forall x, P (var x)) -> (forall c l, (forall t, In t l -> P t) -> P (capply c l)) -> (forall f l, (forall t, In t l -> P t) -> P (fapply f l)) -> forall t, P t. Proof. intros P H1 H2 H3 t. apply term_ind2_gen with (Q := fun l => forall t, In t l -> P t); simpl; try tauto. clear H1 H2 H3 t; intros t1 l H1 H2 t2 [H3 | H3]. - subst; trivial. - auto. Qed. Lemma pattern_ind2_gen : forall (P : pattern -> Prop)(Q : list pattern -> Prop), Q nil -> (forall p l, P p -> Q l -> Q (p :: l)) -> (forall x, P (p_var x)) -> (forall c l, Q l -> P (p_capply c l)) -> forall p, P p. Proof. fix H1 7; intros P Q H2 H3 H4 H5 [ x | c l ]. - apply H4. - apply H5; revert l; fix H6 1; intros [ | p l]. + apply H2. + apply H3. * { apply H1 with (Q:=Q). - apply H2. - apply H3. - apply H4. - apply H5. } * apply H6. Qed. Lemma pattern_ind2 : forall (P : pattern -> Prop), (forall x, P (p_var x)) -> (forall c l, (forall p, In p l -> P p) -> P (p_capply c l)) -> forall p, P p. Proof. intros P H1 H2 p. apply pattern_ind2_gen with (Q := fun l => forall p, In p l -> P p); simpl; try tauto. clear H1 H2 p; intros p1 l H1 H2 p2 [H3 | H3]. - subst; trivial. - auto. Qed. (* Boolean equalities for syntax *) Variable variable_eq_dec : forall (x1 x2 : variable), {x1=x2}+{x1<>x2}. Definition variable_beq (x1 x2 : variable) : bool := if variable_eq_dec x1 x2 then true else false. Lemma variable_beq_eq : forall x1 x2, variable_beq x1 x2 = true <-> x1 = x2. Proof. unfold variable_beq. intros x1 x2. split; intro H; destruct (variable_eq_dec x1 x2); [ trivial | discriminate | trivial | tauto ]. Qed. Variable function_eq_dec : forall (x1 x2 : function), {x1=x2}+{x1<>x2}. Definition function_beq (x1 x2 : function) : bool := if function_eq_dec x1 x2 then true else false. Lemma function_beq_eq : forall x1 x2, function_beq x1 x2 = true <-> x1 = x2. Proof. unfold function_beq. intros x1 x2. split; intro H; destruct (function_eq_dec x1 x2); [ trivial | discriminate | trivial | tauto ]. Qed. Variable constructor_eq_dec : forall (x1 x2 : constructor), {x1=x2}+{x1<>x2}. Definition constructor_beq (x1 x2 : constructor) : bool := if constructor_eq_dec x1 x2 then true else false. Lemma constructor_beq_eq : forall x1 x2, constructor_beq x1 x2 = true <-> x1 = x2. Proof. unfold constructor_beq. intros x1 x2. split; intro H; destruct (constructor_eq_dec x1 x2); [ trivial | discriminate | trivial | tauto ]. Qed. Fixpoint value_beq (v1 v2 : value) : bool := match v1, v2 with | c_capply c lv, c_capply c' lv' => constructor_beq c c' && list_beq _ value_beq lv lv' end. Lemma value_ind2 : forall (P : value -> Prop), (forall c l, (forall v, In v l -> P v) -> P (c_capply c l)) -> forall v, P v. Proof. intros P H1 v. apply value_ind2_gen with (Q := fun l => forall v, In v l -> P v); simpl; try tauto. clear H1 v; intros v1 l H1 H2 v2 [H3 | H3]. - subst; trivial. - auto. Qed. Lemma value_beq_eq v1 v2 : value_beq v1 v2 = true <-> v1 = v2. Proof. revert v2. induction v1 as [ c1 lv1 IH ] using value_ind2; simpl; intros [ c2 lv2 ]. rewrite andb_true_iff, constructor_beq_eq, list_beq_eq. - split. + intros [ H1 H2 ]. congruence. + intro H. injection H. tauto. - firstorder. Qed. Fixpoint term_beq (t1 t2 : term) : bool := match t1, t2 with | var x, var x' => variable_beq x x' | capply c lt, capply c' lt' => constructor_beq c c' && list_beq _ term_beq lt lt' | fapply f lt, fapply f' lt' => function_beq f f' && list_beq _ term_beq lt lt' | _, _ => false end. Lemma term_beq_eq t1 t2 : term_beq t1 t2 = true <-> t1 = t2. Proof. revert t2. induction t1 as [ x1 | c1 lt1 IH | f1 lt1 IH ] using term_ind2; simpl; intros [ x2 | c2 lt2 | f2 lt2 ]; try (split; congruence). - rewrite variable_beq_eq. split; congruence. - rewrite andb_true_iff, constructor_beq_eq, list_beq_eq. + split. * intros [ H1 H2 ]. congruence. * intro H. split; congruence. + firstorder. - rewrite andb_true_iff, function_beq_eq, list_beq_eq. + split. * intros [ H1 H2 ]. congruence. * intro H. split; congruence. + firstorder. Qed. (* Automatic conversion of a [value] or [pattern] into a [term] *) Fixpoint pattern_from_value (v : value) : pattern := match v with | c_capply c lv => p_capply c (map pattern_from_value lv) end. Fixpoint term_from_value (v : value) : term := match v with | c_capply c lc => capply c (map term_from_value lc) end. Coercion term_from_value : value >-> term. Lemma term_from_value_not_var : forall v x, ~ term_from_value v = var x. Proof. intros v x; destruct v; simpl; congruence. Qed. Lemma term_from_value_not_fapply : forall v f lt, ~ term_from_value v = fapply f lt. Proof. intros v x; destruct v; simpl; congruence. Qed. Lemma term_from_value_injective (v v': value) : term_from_value v = term_from_value v' -> v = v'. Proof. revert v'; induction v as [ c lv IH ] using value_ind2; intros v' Heq. destruct v' as [ c' lv' ]. simpl in Heq. injection Heq; intros Heqlv Heqc. subst c'. f_equal. clear c Heq. assert (Hlen : length lv = length lv'). { do 2 rewrite <- map_length with (f := term_from_value). rewrite Heqlv. trivial. } revert lv' Heqlv Hlen IH; induction lv as [ | v lv IH' ]; intros lv' Heqlv Hlen IH; destruct lv' as [ | v' lv']; [ trivial | inversion Hlen | inversion Hlen | ]. f_equal. - apply IH; [ now left | ]. injection Heqlv; intros; assumption. - apply IH'. + injection Heqlv; intros; assumption. + injection Hlen; intros; assumption. + intros v'' Hin. apply IH. now right. Qed. Fixpoint term_from_pattern (p : pattern) : term := match p with | p_var v => var v | p_capply c lp => capply c (map term_from_pattern lp) end. Coercion term_from_pattern : pattern >-> term. Lemma term_from_pattern_not_fapply : forall v f lt, ~ term_from_pattern v = fapply f lt. Proof. intros v x; destruct v; simpl; congruence. Qed. (* Doit-on définir explicitement term_value ? *) Fixpoint term_value (t: term) : Prop := match t with | capply _ lt => andl (map term_value lt) | _ => False end. Lemma term_value_eqv (t: term) : term_value t <-> exists (v: value), t = term_from_value v. Proof. induction t as [ | c lt IH | ] using term_ind2. - split. + intros Himp; inversion Himp. + intros Himp; destruct Himp as [ v Himp ]; destruct v; discriminate. - split. + intros Hval. assert (exists lv, Forall2 (fun t v => t = term_from_value v) lt lv) as [ lv Hfor2 ]. { apply forall_exists_list with (P := term_value). - intros t Hin Hvalt. apply IH; assumption. - simpl in Hval. apply forall_andl; assumption. } exists (c_capply c lv). simpl. f_equal. clear c Hval IH. revert lv Hfor2. induction lt as [ | t lt IH ]; intros lv Hfor2. * inversion Hfor2; tauto. * inversion Hfor2 as [ | Ba v Bc lv' Be Hfor2' Bg Bh ]; subst. simpl; f_equal. apply IH; assumption. + intros [ v Heq ]. destruct v as [ c' lv ]. inversion Heq; simpl; clear. rewrite map_map. induction lv as [ | v lv IH ]. * simpl; trivial. * simpl. split; [ idtac | assumption ]. clear IH lv. induction v as [ c lv ] using value_ind2. simpl. rewrite map_map. rewrite <- forall_andl; apply Forall_forall; assumption. - split. + intros Himp; inversion Himp. + intros Himp; destruct Himp as [ v Himp ]; destruct v; discriminate. Qed. (* Well-formedness of a program *) Fixpoint vars_of_term (t : term) : list variable := match t with | var x => [x] | capply _ lt => flat_map vars_of_term lt | fapply _ lt => flat_map vars_of_term lt end. Fixpoint vars_of_pattern (p : pattern) : list variable := match p with | p_var x => [x] | p_capply _ lp => flat_map vars_of_pattern lp end. Lemma vars_of_pattern_term p : vars_of_pattern p = vars_of_term (term_from_pattern p). Proof. induction p as [x | c lp IH] using pattern_ind2; simpl; trivial. apply flat_map_comp; exact IH. Qed. Fixpoint functions_of_term (t:term) : list function := match t with | var _ => [] | capply _ lt => flat_map functions_of_term lt | fapply f lt => f :: flat_map functions_of_term lt end. Fixpoint fapplies_in_term (t: term) : list term := match t with | var _ => [] | capply _ lt => flat_map fapplies_in_term lt | fapply _ lt => t :: flat_map fapplies_in_term lt end. Lemma fapplies_in_term_are_fapplies t1 t2 : In t1 (fapplies_in_term t2) -> exists f lt, t1 = fapply f lt. Proof. revert t1. induction t2 as [ x | c lt IH | f lt IH ] using term_ind2; intros t1 Hin; simpl in Hin; try tauto. - simpl in Hin. apply in_flat_map in Hin. destruct Hin as (t & Hinlt & Hinfapp). destruct (IH t Hinlt t1 Hinfapp) as (f' & lt' & Heq). exists f'; exists lt'; assumption. - simpl in Hin. destruct Hin as [ Heq | Hin ]. + exists f; exists lt; symmetry; assumption. + apply in_flat_map in Hin. destruct Hin as (t & Hinlt & Hinfapp). destruct (IH t Hinlt t1 Hinfapp) as (f' & lt' & Heq). exists f'; exists lt'; assumption. Qed. Lemma fapplies_in_value_nil (v: value) : fapplies_in_term (@term_from_value v) = []. Proof. induction v as [ c lv IH ] using value_ind2. simpl. rewrite <- flat_map_comp with (h := fun x => fapplies_in_term (@term_from_value x)); trivial. induction lv as [ | v' lv' IH' ]; trivial. simpl. rewrite IH, IH'; firstorder. Qed. Fixpoint max_arity_pattern (p : pattern) : nat := match p with | p_var _ => 0 | p_capply _ lp => max (length lp) (maxl (map max_arity_pattern lp)) end. Fixpoint max_arity_term (t : term) : nat := match t with | var _ => 0 | capply _ lt => max (length lt) (maxl (map max_arity_term lt)) | fapply _ lt => max (length lt) (maxl (map max_arity_term lt)) end. Definition max_arity_rule (r : rule) : nat := match r with | rule_intro _ lp t => max (max_arity_term t) (max (length lp) (maxl (map max_arity_pattern lp))) end. Definition max_arity_prog (prog : list rule) : nat := maxl (map max_arity_rule prog). Definition rule_vars_defined (r : rule) : Prop := match r with | rule_intro _ lp t => incl (vars_of_term t) (flat_map vars_of_pattern lp) end. Definition wf_prog (prog : list rule) : Prop := andl (map rule_vars_defined prog) /\ max_arity_prog prog <= max_arity. Fixpoint subst (s : variable -> value)(t : term) : term := match t with | var x => s x | capply c lt => capply c (map (subst s) lt) | fapply f lt => fapply f (map (subst s) lt) end. Fixpoint psubst (s : variable -> value)(p : pattern) : value := match p with | p_var x => s x | p_capply c lp => c_capply c (map (psubst s) lp) end. Lemma subst_not_var : forall s t x, ~ subst s t = var x. Proof. intros s t x; destruct t; simpl; try congruence; apply term_from_value_not_var. Qed. Lemma subst_psubst s p : subst s (term_from_pattern p) = term_from_value (psubst s p). Proof. induction p as [ x | c lp IH1 ] using pattern_ind2; simpl; trivial. f_equal; do 2 rewrite map_map; revert IH1; clear; intro IH1; induction lp as [ | p lp IH2]; simpl; trivial. f_equal. - apply IH1; simpl; tauto. - apply IH2. intros; apply IH1; simpl; tauto. Qed. (* Sizes *) Fixpoint value_size (v : value) : nat := match v with | c_capply _ lv => 1 + suml (map value_size lv) end. Fixpoint term_size (t : term) := match t with | var _ => 1 | capply _ lt => 1 + suml (map term_size lt) | fapply _ lt => 1 + suml (map term_size lt) end. Lemma gt_term_size_O t : term_size t > 0. Proof. case t; intros ; simpl; apply gt_Sn_O. Qed. Lemma in_capply_term_size_lt c (t : term) lt : In t lt -> term_size t < term_size (capply c lt). Proof. simpl. induction lt as [ | t' lt IH ]; simpl; try tauto. intros [ H | H ]. - subst t'. omega. - apply IH in H. omega. Qed. Lemma in_fapply_term_size_lt f (t : term) lt : In t lt -> term_size t < term_size (fapply f lt). Proof. simpl. induction lt as [ | t' lt IH ]; simpl; try tauto. intros [ H | H ]. - subst t'. omega. - apply IH in H. omega. Qed. (* Right-hand side of a rule *) Definition rhs_of_rule (r : rule) : term := match r with rule_intro _ _ t => t end. (* Injecte les membres gauches des règles dans les term *) Definition lhs_of_rule (r : rule) : term := match r with rule_intro f lp _ => fapply f (map term_from_pattern lp) end. Definition max_rhs (prog : list rule) : nat := maxl (map term_size (map rhs_of_rule prog)). (* This lemma corresponds to the first four lines of the proof of Proposition 4. *) (* Une règle bien formée contient uniquement des variables qui sont dans les motifs. Soit un arbre de preuve bien formé et un programme. Pour chaque activation, montrons que |rs| ≤ activation_bound p Pour ça, calculons la taille de rs. |rs| ≤ |r| (1+ plus grand substitut d’une variable) car |rs| contient au plus |r| variables. (Lemme pour prouver ça) par ailleurs « plus grand substitut d’une variable » ≤ |t| pour toutes les variables de r car : le programme est bien formé, donc les variables de r apparaissent dans les motifs, donc la substitution les fait correspondre à des sous-termes de t (lemme : un sous-terme a une taille inférieure ?) *) Lemma compatible_sizes: forall v, term_size (term_from_value v) = value_size v. Proof. induction v as [c lv IH] using value_ind2; simpl; do 2 f_equal; rewrite map_map; apply map_in_ext; trivial. Qed. Definition max_size_image_subst (t : term) (s : variable -> value) : nat := maxl (map value_size (map s (vars_of_term t))). Lemma incl_le_max_size_image_subst : forall s t u, incl (vars_of_term t) (vars_of_term u) -> max_size_image_subst t s <= max_size_image_subst u s. Proof. intros s t u H_incl. unfold max_size_image_subst. apply incl_le_maxl. do 2 rewrite map_map. unfold incl. intro size. rewrite in_map_iff. intro H_size_in_var_t. destruct H_size_in_var_t as [ var [ H_var_size H_var_in_t ] ]. set (var_size := fun x : variable => value_size (s x)). replace size with (var_size var). apply in_map. apply (H_incl var H_var_in_t). Qed. Lemma step_one: forall s t, term_size (subst s t) <= term_size t * (1 + max_size_image_subst t s). Proof. intros s t; induction t as [ x | c lt IH | f lt IH ] using term_ind2. - unfold max_size_image_subst; simpl; rewrite plus_0_r; rewrite compatible_sizes; apply le_S; apply le_max_l. - simpl; eapply le_trans with (S _). + apply le_n_S; rewrite map_map; apply suml_map_le; apply IH. + clear IH; apply le_n_S; induction lt as [ | t lt IH ]; simpl; trivial; etransitivity. * apply plus_le_compat_l; apply IH. * { clear IH; unfold max_size_image_subst; simpl; do 2 rewrite map_app; rewrite maxl_app. set (w := term_size t); set (x:= maxl (map value_size (map s (vars_of_term t)))); set (y:= maxl (map value_size (map s (flat_map vars_of_term lt)))); set (z := suml (map term_size lt)). replace (max x y + (w + z) * S (max x y)) with (w * S (max x y) + (max x y + z * S (max x y))). - apply plus_le_compat. + apply mult_le_compat_l; apply le_n_S. apply le_max_l. + apply plus_le_compat. * apply le_max_r. * apply mult_le_compat_l; apply le_n_S; apply le_max_r. - ring. } - simpl; eapply le_trans with (S _). + apply le_n_S; rewrite map_map; apply suml_map_le; apply IH. + clear IH; apply le_n_S; induction lt as [ | t lt IH ]; simpl; trivial; etransitivity. * apply plus_le_compat_l; apply IH. * { clear IH; unfold max_size_image_subst; simpl; do 2 rewrite map_app; rewrite maxl_app. set (w := term_size t); set (x:= maxl (map value_size (map s (vars_of_term t)))); set (y:= maxl (map value_size (map s (flat_map vars_of_term lt)))); set (z := suml (map term_size lt)). replace (max x y + (w + z) * S (max x y)) with (w * S (max x y) + (max x y + z * S (max x y))). - apply plus_le_compat. + apply mult_le_compat_l; apply le_n_S. apply le_max_l. + apply plus_le_compat. * apply le_max_r. * apply mult_le_compat_l; apply le_n_S; apply le_max_r. - ring. } Qed. (* |r| ≤ |t| t match le motif, donc pour toute variable v du motif, |v sigma| ≤ |t| soit R la taille maximale d’une image de variable par la substitution donc |v sigma| ≤ R ≤ |t| toute variable de r est une variable du motif donc de taille ≤ |t| |rsig| ≤ |r|(R+1) d’après (1) |r| ≤ max_rhs par définition |rsig| ≤ max_rhs(R+1) |rsig| ≤ activ(|t|) pour activ = x → max_rhs(x+1) *) (* |xσ| ≤ |pσ| pour x ∈ p *) Lemma size_subst_var_le_size_value: forall p s (x:variable) v, v = psubst s p -> In x (vars_of_pattern p) -> value_size (s x) <= value_size v. Proof. intros p s x. induction p as [ x' | c lp IH ] using pattern_ind2 ; intros v H_match H_x_in_pattern. - (* Cas de base p = x *) simpl in *. destruct H_x_in_pattern. + subst. trivial. + case H. - (* Cas récursif *) simpl in * |-. subst v. simpl. (* On prouve d’abord que x dans le motif de départ implique qu’il est dans un des p de lp *) rewrite in_flat_map in H_x_in_pattern. destruct H_x_in_pattern as [ p [ H_p_in_lp H_x_in_p ] ]. etransitivity. + apply IH with p; trivial. + rewrite map_map. etransitivity. * apply in_le_suml. instantiate (1 := map (fun x0 : pattern => value_size (psubst s x0)) lp). rewrite in_map_iff; exists p. split; trivial. * apply le_n_Sn. Qed. Lemma max_size_image_subst_bounded : forall t s, max_size_image_subst t s <= term_size (subst s t). Proof. intros t s; unfold max_size_image_subst; rewrite map_map; induction t as [ x | c lt IH | f lt IH ] using term_ind2; simpl; try (rewrite max_0_r; rewrite compatible_sizes; trivial); (transitivity (suml (map term_size (map (subst s) lt))); [idtac | apply le_n_Sn]); rewrite map_map; apply maxl_le_suml_map; exact IH. Qed. (* This definition corresponds to the r in the proof of Proposition 4. *) Definition activation_bound (prog : list rule) : nat -> nat := fun x => max_rhs prog * (1 + x). Lemma activation_bound_monotone (prog : list rule) : forall x y, x <= y -> activation_bound prog x <= activation_bound prog y. Proof. intros x y H_le. unfold activation_bound. apply mult_le_compat_l. apply le_n_S. assumption. Qed. Definition nb_rhs_functions (r: rule) := match r with | rule_intro _ _ t => length (functions_of_term t) end. Definition max_nb_rhs_functions (prog : list rule) : nat := maxl (map nb_rhs_functions prog). Lemma no_func_in_pattern p: functions_of_term (term_from_pattern p) = []. Proof. induction p using pattern_ind2; simpl; auto. apply flat_map_nil. intros. induction l; simpl in *; try (now exfalso). destruct H0. - subst. apply H. auto. - apply IHl; auto. Qed. Lemma no_funcs_in_patterns l: flat_map functions_of_term (map term_from_pattern l) = []. Proof. induction l; simpl; auto. rewrite IHl. rewrite no_func_in_pattern. simpl. auto. Qed. End Syntax. Arguments var [variable function constructor]. Arguments p_var [variable constructor].
using SparseIR using Test import PyCall: pyimport, PyNULL, PyVector import LegendrePolynomials: Pl @testset "test_augmented_bosonic_basis" begin """Augmented bosonic basis""" wmax = 2 beta = 1000 basis = FiniteTempBasis(boson, beta, wmax, 1e-6) basis_legg = LegendreBasis(boson, beta, 2) basis_comp = CompositeBasis([basis_legg, basis]) # G(tau) = c - e^{-tau*pole}/(1 - e^{-beta*pole}) pole = 1.0 c = 1e-2 tau_smpl = TauSampling(basis_comp) gtau = c .- exp.(-tau_smpl.sampling_points .* pole) ./ (1 - exp(-beta * pole)) gl_from_tau = fit(tau_smpl, gtau) gtau_reconst = evaluate(tau_smpl, gl_from_tau) @test isapprox(gtau, gtau_reconst; atol=1e-14 * maximum(abs.(gtau)), rtol=0) end
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.group.hom /-! # Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ universes u v w namespace units variables {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : units M →* units N := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : units M) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma coe_map_inv (f : M →* N) (u : units M) : ↑(map f u)⁻¹ = f ↑u⁻¹ := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id (units M) := by ext; refl /-- Coercion `units M → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : units M →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : units M) : coe_hom M x = ↑x := rfl /-- If a map `g : M → units N` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → units N) (h : ∀ x, ↑(g x) = f x) : M →* units N := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `units M`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* units M := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom section is_unit variables {M : Type*} {N : Type*} @[to_additive] lemma is_unit.map [monoid M] [monoid N] (f : M →* N) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact (units.map f y).is_unit /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* units N`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def is_unit.lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* units N := units.lift_right f (λ x, classical.some (hf x)) $ λ x, classical.some_spec (hf x) @[to_additive] lemma is_unit.coe_lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := units.coe_lift_right _ x @[simp, to_additive] lemma is_unit.mul_lift_right_inv [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : f x * ↑(is_unit.lift_right f h x)⁻¹ = 1 := units.mul_lift_right_inv (λ y, classical.some_spec $ h y) x @[simp, to_additive] lemma is_unit.lift_right_inv_mul [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : ↑(is_unit.lift_right f h x)⁻¹ * f x = 1 := units.lift_right_inv_mul (λ y, classical.some_spec $ h y) x end is_unit
theory Chapter2 imports Main begin text \<open> \section*{Chapter 2} \exercise Use the \textbf{value} command to evaluate the following expressions: \<close> value "1 + (2::int)" value "1 - (2::nat)" value "1 - (2::int)" value "[a,b] @ [c,d]" text \<open> \endexercise \exercise Recall the definition of our own addition function on @{typ nat}: \<close> fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "add 0 n = n" | "add (Suc m) n = Suc(add m n)" text \<open> Prove that @{const add} is associative and commutative. You will need additional lemmas. \<close> lemma add_zero: "add n 0 = n" by(induction n, auto) lemma add_succ: "Suc (add n m) = add n (Suc m)" by(induction n, auto) lemma add_comm: "add m n = add n m" by(induction m, auto simp: add_zero add_succ) (* your definition/proof here *) text \<open> Define a recursive function \<close> fun double :: "nat \<Rightarrow> nat" where "double 0 = 0" | "double (Suc n) = Suc(Suc(double n))" (* your definition/proof here *) text \<open> and prove that \<close> lemma double_add: "double m = add m m" apply(induction m, auto) using add_succ by fastforce (* your definition/proof here *) text \<open> \endexercise \exercise Define a function that counts the number of occurrences of an element in a list: \<close> fun count :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" where "count [] x = 0" | "count (x#xs) y = count xs y + (if x = y then 1 else 0)" (* your definition/proof here *) text \<open> Test your definition of @{term count} on some examples. Prove the following inequality: \<close> theorem "count xs x \<le> length xs" by(induction xs, auto) (* your definition/proof here *) text \<open> \endexercise \exercise Define a function @{text snoc} that appends an element to the end of a list. Do not use the existing append operator @{text "@"} for lists. \<close> fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where "snoc [] v = [v]" | "snoc (x#xs) v = x # snoc xs v" (* your definition/proof here *) text \<open> Convince yourself on some test cases that your definition of @{term snoc} behaves as expected. With the help of @{text snoc} define a recursive function @{text reverse} that reverses a list. Do not use the predefined function @{const rev}. \<close> fun reverse :: "'a list \<Rightarrow> 'a list" where "reverse [] = []" | "reverse (x#xs) = snoc (reverse xs) x" (* your definition/proof here *) text \<open> Prove the following theorem. You will need an additional lemma. \<close> lemma snoc_add_last: "snoc xs v = xs @ [v]" by(induction xs, auto) lemma reverse_last_to_first: "reverse (xs@[v]) = v # reverse xs" by(induction xs, auto) theorem "reverse (reverse xs) = xs" apply(induction xs) apply auto using snoc_add_last by (metis reverse_last_to_first) (* your definition/proof here *) text \<open> \endexercise \exercise The aim of this exercise is to prove the summation formula \[ \sum_{i=0}^{n}i = \frac{n(n+1)}{2} \] Define a recursive function @{text "sum_upto n = 0 + ... + n"}: \<close> fun sum_upto :: "nat \<Rightarrow> nat" where "sum_upto 0 = 0" | "sum_upto (Suc n) = (Suc n)+sum_upto n" (* your definition/proof here *) text \<open> Now prove the summation formula by induction on @{text "n"}. First, write a clear but informal proof by hand following the examples in the main text. Then prove the same property in Isabelle: \<close> lemma "sum_upto n = n * (n+1) div 2" by(induction n, auto) (* your definition/proof here *) text \<open> \endexercise \exercise Starting from the type @{text "'a tree"} defined in the text, define a function that collects all values in a tree in a list, in any order, without removing duplicates. \<close> datatype 'a tree = Tip | Node "'a tree" 'a "'a tree" fun contents :: "'a tree \<Rightarrow> 'a list" where "contents Tip = []" | "contents (Node l v r) = v # (contents l) @ (contents r)" (* your definition/proof here *) text \<open> Then define a function that sums up all values in a tree of natural numbers \<close> fun sum_tree :: "nat tree \<Rightarrow> nat" where "sum_tree Tip = 0" | "sum_tree (Node l v r) = v + (sum_tree l) + (sum_tree r)" (* your definition/proof here *) text \<open> and prove \<close> lemma "sum_tree t = sum_list(contents t)" by(induction t, auto) (* your definition/proof here *) text \<open> \endexercise \exercise Define a new type @{text "'a tree2"} of binary trees where values are also stored in the leaves of the tree. Also reformulate the @{text mirror} function accordingly. Define two functions \<close> datatype 'a tree2 = Tip 'a | Node "'a tree2" 'a "'a tree2" fun mirror :: "'a tree2 \<Rightarrow> 'a tree2" where "mirror (Tip v) = Tip v" | "mirror (Node l v r) = Node (mirror r) v (mirror l)" fun pre_order :: "'a tree2 \<Rightarrow> 'a list" where "pre_order (Tip v) = [v]" | "pre_order (Node l v r) = v # (pre_order l) @ (pre_order r)" (* your definition/proof here *) fun post_order :: "'a tree2 \<Rightarrow> 'a list" where "post_order (Tip v) = [v]" | "post_order (Node l v r) = (post_order l) @ (post_order r) @ [v]" (* your definition/proof here *) text \<open> that traverse a tree and collect all stored values in the respective order in a list. Prove \<close> lemma "pre_order (mirror t) = rev (post_order t)" by(induction t, auto) (* your definition/proof here *) text \<open> \endexercise \exercise Define a recursive function \<close> fun intersperse :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where "intersperse a [] = [] " | "intersperse a [x] = [x]" | "intersperse a (x#xs) = x#a#(intersperse a xs)" (* your definition/proof here *) text \<open> such that @{text "intersperse a [x\<^sub>1, ..., x\<^sub>n] = [x\<^sub>1, a, x\<^sub>2, a, ..., a, x\<^sub>n]"}. Prove \<close> lemma "map f (intersperse a xs) = intersperse (f a) (map f xs)" by (induction a xs rule: intersperse.induct, auto) (* your definition/proof here *) text \<open> \endexercise \exercise Write a tail-recursive variant of the @{text add} function on @{typ nat}: \<close> fun itadd :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "itadd a 0 = a" | "itadd a (Suc b) = itadd (Suc a) b" (* your definition/proof here *) text \<open> Tail-recursive means that in the recursive case, @{const itadd} needs to call itself directly: \mbox{@{term"itadd (Suc m) n"}} @{text"= itadd \<dots>"}. Prove \<close> lemma itadd_suc_suc_itadd: "itadd (Suc m) n = Suc (itadd m n)" by(induction m n rule: itadd.induct, auto) lemma "itadd m n = add m n" apply(induction m n rule: itadd.induct, auto simp: add_zero) using add_succ itadd_suc_suc_itadd by presburger (* your definition/proof here *) text \<open> \endexercise \exercise\label{exe:tree0} Define a datatype @{text tree0} of binary tree skeletons which do not store any information, neither in the inner nodes nor in the leaves. Define a function that counts the number of all nodes (inner nodes and leaves) in such a tree: \<close> datatype tree0 = Tip | Node tree0 tree0 fun nodes :: "tree0 \<Rightarrow> nat" where "nodes Tip = 1" | "nodes (Node l r) = (nodes l) + (nodes r) + 1" (* your definition/proof here *) text \<open> Consider the following recursive function: \<close> fun explode :: "nat \<Rightarrow> tree0 \<Rightarrow> tree0" where "explode 0 t = t" | "explode (Suc n) t = explode n (Node t t)" value "explode 2 Tip" text \<open> Experiment how @{text explode} influences the size of a binary tree and find an equation expressing the size of a tree after exploding it (\noquotes{@{term [source] "nodes (explode n t)"}}) as a function of @{term "nodes t"} and @{text n}. Prove your equation. You may use the usual arithmetic operations including the exponentiation operator ``@{text"^"}''. For example, \noquotes{@{prop [source] "2 ^ 2 = 4"}}. Hint: simplifying with the list of theorems @{thm[source] algebra_simps} takes care of common algebraic properties of the arithmetic operators. \endexercise \<close> text \<open> \exercise Define arithmetic expressions in one variable over integers (type @{typ int}) as a data type: \<close> datatype exp = Var | Const int | Add exp exp | Mult exp exp text \<open> Define a function @{text eval} that evaluates an expression at some value: \<close> fun eval :: "exp \<Rightarrow> int \<Rightarrow> int" where "eval Var i = i" | "eval (Const c) i = c" | "eval (Add e1 e2) i = (eval e1 i) + (eval e2 i)" | "eval (Mult e1 e2) i = (eval e1 i) * (eval e2 i)" (* your definition/proof here *) text \<open> For example, @{prop"eval (Add (Mult (Const 2) Var) (Const 3)) i = 2*i+3"}. A polynomial can be represented as a list of coefficients, starting with the constant. For example, @{term "[4, 2, -1, 3::int]"} represents the polynomial $4 + 2x - x^2 + 3x^3$. Define a function @{text evalp} that evaluates a polynomial at a given value: \<close> fun evalp :: "int list \<Rightarrow> int \<Rightarrow> int" where "evalp [] v = 0" | "evalp (x#xs) v = x + (evalp xs v) * v" (* your definition/proof here *) text \<open> Define a function @{text coeffs} that transforms an expression into a polynomial. This will require auxiliary functions. \<close> fun multdown :: "exp \<Rightarrow> exp" where "multdown Var = Var" | "multdown (Const c) = Const c" | "multdown (Add e1 e2) = Add (multdown e1) (multdown e2)" | "multdown (Mult (Const c) (Add e1 e2)) = Add (Mult (Const c) e1) (Mult (Const c) e2)" | "multdown (Mult (Add e1 e2) (Const c)) = multdown (Mult (Const c) (Add e1 e2))" | "multdown (Mult Var (Add e1 e2)) = Add (Mult Var e1) (Mult Var e2)" | "multdown (Mult (Add e1 e2) Var) = multdown (Mult Var (Add e1 e2))" | "multdown (Mult e1 e2) = Mult (multdown e1) (multdown e2)" fun transexpr :: "exp \<Rightarrow> exp" where "transexpr Var = Var" | "transexpr (Const c) = (Const c)" | "transexpr (Mult (Add e1 e2) (Const c)) = transexpr (Mult (Const c) (Add e1 e2))" | "transexpr ((Const c) Mult (Add e1 e2)) = Add (Mult (Const c) e1) (Mult (Const c) e2)" | "transexpr (Mult Var (Add e1 e2)) = transexpr (Mult (Add e1 e2) Var)" | "transexpr (Mult (Add e1 e2) Var) = Add (Mult e1 Var) (Mult e2 Var)" fun coeffs :: "exp \<Rightarrow> int list" where (* your definition/proof here *) text \<open> Prove that @{text coeffs} preserves the value of the expression: \<close> theorem evalp_coeffs: "evalp (coeffs e) x = eval e x" (* your definition/proof here *) text \<open> Hint: consider the hint in Exercise~\ref{exe:tree0}. \endexercise \<close> end
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq. From LCAC Require Import Relations_ext seq_ext_base ssrnat_ext seq_ext. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Inductive typ := tyvar of nat | tyfun of typ & typ | tyabs of typ. Inductive term := var of nat (* variable *) | app of term & term (* value application *) | abs of typ & term (* value abstraction *) | uapp of term & typ (* universal application *) | uabs of term. (* universal abstraction *) Coercion tyvar : nat >-> typ. Coercion var : nat >-> term. Notation "ty ->t ty'" := (tyfun ty ty') (at level 55, right associativity). Notation "t @ t'" := (app t t') (at level 65, left associativity). Notation "t @' ty" := (uapp t ty) (at level 65, left associativity). Fixpoint eqtyp t1 t2 := match t1, t2 with | tyvar n, tyvar m => n == m | t1l ->t t1r, t2l ->t t2r => eqtyp t1l t2l && eqtyp t1r t2r | tyabs t1, tyabs t2 => eqtyp t1 t2 | _, _ => false end. Lemma eqtypP : Equality.axiom eqtyp. Proof. move => t1 t2; apply: (iffP idP) => [| <-]; last by elim: t1 => //= t ->. by elim: t1 t2 => [n | t1l IHt1l t1r IHt1r | t1 IHt1] [// m /eqP -> | //= t2l t2r /andP [] /IHt1l -> /IHt1r -> | // t2 /IHt1 ->]. Defined. Canonical typ_eqMixin := EqMixin eqtypP. Canonical typ_eqType := Eval hnf in EqType typ typ_eqMixin. Fixpoint eqterm t1 t2 := match t1, t2 with | var n, var m => n == m | t1l @ t1r, t2l @ t2r => eqterm t1l t2l && eqterm t1r t2r | abs ty1 t1, abs ty2 t2 => (ty1 == ty2) && eqterm t1 t2 | t1 @' ty1, t2 @' ty2 => eqterm t1 t2 && (ty1 == ty2) | uabs t1, uabs t2 => eqterm t1 t2 | _, _ => false end. Lemma eqtermP : Equality.axiom eqterm. Proof. move => t1 t2; apply: (iffP idP) => [| <-]; last by elim: t1 => //= [t -> t' -> | ty t -> | t ->] *; rewrite ?eqxx. by elim: t1 t2 => [n | t1l IHt1l t1r IHt1r | ty1 t1 IHt1 | t1 IHt1 ty1 | t1 IHt1] [// m /eqP -> | //= t2l t2r /andP [] /IHt1l -> /IHt1r -> | //= ty2 t2 /andP [] /eqP -> /IHt1 -> | //= t2 ty2 /andP [] /IHt1 -> /eqP -> | //= t2 /IHt1 ->]. Defined. Canonical term_eqMixin := EqMixin eqtermP. Canonical term_eqType := Eval hnf in EqType term term_eqMixin. Fixpoint shift_typ d c t := match t with | tyvar n => tyvar (if c <= n then n + d else n) | tl ->t tr => shift_typ d c tl ->t shift_typ d c tr | tyabs t => tyabs (shift_typ d c.+1 t) end. Notation subst_typv ts m n := (shift_typ n 0 (nth (tyvar (m - n - size ts)) ts (m - n))) (only parsing). Fixpoint subst_typ n ts t := match t with | tyvar m => if n <= m then subst_typv ts m n else m | tl ->t tr => subst_typ n ts tl ->t subst_typ n ts tr | tyabs t => tyabs (subst_typ n.+1 ts t) end. Fixpoint typemap (f : nat -> typ -> typ) n t := match t with | var m => var m | tl @ tr => typemap f n tl @ typemap f n tr | abs ty t => abs (f n ty) (typemap f n t) | t @' ty => typemap f n t @' f n ty | uabs t => uabs (typemap f n.+1 t) end. Fixpoint shift_term d c t := match t with | var n => var (if c <= n then n + d else n) | tl @ tr => shift_term d c tl @ shift_term d c tr | abs ty t => abs ty (shift_term d c.+1 t) | t @' ty => shift_term d c t @' ty | uabs t => uabs (shift_term d c t) end. Notation subst_termv ts m n n' := (typemap (shift_typ n') 0 (shift_term n 0 (nth (var (m - n - size ts)) ts (m - n)))) (only parsing). Fixpoint subst_term n n' ts t := match t with | var m => if n <= m then subst_termv ts m n n' else m | tl @ tr => subst_term n n' ts tl @ subst_term n n' ts tr | abs ty t => abs ty (subst_term n.+1 n' ts t) | t @' ty => subst_term n n' ts t @' ty | uabs t => uabs (subst_term n n'.+1 ts t) end. Reserved Notation "t ->r1 t'" (at level 70, no associativity). Inductive reduction1 : relation term := | red1fst ty t1 t2 : abs ty t1 @ t2 ->r1 subst_term 0 0 [:: t2] t1 | red1snd t ty : uabs t @' ty ->r1 typemap (subst_typ^~ [:: ty]) 0 t | red1appl t1 t1' t2 : t1 ->r1 t1' -> t1 @ t2 ->r1 t1' @ t2 | red1appr t1 t2 t2' : t2 ->r1 t2' -> t1 @ t2 ->r1 t1 @ t2' | red1abs ty t t' : t ->r1 t' -> abs ty t ->r1 abs ty t' | red1uapp t t' ty : t ->r1 t' -> t @' ty ->r1 t' @' ty | red1uabs t t' : t ->r1 t' -> uabs t ->r1 uabs t' where "t ->r1 t'" := (reduction1 t t'). Notation reduction := [* reduction1]. Infix "->r" := reduction (at level 70, no associativity). Hint Constructors reduction1. Fixpoint typing_rec (ctx : context typ) (t : term) : option typ := match t with | var n => nth None ctx n | tl @ tr => if typing_rec ctx tl is Some (tyl ->t tyr) then (if typing_rec ctx tr == Some tyl then Some tyr else None) else None | abs ty t => omap (tyfun ty) (typing_rec (Some ty :: ctx) t) | t @' ty => if typing_rec ctx t is Some (tyabs ty') then Some (subst_typ 0 [:: ty] ty') else None | uabs t => omap tyabs (typing_rec (ctxmap (shift_typ 1 0) ctx) t) end. Definition typing := nosimpl typing_rec. Notation "ctx \|- t \: ty" := (Some ty == typing ctx t) (at level 69, no associativity). Notation "ctx \|- t \: ty" := (Some (ty : typ) == typing ctx t) (at level 69, no associativity, only parsing). Lemma typing_varE ctx (n : nat) (ty : typ) : ctx \|- n \: ty = ctxindex ctx n ty. Proof. by rewrite /typing /=. Qed. Lemma typing_appP ctx t1 t2 ty : reflect (exists2 tyl, ctx \|- t1 \: tyl ->t ty & ctx \|- t2 \: tyl) (ctx \|- t1 @ t2 \: ty). Proof. apply: (iffP idP); rewrite /typing /=. - by move: (typing_rec ctx t1) => [] // [] // tyl tyr; case: ifP => // /eqP -> /eqP [] ->; exists tyl. - by case => tyl /eqP <- /eqP <-; rewrite eqxx. Qed. Lemma typing_absP ctx t tyl ty : reflect (exists2 tyr, ty = tyl ->t tyr & Some tyl :: ctx \|- t \: tyr) (ctx \|- abs tyl t \: ty). Proof. apply: (iffP idP); rewrite /typing /=. - by case: typing_rec => //= tyr /eqP [] ->; exists tyr. - by case => tyr ->; case: typing_rec => // tyr' /eqP [] <-. Qed. Lemma typing_absE ctx t tyl tyr : ctx \|- abs tyl t \: tyl ->t tyr = Some tyl :: ctx \|- t \: tyr. Proof. by rewrite /typing /=; case: typing_rec => //= tyr'; rewrite /eq_op /= /eq_op /= -/eq_op eqxx. Qed. Lemma typing_absE' ctx t tyl tyl' tyr : ctx \|- abs tyl t \: tyl' ->t tyr = (tyl == tyl') && (Some tyl :: ctx \|- t \: tyr). Proof. rewrite /typing /=; case: typing_rec => //=. - by move => tyr'; rewrite !/eq_op /= /eq_op /= -/eq_op eq_sym. - by rewrite andbF. Qed. Lemma typing_uappP ctx t ty1 ty2 : reflect (exists2 ty3, ty2 = subst_typ 0 [:: ty1] ty3 & ctx \|- t \: tyabs ty3) (ctx \|- t @' ty1 \: ty2). Proof. apply: (iffP idP); rewrite /typing /=. - by move: (typing_rec ctx t) => [] // [] // ty3 /eqP [->]; exists ty3. - by case => t3 -> /eqP <-. Qed. Lemma typing_uabsP ctx t ty : reflect (exists2 ty', ty = tyabs ty' & ctxmap (shift_typ 1 0) ctx \|- t \: ty') (ctx \|- uabs t \: ty). Proof. apply: (iffP idP); rewrite /typing /=. - by case: typing_rec => // ty' /eqP [] ->; exists ty'. - by case => ty' -> /eqP; case: typing_rec => // ty'' <-. Qed. Lemma typing_uabsE ctx t ty : ctx \|- uabs t \: tyabs ty = ctxmap (shift_typ 1 0) ctx \|- t \: ty. Proof. by rewrite /typing /=; case: typing_rec. Qed. Notation SN := (Acc (fun x y => reduction1 y x)). Definition neutral (t : term) : bool := match t with abs _ _ => false | uabs _ => false | _ => true end. Lemma inj_shift_typ d c ty ty' : (shift_typ d c ty == shift_typ d c ty') = (ty == ty'). Proof. elim: ty ty' d c => [n | tyl IHl tyr IHr | ty IH] [m | tyl' tyr' | ty'] d c //=; try by rewrite !eqE /= -!eqE ?IHl ?IHr ?IH. apply/eqP; elimif; case: ifP => H0; apply/eqP; move: H0; rewrite !eqE /= ?(eqn_add2l, eqn_add2r) //; (move => -> // || move/eqP => H; apply/eqP; ssromega). Qed. Lemma shift_zero_ty n t : shift_typ 0 n t = t. Proof. by elim: t n; congruence' => m n; rewrite addn0 if_same. Qed. Lemma shift_add_ty d c d' c' t : c <= c' <= c + d -> shift_typ d' c' (shift_typ d c t) = shift_typ (d' + d) c t. Proof. case/andP; do 2 elimleq; elim: t c; congruence' => *; elimif_omega. Qed. Lemma shift_shift_distr_ty d c d' c' t : c' <= c -> shift_typ d' c' (shift_typ d c t) = shift_typ d (d' + c) (shift_typ d' c' t). Proof. elimleq; elim: t c'; congruence' => *; elimif_omega. Qed. Lemma shift_subst_distr_ty n d c ts t : c <= n -> shift_typ d c (subst_typ n ts t) = subst_typ (d + n) ts (shift_typ d c t). Proof. elimleq; elim: t n c; congruence' => v n c; elimif; rewrite shift_add_ty; elimif_omega. Qed. Lemma subst_shift_distr_ty n d c ts t : n <= c -> shift_typ d c (subst_typ n ts t) = subst_typ n (map (shift_typ d (c - n)) ts) (shift_typ d (size ts + c) t). Proof. elimleq; elim: t n; congruence' => v n; rewrite size_map; elimif. - rewrite !nth_default ?size_map /=; elimif_omega. - rewrite -shift_shift_distr_ty // nth_map' /=. congr shift_typ; apply nth_equal; rewrite size_map; elimif_omega. Qed. Lemma subst_nil_ty n t : subst_typ n [::] t = t. Proof. elim: t n; congruence' => v n; rewrite nth_nil /=; elimif_omega. Qed. Lemma subst_shift_cancel_ty1 n d c ts t : c <= n -> subst_typ n ts (shift_typ d c t) = subst_typ n (drop (c + d - n) ts) (shift_typ (d - minn (c + d - n) (size ts)) c t). Proof. elimleq; elim: t c; congruence' => v c; rewrite size_drop nth_drop. case (leqP' d n); elimif_omega; elimleq. case (leqP' d.+1 (size ts)) => H0; elimif_omega. rewrite !nth_default //; ssromega. Qed. Lemma subst_shift_cancel_ty2 n d c ts t : c <= n -> size ts + n <= d + c -> subst_typ n ts (shift_typ d c t) = shift_typ (d - size ts) c t. Proof. move => H H0; rewrite subst_shift_cancel_ty1 ?drop_oversize ?subst_nil_ty; first congr shift_typ; ssromega. Qed. Lemma subst_shift_cancel_ty3 n d c ts t : n <= c <= n + size ts -> subst_typ n ts (shift_typ d c t) = subst_typ n (take (c - n) ts ++ drop (c + d - n) ts) (shift_typ (c + d - (n + size ts)) c t). Proof. case/andP; elimleq => H; elim: t n; congruence' => v n. rewrite size_cat size_take size_drop nth_cat nth_drop size_take (minn_idPl H); elimif_omega; congr shift_typ. - case (leqP' (c + d) (size ts)) => H0; [rewrite addn0 | rewrite !nth_default]; elimif_omega. - rewrite nth_take; elimif_omega. Qed. Lemma subst_shift_cancel_ty4 n c ts ts' t t' : c <= size ts -> subst_typ n (insert ts' ts t' c) (shift_typ (size ts') (n + c) t) = subst_typ n ts t. Proof. rewrite subst_shift_cancel_ty3 ?size_insert; last ssromega. rewrite -addnA subnDA !addKn subnDA addnK take_insert drop_insert /leq. move/eqP => -> /=; rewrite cats0 cat_take_drop (_ : _ - _ = 0) ?shift_zero_ty //; ssromega. Qed. Lemma subst_app_ty n xs ys t : subst_typ n xs (subst_typ (size xs + n) ys t) = subst_typ n (xs ++ ys) t. Proof. elim: t n; congruence' => v n; rewrite size_cat nth_cat; elimif_omega. rewrite subst_shift_cancel_ty2; elimif_omega. Qed. Lemma subst_subst_distr_ty n m xs ys t : m <= n -> subst_typ n xs (subst_typ m ys t) = subst_typ m (map (subst_typ (n - m) xs) ys) (subst_typ (size ys + n) xs t). Proof. elimleq; elim: t m; congruence' => v m; elimif_omega. - rewrite (@subst_shift_cancel_ty2 m) ?size_map 1?nth_default //=; elimif_omega. - rewrite size_map -shift_subst_distr_ty //= nth_map' /=. congr shift_typ; apply nth_equal; rewrite size_map; elimif_omega. Qed. Lemma subst_subst_compose_ty n m xs ys t : m <= size xs -> subst_typ n xs (subst_typ (n + m) ys t) = subst_typ n (insert (map (subst_typ 0 (drop m xs)) ys) xs 0 m) t. Proof. move => H; elim: t n; congruence' => v n. rewrite size_insert nth_insert size_map; elimif_omega. - by rewrite (maxn_idPr H) nth_default /= 1?addnCA ?leq_addr //= addKn addnC. - rewrite (nth_map (tyvar (v - size ys))) // shift_subst_distr_ty // addn0 subst_shift_cancel_ty1 //=; elimif_omega. Qed. Lemma typemap_compose f g n m t : typemap f n (typemap g m t) = typemap (fun i ty => f (i + n) (g (i + m) ty)) 0 t. Proof. elim: t n m => //=. - by move => tl IHtl tr IHtr n m; rewrite IHtl IHtr. - by move => ty t IHt n m; rewrite IHt. - by move => t IHt ty n m; rewrite IHt. - move => t IHt n m; rewrite {}IHt; congr uabs; elim: t 0 => //; congruence'. Qed. Lemma typemap_eq' f g n m t : (forall o t, f (o + n) t = g (o + m) t) -> typemap f n t = typemap g m t. Proof. move => H; elim: t n m H => //=. - move => tl IHtl tr IHtr n m H; congr app; auto; apply (H 0). - by move => ty t IHt n m H; congr abs; auto; rewrite -(add0n n) -(add0n m). - by move => t IHt ty n m H; congr uapp; auto; apply (H 0). - by move => t IHt n m H; congr uabs; apply IHt => o ty; rewrite -!addSnnS. Qed. Lemma typemap_eq f g n t : (forall n t, f n t = g n t) -> typemap f n t = typemap g n t. Proof. move => H; apply typemap_eq' => {t} o; apply H. Qed. Lemma shifttyp_zero c t : typemap (shift_typ 0) c t = t. Proof. elim: t c => /=; move: shift_zero_ty; congruence. Qed. Lemma shifttyp_add d c d' c' t : c <= c' <= c + d -> typemap (shift_typ d') c' (typemap (shift_typ d) c t) = typemap (shift_typ (d' + d)) c t. Proof. rewrite typemap_compose => H; apply typemap_eq' => {t} n t. by rewrite addn0 shift_add_ty // -addnA !leq_add2l. Qed. Lemma shifttyp_shifttyp_distr d c d' c' t : c' <= c -> typemap (shift_typ d') c' (typemap (shift_typ d) c t) = typemap (shift_typ d) (d' + c) (typemap (shift_typ d') c' t). Proof. rewrite !typemap_compose => H; apply typemap_eq => {t} n t. by rewrite shift_shift_distr_ty ?leq_add2l // addnCA. Qed. Lemma shifttyp_substtyp_distr n d c ts t : c <= n -> typemap (shift_typ d) c (typemap (subst_typ^~ ts) n t) = typemap (subst_typ^~ ts) (d + n) (typemap (shift_typ d) c t). Proof. rewrite !typemap_compose => H; apply typemap_eq => {t} n' t. by rewrite shift_subst_distr_ty ?leq_add2l // addnCA. Qed. Lemma substtyp_shifttyp_distr n d c ts t : n <= c -> typemap (shift_typ d) c (typemap (subst_typ^~ ts) n t) = typemap (subst_typ^~ (map (shift_typ d (c - n)) ts)) n (typemap (shift_typ d) (size ts + c) t). Proof. rewrite !typemap_compose => H; apply typemap_eq => {t} n' t. by rewrite subst_shift_distr_ty ?leq_add2l // subnDl addnCA addnA. Qed. Lemma substtyp_substtyp_distr n m xs ys t : m <= n -> typemap (subst_typ^~ xs) n (typemap (subst_typ^~ ys) m t) = typemap (subst_typ^~ (map (subst_typ (n - m) xs) ys)) m (typemap (subst_typ^~ xs) (size ys + n) t). Proof. rewrite !typemap_compose => H; apply typemap_eq => {t} n' t. by rewrite subst_subst_distr_ty ?leq_add2l // subnDl addnCA addnA. Qed. Lemma shift_typemap_distr f d c n t : shift_term d c (typemap f n t) = typemap f n (shift_term d c t). Proof. elim: t c n => /=; congruence. Qed. Lemma subst_shifttyp_distr n m d c ts t : c + d <= m -> subst_term n m ts (typemap (shift_typ d) c t) = typemap (shift_typ d) c (subst_term n (m - d) ts t). Proof. elimleq; elim: t n c; congruence' => v n c; elimif_omega. rewrite -!shift_typemap_distr shifttyp_add; elimif_omega. Qed. Lemma shifttyp_subst_distr d c n m ts t : m <= c -> typemap (shift_typ d) c (subst_term n m ts t) = subst_term n m (map (typemap (shift_typ d) (c - m)) ts) (typemap (shift_typ d) c t). Proof. by elimleq; elim: t n m; congruence' => v n m; elimif_omega; rewrite size_map -!shift_typemap_distr -shifttyp_shifttyp_distr // nth_map'. Qed. Lemma subst_substtyp_distr n m m' tys ts t : m' <= m -> subst_term n m ts (typemap (subst_typ^~ tys) m' t) = typemap (subst_typ^~ tys) m' (subst_term n (size tys + m) ts t). Proof. elimleq; elim: t n m'; congruence' => v n m'; elimif_omega. rewrite -!shift_typemap_distr typemap_compose. congr shift_term; apply typemap_eq => {v n ts} n t. rewrite subst_shift_cancel_ty2; first congr shift_typ; ssromega. Qed. Lemma substtyp_subst_distr n m m' tys ts t : m <= m' -> typemap (subst_typ^~ tys) m' (subst_term n m ts t) = subst_term n m (map (typemap (subst_typ^~ tys) (m' - m)) ts) (typemap (subst_typ^~ tys) m' t). Proof. elimleq; elim: t n m; congruence' => v n m; elimif_omega. by rewrite size_map -!shift_typemap_distr -shifttyp_substtyp_distr // (nth_map' (typemap _ _)). Qed. Lemma shift_zero n t : shift_term 0 n t = t. Proof. by elim: t n => /=; congruence' => m n; rewrite addn0 if_same. Qed. Lemma shift_add d c d' c' t : c <= c' <= c + d -> shift_term d' c' (shift_term d c t) = shift_term (d' + d) c t. Proof. case/andP; do 2 elimleq; elim: t c; congruence' => *; elimif_omega. Qed. Lemma shift_shift_distr d c d' c' t : c' <= c -> shift_term d' c' (shift_term d c t) = shift_term d (d' + c) (shift_term d' c' t). Proof. elimleq; elim: t c'; congruence' => v c'; elimif_omega. Qed. Lemma subst_shift_distr n m d c ts t : n <= c -> shift_term d c (subst_term n m ts t) = subst_term n m (map (shift_term d (c - n)) ts) (shift_term d (size ts + c) t). Proof. elimleq; elim: t n m; congruence' => v n m; rewrite size_map; elimif_omega. - rewrite !nth_default ?size_map /=; elimif_omega. - rewrite shift_typemap_distr -shift_shift_distr // nth_map' /=. congr (typemap _ _ (shift_term _ _ _)); apply nth_equal; rewrite size_map; elimif_omega. Qed. Lemma shift_subst_distr n m d c ts t : c <= n -> shift_term d c (subst_term n m ts t) = subst_term (d + n) m ts (shift_term d c t). Proof. elimleq; elim: t m c; congruence' => v m c; elimif_omega. rewrite shift_typemap_distr shift_add; elimif_omega. Qed. Lemma subst_shift_cancel n m d c ts t : c <= n -> size ts + n <= d + c -> subst_term n m ts (shift_term d c t) = shift_term (d - size ts) c t. Proof. do 2 elimleq; elim: t m c; congruence' => v m c; elimif_omega. rewrite nth_default /=; first congr var; ssromega. Qed. Lemma subst_subst_distr n n' m m' xs ys t : n' <= n -> m' <= m -> subst_term n m xs (subst_term n' m' ys t) = subst_term n' m' (map (subst_term (n - n') (m - m') xs) ys) (subst_term (size ys + n) m xs t). Proof. do 2 elimleq; elim: t n' m'; congruence' => v n' m'; elimif_omega. - rewrite nth_default /=; elimif_omega. rewrite -!shift_typemap_distr (@subst_shift_cancel n') // size_map; elimif_omega. - rewrite -!shift_typemap_distr -shift_subst_distr // subst_shifttyp_distr; elimif_omega. rewrite nth_map' /=; congr (shift_term _ _ (typemap _ _ _)); apply nth_equal; rewrite !size_map; elimif_omega. Qed. Lemma subst_app n m xs ys t : subst_term n m xs (subst_term (size xs + n) m ys t) = subst_term n m (xs ++ ys) t. Proof. elim: t n m; congruence' => v n m; rewrite nth_cat size_cat; elimif_omega. rewrite -!shift_typemap_distr subst_shift_cancel; elimif_omega. Qed. Lemma subst_nil n m t : subst_term n m [::] t = t. Proof. elim: t n m; congruence' => v n m; rewrite nth_nil /= -fun_if; elimif_omega. Qed. Lemma subst_shifttyp_app n m m' ts t : subst_term n m (map (typemap (shift_typ m') 0) ts) t = subst_term n (m' + m) ts t. Proof. elim: t n m; congruence' => v n m; rewrite size_map; elimif_omega. rewrite -!shift_typemap_distr !(nth_map' (typemap _ _)) /=. congr (shift_term _ _ (nth _ _ _)); elim: ts => //= t ts ->; congr cons. rewrite typemap_compose; apply typemap_eq => {n t ts} n t. rewrite addn0 shift_add_ty; elimif_omega. Qed. Lemma redappl t1 t1' t2 : t1 ->r t1' -> t1 @ t2 ->r t1' @ t2. Proof. apply (rtc_map' (fun x y => @red1appl x y t2)). Qed. Lemma redappr t1 t2 t2' : t2 ->r t2' -> t1 @ t2 ->r t1 @ t2'. Proof. apply (rtc_map' (@red1appr t1)). Qed. Lemma redapp t1 t1' t2 t2' : t1 ->r t1' -> t2 ->r t2' -> t1 @ t2 ->r t1' @ t2'. Proof. by move => H H0; eapply rtc_trans with (t1' @ t2); [apply redappl | apply redappr]. Qed. Lemma redabs ty t t' : t ->r t' -> abs ty t ->r abs ty t'. Proof. apply (rtc_map' (red1abs ty)). Qed. Lemma reduapp t t' ty : t ->r t' -> t @' ty ->r t' @' ty. Proof. apply (rtc_map' (fun x y => @red1uapp x y ty)). Qed. Lemma reduabs t t' : t ->r t' -> uabs t ->r uabs t'. Proof. apply (rtc_map' red1uabs). Qed. Hint Resolve redappl redappr redapp redabs reduapp reduabs. Lemma shifttyp_reduction1 t t' d c : t ->r1 t' -> typemap (shift_typ d) c t ->r1 typemap (shift_typ d) c t'. Proof. move => H; elim/reduction1_ind: t t' / H d c => /=; try by constructor. - by move => ty t1 t2 d c; rewrite shifttyp_subst_distr //= subn0. - by move => t ty d c; rewrite substtyp_shifttyp_distr //= subn0. Qed. Lemma shift_reduction1 t t' d c : t ->r1 t' -> shift_term d c t ->r1 shift_term d c t'. Proof. move => H; elim/reduction1_ind: t t' / H d c => /=; try by constructor. - by move => ty t1 t2 d c; rewrite subst_shift_distr //= subn0. - by move => t ty d c; rewrite shift_typemap_distr. Qed. Lemma substtyp_reduction1 t t' tys n : t ->r1 t' -> typemap (subst_typ^~ tys) n t ->r1 typemap (subst_typ^~ tys) n t'. Proof. move => H; elim/reduction1_ind: t t' / H tys n => /=; try by constructor. - by move => ty t1 t2 tys n; rewrite substtyp_subst_distr // subn0; constructor. - by move => t ty tys n; rewrite substtyp_substtyp_distr //= subn0. Qed. Lemma subst_reduction1 t t' n m ts : t ->r1 t' -> subst_term n m ts t ->r1 subst_term n m ts t'. Proof. move => H; elim/reduction1_ind: t t' / H n m ts => /=; try by constructor. - by move => ty t1 t2 n m ts; rewrite subst_subst_distr //= !subn0. - by move => t ty n m ts; rewrite subst_substtyp_distr. Qed. Lemma subst_reduction t n m ts : Forall (fun t => t.1 ->r t.2) ts -> subst_term n m (unzip1 ts) t ->r subst_term n m (unzip2 ts) t. Proof. move => H; elim: t n m => //=; auto => v n m; rewrite !size_map; elimif_omega. elim: ts v H => //= [[t t']] ts IH [[H _] | v] //=. - move: H. apply (rtc_map' (f := fun x => typemap (shift_typ m) 0 (shift_term n 0 x))) => t1 t2 H. by apply shifttyp_reduction1, shift_reduction1. - by case => _ H; rewrite subSS; apply IH. Qed. Module confluence_proof. Reserved Notation "t ->rp t'" (at level 70, no associativity). Inductive parred : relation term := | parredfst ty t1 t1' t2 t2' : t1 ->rp t1' -> t2 ->rp t2' -> abs ty t1 @ t2 ->rp subst_term 0 0 [:: t2'] t1' | parredsnd t t' ty : t ->rp t' -> uabs t @' ty ->rp typemap (subst_typ^~ [:: ty]) 0 t' | parredvar n : var n ->rp var n | parredapp t1 t1' t2 t2' : t1 ->rp t1' -> t2 ->rp t2' -> t1 @ t2 ->rp t1' @ t2' | parredabs ty t t' : t ->rp t' -> abs ty t ->rp abs ty t' | parreduapp t t' ty : t ->rp t' -> t @' ty ->rp t' @' ty | parreduabs t t' : t ->rp t' -> uabs t ->rp uabs t' where "t ->rp t'" := (parred t t'). Fixpoint reduce_all_redex t : term := match t with | var _ => t | abs ty t1 @ t2 => subst_term 0 0 [:: reduce_all_redex t2] (reduce_all_redex t1) | t1 @ t2 => reduce_all_redex t1 @ reduce_all_redex t2 | abs ty t' => abs ty (reduce_all_redex t') | uabs t @' ty => typemap (subst_typ^~ [:: ty]) 0 (reduce_all_redex t) | t @' ty => reduce_all_redex t @' ty | uabs t => uabs (reduce_all_redex t) end. Lemma parred_refl t : parred t t. Proof. by elim: t; constructor. Qed. Hint Constructors parred. Hint Resolve parred_refl. Lemma betared1_in_parred : inclusion reduction1 parred. Proof. by apply reduction1_ind; constructor. Qed. Lemma parred_in_betared : inclusion parred reduction. Proof. apply parred_ind => //; auto. - move => ty t1 t1' t2 t2' H H0 H1 H2. apply rtc_trans with (abs ty t1' @ t2); auto. apply rtc_trans with (abs ty t1' @ t2'); auto. by apply rtc_step. - move => t t' ty H H0. apply rtc_trans with (uabs t' @' ty); auto. by apply rtc_step. Qed. Lemma shift_parred t t' d c : t ->rp t' -> shift_term d c t ->rp shift_term d c t'. Proof. move => H; elim/parred_ind: t t' / H d c => //=; auto. - by move => t1 t1' t2 t2' ty H H0 H1 H2 d c; rewrite subst_shift_distr //= subn0; auto. - by move => t t' ty H H0 d c; rewrite shift_typemap_distr; auto. Qed. Lemma shifttyp_parred t t' d c : t ->rp t' -> typemap (shift_typ d) c t ->rp typemap (shift_typ d) c t'. Proof. move => H; elim/parred_ind: t t' / H d c => /=; auto. - by move => t1 t1' t2 t2' ty H H0 H1 H2 d c; rewrite shifttyp_subst_distr //= subn0; auto. - by move => t t' ty H H0 n m; rewrite substtyp_shifttyp_distr //= subn0; auto. Qed. Lemma substtyp_parred n tys t t' : t ->rp t' -> typemap (subst_typ^~ tys) n t ->rp typemap (subst_typ^~ tys) n t'. Proof. move => H; elim/parred_ind: t t' / H n => /=; auto. - by move => t1 t1' t2 t2' ty H H0 H1 H2 n; rewrite substtyp_subst_distr //= subn0; auto. - by move => t t' ty H H0 n; rewrite substtyp_substtyp_distr //= subn0; auto. Qed. Lemma subst_parred n m ps t t' : Forall (prod_curry parred) ps -> t ->rp t' -> subst_term n m (unzip1 ps) t ->rp subst_term n m (unzip2 ps) t'. Proof. move => H H0; elim/parred_ind: t t' / H0 n m => /=; auto. - by move => tl tl' tr tr' ty H0 H1 H2 H3 n m; rewrite subst_subst_distr //= !subn0; auto. - by move => t t' ty H0 H1 n m; rewrite subst_substtyp_distr //=; auto. - move => v n m; rewrite !size_map; case: ifP => //; elimleq. elim: ps H v => //= [[t t']] ts IH [H H0] [| v] //=. - by apply shifttyp_parred, shift_parred. - by rewrite subSS; apply IH. Qed. Lemma parred_all_lemma t t' : t ->rp t' -> t' ->rp reduce_all_redex t. Proof with auto. move: t t'; fix IH 3 => t t' H; inversion H; subst => {H} /=... - apply (@subst_parred 0 0 [:: (t2', reduce_all_redex t2)]) => /=... - exact/substtyp_parred/IH. - destruct t1; auto; inversion H0... - destruct t0; auto; inversion H0... Qed. Lemma parred_confluent : confluent parred. Proof. by move => t1 t2 t3 H H0; exists (reduce_all_redex t1); apply parred_all_lemma. Qed. Theorem betared_confluent : confluent reduction. Proof. apply (rtc_confluent' betared1_in_parred parred_in_betared parred_confluent). Qed. End confluence_proof. Module subject_reduction_proof. Lemma ctxleq_preserves_typing ctx1 ctx2 t ty : ctx1 <=c ctx2 -> ctx1 \|- t \: ty -> ctx2 \|- t \: ty. Proof. elim: t ty ctx1 ctx2 => [n | tl IHtl tr IHtr | tyl t IHt | t IHt tyr | t IHt] ty ctx1 ctx2. - move/ctxleqP; apply. - by move => H /typing_appP [tyl H0 H1]; apply/typing_appP; exists tyl; [apply (IHtl _ ctx1) | apply (IHtr _ ctx1)]. - by move => H /typing_absP [tyr -> H0]; rewrite typing_absE; move: H0; apply IHt; rewrite ctxleqE eqxx. - by move => H /typing_uappP [tyl -> H0]; apply/typing_uappP; exists tyl => //; move: H0; apply IHt. - by move => H /typing_uabsP [ty' -> H0]; rewrite typing_uabsE; move: H0; apply IHt, ctxleq_map. Qed. Lemma typing_shifttyp d c ctx t : typing (ctxmap (shift_typ d c) ctx) (typemap (shift_typ d) c t) = omap (shift_typ d c) (typing ctx t). Proof. rewrite /typing. elim: t d c ctx => /= [n | tl IHtl tr IHtr | ty t IHt | t IHt ty | t IHt] d c ctx. - by rewrite (nth_map' (omap _)) /=. - rewrite IHtl /=; move: (typing_rec ctx tl) => [] // [] //= tyl tyr. by rewrite IHtr; case: typing_rec => //= tyl'; rewrite !eqE /= inj_shift_typ; case: ifP. - by move: (IHt d c (Some ty :: ctx)) => /= ->; case: typing_rec. - rewrite IHt; move: (typing_rec ctx t) => [] // [] //= t'. by rewrite subst_shift_distr_ty //= subn0. - have H ty: omap (shift_typ d c) (omap tyabs ty) = omap tyabs (omap (shift_typ d c.+1) ty) by case: ty. by rewrite {}H -IHt; congr (omap tyabs (typing_rec _ _)); rewrite -!map_comp; apply eq_map; case => //= ty'; rewrite shift_shift_distr_ty. Qed. Lemma substtyp_preserves_typing n tys ctx t ty : ctx \|- t \: ty -> ctxmap (subst_typ n tys) ctx \|- typemap (subst_typ^~ tys) n t \: subst_typ n tys ty. Proof. elim: t ty n ctx => [m | tl IHtl tr IHtr | tyl t IHt | t IHt tyr | t IHt] ty n ctx /=. - by apply ctxindex_map. - by case/typing_appP => tyl H H0; apply/typing_appP; exists (subst_typ n tys tyl); [apply (IHtl (tyl ->t ty)) | apply IHtr]. - by case/typing_absP => tyr -> H; rewrite /= typing_absE; move: H; apply IHt. - case/typing_uappP => tyl -> H; apply/typing_uappP; exists (subst_typ n.+1 tys tyl). + by rewrite subst_subst_distr_ty //= subn0. + by move: H; apply IHt. - case/typing_uabsP => ty' -> H; rewrite /= typing_uabsE. suff ->: ctxmap (shift_typ 1 0) (ctxmap (subst_typ n tys) ctx) = ctxmap (subst_typ n.+1 tys) (ctxmap (shift_typ 1 0) ctx) by apply IHt. by rewrite -!map_comp; apply eq_map; case => //= ty''; rewrite shift_subst_distr_ty. Qed. Lemma typing_shift t c ctx1 ctx2 : typing (ctxinsert ctx2 ctx1 c) (shift_term (size ctx2) c t) = typing ctx1 t. Proof. rewrite /typing; elim: t c ctx1 ctx2 => /= [n | tl IHtl tr IHtr | tyl t IHt | t IHt tyr | t IHt] c ctx1 ctx2. - rewrite nth_insert; elimif_omega. - by rewrite IHtl IHtr. - by rewrite -(IHt c.+1 _ ctx2). - by rewrite IHt. - by rewrite map_insert /= -(size_map (omap (shift_typ 1 0)) ctx2) IHt. Qed. Lemma subject_subst t ty n m ctx ctx' : all (fun p => drop n ctx \|- typemap (shift_typ m) 0 p.1 \: p.2) ctx' -> ctxinsert [seq Some p.2 | p <- ctx'] ctx n \|- t \: ty -> ctx \|- subst_term n m (unzip1 ctx') t \: ty. Proof. elim: t ty n m ctx ctx' => [v | tl IHtl tr IHtr | tyl t IHt | t IHt tyr | t IHt] ty n m ctx ctx' H. - rewrite /typing /= nth_insert !size_map => /eqP ->; elimif. + apply/eqP/esym; rewrite nth_default ?size_map /=; elimif_omega. + rewrite -/typing !(nth_map (var 0, tyvar 0)) //. case: {ty v H0} (nth _ _ _) (all_nthP (var 0, tyvar 0) H v H0) => t ty. rewrite /= -(typing_shift _ 0 _ (ctxinsert [::] (take n ctx) n)) size_insert size_take minnC minKn add0n shift_typemap_distr. apply ctxleq_preserves_typing. rewrite /insert take0 sub0n take_minn minnn size_take minnE subKn ?leq_subr //= drop_take_nil cats0 drop0 -catA -{4}(cat_take_drop n ctx) ctxleq_appl. by case (leqP' n (size ctx)) => //= H0; rewrite drop_oversize ?(ltnW H0) //= cats0; apply/ctxleqP => /= i ty' /eqP; rewrite nth_nseq if_same. - by case/typing_appP => /= tyl H0 H1; apply/typing_appP; exists tyl; auto. - by case/typing_absP => /= tyr -> H0; rewrite typing_absE; apply IHt. - by case/typing_uappP => /= tyl -> H0; apply/typing_uappP; exists tyl; auto. - case/typing_uabsP => /= ty' -> H0; rewrite typing_uabsE -(addn0 m.+1) -subst_shifttyp_app. set ctx'' := (map _ (map _ _)). have {ctx''} ->: ctx'' = unzip1 [seq (typemap (shift_typ m.+1) 0 p.1, shift_typ 1 0 p.2) | p <- ctx'] by rewrite /unzip1 /ctx'' -!map_comp /comp /=. apply IHt. + move: H {t ty IHt H0}; rewrite all_map; apply sub_all. rewrite /subpred /preim /pred_of_simpl; case => /= t ty. by rewrite -map_drop shifttyp_zero -(@shifttyp_add m _ 1 0) // typing_shifttyp; case: typing => // ty'' /eqP [] <-. + by move: H0; rewrite map_insert -!map_comp. Qed. Lemma subject_subst0 t ty ctx ctx' : all (fun p => ctx \|- p.1 \: p.2) ctx' -> [seq Some p.2 | p <- ctx'] ++ ctx \|- t \: ty -> ctx \|- subst_term 0 0 (unzip1 ctx') t \: ty. Proof. move => H; move: (@subject_subst t ty 0 0 ctx ctx'); rewrite /insert take0 sub0n drop0 /=; apply; move: H. by apply sub_all; case => t' ty' /=; rewrite shifttyp_zero. Qed. Lemma subject_subst0' ctx tyl tyr t t' : Some tyl :: ctx \|- t \: tyr -> ctx \|- t' \: tyl -> ctx \|- subst_term 0 0 [:: t'] t \: tyr. Proof. by move => H H0; apply (@subject_subst0 _ _ _ [:: (t', tyl)]); rewrite //= andbT. Qed. Theorem subject_reduction ctx t t' ty : t ->r1 t' -> ctx \|- t \: ty -> ctx \|- t' \: ty. Proof. move => H; elim/reduction1_ind: t t' / H ctx ty => /=. - by move => tyl t1 t2 ctx ty /typing_appP [tyl']; rewrite typing_absE' => /andP [] /eqP <- H H0; apply (subject_subst0' H). - move => t tyr ctx ty /typing_uappP [tyl] ->; rewrite typing_uabsE. move/(substtyp_preserves_typing 0 [:: tyr]). set ctx' := ctxmap _ _; have {ctx'} -> //: ctx' = ctx. rewrite {}/ctx' -map_comp -{2}(map_id ctx). apply eq_map; case => //= ty'. by rewrite subst_shift_cancel_ty2 //= shift_zero_ty. - by move => t1 t1' t2 H H0 ctx ty /typing_appP [tyl H1 H2]; apply/typing_appP; exists tyl; auto. - by move => t1 t2 t2' H H0 ctx ty /typing_appP [tyl H1 H2]; apply/typing_appP; exists tyl; auto. - by move => tyl t t' H H0 ctx ty /typing_absP [tyr -> H1]; rewrite typing_absE; auto. - by move => t t' tyr H H0 ctx ty /typing_uappP [tyl -> H1]; apply/typing_uappP; exists tyl; auto. - by move => t t' H H0 ctx ty /typing_uabsP [ty' -> H1]; rewrite typing_uabsE; auto. Qed. End subject_reduction_proof. Module strong_normalization_proof_typefree. Section CRs. Variable (P : term -> Prop). Definition CR1 := forall t, P t -> SN t. Definition CR2 := forall t t', t ->r1 t' -> P t -> P t'. Definition CR3 := forall t, neutral t -> (forall t', t ->r1 t' -> P t') -> P t. Record RC : Prop := reducibility_candidate { rc_cr1 : CR1 ; rc_cr2 : CR2 ; rc_cr3 : CR3 }. End CRs. Lemma CR2' P t t' : RC P -> t ->r t' -> P t -> P t'. Proof. move => H; elim/clos_refl_trans_1n_ind: t t' / => //= x y z H0 _ H1 H2. by apply H1, (rc_cr2 H H0). Qed. Lemma CR4 P t : RC P -> neutral t -> (forall t', ~ t ->r1 t') -> P t. Proof. by move/rc_cr3 => H H0 H1; apply H => // t' /H1. Qed. Lemma CR4' P (v : nat) : RC P -> P v. Proof. by move/CR4; apply => // t' H; inversion H. Qed. Lemma snorm_isrc : RC SN. Proof. constructor; move => /=; try tauto. - by move => t t' H []; apply. - by move => t H H0; constructor => t' H1; apply H0. Qed. Lemma rcfun_isrc P Q : RC P -> RC Q -> RC (fun u => forall v, P v -> Q (u @ v)). Proof. move => H H0; constructor; move => /=. - by move => t /(_ 0 (CR4' _ H)) /(rc_cr1 H0); apply (acc_preservation (f := app^~_)); constructor. - by move => t t' H1 H2 v /H2; apply (rc_cr2 H0); constructor. - move => t1 H1 H2 t2 H3. elim/Acc_ind': t2 / {H3} (rc_cr1 H H3) (H3) => t2 H3 H4. apply (rc_cr3 H0) => //= t3 H5; move: H1; inversion H5; subst => //= _; auto; apply H3 => //; apply (rc_cr2 H H8 H4). Qed. Fixpoint reducible ty (preds : seq (term -> Prop)) : term -> Prop := match ty with | tyvar v => nth SN preds v | tyfun tyl tyr => fun t => forall t', reducible tyl preds t' -> reducible tyr preds (t @ t') | tyabs ty => fun t => forall ty' P, RC P -> reducible ty (P :: preds) (t @' ty') end. Lemma reducibility_isrc ty preds : Forall RC preds -> RC (reducible ty preds). Proof. elim: ty preds => /= [n | tyl IHl tyr IHr | ty IH] preds. - move/Forall_nth /(_ _ n); case: (ltnP n (size preds)). + by move => _; apply. + by move => H _; rewrite (nth_default _ H); apply snorm_isrc. - by move => H; apply rcfun_isrc; [apply IHl | apply IHr]. - move => H; constructor. + move => /= t /(_ 0 SN snorm_isrc) /(rc_cr1 (IH (_ :: _) (conj snorm_isrc H))). by apply (acc_preservation (f := uapp^~_)) => x y H0; constructor. + move => /= t t' H0 H1 ty' P H2; move: (H1 ty' _ H2). by apply (rc_cr2 (IH (_ :: _) (conj H2 H))); constructor. + move => /= t H0 H1 ty' P H2. apply (rc_cr3 (IH (_ :: _) (conj H2 H))) => //= t' H3. by move: H0; inversion H3; subst => //= _; apply H1. Qed. Lemma shift_reducibility c ty preds preds' t : c <= size preds -> (reducible (shift_typ (size preds') c ty) (insert preds' preds SN c) t <-> reducible ty preds t). Proof. elim: ty c preds t => [v | tyl IHl tyr IHr | ty IH] c preds t H. - rewrite /= nth_insert; elimif_omega. - by split => /= H0 t' /(IHl c _ _ H) /H0 /(IHr c _ _ H). - by split => H0 ty' P H1; apply (IH c.+1 (P :: preds)) => //; apply H0. Qed. Lemma subst_reducibility ty preds n tys t : n <= size preds -> (reducible (subst_typ n tys ty) preds t <-> reducible ty (insert [seq reducible ty (drop n preds) | ty <- tys] preds SN n) t). Proof. elim: ty preds n tys t => [v | tyl IHl tyr IHr | ty IH] preds n tys t. - rewrite /= nth_insert size_map; elimif_omega. + by rewrite nth_default ?leq_addr //= addnC. + move => H0. rewrite (nth_map (tyvar (v - size tys))) //=. move: (shift_reducibility (nth (tyvar (v - size tys)) tys v) (take n preds) t (leq0n (size (drop n preds)))). by rewrite /insert take0 drop0 /= cat_take_drop size_takel. - by move => H /=; split => H0 t' /IHl => /(_ H) /H0 /IHr => /(_ H). - move => H /=; split => H0 ty' P /(H0 ty') {H0}. + by move/IH => /= /(_ H); rewrite /insert /= subSS. + by move => H0; apply IH. Qed. Lemma abs_reducibility t tyl tyr tys preds : Forall RC preds -> (forall t', reducible tyl preds t' -> reducible tyr preds (subst_term 0 0 [:: t'] t)) -> reducible (tyl ->t tyr) preds (abs (subst_typ 0 tys tyl) t). Proof. move => /= H. move: (reducible tyl preds) (reducible tyr preds) (reducibility_isrc tyl H) (reducibility_isrc tyr H) => {H} P Q HP HQ H t' H0. have H1: SN t by move: (rc_cr1 HQ (H _ H0)); apply acc_preservation => x y; apply subst_reduction1. move: t t' {H H0} H1 (rc_cr1 HP H0) (H0) (H _ H0); refine (Acc_ind2 _) => t t' IHt IHt' H H0. apply rc_cr3 => // t'' H1; inversion H1; subst => //. - by inversion H5; subst; apply IHt => //; apply (rc_cr2 HQ (subst_reduction1 0 0 [:: t'] H6)). - apply IHt' => //; first by apply (rc_cr2 HP H5). move: H0; apply (CR2' HQ). by apply (@subst_reduction t 0 0 [:: (t', t2')]) => /=; intuition apply rtc_step. Qed. Lemma uabs_reducibility t ty preds : Forall RC preds -> (forall v P, RC P -> reducible ty (P :: preds) (typemap (subst_typ^~ [:: v]) 0 t)) -> reducible (tyabs ty) preds (uabs t). Proof. move => /= H H0 ty' P H1. move: (reducible _ _) (@reducibility_isrc ty (P :: preds)) (H0 ty' P H1) => P' /= /(_ (conj H1 H)) {H H0 H1} H H0. have H1: SN t by move: (rc_cr1 H H0); apply acc_preservation => x y; apply substtyp_reduction1. elim/Acc_ind': t / H1 H0 => t H0 H1. apply (rc_cr3 H) => //= t' H2; inversion H2; subst => //. inversion H6; subst; apply H0 => //. apply (rc_cr2 H (substtyp_reduction1 _ _ H4) H1). Qed. Lemma uapp_reducibility t ty ty' tys preds : Forall RC preds -> reducible (tyabs ty) preds t -> reducible (subst_typ 0 [:: ty'] ty) preds (t @' subst_typ 0 tys ty'). Proof. move => /= H H0. apply subst_reducibility => //=. rewrite /insert take0 sub0n !drop0 /=. by apply H0, reducibility_isrc. Qed. Lemma reduce_lemma ctx preds t ty : [seq Some c.2 | c <- ctx] \|- t \: ty -> Forall RC (unzip2 preds) -> Forall (fun c => reducible c.2 (unzip2 preds) c.1) ctx -> reducible ty (unzip2 preds) (subst_term 0 0 (unzip1 ctx) (typemap (subst_typ^~ (unzip1 preds)) 0 t)). Proof. elim: t ty ctx preds => /=. - move => v ty ctx preds H H0 H1. rewrite shifttyp_zero shift_zero subn0 size_map. elim: ctx v H H1 => //=; first by case. case => t ty' ctx IH [] //=. + by case/eqP => <- []. + by move => v H [H1 H2]; rewrite subSS; apply IH. - move => tl IHtl tr IHtr ty ctx preds /typing_appP [tyl H H0] H1 H2. by move: (IHtl (tyl ->t ty) ctx preds H H1 H2) => /=; apply; apply IHtr. - move => tyl t IHt ty ctx preds /typing_absP [tyr -> H] H0 H1. apply abs_reducibility => // t' H2. by rewrite subst_app //=; apply (IHt tyr ((t', tyl) :: ctx)). - move => t IHt tyr ty ctx preds /typing_uappP [tyl -> H] H0 H1. by apply uapp_reducibility => //; apply IHt. - move => t IHt ty ctx preds /typing_uabsP [ty' ->]; rewrite -map_comp /comp /= => H H0 H1. apply uabs_reducibility => // v P H2. rewrite -(subst_substtyp_distr 0 [:: v]) // typemap_compose /=. have /(typemap_eq 0 t) -> : forall i ty, subst_typ (i + 0) [:: v] (subst_typ (i + 1) (unzip1 preds) ty) = subst_typ i (v :: unzip1 preds) ty by move => i ty''; rewrite addn0 addn1 subst_app_ty. move: (IHt ty' [seq (c.1, shift_typ 1 0 c.2) | c <- ctx] ((v, P) :: preds)). rewrite /unzip1 -!map_comp /comp /=; apply => //=. apply Forall_map; move: H1; rewrite /comp /=; apply Forall_impl => {t ty IHt H H0 H2} [[t ty]] /= /(proj2 (shift_reducibility ty [:: P] t (leq0n _))). by rewrite /insert take0 drop0 sub0n /=; apply. Qed. Theorem typed_term_is_snorm ctx t ty : ctx \|- t \: ty -> SN t. Proof. move => H. move: (@reduce_lemma (map (oapp (pair (var 0)) (var 0, tyvar 0)) ctx) [::] t ty) => /=. rewrite -map_comp /comp /=. have {H} H: [seq Some (oapp (pair (var 0)) (var 0, tyvar 0) c).2 | c <- ctx] \|- t \: ty by move: H; apply subject_reduction_proof.ctxleq_preserves_typing; elim: ctx {t ty} => //; case => // ty ctx H; rewrite ctxleqE eqxx /=. move/(_ H I) {H}. have H: Forall (fun c => reducible c.2 [::] c.1) (map (oapp (pair (var 0)) (var 0, tyvar 0)) ctx) by apply Forall_map, Forall_nth => /= x m _; rewrite /oapp /snd; case: nth => [ty' |]; apply CR4', reducibility_isrc. move/(_ H) => {H} /(rc_cr1 (reducibility_isrc _ _)) /= /(_ I). set f := subst_term _ _ _; set g := typemap _ _. apply (acc_preservation (f := f \o g)) => x y H. by apply subst_reduction1, substtyp_reduction1. Qed. End strong_normalization_proof_typefree. Module strong_normalization_proof_typed. Import subject_reduction_proof. Notation bottom := (tyabs (tyvar 0)). Notation "# ctx" := (rcons ctx (Some bottom)) (at level 65, no associativity). Section CRs. Variable (ctx : context typ) (ty : typ) (P : term -> Prop). Definition CR1 := forall t, #ctx \|- t \: ty -> P t -> SN t. Definition CR2 := forall t t', #ctx \|- t \: ty -> t ->r1 t' -> P t -> P t'. Definition CR3 := forall t, #ctx \|- t \: ty -> neutral t -> (forall t', t ->r1 t' -> P t') -> P t. Record RC : Prop := reducibility_candidate { rc_cr1 : CR1 ; rc_cr2 : CR2 ; rc_cr3 : CR3 }. End CRs. Lemma CR2' ctx ty P t t' : RC ctx ty P -> #ctx \|- t \: ty -> t ->r t' -> P t -> P t'. Proof. move => H H0 H1. elim/clos_refl_trans_1n_ind: t t' / H1 H0 => //= x y z H0 H1 H2 H3 H4. by apply H2; [apply (subject_reduction H0) | apply (rc_cr2 H H3)]. Qed. Lemma CR4 ctx ty P t : RC ctx ty P -> #ctx \|- t \: ty -> neutral t -> (forall t', ~ t ->r1 t') -> P t. Proof. by move/rc_cr3 => H H0 H1 H2; apply H => // t' /H2. Qed. Lemma CR4' ctx ty P (v : nat) : RC ctx ty P -> ctxindex (#ctx) v ty -> P v. Proof. move/CR4 => H H0; apply H => // => t' H1; inversion H1. Qed. Lemma snorm_isrc ctx ty : RC ctx ty SN. Proof. constructor; move => /=; auto. - by move => t t' H H0 []; apply. - by move => t _ _ /(Acc_intro t). Qed. Lemma rcfun_isrc ctx tyl tyr P Q : RC ctx tyl P -> RC ctx tyr Q -> RC ctx (tyl ->t tyr) (fun u => forall v, #ctx \|- v \: tyl -> P v -> Q (u @ v)). Proof. move => HP HQ; constructor; move => /=. - move => t H /(_ (size ctx @' tyl)). have H0 : #ctx \|- size ctx @' tyl \: tyl by rewrite /typing /= nth_rcons ltnn eqxx /= shift_zero_ty. have H1 t': ~ size ctx @' tyl ->r1 t' by move => H1; inversion H1; subst; inversion H5. move/(_ H0 (CR4 HP H0 erefl H1))/(rc_cr1 HQ) => {H1}. have -> : #ctx \|- t @ (size ctx @' tyl) \: tyr by apply/typing_appP; exists tyl. by move/(_ erefl); apply (acc_preservation (f := app^~_)); auto. - move => t t' H H0 H1 v H2 /(H1 _ H2); apply (rc_cr2 HQ). + by apply/typing_appP; exists tyl. + by constructor. - move => t H H0 H1 v H2 H3. elim/Acc_ind': v / {H2 H3} (rc_cr1 HP H2 H3) (H2) (H3) => v IH H2 H3. apply (rc_cr3 HQ) => //=; first by apply/typing_appP; exists tyl. move => t'' H4; move: H0; inversion H4; subst => //= _. + by apply (H1 _ H7). + apply IH => //. * by apply (subject_reduction H7). * by apply (rc_cr2 HP H2 H7). Qed. Fixpoint reducible ctx ty (preds : seq (typ * (term -> Prop))) t : Prop := match ty with | tyvar v => nth SN (unzip2 preds) v t | tyfun tyl tyr => forall v, #ctx \|- v \: subst_typ 0 (unzip1 preds) tyl -> reducible ctx tyl preds v -> reducible ctx tyr preds (t @ v) | tyabs ty => forall ty' P, RC ctx ty' P -> reducible ctx ty ((ty', P) :: preds) (t @' ty') end. Lemma reducibility_isrc ctx ty preds : Forall (fun p => RC ctx p.1 p.2) preds -> RC ctx (subst_typ 0 (unzip1 preds) ty) (reducible ctx ty preds). Proof. elim: ty preds => /= [n | tyl IHl tyr IHr | ty IH] preds. - rewrite shift_zero_ty subn0. elim: preds n => [| P preds IH []] /=. + move => n _; rewrite !nth_nil /= !subn0; apply snorm_isrc. + by case. + by move => n [H] /(IH n) {IH}; rewrite !subSS. - by move => H; apply rcfun_isrc; [apply IHl | apply IHr]. - move => H; constructor. + move => /= t H0 /(_ 0 _ (snorm_isrc _ _)) /(rc_cr1 (IH ((_, _) :: _) (conj (snorm_isrc _ _) H))) /=. suff: #ctx \|- t @' 0 \: subst_typ 0 (tyvar 0 :: unzip1 preds) ty by move => -> /(_ erefl); apply (acc_preservation (f := uapp^~_)) => x y H1; constructor. by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. + move => /= t t' H0 H1 H2 ty' P H3. move: (H2 _ _ H3); apply (rc_cr2 (IH ((_, _) :: _) (conj H3 H))). * by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. * by constructor. + move => /= t H0 H1 H2 ty' P H3. apply (rc_cr3 (IH ((_, _) :: _) (conj H3 H))) => //=. + by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. * by move => t' H4; move: H0; inversion H4; subst => //= _; apply H2. Qed. Lemma shift_reducibility c ty preds preds' ctx t : c <= size preds -> (reducible ctx (shift_typ (size preds') c ty) (insert preds' preds (tyvar 0, SN) c) t <-> reducible ctx ty preds t). Proof. elim: ty c preds t => [v | tyl IHl tyr IHr | ty IH] c preds t H. - rewrite /= /unzip2 map_insert nth_insert size_map; elimif_omega. - rewrite /= /unzip1 map_insert -(size_map (@fst _ _)) /= !subst_shift_cancel_ty4 ?size_map //. by split => H0 v H1 /(IHl c _ _ H) /(H0 _ H1) /(IHr c _ _ H). - by split => /= H0 ty' P H1; apply (IH c.+1 ((ty', P) :: preds)) => //; apply H0. Qed. Lemma subst_reducibility ty preds n tys ctx t : n <= size preds -> (reducible ctx (subst_typ n tys ty) preds t <-> reducible ctx ty (insert [seq (subst_typ 0 (drop n (unzip1 preds)) ty, reducible ctx ty (drop n preds)) | ty <- tys] preds (tyvar 0, SN) n) t). Proof. elim: ty preds n tys t => [v | tyl IHl tyr IHr | ty IH] preds n tys t. - rewrite /= /unzip2 map_insert /= -map_comp /comp /= nth_insert size_map -/unzip2; elimif_omega. + by rewrite nth_default ?leq_addr //= addnC. + move => H0. rewrite (nth_map (tyvar (v - size tys))) //=. move: (shift_reducibility (nth (tyvar (v - size tys)) tys v) (take n preds) ctx t (leq0n (size (drop n preds)))). by rewrite /insert take0 drop0 /= cat_take_drop size_takel. - by move => H /=; split => H0 t' H1 /IHl => /(_ H) /H0 /IHr => /(_ H); apply; move: H1; rewrite /unzip1 map_insert -map_comp /= subst_subst_compose_ty ?size_map. - move => H /=; split => H0 ty' P /H0. + by move/IH => /(_ H); rewrite /insert /= subSS. + by move => H1; apply IH. Qed. Lemma abs_reducibility tyl tyr preds ctx t : #ctx \|- abs (subst_typ 0 (unzip1 preds) tyl) t \: subst_typ 0 (unzip1 preds) (tyl ->t tyr) -> Forall (fun p => RC ctx p.1 p.2) preds -> (forall t', #ctx \|- t' \: subst_typ 0 (unzip1 preds) tyl -> reducible ctx tyl preds t' -> reducible ctx tyr preds (subst_term 0 0 [:: t'] t)) -> reducible ctx (tyl ->t tyr) preds (abs (subst_typ 0 (unzip1 preds) tyl) t). Proof. rewrite /= typing_absE => H H0. move: (reducible ctx tyl preds) (reducible ctx tyr preds) (reducibility_isrc tyl H0) (reducibility_isrc tyr H0) => {H0} P Q HP HQ H0 t' H1 H2. have H3: SN t by move: (rc_cr1 HQ (subject_subst0' H H1) (H0 t' H1 H2)); apply acc_preservation => x y; apply subst_reduction1. move: t t' H3 {H0 H1 H2} (rc_cr1 HP H1 H2) H (H1) (H2) (H0 _ H1 H2). refine (Acc_ind2 _) => t t' IHt IHt' H H0 H1 H2; apply (rc_cr3 HQ) => //=. - by apply/typing_appP; exists (subst_typ 0 (unzip1 preds) tyl) => //; rewrite typing_absE. - move => t'' H3; inversion H3; subst => //. + inversion H7; subst; apply IHt => //. * by move: H; apply subject_reduction. * by apply (@rc_cr2 _ _ _ HQ (subst_term 0 0 [:: t'] t)) => //; [apply (subject_subst0' H) | apply subst_reduction1]. + apply IHt' => //. * by apply (subject_reduction H7). * by apply (rc_cr2 HP H0 H7). * move: H2; apply (CR2' HQ); first by apply (subject_subst0' H). by apply (@subst_reduction t 0 0 [:: (t', t2')]) => /=; intuition apply rtc_step. Qed. Lemma uabs_reducibility ty preds ctx t : #ctx \|- uabs t \: subst_typ 0 (unzip1 preds) (tyabs ty) -> Forall (fun p => RC ctx p.1 p.2) preds -> (forall v P, RC ctx v P -> reducible ctx ty ((v, P) :: preds) (typemap (subst_typ^~ [:: v]) 0 t)) -> reducible ctx (tyabs ty) preds (uabs t). Proof. rewrite /= typing_uabsE => H H0 H1 ty' P H2. move: (substtyp_preserves_typing 0 [:: ty'] H) (H1 ty' P H2). have ->: ctxmap (subst_typ 0 [:: ty']) (ctxmap (shift_typ 1 0) (#ctx)) = #ctx by rewrite !map_rcons /=; congr rcons; elim: ctx {H H0 H1 H2} => //= ty'' ctx {2}<-; case: ty'' => //= ty''; rewrite subst_shift_cancel_ty2 //= subnn shift_zero_ty. move: (reducible _ _) (@reducibility_isrc ctx ty ((ty', P) :: preds)) => P' /= /(_ (conj H2 H0)) {H0 H1 H2}. rewrite -typing_uabsE -/(subst_typ 0 _ (tyabs _)) in H. rewrite subst_app_ty /= => H0 H1 H2. have H3: SN t by move: (rc_cr1 H0 H1 H2); apply acc_preservation => x y; apply substtyp_reduction1. elim/Acc_ind': t / H3 H H1 H2 => t IH H H1 H2; apply (rc_cr3 H0) => //=. - by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. - move => t' H4; inversion H4; subst => //; inversion H7; subst; apply IH => //. + by apply (subject_reduction H7). + by move: H1; apply subject_reduction, substtyp_reduction1. + by apply (rc_cr2 H0 H1 (substtyp_reduction1 _ _ H5) H2). Qed. Lemma uapp_reducibility ty ty' preds ctx t : Forall (fun p => RC ctx p.1 p.2) preds -> reducible ctx (tyabs ty) preds t -> reducible ctx (subst_typ 0 [:: ty'] ty) preds (t @' subst_typ 0 (unzip1 preds) ty'). Proof. move => /= H H0; apply subst_reducibility => //=. by rewrite /insert take0 sub0n !drop0 /=; apply H0, reducibility_isrc. Qed. Lemma reduce_lemma ctx ctx' preds t ty : [seq Some c.2 | c <- ctx] \|- t \: ty -> Forall (fun p => RC ctx' p.1 p.2) preds -> Forall (fun c => #ctx' \|- c.1 \: subst_typ 0 (unzip1 preds) c.2 /\ reducible ctx' c.2 preds c.1) ctx -> reducible ctx' ty preds (subst_term 0 0 (unzip1 ctx) (typemap (subst_typ^~ (unzip1 preds)) 0 t)). Proof. have Hty: forall t ty ctx ctx' preds, [seq Some c.2 | c <- ctx] \|- t \: ty -> Forall (fun p => RC ctx' p.1 p.2) preds -> Forall (fun c => #ctx' \|- c.1 \: subst_typ 0 (unzip1 preds) c.2 /\ reducible ctx' c.2 preds c.1) ctx -> #ctx' \|- subst_term 0 0 (unzip1 ctx) (typemap (subst_typ^~ (unzip1 preds)) 0 t) \: subst_typ 0 (unzip1 preds) ty. clear => t ty ctx ctx' preds H H0 H1. move: (fun t ty => @subject_subst0 t ty (#ctx') [seq (c.1, subst_typ 0 (unzip1 preds) c.2) | c <- ctx]). rewrite /unzip1 -!map_comp !/comp -/unzip1; apply => /=. - by elim: ctx H1 {H} => //= [[]] /= t' ty' ctx IH [] [-> _] /=. - by move: (substtyp_preserves_typing 0 (unzip1 preds) H); rewrite -map_comp; apply ctxleq_preserves_typing, ctxleq_appr. elim: t ty ctx ctx' preds => /=. - move => v ty ctx ctx' preds H H0 H1. rewrite shifttyp_zero shift_zero subn0 size_map. elim: ctx v H H1 => //=; first by case. case => t ty' ctx IH [] //=. + by case/eqP => <- [] []. + by move => v H [H1 H2]; rewrite subSS; apply IH. - move => tl IHtl tr IHtr ty ctx ctx' preds /typing_appP [tyl H H0] H1 H2. by move: (IHtl (tyl ->t ty) ctx ctx' preds H H1 H2) => /=; apply; [apply Hty | apply IHtr]. - move => tyl t IHt ty ctx ctx' preds /typing_absP [tyr -> H] H0 H1. apply abs_reducibility => //; first by apply (Hty (abs tyl t)) => //; rewrite typing_absE. by move => t' H2 H3; rewrite subst_app //=; apply (IHt tyr ((t', tyl) :: ctx)). - move => t IHt tyr ty ctx ctx' preds /typing_uappP [tyl -> H] H0 H1. by apply uapp_reducibility => //; apply IHt. - move => t IHt ty ctx ctx' preds /typing_uabsP [ty' -> H] H0 H1. apply uabs_reducibility => //; first by apply (Hty (uabs t)) => //; rewrite typing_uabsE. move => v P H2. rewrite -(subst_substtyp_distr 0 [:: v]) // typemap_compose /=. have /(typemap_eq 0 t) -> : forall i ty, subst_typ (i + 0) [:: v] (subst_typ (i + 1) (unzip1 preds) ty) = subst_typ i (unzip1 ((v, P) :: preds)) ty by move => i ty''; rewrite addn0 addn1 subst_app_ty. move: (IHt ty' [seq (c.1, shift_typ 1 0 c.2) | c <- ctx] ctx' ((v, P) :: preds)). rewrite /unzip1 -!map_comp /comp /=; apply => //=. + by move: H; rewrite -map_comp /comp /=. + apply Forall_map; move: H1; apply Forall_impl => [[t' ty'']] /= []. rewrite subst_shift_cancel_ty3 //= drop0 !add0n subSS sub0n shift_zero_ty. case (shift_reducibility ty'' [:: (v, P)] ctx' t' (leq0n (size preds))). rewrite /insert take0 drop0 sub0n; auto. Qed. Lemma identical_substitution ctx' ctx t ty n : ctx' ++ ctx \|- t \: ty -> subst_term (size ctx') n [seq var i | i <- iota 0 (size ctx)] t = t. Proof. elim: t ctx' ctx ty n => //=. - move => v ctx' ctx ty n; case: ifP => //; elimleq. rewrite /typing /= size_map size_iota -nth_map' /= nth_cat ltnNge leq_addr //= addKn addnC => H; congr addn. have H0: v < size ctx by elim: v ctx H => [| v IH] []. by move: (ltnW H0); rewrite -subn_eq0 => /eqP ->; rewrite nth_iota. - by move => tl IHtl tr IHtr ctx' ctx tyr n /typing_appP [tyl H H0]; rewrite (IHtl _ _ (tyl ->t tyr)) // (IHtr _ _ tyl). - move => tyl t IHt ctx' ctx ty n /typing_absP [tyr _ H]. rewrite (IHt (Some tyl :: ctx') _ tyr) //. - move => t IHt tyr ctx' ctx ty n /typing_uappP [tyl _ H]. by rewrite (IHt ctx' ctx (tyabs tyl)). - move => t IHt ctx' ctx ty n /typing_uabsP [ty' _]; rewrite map_cat => /IHt => /(_ n.+1). by rewrite !size_map => ->. Qed. Theorem typed_term_is_snorm ctx t ty : ctx \|- t \: ty -> SN t. Proof. move => H. have {H}: map some (map (odflt (tyvar 0)) ctx) \|- t \: ty by move: H; apply ctxleq_preserves_typing; elim: ctx {t ty} => // [[]] // ty ctx H; rewrite ctxleqE eqxx. move: {ctx} (map _ ctx) => ctx H; move: (H). have ->: map some ctx = [seq Some c.2 | c <- zip (map var (iota 0 (size ctx))) ctx] by elim: {H} ctx 0 => //= {t ty} ty ctx IH n; rewrite -IH. move/reduce_lemma => /(_ (map some ctx) [::] I). rewrite /= unzip1_zip ?size_map ?size_iota ?leqnn; last by []. have H0: Forall (fun c => # [seq Some i | i <- ctx] \|- c.1 \: subst_typ 0 [::] c.2 /\ reducible (map some ctx) c.2 [::] c.1) (zip (map var (iota 0 (size ctx))) ctx). apply Forall_nth; case => {H t ty} t ty n; rewrite size_zip size_map size_iota minnn nth_map' (nth_map' (@fst _ _)) /= -/unzip1 -/unzip2 unzip1_zip ?unzip2_zip ?size_map ?size_iota // => H; rewrite (nth_map 0 t var) ?size_iota // nth_iota // add0n. suff: # [seq Some i | i <- ctx] \|- n \: subst_typ 0 [::] (nth ty ctx n) by intuition apply (CR4' (@reducibility_isrc _ (nth ty ctx n) [::] I)). by rewrite /typing /= subst_nil_ty nth_rcons size_map H (nth_map ty). move/(_ H0) => {H0} /(rc_cr1 (reducibility_isrc _ _)) /= /(_ I). have ->: typemap (subst_typ^~ [::]) 0 t = t by elim: {H} t 0 => //=; move: subst_nil_ty; congruence'. move: (@identical_substitution [::] (map some ctx) t ty 0 H). rewrite subst_nil_ty /= size_map => ->. move/(_ (ctxleq_preserves_typing _ H)). by rewrite -cats1 => /(_ (ctxleq_appr _ _)). Qed. End strong_normalization_proof_typed. Module strong_normalization_proof_kripke. Import subject_reduction_proof. Section CRs. Variable (ty : typ) (P : context typ -> term -> Prop). Definition CR_typed := forall ctx t, P ctx t -> ctx \|- t \: ty. Definition CR0 := forall ctx ctx' t, ctx <=c ctx' -> P ctx t -> P ctx' t. Definition CR1 := forall ctx t, P ctx t -> SN t. Definition CR2 := forall ctx t t', t ->r1 t' -> P ctx t -> P ctx t'. Definition CR3 := forall ctx t, ctx \|- t \: ty -> neutral t -> (forall t', t ->r1 t' -> P ctx t') -> P ctx t. Record RC : Prop := reducibility_candidate { rc_typed : CR_typed ; rc_cr0 : CR0 ; rc_cr1 : CR1 ; rc_cr2 : CR2 ; rc_cr3 : CR3 }. End CRs. Lemma CR2' ty P ctx t t' : RC ty P -> t ->r t' -> P ctx t -> P ctx t'. Proof. move => H; elim/clos_refl_trans_1n_ind: t t' / => //= x y z H0 H1 H2 H3. by apply H2, (rc_cr2 H H0). Qed. Lemma CR4 ty P ctx t : RC ty P -> ctx \|- t \: ty -> neutral t -> (forall t', ~ t ->r1 t') -> P ctx t. Proof. by move/rc_cr3 => H H0 H1 H2; apply H => // t' /H2. Qed. Lemma CR4' ty P ctx (v : nat) : RC ty P -> ctxindex ctx v ty -> P ctx v. Proof. move/CR4 => H H0; apply H => // t' H1; inversion H1. Qed. Notation SN' ty := (fun ctx t => ctx \|- t \: ty /\ SN t). Lemma snorm_isrc ty : RC ty (SN' ty). Proof. (constructor; move => /=) => [ctx t [] // | ctx ctx' t H [H0 H1] | ctx t [] // | ctx t t' H [H0 [H1]] | ctx t ]; intuition. - by apply (ctxleq_preserves_typing H). - by apply (subject_reduction H). - by constructor => t' /H1 []. Qed. Definition rcfun tyl tyr (P Q : context typ -> term -> Prop) ctx u : Prop := ctx \|- u \: tyl ->t tyr /\ forall ctx' v, ctx <=c ctx' -> P ctx' v -> Q ctx' (u @ v). Lemma rcfun_isrc tyl tyr P Q : RC tyl P -> RC tyr Q -> RC (tyl ->t tyr) (rcfun tyl tyr P Q). Proof. move => HP HQ; rewrite /rcfun; constructor; move => /=; first tauto. - move => ctx ctx' t H [H0 H1]; split; last move => ctx'' t' H2 H3. + by apply (ctxleq_preserves_typing H). + by apply (H1 ctx'' t') => //; apply ctxleq_trans with ctx'. - move => ctx t [H] /(_ _ _ (ctxleq_appr _ _) (CR4' HP (ctxindex_last ctx tyl))) /(rc_cr1 HQ). by apply (acc_preservation (f := app^~_)); auto. - move => ctx t t' H [H0 H1]; split; last move => ctx' t''. + by apply (subject_reduction H). + by move => /H1 {H1} H1 /H1 {H1}; apply (rc_cr2 HQ); constructor. - move => ctx t H H0 H1; split => // ctx' t' H2 H3. elim/Acc_ind: t' / {H3} (rc_cr1 HP H3) (H3) => t' _ IH H3. apply (rc_cr3 HQ) => //=; first (apply/typing_appP; exists tyl). + by apply (ctxleq_preserves_typing H2). + by apply (rc_typed HP). + move => t'' H4; move: H0; inversion H4; subst => //= _. * by apply (proj2 (H1 _ H7) ctx'). * by apply IH => //; apply (rc_cr2 HP H7). Qed. Fixpoint reducible ty (preds : seq (typ * (context typ -> term -> Prop))) : context typ -> term -> Prop := match ty with | tyvar v => nth (SN' (v - size preds)) (unzip2 preds) v | tyfun tyl tyr => let s := subst_typ 0 (unzip1 preds) in rcfun (s tyl) (s tyr) (reducible tyl preds) (reducible tyr preds) | tyabs ty => fun ctx t => ctx \|- t \: tyabs (subst_typ 1 (unzip1 preds) ty) /\ forall ty' P, RC ty' P -> reducible ty ((ty', P) :: preds) ctx (t @' ty') end. Lemma reducibility_isrc ty preds : Forall (fun p => RC p.1 p.2) preds -> RC (subst_typ 0 (unzip1 preds) ty) (reducible ty preds). Proof. elim: ty preds => /= [n | tyl IHl tyr IHr | ty IH] preds. - rewrite shift_zero_ty subn0. elim: preds n => [| P preds IH []] /=. + move => n _; rewrite !nth_nil /= !subn0; apply snorm_isrc. + by case. + by move => n [H] /(IH n) {IH}; rewrite !subSS. - by move => H; apply rcfun_isrc; [apply IHl | apply IHr]. - move => H; constructor. + by move => /= ctx t []. + move => /= ctx ctx' t H0 [H1 H2]; split; first by move: H1; apply ctxleq_preserves_typing. move => ty' P H3. move: (rc_cr0 (IH ((_, _) :: _) (conj H3 H))) => /(_ ctx ctx' _ H0). by apply; apply H2. + move => /= ctx t [_] /(_ 0 _ (snorm_isrc _)) /(rc_cr1 (IH ((_, _) :: _) (conj (snorm_isrc _) H))). by apply (acc_preservation (f := uapp^~_)) => x y H0; constructor. + move => /= ctx t t' H0 [H1 H2]; split; first by move: H1; apply subject_reduction. move => ty' P H3; move: (H2 _ _ H3). by apply (rc_cr2 (IH ((_, _) :: _) (conj H3 H))); constructor. + move => /= ctx t H0 H1 H2; split => // ty' P H3. apply (rc_cr3 (IH ((_, _) :: _) (conj H3 H))) => //=. + by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. * by move => t' H4; move: H0; inversion H4; subst => //= _; apply H2. Qed. Lemma shift_reducibility c ty preds preds' ctx t : c <= size preds -> (reducible (shift_typ (size preds') c ty) (insert preds' preds (tyvar 0, SN' 0) c) ctx t <-> reducible ty preds ctx t). Proof. elim: ty c preds ctx t => [v | tyl IHl tyr IHr | ty IH] c preds ctx t H. - rewrite /= /unzip2 map_insert nth_insert size_map size_insert; elimif_omega. rewrite (_ : v - size preds = 0) //; ssromega. - rewrite /= /rcfun /unzip1 map_insert -(size_map (@fst _ _)) /= !subst_shift_cancel_ty4 ?size_map //. by split; case => H0 H1; split => // ctx' t' H2 /(IHl c _ _ _ H) /(H1 _ _ H2) /(IHr c _ _ _ H). - rewrite /= /unzip1 map_insert -(size_map (@fst _ _)) -add1n subst_shift_cancel_ty4 ?size_map //. by split; case => H0 H1; split => // ty' P H2; apply (IH c.+1 ((ty', P) :: preds)) => //; apply H1. Qed. Lemma subst_reducibility ty preds n tys ctx t : n <= size preds -> (reducible (subst_typ n tys ty) preds ctx t <-> reducible ty (insert [seq (subst_typ 0 (drop n (unzip1 preds)) ty, reducible ty (drop n preds)) | ty <- tys] preds (tyvar 0, SN' 0) n) ctx t). Proof. elim: ty preds n tys ctx t => [v | tyl IHl tyr IHr | ty IH] preds n tys ctx t. - rewrite /= size_insert size_map /unzip2 map_insert /= -map_comp /comp /= nth_insert size_map -/unzip2; elimif_omega. + by move/maxn_idPr => ->; rewrite nth_default ?leq_addr //= addnC. + move => H0. rewrite (nth_map (tyvar (v - size tys))) //=. move: (shift_reducibility (nth (tyvar (v - size tys)) tys v) (take n preds) ctx t (leq0n (size (drop n preds)))). by rewrite /insert take0 drop0 /= cat_take_drop size_takel. + by move => H; rewrite (_ : v - size preds = 0) //; ssromega. - move => H /=; rewrite /rcfun /= /unzip1 map_insert -!map_comp /comp /= -!subst_subst_compose_ty ?size_map // -/unzip1 add0n. by split; case => H1 H2; split => // ctx' t' H3 /IHl => /(_ H) /(H2 _ _ H3) /IHr => /(_ H). - move => H /=; rewrite /unzip1 map_insert -!map_comp /comp /= -subst_subst_compose_ty ?size_map // add1n -/unzip1. split; case => H0 H1; split => // ty' P /H1 {H0 H1}. + by move/IH => /= /(_ H); rewrite /insert /= subSS. + by move => H0; apply IH. Qed. Lemma abs_reducibility tyl tyr preds ctx t : ctx \|- abs (subst_typ 0 (unzip1 preds) tyl) t \: subst_typ 0 (unzip1 preds) (tyl ->t tyr) -> Forall (fun p => RC p.1 p.2) preds -> (forall ctx' t', ctx <=c ctx' -> reducible tyl preds ctx' t' -> reducible tyr preds ctx' (subst_term 0 0 [:: t'] t)) -> reducible (tyl ->t tyr) preds ctx (abs (subst_typ 0 (unzip1 preds) tyl) t). Proof. move => /= H H0. move: (reducible tyl preds) (reducible tyr preds) (reducibility_isrc tyl H0) (reducibility_isrc tyr H0) => {H0} P Q HP HQ H0; split => // ctx' t' H1 H2. have H3: SN t by move: (rc_cr1 HQ (H0 _ _ H1 H2)); apply acc_preservation => x y; apply subst_reduction1. move: t t' H3 {H0 H2} (rc_cr1 HP H2) H H1 (H2) (H0 _ _ H1 H2). refine (Acc_ind2 _) => t t' IHt IHt' H H0 H1 H2; apply (rc_cr3 HQ) => //=; first (apply/typing_appP; exists (subst_typ 0 (unzip1 preds) tyl)). - by move: H; apply ctxleq_preserves_typing. - by apply (rc_typed HP). - move => t'' H3; inversion H3; subst => //. + inversion H7; subst; apply IHt; auto. * by move: H; apply subject_reduction. * by apply (rc_cr2 HQ (subst_reduction1 0 0 [:: t'] H8)). + apply IHt' => //; first by apply (rc_cr2 HP H7). move: H2; apply (CR2' HQ). by apply (@subst_reduction t 0 0 [:: (t', t2')]) => /=; intuition apply rtc_step. Qed. Lemma uabs_reducibility ty preds ctx t : ctx \|- uabs t \: subst_typ 0 (unzip1 preds) (tyabs ty) -> Forall (fun p => RC p.1 p.2) preds -> (forall v P, RC v P -> reducible ty ((v, P) :: preds) ctx (typemap (subst_typ^~ [:: v]) 0 t)) -> reducible (tyabs ty) preds ctx (uabs t). Proof. move => /= H H0 H1; split => // ty' P H2. move: (reducible _ _) (@reducibility_isrc ty ((ty', P) :: preds)) (H1 ty' P H2) => P' /= /(_ (conj H2 H0)) {H0 H1 H2} H0 H1. have H2: SN t by move: (rc_cr1 H0 H1); apply acc_preservation => x y; apply substtyp_reduction1. elim/Acc_ind': t / H2 H H1 => t H1 H H2; apply (rc_cr3 H0) => //=. - by apply/typing_uappP; exists (subst_typ 1 (unzip1 preds) ty) => //; rewrite subst_app_ty. - move => t' H3; inversion H3; subst => //; inversion H7; subst; apply H1 => //. + by apply (subject_reduction H7). + apply (rc_cr2 H0 (substtyp_reduction1 _ _ H5) H2). Qed. Lemma uapp_reducibility ty ty' preds ctx t : Forall (fun p => RC p.1 p.2) preds -> reducible (tyabs ty) preds ctx t -> reducible (subst_typ 0 [:: ty'] ty) preds ctx (t @' subst_typ 0 (unzip1 preds) ty'). Proof. move => /= H H0. apply subst_reducibility => //=. rewrite /insert take0 sub0n !drop0 /=. by apply H0, reducibility_isrc. Qed. Lemma reduce_lemma ctx ctx' preds t ty : [seq Some c.2 | c <- ctx] \|- t \: ty -> Forall (fun p => RC p.1 p.2) preds -> Forall (fun c => reducible c.2 preds ctx' c.1) ctx -> reducible ty preds ctx' (subst_term 0 0 (unzip1 ctx) (typemap (subst_typ^~ (unzip1 preds)) 0 t)). Proof. have Hty: forall t ty ctx ctx' preds, [seq Some c.2 | c <- ctx] \|- t \: ty -> Forall (fun p => RC p.1 p.2) preds -> Forall (fun c => reducible c.2 preds ctx' c.1) ctx -> ctx' \|- subst_term 0 0 (unzip1 ctx) (typemap (subst_typ^~ (unzip1 preds)) 0 t) \: subst_typ 0 (unzip1 preds) ty. clear => t ty ctx ctx' preds H H0 H1. move: (fun t ty => @subject_subst0 t ty ctx' [seq (c.1, subst_typ 0 (unzip1 preds) c.2) | c <- ctx]). rewrite /unzip1 -!map_comp !/comp -/unzip1; apply => /=. - by elim: ctx H1 {H} => //= [[]] /= t' ty' ctx IH [] /(rc_typed (reducibility_isrc ty' H0)) ->. - by move: (substtyp_preserves_typing 0 (unzip1 preds) H); rewrite -map_comp; apply ctxleq_preserves_typing, ctxleq_appr. elim: t ty ctx ctx' preds => /=. - move => v ty ctx ctx' preds H H0 H1. rewrite shifttyp_zero shift_zero subn0 size_map. elim: ctx v H H1 => //=; first by case. case => t ty' ctx IH [] //=. + by case/eqP => <- []. + by move => v H [H1 H2]; rewrite subSS; apply IH. - move => tl IHtl tr IHtr ty ctx ctx' preds /typing_appP [tyl H H0] H1 H2. by move: (IHtl (tyl ->t ty) ctx ctx' preds H H1 H2) => /= [_]; apply => //; apply IHtr. - move => tyl t IHt ty ctx ctx' preds /typing_absP [tyr -> H] H0 H1. apply abs_reducibility => //; first by apply (Hty (abs tyl t)) => //; rewrite typing_absE. move => ctx'' t' H2 H3; rewrite subst_app //=. apply (IHt tyr ((t', tyl) :: ctx)) => //=; split => //; move: H1. by apply Forall_impl => {t' ty H H3} [[t' ty]] /=; apply (rc_cr0 (reducibility_isrc ty H0) H2). - move => t IHt tyr ty ctx ctx' preds /typing_uappP [tyl -> H] H0 H1. by apply uapp_reducibility => //; apply IHt. - move => t IHt ty ctx ctx' preds /typing_uabsP [ty' -> H] H0 H1. apply uabs_reducibility => //; first by apply (Hty (uabs t)) => //; rewrite typing_uabsE. move => v P H2. rewrite -(subst_substtyp_distr 0 [:: v]) // typemap_compose /=. have /(typemap_eq 0 t) -> : forall i ty, subst_typ (i + 0) [:: v] (subst_typ (i + 1) (unzip1 preds) ty) = subst_typ i (unzip1 ((v, P) :: preds)) ty by move => i ty''; rewrite addn0 addn1 subst_app_ty. move: (IHt ty' [seq (c.1, shift_typ 1 0 c.2) | c <- ctx] ctx' ((v, P) :: preds)). rewrite /unzip1 -!map_comp /comp /=; apply => //=. + by move: H; rewrite -map_comp /comp /=. + apply Forall_map; move: H1; apply Forall_impl => [[t' ty'']] /=. case (shift_reducibility ty'' [:: (v, P)] ctx' t' (leq0n (size preds))). rewrite /insert take0 drop0 sub0n => _ /=; apply. Qed. Theorem typed_term_is_snorm ctx t ty : ctx \|- t \: ty -> SN t. Proof. move => H. have {H}: map some (map (odflt (tyvar 0)) ctx) \|- t \: ty by move: H; apply ctxleq_preserves_typing; elim: ctx {t ty} => // [[]] // ty ctx H; rewrite ctxleqE eqxx. move: {ctx} (map _ ctx) => ctx. have ->: map some ctx = [seq Some c.2 | c <- zip (map var (iota 0 (size ctx))) ctx] by elim: ctx 0 => //= {t ty} ty ctx IH n; rewrite -IH. move => /reduce_lemma; move => /(_ (map some ctx) [::] I). rewrite unzip1_zip ?size_map ?size_iota ?leqnn; last by []. have H: Forall (fun c => reducible c.2 [::] (map some ctx) c.1) (zip (map var (iota 0 (size ctx))) ctx) by apply Forall_nth; case => {t ty} t ty n; rewrite size_zip size_map size_iota minnn nth_map' (nth_map' (@fst _ _)) /= -/unzip1 -/unzip2 unzip1_zip ?unzip2_zip ?size_map ?size_iota // => H; rewrite (nth_map 0 t var) ?size_iota // nth_iota // add0n; apply (CR4' (@reducibility_isrc (nth ty ctx n) [::] I)) => //=; rewrite subst_nil_ty (nth_map ty). move/(_ H) => {H} /(rc_cr1 (reducibility_isrc _ _)) /= /(_ I). set f := subst_term _ _ _; set g := typemap _ _. apply (acc_preservation (f := f \o g)) => x y H. by apply subst_reduction1, substtyp_reduction1. Qed. End strong_normalization_proof_kripke.
Pundits and coaches sometimes characterized Turner as a quarterback who did not excel during practices , but executed well on game @-@ day . Maryland head coach Ralph Friedgen said " He 's pretty go @-@ with @-@ the @-@ flow . And that 's his greatest strength and maybe his greatest weakness . The bottom line is , he plays well in games . " The Baltimore Sun wrote that he " seems to play his best when it counts — and his worst when it doesn 't . " Regarding the 2008 summer practices , offensive coordinator James Franklin said Turner ranked in the middle compared with Jordan Steffy and Josh Portis in terms of completion percentage , fewest interceptions , and " explosive " plays that gained 16 yards or more . Turner conceded that Steffy was a better game @-@ planner during practices . Head coach Ralph Friedgen who had offered critical or subdued assessments of Turners ' practice , said his intensity grew after losing the starting position to Steffy prior to the 2008 season . Turner said , " It lit a fire in me in the sense that I had to be ready . "
Formal statement is: lemma homeomorphism_cont1: "homeomorphism S T f g \<Longrightarrow> continuous_on S f" Informal statement is: If $f$ is a homeomorphism from $S$ to $T$, then $f$ is continuous on $S$.
# Preamble ######################################################################################## using Pkg Pkg.activate(Base.current_project()) cd("..") # Go to the parent directory ################################################################################################### # Packages needed ################################################################################# using PolyGibbs using DelimitedFiles using ImageCore using ImageIO using ImageMagick using FileIO using PyPlot ################################################################################################### # Angle of rotation ############################################################################### const θ = π/4 ################################################################################################### # Retrieve of data from image ##################################################################### @info "Retrieving the image channels and extracting the two-dimensional fields" input = Float64.(channelview(RGB.(load("data/origin/wmap/wmap50.png")))) rchn = input[1, :, :] gchn = input[2, :, :] bchn = input[3, :, :] ################################################################################################### # Identification of the RGB fields dimensions ################################################ j = (size(input)[2] - 1)/2; N = Integer(2*j + 1); @info "The size of the field is $N" ################################################################################################### # Rotation of the image channels ########################################################################### @info "Performing rotation of R channel at θ = $θ" routput = Emodes(rchn, θ) @info "Performing rotation of G channel at θ = $θ" goutput = Emodes(gchn, θ) @info "Performing rotation of B channel at θ = $θ" boutput = Emodes(bchn, θ) ################################################################################################### # Saving results ################################################################################## @info "Writting the results as separate data files for each channel" writedlm("data/target/wmap/wmap50R_rpi4", real(routput)) writedlm("data/target/wmap/wmap50G_rpi4", real(goutput)) writedlm("data/target/wmap/wmap50B_rpi4", real(boutput)) ################################################################################################### begin imgrep = permutedims(StackedView(transpose(real(routput)), transpose(real(goutput)), transpose(real(boutput))), [3, 2, 1]) fig = figure() ax = gca() ax.imshow(imgrep, cmap = "gray") tight_layout() savefig("data/target/wmap/wmap50_rpi4", dpi = 300) end
SUBROUTINE symrzl_par(r1s, rus, rvs, z1s, zus, zvs, lus, lvs, 1 rcons, zcons, r1a, rua, rva, z1a, zua, zva, lua, lva, rcona, 2 zcona) USE vmec_main USE realspace, ONLY: ireflect_par USE parallel_include_module IMPLICIT NONE C----------------------------------------------- C D u m m y A r g u m e n t s C----------------------------------------------- REAL(dp), DIMENSION(nzeta,ntheta3,ns,0:1), INTENT(inout) :: 1 r1s, rus, rvs, z1s, zus, zvs, lus, lvs, rcons, zcons REAL(dp), DIMENSION(nzeta,ntheta3,ns,0:1), INTENT(in) :: 1 r1a, rua, rva, z1a, zua, zva, lua, lva, rcona, zcona C----------------------------------------------- C L o c a l V a r i a b l e s C----------------------------------------------- INTEGER :: mpar, ir, i, jk, jka, n2 INTEGER :: j, k, nsmin, nsmax REAL(dp) :: tsymon, tsymoff C----------------------------------------------- ! ! FIRST SUM SYMMETRIC, ANTISYMMETRIC PIECES ON EXTENDED INTERVAL, THETA = [PI,2*PI] ! CALl second0(tsymon) nsmin = t1lglob nsmax = t1rglob DO k = nsmin, nsmax DO mpar = 0, 1 DO i = 1 + ntheta2, ntheta1 ir = ntheta1 + 2 - i !-theta DO j = 1, nzeta jka = ireflect_par(j) !-zeta r1s(j,i,k,mpar) = r1s(jka,ir,k,mpar) & - r1a(jka,ir,k,mpar) rus(j,i,k,mpar) = rua(jka,ir,k,mpar) & - rus(jka,ir,k,mpar) z1s(j,i,k,mpar) = z1a(jka,ir,k,mpar) & - z1s(jka,ir,k,mpar) zus(j,i,k,mpar) = zus(jka,ir,k,mpar) & - zua(jka,ir,k,mpar) lus(j,i,k,mpar) = lus(jka,ir,k,mpar) & - lua(jka,ir,k,mpar) rcons(j,i,k,mpar) = rcons(jka,ir,k,mpar) & - rcona(jka,ir,k,mpar) zcons(j,i,k,mpar) = zcona(jka,ir,k,mpar) & - zcons(jka,ir,k,mpar) END DO IF (lthreed) THEN DO j = 1, nzeta jka = ireflect_par(j) !-zeta rvs(j,i,k,mpar) = rva(jka,ir,k,mpar) & - rvs(jka,ir,k,mpar) zvs(j,i,k,mpar) = zvs(jka,ir,k,mpar) & - zva(jka,ir,k,mpar) lvs(j,i,k,mpar) = lvs(jka,ir,k,mpar) & - lva(jka,ir,k,mpar) END DO END IF END DO ! ! NOW SUM SYMMETRIC, ANTISYMMETRIC PIECES FOR THETA = [0,PI] ! n2 = ntheta2 r1s(:,:n2,k,mpar) = r1s(:,:n2,k,mpar) + r1a(:,:n2,k,mpar) rus(:,:n2,k,mpar) = rus(:,:n2,k,mpar) + rua(:,:n2,k,mpar) z1s(:,:n2,k,mpar) = z1s(:,:n2,k,mpar) + z1a(:,:n2,k,mpar) zus(:,:n2,k,mpar) = zus(:,:n2,k,mpar) + zua(:,:n2,k,mpar) lus(:,:n2,k,mpar) = lus(:,:n2,k,mpar) + lua(:,:n2,k,mpar) rcons(:,:n2,k,mpar) = rcons(:,:n2,k,mpar) & + rcona(:,:n2,k,mpar) zcons(:,:n2,k,mpar) = zcons(:,:n2,k,mpar) & + zcona(:,:n2,k,mpar) IF (lthreed) THEN rvs(:,:n2,k,mpar) = rvs(:,:n2,k,mpar) & + rva(:,:n2,k,mpar) zvs(:,:n2,k,mpar) = zvs(:,:n2,k,mpar) & + zva(:,:n2,k,mpar) lvs(:,:n2,k,mpar) = lvs(:,:n2,k,mpar) & + lva(:,:n2,k,mpar) END IF END DO END DO CALl second0(tsymoff) symrzl_time = symrzl_time + (tsymoff - tsymon) END SUBROUTINE symrzl_par SUBROUTINE symrzl(r1s, rus, rvs, z1s, zus, zvs, lus, lvs, rcons, & zcons, r1a, rua, rva, z1a, zua, zva, lua, lva, & rcona, zcona) USE vmec_main USE parallel_include_module IMPLICIT NONE C----------------------------------------------- C D u m m y A r g u m e n t s C----------------------------------------------- REAL(dp), DIMENSION(ns*nzeta,ntheta3,0:1), INTENT(inout) :: 1 r1s, rus, rvs, z1s, zus, zvs, lus, lvs, rcons, zcons REAL(dp), DIMENSION(ns*nzeta,ntheta3,0:1), INTENT(in) :: 1 r1a, rua, rva, z1a, zua, zva, lua, lva, rcona, zcona C----------------------------------------------- C L o c a l V a r i a b l e s C----------------------------------------------- INTEGER :: mpar, ir, i, jk, jka, n2 INTEGER :: j, k, nsmin, nsmax REAL(dp) :: tsymon, tsymoff C----------------------------------------------- ! ! FIRST SUM SYMMETRIC, ANTISYMMETRIC PIECES ON EXTENDED INTERVAL, THETA = [PI,2*PI] ! CALl second0(tsymon) DO mpar = 0, 1 DO i = 1 + ntheta2, ntheta1 ir = ntheta1 + 2 - i !-theta DO jk = 1, ns*nzeta jka = ireflect(jk) !-zeta r1s(jk,i,mpar) = r1s(jka,ir,mpar) - r1a(jka,ir,mpar) rus(jk,i,mpar) = rua(jka,ir,mpar) - rus(jka,ir,mpar) z1s(jk,i,mpar) = z1a(jka,ir,mpar) - z1s(jka,ir,mpar) zus(jk,i,mpar) = zus(jka,ir,mpar) - zua(jka,ir,mpar) lus(jk,i,mpar) = lus(jka,ir,mpar) - lua(jka,ir,mpar) rcons(jk,i,mpar) = rcons(jka,ir,mpar) & - rcona(jka,ir,mpar) zcons(jk,i,mpar) = zcona(jka,ir,mpar) & - zcons(jka,ir,mpar) END DO IF (lthreed) THEN DO jk = 1, ns*nzeta jka = ireflect(jk) rvs(jk,i,mpar) = rva(jka,ir,mpar) - rvs(jka,ir,mpar) zvs(jk,i,mpar) = zvs(jka,ir,mpar) - zva(jka,ir,mpar) lvs(jk,i,mpar) = lvs(jka,ir,mpar) - lva(jka,ir,mpar) END DO ENDIF END DO ! ! NOW SUM SYMMETRIC, ANTISYMMETRIC PIECES FOR THETA = [0,PI] ! n2 = ntheta2 r1s(:,:n2,mpar) = r1s(:,:n2,mpar) + r1a(:,:n2,mpar) rus(:,:n2,mpar) = rus(:,:n2,mpar) + rua(:,:n2,mpar) z1s(:,:n2,mpar) = z1s(:,:n2,mpar) + z1a(:,:n2,mpar) zus(:,:n2,mpar) = zus(:,:n2,mpar) + zua(:,:n2,mpar) lus(:,:n2,mpar) = lus(:,:n2,mpar) + lua(:,:n2,mpar) rcons(:,:n2,mpar) = rcons(:,:n2,mpar) + rcona(:,:n2,mpar) zcons(:,:n2,mpar) = zcons(:,:n2,mpar) + zcona(:,:n2,mpar) IF (lthreed) THEN rvs(:,:n2,mpar) = rvs(:,:n2,mpar) + rva(:,:n2,mpar) zvs(:,:n2,mpar) = zvs(:,:n2,mpar) + zva(:,:n2,mpar) lvs(:,:n2,mpar) = lvs(:,:n2,mpar) + lva(:,:n2,mpar) END IF END DO CALl second0(tsymoff) s_symrzl_time = s_symrzl_time + (tsymoff - tsymon) END SUBROUTINE symrzl
-- 2018-11-02, Jesper: -- Problem reported by Martin Escardo -- Example by Guillaume Brunerie -- C-c C-s was generating postfix projections -- even with --postfix-projections disabled. open import Agda.Builtin.Equality record _×_ (A B : Set) : Set where constructor _,_ field fst : A snd : B open _×_ postulate A B : Set p : A × B eta : p ≡ ({!!} , snd p) eta = refl -- C-c C-s should fill the hole with 'fst p'.
If $f$ and $g$ are analytic on a set $S$, then $f + g$ is analytic on $S$.
`phi/F1bar/ord` := (A::set) -> proc(x) return sort([op(A)],(a,b) -> ((a=b) or (op(x[{a,b}][a]) < op(x[{a,b}][b])))); end: ###################################################################### # Apply the isomorphism R^1 = R `trim/F1bar` := (A::set) -> proc(x) local u,x0,P,T,a; x0 := table(); P := `list_elements/big_subsets`(A); for T in P do u := `bottom_normalise/SW`(1)(T)(x[T]); x0[T] := table(); for a in T do x0[T][a] := op(u[a]); od; od; return eval(x0): end: ###################################################################### `subcritical_tree/F1bar` := (A::set) -> proc(x) local x0,R,n,SS,i,j,J,J1,g1,g2,is_subcritical,a,k; x0 := `trim/F1bar`(A)(x); R := `phi/F1bar/ord`(A)(x); n := nops(A); SS := seq({a},a in A); for i from 1 to n-1 do for j from i+1 to n do J := {seq(R[k],k=i..j)}; is_subcritical := true; if i > 1 then J1 := {R[i-1],op(J)}; g1 := `gap/real_functions`(J )(x0[J1]); g2 := `gap/real_functions`(J1)(x0[J1]); if g2 = g1 then is_subcritical := false; fi; fi; if j < n then J1 := {op(J),R[j+1]}; g1 := `gap/real_functions`(J )(x0[J1]); g2 := `gap/real_functions`(J1)(x0[J1]); if g2 = g1 then is_subcritical := false; fi; fi; if is_subcritical then SS := SS,J; fi; od; od; SS := {SS}; return SS; end: ###################################################################### `theta/F1bar/K` := (A::set) -> proc(x) local x0,R,n,SS,i,j,k,J,J1,t,parent; x0 := `trim/F1bar`(A)(x); R := `phi/F1bar/ord`(A)(x); SS := `subcritical_tree/F1bar`(A)(x); parent := parent_map(A)(SS); n := nops(A); t := table(); for i from 1 to n do for j from i to n do J := {seq(R[k],k=i..j)}; if nops(J) = 1 or nops(J) = n then t[J] := 1; elif not(member(J,SS)) then t[J] := 0; else J1 := parent[J]; t[J] := 1 - `gap/real_functions`(J)(x0[J1])/ `gap/real_functions`(J1)(x0[J1]); fi; od; od; return [R,eval(t)]; end: ###################################################################### `phi/K/F1bar` := (A::set) -> proc(Rt) local R,t,n,r,i,j,k,l,x,P,Q,Q1,J,M,M1,m,T,U; R,t := op(Rt); n := nops(A); r := table(); for i from 1 to n do r[R[i]] := i; od; x := table(); m := table(); P := `list_elements/big_subsets`(A); Q := {seq(seq([seq(R[k],k=i..j)],j=i..n),i=1..n)}; Q1 := select(J -> nops(J)>1,Q); for J in Q do m[J] := table(); M := select(U -> ({op(J)} minus {op(U)} <> {}),Q); for i from 1 to nops(J) - 1 do M1 := select(U -> member(J[i],U) and member(J[i+1],U),M); m[J][J[i]] := mul(1-t[{op(U)}],U in M1); od; od; for T in P do x[T] := table(); i := min(op(map(a -> r[a],T))); j := max(op(map(a -> r[a],T))); J := [seq(R[k],k=i..j)]; for k from i to j do if member(R[k],T) then x[T][R[k]] := [add(m[J][R[l]],l=i..k-1)]; fi od; od; return eval(x); end:
module _ where record Semiring (A : Set) : Set where infixl 6 _+_ field _+_ : A → A → A open Semiring {{...}} public infix 4 _≡_ postulate Ord : Set → Set Nat Bool : Set zero : Nat _≡_ : Nat → Nat → Set refl : ∀ {x} → x ≡ x to : ∀ {x} y → x ≡ y trans : {x y z : Nat} → x ≡ y → y ≡ z → x ≡ z instance ringNat′ : Semiring Nat _+N_ : Nat → Nat → Nat instance ringNat : Semiring Nat ringNat ._+_ = _+N_ bad : (a b c : Nat) → a +N b ≡ c +N a bad a b c = trans (to (a + c)) refl -- Should list the errors from testing both ringNat and ringNat′
I’m always impressed when I come across simple tools that Gamemasters can use to rapidly generate content. watabou’s incredible Medieval Fantasy City Generator seems to be exactly that. A time sink of possibility, messing with the options in style and layout means that you can tweak features of the output and find your favoured combination. For Ambria, I have Coast turned off (Layout > Coast) and everything else turned on, unless it’s a small settlement, like this one, where I also turned off Citadel (Layout > Citadel). My output uses Style > Palette > Black & White with Watercolours switched on. Annotations > Small plus Wards. I also set Towers > Square and Buildings > Simple. You could equally turn off the Watercolours and Wards, then do a little colouring of your own – adding labels by hands or in a package like Photoshop (or even something online suitable for quick annotations of imagery). Mapping the exported image to the location, use the wards as both store and accommodation, like Yndaros. Craftspeople, for example, will usually live above or behind their shopfront. Oh and give the Warp function a try. Seriously, I have lost a couple of hours already just generating towns and then warping them in myriad directions. Very nice tool – worthy of a donation for the effort.
" An obligation for rich nations to help poor nations " , especially in times of " immediate need " .
Require Import Arith. Require Import List. Require Import Relations. Require Import Wellfounded. Require Import list_util. Require Import ModEq. Set Implicit Arguments. Hint Resolve le_plus_r le_plus_l le_n_S le_S_n. Section CharType. Variable C: Set. Variable C_eq_dec: forall x y:C, {x=y}+{x<>y}. (* Deterministic Finite Automata *) Record DFA: Set := mkDFA { DFAstates: list nat; DFAtrans: nat->C->nat; DFAinit: nat; DFAaccept: list nat; DFAtrans_const: forall c s, In s DFAstates -> In (DFAtrans s c) DFAstates; DFAinit_const: In DFAinit DFAstates; DFAacc_const: incl DFAaccept DFAstates}. Definition DFAacc (d:DFA) (w:list C) : Prop := In (fold_left (DFAtrans d) w (DFAinit d)) (DFAaccept d). Definition DFAacc_dec: forall d w, {DFAacc d w}+{~DFAacc d w}. intros. destruct (in_dec nat_eq_dec (fold_left (DFAtrans d) w (DFAinit d)) (DFAaccept d)); [left|right]; auto. Defined. Definition DFA_neg: forall d, {e|forall w, DFAacc e w <-> ~DFAacc d w}. intros. destruct d. assert (H:incl (removeAll nat_eq_dec DFAaccept0 DFAstates0) DFAstates0). intros s Hs. apply removeAll_In in Hs. destruct Hs; auto. exists (mkDFA DFAtrans0 DFAinit0 DFAtrans_const0 DFAinit_const0 H). unfold DFAacc; simpl; intros; split; intros. apply removeAll_In in H0. destruct H0; auto. apply removeAll_In. split; auto. clear -DFAinit_const0 DFAtrans_const0. revert DFAinit_const0. generalize DFAinit0. induction w; simpl; auto. Defined. Definition DFA_and: forall d1 d2, {e|forall w, DFAacc e w <-> DFAacc d1 w /\ DFAacc d2 w}. intros. destruct d1 as [st1 tr1 i1 a1 Ht1 Hi1 Ha1]. destruct d2 as [st2 tr2 i2 a2 Ht2 Hi2 Ha2]. destruct (ubound_sig st2) as [u H _]. destruct (nat_eq_dec u 0) as [Hu|Hu]. subst u. absurd (i2<0); auto. remember (flat_map (fun x=> (map (fun y=>x*u+y) st2)) st1) as st. remember (i1*u+i2) as i. remember (flat_map (fun x=>map (fun y=>x*u+y) a2) a1) as a. remember (fun s c=> let (s1,s2):=(divN Hu s,modN Hu s) in tr1 s1 c*u+tr2 s2 c) as tr. assert (Htr:forall c s, In s st-> In (tr s c) st). subst st tr. intros. apply in_flat_map. apply in_flat_map in H0. destruct H0 as [s1 [H1 H2]]. apply in_map_iff in H2. destruct H2 as [s2 [H2 H3]]. subst s. unfold divN. unfold modN. destruct (divmod u (s1*u+s2)) as [[q [r [H4 H5] H6]]|H4]; [|contradiction]. destruct (H6 s1 s2); auto. subst q r. exists (tr1 s1 c). split; auto. apply in_map_iff. exists (tr2 s2 c); auto. assert (Hi:In i st). subst i st. apply in_flat_map. exists i1. split; auto. apply in_map_iff. exists i2; auto. assert (Ha:incl a st). subst a st. intros s Hs. apply in_flat_map in Hs. apply in_flat_map. destruct Hs as [s1 [H0 H1]]. apply in_map_iff in H1. destruct H1 as [s2 [H1 H2]]. subst s. exists s1. split; auto. apply in_map_iff. exists s2; auto. exists (mkDFA tr i Htr Hi Ha). unfold DFAacc; simpl. assert (forall w s1 s2, In s1 st1->In s2 st2->fold_left tr w (s1*u+s2)=fold_left tr1 w s1*u+fold_left tr2 w s2). induction w; simpl; intros; auto. rewrite <- IHw; auto. f_equal. subst tr. unfold divN. unfold modN. destruct (divmod u (s1*u+s2)) as [[q [r [H2 H3] H4]]|H4]; [|contradiction]. destruct (H4 s1 s2); auto. subst q r; auto. intros; split; intros. subst a i. rewrite H0 in H1; auto. apply in_flat_map in H1. destruct H1 as [s1 [H1 H2]]. apply in_map_iff in H2. destruct H2 as [s2 [H2 H3]]. destruct (divmod u (s1*u+s2)) as [[q [r [H4 H5] H6]]|H4]; [|contradiction]. destruct (H6 s1 s2); auto. subst q r. destruct (H6 (fold_left tr1 w i1) (fold_left tr2 w i2)); auto. apply H. revert Hi2. generalize i2. clear -Ht2. induction w; simpl; auto. subst s1 s2; auto. destruct H1. subst tr i a. apply in_flat_map. exists (fold_left tr1 w i1). split; auto. apply in_map_iff. exists (fold_left tr2 w i2). split; auto. rewrite H0; auto. Defined. Definition DFA_nil: {d|forall w, ~DFAacc d w}. assert (Htr:forall (c:C) (s:nat), In s (0::nil) -> In ((fun _ _=>0) c s) (0::nil)). auto. assert (Hi:In 0 (0::nil)). auto. assert (Ha:incl nil (0::nil)). auto. exists (mkDFA (fun _ _=>0) 0 Htr Hi Ha). unfold DFAacc. simpl. intros w D; auto. Defined. Definition DFA_word: forall w, {d|forall cs, DFAacc d cs <-> cs=w}. induction w. assert (Htr:forall c s, In s (1::0::nil) -> In ((fun (c:C) s=> 0) c s) (1::0::nil)). intros. auto. assert (Hi: In 1 (1::0::nil)); auto. assert (Ha: incl (1::nil) (1::0::nil)). intros x Hx. destruct Hx. subst x; auto. destruct H. exists (mkDFA (fun _ _=>0) 1 Htr Hi Ha). unfold DFAacc. simpl. intros; split; intros. destruct H. destruct cs; auto. simpl in H. contradict H. induction cs; simpl. discriminate. auto. destruct H. subst cs. simpl; auto. destruct IHw as [d H]. destruct d as [st tr i ac Htr Hi Ha]. unfold DFAacc in H. simpl in H. destruct (ubound_sig st) as [u Hu _]. remember (fun s c=>if nat_eq_dec s u then if C_eq_dec c a then i else (S u) else if nat_eq_dec s (S u) then (S u) else tr s c) as tr'. assert (Htr':forall c s, In s (S u::u::st) -> In (tr' s c) (S u::u::st)). intros. subst tr'. destruct (nat_eq_dec s u). destruct (C_eq_dec c a); auto. destruct (nat_eq_dec s (S u)); auto. right; right. apply Htr. destruct H0. contradict n0; auto. destruct H0. contradict n; auto. auto. assert (Hi':In u (S u::u::st)); auto. assert (Ha':incl ac (S u::u::st)); auto. intros x Hx; auto. assert (Ht1:forall s c, In s st ->tr' s c = tr s c). intros. subst tr'. destruct (nat_eq_dec s u). subst s. absurd (u<u); auto. destruct (nat_eq_dec s (S u)). subst s. absurd (S u<u); auto. auto. exists (mkDFA tr' u Htr' Hi' Ha'). unfold DFAacc. simpl. intros; split; intros. destruct cs. simpl in H0. absurd (u<u); auto. simpl in H0. rewrite Heqtr' in H0. destruct (nat_eq_dec u u). destruct (C_eq_dec c a). subst a. f_equal. apply H. rewrite <- Heqtr' in H0. revert H0. revert Hi. generalize i as s. induction cs; simpl; intros; auto. apply IHcs; auto. rewrite Ht1 in H0; auto. rewrite <- Heqtr' in H0. replace (fold_left tr' cs (S u)) with (S u) in H0. absurd (S u<u); auto. clear H0. induction cs; simpl; auto. rewrite IHcs at 1. f_equal. subst tr'. destruct (nat_eq_dec (S u) u). absurd (u<u); auto. rewrite <- e0 at 2; auto. destruct (nat_eq_dec (S u) (S u)); auto. contradict n1; auto. contradict n; auto. subst cs. simpl. replace (tr' u a) with i. replace (fold_left tr' w i) with (fold_left tr w i). apply H; auto. revert Hi. generalize i as s. clear H. induction w; simpl; intros; auto. rewrite Ht1; auto. subst tr'. destruct (nat_eq_dec u u). destruct (C_eq_dec a a); auto. contradict n; auto. contradict n; auto. Defined. (* Non-deterministic Finite Automata *) Record NFA: Type := mkNFA { NFAstates: list nat; NFAtrans: nat -> C -> list nat; NFAinit: list nat; (* take a list for future extension *) NFAaccept: list nat; NFAtrans_const: forall c s, In s NFAstates -> incl (NFAtrans s c) NFAstates; NFAinit_const: incl NFAinit NFAstates; NFAacc_const: incl NFAaccept NFAstates; }. Inductive NFAsteps (tr:nat->C->list nat) : list C -> list nat -> Prop:= | NFAsteps_nil: forall s, NFAsteps tr nil (s::nil) | NFAsteps_cons: forall s t l w c, NFAsteps tr w (t::l) -> In t (tr s c) -> NFAsteps tr (c::w) (s::t::l) . Inductive NFAacc (n:NFA) (w:list C) : Prop := NFAacc_intro: forall is es l, In es (NFAaccept n) ->In is (NFAinit n) -> NFAsteps (NFAtrans n) w l -> Head is l -> Tail es l -> NFAacc n w. Hint Constructors NFAsteps NFAacc. Theorem NFAsteps_const: forall l s w st tr, (forall c s, In s st-> incl (tr s c) st) -> NFAsteps tr w l -> Head s l -> In s st -> incl l st. Proof. induction l; intros. inversion H1. inversion H0. inversion H1. subst a w s0 l a0 l0. intros x Hx. destruct Hx. subst x; auto. destruct H3. inversion H1. subst w s0 l a0 a l1. intros x Hx. destruct Hx. subst x; auto. cut (incl (t::l0) st); intros; auto. apply IHl with (w:=w0) (tr:=tr) (s:=t); auto. apply H in H7; auto. Qed. Definition NFAsteps_states': forall tr w s, {sl| forall l, In l sl <-> Head s l /\ NFAsteps tr w l}. induction w; intros. exists ((s::nil)::nil); intros; split; intros. destruct H. subst l; auto. destruct H. destruct H. inversion H0. subst l. inversion H. subst a s0 l. left; auto. exists (flat_map (fun t=>let (sl,_):= IHw t in map (cons s) sl) (tr s a)). intros; split; intros. apply in_flat_map in H. destruct H as [t [H1 H2]]. destruct (IHw t) as [sl H3]. apply in_map_iff in H2. destruct H2 as [m [H4 H5]]. subst l. split; auto. apply H3 in H5. destruct H5. inversion H. subst a0 m. auto. destruct H. apply in_flat_map. inversion H0. subst a w0 l. inversion H. subst a s0 l. exists t. split; auto. destruct (IHw t) as [sl H6]. apply in_map_iff. exists (t::l0); auto. split; auto. apply H6. auto. Defined. Definition NFAsteps_states: forall tr w sl, {tl| forall t, In t tl <-> exists s l, In s sl /\ NFAsteps tr w l /\ Head s l /\ Tail t l}. intros. exists (map (fun l=>match tail l with inleft (existT _ a _) => a |inright _ => 0 end) (flat_map (fun s=>let (l,_):=NFAsteps_states' tr w s in l) sl)). intros; split; intros. apply in_map_iff in H. destruct H as [x [H H0]]. apply in_flat_map in H0. destruct H0 as [y [H0 H1]]. destruct (NFAsteps_states' tr w y) as [l H2]. apply H2 in H1. destruct H1. destruct (tail x) as [[a [m H4]]|H4]. subst x a. exists y. exists (m++t::nil); auto. subst x t. inversion H1. destruct H as [s [l [H1 [H2 [H3 H4]]]]]. apply in_map_iff. exists l. split. destruct (tail l) as [[a [m H5]]|H5]. subst l. apply Tail_app_rev in H4. inversion H4; auto. inversion H5. discriminate. subst l. inversion H3. apply in_flat_map. exists s. split; auto. destruct (NFAsteps_states' tr w s). apply i. auto. Defined. Definition NFAacc_dec: forall n w, {NFAacc n w}+{~NFAacc n w}. intros. destruct (NFAsteps_states (NFAtrans n) w (NFAinit n)) as [tl H _]. destruct findP with (l:=tl) (P:=fun s=>In s (NFAaccept n)) as [[s H0]|H0]. intros. apply in_dec. apply nat_eq_dec. left. apply H in H0. destruct H0 as [is [l [H1 [H2 [H3 H4]]]]]. apply NFAacc_intro with is s l; auto. right. intros D. inversion D. contradict H1. apply H0. apply H. exists is. exists l; auto. Defined. Theorem NFAsteps_app: forall tr w1 l1, NFAsteps tr w1 l1 -> forall w2 l2 s, NFAsteps tr w2 (s::l2) -> Tail s l1 -> NFAsteps tr (w1++w2) (l1++l2). Proof. intros tr w1 l1 H. induction H; simpl; intros. inversion H0. subst a s0; auto. inversion H3. apply NFAsteps_cons; auto. apply IHNFAsteps with s0; auto. inversion H2; auto. Qed. Theorem NFAsteps_app_s_rev: forall tr l1 l2 w s, NFAsteps tr w (l1++l2) -> Tail s l1 -> exists w1 w2, w=w1++w2 /\ NFAsteps tr w1 l1 /\ NFAsteps tr w2 (s::l2). Proof. induction l1 as [|t l1]; simpl; intros. inversion H0. inversion H. subst w s0. exists nil. exists nil. split; auto. split. destruct l1; auto. inversion H4. destruct l2; auto. destruct l1; inversion H4. subst w s0. rewrite H2 in H4. inversion H0. subst a t l1. simpl in H2. subst l2. exists nil. exists (c::w0); auto. subst a b l0. destruct l1. inversion H6. inversion H2. subst t0 l. apply IHl1 with (s:=s) in H4; auto. destruct H4 as [w1 [w2 [H9 [H7 H8]]]]. exists (c::w1). exists w2. split; simpl; f_equal; auto. Qed. Theorem NFAsteps_app_w_rev: forall tr w1 w2 l, NFAsteps tr (w1++w2) l -> exists s l1 l2, l=l1++l2 /\ NFAsteps tr w1 l1 /\ NFAsteps tr w2 (s::l2) /\ Tail s l1. Proof. induction w1 as [|c w1]; simpl; intros. destruct l as [|t l]. inversion H. exists t. exists (t::nil). exists l; auto. inversion H. subst c0 w l. apply IHw1 in H2. destruct H2 as [u [l1 [l2 [Ha [Hb [Hc Hd]]]]]]. exists u. destruct l1. inversion Hb. inversion Ha. subst n l0. exists (s::t::l1). exists l2. split; auto. Qed. Theorem NFAsteps_parteq: forall tr1 tr2 w l st, incl l st -> (forall s c, In s st -> tr1 s c = tr2 s c) -> NFAsteps tr1 w l -> NFAsteps tr2 w l. Proof. intros. induction H1; auto. apply NFAsteps_cons; auto. apply IHNFAsteps. intros x Hx; auto. rewrite <- H0; auto. Qed. Theorem NFAsteps_length: forall tr w l, NFAsteps tr w l -> length l = S(length w). Proof. intros. induction H; simpl; auto. Qed. (* Non-deterministic Finite Automata with Empty *) Record EFA: Set := mkEFA { EFAstates: list nat; EFAtrans: nat->C->list nat; EFAempty: nat->list nat; EFAinit: list nat; (* take a list for future extension *) EFAaccept: list nat; EFAtrans_const: forall c s, In s EFAstates -> incl (EFAtrans s c) EFAstates; EFAempty_const: forall s, In s EFAstates -> incl (EFAempty s) EFAstates; EFAinit_const: incl EFAinit EFAstates; EFAacc_const: incl EFAaccept EFAstates; }. Inductive EFAsteps (tr:nat->C->list nat) (emp:nat->list nat) : list C -> list nat -> Prop:= | EFAsteps_nil: forall s, EFAsteps tr emp nil (s::nil) | EFAsteps_empty: forall s t l w, EFAsteps tr emp w (t::l) -> In t (emp s) -> EFAsteps tr emp w (s::t::l) | EFAsteps_cons: forall s t l w c, EFAsteps tr emp w (t::l) -> In t (tr s c) -> EFAsteps tr emp (c::w) (s::t::l) . Inductive EFAacc (n:EFA) (w:list C) : Prop := EFAacc_intro: forall is es l, In es (EFAaccept n) -> In is (EFAinit n) -> EFAsteps (EFAtrans n) (EFAempty n) w l -> Head is l -> Tail es l -> EFAacc n w. Hint Constructors EFAsteps EFAacc clos_refl_trans. Theorem EFAsteps_const: forall l w s st tr emp, (forall c s, In s st->incl (tr s c) st) -> (forall s, In s st->incl (emp s) st) -> In s st -> EFAsteps tr emp w l -> Head s l -> incl l st. Proof. induction l; intros. inversion H3. intros x Hx. destruct Hx. subst x. inversion H3. subst a a0 l0. auto. inversion H2. subst w s0 l. destruct H4. subst w0 a l. cut (incl (t::l0) st); intros; auto. apply IHl with (w:=w) (tr:=tr) (emp:=emp) (s:=t); auto. inversion H3. subst a s0 l. apply H0 in H9; auto. inversion H3. subst w a s0 a0 l l1. cut (incl (t::l0) st); intros; auto. apply IHl with (w:=w0) (s:=t) (tr:=tr) (emp:=emp); auto. apply H in H9; auto. Qed. Theorem EFAsteps_app: forall tr emp w1 l1, EFAsteps tr emp w1 l1 -> forall w2 l2 s, EFAsteps tr emp w2 (s::l2) -> Tail s l1 -> EFAsteps tr emp (w1++w2) (l1++l2). Proof. intros tr emp w1 l1 H. induction H; simpl; intros. inversion H0. subst a s0; auto. inversion H3. apply EFAsteps_empty; auto. replace (t::l++l2) with ((t::l)++l2); auto. apply IHEFAsteps with s0; auto. inversion H2; auto. apply EFAsteps_cons; auto. replace (t::l++l2) with ((t::l)++l2); auto. apply IHEFAsteps with s0; auto. inversion H2; auto. Qed. Theorem EFAsteps_app_s_rev: forall tr emp l1 l2 w s, EFAsteps tr emp w (l1++l2) -> Tail s l1 -> exists w1 w2, w=w1++w2 /\ EFAsteps tr emp w1 l1 /\ EFAsteps tr emp w2 (s::l2). Proof. induction l1 as [|t l1]; simpl; intros. inversion H0. inversion H. subst w s0. exists nil. exists nil. split; auto. split. destruct l1; auto. inversion H4. destruct l2; auto. destruct l1; inversion H4. subst w0 s0. rewrite H2 in H4. inversion H0. subst a t l1. simpl in H2. subst l2. exists nil. exists w; auto. subst a b l0. destruct l1. inversion H6. inversion H2. subst n l. apply IHl1 with (s:=s) in H4; auto. destruct H4 as [w1 [w2 [H9 [H7 H8]]]]. exists w1. exists w2. split; auto. subst s0 w. inversion H0. subst a t l1. exists nil. exists (c::w0). simpl in H2. subst l2. auto. subst a b l0. destruct l1. inversion H6. inversion H2. subst n l. replace (t0::l1++l2) with ((t0::l1)++l2) in H4; auto. apply IHl1 with (s:=s) in H4; auto. destruct H4 as [w1 [w2 [H7 [H8 H9]]]]. subst w0. exists (c::w1). exists w2; auto. Qed. Theorem EFAsteps_cons_rev: forall tr emp w c l, EFAsteps tr emp (c::w) l -> exists s t l1 l2, l=l1++t::l2 /\ Tail s l1 /\ EFAsteps tr emp nil l1 /\ EFAsteps tr emp w (t::l2) /\ In t (tr s c). Proof. intros tr emp w c l H. remember (c::w) as w' in H. revert Heqw'. revert c w. induction H; intros. inversion Heqw'. apply IHEFAsteps in Heqw'. destruct Heqw' as [s' [t' [l1' [l2' [H1 [H2 [H3 [H4 H5]]]]]]]]. exists s'. exists t'. exists (s::l1'). exists l2'. split. simpl; f_equal; auto. split ; auto. split; auto. destruct l1'; auto. inversion H1. subst n l; auto. inversion Heqw'. subst c0 w0. exists s. exists t. exists (s::nil). exists l; auto. Qed. Theorem EFAsteps_app_w_rev: forall tr emp w1 w2 l, EFAsteps tr emp (w1++w2) l -> exists s l1 l2, l=l1++l2 /\ Tail s l1 /\ EFAsteps tr emp w1 l1 /\ EFAsteps tr emp w2 (s::l2). Proof. induction w1 as [|c w1]; simpl; intros. destruct l as [|s l]. inversion H. exists s. exists (s::nil). exists l; auto. destruct (EFAsteps_cons_rev H) as [s [t [l1 [l2 [H1 [H2 [H3 [H4 H5]]]]]]]]. subst l. destruct (IHw1 w2 (t::l2) H4) as [u [m1 [m2 [H6 [H7 [H8 H9]]]]]]. destruct m1. inversion H8. inversion H6. subst n l2. exists u. exists (l1++t::m1). exists m2. split; auto. rewrite <- app_assoc; auto. split; auto. split; auto. replace (c::w1) with (nil++c::w1); auto. apply EFAsteps_app with s; auto. Qed. Definition EFA_empty_states': forall emp sl st, (forall s, In s st -> incl (emp s) st) -> incl sl st-> {tl|forall t, In t tl<->exists s, In s sl /\ clos_refl_trans nat (fun x y=>In y (emp x)) s t}. intros emp sl st He. apply (Fix (well_founded_ltof (list nat) (fun l=>length (removeAll nat_eq_dec l st)))) with (P:=fun sl=>incl sl st->{tl|forall t,In t tl<->exists s,In s sl/\clos_refl_trans nat (fun x y=>In y (emp x)) s t}). clear sl. intros sl IH H. destruct (incl_dec nat_eq_dec (flat_map emp sl) sl) as [[x H0 H1]|H0]. destruct (IH (flat_map emp sl++sl)) as [tl H2]. unfold ltof. rewrite removeAll_app. apply removeAll_length2 with x; auto. apply removeAll_In. split; auto. apply in_flat_map in H0. destruct H0 as [y [H2 H3]]. apply He in H3; auto. intros y Hy. apply in_app_or in Hy. destruct Hy; auto. apply in_flat_map in H2. destruct H2 as [z [H3 H4]]. apply He in H4; auto. exists tl. intros t; split; intros. apply H2 in H3. destruct H3 as [s [H4 H5]]. apply in_app_or in H4. destruct H4. apply in_flat_map in H3. destruct H3 as [u [H6 H7]]. exists u. split; auto. apply rt_trans with s; auto. exists s; auto. apply H2. destruct H3 as [s [H4 H5]]. exists s. split; auto. apply in_or_app; auto. exists sl. intros; split; intros. exists t; auto. destruct H1 as [s [H2 H3]]. clear -H0 H2 H3 He. induction H3; auto. apply H0. apply in_flat_map. exists x; auto. Defined. Theorem EFAsteps_incl: forall tr1 emp1 tr2 emp2 w l st, incl l st -> (forall s t, In s st-> In t (emp1 s) -> In t st -> In t (emp2 s)) -> (forall s c t, In s st -> In t (tr1 s c) -> In t st -> In t (tr2 s c)) -> EFAsteps tr1 emp1 w l -> EFAsteps tr2 emp2 w l. Proof. intros. induction H2; auto. apply EFAsteps_empty; auto. apply IHEFAsteps. intros x Hx; auto. apply EFAsteps_cons; auto. apply IHEFAsteps. intros x Hx; auto. Qed. Definition EFA_empty_states: forall tr emp sl st, (forall s, In s st->incl (emp s) st) -> incl sl st -> {tl|forall t, In t tl<->exists s, In s sl /\ exists l, EFAsteps tr emp nil l /\ Head s l /\ Tail t l}. intros. destruct (EFA_empty_states' emp H H0) as [tl H1]. exists tl. intros; split; intros. apply H1 in H2. destruct H2 as [s [H2 H3]]. exists s. split; auto. clear -H3. induction H3. exists (x::y::nil); auto. exists (x::nil); auto. destruct IHclos_refl_trans1 as [l [H1 [H5 H6]]]; auto. destruct IHclos_refl_trans2 as [m [H7 [H9 H10]]]. inversion H9. subst a m. exists (l++l0). split. cut (EFAsteps tr emp (nil++nil) (l++l0)); auto. apply EFAsteps_app with y; auto. split. inversion H5; simpl; auto. inversion H10. subst a z l0. rewrite app_nil_r; auto. subst a b l1. auto. apply H1. destruct H2 as [s [H3 [l [H4 [H5 H6]]]]]. exists s; split; auto. inversion H5. subst a l. clear -H4 H6. revert H6 H4. revert s. induction l0; intros. inversion H6. apply rt_refl. inversion H1. inversion H4. subst w s0 t0 l0. apply rt_trans with a. apply rt_step; auto. apply IHl0; auto. inversion H6; auto. Defined. Definition EFAsteps_states: forall tr emp w sl st, (forall c s, In s st->incl (tr s c) st) -> (forall s, In s st->incl (emp s) st) ->incl sl st -> {tl|forall t, In t tl <-> exists s, In s sl /\ exists l, EFAsteps tr emp w l /\ Head s l /\ Tail t l}. induction w as [|c w]; intros. destruct (EFA_empty_states tr emp H0 H1) as [tl H2]. exists tl. auto. destruct (EFA_empty_states tr emp H0 H1) as [tl H2]. assert (H3: incl (flat_map (fun s=>tr s c) tl) st). intros x Hx. apply in_flat_map in Hx. destruct Hx as [y [H3 H4]]. apply H in H4; auto. destruct (H2 y). destruct (H5 H3) as [s [Ha [l [Hb [Hc Hd]]]]]. apply EFAsteps_const with (s:=s) (st:=st) in Hb; auto. destruct (IHw (flat_map (fun s=>tr s c) tl) st H H0 H3) as [ul H4]. clear IHw. exists ul. intros; split; intros. apply H4 in H5. destruct H5 as [s [Ha [l [Hb [Hc Hd]]]]]. clear H4. apply in_flat_map in Ha. destruct Ha as [x [H4 H5]]. apply H2 in H4. destruct H4 as [y [H4 [m [H8 [H6 H7]]]]]. clear H2. exists y. split; auto. exists (m++l). split. replace (c::w) with (nil++c::w); auto. apply EFAsteps_app with x; auto. inversion Hc. subst a l. apply EFAsteps_cons; auto. split. inversion H6; simpl; auto. auto. apply H4. clear H4. destruct H5 as [s [H4 [l [H8 [H6 H7]]]]]. destruct (EFAsteps_cons_rev H8) as [u [v [l1 [l2 [Ha [Hb [Hc [Hd He]]]]]]]]. subst l. exists v. split. apply in_flat_map. exists u. split; auto. apply H2. clear H2. exists s. split; auto. exists l1; auto. split; auto. split; auto. destruct l1. inversion Hc. inversion H6; auto. exists (v::l2). split; auto. split; auto. apply Tail_app_rev in H7; auto. discriminate. Defined. Definition EFAacc_dec: forall n w, {EFAacc n w}+{~EFAacc n w}. intros. destruct EFAsteps_states with (tr:=EFAtrans n) (emp:=EFAempty n) (sl:=EFAinit n) (w:=w) (st:=EFAstates n) as [tl H]. apply (EFAtrans_const n). apply (EFAempty_const n). apply (EFAinit_const n); auto. destruct findP with (P:=fun s=>In s tl) (l:=EFAaccept n). intros. apply in_dec. apply nat_eq_dec. destruct s as [s H1 H2]. left. apply H in H2. destruct H2 as [is [H4 [l [H5 [H6 H7]]]]]. apply EFAacc_intro with is s l; auto. right. intros D. inversion D. apply n0 in H0. contradict H0. apply H. exists is. split; auto. exists l; auto. Defined. Definition EFA2NFA: forall e, {n| forall w, EFAacc e w <-> NFAacc n w}. intros. destruct (EFA_empty_states (EFAtrans e) (EFAempty e) (EFAempty_const e) (EFAinit_const e)) as [is H]. assert (Hi: incl is (EFAstates e)). intros x Hx. apply H in Hx. destruct Hx as [s [H1 [l [H2 [H3 H4]]]]]. apply (EFAinit_const e) in H1. apply EFAsteps_const with (s:=s) (st:=EFAstates e) in H2; auto. apply (EFAtrans_const e). apply (EFAempty_const e); auto. remember (fun s c=>match in_dec nat_eq_dec s (EFAstates e) with |left H => match EFA_empty_states (EFAtrans e) (EFAempty e) (EFAempty_const e) (EFAtrans_const e c s H) with exist _ sl _ => sl end |right _ => nil end) as tr. assert (Ht: forall c s, In s (EFAstates e) -> incl (tr s c) (EFAstates e)). intros. subst tr. destruct (in_dec nat_eq_dec s (EFAstates e)); [|contradiction]. destruct (EFA_empty_states (EFAtrans e) (EFAempty e) (EFAempty_const e) (EFAtrans_const e c s i)) as [tl H1]. intros x Hx. apply H1 in Hx. destruct Hx as [t [H2 [l [H3 [H4 H5]]]]]. inversion H4. subst a l. assert (In t (EFAstates e)). apply (EFAtrans_const e c s); auto. apply EFAsteps_const with (s:=t) (st:=EFAstates e) in H3; auto. apply EFAtrans_const. apply EFAempty_const. exists (mkNFA (NFAstates:=EFAstates e) tr Ht Hi (EFAacc_const e)). cut (forall w t, (exists s, In s (EFAinit e) /\ exists l, EFAsteps (EFAtrans e) (EFAempty e) w l /\ Head s l /\ Tail t l) <-> exists s, In s is /\ exists l, NFAsteps tr w l /\ Head s l /\ Tail t l). intros; split; intros. inversion H1. assert (exists s, In s (EFAinit e) /\ exists l, EFAsteps (EFAtrans e) (EFAempty e) w l /\ Head s l /\ Tail es l). exists is0. split; auto. exists l; auto. apply (H0 w es) in H7. destruct H7 as [s [Ha [m [Hb [Hc Hd]]]]]. apply NFAacc_intro with s es m; auto. inversion H1. assert (exists s, In s is/\ exists l, NFAsteps tr w l /\ Head s l /\Tail es l). exists is0; split; auto. exists l; auto. apply H0 in H7. destruct H7 as [s [Ha [m [Hb [Hc Hd]]]]]. apply EFAacc_intro with s es m; auto. intros w. apply (Fix (well_founded_ltof (list C) (length (A:=C)))) with (P:=fun w=>forall t, (exists s, In s (EFAinit e)/\(exists l, EFAsteps (EFAtrans e) (EFAempty e) w l/\Head s l/\Tail t l))<->(exists s, In s is/\exists l, NFAsteps tr w l/\Head s l/\Tail t l)). clear w. intros w IH t. destruct (tail w) as [[c [w' H1]]|H1]. subst w. split; intros. destruct H0 as [s [H1 [l [H2 [H3 H4]]]]]. apply EFAsteps_app_w_rev in H2. destruct H2 as [u [l1 [l2 [Ha [Hb [Hc Hd]]]]]]. subst l. apply EFAsteps_cons_rev in Hd. destruct Hd as [v [w [m1 [m2 [H5 [H6 [H7 [H8 H9]]]]]]]]. assert (exists s, In s (EFAinit e) /\ exists l, EFAsteps (EFAtrans e) (EFAempty e) w' l/\Head s l/\Tail v l). exists s. split; auto. destruct m1. inversion H7. inversion H5. subst n l2. exists (l1++m1); auto. split; auto. replace w' with (w'++nil). apply EFAsteps_app with u; auto. rewrite app_nil_r; auto. split. destruct l1. inversion Hc. inversion H3; simpl; auto. inversion H6. subst v m1 a. rewrite app_nil_r; auto. clear -H10. induction l1; simpl; auto. apply IH in H0. clear IH. destruct H0 as [x [Hd [l [He [Hf Hg]]]]]. exists x. split; auto. exists (l++t::nil). split. apply NFAsteps_app with v; auto. apply NFAsteps_cons; auto. simpl. subst tr. destruct (in_dec nat_eq_dec v (EFAstates e)). destruct (EFA_empty_states (EFAtrans e) (EFAempty e) (EFAempty_const e) (EFAtrans_const e c v i)). apply i0. exists w. split; auto. exists (w::m2). split; auto. split; auto. destruct l2. destruct m1. inversion H7. inversion H5. destruct m1; inversion H10. clear -H5 H4. assert (Tail t (n::l2)). induction l1; auto. apply IHl1. inversion H4; auto. destruct l1; inversion H2. destruct m1. inversion H5. subst u m2. auto. inversion H5. rewrite H2 in H. clear -H. induction m1; auto. apply IHm1. inversion H; auto. destruct m1; inversion H3. contradict n. apply Hi in Hd. inversion Hf. subst a l. apply NFAsteps_const with (s:=x) (st:=EFAstates e) in He; auto. split. inversion Hf; simpl; auto. auto. unfold ltof. rewrite app_length. rewrite plus_comm; auto. destruct H0 as [u [H1 [l [H2 [H3 H4]]]]]. apply NFAsteps_app_w_rev in H2. destruct H2 as [v [m1 [m2 [Ha [Hb [Hc Hd]]]]]]. subst l. assert (exists s, In s is/\exists l, NFAsteps tr w' l/\Head s l/\Tail v l). exists u. split; auto. exists m1; split; auto. split; auto. destruct m1. inversion Hb. inversion H3; auto. apply IH in H0. clear IH. destruct H0 as [x [H5 [l [H6 [H7 H8]]]]]. exists x; split; auto. inversion Hc. subst c0 w s m2. clear Hc. simpl in H12. inversion H10. subst t0 l0. clear H10. assert (s=t). clear -H4. induction m1; simpl; auto. inversion H4; auto. inversion H1. apply IHm1. inversion H4; auto. destruct m1; inversion H2. subst s. clear H4. subst tr. destruct (in_dec nat_eq_dec v (EFAstates e)). destruct (EFA_empty_states (EFAtrans e) (EFAempty e) (EFAempty_const e) (EFAtrans_const e c v i)). apply i0 in H12. destruct H12 as [s [H13 [m [H14 [H15 H16]]]]]. exists (l++m). split. apply EFAsteps_app with v; auto. inversion H15. subst a m. apply EFAsteps_cons; auto. split. inversion H7; simpl; auto. apply Tail_app; auto. inversion H12. unfold ltof. rewrite app_length. rewrite plus_comm; auto. subst w. clear IH. split; intros. destruct H0 as [s [H1 [l [H2 [H3 H4]]]]]. exists t. split. apply H. exists s. split; auto. exists l; auto. exists (t::nil); auto. destruct H0 as [s [H1 [l [H2 [H3 H4]]]]]. inversion H2. subst l. inversion H3. subst a s0 l. inversion H4. subst a t. apply H in H1. destruct H1 as [t [Ha [l [Hb [Hc Hd]]]]]. exists t. split; auto. exists l; auto. inversion H6. Defined. Definition NFA2EFA: forall n, {e|forall w, EFAacc e w <-> NFAacc n w}. intros. assert (H: forall s, In s (NFAstates n) -> incl ((fun _=>nil) s) (NFAstates n)). intros. intros x Hx; inversion Hx. exists (mkEFA (NFAtrans n) (fun _ => nil) (NFAtrans_const n) H (NFAinit_const n) (NFAacc_const n)). intros; split; intros. inversion H0. clear H0. simpl in H1. simpl in H2. apply NFAacc_intro with is es l; auto. clear -H3. simpl in H3. induction H3; auto. inversion H0. inversion H0. apply EFAacc_intro with is es l; auto. clear -H3. simpl. induction H3; auto. Defined. Definition DFA2NFA: forall d, {n|forall w, DFAacc d w <-> NFAacc n w}. intros. assert (Ht: forall c s, In s (DFAstates d)->incl (DFAtrans d s c::nil) (DFAstates d)). intros. intros x Hx. destruct Hx. subst x. apply DFAtrans_const; auto. destruct H0. assert (Hi: incl (DFAinit d::nil) (DFAstates d)). intros x Hx. destruct Hx. subst x. apply DFAinit_const; auto. destruct H. exists (mkNFA (fun s c=>DFAtrans d s c::nil) Ht Hi (DFAacc_const d)). unfold DFAacc. cut (forall w s t, t=fold_left (DFAtrans d) w s <-> exists l, NFAsteps (fun s c =>DFAtrans d s c::nil) w l /\ Head s l /\Tail t l). intros. split; intros. destruct (H w (DFAinit d) (fold_left (DFAtrans d) w (DFAinit d))). destruct H1 as [l [H3 [H4 H5]]]; auto. apply NFAacc_intro with (DFAinit d) (fold_left (DFAtrans d) w (DFAinit d)) l; auto. simpl. auto. inversion H0. clear H0. simpl in H1. simpl in H2. destruct H2; [|destruct H0]. subst is. assert (es=fold_left (DFAtrans d) w (DFAinit d)). apply H. exists l; auto. rewrite <- H0; auto. induction w; intros; split; intros. simpl in H. subst t. exists (s::nil); auto. destruct H as [l [H1 [H2 H3]]]. inversion H1. subst l. inversion H2. subst a s0 l. inversion H3. subst t; auto. inversion H4. simpl in H. subst t. destruct (IHw (DFAtrans d s a) (fold_left (DFAtrans d) w (DFAtrans d s a))). clear IHw H0. destruct H as [l [H1 [H2 H3]]]; auto. exists (s::l). split; auto. inversion H2. subst a0 l. apply NFAsteps_cons; auto. simpl. destruct H as [l [H1 [H2 H3]]]. inversion H1. clear H1. simpl in H6. destruct H6; [|destruct H1]. subst a w0 l t0. simpl. apply IHw. clear IHw. inversion H2. subst s0 a l. exists (DFAtrans d s c::l0); auto. split; auto. split; auto. inversion H3; auto. Defined. Definition DFA2EFA: forall d, {e|forall w, DFAacc d w <-> EFAacc e w}. intros. destruct (DFA2NFA d) as [n H]. destruct (NFA2EFA n) as [e H0]. exists e. intros; split; intros. apply H0. apply H; auto. apply H; apply H0; auto. Defined. Definition NFA2DFA: forall n, {d|forall w, NFAacc n w <-> DFAacc d w}. intros. remember (fun s c=>ps2i nat_eq_dec (NFAstates n) (flat_map (fun s=>NFAtrans n s c) (i2ps nat_eq_dec (NFAstates n) s))) as t. assert (Hu: forall c s, In s (seq 0 (psSize nat_eq_dec (NFAstates n))) -> In (t s c) (seq 0 (psSize nat_eq_dec (NFAstates n)))). intros. subst t. apply in_seq. split. apply le_O_n. apply ps2i_spec1. intros x Hx. apply in_flat_map in Hx. destruct Hx as [y [H4 H5]]. apply NFAtrans_const in H5; auto. apply i2ps_spec1 in H4; auto. apply in_seq in H. destruct H; auto. assert (Hj: In (ps2i nat_eq_dec (NFAstates n) (NFAinit n)) (seq 0 (psSize nat_eq_dec (NFAstates n)))). apply in_seq. split. apply le_O_n. apply ps2i_spec1. intros x Hx. apply NFAinit_const; auto. destruct (contain_powerSet nat_eq_dec (NFAstates n) (NFAaccept n)) as [al H4]. assert (Hac: incl (map (ps2i nat_eq_dec (NFAstates n)) al) (seq 0 (psSize nat_eq_dec (NFAstates n)))). intros x Hx. apply in_seq. split. apply le_O_n. apply in_map_iff in Hx. destruct Hx as [y [H1 H2]]. subst x. apply ps2i_spec1; auto. assert (Exists (equiv y) al). apply Exists_exists. exists y; split; auto. apply equiv_refl. apply H4 in H. destruct H; auto. exists (mkDFA t (ps2i nat_eq_dec (NFAstates n) (NFAinit n)) Hu Hj Hac). assert (H5: forall w, fold_left t w (ps2i nat_eq_dec (NFAstates n) (NFAinit n)) = let (tl,_) := NFAsteps_states (NFAtrans n) w (NFAinit n) in ps2i nat_eq_dec (NFAstates n) tl). apply (Fix (well_founded_ltof (list C) (length (A:=C)))). intros w IH. destruct (tail w) as [[c [w' H1]]|H1]. subst w. destruct (NFAsteps_states (NFAtrans n) (w'++c::nil) (NFAinit n)) as [tl H1]. rewrite fold_left_app. rewrite IH. clear IH. destruct (NFAsteps_states (NFAtrans n) w' (NFAinit n)) as [ul H0]. assert (Hv:incl ul (NFAstates n)). intros z Hz. apply H0 in Hz. destruct Hz as [s [l [Hs [Ht [Hw Hv]]]]]. apply NFAsteps_const with (s:=s) (st:=NFAstates n) in Ht; auto. apply NFAtrans_const. apply NFAinit_const in Hs; auto. simpl. subst t. apply ps2i_spec3. intros x; split; intros. apply in_flat_map in H. destruct H as [y [H5 H6]]. apply i2ps_spec3 in H5. apply H1. apply H0 in H5. destruct H5 as [s [l [Ha [Hb [Hc Hd]]]]]. exists s. exists (l++x::nil); split; auto. split. apply NFAsteps_app with y; auto. split. inversion Hc; simpl; auto. auto. auto. apply H1 in H. destruct H as [s [l [H5 [H6 [H7 H8]]]]]. apply in_flat_map. apply NFAsteps_app_w_rev in H6. destruct H6 as [t [m1 [m2 [Ha [Hb [Hc Hd]]]]]]. subst l. inversion Hc. subst c0 w s0 m2. inversion H6. subst t0 l. apply Tail_app_rev in H8; auto. inversion H8. subst s0. exists t. split; auto. apply i2ps_spec3. apply Hv. subst a. apply H0. exists s. exists m1; split; auto. split; auto. split; auto. destruct m1. inversion Hb. inversion H7; auto. inversion H3. discriminate. unfold ltof. rewrite app_length. simpl. rewrite <- plus_n_Sm. rewrite <- plus_n_O; auto. subst w. simpl. f_equal. generalize (NFAinit n). induction l; simpl; auto. f_equal; auto. intros; split; intros. inversion H. unfold DFAacc; simpl. rewrite H5. destruct (NFAsteps_states (NFAtrans n) w (NFAinit n)) as[tl H7]. assert (H8:incl tl (NFAstates n)). intros x Hx. apply H7 in Hx. destruct Hx as [s [m [Ha [Hb [Hc Hd]]]]]. apply NFAsteps_const with (s:=s) (st:=NFAstates n) in Hb; auto. apply NFAtrans_const. apply NFAinit_const in Ha; auto. assert (Exists (equiv tl) al). apply H4. split; auto. exists es; split; auto. apply H7. exists is. exists l; split; auto. apply Exists_exists in H9. destruct H9 as [x [Ha Hb]]. apply in_map_iff. exists x; split; auto. apply ps2i_spec3. apply equiv_sym; auto. unfold DFAacc in H. simpl in H. apply in_map_iff in H. destruct H as [x [H1 H2]]. rewrite H5 in H1. destruct (NFAsteps_states (NFAtrans n) w (NFAinit n)) as [ul H6]. assert (H7:incl ul (NFAstates n)). intros y Hy. apply H6 in Hy. destruct Hy as [s [m [Ha [Hb [Hc Hd]]]]]. apply NFAsteps_const with (s:=s) (st:=NFAstates n) in Hb; auto. apply NFAtrans_const. apply NFAinit_const in Ha; auto. apply ps2i_spec2 in H1; auto. assert (Exists (equiv ul) al). apply Exists_exists. exists x. split; auto. apply equiv_sym; auto. apply H4 in H. destruct H. destruct H0 as [y [H8 H9]]. apply H6 in H8. destruct H8 as [s [l [Ha [Hb [Hc Hd]]]]]. apply NFAacc_intro with s y l; auto. assert (Exists (equiv x) al). apply Exists_exists. exists x; split; auto. apply equiv_refl. apply H4 in H. destruct H; auto. Defined. Definition EFA2DFA: forall e, {d|forall w, EFAacc e w <-> DFAacc d w}. intros. destruct (EFA2NFA e) as [n H]. destruct (NFA2DFA n) as [d H0]. exists d; intros; split; intros. apply H0. apply H; auto. apply H; apply H0; auto. Defined. Definition EFA_map: forall e (f:nat->nat), (forall x y, In x (EFAstates e) -> In y (EFAstates e) -> f x=f y -> x=y) -> {e'|EFAstates e'=map f (EFAstates e) & forall w, EFAacc e w <-> EFAacc e' w}. intros e. destruct e as [st tr emp ini acc Htr Hemp Hini Hacc]. simpl. intros. destruct (inv_func nat_eq_dec f st 0 H) as [g Hg1 _]. remember (fun s c=>map f (tr (g s) c)) as tr'. assert (Htr': forall c s, In s (map f st) -> incl (tr' s c) (map f st)). intros. apply in_map_iff in H0. destruct H0 as [x [H1 H2]]. subst s. subst tr'. rewrite Hg1; auto. intros y Hy. apply in_map_iff in Hy. destruct Hy as [z [H3 H4]]. subst y. apply in_map_iff. exists z; split; auto. apply Htr in H4; auto. remember (fun s=>map f (emp (g s))) as emp'. assert (Hemp': forall s, In s (map f st)->incl (emp' s) (map f st)). intros. apply in_map_iff in H0. destruct H0 as [x [H1 H2]]. subst s. subst emp'. rewrite Hg1; auto. intros y Hy. apply in_map_iff in Hy. destruct Hy as [z [H3 H4]]. subst y. apply in_map_iff. exists z; split; auto. apply Hemp in H4; auto. assert (Hini': forall s, In s (map f ini)->In s (map f st)). intros. apply in_map_iff in H0. destruct H0 as [x [H1 H2]]. subst s. apply in_map_iff. exists x; split; auto. assert (Hacc': incl (map f acc) (map f st)). intros x Hx. apply in_map_iff in Hx. destruct Hx as [y [H1 H2]]. subst x. apply in_map_iff. exists y; split; auto. exists (mkEFA tr' emp' Htr' Hemp' Hini' Hacc'); auto. intros; split; intros; inversion H0. simpl in H1. simpl in H2. clear H0. apply EFAacc_intro with (f is) (f es) (map f l); simpl; auto. simpl in H3. apply in_map_iff. exists es; split; auto. simpl in H3. apply in_map_iff. exists is; auto. simpl in H3. assert (H6:incl l st). apply EFAsteps_const with (s:=is) (st:=st) in H3; auto. subst emp' tr'. clear -H3 H6 Hg1. revert H3. revert H6. revert w. induction l; intros. inversion H3. inversion H3; simpl; auto. subst a w0 l. apply EFAsteps_empty; auto. apply IHl; auto. intros x Hx. apply H6. right; auto. simpl. simpl in H4. apply in_map_iff. exists t. split; auto. rewrite Hg1; auto. subst a w l. apply EFAsteps_cons; auto. apply IHl; auto. intros x Hx. apply H6. right; auto. simpl. rewrite Hg1; auto. apply in_map_iff. exists t; split; auto. inversion H4; simpl; auto. clear -H5. induction H5; simpl; auto. simpl in H1. simpl in H2. clear H0. apply in_map_iff in H1. destruct H1 as [es' [H6 H1]]. subst es. apply in_map_iff in H2. destruct H2 as [is' [H6 H2]]. subst is. apply EFAacc_intro with is' es' (map g l); simpl; auto. assert (H6:incl l (map f st)). apply EFAsteps_const with (s:=f is') (st:=map f st) in H3; auto. apply in_map_iff. exists is'; split; auto. simpl in H3. revert H3. revert H6. revert w. subst emp' tr'. clear -Hemp Htr Hg1. induction l; intros. inversion H3. inversion H3; simpl; auto. apply EFAsteps_empty; auto. subst w0 a l. apply IHl; auto. intros x Hx; auto. simpl. simpl in H4. subst a w0 l. apply in_map_iff in H4. destruct H4 as [u [H4 H5]]. subst t. rewrite Hg1; auto. apply Hemp in H5; auto. cut (In s (map f st)); intros. apply in_map_iff in H. destruct H as [x [H7 H8]]. subst s. rewrite Hg1; auto. apply H6; auto. apply EFAsteps_cons; auto. subst w a l. apply IHl; auto. intros x Hx; auto. simpl. subst w a l. simpl in H4. apply in_map_iff in H4. destruct H4 as [u [H4 H5]]. subst t. rewrite Hg1; auto. apply Htr in H5; auto. cut (In s (map f st)); intros; auto. apply in_map_iff in H. destruct H as [x [H8 H7]]. subst s. rewrite Hg1; auto. inversion H4; simpl. rewrite Hg1; auto. apply Hacc in H1. clear -H1 H5 Hg1. induction l. inversion H5. simpl. inversion H5; auto. simpl. rewrite Hg1; auto. Defined. End CharType. Hint Constructors NFAsteps NFAacc EFAsteps EFAacc.
[STATEMENT] lemma is_hashmap_finite[simp]: "h \<Turnstile> is_hashmap m mi \<Longrightarrow> finite (dom m)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. h \<Turnstile> is_hashmap m mi \<Longrightarrow> finite (dom m) [PROOF STEP] unfolding is_hashmap_def is_hashmap'_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. h \<Turnstile> (\<exists>\<^sub>Al. is_hashtable l mi * \<up> (map_of (concat l) = m)) \<Longrightarrow> finite (dom m) [PROOF STEP] by auto
(* 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: gga_exc *) (* prefix: gga_x_b88_params *params; assert(p->params != NULL); params = (gga_x_b88_params * )(p->params); *) $ifdef gga_x_b88_params params_a_beta := 0.0042: params_a_gamma := 6.0: $endif b88_f := x -> 1 + params_a_beta/X_FACTOR_C*x^2/(1 + params_a_gamma*params_a_beta*x*arcsinh(x)): f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(b88_f, rs, zeta, xs0, xs1):
function dx = susp_sys(x,u) % Dynamics of the syspension system x1 = x(1); x2 = x(2); x3 = x(3); x4 = x(4); % Coefficients mb = 300; % kg mw = 60; % kg bs = 1000; % N/m/s ks = 16000 ; % N/m kt = 190000; % N/m kn = ks/10; % N/m % System Dynamics dx1 = x2; dx2 = -(ks*(x1-x3)+kn*(x1-x3)^3)/mb - (bs*(x2-x4)-10000*u)/mb; dx3 = x4; dx4 = (ks*(x1-x3)+kn*(x1-x3)^3)/mw + (bs*(x2-x4)-kt*x3-10000*u)/mw; % Combine the output dx = [dx1; dx2; dx3; dx4]; end
K 'inich B 'aaknal Chaak was enthroned in 688 , twenty years after Ruler 2 , and reigned for twenty @-@ seven years . During his reign he restored Toniná 's power with a number of military victories over Palenque , and his reign was dominated by the struggle against the rival city for regional power . Ballcourt 1 , the larger of Toniná 's two ballcourts , was dedicated in 699 to celebrate three victories over the city 's arch @-@ rival . The ballcourt originally had six sculptures of bound captives , all vassals of the enemy Palenque king from the Usumacinta region . The date of the king 's death is unknown .
import System.File main : IO () main = do Right () <- copyFile "source.bin" "dest.bin" | Left err => printLn err pure ()
# Loglinear Regression Loglinear regressions treat the explanatory variable as an exponential function of the parameters, i.e.: \begin{equation} ln(y) = \mathbf{\beta \cdot x} + \epsilon \end{equation} With $\epsilon$ some noise term. The exogenous variabel $y$ has to be strictly positive. Effectively, the algorithm fits an exponential curve, which seems like an extreme assumption about the data at first. However, for sufficiently small coefficients, the exponential relationship is approximately linear. Empirically, loglinear and linear models seem to be about equally good at fitting line data when the data has approximately normal distribution, though they find notably different fits. The loglinear model even remains accurate in the interval of the exogenous variable not overlapping with the training data. In the presence of outliers (which I modeled using a fat tailed noise distribution), the loglinear model has worse error when the error is averaged over many examples. However, in individual cases, the loglinear fit can actually be quite a bit better at outlier rejection than the linear fit. Below, linear and loglinear regressions are fit to line data with t-distributed noise. The mean squared error and mean absolute error for train/test splits on the same range and on disconnected ranges are measured for different degrees of freedom of the noise distribution, ranging from highly fat tailed to normal. Lower degrees of freedom lead to fatter tails, high degrees of freedom result in normally distributed loss. It is running once for a relatively small dataset (N=5) and one for a moderately-sized dataset (N=100). It's worth nothing that all the experiments below are in 1D. ### Motivation for Loglinear Regression: Loglinear regression is a good choice when the effect of the exogenous variables is expected to be multiplicative, rather than additive. For example, when rates are in play where an exogenous variable modulates the impact of another exogenous variable. #### Example For example, assume that the number of customers $y$ at a bar are assumed to depend on the number of people living close by ($p \in [0,\infty)$) and whether the next day is a workday or not ($I_w \in [0,1]$). In that case, whether the next day is work day or not should not add a fixed number of customers across all bars. Rather, it makes it more likely that people will go to a bar, and so bars in areas with lots of people living close by should see a proportional increase in customers. The model should be: \begin{equation} y = c_p p c_w^{I_w} \end{equation} Where $c_p$ is the rate of someone close by going to a bar (at all) and $c_w$ is the rate increase on weekends. Taking the logarithm transforms this into a line equation: \begin{equation} \begin{array}{rl} ln(y) &= ln(c_p) + ln(p) + ln(c_w) I_w \\ ln(\frac{y}{p}) &= ln(c_p) + ln(c_w) I_w \end{array} \end{equation} Which gives a loglinear model. Less convincing would be: \begin{equation} y = e^{ap + b I_w + c} \end{equation} So then: \begin{equation} ln(y) = c + ap + b I_w \end{equation} In that case the impact of the population parameter is modeled exponentially, which is a bit strange. ```python import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error """ Make Data, linear case, fat-tailed noise """ x_eval = np.linspace(0,20,100).reshape(-1,1) x_train = (5,10) def get_data(N,df=1,x_range=x_train): a = 10.3 b = 10.25 eps = 10.5 x = np.sort(np.random.uniform(low=x_train[0],high=x_train[1],size=N)) y = np.abs(a + b*x + eps*np.random.standard_t(df=df,size=N)) return x.reshape(-1,1),y.reshape(-1,1) class LogLinearRegression(LinearRegression): def fit(self,x,y): return super().fit(x,np.log(y)) def predict(self,x): return np.exp(super().predict(x)) """ Fit """ x,y = get_data(10) linreg = LinearRegression().fit(x,y) loglinreg = LogLinearRegression().fit(x,y) fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(1,1,1) ax1.plot(x,y,'o') ax1.plot(x_eval,linreg.predict(x_eval)) ax1.plot(x_eval,loglinreg.predict(x_eval)) ``` ```python def get_error(model,x_range_train,x_range_test,df,n_datapoints_train): """ train & test out of sample """ N_TRIALS = 100000 # takes forever!! N_DATAPOINTS_TEST = 1000 msq = [] mae = [] for i in range(N_TRIALS): if i% 1000 == 0: print("trials: %i/%i" % (i,N_TRIALS),end='\r') x_train,y_train = get_data(n_datapoints_train, df=df, x_range=x_range_train) x_test,y_test = get_data(N_DATAPOINTS_TEST, df=df, x_range=x_range_train) model.fit(x_train,y_train) y_pred = model.predict(x_test) msq.append(mean_squared_error(y_pred,y_test)) mae.append(mean_absolute_error(y_pred,y_test)) print("df=%i done." % df) return np.mean(msq),np.mean(mae) dfs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] linreg_errors_vs_df = np.array([get_error(LinearRegression(),x_range_train=(5,10),x_range_test=(5,10),df=df,n_datapoints_train=5) for df in dfs]) loglinreg_errors_vs_df = np.array([get_error(LogLinearRegression(),x_range_train=(5,10),x_range_test=(5,10),df=df,n_datapoints_train=5) for df in dfs]) fig = plt.figure(figsize=(12,5)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.semilogy(dfs,linreg_errors_vs_df[:,0],'d-') ax1.semilogy(dfs,loglinreg_errors_vs_df[:,0],'o-') ax1.set_title('msq') ax1.legend('lingreg,loglinreg'.split(',')) ax1.set_xlabel("student's t-noise dof") ax2.semilogy(dfs,linreg_errors_vs_df[:,1],'d-') ax2.semilogy(dfs,loglinreg_errors_vs_df[:,1],'o-') ax2.set_title('mae') ax2.legend('linreg,loglinreg'.split(',')) ax2.set_xlabel("student's t-noise dof") plt.suptitle("Same Range, 5 Datapoints") ``` ```python linreg_errors_vs_df = np.array([get_error(LinearRegression(),x_range_train=(5,10),x_range_test=(10,15),df=df,n_datapoints_train=5) for df in dfs]) loglinreg_errors_vs_df = np.array([get_error(LogLinearRegression(),x_range_train=(5,10),x_range_test=(10,15),df=df,n_datapoints_train=5) for df in dfs]) fig = plt.figure(figsize=(12,5)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.semilogy(dfs,linreg_errors_vs_df[:,0],'d-') ax1.semilogy(dfs,loglinreg_errors_vs_df[:,0],'o-') ax1.set_title('msq') ax1.legend('lingreg,loglinreg'.split(',')) ax1.set_xlabel("student's t-noise dof") ax2.semilogy(dfs,linreg_errors_vs_df[:,1],'d-') ax2.semilogy(dfs,loglinreg_errors_vs_df[:,1],'o-') ax2.set_title('mae') ax2.legend('linreg,loglinreg'.split(',')) ax2.set_xlabel("student's t-noise dof") plt.suptitle("Out of Range, 5 Datapoints") ``` ```python """ Increase number of data points """ linreg_errors_vs_df = np.array([get_error(LinearRegression(),x_range_train=(5,10),x_range_test=(5,10),df=df,n_datapoints_train=100) for df in dfs]) loglinreg_errors_vs_df = np.array([get_error(LogLinearRegression(),x_range_train=(5,10),x_range_test=(5,10),df=df,n_datapoints_train=100) for df in dfs]) fig = plt.figure(figsize=(12,5)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.semilogy(dfs,linreg_errors_vs_df[:,0],'d-') ax1.semilogy(dfs,loglinreg_errors_vs_df[:,0],'o-') ax1.set_title('msq') ax1.legend('lingreg,loglinreg'.split(',')) ax1.set_xlabel("student's t-noise dof") ax2.semilogy(dfs,linreg_errors_vs_df[:,1],'d-') ax2.semilogy(dfs,loglinreg_errors_vs_df[:,1],'o-') ax2.set_title('mae') ax2.legend('linreg,loglinreg'.split(',')) ax2.set_xlabel("student's t-noise dof") plt.suptitle("Same Range, 100 Datapoints") ``` ```python linreg_errors_vs_df = np.array([get_error(LinearRegression(),x_range_train=(5,10),x_range_test=(10,15),df=df,n_datapoints_train=100) for df in dfs]) loglinreg_errors_vs_df = np.array([get_error(LogLinearRegression(),x_range_train=(5,10),x_range_test=(10,15),df=df,n_datapoints_train=100) for df in dfs]) fig = plt.figure(figsize=(12,5)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.semilogy(dfs,linreg_errors_vs_df[:,0],'d-') ax1.semilogy(dfs,loglinreg_errors_vs_df[:,0],'o-') ax1.set_title('msq') ax1.legend('lingreg,loglinreg'.split(',')) ax1.set_xlabel("student's t-noise dof") ax2.semilogy(dfs,linreg_errors_vs_df[:,1],'d-') ax2.semilogy(dfs,loglinreg_errors_vs_df[:,1],'o-') ax2.set_title('mae') ax2.legend('linreg,loglinreg'.split(',')) ax2.set_xlabel("student's t-noise dof") plt.suptitle("Out of Range, 100 Datapoints") ```
[STATEMENT] lemma count_lower_result: "count (lower_result C) z = count C z - (if z = x then 1 else 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. count (lower_result C) z = count C z - (if z = x then 1 else 0) [PROOF STEP] by (auto simp: lower_result_def)
[STATEMENT] lemma ex_gt_count_imp_le_multiset: "(\<forall>y :: 'a :: order. y \<in># M + N \<longrightarrow> y \<le> x) \<Longrightarrow> count M x < count N x \<Longrightarrow> M < N" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>y. y \<in># M + N \<longrightarrow> y \<le> x; count M x < count N x\<rbrakk> \<Longrightarrow> M < N [PROOF STEP] unfolding less_multiset\<^sub>H\<^sub>O [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>y. y \<in># M + N \<longrightarrow> y \<le> x; count M x < count N x\<rbrakk> \<Longrightarrow> M \<noteq> N \<and> (\<forall>y. count N y < count M y \<longrightarrow> (\<exists>x>y. count M x < count N x)) [PROOF STEP] by (metis count_greater_zero_iff le_imp_less_or_eq less_imp_not_less not_gr_zero union_iff)
[STATEMENT] lemma fps_integral0_zero: "fps_integral0 (0::'a::{semiring_1,inverse} fps) = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. fps_integral0 0 = 0 [PROOF STEP] by (intro fps_ext) (simp add: fps_integral_def)
Require Import Arith Lia. Require Import List. Require Import Recdef. Import ListNotations. Require Import TPPMark2019.Value. Require Import TPPMark2019.Tape. Require Import TPPMark2019.CTM. Require Import TPPMark2019.Clearer. Require Import TPPMark2019.Util. Set Implicit Arguments. Instance BoolFinite : Finite.class bool := {| Finite.card := 2; Finite.surj n := n =? 1; |}. Proof. destruct x; eauto. Defined. Instance BoolValue : @Value.class bool BoolFinite := {| Value.zero := false; Value.one := true; |}. Proof. - decide equality. - auto. Defined. Module ListTape. Record t (V : Type) : Type := { left_part: list V; top : V; right_part :list V; }. Arguments Build_t {V}. Arguments left_part {V} t. Arguments top {V} t. Arguments right_part {V} t. Definition size {V} '(Build_t l v r : t V) : nat := S (length l + length r). Definition head {V} '(Build_t l _ _ : t V) : nat := length l. Definition read {V} '(Build_t _ v _ : t V) : V := v. Definition write {V} (v : V) '(Build_t l _ r : t V) : t V := Build_t l v r. Function move_right {V} (tape : t V) := let '(Build_t l v r) := tape in match r with | [] => match rev l with | nil => Build_t [] v [] | v' :: r' => Build_t [] v' (r' ++ [v]) end | v' :: r' => Build_t (v :: l) v' r' end. Function move_left {V} (tape : t V) : t V := let '(Build_t l v r) := tape in match l with | [] => match rev r with | nil => Build_t [] v [] | v' :: l' => Build_t (l' ++ [v]) v' [] end | v' :: l' => Build_t l' v' (v :: r) end. Definition to_list {V} '(Build_t l v r : t V) : list V := rev l ++ v :: r. Definition from_list {V} `{Value.class V} (vs : list V) : t V := match vs with | [] => Build_t [] Value.zero [] | v :: vs' => Build_t [] v vs' end. End ListTape. Instance ListTape_Tape V `{Value.class V} : Tape.ops (ListTape.t V) V := {| Tape.read := ListTape.read; Tape.write := ListTape.write; Tape.move_right := ListTape.move_right; Tape.move_left := ListTape.move_left; |}. Instance ListTape_TapeSpec V `{Value.class V} : Tape.spec := {| Tape.to_list := ListTape.to_list; Tape.size := ListTape.size; Tape.head := ListTape.head; |}. Proof. - destruct t. simpl. ssimpl_list. auto. - destruct t. simpl. auto with arith. - destruct t. simpl. rewrite nth_error_app2; ssimpl_list; auto. rewrite Nat.sub_diag. reflexivity. - destruct t. simpl. rewrite nth_error_app2; ssimpl_list; auto. rewrite Nat.sub_diag. reflexivity. - intros i v t. destruct t. simpl. destruct (Nat.lt_ge_cases i (length (rev left_part))). + rewrite !nth_error_app1; auto. + rewrite !nth_error_app2; auto. case_eq (i - length (rev left_part)); simpl; auto. rewrite rev_length in *. lia. - intros v t. destruct t. reflexivity. - destruct t as [l v r]. destruct r; simpl; [destruct l using rev_ind|]; ssimpl_list; auto. rewrite <- List.app_assoc. auto. - destruct t as [l v r]. simpl. destruct r; [destruct l using rev_ind|]; rewrite ?rev_unit; simpl; auto; destruct_cmpbs. - destruct t as [l v r]; simpl; destruct l; simpl; [destruct r using rev_ind|]; ssimpl_list; auto. rewrite <- List.app_assoc. auto. - destruct t as [l v r]. simpl. destruct l; [destruct r using rev_ind|]; rewrite ?rev_unit; simpl; auto; destruct_cmpbs. ssimpl_list. auto with arith. Defined.
[GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) hC : IsPiSystem C hD : IsPiSystem D ⊢ IsPiSystem (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] rintro _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ _ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) hC : IsPiSystem C hD : IsPiSystem D s₁ : Set α t₁ : Set β hs₁ : s₁ ∈ C ht₁ : t₁ ∈ D s₂ : Set α t₂ : Set β hs₂ : s₂ ∈ C ht₂ : t₂ ∈ D hst : Set.Nonempty ((fun x x_1 => x ×ˢ x_1) s₁ t₁ ∩ (fun x x_1 => x ×ˢ x_1) s₂ t₂) ⊢ (fun x x_1 => x ×ˢ x_1) s₁ t₁ ∩ (fun x x_1 => x ×ˢ x_1) s₂ t₂ ∈ image2 (fun x x_1 => x ×ˢ x_1) C D [PROOFSTEP] rw [prod_inter_prod] at hst ⊢ [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) hC : IsPiSystem C hD : IsPiSystem D s₁ : Set α t₁ : Set β hs₁ : s₁ ∈ C ht₁ : t₁ ∈ D s₂ : Set α t₂ : Set β hs₂ : s₂ ∈ C ht₂ : t₂ ∈ D hst : Set.Nonempty ((s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂)) ⊢ (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) ∈ image2 (fun x x_1 => x ×ˢ x_1) C D [PROOFSTEP] rw [prod_nonempty_iff] at hst [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) hC : IsPiSystem C hD : IsPiSystem D s₁ : Set α t₁ : Set β hs₁ : s₁ ∈ C ht₁ : t₁ ∈ D s₂ : Set α t₂ : Set β hs₂ : s₂ ∈ C ht₂ : t₂ ∈ D hst : Set.Nonempty (s₁ ∩ s₂) ∧ Set.Nonempty (t₁ ∩ t₂) ⊢ (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) ∈ image2 (fun x x_1 => x ×ˢ x_1) C D [PROOFSTEP] exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2) [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ IsCountablySpanning (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] rcases hC, hD with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩ [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) s : ℕ → Set α h1s : ∀ (n : ℕ), s n ∈ C h2s : ⋃ (n : ℕ), s n = univ t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ ⊢ IsCountablySpanning (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] refine' ⟨fun n => s n.unpair.1 ×ˢ t n.unpair.2, fun n => mem_image2_of_mem (h1s _) (h1t _), _⟩ [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 C : Set (Set α) D : Set (Set β) s : ℕ → Set α h1s : ∀ (n : ℕ), s n ∈ C h2s : ⋃ (n : ℕ), s n = univ t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ ⊢ ⋃ (n : ℕ), (fun n => s (Nat.unpair n).fst ×ˢ t (Nat.unpair n).snd) n = univ [PROOFSTEP] rw [iUnion_unpair_prod, h2s, h2t, univ_prod_univ] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ Prod.instMeasurableSpace = generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] apply le_antisymm [GOAL] case a α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ Prod.instMeasurableSpace ≤ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] refine' sup_le _ _ [GOAL] case a.refine'_1 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ MeasurableSpace.comap Prod.fst (generateFrom C) ≤ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] rw [comap_generateFrom] [GOAL] case a.refine'_2 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ MeasurableSpace.comap Prod.snd (generateFrom D) ≤ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] rw [comap_generateFrom] [GOAL] case a.refine'_1 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ generateFrom (preimage Prod.fst '' C) ≤ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] apply generateFrom_le [GOAL] case a.refine'_2 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ generateFrom (preimage Prod.snd '' D) ≤ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] apply generateFrom_le [GOAL] case a.refine'_1.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ ∀ (t : Set (α × β)), t ∈ preimage Prod.fst '' C → MeasurableSet t [PROOFSTEP] rintro _ ⟨s, hs, rfl⟩ [GOAL] case a.refine'_2.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ ∀ (t : Set (α × β)), t ∈ preimage Prod.snd '' D → MeasurableSet t [PROOFSTEP] rintro _ ⟨s, hs, rfl⟩ [GOAL] case a.refine'_1.h.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α hs : s ∈ C ⊢ MeasurableSet (Prod.fst ⁻¹' s) [PROOFSTEP] rcases hD with ⟨t, h1t, h2t⟩ [GOAL] case a.refine'_1.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C s : Set α hs : s ∈ C t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ ⊢ MeasurableSet (Prod.fst ⁻¹' s) [PROOFSTEP] rw [← prod_univ, ← h2t, prod_iUnion] [GOAL] case a.refine'_1.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C s : Set α hs : s ∈ C t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ ⊢ MeasurableSet (⋃ (i : ℕ), s ×ˢ t i) [PROOFSTEP] apply MeasurableSet.iUnion [GOAL] case a.refine'_1.h.intro.intro.intro.intro.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C s : Set α hs : s ∈ C t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ ⊢ ∀ (b : ℕ), MeasurableSet (s ×ˢ t b) [PROOFSTEP] intro n [GOAL] case a.refine'_1.h.intro.intro.intro.intro.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C s : Set α hs : s ∈ C t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ n : ℕ ⊢ MeasurableSet (s ×ˢ t n) [PROOFSTEP] apply measurableSet_generateFrom [GOAL] case a.refine'_1.h.intro.intro.intro.intro.h.ht α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C s : Set α hs : s ∈ C t : ℕ → Set β h1t : ∀ (n : ℕ), t n ∈ D h2t : ⋃ (n : ℕ), t n = univ n : ℕ ⊢ s ×ˢ t n ∈ image2 (fun x x_1 => x ×ˢ x_1) C D [PROOFSTEP] exact ⟨s, t n, hs, h1t n, rfl⟩ [GOAL] case a.refine'_2.h.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set β hs : s ∈ D ⊢ MeasurableSet (Prod.snd ⁻¹' s) [PROOFSTEP] rcases hC with ⟨t, h1t, h2t⟩ [GOAL] case a.refine'_2.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hD : IsCountablySpanning D s : Set β hs : s ∈ D t : ℕ → Set α h1t : ∀ (n : ℕ), t n ∈ C h2t : ⋃ (n : ℕ), t n = univ ⊢ MeasurableSet (Prod.snd ⁻¹' s) [PROOFSTEP] rw [← univ_prod, ← h2t, iUnion_prod_const] [GOAL] case a.refine'_2.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hD : IsCountablySpanning D s : Set β hs : s ∈ D t : ℕ → Set α h1t : ∀ (n : ℕ), t n ∈ C h2t : ⋃ (n : ℕ), t n = univ ⊢ MeasurableSet (⋃ (i : ℕ), t i ×ˢ s) [PROOFSTEP] apply MeasurableSet.iUnion [GOAL] case a.refine'_2.h.intro.intro.intro.intro.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hD : IsCountablySpanning D s : Set β hs : s ∈ D t : ℕ → Set α h1t : ∀ (n : ℕ), t n ∈ C h2t : ⋃ (n : ℕ), t n = univ ⊢ ∀ (b : ℕ), MeasurableSet (t b ×ˢ s) [PROOFSTEP] rintro n [GOAL] case a.refine'_2.h.intro.intro.intro.intro.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hD : IsCountablySpanning D s : Set β hs : s ∈ D t : ℕ → Set α h1t : ∀ (n : ℕ), t n ∈ C h2t : ⋃ (n : ℕ), t n = univ n : ℕ ⊢ MeasurableSet (t n ×ˢ s) [PROOFSTEP] apply measurableSet_generateFrom [GOAL] case a.refine'_2.h.intro.intro.intro.intro.h.ht α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hD : IsCountablySpanning D s : Set β hs : s ∈ D t : ℕ → Set α h1t : ∀ (n : ℕ), t n ∈ C h2t : ⋃ (n : ℕ), t n = univ n : ℕ ⊢ t n ×ˢ s ∈ image2 (fun x x_1 => x ×ˢ x_1) C D [PROOFSTEP] exact mem_image2_of_mem (h1t n) hs [GOAL] case a α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) ≤ Prod.instMeasurableSpace [PROOFSTEP] apply generateFrom_le [GOAL] case a.h α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D ⊢ ∀ (t : Set (α × β)), t ∈ image2 (fun x x_1 => x ×ˢ x_1) C D → MeasurableSet t [PROOFSTEP] rintro _ ⟨s, t, hs, ht, rfl⟩ [GOAL] case a.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ MeasurableSet ((fun x x_1 => x ×ˢ x_1) s t) [PROOFSTEP] dsimp only [GOAL] case a.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ MeasurableSet (s ×ˢ t) [PROOFSTEP] rw [prod_eq] [GOAL] case a.h.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ MeasurableSet (Prod.fst ⁻¹' s ∩ Prod.snd ⁻¹' t) [PROOFSTEP] apply (measurable_fst _).inter (measurable_snd _) [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ MeasurableSet s [PROOFSTEP] exact measurableSet_generateFrom hs [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 C : Set (Set α) D : Set (Set β) hC : IsCountablySpanning C hD : IsCountablySpanning D s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ MeasurableSet t [PROOFSTEP] exact measurableSet_generateFrom ht [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝ : NormedAddCommGroup E C : Set (Set α) D : Set (Set β) hC : generateFrom C = inst✝⁵ hD : generateFrom D = inst✝³ h2C : IsCountablySpanning C h2D : IsCountablySpanning D ⊢ generateFrom (image2 (fun x x_1 => x ×ˢ x_1) C D) = Prod.instMeasurableSpace [PROOFSTEP] rw [← hC, ← hD, generateFrom_prod_eq h2C h2D] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s) [PROOFSTEP] refine' induction_on_inter (C := fun s => Measurable fun x => ν (Prod.mk x ⁻¹' s)) generateFrom_prod.symm isPiSystem_prod _ _ _ _ hs [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s ⊢ (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) ∅ [PROOFSTEP] simp [measurable_zero, const_def] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s ⊢ ∀ (t : Set (α × β)), t ∈ image2 (fun x x_1 => x ×ˢ x_1) {s | MeasurableSet s} {t | MeasurableSet t} → (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) t [PROOFSTEP] rintro _ ⟨s, t, hs, _, rfl⟩ [GOAL] case refine'_2.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s✝ : Set (α × β) hs✝ : MeasurableSet s✝ s : Set α t : Set β hs : s ∈ {s | MeasurableSet s} left✝ : t ∈ {t | MeasurableSet t} ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' (fun x x_1 => x ×ˢ x_1) s t) [PROOFSTEP] simp only [mk_preimage_prod_right_eq_if, measure_if] [GOAL] case refine'_2.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s✝ : Set (α × β) hs✝ : MeasurableSet s✝ s : Set α t : Set β hs : s ∈ {s | MeasurableSet s} left✝ : t ∈ {t | MeasurableSet t} ⊢ Measurable fun x => indicator s (fun x => ↑↑ν t) x [PROOFSTEP] exact measurable_const.indicator hs [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s ⊢ ∀ (t : Set (α × β)), MeasurableSet t → (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) t → (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) tᶜ [PROOFSTEP] intro t ht h2t [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s t : Set (α × β) ht : MeasurableSet t h2t : Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' t) ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' tᶜ) [PROOFSTEP] simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)] [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s t : Set (α × β) ht : MeasurableSet t h2t : Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' t) ⊢ Measurable fun x => ↑↑ν univ - ↑↑ν (Prod.mk x ⁻¹' t) [PROOFSTEP] exact h2t.const_sub _ [GOAL] case refine'_4 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s ⊢ ∀ (f : ℕ → Set (α × β)), Pairwise (Disjoint on f) → (∀ (i : ℕ), MeasurableSet (f i)) → (∀ (i : ℕ), (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (f i)) → (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (⋃ (i : ℕ), f i) [PROOFSTEP] intro f h1f h2f h3f [GOAL] case refine'_4 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s f : ℕ → Set (α × β) h1f : Pairwise (Disjoint on f) h2f : ∀ (i : ℕ), MeasurableSet (f i) h3f : ∀ (i : ℕ), (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (f i) ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' ⋃ (i : ℕ), f i) [PROOFSTEP] simp_rw [preimage_iUnion] [GOAL] case refine'_4 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s f : ℕ → Set (α × β) h1f : Pairwise (Disjoint on f) h2f : ∀ (i : ℕ), MeasurableSet (f i) h3f : ∀ (i : ℕ), (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (f i) ⊢ Measurable fun x => ↑↑ν (⋃ (i : ℕ), Prod.mk x ⁻¹' f i) [PROOFSTEP] have : ∀ b, ν (⋃ i, Prod.mk b ⁻¹' f i) = ∑' i, ν (Prod.mk b ⁻¹' f i) := fun b => measure_iUnion (fun i j hij => Disjoint.preimage _ (h1f hij)) fun i => measurable_prod_mk_left (h2f i) [GOAL] case refine'_4 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s f : ℕ → Set (α × β) h1f : Pairwise (Disjoint on f) h2f : ∀ (i : ℕ), MeasurableSet (f i) h3f : ∀ (i : ℕ), (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (f i) this : ∀ (b : α), ↑↑ν (⋃ (i : ℕ), Prod.mk b ⁻¹' f i) = ∑' (i : ℕ), ↑↑ν (Prod.mk b ⁻¹' f i) ⊢ Measurable fun x => ↑↑ν (⋃ (i : ℕ), Prod.mk x ⁻¹' f i) [PROOFSTEP] simp_rw [this] [GOAL] case refine'_4 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : IsFiniteMeasure ν s : Set (α × β) hs : MeasurableSet s f : ℕ → Set (α × β) h1f : Pairwise (Disjoint on f) h2f : ∀ (i : ℕ), MeasurableSet (f i) h3f : ∀ (i : ℕ), (fun s => Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s)) (f i) this : ∀ (b : α), ↑↑ν (⋃ (i : ℕ), Prod.mk b ⁻¹' f i) = ∑' (i : ℕ), ↑↑ν (Prod.mk b ⁻¹' f i) ⊢ Measurable fun x => ∑' (i : ℕ), ↑↑ν (Prod.mk x ⁻¹' f i) [PROOFSTEP] apply Measurable.ennreal_tsum h3f [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s) [PROOFSTEP] have : ∀ x, MeasurableSet (Prod.mk x ⁻¹' s) := fun x => measurable_prod_mk_left hs [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s this : ∀ (x : α), MeasurableSet (Prod.mk x ⁻¹' s) ⊢ Measurable fun x => ↑↑ν (Prod.mk x ⁻¹' s) [PROOFSTEP] simp only [← @iSup_restrict_spanningSets _ _ ν, this] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s this : ∀ (x : α), MeasurableSet (Prod.mk x ⁻¹' s) ⊢ Measurable fun x => ⨆ (i : ℕ), ↑↑(Measure.restrict ν (spanningSets ν i)) (Prod.mk x ⁻¹' s) [PROOFSTEP] apply measurable_iSup [GOAL] case hf α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s this : ∀ (x : α), MeasurableSet (Prod.mk x ⁻¹' s) ⊢ ∀ (i : ℕ), Measurable fun b => ↑↑(Measure.restrict ν (spanningSets ν i)) (Prod.mk b ⁻¹' s) [PROOFSTEP] intro i [GOAL] case hf α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s this : ∀ (x : α), MeasurableSet (Prod.mk x ⁻¹' s) i : ℕ ⊢ Measurable fun b => ↑↑(Measure.restrict ν (spanningSets ν i)) (Prod.mk b ⁻¹' s) [PROOFSTEP] haveI := Fact.mk (measure_spanningSets_lt_top ν i) [GOAL] case hf α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s this✝ : ∀ (x : α), MeasurableSet (Prod.mk x ⁻¹' s) i : ℕ this : Fact (↑↑ν (spanningSets ν i) < ⊤) ⊢ Measurable fun b => ↑↑(Measure.restrict ν (spanningSets ν i)) (Prod.mk b ⁻¹' s) [PROOFSTEP] exact measurable_measure_prod_mk_left_finite hs [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ Measurable fun x => map (Prod.mk x) ν [PROOFSTEP] apply measurable_of_measurable_coe [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ ∀ (s : Set (α × β)), MeasurableSet s → Measurable fun b => ↑↑(map (Prod.mk b) ν) s [PROOFSTEP] intro s hs [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun b => ↑↑(map (Prod.mk b) ν) s [PROOFSTEP] simp_rw [map_apply measurable_prod_mk_left hs] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun b => ↑↑ν (Prod.mk b ⁻¹' s) [PROOFSTEP] exact measurable_measure_prod_mk_left hs [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E μ : Measure α inst✝ : SigmaFinite μ ⊢ Measurable fun y => map (fun x => (x, y)) μ [PROOFSTEP] apply measurable_of_measurable_coe [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E μ : Measure α inst✝ : SigmaFinite μ ⊢ ∀ (s : Set (α × β)), MeasurableSet s → Measurable fun b => ↑↑(map (fun x => (x, b)) μ) s [PROOFSTEP] intro s hs [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E μ : Measure α inst✝ : SigmaFinite μ s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun b => ↑↑(map (fun x => (x, b)) μ) s [PROOFSTEP] simp_rw [map_apply measurable_prod_mk_right hs] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E μ : Measure α inst✝ : SigmaFinite μ s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun b => ↑↑μ ((fun x => (x, b)) ⁻¹' s) [PROOFSTEP] exact measurable_measure_prod_mk_right hs [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f ⊢ MeasurableEmbedding fun x => (g x.fst, f x.snd) [PROOFSTEP] have h_inj : Function.Injective fun x : γ × α => (g x.fst, f x.snd) := by intro x y hxy rw [← @Prod.mk.eta _ _ x, ← @Prod.mk.eta _ _ y] simp only [Prod.mk.inj_iff] at hxy ⊢ exact ⟨hg.injective hxy.1, hf.injective hxy.2⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f ⊢ Injective fun x => (g x.fst, f x.snd) [PROOFSTEP] intro x y hxy [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f x y : γ × α hxy : (fun x => (g x.fst, f x.snd)) x = (fun x => (g x.fst, f x.snd)) y ⊢ x = y [PROOFSTEP] rw [← @Prod.mk.eta _ _ x, ← @Prod.mk.eta _ _ y] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f x y : γ × α hxy : (fun x => (g x.fst, f x.snd)) x = (fun x => (g x.fst, f x.snd)) y ⊢ (x.fst, x.snd) = (y.fst, y.snd) [PROOFSTEP] simp only [Prod.mk.inj_iff] at hxy ⊢ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f x y : γ × α hxy : g x.fst = g y.fst ∧ f x.snd = f y.snd ⊢ x.fst = y.fst ∧ x.snd = y.snd [PROOFSTEP] exact ⟨hg.injective hxy.1, hf.injective hxy.2⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) ⊢ MeasurableEmbedding fun x => (g x.fst, f x.snd) [PROOFSTEP] refine' ⟨h_inj, _, _⟩ [GOAL] case refine'_1 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) ⊢ Measurable fun x => (g x.fst, f x.snd) [PROOFSTEP] exact (hg.measurable.comp measurable_fst).prod_mk (hf.measurable.comp measurable_snd) [GOAL] case refine'_2 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) ⊢ ∀ ⦃s : Set (γ × α)⦄, MeasurableSet s → MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s) [PROOFSTEP] refine' fun s hs => @MeasurableSpace.induction_on_inter _ (fun s => MeasurableSet ((fun x : γ × α => (g x.fst, f x.snd)) '' s)) _ _ generateFrom_prod.symm isPiSystem_prod _ _ _ _ _ hs [GOAL] case refine'_2.refine'_1 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s ⊢ (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) ∅ [PROOFSTEP] simp only [Set.image_empty, MeasurableSet.empty] [GOAL] case refine'_2.refine'_2 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s ⊢ ∀ (t : Set (γ × α)), t ∈ image2 (fun x x_1 => x ×ˢ x_1) {s | MeasurableSet s} {t | MeasurableSet t} → (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) t [PROOFSTEP] rintro t ⟨t₁, t₂, ht₁, ht₂, rfl⟩ [GOAL] case refine'_2.refine'_2.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s t₁ : Set γ t₂ : Set α ht₁ : t₁ ∈ {s | MeasurableSet s} ht₂ : t₂ ∈ {t | MeasurableSet t} ⊢ MeasurableSet ((fun x => (g x.fst, f x.snd)) '' (fun x x_1 => x ×ˢ x_1) t₁ t₂) [PROOFSTEP] rw [← Set.prod_image_image_eq] [GOAL] case refine'_2.refine'_2.intro.intro.intro.intro α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s t₁ : Set γ t₂ : Set α ht₁ : t₁ ∈ {s | MeasurableSet s} ht₂ : t₂ ∈ {t | MeasurableSet t} ⊢ MeasurableSet ((g '' t₁) ×ˢ (f '' t₂)) [PROOFSTEP] exact (hg.measurableSet_image.mpr ht₁).prod (hf.measurableSet_image.mpr ht₂) [GOAL] case refine'_2.refine'_3 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s ⊢ ∀ (t : Set (γ × α)), MeasurableSet t → (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) t → (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) tᶜ [PROOFSTEP] intro t _ ht_m [GOAL] case refine'_2.refine'_3 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s t : Set (γ × α) a✝ : MeasurableSet t ht_m : MeasurableSet ((fun x => (g x.fst, f x.snd)) '' t) ⊢ MeasurableSet ((fun x => (g x.fst, f x.snd)) '' tᶜ) [PROOFSTEP] rw [← Set.range_diff_image h_inj, ← Set.prod_range_range_eq] [GOAL] case refine'_2.refine'_3 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s t : Set (γ × α) a✝ : MeasurableSet t ht_m : MeasurableSet ((fun x => (g x.fst, f x.snd)) '' t) ⊢ MeasurableSet (range g ×ˢ range f \ (fun x => (g x.fst, f x.snd)) '' t) [PROOFSTEP] exact MeasurableSet.diff (MeasurableSet.prod hg.measurableSet_range hf.measurableSet_range) ht_m [GOAL] case refine'_2.refine'_4 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g : γ → δ hg : MeasurableEmbedding g hf : MeasurableEmbedding f h_inj : Injective fun x => (g x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s ⊢ ∀ (f_1 : ℕ → Set (γ × α)), Pairwise (Disjoint on f_1) → (∀ (i : ℕ), MeasurableSet (f_1 i)) → (∀ (i : ℕ), (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) (f_1 i)) → (fun s => MeasurableSet ((fun x => (g x.fst, f x.snd)) '' s)) (⋃ (i : ℕ), f_1 i) [PROOFSTEP] intro g _ _ hg [GOAL] case refine'_2.refine'_4 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g✝ : γ → δ hg✝ : MeasurableEmbedding g✝ hf : MeasurableEmbedding f h_inj : Injective fun x => (g✝ x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s g : ℕ → Set (γ × α) a✝¹ : Pairwise (Disjoint on g) a✝ : ∀ (i : ℕ), MeasurableSet (g i) hg : ∀ (i : ℕ), (fun s => MeasurableSet ((fun x => (g✝ x.fst, f x.snd)) '' s)) (g i) ⊢ MeasurableSet ((fun x => (g✝ x.fst, f x.snd)) '' ⋃ (i : ℕ), g i) [PROOFSTEP] simp_rw [Set.image_iUnion] [GOAL] case refine'_2.refine'_4 α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝⁵ : MeasurableSpace α✝ inst✝⁴ : MeasurableSpace α' inst✝³ : MeasurableSpace β✝ inst✝² : MeasurableSpace β' inst✝¹ : MeasurableSpace γ✝ μ μ' : Measure α✝ ν ν' : Measure β✝ τ : Measure γ✝ inst✝ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 δ : Type u_10 mα : MeasurableSpace α mβ : MeasurableSpace β mγ : MeasurableSpace γ mδ : MeasurableSpace δ f : α → β g✝ : γ → δ hg✝ : MeasurableEmbedding g✝ hf : MeasurableEmbedding f h_inj : Injective fun x => (g✝ x.fst, f x.snd) s : Set (γ × α) hs : MeasurableSet s g : ℕ → Set (γ × α) a✝¹ : Pairwise (Disjoint on g) a✝ : ∀ (i : ℕ), MeasurableSet (g i) hg : ∀ (i : ℕ), (fun s => MeasurableSet ((fun x => (g✝ x.fst, f x.snd)) '' s)) (g i) ⊢ MeasurableSet (⋃ (i : ℕ), (fun x => (g✝ x.fst, f x.snd)) '' g i) [PROOFSTEP] exact MeasurableSet.iUnion hg [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ ∀ {f : α × β → ℝ≥0∞}, Measurable f → Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν [PROOFSTEP] have m := @measurable_prod_mk_left [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ {f : α × β → ℝ≥0∞}, Measurable f → Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν [PROOFSTEP] refine' Measurable.ennreal_induction (P := fun f => Measurable fun (x : α) => ∫⁻ y, f (x, y) ∂ν) _ _ _ [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ (c : ℝ≥0∞) ⦃s : Set (α × β)⦄, MeasurableSet s → (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (Set.indicator s fun x => c) [PROOFSTEP] intro c s hs [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun x => ∫⁻ (y : β), Set.indicator s (fun x => c) (x, y) ∂ν [PROOFSTEP] simp only [← indicator_comp_right] [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun x => ∫⁻ (y : β), Set.indicator (Prod.mk x ⁻¹' s) ((fun x => c) ∘ Prod.mk x) y ∂ν [PROOFSTEP] suffices Measurable fun x => c * ν (Prod.mk x ⁻¹' s) by simpa [lintegral_indicator _ (m hs)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s this : Measurable fun x => c * ↑↑ν (Prod.mk x ⁻¹' s) ⊢ Measurable fun x => ∫⁻ (y : β), Set.indicator (Prod.mk x ⁻¹' s) ((fun x => c) ∘ Prod.mk x) y ∂ν [PROOFSTEP] simpa [lintegral_indicator _ (m hs)] [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ Measurable fun x => c * ↑↑ν (Prod.mk x ⁻¹' s) [PROOFSTEP] exact (measurable_measure_prod_mk_left hs).const_mul _ [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ ⦃f g : α × β → ℝ≥0∞⦄, Disjoint (support f) (support g) → Measurable f → Measurable g → (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) f → (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) g → (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f + g) [PROOFSTEP] rintro f g - hf - h2f h2g [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν ⊢ Measurable fun x => ∫⁻ (y : β), (f + g) (x, y) ∂ν [PROOFSTEP] simp only [Pi.add_apply] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν ⊢ Measurable fun x => ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] conv => enter [1, x]; erw [lintegral_add_left (hf.comp m)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν | Measurable fun x => ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] enter [1, x]; erw [lintegral_add_left (hf.comp m)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν | Measurable fun x => ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] enter [1, x]; erw [lintegral_add_left (hf.comp m)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν | Measurable fun x => ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] enter [1, x] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.13769} {β : Type ?u.13770} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν x : α | ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] erw [lintegral_add_left (hf.comp m)] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f h2f : Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν h2g : Measurable fun x => ∫⁻ (y : β), g (x, y) ∂ν ⊢ Measurable fun x => ∫⁻ (a : β), (f ∘ Prod.mk x) a ∂ν + ∫⁻ (a : β), g (x, a) ∂ν [PROOFSTEP] exact h2f.add h2g [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ ⦃f : ℕ → α × β → ℝ≥0∞⦄, (∀ (n : ℕ), Measurable (f n)) → Monotone f → (∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n)) → (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) fun x => ⨆ (n : ℕ), f n x [PROOFSTEP] intro f hf h2f h3f [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) ⊢ Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] have := measurable_iSup h3f [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν ⊢ Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] have : ∀ x, Monotone fun n y => f n (x, y) := fun x i j hij y => h2f hij (x, y) [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) ⊢ Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] conv => enter [1, x]; erw [lintegral_iSup (fun n => (hf n).comp m) (this x)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) | Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] enter [1, x]; erw [lintegral_iSup (fun n => (hf n).comp m) (this x)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) | Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] enter [1, x]; erw [lintegral_iSup (fun n => (hf n).comp m) (this x)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) | Measurable fun x => ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] enter [1, x] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) x : α | ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν [PROOFSTEP] erw [lintegral_iSup (fun n => (hf n).comp m) (this x)] [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => Measurable fun x => ∫⁻ (y : β), f (x, y) ∂ν) (f n) this✝ : Measurable fun b => ⨆ (i : ℕ), ∫⁻ (y : β), f i (b, y) ∂ν this : ∀ (x : α), Monotone fun n y => f n (x, y) ⊢ Measurable fun x => ⨆ (n : ℕ), ∫⁻ (a : β), (f n ∘ Prod.mk x) a ∂ν [PROOFSTEP] assumption [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s ⊢ ↑↑(Measure.prod μ ν) s = ∫⁻ (x : α), ↑↑ν (Prod.mk x ⁻¹' s) ∂μ [PROOFSTEP] simp_rw [Measure.prod, bind_apply hs (Measurable.map_prod_mk_left (ν := ν)), map_apply measurable_prod_mk_left hs] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ⊢ ↑↑(Measure.prod μ ν) (s ×ˢ t) = ↑↑μ s * ↑↑ν t [PROOFSTEP] apply le_antisymm [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ⊢ ↑↑(Measure.prod μ ν) (s ×ˢ t) ≤ ↑↑μ s * ↑↑ν t [PROOFSTEP] set ST := toMeasurable μ s ×ˢ toMeasurable ν t [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable μ s ×ˢ toMeasurable ν t ⊢ ↑↑(Measure.prod μ ν) (s ×ˢ t) ≤ ↑↑μ s * ↑↑ν t [PROOFSTEP] have hSTm : MeasurableSet ST := (measurableSet_toMeasurable _ _).prod (measurableSet_toMeasurable _ _) [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable μ s ×ˢ toMeasurable ν t hSTm : MeasurableSet ST ⊢ ↑↑(Measure.prod μ ν) (s ×ˢ t) ≤ ↑↑μ s * ↑↑ν t [PROOFSTEP] calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν ST := measure_mono <| Set.prod_mono (subset_toMeasurable _ _) (subset_toMeasurable _ _) _ = μ (toMeasurable μ s) * ν (toMeasurable ν t) := by rw [prod_apply hSTm] simp_rw [mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurableSet_toMeasurable _ _), lintegral_const, restrict_apply_univ, mul_comm] _ = μ s * ν t := by rw [measure_toMeasurable, measure_toMeasurable] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable μ s ×ˢ toMeasurable ν t hSTm : MeasurableSet ST ⊢ ↑↑(Measure.prod μ ν) ST = ↑↑μ (toMeasurable μ s) * ↑↑ν (toMeasurable ν t) [PROOFSTEP] rw [prod_apply hSTm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable μ s ×ˢ toMeasurable ν t hSTm : MeasurableSet ST ⊢ ∫⁻ (x : α), ↑↑ν (Prod.mk x ⁻¹' ST) ∂μ = ↑↑μ (toMeasurable μ s) * ↑↑ν (toMeasurable ν t) [PROOFSTEP] simp_rw [mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurableSet_toMeasurable _ _), lintegral_const, restrict_apply_univ, mul_comm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable μ s ×ˢ toMeasurable ν t hSTm : MeasurableSet ST ⊢ ↑↑μ (toMeasurable μ s) * ↑↑ν (toMeasurable ν t) = ↑↑μ s * ↑↑ν t [PROOFSTEP] rw [measure_toMeasurable, measure_toMeasurable] [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] set ST := toMeasurable (μ.prod ν) (s ×ˢ t) [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] have hSTm : MeasurableSet ST := measurableSet_toMeasurable _ _ [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] have hST : s ×ˢ t ⊆ ST := subset_toMeasurable _ _ [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] set f : α → ℝ≥0∞ := fun x => ν (Prod.mk x ⁻¹' ST) [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST f : α → ℝ≥0∞ := fun x => ↑↑ν (Prod.mk x ⁻¹' ST) ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] have hfm : Measurable f := measurable_measure_prod_mk_left hSTm [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST f : α → ℝ≥0∞ := fun x => ↑↑ν (Prod.mk x ⁻¹' ST) hfm : Measurable f ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] set s' : Set α := {x | ν t ≤ f x} [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST f : α → ℝ≥0∞ := fun x => ↑↑ν (Prod.mk x ⁻¹' ST) hfm : Measurable f s' : Set α := {x | ↑↑ν t ≤ f x} ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] have hss' : s ⊆ s' := fun x hx => measure_mono fun y hy => hST <| mk_mem_prod hx hy [GOAL] case a α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST f : α → ℝ≥0∞ := fun x => ↑↑ν (Prod.mk x ⁻¹' ST) hfm : Measurable f s' : Set α := {x | ↑↑ν t ≤ f x} hss' : s ⊆ s' ⊢ ↑↑μ s * ↑↑ν t ≤ ↑↑(Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] calc μ s * ν t ≤ μ s' * ν t := mul_le_mul_right' (measure_mono hss') _ _ = ∫⁻ _ in s', ν t ∂μ := by rw [set_lintegral_const, mul_comm] _ ≤ ∫⁻ x in s', f x ∂μ := (set_lintegral_mono measurable_const hfm fun x => id) _ ≤ ∫⁻ x, f x ∂μ := (lintegral_mono' restrict_le_self le_rfl) _ = μ.prod ν ST := (prod_apply hSTm).symm _ = μ.prod ν (s ×ˢ t) := measure_toMeasurable _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α t : Set β ST : Set (α × β) := toMeasurable (Measure.prod μ ν) (s ×ˢ t) hSTm : MeasurableSet ST hST : s ×ˢ t ⊆ ST f : α → ℝ≥0∞ := fun x => ↑↑ν (Prod.mk x ⁻¹' ST) hfm : Measurable f s' : Set α := {x | ↑↑ν t ≤ f x} hss' : s ⊆ s' ⊢ ↑↑μ s' * ↑↑ν t = ∫⁻ (x : α) in s', ↑↑ν t ∂μ [PROOFSTEP] rw [set_lintegral_const, mul_comm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν ⊢ IsOpenPosMeasure (Measure.prod μ ν) [PROOFSTEP] constructor [GOAL] case open_pos α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν ⊢ ∀ (U : Set (X × Y)), IsOpen U → Set.Nonempty U → ↑↑(Measure.prod μ ν) U ≠ 0 [PROOFSTEP] rintro U U_open ⟨⟨x, y⟩, hxy⟩ [GOAL] case open_pos.intro.mk α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U ⊢ ↑↑(Measure.prod μ ν) U ≠ 0 [PROOFSTEP] rcases isOpen_prod_iff.1 U_open x y hxy with ⟨u, v, u_open, v_open, xu, yv, huv⟩ [GOAL] case open_pos.intro.mk.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U u : Set X v : Set Y u_open : IsOpen u v_open : IsOpen v xu : x ∈ u yv : y ∈ v huv : u ×ˢ v ⊆ U ⊢ ↑↑(Measure.prod μ ν) U ≠ 0 [PROOFSTEP] refine' ne_of_gt (lt_of_lt_of_le _ (measure_mono huv)) [GOAL] case open_pos.intro.mk.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U u : Set X v : Set Y u_open : IsOpen u v_open : IsOpen v xu : x ∈ u yv : y ∈ v huv : u ×ˢ v ⊆ U ⊢ 0 < ↑↑(Measure.prod μ ν) (u ×ˢ v) [PROOFSTEP] simp only [prod_prod, CanonicallyOrderedCommSemiring.mul_pos] [GOAL] case open_pos.intro.mk.intro.intro.intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U u : Set X v : Set Y u_open : IsOpen u v_open : IsOpen v xu : x ∈ u yv : y ∈ v huv : u ×ˢ v ⊆ U ⊢ 0 < ↑↑μ u ∧ 0 < ↑↑ν v [PROOFSTEP] constructor [GOAL] case open_pos.intro.mk.intro.intro.intro.intro.intro.intro.left α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U u : Set X v : Set Y u_open : IsOpen u v_open : IsOpen v xu : x ∈ u yv : y ∈ v huv : u ×ˢ v ⊆ U ⊢ 0 < ↑↑μ u [PROOFSTEP] exact u_open.measure_pos μ ⟨x, xu⟩ [GOAL] case open_pos.intro.mk.intro.intro.intro.intro.intro.intro.right α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ X : Type u_7 Y : Type u_8 inst✝⁴ : TopologicalSpace X inst✝³ : TopologicalSpace Y m : MeasurableSpace X μ : Measure X inst✝² : IsOpenPosMeasure μ m' : MeasurableSpace Y ν : Measure Y inst✝¹ : IsOpenPosMeasure ν inst✝ : SigmaFinite ν U : Set (X × Y) U_open : IsOpen U x : X y : Y hxy : (x, y) ∈ U u : Set X v : Set Y u_open : IsOpen u v_open : IsOpen v xu : x ∈ u yv : y ∈ v huv : u ×ˢ v ⊆ U ⊢ 0 < ↑↑ν v [PROOFSTEP] exact v_open.measure_pos ν ⟨y, yv⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α✝ inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β✝ inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν✝ α : Type u_7 β : Type u_8 mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝¹ : IsFiniteMeasure μ inst✝ : IsFiniteMeasure ν ⊢ IsFiniteMeasure (Measure.prod μ ν) [PROOFSTEP] constructor [GOAL] case measure_univ_lt_top α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α✝ inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β✝ inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν✝ α : Type u_7 β : Type u_8 mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝¹ : IsFiniteMeasure μ inst✝ : IsFiniteMeasure ν ⊢ ↑↑(Measure.prod μ ν) univ < ⊤ [PROOFSTEP] rw [← univ_prod_univ, prod_prod] [GOAL] case measure_univ_lt_top α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α✝ inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β✝ inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν✝ α : Type u_7 β : Type u_8 mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝¹ : IsFiniteMeasure μ inst✝ : IsFiniteMeasure ν ⊢ ↑↑μ univ * ↑↑ν univ < ⊤ [PROOFSTEP] exact mul_lt_top (measure_lt_top _ _).ne (measure_lt_top _ _).ne [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α✝ inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β✝ inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν✝ α : Type u_7 β : Type u_8 mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝¹ : IsProbabilityMeasure μ inst✝ : IsProbabilityMeasure ν ⊢ ↑↑(Measure.prod μ ν) univ = 1 [PROOFSTEP] rw [← univ_prod_univ, prod_prod, measure_univ, measure_univ, mul_one] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν ⊢ IsFiniteMeasureOnCompacts (Measure.prod μ ν) [PROOFSTEP] refine' ⟨fun K hK => _⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K ⊢ ↑↑(Measure.prod μ ν) K < ⊤ [PROOFSTEP] set L := (Prod.fst '' K) ×ˢ (Prod.snd '' K) with hL [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) ⊢ ↑↑(Measure.prod μ ν) K < ⊤ [PROOFSTEP] have : K ⊆ L := by rintro ⟨x, y⟩ hxy simp only [prod_mk_mem_set_prod_eq, mem_image, Prod.exists, exists_and_right, exists_eq_right] exact ⟨⟨y, hxy⟩, ⟨x, hxy⟩⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) ⊢ K ⊆ L [PROOFSTEP] rintro ⟨x, y⟩ hxy [GOAL] case mk α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) x : α y : β hxy : (x, y) ∈ K ⊢ (x, y) ∈ L [PROOFSTEP] simp only [prod_mk_mem_set_prod_eq, mem_image, Prod.exists, exists_and_right, exists_eq_right] [GOAL] case mk α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) x : α y : β hxy : (x, y) ∈ K ⊢ (∃ x_1, (x, x_1) ∈ K) ∧ ∃ a, (a, y) ∈ K [PROOFSTEP] exact ⟨⟨y, hxy⟩, ⟨x, hxy⟩⟩ [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) this : K ⊆ L ⊢ ↑↑(Measure.prod μ ν) K < ⊤ [PROOFSTEP] apply lt_of_le_of_lt (measure_mono this) [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) this : K ⊆ L ⊢ ↑↑(Measure.prod μ ν) L < ⊤ [PROOFSTEP] rw [hL, prod_prod] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝¹¹ : MeasurableSpace α✝ inst✝¹⁰ : MeasurableSpace α' inst✝⁹ : MeasurableSpace β✝ inst✝⁸ : MeasurableSpace β' inst✝⁷ : MeasurableSpace γ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ : Measure γ inst✝⁶ : NormedAddCommGroup E inst✝⁵ : SigmaFinite ν✝ α : Type u_7 β : Type u_8 inst✝⁴ : TopologicalSpace α inst✝³ : TopologicalSpace β mα : MeasurableSpace α mβ : MeasurableSpace β μ : Measure α ν : Measure β inst✝² : IsFiniteMeasureOnCompacts μ inst✝¹ : IsFiniteMeasureOnCompacts ν inst✝ : SigmaFinite ν K : Set (α × β) hK : IsCompact K L : Set (α × β) := (Prod.fst '' K) ×ˢ (Prod.snd '' K) hL : L = (Prod.fst '' K) ×ˢ (Prod.snd '' K) this : K ⊆ L ⊢ ↑↑μ (Prod.fst '' K) * ↑↑ν (Prod.snd '' K) < ⊤ [PROOFSTEP] exact mul_lt_top (IsCompact.measure_lt_top (hK.image continuous_fst)).ne (IsCompact.measure_lt_top (hK.image continuous_snd)).ne [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s h2s : ↑↑(Measure.prod μ ν) s ≠ ⊤ ⊢ ∀ᵐ (x : α) ∂μ, ↑↑ν (Prod.mk x ⁻¹' s) < ⊤ [PROOFSTEP] rw [prod_apply hs] at h2s [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s h2s : ∫⁻ (x : α), ↑↑ν (Prod.mk x ⁻¹' s) ∂μ ≠ ⊤ ⊢ ∀ᵐ (x : α) ∂μ, ↑↑ν (Prod.mk x ⁻¹' s) < ⊤ [PROOFSTEP] refine' ae_lt_top (measurable_measure_prod_mk_left hs) h2s [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) hs : MeasurableSet s ⊢ ↑↑(Measure.prod μ ν) s = 0 ↔ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) =ᶠ[ae μ] 0 [PROOFSTEP] rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) h : ↑↑(Measure.prod μ ν) s = 0 ⊢ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) =ᶠ[ae μ] 0 [PROOFSTEP] obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h [GOAL] case intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) h : ↑↑(Measure.prod μ ν) s = 0 t : Set (α × β) hst : s ⊆ t mt : MeasurableSet t ht : ↑↑(Measure.prod μ ν) t = 0 ⊢ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) =ᶠ[ae μ] 0 [PROOFSTEP] rw [measure_prod_null mt] at ht [GOAL] case intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) h : ↑↑(Measure.prod μ ν) s = 0 t : Set (α × β) hst : s ⊆ t mt : MeasurableSet t ht : (fun x => ↑↑ν (Prod.mk x ⁻¹' t)) =ᶠ[ae μ] 0 ⊢ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) =ᶠ[ae μ] 0 [PROOFSTEP] rw [eventuallyLE_antisymm_iff] [GOAL] case intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set (α × β) h : ↑↑(Measure.prod μ ν) s = 0 t : Set (α × β) hst : s ⊆ t mt : MeasurableSet t ht : (fun x => ↑↑ν (Prod.mk x ⁻¹' t)) =ᶠ[ae μ] 0 ⊢ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) ≤ᶠ[ae μ] 0 ∧ 0 ≤ᶠ[ae μ] fun x => ↑↑ν (Prod.mk x ⁻¹' s) [PROOFSTEP] exact ⟨EventuallyLE.trans_eq (eventually_of_forall fun x => (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall fun x => zero_le _⟩ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite ν' h1 : μ ≪ μ' h2 : ν ≪ ν' ⊢ Measure.prod μ ν ≪ Measure.prod μ' ν' [PROOFSTEP] refine' AbsolutelyContinuous.mk fun s hs h2s => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite ν' h1 : μ ≪ μ' h2 : ν ≪ ν' s : Set (α × β) hs : MeasurableSet s h2s : ↑↑(Measure.prod μ' ν') s = 0 ⊢ ↑↑(Measure.prod μ ν) s = 0 [PROOFSTEP] rw [measure_prod_null hs] at h2s ⊢ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite ν' h1 : μ ≪ μ' h2 : ν ≪ ν' s : Set (α × β) hs : MeasurableSet s h2s : (fun x => ↑↑ν' (Prod.mk x ⁻¹' s)) =ᶠ[ae μ'] 0 ⊢ (fun x => ↑↑ν (Prod.mk x ⁻¹' s)) =ᶠ[ae μ] 0 [PROOFSTEP] exact (h2s.filter_mono h1.ae_le).mono fun _ h => h2 h [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν✝ ν : Measure β C : Set (Set α) D : Set (Set β) hμ : FiniteSpanningSetsIn μ C hν : FiniteSpanningSetsIn ν D ⊢ FiniteSpanningSetsIn (Measure.prod μ ν) (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] haveI := hν.sigmaFinite [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν✝ ν : Measure β C : Set (Set α) D : Set (Set β) hμ : FiniteSpanningSetsIn μ C hν : FiniteSpanningSetsIn ν D this : SigmaFinite ν ⊢ FiniteSpanningSetsIn (Measure.prod μ ν) (image2 (fun x x_1 => x ×ˢ x_1) C D) [PROOFSTEP] refine' ⟨fun n => hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, fun n => mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), fun n => _, _⟩ [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν✝ ν : Measure β C : Set (Set α) D : Set (Set β) hμ : FiniteSpanningSetsIn μ C hν : FiniteSpanningSetsIn ν D this : SigmaFinite ν n : ℕ ⊢ ↑↑(Measure.prod μ ν) ((fun n => FiniteSpanningSetsIn.set hμ (Nat.unpair n).fst ×ˢ FiniteSpanningSetsIn.set hν (Nat.unpair n).snd) n) < ⊤ [PROOFSTEP] rw [prod_prod] [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν✝ ν : Measure β C : Set (Set α) D : Set (Set β) hμ : FiniteSpanningSetsIn μ C hν : FiniteSpanningSetsIn ν D this : SigmaFinite ν n : ℕ ⊢ ↑↑μ (FiniteSpanningSetsIn.set hμ (Nat.unpair n).fst) * ↑↑ν (FiniteSpanningSetsIn.set hν (Nat.unpair n).snd) < ⊤ [PROOFSTEP] exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν✝ ν : Measure β C : Set (Set α) D : Set (Set β) hμ : FiniteSpanningSetsIn μ C hν : FiniteSpanningSetsIn ν D this : SigmaFinite ν ⊢ ⋃ (i : ℕ), (fun n => FiniteSpanningSetsIn.set hμ (Nat.unpair n).fst ×ˢ FiniteSpanningSetsIn.set hν (Nat.unpair n).snd) i = univ [PROOFSTEP] simp_rw [iUnion_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ QuasiMeasurePreserving Prod.fst [PROOFSTEP] refine' ⟨measurable_fst, AbsolutelyContinuous.mk fun s hs h2s => _⟩ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set α hs : MeasurableSet s h2s : ↑↑μ s = 0 ⊢ ↑↑(map Prod.fst (Measure.prod μ ν)) s = 0 [PROOFSTEP] rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ QuasiMeasurePreserving Prod.snd [PROOFSTEP] refine' ⟨measurable_snd, AbsolutelyContinuous.mk fun s hs h2s => _⟩ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν s : Set β hs : MeasurableSet s h2s : ↑↑ν s = 0 ⊢ ↑↑(map Prod.snd (Measure.prod μ ν)) s = 0 [PROOFSTEP] rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ✝ μ : Measure α ν : Measure β C : Set (Set α) D : Set (Set β) hC : generateFrom C = inst✝⁷ hD : generateFrom D = inst✝⁵ h2C : IsPiSystem C h2D : IsPiSystem D h3C : FiniteSpanningSetsIn μ C h3D : FiniteSpanningSetsIn ν D μν : Measure (α × β) h₁ : ∀ (s : Set α), s ∈ C → ∀ (t : Set β), t ∈ D → ↑↑μν (s ×ˢ t) = ↑↑μ s * ↑↑ν t ⊢ Measure.prod μ ν = μν [PROOFSTEP] refine' (h3C.prod h3D).ext (generateFrom_eq_prod hC hD h3C.isCountablySpanning h3D.isCountablySpanning).symm (h2C.prod h2D) _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ✝ μ : Measure α ν : Measure β C : Set (Set α) D : Set (Set β) hC : generateFrom C = inst✝⁷ hD : generateFrom D = inst✝⁵ h2C : IsPiSystem C h2D : IsPiSystem D h3C : FiniteSpanningSetsIn μ C h3D : FiniteSpanningSetsIn ν D μν : Measure (α × β) h₁ : ∀ (s : Set α), s ∈ C → ∀ (t : Set β), t ∈ D → ↑↑μν (s ×ˢ t) = ↑↑μ s * ↑↑ν t ⊢ ∀ (s : Set (α × β)), s ∈ image2 (fun x x_1 => x ×ˢ x_1) C D → ↑↑(Measure.prod μ ν) s = ↑↑μν s [PROOFSTEP] rintro _ ⟨s, t, hs, ht, rfl⟩ [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ✝ μ : Measure α ν : Measure β C : Set (Set α) D : Set (Set β) hC : generateFrom C = inst✝⁷ hD : generateFrom D = inst✝⁵ h2C : IsPiSystem C h2D : IsPiSystem D h3C : FiniteSpanningSetsIn μ C h3D : FiniteSpanningSetsIn ν D μν : Measure (α × β) h₁ : ∀ (s : Set α), s ∈ C → ∀ (t : Set β), t ∈ D → ↑↑μν (s ×ˢ t) = ↑↑μ s * ↑↑ν t s : Set α t : Set β hs : s ∈ C ht : t ∈ D ⊢ ↑↑(Measure.prod μ ν) ((fun x x_1 => x ×ˢ x_1) s t) = ↑↑μν ((fun x x_1 => x ×ˢ x_1) s t) [PROOFSTEP] haveI := h3D.sigmaFinite [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ✝ μ : Measure α ν : Measure β C : Set (Set α) D : Set (Set β) hC : generateFrom C = inst✝⁷ hD : generateFrom D = inst✝⁵ h2C : IsPiSystem C h2D : IsPiSystem D h3C : FiniteSpanningSetsIn μ C h3D : FiniteSpanningSetsIn ν D μν : Measure (α × β) h₁ : ∀ (s : Set α), s ∈ C → ∀ (t : Set β), t ∈ D → ↑↑μν (s ×ˢ t) = ↑↑μ s * ↑↑ν t s : Set α t : Set β hs : s ∈ C ht : t ∈ D this : SigmaFinite ν ⊢ ↑↑(Measure.prod μ ν) ((fun x x_1 => x ×ˢ x_1) s t) = ↑↑μν ((fun x x_1 => x ×ˢ x_1) s t) [PROOFSTEP] rw [h₁ s hs t ht, prod_prod] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ ⊢ map Prod.swap (Measure.prod μ ν) = Measure.prod ν μ [PROOFSTEP] refine' (prod_eq _).symm [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ ⊢ ∀ (s : Set β) (t : Set α), MeasurableSet s → MeasurableSet t → ↑↑(map Prod.swap (Measure.prod μ ν)) (s ×ˢ t) = ↑↑ν s * ↑↑μ t [PROOFSTEP] intro s t hs ht [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set β t : Set α hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(map Prod.swap (Measure.prod μ ν)) (s ×ˢ t) = ↑↑ν s * ↑↑μ t [PROOFSTEP] simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set (α × β) hs : MeasurableSet s ⊢ ↑↑(Measure.prod μ ν) s = ∫⁻ (y : β), ↑↑μ ((fun x => (x, y)) ⁻¹' s) ∂ν [PROOFSTEP] rw [← prod_swap, map_apply measurable_swap hs, prod_apply (measurable_swap hs)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set (α × β) hs : MeasurableSet s ⊢ ∫⁻ (x : β), ↑↑μ (Prod.mk x ⁻¹' (Prod.swap ⁻¹' s)) ∂ν = ∫⁻ (y : β), ↑↑μ ((fun x => (x, y)) ⁻¹' s) ∂ν [PROOFSTEP] rfl [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite τ ⊢ map (↑MeasurableEquiv.prodAssoc) (Measure.prod (Measure.prod μ ν) τ) = Measure.prod μ (Measure.prod ν τ) [PROOFSTEP] refine' (prod_eq_generateFrom generateFrom_measurableSet generateFrom_prod isPiSystem_measurableSet isPiSystem_prod μ.toFiniteSpanningSetsIn (ν.toFiniteSpanningSetsIn.prod τ.toFiniteSpanningSetsIn) _).symm [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite τ ⊢ ∀ (s : Set α), s ∈ {s | MeasurableSet s} → ∀ (t : Set (β × γ)), t ∈ image2 (fun x x_1 => x ×ˢ x_1) {s | MeasurableSet s} {t | MeasurableSet t} → ↑↑(map (↑MeasurableEquiv.prodAssoc) (Measure.prod (Measure.prod μ ν) τ)) (s ×ˢ t) = ↑↑μ s * ↑↑(Measure.prod ν τ) t [PROOFSTEP] rintro s hs _ ⟨t, u, ht, hu, rfl⟩ [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite τ s : Set α hs : s ∈ {s | MeasurableSet s} t : Set β u : Set γ ht : t ∈ {s | MeasurableSet s} hu : u ∈ {t | MeasurableSet t} ⊢ ↑↑(map (↑MeasurableEquiv.prodAssoc) (Measure.prod (Measure.prod μ ν) τ)) (s ×ˢ (fun x x_1 => x ×ˢ x_1) t u) = ↑↑μ s * ↑↑(Measure.prod ν τ) ((fun x x_1 => x ×ˢ x_1) t u) [PROOFSTEP] rw [mem_setOf_eq] at hs ht hu [GOAL] case intro.intro.intro.intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite τ s : Set α hs : MeasurableSet s t : Set β u : Set γ ht : MeasurableSet t hu : MeasurableSet u ⊢ ↑↑(map (↑MeasurableEquiv.prodAssoc) (Measure.prod (Measure.prod μ ν) τ)) (s ×ˢ (fun x x_1 => x ×ˢ x_1) t u) = ↑↑μ s * ↑↑(Measure.prod ν τ) ((fun x x_1 => x ×ˢ x_1) t u) [PROOFSTEP] simp_rw [map_apply (MeasurableEquiv.measurable _) (hs.prod (ht.prod hu)), MeasurableEquiv.prodAssoc, MeasurableEquiv.coe_mk, Equiv.prod_assoc_preimage, prod_prod, mul_assoc] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set α t : Set β ⊢ Measure.prod (restrict μ s) (restrict ν t) = restrict (Measure.prod μ ν) (s ×ˢ t) [PROOFSTEP] refine' prod_eq fun s' t' hs' ht' => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set α t : Set β s' : Set α t' : Set β hs' : MeasurableSet s' ht' : MeasurableSet t' ⊢ ↑↑(restrict (Measure.prod μ ν) (s ×ˢ t)) (s' ×ˢ t') = ↑↑(restrict μ s) s' * ↑↑(restrict ν t) t' [PROOFSTEP] rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs', restrict_apply ht'] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set α ⊢ Measure.prod (restrict μ s) ν = restrict (Measure.prod μ ν) (s ×ˢ univ) [PROOFSTEP] have : ν = ν.restrict Set.univ := Measure.restrict_univ.symm [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ s : Set α this : ν = restrict ν univ ⊢ Measure.prod (restrict μ s) ν = restrict (Measure.prod μ ν) (s ×ˢ univ) [PROOFSTEP] rw [this, Measure.prod_restrict, ← this] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ y : β ⊢ Measure.prod μ (dirac y) = map (fun x => (x, y)) μ [PROOFSTEP] refine' prod_eq fun s t hs ht => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ y : β s : Set α t : Set β hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(map (fun x => (x, y)) μ) (s ×ˢ t) = ↑↑μ s * ↑↑(dirac y) t [PROOFSTEP] simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ fun _ => μ s, Pi.one_apply, mul_one] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ x : α ⊢ Measure.prod (dirac x) ν = map (Prod.mk x) ν [PROOFSTEP] refine' prod_eq fun s t hs ht => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ x : α s : Set α t : Set β hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(map (Prod.mk x) ν) (s ×ˢ t) = ↑↑(dirac x) s * ↑↑ν t [PROOFSTEP] simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ fun _ => ν t, Pi.one_apply, one_mul] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ x : α y : β ⊢ Measure.prod (dirac x) (dirac y) = dirac (x, y) [PROOFSTEP] rw [prod_dirac, map_dirac measurable_prod_mk_right] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁹ : MeasurableSpace α inst✝⁸ : MeasurableSpace α' inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace β' inst✝⁵ : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁴ : NormedAddCommGroup E inst✝³ : SigmaFinite ν✝ inst✝² : SigmaFinite μ ι : Type u_7 inst✝¹ : Finite ι ν : ι → Measure β inst✝ : ∀ (i : ι), SigmaFinite (ν i) ⊢ Measure.prod μ (sum ν) = sum fun i => Measure.prod μ (ν i) [PROOFSTEP] refine' prod_eq fun s t hs ht => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁹ : MeasurableSpace α inst✝⁸ : MeasurableSpace α' inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace β' inst✝⁵ : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝⁴ : NormedAddCommGroup E inst✝³ : SigmaFinite ν✝ inst✝² : SigmaFinite μ ι : Type u_7 inst✝¹ : Finite ι ν : ι → Measure β inst✝ : ∀ (i : ι), SigmaFinite (ν i) s : Set α t : Set β hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(sum fun i => Measure.prod μ (ν i)) (s ×ˢ t) = ↑↑μ s * ↑↑(sum ν) t [PROOFSTEP] simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod, ENNReal.tsum_mul_left] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁹ : MeasurableSpace α inst✝⁸ : MeasurableSpace α' inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace β' inst✝⁵ : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁴ : NormedAddCommGroup E inst✝³ : SigmaFinite ν inst✝² : SigmaFinite μ✝ ι : Type u_7 inst✝¹ : Finite ι μ : ι → Measure α inst✝ : ∀ (i : ι), SigmaFinite (μ i) ⊢ Measure.prod (sum μ) ν = sum fun i => Measure.prod (μ i) ν [PROOFSTEP] refine' prod_eq fun s t hs ht => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁹ : MeasurableSpace α inst✝⁸ : MeasurableSpace α' inst✝⁷ : MeasurableSpace β inst✝⁶ : MeasurableSpace β' inst✝⁵ : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝⁴ : NormedAddCommGroup E inst✝³ : SigmaFinite ν inst✝² : SigmaFinite μ✝ ι : Type u_7 inst✝¹ : Finite ι μ : ι → Measure α inst✝ : ∀ (i : ι), SigmaFinite (μ i) s : Set α t : Set β hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(sum fun i => Measure.prod (μ i) ν) (s ×ˢ t) = ↑↑(sum μ) s * ↑↑ν t [PROOFSTEP] simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod, ENNReal.tsum_mul_right] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν'✝ : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ ν' : Measure β inst✝ : SigmaFinite ν' ⊢ Measure.prod μ (ν + ν') = Measure.prod μ ν + Measure.prod μ ν' [PROOFSTEP] refine' prod_eq fun s t _ _ => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν'✝ : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ ν' : Measure β inst✝ : SigmaFinite ν' s : Set α t : Set β x✝¹ : MeasurableSet s x✝ : MeasurableSet t ⊢ ↑↑(Measure.prod μ ν + Measure.prod μ ν') (s ×ˢ t) = ↑↑μ s * ↑↑(ν + ν') t [PROOFSTEP] simp_rw [add_apply, prod_prod, left_distrib] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ'✝ : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ μ' : Measure α inst✝ : SigmaFinite μ' ⊢ Measure.prod (μ + μ') ν = Measure.prod μ ν + Measure.prod μ' ν [PROOFSTEP] refine' prod_eq fun s t _ _ => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ'✝ : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ μ' : Measure α inst✝ : SigmaFinite μ' s : Set α t : Set β x✝¹ : MeasurableSet s x✝ : MeasurableSet t ⊢ ↑↑(Measure.prod μ ν + Measure.prod μ' ν) (s ×ˢ t) = ↑↑(μ + μ') s * ↑↑ν t [PROOFSTEP] simp_rw [add_apply, prod_prod, right_distrib] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ ν : Measure β ⊢ Measure.prod 0 ν = 0 [PROOFSTEP] rw [Measure.prod] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν✝ ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν✝ inst✝ : SigmaFinite μ ν : Measure β ⊢ (bind 0 fun x => map (Prod.mk x) ν) = 0 [PROOFSTEP] exact bind_zero_left _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ✝ μ : Measure α ⊢ Measure.prod μ 0 = 0 [PROOFSTEP] simp [Measure.prod] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ δ : Type u_7 inst✝ : MeasurableSpace δ f : α → β g : γ → δ μa : Measure α μc : Measure γ hfa : SigmaFinite (map f μa) hgc : SigmaFinite (map g μc) hf : Measurable f hg : Measurable g ⊢ Measure.prod (map f μa) (map g μc) = map (Prod.map f g) (Measure.prod μa μc) [PROOFSTEP] haveI := hgc.of_map μc hg.aemeasurable [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ δ : Type u_7 inst✝ : MeasurableSpace δ f : α → β g : γ → δ μa : Measure α μc : Measure γ hfa : SigmaFinite (map f μa) hgc : SigmaFinite (map g μc) hf : Measurable f hg : Measurable g this : SigmaFinite μc ⊢ Measure.prod (map f μa) (map g μc) = map (Prod.map f g) (Measure.prod μa μc) [PROOFSTEP] refine' prod_eq fun s t hs ht => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ δ : Type u_7 inst✝ : MeasurableSpace δ f : α → β g : γ → δ μa : Measure α μc : Measure γ hfa : SigmaFinite (map f μa) hgc : SigmaFinite (map g μc) hf : Measurable f hg : Measurable g this : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(map (Prod.map f g) (Measure.prod μa μc)) (s ×ˢ t) = ↑↑(map f μa) s * ↑↑(map g μc) t [PROOFSTEP] rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E inst✝² : SigmaFinite ν inst✝¹ : SigmaFinite μ δ : Type u_7 inst✝ : MeasurableSpace δ f : α → β g : γ → δ μa : Measure α μc : Measure γ hfa : SigmaFinite (map f μa) hgc : SigmaFinite (map g μc) hf : Measurable f hg : Measurable g this : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(Measure.prod μa μc) (Prod.map f g ⁻¹' s ×ˢ t) = ↑↑μa (f ⁻¹' s) * ↑↑μc (g ⁻¹' t) [PROOFSTEP] exact prod_prod (f ⁻¹' s) (g ⁻¹' t) [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] classical have : Measurable fun p : α × γ => (f p.1, g p.1 p.2) := (hf.1.comp measurable_fst).prod_mk hgm rcases eq_or_ne μa 0 with (rfl | ha) · rw [← hf.map_eq, zero_prod, Measure.map_zero, zero_prod] exact ⟨this, by simp only [Measure.map_zero]⟩ have sf : SigmaFinite μc := by rcases(ae_neBot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩ exact SigmaFinite.of_map _ hgm.of_uncurry_left.aemeasurable (by rwa [hx]) -- Thus we can apply `Measure.prod_eq` to prove equality of measures. refine' ⟨this, (prod_eq fun s t hs ht => _).symm⟩ rw [map_apply this (hs.prod ht)] refine' (prod_apply (this <| hs.prod ht)).trans _ have : ∀ᵐ x ∂μa, μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun _ => μd t) x := by refine' hg.mono fun x hx => _ subst hx simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage] split_ifs exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] simp only [preimage_preimage] rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] have : Measurable fun p : α × γ => (f p.1, g p.1 p.2) := (hf.1.comp measurable_fst).prod_mk hgm [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] rcases eq_or_ne μa 0 with (rfl | ha) [GOAL] case inl α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) hf : MeasurePreserving f hg : ∀ᵐ (x : α) ∂0, map (g x) μc = μd ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] rw [← hf.map_eq, zero_prod, Measure.map_zero, zero_prod] [GOAL] case inl α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) hf : MeasurePreserving f hg : ∀ᵐ (x : α) ∂0, map (g x) μc = μd ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] exact ⟨this, by simp only [Measure.map_zero]⟩ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) hf : MeasurePreserving f hg : ∀ᵐ (x : α) ∂0, map (g x) μc = μd ⊢ map (fun p => (f p.fst, g p.fst p.snd)) 0 = 0 [PROOFSTEP] simp only [Measure.map_zero] [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] have sf : SigmaFinite μc := by rcases(ae_neBot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩ exact SigmaFinite.of_map _ hgm.of_uncurry_left.aemeasurable (by rwa [hx]) -- Thus we can apply `Measure.prod_eq` to prove equality of measures. [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 ⊢ SigmaFinite μc [PROOFSTEP] rcases(ae_neBot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩ [GOAL] case intro α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 x : α hx : map (g x) μc = μd ⊢ SigmaFinite μc [PROOFSTEP] exact SigmaFinite.of_map _ hgm.of_uncurry_left.aemeasurable (by rwa [hx]) -- Thus we can apply `Measure.prod_eq` to prove equality of measures. [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 x : α hx : map (g x) μc = μd ⊢ SigmaFinite (map (g ?m.96015) μc) [PROOFSTEP] rwa [hx] [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc ⊢ MeasurePreserving fun p => (f p.fst, g p.fst p.snd) [PROOFSTEP] refine' ⟨this, (prod_eq fun s t hs ht => _).symm⟩ [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(map (fun p => (f p.fst, g p.fst p.snd)) (Measure.prod μa μc)) (s ×ˢ t) = ↑↑μb s * ↑↑μd t [PROOFSTEP] rw [map_apply this (hs.prod ht)] [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ↑↑(Measure.prod μa μc) ((fun p => (f p.fst, g p.fst p.snd)) ⁻¹' s ×ˢ t) = ↑↑μb s * ↑↑μd t [PROOFSTEP] refine' (prod_apply (this <| hs.prod ht)).trans _ [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ∫⁻ (x : α), ↑↑μc (Prod.mk x ⁻¹' ((fun p => (f p.fst, g p.fst p.snd)) ⁻¹' s ×ˢ t)) ∂μa = ↑↑μb s * ↑↑μd t [PROOFSTEP] have : ∀ᵐ x ∂μa, μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun _ => μd t) x := by refine' hg.mono fun x hx => _ subst hx simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage] split_ifs exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t ⊢ ∀ᵐ (x : α) ∂μa, ↑↑μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun x => ↑↑μd t) x [PROOFSTEP] refine' hg.mono fun x hx => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t x : α hx : map (g x) μc = μd ⊢ ↑↑μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun x => ↑↑μd t) x [PROOFSTEP] subst hx [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ inst✝¹ : SigmaFinite μb f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t x : α inst✝ : SigmaFinite (map (g x) μc) hg : ∀ᵐ (x_1 : α) ∂μa, map (g x_1) μc = map (g x) μc ⊢ ↑↑μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun x_1 => ↑↑(map (g x) μc) t) x [PROOFSTEP] simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ inst✝¹ : SigmaFinite μb f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t x : α inst✝ : SigmaFinite (map (g x) μc) hg : ∀ᵐ (x_1 : α) ∂μa, map (g x_1) μc = map (g x) μc ⊢ ↑↑μc (if f x ∈ s then (fun b => g x b) ⁻¹' t else ∅) = if f x ∈ s then ↑↑(map (g x) μc) t else 0 [PROOFSTEP] split_ifs [GOAL] case pos α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ inst✝¹ : SigmaFinite μb f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t x : α inst✝ : SigmaFinite (map (g x) μc) hg : ∀ᵐ (x_1 : α) ∂μa, map (g x_1) μc = map (g x) μc h✝ : f x ∈ s ⊢ ↑↑μc ((fun b => g x b) ⁻¹' t) = ↑↑(map (g x) μc) t case neg α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ inst✝¹ : SigmaFinite μb f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) this : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t x : α inst✝ : SigmaFinite (map (g x) μc) hg : ∀ᵐ (x_1 : α) ∂μa, map (g x_1) μc = map (g x) μc h✝ : ¬f x ∈ s ⊢ ↑↑μc ∅ = 0 [PROOFSTEP] exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this✝ : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t this : ∀ᵐ (x : α) ∂μa, ↑↑μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun x => ↑↑μd t) x ⊢ ∫⁻ (x : α), ↑↑μc (Prod.mk x ⁻¹' ((fun p => (f p.fst, g p.fst p.snd)) ⁻¹' s ×ˢ t)) ∂μa = ↑↑μb s * ↑↑μd t [PROOFSTEP] simp only [preimage_preimage] [GOAL] case inr α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁸ : MeasurableSpace α inst✝⁷ : MeasurableSpace α' inst✝⁶ : MeasurableSpace β inst✝⁵ : MeasurableSpace β' inst✝⁴ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝³ : NormedAddCommGroup E δ : Type u_7 inst✝² : MeasurableSpace δ μa : Measure α μb : Measure β μc : Measure γ μd : Measure δ inst✝¹ : SigmaFinite μb inst✝ : SigmaFinite μd f : α → β hf : MeasurePreserving f g : α → γ → δ hgm : Measurable (uncurry g) hg : ∀ᵐ (x : α) ∂μa, map (g x) μc = μd this✝ : Measurable fun p => (f p.fst, g p.fst p.snd) ha : μa ≠ 0 sf : SigmaFinite μc s : Set β t : Set δ hs : MeasurableSet s ht : MeasurableSet t this : ∀ᵐ (x : α) ∂μa, ↑↑μc ((fun y => (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (fun x => ↑↑μd t) x ⊢ ∫⁻ (x : α), ↑↑μc ((fun x_1 => (f x, g x x_1)) ⁻¹' s ×ˢ t) ∂μa = ↑↑μb s * ↑↑μd t [PROOFSTEP] rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ✝ : Measure γ inst✝¹ : NormedAddCommGroup E f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝ : SigmaFinite ν h2f : ∀ᵐ (x : α) ∂μ, QuasiMeasurePreserving fun y => f (x, y) ⊢ QuasiMeasurePreserving f [PROOFSTEP] refine' ⟨hf, _⟩ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ✝ : Measure γ inst✝¹ : NormedAddCommGroup E f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝ : SigmaFinite ν h2f : ∀ᵐ (x : α) ∂μ, QuasiMeasurePreserving fun y => f (x, y) ⊢ map f (Measure.prod μ ν) ≪ τ [PROOFSTEP] refine' AbsolutelyContinuous.mk fun s hs h2s => _ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ✝ : Measure γ inst✝¹ : NormedAddCommGroup E f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝ : SigmaFinite ν h2f : ∀ᵐ (x : α) ∂μ, QuasiMeasurePreserving fun y => f (x, y) s : Set γ hs : MeasurableSet s h2s : ↑↑τ s = 0 ⊢ ↑↑(map f (Measure.prod μ ν)) s = 0 [PROOFSTEP] rw [map_apply hf hs, prod_apply (hf hs)] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ✝ : Measure γ inst✝¹ : NormedAddCommGroup E f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝ : SigmaFinite ν h2f : ∀ᵐ (x : α) ∂μ, QuasiMeasurePreserving fun y => f (x, y) s : Set γ hs : MeasurableSet s h2s : ↑↑τ s = 0 ⊢ ∫⁻ (x : α), ↑↑ν (Prod.mk x ⁻¹' (f ⁻¹' s)) ∂μ = 0 [PROOFSTEP] simp_rw [preimage_preimage] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν✝ ν' : Measure β τ✝ : Measure γ inst✝¹ : NormedAddCommGroup E f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝ : SigmaFinite ν h2f : ∀ᵐ (x : α) ∂μ, QuasiMeasurePreserving fun y => f (x, y) s : Set γ hs : MeasurableSet s h2s : ↑↑τ s = 0 ⊢ ∫⁻ (x : α), ↑↑ν ((fun x_1 => f (x, x_1)) ⁻¹' s) ∂μ = 0 [PROOFSTEP] rw [lintegral_congr_ae (h2f.mono fun x hx => hx.preimage_null h2s), lintegral_zero] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝¹⁰ : MeasurableSpace α✝ inst✝⁹ : MeasurableSpace α' inst✝⁸ : MeasurableSpace β✝ inst✝⁷ : MeasurableSpace β' inst✝⁶ : MeasurableSpace γ✝ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ✝ : Measure γ✝ inst✝⁵ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 inst✝⁴ : MeasurableSpace α inst✝³ : MeasurableSpace β inst✝² : MeasurableSpace γ f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite ν h2f : ∀ᵐ (y : β) ∂ν, QuasiMeasurePreserving fun x => f (x, y) ⊢ QuasiMeasurePreserving f [PROOFSTEP] rw [← prod_swap] [GOAL] α✝ : Type u_1 α' : Type u_2 β✝ : Type u_3 β' : Type u_4 γ✝ : Type u_5 E : Type u_6 inst✝¹⁰ : MeasurableSpace α✝ inst✝⁹ : MeasurableSpace α' inst✝⁸ : MeasurableSpace β✝ inst✝⁷ : MeasurableSpace β' inst✝⁶ : MeasurableSpace γ✝ μ✝ μ' : Measure α✝ ν✝ ν' : Measure β✝ τ✝ : Measure γ✝ inst✝⁵ : NormedAddCommGroup E α : Type u_7 β : Type u_8 γ : Type u_9 inst✝⁴ : MeasurableSpace α inst✝³ : MeasurableSpace β inst✝² : MeasurableSpace γ f : α × β → γ μ : Measure α ν : Measure β τ : Measure γ hf : Measurable f inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite ν h2f : ∀ᵐ (y : β) ∂ν, QuasiMeasurePreserving fun x => f (x, y) ⊢ QuasiMeasurePreserving f [PROOFSTEP] convert (QuasiMeasurePreserving.prod_of_right (hf.comp measurable_swap) h2f).comp ((measurable_swap.measurePreserving (ν.prod μ)).symm MeasurableEquiv.prodComm).quasiMeasurePreserving [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite ν f : β × α → γ hf : AEMeasurable f ⊢ AEMeasurable fun z => f (Prod.swap z) [PROOFSTEP] rw [← Measure.prod_swap] at hf [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite μ inst✝ : SigmaFinite ν f : β × α → γ hf : AEMeasurable f ⊢ AEMeasurable fun z => f (Prod.swap z) [PROOFSTEP] exact hf.comp_measurable measurable_swap [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ f : α × β → ℝ≥0∞ hf : AEMeasurable f ⊢ ∫⁻ (z : β × α), f (Prod.swap z) ∂Measure.prod ν μ = ∫⁻ (z : α × β), f z ∂Measure.prod μ ν [PROOFSTEP] rw [← prod_swap] at hf [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ f : α × β → ℝ≥0∞ hf : AEMeasurable f ⊢ ∫⁻ (z : β × α), f (Prod.swap z) ∂Measure.prod ν μ = ∫⁻ (z : α × β), f z ∂Measure.prod μ ν [PROOFSTEP] rw [← lintegral_map' hf measurable_swap.aemeasurable, prod_swap] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ⊢ ∀ (f : α × β → ℝ≥0∞), Measurable f → ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ [PROOFSTEP] have m := @measurable_prod_mk_left [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ (f : α × β → ℝ≥0∞), Measurable f → ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ [PROOFSTEP] refine' Measurable.ennreal_induction (P := fun f => ∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ) _ _ _ [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ (c : ℝ≥0∞) ⦃s : Set (α × β)⦄, MeasurableSet s → (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (indicator s fun x => c) [PROOFSTEP] intro c s hs [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ ∫⁻ (z : α × β), indicator s (fun x => c) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), indicator s (fun x => c) (x, y) ∂ν ∂μ [PROOFSTEP] conv_rhs => enter [2, x, 2, y] rw [← indicator_comp_right, const_def, const_comp, ← const_def] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator s (fun x => c) (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x, 2, y] rw [← indicator_comp_right, const_def, const_comp, ← const_def] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator s (fun x => c) (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x, 2, y] rw [← indicator_comp_right, const_def, const_comp, ← const_def] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator s (fun x => c) (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x, 2, y] [GOAL] case h.h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s x : α y : β | indicator s (fun x => c) (x, y) [PROOFSTEP] rw [← indicator_comp_right, const_def, const_comp, ← const_def] [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ ∫⁻ (z : α × β), indicator s (fun x => c) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), indicator (Prod.mk x ⁻¹' s) (fun x => c) y ∂ν ∂μ [PROOFSTEP] conv_rhs => enter [2, x] rw [lintegral_indicator _ (m (x := x) hs), lintegral_const, Measure.restrict_apply MeasurableSet.univ, univ_inter] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator (Prod.mk x ⁻¹' s) (fun x => c) y ∂ν ∂μ [PROOFSTEP] enter [2, x] rw [lintegral_indicator _ (m (x := x) hs), lintegral_const, Measure.restrict_apply MeasurableSet.univ, univ_inter] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator (Prod.mk x ⁻¹' s) (fun x => c) y ∂ν ∂μ [PROOFSTEP] enter [2, x] rw [lintegral_indicator _ (m (x := x) hs), lintegral_const, Measure.restrict_apply MeasurableSet.univ, univ_inter] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s | ∫⁻ (x : α), ∫⁻ (y : β), indicator (Prod.mk x ⁻¹' s) (fun x => c) y ∂ν ∂μ [PROOFSTEP] enter [2, x] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type ?u.142685} {β : Type ?u.142686} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s x : α | ∫⁻ (y : β), indicator (Prod.mk x ⁻¹' s) (fun x => c) y ∂ν [PROOFSTEP] rw [lintegral_indicator _ (m (x := x) hs), lintegral_const, Measure.restrict_apply MeasurableSet.univ, univ_inter] [GOAL] case refine'_1 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) c : ℝ≥0∞ s : Set (α × β) hs : MeasurableSet s ⊢ ∫⁻ (z : α × β), indicator s (fun x => c) z ∂Measure.prod μ ν = ∫⁻ (x : α), c * ↑↑ν (Prod.mk x ⁻¹' s) ∂μ [PROOFSTEP] simp [hs, lintegral_const_mul, measurable_measure_prod_mk_left (ν := ν) hs, prod_apply] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ ⦃f g : α × β → ℝ≥0∞⦄, Disjoint (support f) (support g) → Measurable f → Measurable g → (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) f → (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) g → (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f + g) [PROOFSTEP] rintro f g - hf _ h2f h2g [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ ⊢ ∫⁻ (z : α × β), (f + g) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (f + g) (x, y) ∂ν ∂μ [PROOFSTEP] simp only [Pi.add_apply] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ ⊢ ∫⁻ (z : α × β), f z + g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν ∂μ [PROOFSTEP] conv_lhs => rw [lintegral_add_left hf] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (z : α × β), f z + g z ∂Measure.prod μ ν [PROOFSTEP] rw [lintegral_add_left hf] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (z : α × β), f z + g z ∂Measure.prod μ ν [PROOFSTEP] rw [lintegral_add_left hf] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (z : α × β), f z + g z ∂Measure.prod μ ν [PROOFSTEP] rw [lintegral_add_left hf] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ ⊢ ∫⁻ (a : α × β), f a ∂Measure.prod μ ν + ∫⁻ (a : α × β), g a ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν ∂μ [PROOFSTEP] conv_rhs => enter [2, x]; erw [lintegral_add_left (hf.comp (m (x := x)))] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x]; erw [lintegral_add_left (hf.comp (m (x := x)))] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x]; erw [lintegral_add_left (hf.comp (m (x := x)))] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ | ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν ∂μ [PROOFSTEP] enter [2, x] [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ x : α | ∫⁻ (y : β), f (x, y) + g (x, y) ∂ν [PROOFSTEP] erw [lintegral_add_left (hf.comp (m (x := x)))] [GOAL] case refine'_2 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f g : α × β → ℝ≥0∞ hf : Measurable f a✝ : Measurable g h2f : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ h2g : ∫⁻ (z : α × β), g z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), g (x, y) ∂ν ∂μ ⊢ ∫⁻ (a : α × β), f a ∂Measure.prod μ ν + ∫⁻ (a : α × β), g a ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (a : β), (f ∘ Prod.mk x) a ∂ν + ∫⁻ (a : β), g (x, a) ∂ν ∂μ [PROOFSTEP] simp [lintegral_add_left, Measurable.lintegral_prod_right', hf, h2f, h2g] [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) ⊢ ∀ ⦃f : ℕ → α × β → ℝ≥0∞⦄, (∀ (n : ℕ), Measurable (f n)) → Monotone f → (∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n)) → (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) fun x => ⨆ (n : ℕ), f n x [PROOFSTEP] intro f hf h2f h3f [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n) ⊢ ∫⁻ (z : α × β), (fun x => ⨆ (n : ℕ), f n x) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν ∂μ [PROOFSTEP] have kf : ∀ x n, Measurable fun y => f n (x, y) := fun x n => (hf n).comp m [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n) kf : ∀ (x : α) (n : ℕ), Measurable fun y => f n (x, y) ⊢ ∫⁻ (z : α × β), (fun x => ⨆ (n : ℕ), f n x) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν ∂μ [PROOFSTEP] have k2f : ∀ x, Monotone fun n y => f n (x, y) := fun x i j hij y => h2f hij (x, y) [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n) kf : ∀ (x : α) (n : ℕ), Measurable fun y => f n (x, y) k2f : ∀ (x : α), Monotone fun n y => f n (x, y) ⊢ ∫⁻ (z : α × β), (fun x => ⨆ (n : ℕ), f n x) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν ∂μ [PROOFSTEP] have lf : ∀ n, Measurable fun x => ∫⁻ y, f n (x, y) ∂ν := fun n => (hf n).lintegral_prod_right' [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n) kf : ∀ (x : α) (n : ℕ), Measurable fun y => f n (x, y) k2f : ∀ (x : α), Monotone fun n y => f n (x, y) lf : ∀ (n : ℕ), Measurable fun x => ∫⁻ (y : β), f n (x, y) ∂ν ⊢ ∫⁻ (z : α × β), (fun x => ⨆ (n : ℕ), f n x) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν ∂μ [PROOFSTEP] have l2f : Monotone fun n x => ∫⁻ y, f n (x, y) ∂ν := fun i j hij x => lintegral_mono (k2f x hij) [GOAL] case refine'_3 α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν m : ∀ {α : Type u_1} {β : Type u_3} {m : MeasurableSpace α} {mβ : MeasurableSpace β} {x : α}, Measurable (Prod.mk x) f : ℕ → α × β → ℝ≥0∞ hf : ∀ (n : ℕ), Measurable (f n) h2f : Monotone f h3f : ∀ (n : ℕ), (fun f => ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ) (f n) kf : ∀ (x : α) (n : ℕ), Measurable fun y => f n (x, y) k2f : ∀ (x : α), Monotone fun n y => f n (x, y) lf : ∀ (n : ℕ), Measurable fun x => ∫⁻ (y : β), f n (x, y) ∂ν l2f : Monotone fun n x => ∫⁻ (y : β), f n (x, y) ∂ν ⊢ ∫⁻ (z : α × β), (fun x => ⨆ (n : ℕ), f n x) z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), (fun x => ⨆ (n : ℕ), f n x) (x, y) ∂ν ∂μ [PROOFSTEP] simp only [lintegral_iSup hf h2f, lintegral_iSup (kf _), k2f, lintegral_iSup lf l2f, h3f] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α × β → ℝ≥0∞ hf : AEMeasurable f ⊢ ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ [PROOFSTEP] have A : ∫⁻ z, f z ∂μ.prod ν = ∫⁻ z, hf.mk f z ∂μ.prod ν := lintegral_congr_ae hf.ae_eq_mk [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α × β → ℝ≥0∞ hf : AEMeasurable f A : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (z : α × β), AEMeasurable.mk f hf z ∂Measure.prod μ ν ⊢ ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ [PROOFSTEP] have B : (∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ) = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ := by apply lintegral_congr_ae filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α × β → ℝ≥0∞ hf : AEMeasurable f A : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (z : α × β), AEMeasurable.mk f hf z ∂Measure.prod μ ν ⊢ ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ = ∫⁻ (x : α), ∫⁻ (y : β), AEMeasurable.mk f hf (x, y) ∂ν ∂μ [PROOFSTEP] apply lintegral_congr_ae [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α × β → ℝ≥0∞ hf : AEMeasurable f A : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (z : α × β), AEMeasurable.mk f hf z ∂Measure.prod μ ν ⊢ (fun a => ∫⁻ (y : β), f (a, y) ∂ν) =ᶠ[ae μ] fun a => ∫⁻ (y : β), AEMeasurable.mk f hf (a, y) ∂ν [PROOFSTEP] filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α × β → ℝ≥0∞ hf : AEMeasurable f A : ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (z : α × β), AEMeasurable.mk f hf z ∂Measure.prod μ ν B : ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ = ∫⁻ (x : α), ∫⁻ (y : β), AEMeasurable.mk f hf (x, y) ∂ν ∂μ ⊢ ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (x : α), ∫⁻ (y : β), f (x, y) ∂ν ∂μ [PROOFSTEP] rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ f : α × β → ℝ≥0∞ hf : AEMeasurable f ⊢ ∫⁻ (z : α × β), f z ∂Measure.prod μ ν = ∫⁻ (y : β), ∫⁻ (x : α), f (x, y) ∂μ ∂ν [PROOFSTEP] simp_rw [← lintegral_prod_swap f hf] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν inst✝ : SigmaFinite μ f : α × β → ℝ≥0∞ hf : AEMeasurable f ⊢ ∫⁻ (z : β × α), f (Prod.swap z) ∂Measure.prod ν μ = ∫⁻ (y : β), ∫⁻ (x : α), f (x, y) ∂μ ∂ν [PROOFSTEP] exact lintegral_prod _ hf.prod_swap [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν f : α → ℝ≥0∞ g : β → ℝ≥0∞ hf : AEMeasurable f hg : AEMeasurable g ⊢ ∫⁻ (z : α × β), f z.fst * g z.snd ∂Measure.prod μ ν = (∫⁻ (x : α), f x ∂μ) * ∫⁻ (y : β), g y ∂ν [PROOFSTEP] simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) s : Set α hs : MeasurableSet s ⊢ ↑↑(fst ρ) s = ↑↑ρ (Prod.fst ⁻¹' s) [PROOFSTEP] rw [fst, Measure.map_apply measurable_fst hs] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) ⊢ ↑↑(fst ρ) univ = ↑↑ρ univ [PROOFSTEP] rw [fst_apply MeasurableSet.univ, preimage_univ] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) ⊢ fst 0 = 0 [PROOFSTEP] simp [fst] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsFiniteMeasure ρ ⊢ IsFiniteMeasure (fst ρ) [PROOFSTEP] rw [fst] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsFiniteMeasure ρ ⊢ IsFiniteMeasure (map Prod.fst ρ) [PROOFSTEP] infer_instance [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ρ ⊢ ↑↑(fst ρ) univ = 1 [PROOFSTEP] rw [fst_univ] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ρ ⊢ ↑↑ρ univ = 1 [PROOFSTEP] exact measure_univ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ν ⊢ fst (Measure.prod μ ν) = μ [PROOFSTEP] ext1 s hs [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ν s : Set α hs : MeasurableSet s ⊢ ↑↑(fst (Measure.prod μ ν)) s = ↑↑μ s [PROOFSTEP] rw [fst_apply hs, ← prod_univ, prod_prod, measure_univ, mul_one] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y ⊢ fst (map (fun a => (X a, Y a)) μ) = map X μ [PROOFSTEP] by_cases hX : AEMeasurable X μ [GOAL] case pos α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : AEMeasurable X ⊢ fst (map (fun a => (X a, Y a)) μ) = map X μ [PROOFSTEP] ext1 s hs [GOAL] case pos.h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : AEMeasurable X s : Set β hs : MeasurableSet s ⊢ ↑↑(fst (map (fun a => (X a, Y a)) μ)) s = ↑↑(map X μ) s [PROOFSTEP] rw [Measure.fst_apply hs, Measure.map_apply_of_aemeasurable (hX.prod_mk hY) (measurable_fst hs), Measure.map_apply_of_aemeasurable hX hs, ← prod_univ, mk_preimage_prod, preimage_univ, inter_univ] [GOAL] case neg α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : ¬AEMeasurable X ⊢ fst (map (fun a => (X a, Y a)) μ) = map X μ [PROOFSTEP] have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by contrapose! hX; exact measurable_fst.comp_aemeasurable hX [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : ¬AEMeasurable X ⊢ ¬AEMeasurable fun x => (X x, Y x) [PROOFSTEP] contrapose! hX [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : AEMeasurable fun x => (X x, Y x) ⊢ AEMeasurable X [PROOFSTEP] exact measurable_fst.comp_aemeasurable hX [GOAL] case neg α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hY : AEMeasurable Y hX : ¬AEMeasurable X this : ¬AEMeasurable fun x => (X x, Y x) ⊢ fst (map (fun a => (X a, Y a)) μ) = map X μ [PROOFSTEP] simp [map_of_not_aemeasurable, hX, this] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) s : Set β hs : MeasurableSet s ⊢ ↑↑(snd ρ) s = ↑↑ρ (Prod.snd ⁻¹' s) [PROOFSTEP] rw [snd, Measure.map_apply measurable_snd hs] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) ⊢ ↑↑(snd ρ) univ = ↑↑ρ univ [PROOFSTEP] rw [snd_apply MeasurableSet.univ, preimage_univ] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) ⊢ snd 0 = 0 [PROOFSTEP] simp [snd] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsFiniteMeasure ρ ⊢ IsFiniteMeasure (snd ρ) [PROOFSTEP] rw [snd] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsFiniteMeasure ρ ⊢ IsFiniteMeasure (map Prod.snd ρ) [PROOFSTEP] infer_instance [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ρ ⊢ ↑↑(snd ρ) univ = 1 [PROOFSTEP] rw [snd_univ] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure ρ ⊢ ↑↑ρ univ = 1 [PROOFSTEP] exact measure_univ [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure μ ⊢ snd (Measure.prod μ ν) = ν [PROOFSTEP] ext1 s hs [GOAL] case h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁷ : MeasurableSpace α inst✝⁶ : MeasurableSpace α' inst✝⁵ : MeasurableSpace β inst✝⁴ : MeasurableSpace β' inst✝³ : MeasurableSpace γ μ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝² : NormedAddCommGroup E inst✝¹ : SigmaFinite ν ρ : Measure (α × β) inst✝ : IsProbabilityMeasure μ s : Set β hs : MeasurableSet s ⊢ ↑↑(snd (Measure.prod μ ν)) s = ↑↑ν s [PROOFSTEP] rw [snd_apply hs, ← univ_prod, prod_prod, measure_univ, one_mul] [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X ⊢ snd (map (fun a => (X a, Y a)) μ) = map Y μ [PROOFSTEP] by_cases hY : AEMeasurable Y μ [GOAL] case pos α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : AEMeasurable Y ⊢ snd (map (fun a => (X a, Y a)) μ) = map Y μ [PROOFSTEP] ext1 s hs [GOAL] case pos.h α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : AEMeasurable Y s : Set γ hs : MeasurableSet s ⊢ ↑↑(snd (map (fun a => (X a, Y a)) μ)) s = ↑↑(map Y μ) s [PROOFSTEP] rw [Measure.snd_apply hs, Measure.map_apply_of_aemeasurable (hX.prod_mk hY) (measurable_snd hs), Measure.map_apply_of_aemeasurable hY hs, ← univ_prod, mk_preimage_prod, preimage_univ, univ_inter] [GOAL] case neg α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : ¬AEMeasurable Y ⊢ snd (map (fun a => (X a, Y a)) μ) = map Y μ [PROOFSTEP] have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by contrapose! hY; exact measurable_snd.comp_aemeasurable hY [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : ¬AEMeasurable Y ⊢ ¬AEMeasurable fun x => (X x, Y x) [PROOFSTEP] contrapose! hY [GOAL] α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : AEMeasurable fun x => (X x, Y x) ⊢ AEMeasurable Y [PROOFSTEP] exact measurable_snd.comp_aemeasurable hY [GOAL] case neg α : Type u_1 α' : Type u_2 β : Type u_3 β' : Type u_4 γ : Type u_5 E : Type u_6 inst✝⁶ : MeasurableSpace α inst✝⁵ : MeasurableSpace α' inst✝⁴ : MeasurableSpace β inst✝³ : MeasurableSpace β' inst✝² : MeasurableSpace γ μ✝ μ' : Measure α ν ν' : Measure β τ : Measure γ inst✝¹ : NormedAddCommGroup E inst✝ : SigmaFinite ν ρ : Measure (α × β) X : α → β Y : α → γ μ : Measure α hX : AEMeasurable X hY : ¬AEMeasurable Y this : ¬AEMeasurable fun x => (X x, Y x) ⊢ snd (map (fun a => (X a, Y a)) μ) = map Y μ [PROOFSTEP] simp [map_of_not_aemeasurable, hY, this]
/** * Copyright (c) 2019 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <type_traits> #include <stack> #include <iostream> #include <boost/iostreams/stream_buffer.hpp> #include <boost/iostreams/device/array.hpp> #include "dbglog/dbglog.hpp" #include "math/transform.hpp" #include "meshloader.hpp" namespace bio = boost::iostreams; namespace gltf { MeshLoader::~MeshLoader() {} namespace { using ArrayBuffer = bio::stream_buffer<bio::array_source> ; using VertexIndex = std::uint32_t; template <typename T> const std::vector<T>& getList(const Model &model); template <typename T> const char* typeName(); #define DEDCLARE_TYPE(Type, Name) \ template <> const std::vector<Type>& \ getList<Type>(const Model &model) { return model.Name; } \ template <> constexpr const char* typeName<Type>() { return #Type; } DEDCLARE_TYPE(Scene, scenes) DEDCLARE_TYPE(Node, nodes) DEDCLARE_TYPE(Mesh, meshes) DEDCLARE_TYPE(Sampler, samplers) DEDCLARE_TYPE(Texture, textures) DEDCLARE_TYPE(Buffer, buffers) DEDCLARE_TYPE(Image, images) DEDCLARE_TYPE(BufferView, bufferViews) DEDCLARE_TYPE(Accessor, accessors) DEDCLARE_TYPE(Material, materials) #undef DEDCLARE_TYPE struct ModelGetter { ModelGetter(const Model &model) : model(model) {} const Model &model; template <typename T> const T& get(Index index) const { const auto &list(getList<T>(model)); if ((index < 0) || (std::size_t(index) >= list.size())) { LOGTHROW(err1, std::runtime_error) << typeName<T>() << " index " << index << " out of range [0, " << list.size() << ")."; } return list[index]; } template <typename T> const T* get(const OptIndex &index) const { return index ? &get<T>(*index) : nullptr; } const Scene& getScene(const OptIndex &useScene) const { if (useScene) { return get<Scene>(*useScene); } if (model.scene) { return get<Scene>(*model.scene); } if (model.scenes.empty()) { LOGTHROW(err1, std::runtime_error) << "No usable scene in glTF model."; } return model.scenes.front(); } }; template <typename T> const char* getName(const T &what) { return what.name ? what.name->c_str() : typeName<T>(); } using TrafoStack = std::stack<math::Matrix4>; TrafoStack* applyNodeTrafo(TrafoStack &stack, const Node &node) { if (node.matrix) { stack.push(prod(stack.top(), *node.matrix)); return &stack; } // TODO: apply T * R * S from node if (node.rotation || node.scale || node.translation) { LOGTHROW(err1, std::runtime_error) << "rotation/scale/translation not implemented yet"; } return nullptr; } struct TrafoHolder { TrafoStack *trafos; TrafoHolder(TrafoStack &trafos, const Node &node) : trafos(applyNodeTrafo(trafos, node)) {} ~TrafoHolder() { if (trafos) { trafos->pop(); } } }; template <typename T> const T* getBegin(const Accessor &a, const BufferView &bv, const Data &data) { return reinterpret_cast<const T*> (data.data() + bv.byteOffset + a.offset); } template <typename T> std::size_t getSkip(const Accessor &a, const BufferView &bv) { // tightly packed? => no skip if (!bv.byteStride) { return 0; } // stride in scalars const auto typedStride(*bv.byteStride / sizeof(T)); // how many scalars we need to skip to next one return typedStride - elementSize(a.type); } template <typename T, bool normalized, typename Enable = void> struct Normalizer; template <typename T> struct Normalizer<T, false, void> { double normalize(T value) const { return value; } }; // signed template <typename T> struct Normalizer<T, true, typename std::enable_if <std::is_signed<T>::value>::type> { double normalize(T value) const { if (value >= 0) { return value / max; } return value / min; }; static constexpr double min = -std::numeric_limits<T>::min(); static constexpr double max = std::numeric_limits<T>::max(); }; // unsigned template <typename T> struct Normalizer<T, true, typename std::enable_if <std::is_unsigned<T>::value>::type> { double normalize(T value) const { return value / max; }; static constexpr double max = std::numeric_limits<T>::max(); }; template <typename StoredT, bool normalized> class AttributeReader : private Normalizer<StoredT, normalized> { public: using stored_type = StoredT; AttributeReader(const Accessor &a, const BufferView &bv, const Data &data) : elementSize_(elementSize(a.type)) , begin_(getBegin<stored_type>(a, bv, data)) , skip_(getSkip<stored_type>(a, bv)) , end_(begin_ + a.count * (elementSize_ + skip_)) {} template <typename F> void read(F f) const { for (const auto *i(begin_); i != end_; i += skip_) { for (std::size_t index(0); index < elementSize_; ++index, ++i) { f(this->normalize(*i), index); } } } private: std::size_t elementSize_; const stored_type *begin_; const std::size_t skip_; const stored_type *end_; }; class AttributeExtractor { public: AttributeExtractor(const Accessor &a, const BufferView &bv , const Data &data) : a_(a), bv_(bv), data_(data) {} /** Calls f(item) for each item. */ template <typename F> void read(F f) const { #define CASE_TYPE(CType, Type, Normalized) \ case ComponentType::CType: \ return AttributeReader<Type, Normalized>(a_, bv_, data_).read(f) if (a_.normalized) { switch (a_.componentType) { CASE_TYPE(byte, std::int8_t, true); CASE_TYPE(ubyte, std::uint8_t, true); CASE_TYPE(short_, std::int16_t, true); CASE_TYPE(ushort, std::uint16_t, true); CASE_TYPE(uint, std::uint32_t, true); CASE_TYPE(float_, float, false); } } else { switch (a_.componentType) { CASE_TYPE(byte, std::int8_t, false); CASE_TYPE(ubyte, std::uint8_t, false); CASE_TYPE(short_, std::int16_t, false); CASE_TYPE(ushort, std::uint16_t, false); CASE_TYPE(uint, std::uint32_t, false); CASE_TYPE(float_, float, false); } } #undef CASE_TYPE } private: const Accessor &a_; const BufferView &bv_; const Data &data_; }; template <typename StoredT> class IndexReader { public: using stored_type = StoredT; IndexReader(const Accessor &a, const BufferView &bv, const Data &data) : begin_(getBegin<stored_type>(a, bv, data)) , end_(begin_ + a.count) {} template <typename F> void read(F f) const { for (const auto *i(begin_); i != end_; ++i) { f(*i); } } private: const stored_type *begin_; const stored_type *end_; }; class IndexExtractor { public: IndexExtractor(const Accessor &a, const BufferView &bv, const Data &data) : a_(a), bv_(bv), data_(data) {} /** Calls f(item) for each item. */ template <typename F> void read(F f) const { if (a_.type != AttributeType::scalar) { LOGTHROW(err1, std::runtime_error) << "Index must be a scalar."; } if (a_.normalized) { LOGTHROW(err1, std::runtime_error) << "Index must not be normalized."; } #define CASE_TYPE(CType, Type) \ case ComponentType::CType: \ return IndexReader<Type>(a_, bv_, data_).read(f) switch (a_.componentType) { CASE_TYPE(ubyte, std::uint8_t); CASE_TYPE(ushort, std::uint16_t); CASE_TYPE(uint, std::uint32_t); default: LOGTHROW(err1, std::runtime_error) << "Index must be a unsigned number."; } #undef CASE_TYPE } private: const Accessor &a_; const BufferView &bv_; const Data &data_; }; const Data& extractData(const ModelGetter &mg, Index index) { struct AttributeExtractor : public boost::static_visitor<const Data&> { const Data& operator()(const InlineBuffer &buffer) { return buffer.data; } const Data& operator()(const ExternalBuffer&) { LOGTHROW(err1, std::runtime_error) << "External buffer is not supported (yet)."; throw; } } v; return boost::apply_visitor(v, mg.get<Buffer>(index)); } void addImage(MeshLoader &loader, const Data &data , const BufferView *bv = nullptr) { const auto begin(data.data() + (bv ? bv->byteOffset : 0)); const auto end(begin + (bv ? bv->byteLength : data.size())); loader.image(DataView(begin, end)); #if 0 ArrayBuffer ab(begin, end); std::istream is(&ab); is.exceptions(std::ios::badbit | std::ios::failbit); loader.image(is); #endif } void extractImage(MeshLoader &loader, const BufferView &bv , const Buffer &buffer) { struct ImageAttributeExtractor : public boost::static_visitor<void> { MeshLoader &loader; const BufferView &bv; ImageAttributeExtractor(MeshLoader &loader, const BufferView &bv) : loader(loader), bv(bv) {} void operator()(const InlineBuffer &buffer) { addImage(loader, buffer.data, &bv); } void operator()(const ExternalBuffer&) { LOGTHROW(err1, std::runtime_error) << "External buffer is not supported (yet)."; } } v(loader, bv); return boost::apply_visitor(v, buffer); } void extractImage(MeshLoader &loader, const ModelGetter &mg, Index index) { struct ImageExtractor : public boost::static_visitor<> { MeshLoader &loader; const ModelGetter &mg; ImageExtractor(MeshLoader &loader, const ModelGetter &mg) : loader(loader), mg(mg) {} void operator()(const InlineImage &image) { addImage(loader, image.data); } void operator()(const ExternalImage &image) { loader.image(image.uri); } void operator()(const BufferViewImage &image) { const auto &bv(mg.get<BufferView>(image.bufferView)); const auto &buffer(mg.get<Buffer>(bv.buffer)); extractImage(loader, bv, buffer); } } v(loader, mg); return boost::apply_visitor(v, mg.get<Image>(index)); } class Decoder { public: Decoder(MeshLoader &loader, const Model &model , const MeshLoader::DecodeOptions &options) : loader_(loader), options_(options), mg_(model) { trafos_.push(options_.trafo); for (const auto nodeId : mg_.getScene(options_.scene).nodes) { processNode(mg_.get<Node>(nodeId)); } } private: void processNode(const Node &node) { TrafoHolder th(trafos_, node); if (const auto *mesh = mg_.get<Mesh>(node.mesh)) { processMesh(*mesh); } for (const auto childId : node.children) { processNode(mg_.get<Node>(childId)); } } void processMesh(const Mesh &mesh) { loader_.mesh(); for (const auto &primitive : mesh.primitives) { processPrimitive(primitive); } } void processPrimitive(const Primitive &primitive) { // vertices const auto vertexCount([&]() { math::Points3d vertices; extractor<AttributeExtractor> (primitive, AttributeSemantic::position) .read([&vertices](double value, std::size_t index) mutable { if (!index) { vertices.emplace_back(); } vertices.back()(index) = value; }); math::transform(trafo(), vertices); auto size(vertices.size()); loader_.vertices(std::move(vertices)); return size; }()); // are there texture coordinates if (const auto *a = accessor(primitive, AttributeSemantic::texCoord0 , std::nothrow)) { // image extractTextureImage(primitive); math::Points2d tc; extractor<AttributeExtractor>(*a).read ([&tc](double value, std::size_t index) mutable { if (!index) { tc.emplace_back(); } tc.back()(index) = value; }); // flip texture coordinates if asked to if (options_.flipTc) { for (auto &t : tc) { t(1) = 1.0 - t(1); } } loader_.tc(std::move(tc)); } // faces if (const auto *a = mg_.get<Accessor>(primitive.indices)) { // read indices from accessor loader_.faces(faces(primitive.mode, *a)); } else { loader_.faces(faces(primitive.mode, vertexCount)); } } const Accessor& accessor(const Primitive &primitive , AttributeSemantic semantic) const { if (const auto *a = accessor(primitive, semantic, std::nothrow)) { return *a; } LOGTHROW(err1, std::runtime_error) << "Mandatory accessor for attribute " << semantic << " not found."; throw; } const Accessor* accessor(const Primitive &primitive , AttributeSemantic semantic , const std::nothrow_t&) const { if (const auto *a = mg_.get<Accessor>(primitive.attribute(semantic))) { a->validate(semantic); if (!a->bufferView) { LOGTHROW(err1, std::runtime_error) << "Accessor without buffer view is unsupported."; } return a; } return nullptr; } template <typename Extractor> Extractor extractor(const Accessor &accessor) const { // TODO: handle bufferView-less accessor if (!accessor.bufferView) { LOGTHROW(err2, std::runtime_error) << "No buffer view present in accessor."; } const auto &bv(mg_.get<BufferView>(*accessor.bufferView)); return Extractor(accessor, bv, extractData(mg_, bv.buffer)); } template <typename Extractor> Extractor extractor(const Primitive &primitive , AttributeSemantic semantic) const { return extractor<Extractor>(accessor(primitive, semantic)); } void extractTextureImage(const Primitive &primitive) const { // extract image from texture from material const auto *material(mg_.get<Material>(primitive.material)); if (!material) { LOGTHROW(err1, std::runtime_error) << "Expected material for texture coordinates."; } if (!material->pbrMetallicRoughness) { LOGTHROW(err1, std::runtime_error) << "Expected PBR metallic roughness material for " "texture coordinates."; } if (!material->pbrMetallicRoughness->baseColorTexture) { LOGTHROW(err1, std::runtime_error) << "Expected base color texture for texture coordinates."; } const auto &texture (mg_.get<Texture> (material->pbrMetallicRoughness->baseColorTexture->index)); // notify loader with image extractImage(loader_, mg_, texture.source); } MeshLoader::Faces faces(PrimitiveMode mode, const Accessor &a) const { const auto e(extractor<IndexExtractor>(a)); MeshLoader::Faces faces; switch (mode) { case PrimitiveMode::triangles: { // 3 consecutive indices form a triangle int i(0); e.read([&faces, &i](VertexIndex vi) mutable { if (!i) { faces.emplace_back(); } faces.back()[i++] = vi; i %= 3; }); } break; case PrimitiveMode::triangleStrip: // TODO: implement me case PrimitiveMode::triangleFan: // TODO: implement me default: LOGTHROW(err1, std::runtime_error) << "Only triangles are supported.."; } return faces; } MeshLoader::Faces faces(PrimitiveMode mode, std::size_t vertexCount) const { MeshLoader::Faces faces; switch (mode) { case PrimitiveMode::triangles: { // 3 consecutive indices form a triangle faces.resize(vertexCount / 3); std::size_t i(0); for (auto &face : faces) { for (int ii(0); ii < 3; ++ii, ++i) { face[ii] = i; } } } break; case PrimitiveMode::triangleStrip: // TODO: implement me case PrimitiveMode::triangleFan: // TODO: implement me default: LOGTHROW(err1, std::runtime_error) << "Only triangles are supported.."; } return faces; } const math::Matrix4& trafo() const { return trafos_.top(); } MeshLoader &loader_; const MeshLoader::DecodeOptions &options_; const ModelGetter mg_; TrafoStack trafos_; }; } // namespace void decodeMesh(MeshLoader &loader, const Model &model , const MeshLoader::DecodeOptions &options) { Decoder(loader, model, options); } void MeshLoader::image(const boost::filesystem::path&) { LOGTHROW(err2, std::logic_error) << "This gltf::MeshLoader does not support external images." ; } } // namespace gltf
State Before: α : Type u_1 β : Type u_2 inst✝ : NormedAddCommGroup β u v w : α → β l : Filter α huv : u ~[l] v ⊢ (fun x => -u x) ~[l] fun x => -v x State After: α : Type u_1 β : Type u_2 inst✝ : NormedAddCommGroup β u v w : α → β l : Filter α huv : u ~[l] v ⊢ ((fun x => -u x) - fun x => -v x) =o[l] fun x => -v x Tactic: rw [IsEquivalent] State Before: α : Type u_1 β : Type u_2 inst✝ : NormedAddCommGroup β u v w : α → β l : Filter α huv : u ~[l] v ⊢ ((fun x => -u x) - fun x => -v x) =o[l] fun x => -v x State After: case h.e'_7.h α : Type u_1 β : Type u_2 inst✝ : NormedAddCommGroup β u v w : α → β l : Filter α huv : u ~[l] v x✝ : α ⊢ ((fun x => -u x) - fun x => -v x) x✝ = -(u - v) x✝ Tactic: convert huv.isLittleO.neg_left.neg_right State Before: case h.e'_7.h α : Type u_1 β : Type u_2 inst✝ : NormedAddCommGroup β u v w : α → β l : Filter α huv : u ~[l] v x✝ : α ⊢ ((fun x => -u x) - fun x => -v x) x✝ = -(u - v) x✝ State After: no goals Tactic: simp [neg_add_eq_sub]
[STATEMENT] lemma "mono_on UNIV bool_fun_top" [PROOF STATE] proof (prove) goal (1 subgoal): 1. mono bool_fun_top [PROOF STEP] by (simp add: bool_fun_top_def mono_onI monotone_bool_fun_def)
lemma measure_eq_AE: assumes iff: "AE x in M. x \<in> A \<longleftrightarrow> x \<in> B" assumes A: "A \<in> sets M" and B: "B \<in> sets M" shows "measure M A = measure M B"
{-# OPTIONS --cubical --safe #-} module Algebra where open import Prelude module _ {a} {A : Type a} (_∙_ : A → A → A) where Associative : Type a Associative = ∀ x y z → (x ∙ y) ∙ z ≡ x ∙ (y ∙ z) Commutative : Type _ Commutative = ∀ x y → x ∙ y ≡ y ∙ x Idempotent : Type _ Idempotent = ∀ x → x ∙ x ≡ x module _ {a b} {A : Type a} {B : Type b} where Identityˡ : (A → B → B) → A → Type _ Identityˡ _∙_ x = ∀ y → x ∙ y ≡ y Zeroˡ : (A → B → A) → A → Type _ Zeroˡ _∙_ x = ∀ y → x ∙ y ≡ x Zeroʳ : (A → B → B) → B → Type _ Zeroʳ _∙_ x = ∀ y → y ∙ x ≡ x Identityʳ : (A → B → A) → B → Type _ Identityʳ _∙_ x = ∀ y → y ∙ x ≡ y _Distributesʳ_ : (A → B → B) → (B → B → B) → Type _ _⊗_ Distributesʳ _⊕_ = ∀ x y z → x ⊗ (y ⊕ z) ≡ (x ⊗ y) ⊕ (x ⊗ z) _Distributesˡ_ : (B → A → B) → (B → B → B) → Type _ _⊗_ Distributesˡ _⊕_ = ∀ x y z → (x ⊕ y) ⊗ z ≡ (x ⊗ z) ⊕ (y ⊗ z) record Semigroup ℓ : Type (ℓsuc ℓ) where infixl 6 _∙_ field 𝑆 : Type ℓ _∙_ : 𝑆 → 𝑆 → 𝑆 assoc : ∀ x y z → (x ∙ y) ∙ z ≡ x ∙ (y ∙ z) record Monoid ℓ : Type (ℓsuc ℓ) where infixl 6 _∙_ field 𝑆 : Type ℓ _∙_ : 𝑆 → 𝑆 → 𝑆 ε : 𝑆 assoc : ∀ x y z → (x ∙ y) ∙ z ≡ x ∙ (y ∙ z) ε∙ : ∀ x → ε ∙ x ≡ x ∙ε : ∀ x → x ∙ ε ≡ x semigroup : Semigroup ℓ semigroup = record { 𝑆 = 𝑆; _∙_ = _∙_; assoc = assoc } record MonoidHomomorphism_⟶_ {ℓ₁ ℓ₂} (from : Monoid ℓ₁) (to : Monoid ℓ₂) : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where open Monoid from open Monoid to renaming ( 𝑆 to 𝑅 ; _∙_ to _⊙_ ; ε to ⓔ ) field f : 𝑆 → 𝑅 ∙-homo : ∀ x y → f (x ∙ y) ≡ f x ⊙ f y ε-homo : f ε ≡ ⓔ record Group ℓ : Type (ℓsuc ℓ) where field monoid : Monoid ℓ open Monoid monoid public field inv : 𝑆 → 𝑆 ∙⁻ : ∀ x → x ∙ inv x ≡ ε ⁻∙ : ∀ x → inv x ∙ x ≡ ε record CommutativeMonoid ℓ : Type (ℓsuc ℓ) where field monoid : Monoid ℓ open Monoid monoid public field comm : Commutative _∙_ record Semilattice ℓ : Type (ℓsuc ℓ) where field commutativeMonoid : CommutativeMonoid ℓ open CommutativeMonoid commutativeMonoid public field idem : Idempotent _∙_ record NearSemiring ℓ : Type (ℓsuc ℓ) where infixl 6 _+_ infixl 7 _*_ field 𝑅 : Type ℓ _+_ : 𝑅 → 𝑅 → 𝑅 _*_ : 𝑅 → 𝑅 → 𝑅 1# : 𝑅 0# : 𝑅 +-assoc : Associative _+_ *-assoc : Associative _*_ 0+ : Identityˡ _+_ 0# +0 : Identityʳ _+_ 0# 1* : Identityˡ _*_ 1# *1 : Identityʳ _*_ 1# 0* : Zeroˡ _*_ 0# ⟨+⟩* : _*_ Distributesˡ _+_ record Semiring ℓ : Type (ℓsuc ℓ) where field nearSemiring : NearSemiring ℓ open NearSemiring nearSemiring public field +-comm : Commutative _+_ *0 : Zeroʳ _*_ 0# *⟨+⟩ : _*_ Distributesʳ _+_ record IdempotentSemiring ℓ : Type (ℓsuc ℓ) where field semiring : Semiring ℓ open Semiring semiring public field +-idem : Idempotent _+_ record CommutativeSemiring ℓ : Type (ℓsuc ℓ) where field semiring : Semiring ℓ open Semiring semiring public field *-comm : Commutative _*_ record LeftSemimodule ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field semiring : Semiring ℓ₁ open Semiring semiring public field semimodule : CommutativeMonoid ℓ₂ open CommutativeMonoid semimodule renaming (_∙_ to _∪_) public renaming (𝑆 to 𝑉 ; assoc to ∪-assoc ; ε∙ to ∅∪ ; ∙ε to ∪∅ ; ε to ∅ ) infixr 7 _⋊_ field _⋊_ : 𝑅 → 𝑉 → 𝑉 ⟨*⟩⋊ : ∀ x y z → (x * y) ⋊ z ≡ x ⋊ (y ⋊ z) ⟨+⟩⋊ : ∀ x y z → (x + y) ⋊ z ≡ (x ⋊ z) ∪ (y ⋊ z) ⋊⟨∪⟩ : _⋊_ Distributesʳ _∪_ 1⋊ : Identityˡ _⋊_ 1# 0⋊ : ∀ x → 0# ⋊ x ≡ ∅ record StarSemiring ℓ : Type (ℓsuc ℓ) where field semiring : Semiring ℓ open Semiring semiring public field _⋆ : 𝑅 → 𝑅 star-iterʳ : ∀ x → x ⋆ ≡ 1# + x * x ⋆ star-iterˡ : ∀ x → x ⋆ ≡ 1# + x ⋆ * x _⁺ : 𝑅 → 𝑅 x ⁺ = x * x ⋆ record Functor ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field 𝐹 : Type ℓ₁ → Type ℓ₂ map : (A → B) → 𝐹 A → 𝐹 B map-id : map (id {ℓ₁} {A}) ≡ id map-comp : (f : B → C) → (g : A → B) → map (f ∘ g) ≡ map f ∘ map g record Applicative ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field functor : Functor ℓ₁ ℓ₂ open Functor functor public infixl 5 _<*>_ field pure : A → 𝐹 A _<*>_ : 𝐹 (A → B) → 𝐹 A → 𝐹 B map-ap : (f : A → B) → map f ≡ pure f <*>_ pure-homo : (f : A → B) → (x : A) → map f (pure x) ≡ pure (f x) <*>-interchange : (u : 𝐹 (A → B)) → (y : A) → u <*> pure y ≡ map (_$ y) u <*>-comp : (u : 𝐹 (B → C)) → (v : 𝐹 (A → B)) → (w : 𝐹 A) → pure _∘′_ <*> u <*> v <*> w ≡ u <*> (v <*> w) record Monad ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field applicative : Applicative ℓ₁ ℓ₂ open Applicative applicative public infixl 1 _>>=_ field _>>=_ : 𝐹 A → (A → 𝐹 B) → 𝐹 B >>=-idˡ : (f : A → 𝐹 B) → (x : A) → (pure x >>= f) ≡ f x >>=-idʳ : (x : 𝐹 A) → (x >>= pure) ≡ x >>=-assoc : (xs : 𝐹 A) (f : A → 𝐹 B) (g : B → 𝐹 C) → ((xs >>= f) >>= g) ≡ (xs >>= (λ x → f x >>= g)) return : A → 𝐹 A return = pure record Alternative ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field applicative : Applicative ℓ₁ ℓ₂ open Applicative applicative public field 0# : 𝐹 A _<|>_ : 𝐹 A → 𝐹 A → 𝐹 A <|>-idˡ : (x : 𝐹 A) → 0# <|> x ≡ x <|>-idʳ : (x : 𝐹 A) → x <|> 0# ≡ x 0-annˡ : (x : 𝐹 A) → 0# <*> x ≡ 0# {B} <|>-distrib : (x y : 𝐹 (A → B)) → (z : 𝐹 A) → (x <|> y) <*> z ≡ (x <*> z) <|> (y <*> z) record MonadPlus ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field monad : Monad ℓ₁ ℓ₂ open Monad monad public field 0# : 𝐹 A _<|>_ : 𝐹 A → 𝐹 A → 𝐹 A <|>-idˡ : (x : 𝐹 A) → 0# <|> x ≡ x <|>-idʳ : (x : 𝐹 A) → x <|> 0# ≡ x 0-annˡ : (x : A → 𝐹 B) → (0# >>= x) ≡ 0# <|>-distrib : (x y : 𝐹 A) → (z : A → 𝐹 B) → ((x <|> y) >>= z) ≡ (x >>= z) <|> (y >>= z) Endo : Type a → Type a Endo A = A → A endoMonoid : ∀ {a} → Type a → Monoid a endoMonoid A .Monoid.𝑆 = Endo A endoMonoid A .Monoid.ε x = x endoMonoid A .Monoid._∙_ f g x = f (g x) endoMonoid A .Monoid.assoc _ _ _ = refl endoMonoid A .Monoid.ε∙ _ = refl endoMonoid A .Monoid.∙ε _ = refl record Foldable ℓ₁ ℓ₂ : Type (ℓsuc (ℓ₁ ℓ⊔ ℓ₂)) where field 𝐹 : Type ℓ₁ → Type ℓ₂ open Monoid ⦃ ... ⦄ field foldMap : {A : Type ℓ₁} ⦃ _ : Monoid ℓ₁ ⦄ → (A → 𝑆) → 𝐹 A → 𝑆 foldr : {A B : Type ℓ₁} → (A → B → B) → B → 𝐹 A → B foldr f b xs = foldMap ⦃ endoMonoid _ ⦄ f xs b
[STATEMENT] lemma firstPosDomainForElements: shows "(0 \<le> firstPos a l \<and> firstPos a l < length l) = (a \<in> set l)" (is "?lhs = ?rhs") [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0 \<le> firstPos a l \<and> firstPos a l < length l) = (a \<in> set l) [PROOF STEP] by (induct l) auto
using Plots,FFTW,JLD2 function sqaure_windowing_signal(signal::Array{Float64}) windowed_signal = signal window_correction_factor = 1 return (windowed_signal,window_correction_factor) end function hanning_windowing_signal(signal::Array{Float64}) windowed_signal::Array{Float64} = [] window::Array{Float64} = [] total_window_power = 0 j = 1 for w = signal window_val = 0.5*(1 - cos(2*pi*j/length(signal))) push!(window,window_val) windowed = window_val*w push!(windowed_signal, windowed) total_window_power += window_val j += 1 end window_correction_factor = length(signal)/total_window_power return (windowed_signal,window_correction_factor) end function main() sampling_rate = 0 window_size = 64*1024*1024 w_fm_vals::Array{Float64} = [] jldopen(ARGS[1],"r") do f sampling_rate = f["samplingrate"] w_fm_vals = f["w_fm"] end (windowed_signal, window_correction_factor) = sqaure_windowing_signal(w_fm_vals[1:window_size]) powers = map(x->20*log10(abs(x)*window_correction_factor),fft(windowed_signal)|>fftshift) freqs = fftfreq( window_size, sampling_rate )|>fftshift println(freqs) plot_graph=plot(freqs, powers, size=(2000,700), fmt =:png) savefig(plot_graph, "fm_fft1.png") plot_graph=plot(freqs, powers, xlims=(7.6*10^6, 8.0*10^6), size=(2000,700), fmt =:png) savefig(plot_graph, "fm_fft2.png") end main()
using BeaconK8sUtilities using Test, Logging, JSON3, Dates function capture_logs(f) io = IOBuffer() Logging.with_logger(f, json_logger(; io)) return JSON3.read(take!(io), Dict) end struct TestObj1 f::Any end struct TestObj2 f::Any end BeaconK8sUtilities.jsonable(obj::TestObj1) = (; obj.f) @testset "BeaconK8sUtilities.jl" begin @testset "setup_tensorboard" begin testdir = mktempdir() test_args = (; app="test-app", logdir="test-logdir", ecr="test-ecr", service_account="test-service-account", namespace="test-namespace") @test setup_tensorboard(testdir; test_args...) === nothing # Check we at least get the right files @test Set(readdir(testdir)) == Set(["tensorboard.dockerfile", "tensorboard.sh", "tensorboard.yaml"]) # No `overwrite=true` @test_throws ErrorException setup_tensorboard(testdir; test_args...) # Works with `overwrite=true` @test setup_tensorboard(testdir; test_args..., overwrite=true) === nothing @test Set(readdir(testdir)) == Set(["tensorboard.dockerfile", "tensorboard.sh", "tensorboard.yaml"]) end @testset "setup_follow" begin testdir = mktempdir() test_args = (; namespace="test-namespace") @test setup_follow(testdir; test_args...) === nothing # Check we at least get the right files @test readdir(testdir) == ["follow.sh"] # No `overwrite=true` @test_throws ErrorException setup_follow(testdir; test_args...) # Works with `overwrite=true` @test setup_follow(testdir; test_args..., overwrite=true) === nothing @test readdir(testdir) == ["follow.sh"] end @testset "json_logger" begin logs = capture_logs() do @info "Hi" x = Dict("a" => Dict("b" => 2)) end @test logs["msg"] == "Hi" @test logs["kwargs"]["x"] == Dict("a" => Dict("b" => 2)) @test logs["kwargs"]["worker_id"] == 1 @test parse(DateTime, logs["kwargs"]["timestamp"], dateformat"yyyy-mm-dd HH:MM:SS") isa DateTime logs = capture_logs() do @info "Hi" x = TestObj1("a") end @test logs["kwargs"]["x"] == Dict("f" => "a") logs = capture_logs() do @info "Hi" x = TestObj2("a") end @test logs["kwargs"]["x"] == "TestObj2(\"a\")" @test logs["kwargs"]["LoggingFormats.FormatError"] == "ArgumentError: TestObj2 doesn't have a defined `StructTypes.StructType`" # test `maxlog` f() = @info "hi" maxlog = 1 io = IOBuffer() Logging.with_logger(json_logger(; io)) do f() return f() end logs = String(take!(io)) lines = split(logs, '\n') @test length(lines) == 2 @test lines[2] == "" @test JSON3.read(lines[1])["msg"] == "hi" end end
[STATEMENT] lemma hsi_method_via_spy_framework_code[code] : "hsi_method_via_spy_framework M m = (let tables = (compute_ofsm_tables M (size M - 1)); distMap = mapping_of (map (\<lambda> (q1,q2) . ((q1,q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda> qq . fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = (\<lambda> q1 q2 . if q1 \<in> states M \<and> q2 \<in> states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1,q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2); hsiMap = mapping_of (map (\<lambda> q . (q,from_list (map (\<lambda>q' . distHelper q q') (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = (\<lambda> k q . if q \<in> states M then the (Mapping.lookup hsiMap q) else get_HSI M q) in spy_framework_static_with_empty_graph M distFun m)" (is "?f1 = ?f2") [PROOF STATE] proof (prove) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] define hsiMap' where "hsiMap' = mapping_of (map (\<lambda> q . (q,from_list (map (\<lambda>q' . get_distinguishing_sequence_from_ofsm_tables M q q') (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))" [PROOF STATE] proof (state) this: hsiMap' = mapping_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] define distFun' where "distFun' = (\<lambda> M q . if q \<in> states M then the (Mapping.lookup hsiMap' q) else get_HSI M q)" [PROOF STATE] proof (state) this: distFun' = (\<lambda>M q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap' q) else get_HSI M q) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] have *: "?f2 = spy_framework_static_with_empty_graph M (\<lambda> k q . distFun' M q) m" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) = spy_framework_static_with_empty_graph M (\<lambda>k. distFun' M) m [PROOF STEP] unfolding distFun'_def hsiMap'_def Let_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (\<lambda>q2. if q \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q \<noteq> q2 then the (Mapping.lookup (mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables (compute_ofsm_tables M (FSM.size M - 1)) M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M))))) (q, q2)) else get_distinguishing_sequence_from_ofsm_tables M q q2) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m = spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m [PROOF STEP] apply (subst (2) get_distinguishing_sequence_from_ofsm_tables_precomputed[of M]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (\<lambda>q2. if q \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q \<noteq> q2 then the (Mapping.lookup (mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables (compute_ofsm_tables M (FSM.size M - 1)) M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M))))) (q, q2)) else get_distinguishing_sequence_from_ofsm_tables M q q2) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m = spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map ((let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2 in distHelper) q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m [PROOF STEP] unfolding Let_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (\<lambda>q2. if q \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q \<noteq> q2 then the (Mapping.lookup (mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables (compute_ofsm_tables M (FSM.size M - 1)) M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M))))) (q, q2)) else get_distinguishing_sequence_from_ofsm_tables M q q2) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m = spy_framework_static_with_empty_graph M (\<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (\<lambda>q2. if q \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q \<noteq> q2 then the (Mapping.lookup (mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables (compute_ofsm_tables M (FSM.size M - 1)) M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M))))) (q, q2)) else get_distinguishing_sequence_from_ofsm_tables M q q2) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) q) else get_HSI M q) m [PROOF STEP] by presburger [PROOF STATE] proof (state) this: (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) = spy_framework_static_with_empty_graph M (\<lambda>k. distFun' M) m goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] define hsiMap where "hsiMap = map_of (map (\<lambda> q . (q,from_list (map (\<lambda>q' . get_distinguishing_sequence_from_ofsm_tables M q q') (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))" [PROOF STATE] proof (state) this: hsiMap = map_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] define distFun where "distFun = (\<lambda> M q . if q \<in> states M then the (hsiMap q) else get_HSI M q)" [PROOF STATE] proof (state) this: distFun = (\<lambda>M q. if q \<in> FSM.states M then the (hsiMap q) else get_HSI M q) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] have "distinct (map fst (map (\<lambda> q . (q,from_list (map (\<lambda>q' . get_distinguishing_sequence_from_ofsm_tables M q q') (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) [PROOF STEP] using states_as_list_distinct [PROOF STATE] proof (prove) using this: distinct (states_as_list ?M) goal (1 subgoal): 1. distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) [PROOF STEP] by (metis map_pair_fst) [PROOF STATE] proof (state) this: distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) [PROOF STEP] have "Mapping.lookup hsiMap' = hsiMap" [PROOF STATE] proof (prove) using this: distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) goal (1 subgoal): 1. Mapping.lookup hsiMap' = hsiMap [PROOF STEP] unfolding hsiMap_def hsiMap'_def [PROOF STATE] proof (prove) using this: distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) goal (1 subgoal): 1. Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) = map_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)) [PROOF STEP] using mapping_of_map_of [PROOF STATE] proof (prove) using this: distinct (map fst (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) distinct (map fst ?kvs) \<Longrightarrow> Mapping.lookup (mapping_of ?kvs) = map_of ?kvs goal (1 subgoal): 1. Mapping.lookup (mapping_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M))) = map_of (map (\<lambda>q. (q, from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Mapping.lookup hsiMap' = hsiMap goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: Mapping.lookup hsiMap' = hsiMap [PROOF STEP] have "distFun' = distFun" [PROOF STATE] proof (prove) using this: Mapping.lookup hsiMap' = hsiMap goal (1 subgoal): 1. distFun' = distFun [PROOF STEP] unfolding distFun_def distFun'_def [PROOF STATE] proof (prove) using this: Mapping.lookup hsiMap' = hsiMap goal (1 subgoal): 1. (\<lambda>M q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap' q) else get_HSI M q) = (\<lambda>M q. if q \<in> FSM.states M then the (hsiMap q) else get_HSI M q) [PROOF STEP] by meson [PROOF STATE] proof (state) this: distFun' = distFun goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] have **:"distFun M = get_HSI M" [PROOF STATE] proof (prove) goal (1 subgoal): 1. distFun M = get_HSI M [PROOF STEP] proof [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. distFun M x = get_HSI M x [PROOF STEP] fix q [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. distFun M x = get_HSI M x [PROOF STEP] show "distFun M q = get_HSI M q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. distFun M q = get_HSI M q [PROOF STEP] proof (cases "q \<in> states M") [PROOF STATE] proof (state) goal (2 subgoals): 1. q \<in> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q 2. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] case True [PROOF STATE] proof (state) this: q \<in> FSM.states M goal (2 subgoals): 1. q \<in> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q 2. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] then [PROOF STATE] proof (chain) picking this: q \<in> FSM.states M [PROOF STEP] have "q \<in> list.set (states_as_list M)" [PROOF STATE] proof (prove) using this: q \<in> FSM.states M goal (1 subgoal): 1. q \<in> list.set (states_as_list M) [PROOF STEP] using states_as_list_set [PROOF STATE] proof (prove) using this: q \<in> FSM.states M list.set (states_as_list ?M) = FSM.states ?M goal (1 subgoal): 1. q \<in> list.set (states_as_list M) [PROOF STEP] by blast [PROOF STATE] proof (state) this: q \<in> list.set (states_as_list M) goal (2 subgoals): 1. q \<in> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q 2. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] then [PROOF STATE] proof (chain) picking this: q \<in> list.set (states_as_list M) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: q \<in> list.set (states_as_list M) goal (1 subgoal): 1. distFun M q = get_HSI M q [PROOF STEP] unfolding distFun_def hsiMap_def map_of_map_pair_entry get_HSI.simps [PROOF STATE] proof (prove) using this: q \<in> list.set (states_as_list M) goal (1 subgoal): 1. (if q \<in> FSM.states M then the (if q \<in> list.set (states_as_list M) then Some (from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M)))) else None) else from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M)))) = from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))) [PROOF STEP] using True [PROOF STATE] proof (prove) using this: q \<in> list.set (states_as_list M) q \<in> FSM.states M goal (1 subgoal): 1. (if q \<in> FSM.states M then the (if q \<in> list.set (states_as_list M) then Some (from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M)))) else None) else from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M)))) = from_list (map (get_distinguishing_sequence_from_ofsm_tables M q) (filter ((\<noteq>) q) (states_as_list M))) [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: distFun M q = get_HSI M q goal (1 subgoal): 1. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] case False [PROOF STATE] proof (state) this: q \<notin> FSM.states M goal (1 subgoal): 1. q \<notin> FSM.states M \<Longrightarrow> distFun M q = get_HSI M q [PROOF STEP] then [PROOF STATE] proof (chain) picking this: q \<notin> FSM.states M [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: q \<notin> FSM.states M goal (1 subgoal): 1. distFun M q = get_HSI M q [PROOF STEP] using distFun_def [PROOF STATE] proof (prove) using this: q \<notin> FSM.states M distFun = (\<lambda>M q. if q \<in> FSM.states M then the (hsiMap q) else get_HSI M q) goal (1 subgoal): 1. distFun M q = get_HSI M q [PROOF STEP] by auto [PROOF STATE] proof (state) this: distFun M q = get_HSI M q goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: distFun M q = get_HSI M q goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: distFun M = get_HSI M goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) [PROOF STEP] unfolding * ** \<open>distFun' = distFun\<close> hsi_method_via_spy_framework_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. spy_framework_static_with_empty_graph M (\<lambda>k. get_HSI M) m = spy_framework_static_with_empty_graph M (\<lambda>k. get_HSI M) m [PROOF STEP] by simp [PROOF STATE] proof (state) this: hsi_method_via_spy_framework M m = (let tables = compute_ofsm_tables M (FSM.size M - 1); distMap = mapping_of (map (\<lambda>(q1, q2). ((q1, q2), get_distinguishing_sequence_from_ofsm_tables_with_provided_tables tables M q1 q2)) (filter (\<lambda>qq. fst qq \<noteq> snd qq) (List.product (states_as_list M) (states_as_list M)))); distHelper = \<lambda>q1 q2. if q1 \<in> FSM.states M \<and> q2 \<in> FSM.states M \<and> q1 \<noteq> q2 then the (Mapping.lookup distMap (q1, q2)) else get_distinguishing_sequence_from_ofsm_tables M q1 q2; hsiMap = mapping_of (map (\<lambda>q. (q, from_list (map (distHelper q) (filter ((\<noteq>) q) (states_as_list M))))) (states_as_list M)); distFun = \<lambda>k q. if q \<in> FSM.states M then the (Mapping.lookup hsiMap q) else get_HSI M q in spy_framework_static_with_empty_graph M distFun m) goal: No subgoals! [PROOF STEP] qed
(* *********************************************************************) (* *) (* 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 whole compiler and its proof of semantic preservation *) (** Libraries. *) Require Import String. Require Import Coqlib. Require Import Errors. Require Import AST. Require Import Smallstep. (** Languages (syntax and semantics). *) Require Csyntax. Require Csem. Require Cstrategy. Require Cexec. Require Clight. Require Csharpminor. Require Cminor. Require CminorSel. Require RTL. Require LTL. Require Linear. Require Mach. Require Asm. (** Translation passes. *) Require Initializers. Require SimplExpr. Require SimplLocals. Require Cshmgen. Require Cminorgen. Require Selection. Require RTLgen. Require Tailcall. Require Inlining. Require Renumber. Require Constprop. Require CSE. Require Deadcode. Require Unusedglob. Require Allocation. Require Tunneling. Require Linearize. Require CleanupLabels. Require Stacking. Require Asmgen. (** Proofs of semantic preservation. *) Require SimplExprproof. Require SimplLocalsproof. Require Cshmgenproof. Require Cminorgenproof. Require Selectionproof. Require RTLgenproof. Require Tailcallproof. Require Inliningproof. Require Renumberproof. Require Constpropproof. Require CSEproof. Require Deadcodeproof. Require Unusedglobproof. Require Allocproof. Require Tunnelingproof. Require Linearizeproof. Require CleanupLabelsproof. Require Stackingproof. Require Asmgenproof. (** Command-line flags. *) Require Import Compopts. (** Pretty-printers (defined in Caml). *) Parameter print_Clight: Clight.program -> unit. Parameter print_Cminor: Cminor.program -> unit. Parameter print_RTL: Z -> RTL.program -> unit. Parameter print_LTL: LTL.program -> unit. Parameter print_Mach: Mach.program -> unit. Open Local Scope string_scope. (** * Composing the translation passes *) (** We first define useful monadic composition operators, along with funny (but convenient) notations. *) Definition apply_total (A B: Type) (x: res A) (f: A -> B) : res B := match x with Error msg => Error msg | OK x1 => OK (f x1) end. Definition apply_partial (A B: Type) (x: res A) (f: A -> res B) : res B := match x with Error msg => Error msg | OK x1 => f x1 end. Notation "a @@@ b" := (apply_partial _ _ a b) (at level 50, left associativity). Notation "a @@ b" := (apply_total _ _ a b) (at level 50, left associativity). Definition print {A: Type} (printer: A -> unit) (prog: A) : A := let unused := printer prog in prog. Definition time {A B: Type} (name: string) (f: A -> B) : A -> B := f. Definition total_if {A: Type} (flag: unit -> bool) (f: A -> A) (prog: A) : A := if flag tt then f prog else prog. Definition partial_if {A: Type} (flag: unit -> bool) (f: A -> res A) (prog: A) : res A := if flag tt then f prog else OK prog. (** We define three translation functions for whole programs: one starting with a C program, one with a Cminor program, one with an RTL program. The three translations produce Asm programs ready for pretty-printing and assembling. *) Definition transf_rtl_program (f: RTL.program) : res Asm.program := OK f @@ print (print_RTL 0) @@ total_if Compopts.optim_tailcalls (time "Tail calls" Tailcall.transf_program) @@ print (print_RTL 1) @@@ time "Inlining" Inlining.transf_program @@ print (print_RTL 2) @@ time "Renumbering" Renumber.transf_program @@ print (print_RTL 3) @@ total_if Compopts.optim_constprop (time "Constant propagation" Constprop.transf_program) @@ print (print_RTL 4) @@ total_if Compopts.optim_constprop (time "Renumbering" Renumber.transf_program) @@ print (print_RTL 5) @@@ partial_if Compopts.optim_CSE (time "CSE" CSE.transf_program) @@ print (print_RTL 6) @@@ partial_if Compopts.optim_redundancy (time "Redundancy elimination" Deadcode.transf_program) @@ print (print_RTL 7) @@@ time "Unused globals" Unusedglob.transform_program @@ print (print_RTL 8) @@@ time "Register allocation" Allocation.transf_program @@ print print_LTL @@ time "Branch tunneling" Tunneling.tunnel_program @@@ time "CFG linearization" Linearize.transf_program @@ time "Label cleanup" CleanupLabels.transf_program @@@ time "Mach generation" Stacking.transf_program @@ print print_Mach @@@ time "Asm generation" Asmgen.transf_program. Definition transf_cminor_program (p: Cminor.program) : res Asm.program := OK p @@ print print_Cminor @@@ time "Instruction selection" Selection.sel_program @@@ time "RTL generation" RTLgen.transl_program @@@ transf_rtl_program. Definition transf_clight_program (p: Clight.program) : res Asm.program := OK p @@ print print_Clight @@@ time "Simplification of locals" SimplLocals.transf_program @@@ time "C#minor generation" Cshmgen.transl_program @@@ time "Cminor generation" Cminorgen.transl_program @@@ transf_cminor_program. Definition transf_c_program (p: Csyntax.program) : res Asm.program := OK p @@@ time "Clight generation" SimplExpr.transl_program @@@ transf_clight_program. (** Force [Initializers] and [Cexec] to be extracted as well. *) Definition transl_init := Initializers.transl_init. Definition cexec_do_step := Cexec.do_step. (** The following lemmas help reason over compositions of passes. *) Lemma print_identity: forall (A: Type) (printer: A -> unit) (prog: A), print printer prog = prog. Proof. intros; unfold print. destruct (printer prog); auto. Qed. Lemma compose_print_identity: forall (A: Type) (x: res A) (f: A -> unit), x @@ print f = x. Proof. intros. destruct x; simpl. rewrite print_identity. auto. auto. Qed. Remark forward_simulation_identity: forall sem, forward_simulation sem sem. Proof. intros. apply forward_simulation_step with (fun s1 s2 => s2 = s1); intros. - auto. - exists s1; auto. - subst s2; auto. - subst s2. exists s1'; auto. Qed. Lemma total_if_simulation: forall (A: Type) (sem: A -> semantics) (flag: unit -> bool) (f: A -> A) (prog: A), (forall p, forward_simulation (sem p) (sem (f p))) -> forward_simulation (sem prog) (sem (total_if flag f prog)). Proof. intros. unfold total_if. destruct (flag tt). auto. apply forward_simulation_identity. Qed. Lemma partial_if_simulation: forall (A: Type) (sem: A -> semantics) (flag: unit -> bool) (f: A -> res A) (prog tprog: A), partial_if flag f prog = OK tprog -> (forall p tp, f p = OK tp -> forward_simulation (sem p) (sem tp)) -> forward_simulation (sem prog) (sem tprog). Proof. intros. unfold partial_if in *. destruct (flag tt). eauto. inv H. apply forward_simulation_identity. Qed. (** * Semantic preservation *) (** We prove that the [transf_program] translations preserve semantics by constructing the following simulations: - Forward simulations from [Cstrategy] / [Cminor] / [RTL] to [Asm] (composition of the forward simulations for each pass). - Backward simulations for the same languages (derived from the forward simulation, using receptiveness of the source language and determinacy of [Asm]). - Backward simulation from [Csem] to [Asm] (composition of two backward simulations). These results establish the correctness of the whole compiler! *) Theorem transf_rtl_program_correct: forall p tp, transf_rtl_program p = OK tp -> forward_simulation (RTL.semantics p) (Asm.semantics tp) * backward_simulation (RTL.semantics p) (Asm.semantics tp). Proof. intros. assert (F: forward_simulation (RTL.semantics p) (Asm.semantics tp)). unfold transf_rtl_program, time in H. repeat rewrite compose_print_identity in H. simpl in H. set (p1 := total_if optim_tailcalls Tailcall.transf_program p) in *. destruct (Inlining.transf_program p1) as [p11|] eqn:?; simpl in H; try discriminate. set (p12 := Renumber.transf_program p11) in *. set (p2 := total_if optim_constprop Constprop.transf_program p12) in *. set (p21 := total_if optim_constprop Renumber.transf_program p2) in *. destruct (partial_if optim_CSE CSE.transf_program p21) as [p3|] eqn:?; simpl in H; try discriminate. destruct (partial_if optim_redundancy Deadcode.transf_program p3) as [p31|] eqn:?; simpl in H; try discriminate. destruct (Unusedglob.transform_program p31) as [p32|] eqn:?; simpl in H; try discriminate. destruct (Allocation.transf_program p32) as [p4|] eqn:?; simpl in H; try discriminate. set (p5 := Tunneling.tunnel_program p4) in *. destruct (Linearize.transf_program p5) as [p6|] eqn:?; simpl in H; try discriminate. set (p7 := CleanupLabels.transf_program p6) in *. destruct (Stacking.transf_program p7) as [p8|] eqn:?; simpl in H; try discriminate. apply compose_forward_simulation with (RTL.semantics p1). apply total_if_simulation. apply Tailcallproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p11). apply Inliningproof.transf_program_correct; auto. apply compose_forward_simulation with (RTL.semantics p12). apply Renumberproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p2). apply total_if_simulation. apply Constpropproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p21). apply total_if_simulation. apply Renumberproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p3). eapply partial_if_simulation; eauto. apply CSEproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p31). eapply partial_if_simulation; eauto. apply Deadcodeproof.transf_program_correct. apply compose_forward_simulation with (RTL.semantics p32). apply Unusedglobproof.transf_program_correct; auto. apply compose_forward_simulation with (LTL.semantics p4). apply Allocproof.transf_program_correct; auto. apply compose_forward_simulation with (LTL.semantics p5). apply Tunnelingproof.transf_program_correct. apply compose_forward_simulation with (Linear.semantics p6). apply Linearizeproof.transf_program_correct; auto. apply compose_forward_simulation with (Linear.semantics p7). apply CleanupLabelsproof.transf_program_correct. apply compose_forward_simulation with (Mach.semantics Asmgenproof0.return_address_offset p8). apply Stackingproof.transf_program_correct. exact Asmgenproof.return_address_exists. auto. apply Asmgenproof.transf_program_correct; eauto. split. auto. apply forward_to_backward_simulation. auto. apply RTL.semantics_receptive. apply Asm.semantics_determinate. Qed. Theorem transf_cminor_program_correct: forall p tp, transf_cminor_program p = OK tp -> forward_simulation (Cminor.semantics p) (Asm.semantics tp) * backward_simulation (Cminor.semantics p) (Asm.semantics tp). Proof. intros. assert (F: forward_simulation (Cminor.semantics p) (Asm.semantics tp)). unfold transf_cminor_program, time in H. repeat rewrite compose_print_identity in H. simpl in H. destruct (Selection.sel_program p) as [p1|] eqn:?; simpl in H; try discriminate. destruct (RTLgen.transl_program p1) as [p2|] eqn:?; simpl in H; try discriminate. eapply compose_forward_simulation. apply Selectionproof.transf_program_correct. eauto. eapply compose_forward_simulation. apply RTLgenproof.transf_program_correct. eassumption. exact (fst (transf_rtl_program_correct _ _ H)). split. auto. apply forward_to_backward_simulation. auto. apply Cminor.semantics_receptive. apply Asm.semantics_determinate. Qed. Theorem transf_clight_program_correct: forall p tp, transf_clight_program p = OK tp -> forward_simulation (Clight.semantics1 p) (Asm.semantics tp) * backward_simulation (Clight.semantics1 p) (Asm.semantics tp). Proof. intros. assert (F: forward_simulation (Clight.semantics1 p) (Asm.semantics tp)). revert H; unfold transf_clight_program, time; simpl. rewrite print_identity. caseEq (SimplLocals.transf_program p); simpl; try congruence; intros p0 EQ0. caseEq (Cshmgen.transl_program p0); simpl; try congruence; intros p1 EQ1. caseEq (Cminorgen.transl_program p1); simpl; try congruence; intros p2 EQ2. intros EQ3. eapply compose_forward_simulation. apply SimplLocalsproof.transf_program_correct. eauto. eapply compose_forward_simulation. apply Cshmgenproof.transl_program_correct. eauto. eapply compose_forward_simulation. apply Cminorgenproof.transl_program_correct. eauto. exact (fst (transf_cminor_program_correct _ _ EQ3)). split. auto. apply forward_to_backward_simulation. auto. apply Clight.semantics_receptive. apply Asm.semantics_determinate. Qed. Theorem transf_cstrategy_program_correct: forall p tp, transf_c_program p = OK tp -> forward_simulation (Cstrategy.semantics p) (Asm.semantics tp) * backward_simulation (atomic (Cstrategy.semantics p)) (Asm.semantics tp). Proof. intros. assert (F: forward_simulation (Cstrategy.semantics p) (Asm.semantics tp)). revert H; unfold transf_c_program, time; simpl. caseEq (SimplExpr.transl_program p); simpl; try congruence; intros p0 EQ0. intros EQ1. eapply compose_forward_simulation. apply SimplExprproof.transl_program_correct. eauto. exact (fst (transf_clight_program_correct _ _ EQ1)). split. auto. apply forward_to_backward_simulation. apply factor_forward_simulation. auto. eapply sd_traces. eapply Asm.semantics_determinate. apply atomic_receptive. apply Cstrategy.semantics_strongly_receptive. apply Asm.semantics_determinate. Qed. Theorem transf_c_program_correct: forall p tp, transf_c_program p = OK tp -> backward_simulation (Csem.semantics p) (Asm.semantics tp). Proof. intros. apply compose_backward_simulation with (atomic (Cstrategy.semantics p)). eapply sd_traces; eapply Asm.semantics_determinate. apply factor_backward_simulation. apply Cstrategy.strategy_simulation. apply Csem.semantics_single_events. eapply ssr_well_behaved; eapply Cstrategy.semantics_strongly_receptive. exact (snd (transf_cstrategy_program_correct _ _ H)). Qed.
Require Import Crypto.Specific.Framework.RawCurveParameters. Require Import Crypto.Util.LetIn. (*** Modulus : 2^321 - 9 Base: 26.75 ***) Definition curve : CurveParameters := {| sz := 12%nat; base := 26 + 3/4; bitwidth := 32; s := 2^321; c := [(1, 9)]; carry_chains := Some [seq 0 (pred 12); [0; 1]]%nat; a24 := None; coef_div_modulus := Some 2%nat; goldilocks := None; karatsuba := None; montgomery := false; freeze := Some true; ladderstep := false; mul_code := None; square_code := None; upper_bound_of_exponent_loose := None; upper_bound_of_exponent_tight := None; allowable_bit_widths := None; freeze_extra_allowable_bit_widths := None; modinv_fuel := None |}. Ltac extra_prove_mul_eq _ := idtac. Ltac extra_prove_square_eq _ := idtac.
cache_path <- system.file("extdata/data/", package = "Stonkalysis") cache_date_table <- reactiveValues(cache_date_table = data.frame()) av_tickers <- reactiveValues(av_tickers = list.files(cache_path, recursive = FALSE, full.names=FALSE)) ticker_choice <- reactiveValues(ticker_choice = readTickers(cache_path)) update_table <- function() { showModal(modalDialog(title = "Updating table...", easyClose = FALSE, footer = NULL)) cache_date <- data.frame() for(t in av_tickers$av_tickers) { p <- readRDS(file=paste(cache_path, t, "/profile.Rds",sep="")) p <- p$companyName d <- readRDS(file=paste(cache_path, t, "/cache_date.Rds",sep="")) cache_date <- rbind(cache_date, c(t, p, d)) } colnames(cache_date) <- c("Ticker","Company Name", "Cache Date") cache_date_table$cache_date_table <- cache_date removeModal() } observeEvent(TRUE, { update_table() }) output$api_key <- renderUI({ textInput(inputId = "api_key", "", value=apikey) }) observeEvent(input$update_available_tickers, { showModal(modalDialog(title = "Updating available tickers from API....", easyClose = FALSE, footer = NULL)) ticker_choice$ticker_choice <- updateTickers(cache_path, APIURL, apikey) removeModal() }) observeEvent(input$add_key, { if(input$api_key != apikey) { writeLines(input$api_key, con = system.file("Stonkalysis/server", 'apikey', package = "Stonkalysis")) apikey <<- input$api_key } }) output$cache_table <- DT::renderDataTable ({ DT::datatable(cache_date_table$cache_date_table, options = list(lengthMenu = c(5,10,15,20,25,30), pageLength = 10), rowname = FALSE) }) output$available_tickers <- renderUI({ av_tickers$av_tickers <- list.files(cache_path, recursive = FALSE, full.names=FALSE) for(t in av_tickers$av_tickers) { ticker_choice$ticker_choice <- ticker_choice$ticker_choice[ticker_choice$ticker_choice != t] } selectizeInput(inputId = "add_ticker", label = "", choices = c(ticker_choice$ticker_choice), multiple = TRUE) }) output$delete_tickers <- renderUI({ temp <- av_tickers$av_tickers selectizeInput(inputId = "delete_ticker", label = "", choices = c(temp), multiple = TRUE) }) observeEvent(input$delete_ticker_button, { showModal(modalDialog(title = "Deleting ticker from cache...", easyClose = FALSE, footer = NULL)) if(length(input$delete_ticker) > 0) { for(t in input$delete_ticker) { unlink(paste(cache_path, t,sep=""), recursive=TRUE) } av_tickers$av_tickers <- list.files(cache_path, recursive = FALSE, full.names=FALSE) for(t in av_tickers$av_tickers) { ticker_choice$ticker_choice <- ticker_choice$ticker_choice[ticker_choice$ticker_choice != t] } update_table() } removeModal() }) observeEvent(input$add_tickers, { showModal(modalDialog(title = "Adding ticker to cache...", easyClose = FALSE, footer = NULL)) if(length(input$add_ticker) > 0) { for(t in input$add_ticker) { updateCache(t, APIURL, apikey, cache_path) } av_tickers$av_tickers <- list.files(cache_path, recursive = FALSE, full.names=FALSE) for(t in av_tickers$av_tickers) { ticker_choice$ticker_choice <- ticker_choice$ticker_choice[ticker_choice$ticker_choice != t] } update_table() } removeModal() }) output$cached_tickers <- renderUI({ temp <- av_tickers$av_tickers selectizeInput(inputId = "update_ticker", label = "", choices = c(temp), multiple = TRUE) }) observeEvent(input$update_tickers, { showModal(modalDialog(title = "Updating cache...", easyClose = FALSE, footer = NULL)) if(length(input$update_ticker) > 0) { for(t in input$update_ticker) { updateCache(t, APIURL, apikey, cache_path) } update_table() } removeModal() })
open import Prelude renaming (_≟_ to _N≟_) module Implicits.Syntax.Type.Unification.McBride where open import Implicits.Syntax open import Implicits.Syntax.MetaType open import Data.Vec hiding (_>>=_) open import Data.Vec.Properties open import Data.Nat as N using () open import Data.Nat.Properties.Simple open import Data.Product open import Category.Monad open import Data.Maybe hiding (module Maybe; map) open import Data.Maybe as Maybe using (monad; functor) open import Level using () renaming (zero to level₀) open RawMonad {level₀} monad using (_>>=_; return) open import Category.Functor open RawFunctor {level₀} functor open import Data.Star hiding (_>>=_) open import Data.Fin.Properties as FinProp using () open import Data.Fin.Substitution open import Implicits.Substitutions open import Implicits.Substitutions.Lemmas private module M = MetaTypeMetaSubst module T = MetaTypeTypeSubst thin : ∀ {n} → Fin (suc n) → Fin n → Fin (suc n) thin zero y = suc y thin (suc x) zero = zero thin (suc x) (suc y) = suc (thin x y) thick : ∀ {n} → (x y : Fin (suc n)) → Maybe (Fin n) thick zero zero = nothing thick zero (suc y) = just y thick {zero} (suc ()) zero thick {suc n} (suc x) zero = just zero thick {zero} (suc ()) _ thick {suc n} (suc x) (suc y) = suc <$> (thick x y) check' : ∀ {ν} → Fin (suc ν) → Type (suc ν) → Maybe (Type ν) check' n (simpl (tvar m)) = (λ n → simpl (tvar n)) <$> (thick n m) check' n (simpl (tc x)) = just (simpl (tc x)) check' n (simpl (a →' b)) with check' n a | check' n b check' n (simpl (a →' b)) | just x | just y = just (simpl (x →' y)) check' n (simpl (a →' b)) | _ | nothing = nothing check' n (simpl (a →' b)) | nothing | _ = nothing check' n (a ⇒ b) with check' n a | check' n b check' n (a ⇒ b) | just x | just y = just (x ⇒ y) check' n (a ⇒ b) | _ | nothing = nothing check' n (a ⇒ b) | nothing | _ = nothing check' n (∀' t) with check' (suc n) t check' n (∀' t) | just x = just (∀' x) check' n (∀' t) | nothing = nothing substitute : {ν m n : ℕ} → (Fin m → MetaType n ν) → MetaType m ν → MetaType n ν substitute f a = a M./ (tabulate f) _for_ : ∀ {n ν} → Type ν → Fin (suc n) → Fin (suc n) → MetaType n ν _for_ t' x y with thick x y _for_ t' x y | just y' = simpl (mvar y') _for_ t' x y | nothing = to-meta t' data ASub (ν : ℕ) : ℕ → ℕ → Set where _//_ : ∀ {m} → (t' : Type ν) → Fin (suc m) → ASub ν (suc m) m AList : ℕ → ℕ → ℕ → Set AList ν m n = Star (ASub ν) m n asub-tp-weaken : ∀ {ν m n} → ASub ν m n → ASub (suc ν) m n asub-tp-weaken (t' // x) = tp-weaken t' // x asub-weaken : ∀ {ν m n} → ASub ν m n → ASub ν (suc m) (suc n) asub-weaken (t' // x) = t' // (suc x) alist-weaken : ∀ {ν m n} → AList ν m n → AList (suc ν) m n alist-weaken s = gmap Prelude.id (λ x → asub-tp-weaken x) s _◇_ : ∀ {l m n ν} → (Fin m → MetaType n ν) → (Fin l → MetaType m ν) → (Fin l → MetaType n ν) f ◇ g = substitute f ∘ g asub' : ∀ {ν m n} → (σ : AList ν m n) → Fin m → MetaType n ν asub' ε = λ n → simpl (mvar n) asub' (t' // x ◅ y) = asub' y ◇ (t' for x) asub : ∀ {ν m n} → (σ : AList ν m n) → Sub (flip MetaType ν) m n asub s = tabulate (asub' s) mgu : ∀ {m ν} → MetaType m ν → Type ν → Maybe (∃ (AList ν m)) mgu {ν} s t = amgu s t (ν , ε) where amgu : ∀ {ν m} (s : MetaType m ν) → (t : Type ν)→ ∃ (AList ν m) → Maybe (∃ (AList ν m)) -- non-matching constructors amgu (simpl (tc x)) (_ ⇒ _) acc = nothing amgu (simpl (tc _)) (∀' _) x = nothing amgu (simpl (tc x)) (simpl (_ →' _)) acc = nothing amgu (simpl (tc _)) (simpl (tvar _)) x = nothing amgu (simpl (_ →' _)) (∀' _) x = nothing amgu (simpl (_ →' _)) (_ ⇒ _) x = nothing amgu (simpl (_ →' _)) (simpl (tc _)) acc = nothing amgu (simpl (_ →' _)) (simpl (tvar _)) x = nothing amgu (_ ⇒ _) (simpl x) acc = nothing amgu (_ ⇒ _) (∀' _) x = nothing amgu (∀' _) (_ ⇒ _) x = nothing amgu (∀' _) (simpl _) x = nothing amgu (simpl (tvar _)) (_ ⇒ _) x = nothing amgu (simpl (tvar _)) (∀' _) x = nothing amgu (simpl (tvar _)) (simpl (tc _)) x = nothing amgu (simpl (tvar _)) (simpl (_ →' _)) acc = nothing -- matching constructors amgu (a ⇒ b) (a' ⇒ b') acc = _>>=_ (amgu b b' acc) (amgu a a') amgu (simpl (a →' b)) (simpl (a' →' b')) acc = _>>=_ (amgu b b' acc) (amgu a a') amgu (simpl (tc x)) (simpl (tc y)) acc with x N≟ y amgu (simpl (tc x)) (simpl (tc y)) acc | yes p = just (, ε) amgu (simpl (tc x)) (simpl (tc y)) acc | no ¬p = nothing amgu (∀' a) (∀' b) (m , acc) = σ >>= strengthen' where σ = amgu a b (m , alist-weaken acc) strengthen' : ∀ {ν n} → ∃ (AList (suc ν) n) → Maybe (∃ (AList ν n)) strengthen' (m , ε) = just (m , ε) strengthen' (m , t' // x ◅ acc) with check' zero t' strengthen' (m , t' // x ◅ acc) | just z = (λ { (m , u) → m , z // x ◅ u }) <$> (strengthen' (m , acc)) strengthen' (m , t' // x ◅ acc) | nothing = nothing -- var-var amgu ((simpl (tvar x))) ((simpl (tvar y))) (m , ε) with x FinProp.≟ y amgu ((simpl (tvar x))) ((simpl (tvar y))) (m , ε) | yes _ = just (, ε) amgu ((simpl (tvar x))) ((simpl (tvar y))) (m , ε) | no _ = nothing -- var-rigid / rigid-var amgu (simpl (mvar ())) t (zero , ε) amgu (simpl (mvar x)) t (suc m , ε) = just (m , t // x ◅ ε) amgu s t (m , t' // x ◅ us) with amgu (substitute (t' for x) s) t (m , us) amgu s t (m , t' // x ◅ us) | just (m' , us') = just (m' , t' // x ◅ us') amgu s t (m , t' // x ◅ us) | nothing = nothing
flavor 1 srclang 3 id 65535 numfuncs 7 import "ThreadTest.mplt" import "/home/bravewtz/Desktop/openarkcompiler/libjava-core/libjava-core.mplt" entryfunc &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V fileinfo { @INFO_filename "ThreadTest.jar"} srcfileinfo { 1 "ThreadTest.java"} type $__class_meta__ <struct { @shadow <* void> final, @monitor i32 final, @classloader u16 final, @objsize u16 final, @itab <* void> final, @vtab <* void> final, @gctib <* void> final, @classinforo <* void> final, @clinitbridge <* void> final}> type $__class_meta_ro__ <struct { @classname <* void> final, @ifields <* void> final, @methods <* void> final, @superclass_or_componentclass <* void> final, @numoffields u16 final, @numofmethods u16 final, @flag u16 final, @numofsuperclasses u16 final, @padding u32 final, @mod i32 final, @annotation i32 final, @clinitAddr i32 final}> type $__method_info__ <struct { @method_in_vtab_index i64 final, @declaringclass i64 final, @addr i64 final, @mod i32 final, @methodname i32 final, @signaturename i32 final, @annotationvalue i32 final, @flag u16 final, @argsize u16 final, @padding u32 final}> type $__method_info_compact__ <struct { @method_in_vtab_index i32 final, @addr i32 final, @lebPadding0 u8 final}> type $__field_info__ <struct { @offset u64 final, @mod u32 final, @flag u16 final, @index u16 final, @typeName i64 final, @fieldname u32 final, @annotation u32 final, @declaringclass <* void> final}> type $__field_info_compact__ <struct { @offset u32 final, @lebPadding0 u8 final}> type $__superclass_meta__ <struct { @superclassinfo <* void> final}> type $MUIDFuncDefTabEntry <struct { @funcUnifiedAddr u64}> type $MUIDFuncInfTabEntry <struct { @funcSize u32, @funcName u32}> type $MUIDFuncDefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDDataDefTabEntry <struct { @dataUnifiedAddr u64}> type $MUIDDataDefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDUnifiedUndefTabEntry <struct { @globalAddress u64}> type $MUIDUnifiedUndefMuidTabEntry <struct { @muidLow u64, @muidHigh u64}> type $MUIDRangeTabEntry <struct { @tabBegin <* void>, @tabEnd <* void>}> javaclass $LThreadTest_3B <$LThreadTest_3B> public javaclass $LThreadTest_24FirstThread_3B <$LThreadTest_24FirstThread_3B> javaclass $LThreadTest_24SecondThread_3B <$LThreadTest_24SecondThread_3B> var $_C_STR_5ca9762cf0b6a8cb0f4e692a3a6e142c fstatic <[5] u64> readonly = [0, 0x2700000000, 0x45544e498db7b2ca, 0x5f44455450555252, 0x4547415353454d] var $_C_STR_4f004b00 fstatic <[3] u64> readonly = [0, 0x500000000, 0x4b4f000009dc] var $LThreadTest_3B_7Cflag i64 static volatile = 0 var $LThreadTest_3B_7Cnumber i32 static = 0 func &LThreadTest_24FirstThread_3B_7Cstart_7C_28_29V public virtual synchronized (var %_this <* <$LThreadTest_24FirstThread_3B>>) void func &LThreadTest_24SecondThread_3B_7Cstart_7C_28_29V public virtual synchronized (var %_this <* <$LThreadTest_24SecondThread_3B>>) void func &LThreadTest_24FirstThread_3B_7Cjoin_7C_28_29V final public virtual (var %_this <* <$LThreadTest_24FirstThread_3B>>) void func &LThreadTest_24SecondThread_3B_7Cjoin_7C_28_29V final public virtual (var %_this <* <$LThreadTest_24SecondThread_3B>>) void var $Ljava_2Flang_2FSystem_3B_7Cout extern <* <$Ljava_2Fio_2FPrintStream_3B>> final public static var $__cinf_Ljava_2Flang_2FString_3B <$__class_meta__> func &MCC_GetOrInsertLiteral () <* <$Ljava_2Flang_2FString_3B>> var $__vtb_LThreadTest_3B fstatic <[11] <* void>> = [28, 72, 104, 116, 20, 12, 176, 24, 60, 156, 84] var $__vtb_LThreadTest_24FirstThread_3B fstatic <[45] <* void>> = [28, 72, 104, 140, 188, 12, 176, 24, 60, 156, 84, 22, 136, 100, 4, 68, 8, 32, 132, 80, 52, 172, 112, 180, 76, 56, 16, 192, 44, 184, 164, 168, 88, 48, 148, 96, 64, 144, 40, 92, 160, 152, 108, 120, 36] var $__itb_LThreadTest_24FirstThread_3B fstatic <[4] <* void>> = [0, 0, 0, 22] var $__vtb_LThreadTest_24SecondThread_3B fstatic <[45] <* void>> = [28, 72, 104, 140, 188, 12, 176, 24, 60, 156, 84, 30, 136, 100, 4, 68, 8, 32, 132, 80, 52, 172, 112, 180, 76, 56, 16, 192, 44, 184, 164, 168, 88, 48, 148, 96, 64, 144, 40, 92, 160, 152, 108, 120, 36] var $__itb_LThreadTest_24SecondThread_3B fstatic <[4] <* void>> = [0, 0, 0, 30] var $__cinf_LThreadTest_3B <$__class_meta__> public var $__fields_info__LThreadTest_3B fstatic <[2] <$__field_info__>> public = [[1= addrof ptr $LThreadTest_3B_7Cflag, 2= 72, 3= 0x47c0, 4= 0, 5= 76, 6= 56, 7= 84, 8= addrof ptr $__cinf_LThreadTest_3B], [1= addrof ptr $LThreadTest_3B_7Cnumber, 2= 8, 3= 0x5780, 4= 1, 5= 128, 6= 100, 7= 84, 8= addrof ptr $__cinf_LThreadTest_3B]] var $__methods_info__LThreadTest_3B fstatic <[3] <$__method_info__>> public = [[1= 0xfff6, 2= addrof ptr $__cinf_LThreadTest_3B, 3= addroffunc ptr &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V, 4= 0x10008, 5= 136, 6= 172, 7= 84, 8= 0x2741, 9= 0, 10= 0], [1= 0xfff6, 2= addrof ptr $__cinf_LThreadTest_3B, 3= addroffunc ptr &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V, 4= 9, 5= 188, 6= 208, 7= 84, 8= 0xa201, 9= 1, 10= 0], [1= 0xfff6, 2= addrof ptr $__cinf_LThreadTest_3B, 3= addroffunc ptr &LThreadTest_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10001, 5= 300, 6= 172, 7= 84, 8= 0xad81, 9= 1, 10= 0]] var $__cinf_Ljava_2Flang_2FObject_3B extern <$__class_meta__> public var $__superclasses__LThreadTest_3B fstatic <[1] <$__superclass_meta__>> public = [[1= 0x4000000000000001]] var $__classinforo__LThreadTest_3B fstatic <$__class_meta_ro__> public = [1= 4, 2= addrof ptr $__fields_info__LThreadTest_3B, 3= addrof ptr $__methods_info__LThreadTest_3B, 4= addrof ptr $__superclasses__LThreadTest_3B, 5= 2, 6= 3, 7= 0, 8= 1, 9= 0, 10= 33, 11= 84, 12= addroffunc ptr &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V] var $MCC_GCTIB__LThreadTest_3B fstatic <* void> public var $classInitProtectRegion extern ptr extern var $__cinf_LThreadTest_3B <$__class_meta__> public = [1= 0x601746118725705b, 2= 0, 3= 0xffff, 4= 0, 5= 0, 6= addrof ptr $__vtb_LThreadTest_3B, 7= addrof ptr $MCC_GCTIB__LThreadTest_3B, 8= addrof ptr $__classinforo__LThreadTest_3B, 9= addrof ptr $classInitProtectRegion] var $__cinf_LThreadTest_24FirstThread_3B <$__class_meta__> public var $__methods_info__LThreadTest_24FirstThread_3B fstatic <[2] <$__method_info__>> public = [[1= 0xfff6, 2= addrof ptr $__cinf_LThreadTest_24FirstThread_3B, 3= addroffunc ptr &LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10000, 5= 300, 6= 172, 7= 84, 8= 0xad81, 9= 1, 10= 0], [1= 11, 2= addrof ptr $__cinf_LThreadTest_24FirstThread_3B, 3= addroffunc ptr &LThreadTest_24FirstThread_3B_7Crun_7C_28_29V, 4= 1, 5= 428, 6= 172, 7= 84, 8= 0xcd40, 9= 1, 10= 0]] var $__cinf_Ljava_2Flang_2FThread_3B extern <$__class_meta__> public var $__superclasses__LThreadTest_24FirstThread_3B fstatic <[1] <$__superclass_meta__>> public = [[1= 0x4000000000000000]] var $__classinforo__LThreadTest_24FirstThread_3B fstatic <$__class_meta_ro__> public = [1= 328, 2= 0, 3= addrof ptr $__methods_info__LThreadTest_24FirstThread_3B, 4= addrof ptr $__superclasses__LThreadTest_24FirstThread_3B, 5= 0, 6= 2, 7= 0, 8= 1, 9= 0, 10= 32, 11= 84, 12= 0] var $MCC_GCTIB__LThreadTest_24FirstThread_3B fstatic <* void> public var $__cinf_LThreadTest_24FirstThread_3B <$__class_meta__> public = [1= -1910748702277457663, 2= 0, 3= 0xffff, 4= 0, 5= addrof ptr $__itb_LThreadTest_24FirstThread_3B, 6= addrof ptr $__vtb_LThreadTest_24FirstThread_3B, 7= addrof ptr $MCC_GCTIB__LThreadTest_24FirstThread_3B, 8= addrof ptr $__classinforo__LThreadTest_24FirstThread_3B, 9= addrof ptr $classInitProtectRegion] var $__cinf_LThreadTest_24SecondThread_3B <$__class_meta__> public var $__methods_info__LThreadTest_24SecondThread_3B fstatic <[2] <$__method_info__>> public = [[1= 0xfff6, 2= addrof ptr $__cinf_LThreadTest_24SecondThread_3B, 3= addroffunc ptr &LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V, 4= 0x10000, 5= 300, 6= 172, 7= 84, 8= 0xad81, 9= 1, 10= 0], [1= 11, 2= addrof ptr $__cinf_LThreadTest_24SecondThread_3B, 3= addroffunc ptr &LThreadTest_24SecondThread_3B_7Crun_7C_28_29V, 4= 1, 5= 428, 6= 172, 7= 84, 8= 0xcd40, 9= 1, 10= 0]] var $__superclasses__LThreadTest_24SecondThread_3B fstatic <[1] <$__superclass_meta__>> public = [[1= 0x4000000000000000]] var $__classinforo__LThreadTest_24SecondThread_3B fstatic <$__class_meta_ro__> public = [1= 444, 2= 0, 3= addrof ptr $__methods_info__LThreadTest_24SecondThread_3B, 4= addrof ptr $__superclasses__LThreadTest_24SecondThread_3B, 5= 0, 6= 2, 7= 0, 8= 1, 9= 0, 10= 32, 11= 84, 12= 0] var $MCC_GCTIB__LThreadTest_24SecondThread_3B fstatic <* void> public var $__cinf_LThreadTest_24SecondThread_3B <$__class_meta__> public = [1= 0x56e06a892c2826fd, 2= 0, 3= 0xffff, 4= 0, 5= addrof ptr $__itb_LThreadTest_24SecondThread_3B, 6= addrof ptr $__vtb_LThreadTest_24SecondThread_3B, 7= addrof ptr $MCC_GCTIB__LThreadTest_24SecondThread_3B, 8= addrof ptr $__classinforo__LThreadTest_24SecondThread_3B, 9= addrof ptr $classInitProtectRegion] var $__muid_classmetadata_bucket$$ThreadTest_jar <[3] <* void>> public = [addrof ptr $__cinf_LThreadTest_3B, addrof ptr $__cinf_LThreadTest_24FirstThread_3B, addrof ptr $__cinf_LThreadTest_24SecondThread_3B] func &MCC_Reflect_ThrowCastException nosideeffect () void func &MCC_Reflect_Check_Casting_NoArray nosideeffect () void func &MCC_Reflect_Check_Casting_Array nosideeffect () void func &MCC_CheckThrowPendingException nosideeffect () void func &MCC_PreNativeCall (var %caller ref) <* void> func &MCC_PostNativeCall (var %env <* void>) void func &MCC_DecodeReference nosideeffect (var %obj ref) ref func &MCC_CallFastNative (var %func <* void>) <* void> func &MCC_CallSlowNative0 (var %func <* void>) <* void> func &MCC_CallSlowNative1 (var %func <* void>) <* void> func &MCC_CallSlowNative2 (var %func <* void>) <* void> func &MCC_CallSlowNative3 (var %func <* void>) <* void> func &MCC_CallSlowNative4 (var %func <* void>) <* void> func &MCC_CallSlowNative5 (var %func <* void>) <* void> func &MCC_CallSlowNative6 (var %func <* void>) <* void> func &MCC_CallSlowNative7 (var %func <* void>) <* void> func &MCC_CallSlowNative8 (var %func <* void>) <* void> func &MCC_CallFastNativeExt (var %func <* void>) <* void> func &MCC_CallSlowNativeExt (var %func <* void>) <* void> func &MCC_SetReliableUnwindContext nosideeffect () void var $__reg_jni_func_tab$$ThreadTest_jar <[0] <* void>> var $__cinf_Ljava_2Flang_2FSystem_3B extern <$__class_meta__> func &MCC_getFuncPtrFromItabSecondHash64 nosideeffect () ptr var $__cinf_Ljava_2Flang_2FInterruptedException_3B extern ptr var $__muid_func_def_tab$$ThreadTest_jar fstatic <[7] <$MUIDFuncDefTabEntry>> = [[1= addroffunc ptr &LThreadTest_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V], [1= addroffunc ptr &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24FirstThread_3B_7Crun_7C_28_29V], [1= addroffunc ptr &LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24SecondThread_3B_7Crun_7C_28_29V]] var $__muid_func_inf_tab$$ThreadTest_jar fstatic <[7] <$MUIDFuncInfTabEntry>> = [[1= addroffunc ptr &LThreadTest_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LThreadTest_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V, 2= addroffunc ptr &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V], [1= addroffunc ptr &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V, 2= addroffunc ptr &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24FirstThread_3B_7Crun_7C_28_29V, 2= addroffunc ptr &LThreadTest_24FirstThread_3B_7Crun_7C_28_29V], [1= addroffunc ptr &LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V, 2= addroffunc ptr &LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V], [1= addroffunc ptr &LThreadTest_24SecondThread_3B_7Crun_7C_28_29V, 2= addroffunc ptr &LThreadTest_24SecondThread_3B_7Crun_7C_28_29V]] var $__muid_func_def_muid_tab$$ThreadTest_jar fstatic <[7] <$MUIDFuncDefMuidTabEntry>> = [[1= 0x13e812340dcd9747, 2= -4390240725891335583], [1= -6465699462723914147, 2= -3078620880440254106], [1= -5662764354190214830, 2= -3895768361636494236], [1= -1515835811489525396, 2= -2491556408962237634], [1= 0x1375bee4553224da, 2= -3022497157433240244], [1= -7260689426497094992, 2= -2683817943550545190], [1= -9025088470043148724, 2= -1511184063164969663]] var $__muid_func_muid_idx_tab$$ThreadTest_jar fstatic <[7] u32> = [0, 2, 1, 4, 5, 3, 6] var $__muid_data_def_tab$$ThreadTest_jar fstatic <[5] <$MUIDDataDefTabEntry>> = [[1= addrof ptr $LThreadTest_3B_7Cflag], [1= addrof ptr $LThreadTest_3B_7Cnumber], [1= addrof ptr $__cinf_LThreadTest_24FirstThread_3B], [1= addrof ptr $__cinf_LThreadTest_24SecondThread_3B], [1= addrof ptr $__cinf_LThreadTest_3B]] var $__muid_data_def_muid_tab$$ThreadTest_jar fstatic <[5] <$MUIDDataDefMuidTabEntry>> = [[1= 0x2e4837acea6c8f18, 2= -4202138265818549454], [1= -8251186736023717379, 2= -4124130188192603885], [1= 0x542c8f5477072117, 2= -1316117149944976241], [1= -7008824318707944130, 2= -1246917843157017273], [1= -1558453601909796022, 2= -1101611014159457623]] var $__muid_func_undef_tab$$ThreadTest_jar fstatic <[48] <$MUIDUnifiedUndefTabEntry>> = [[1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0], [1= 0]] var $__muid_func_undef_muid_tab$$ThreadTest_jar fstatic <[48] <$MUIDUnifiedUndefMuidTabEntry>> = [[1= 0x2223b87409cad2eb, 2= -4544858217376317221], [1= 0x4fa4baf54c8ffa4c, 2= -4330908427870763329], [1= 0x3e32352aee789835, 2= -3887705395317205813], [1= 0x45d51d3a37f2eaf8, 2= -3803052163954213614], [1= -4187412136968710015, 2= -3800091941095621250], [1= 0x6742c234127e0a27, 2= -3762262047879347071], [1= 0x7230554331c55d92, 2= -3676689525926909155], [1= 0x27f27d55f7b9c5d9, 2= -3648645570896318275], [1= 0x7a67983d5ce27047, 2= -3536642499983467643], [1= -4444155200099052867, 2= -3515440642439275467], [1= -1302430067206559936, 2= -3462335513377456398], [1= 0x1c335bd3cc2bcbc5, 2= -2941286735605730226], [1= -602739002717106589, 2= -2871649643308752234], [1= 0x3ac18f49b10ae9c8, 2= -2761083912114346695], [1= -715372855679083712, 2= -2647497990906227723], [1= -7085459064379798003, 2= -2504140512675861057], [1= -5912326000629320870, 2= -2445642633367446670], [1= -7464356948810446352, 2= -2259485500590180091], [1= -8120584984539259228, 2= -2249302601425884092], [1= 0x6a5bce1d7dcfa267, 2= -2139116575755650336], [1= 0x783627f2afd1cbde, 2= -2046851302095768916], [1= -9011904582352340104, 2= -2021666714678159314], [1= -8733927297512235975, 2= -1796627844226479270], [1= 0x59ce545d6d9ab36e, 2= -1786941763209948044], [1= -587008565175255386, 2= -1765108571334409255], [1= -2701934576591406938, 2= -1693831364093527548], [1= 0x2beff4a27d3d2725, 2= -1590592096693131319], [1= 0x465af7fb7b37cebf, 2= -1370147957366279709], [1= 0x126777a7fe39e1fb, 2= -1314856249532362766], [1= 0x1e487b9899688ddc, 2= -1222088747469901692], [1= -2286157587747070287, 2= -1198859979193267183], [1= 0xbf40578f3343f7a, 2= -1198421541845410999], [1= 0x82ba7802132264b, 2= -1140277309818752746], [1= 0x16d67c99c97a7226, 2= -1118615548797384204], [1= -6517504468940763734, 2= -985898192824390983], [1= 0x4a2c12aa722ee760, 2= -969283531794502784], [1= -4151460732252162179, 2= -959188706633355145], [1= 0x524b6341e766ec9b, 2= -942822020201989684], [1= 0x7ca2bdf69a6c7c94, 2= -801329978528900548], [1= 0x7c8e2c146ebd0e05, 2= -719105873032197634], [1= 0x3e05543ea29d21a1, 2= -670103158184685825], [1= -7069492754778935884, 2= -629688729876427650], [1= -1236337316879982579, 2= -549283759455216643], [1= 0x477aafa4d7dd102b, 2= -442561182569419835], [1= 0x688cc73fd64e714e, 2= -330519468687830863], [1= 0x1c2ea56e3be7621, 2= -302634276939952847], [1= 0x54a363649fd92710, 2= -302464603624962686], [1= 0x593c3fc28ebb7385, 2= -155033466871350824]] var $__muid_data_undef_tab$$ThreadTest_jar fstatic <[5] <$MUIDUnifiedUndefTabEntry>> = [[1= addrof ptr $__cinf_Ljava_2Flang_2FThread_3B], [1= addrof ptr $__cinf_Ljava_2Flang_2FObject_3B], [1= addrof ptr $__cinf_Ljava_2Flang_2FInterruptedException_3B], [1= addrof ptr $Ljava_2Flang_2FSystem_3B_7Cout], [1= addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B]] var $__muid_data_undef_muid_tab$$ThreadTest_jar fstatic <[5] <$MUIDUnifiedUndefMuidTabEntry>> = [[1= -2081497933309471564, 2= -4183766768174827520], [1= -567417612161374449, 2= -3298852447504547670], [1= -5803877874595771331, 2= -2832522094489880871], [1= 0x191283ac418c4bb9, 2= -1676204161023949463], [1= -5921653145571052587, 2= -171150348656858163]] var $__muid_range_tab$$ThreadTest_jar fstatic <[29] <$MUIDRangeTabEntry>> = [[1= 0x7594c0b336c6743a, 2= -4211634493258138111], [1= 0x470db1cb78bce104, 2= -3981267291069264544], [1= 2, 2= 2], [1= 3, 2= 3], [1= 4, 2= 4], [1= 5, 2= 5], [1= 6, 2= 6], [1= 7, 2= 7], [1= 8, 2= 8], [1= 9, 2= 9], [1= 0, 2= 0], [1= 11, 2= 11], [1= 12, 2= 12], [1= 13, 2= 13], [1= 14, 2= 14], [1= 15, 2= 15], [1= addrof ptr $__muid_func_def_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_def_tab$$ThreadTest_jar], [1= 0, 2= 0], [1= addrof ptr $__muid_func_inf_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_inf_tab$$ThreadTest_jar], [1= addrof ptr $__muid_func_undef_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_undef_tab$$ThreadTest_jar], [1= addrof ptr $__muid_data_def_tab$$ThreadTest_jar, 2= addrof ptr $__muid_data_def_tab$$ThreadTest_jar], [1= 0, 2= 0], [1= addrof ptr $__muid_data_undef_tab$$ThreadTest_jar, 2= addrof ptr $__muid_data_undef_tab$$ThreadTest_jar], [1= addrof ptr $__muid_func_def_muid_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_def_muid_tab$$ThreadTest_jar], [1= addrof ptr $__muid_func_undef_muid_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_undef_muid_tab$$ThreadTest_jar], [1= addrof ptr $__muid_data_def_muid_tab$$ThreadTest_jar, 2= addrof ptr $__muid_data_def_muid_tab$$ThreadTest_jar], [1= addrof ptr $__muid_data_undef_muid_tab$$ThreadTest_jar, 2= addrof ptr $__muid_data_undef_muid_tab$$ThreadTest_jar], [1= addrof ptr $__muid_func_muid_idx_tab$$ThreadTest_jar, 2= addrof ptr $__muid_func_muid_idx_tab$$ThreadTest_jar], [1= 0, 2= 0]] var $__reflection_strtab$$ThreadTest_jar fstatic <[137] u8> = [0, 76, 84, 104, 114, 101, 97, 100, 84, 101, 115, 116, 59, 0, 102, 108, 97, 103, 0, 74, 0, 48, 33, 48, 0, 110, 117, 109, 98, 101, 114, 0, 73, 0, 60, 99, 108, 105, 110, 105, 116, 62, 0, 40, 41, 86, 0, 109, 97, 105, 110, 0, 40, 91, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 41, 86, 0, 60, 105, 110, 105, 116, 62, 0, 76, 84, 104, 114, 101, 97, 100, 84, 101, 115, 116, 36, 70, 105, 114, 115, 116, 84, 104, 114, 101, 97, 100, 59, 0, 114, 117, 110, 0, 76, 84, 104, 114, 101, 97, 100, 84, 101, 115, 116, 36, 83, 101, 99, 111, 110, 100, 84, 104, 114, 101, 97, 100, 59, 0] var $__compilerVersionNum$$ThreadTest_jar <[0] <* void>> = [1, 0] func &LThreadTest_3B_7C_3Cinit_3E_7C_28_29V public constructor (var %_this <* <$LThreadTest_3B>>) void { funcid 48153 var %Reg1_R43698 <* <$LThreadTest_3B>> localrefvar var %Reg1_R57 <* <$Ljava_2Flang_2FObject_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43698) dassign %Reg1_R43698 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R57) dassign %Reg1_R57 0 (retype ref <* <$Ljava_2Flang_2FObject_3B>> (dread ref %Reg1_R43698)) intrinsiccall MCCIncRef (dread ref %Reg1_R57) intrinsiccall MCCDecRef (regread ptr %1) #Call function:Ljava_2Flang_2FObject_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[48] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_func_undef_tab$$ThreadTest_jar, constval i64 31))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R57) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43698, dread ref %Reg1_R57) return () } func &LThreadTest_3B_7Cmain_7C_28ALjava_2Flang_2FString_3B_29V public static (var %Reg5_R743 <* <[] <* <$Ljava_2Flang_2FString_3B>>>>) void { funcid 48154 var %Reg0_R43700 <* <$LThreadTest_24FirstThread_3B>> localrefvar var %Reg2_R43700 <* <$LThreadTest_24FirstThread_3B>> localrefvar var %Reg0_R43702 <* <$LThreadTest_24SecondThread_3B>> localrefvar var %Reg3_R43702 <* <$LThreadTest_24SecondThread_3B>> localrefvar var %Reg0_R20155 <* <$Ljava_2Flang_2FInterruptedException_3B>> localrefvar var %Reg4_R20155 <* <$Ljava_2Flang_2FInterruptedException_3B>> localrefvar var %Reg0_R562 <* <$Ljava_2Fio_2FPrintStream_3B>> localrefvar var %Reg1_R43 <* <$Ljava_2Flang_2FString_3B>> localrefvar var %L_STR_161348 <* <$Ljava_2Flang_2FString_3B>> var %L_STR_161349 <* <$Ljava_2Flang_2FString_3B>> var %__muid_symptr <* void> intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_3B) #INSTIDX : 0||0000: new intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_24FirstThread_3B) regassign ptr %1 (dread ref %Reg0_R43700) dassign %Reg0_R43700 0 (gcmalloc ref <$LThreadTest_24FirstThread_3B>) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 3||0003: dup #INSTIDX : 4||0004: invokespecial #Call function:LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$ThreadTest_jar, constval i64 3))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg0_R43700) {} #INSTIDX : 7||0007: astore_1 intrinsiccall MCCIncRef (dread ref %Reg0_R43700) intrinsiccall MCCDecRef (dread ref %Reg2_R43700) dassign %Reg2_R43700 0 (dread ref %Reg0_R43700) #INSTIDX : 8||0008: new intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_24SecondThread_3B) regassign ptr %2 (dread ref %Reg0_R43702) dassign %Reg0_R43702 0 (gcmalloc ref <$LThreadTest_24SecondThread_3B>) intrinsiccall MCCDecRef (regread ptr %2) #INSTIDX : 11||000b: dup #INSTIDX : 12||000c: invokespecial #Call function:LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDFuncDefTabEntry>> 1 (array 0 ptr <* <[7] <$MUIDFuncDefTabEntry>>> (addrof ptr $__muid_func_def_tab$$ThreadTest_jar, constval i64 5))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg0_R43702) {} #INSTIDX : 15||000f: astore_2 intrinsiccall MCCIncRef (dread ref %Reg0_R43702) intrinsiccall MCCDecRef (dread ref %Reg3_R43702) dassign %Reg3_R43702 0 (dread ref %Reg0_R43702) #INSTIDX : 16||0010: aload_1 #INSTIDX : 17||0011: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg2_R43700)), constval u32 104)), dread ref %Reg2_R43700) {} #INSTIDX : 20||0014: aload_2 #INSTIDX : 21||0015: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg3_R43702)), constval u32 104)), dread ref %Reg3_R43702) {} try { @label0 } #INSTIDX : 24||0018: aload_1 #INSTIDX : 25||0019: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg2_R43700)), constval u32 240)), dread ref %Reg2_R43700) {} #INSTIDX : 28||001c: aload_2 #INSTIDX : 29||001d: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg3_R43702)), constval u32 240)), dread ref %Reg3_R43702) {} endtry #INSTIDX : 32||0020: goto goto @label1 @label0 catch { <* <$Ljava_2Flang_2FInterruptedException_3B>> } intrinsiccall MCCDecRef (dread ref %Reg0_R20155) dassign %Reg0_R20155 0 (regread ptr %%thrownval) #INSTIDX : 35||0023: astore_3 intrinsiccall MCCIncRef (dread ref %Reg0_R20155) intrinsiccall MCCDecRef (dread ref %Reg4_R20155) dassign %Reg4_R20155 0 (dread ref %Reg0_R20155) #INSTIDX : 36||0024: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %3 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$ThreadTest_jar, constval i64 3)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %3) #INSTIDX : 39||0027: ldc callassigned &MCC_GetOrInsertLiteral (addrof ptr $_C_STR_5ca9762cf0b6a8cb0f4e692a3a6e142c) { dassign %L_STR_161348 0 } intrinsiccall MCCIncRef (dread ptr %L_STR_161348) intrinsiccall MCCDecRef (dread ref %Reg1_R43) dassign %Reg1_R43 0 (dread ptr %L_STR_161348) #INSTIDX : 41||0029: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 312)), dread ref %Reg0_R562, dread ref %Reg1_R43) {} @label1 #INSTIDX : 44||002c: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %4 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$ThreadTest_jar, constval i64 3)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %4) #INSTIDX : 47||002f: ldc callassigned &MCC_GetOrInsertLiteral (addrof ptr $_C_STR_4f004b00) { dassign %L_STR_161349 0 } intrinsiccall MCCIncRef (dread ptr %L_STR_161349) intrinsiccall MCCDecRef (dread ref %Reg1_R43) dassign %Reg1_R43 0 (dread ptr %L_STR_161349) #INSTIDX : 49||0031: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 312)), dread ref %Reg0_R562, dread ref %Reg1_R43) {} #INSTIDX : 52||0034: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg0_R43700, dread ref %Reg2_R43700, dread ref %Reg0_R43702, dread ref %Reg3_R43702, dread ref %Reg0_R20155, dread ref %Reg4_R20155, dread ref %Reg0_R562, dread ref %Reg1_R43) return () } func &LThreadTest_3B_7C_3Cclinit_3E_7C_28_29V static constructor () void { funcid 48155 var %Reg0_J i64 var %Reg0_I i32 var %__muid_funcptr <* void> #INSTIDX : 0||0000: lconst_0 dassign %Reg0_J 0 (constval i64 0) #INSTIDX : 1||0001: putstatic #Assign to: LThreadTest_3B_7Cflag dassign %__muid_funcptr 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 0))) iassign <* i64> 0 (dread ptr %__muid_funcptr, dread i64 %Reg0_J) #INSTIDX : 4||0004: iconst_0 dassign %Reg0_I 0 (constval i32 0) #INSTIDX : 5||0005: putstatic #Assign to: LThreadTest_3B_7Cnumber dassign %__muid_funcptr 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 1))) iassign <* i32> 0 (dread ptr %__muid_funcptr, dread i32 %Reg0_I) #INSTIDX : 8||0008: return intrinsiccall MPL_CLEANUP_LOCALREFVARS () return () } func &LThreadTest_24FirstThread_3B_7C_3Cinit_3E_7C_28_29V constructor (var %_this <* <$LThreadTest_24FirstThread_3B>>) void { funcid 48156 var %Reg1_R43700 <* <$LThreadTest_24FirstThread_3B>> localrefvar var %Reg1_R1610 <* <$Ljava_2Flang_2FThread_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43700) dassign %Reg1_R43700 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R1610) dassign %Reg1_R1610 0 (retype ref <* <$Ljava_2Flang_2FThread_3B>> (dread ref %Reg1_R43700)) intrinsiccall MCCIncRef (dread ref %Reg1_R1610) intrinsiccall MCCDecRef (regread ptr %1) #Call function:Ljava_2Flang_2FThread_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[48] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_func_undef_tab$$ThreadTest_jar, constval i64 30))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R1610) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43700, dread ref %Reg1_R1610) return () } func &LThreadTest_24FirstThread_3B_7Crun_7C_28_29V public virtual (var %_this <* <$LThreadTest_24FirstThread_3B>>) void { funcid 48157 var %Reg4_R43700 <* <$LThreadTest_24FirstThread_3B>> localrefvar var %Reg0_J i64 var %Reg1_J i64 var %Reg0_I i32 var %Reg0_R562 <* <$Ljava_2Fio_2FPrintStream_3B>> localrefvar var %Reg1_I i32 intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg4_R43700) dassign %Reg4_R43700 0 (dread ref %_this) @label2 #INSTIDX : 0||0000: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_3B) #Read from: LThreadTest_3B_7Cflag dassign %Reg0_J 0 (iread i64 <* i64> 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 0)))) #INSTIDX : 3||0003: ldc2_w dassign %Reg1_J 0 (constval i64 0x7fffffffffffffff) #INSTIDX : 6||0006: lcmp dassign %Reg0_I 0 (cmp i32 i64 (dread i64 %Reg0_J, dread i64 %Reg1_J)) #INSTIDX : 7||0007: ifeq brtrue @label3 (eq i32 i32 (dread i32 %Reg0_I, constval i32 0)) #INSTIDX : 10||000a: goto goto @label2 @label3 #INSTIDX : 13||000d: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_Ljava_2Flang_2FSystem_3B) regassign ptr %1 (dread ref %Reg0_R562) #Read from: Ljava_2Flang_2FSystem_3B_7Cout dassign %Reg0_R562 0 (iread ref <* <* <$Ljava_2Fio_2FPrintStream_3B>>> 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_data_undef_tab$$ThreadTest_jar, constval i64 3)))) intrinsiccall MCCIncRef (dread ref %Reg0_R562) intrinsiccall MCCDecRef (regread ptr %1) #INSTIDX : 16||0010: getstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_3B) #Read from: LThreadTest_3B_7Cnumber dassign %Reg1_I 0 (iread i32 <* i32> 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 1)))) #INSTIDX : 19||0013: invokevirtual icallassigned ( iread u64 <* u64> 0 (add ptr ( iread ptr <* <$__class_meta__>> 6 (iread ref <* <$Ljava_2Flang_2FObject_3B>> 1 (dread ref %Reg0_R562)), constval u32 272)), dread ref %Reg0_R562, dread i32 %Reg1_I) {} #INSTIDX : 22||0016: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg4_R43700, dread ref %Reg0_R562) return () } func &LThreadTest_24SecondThread_3B_7C_3Cinit_3E_7C_28_29V constructor (var %_this <* <$LThreadTest_24SecondThread_3B>>) void { funcid 48158 var %Reg1_R43702 <* <$LThreadTest_24SecondThread_3B>> localrefvar var %Reg1_R1610 <* <$Ljava_2Flang_2FThread_3B>> localrefvar var %__muid_symptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg1_R43702) dassign %Reg1_R43702 0 (dread ref %_this) #INSTIDX : 0||0000: aload_0 #INSTIDX : 1||0001: invokespecial regassign ptr %1 (dread ref %Reg1_R1610) dassign %Reg1_R1610 0 (retype ref <* <$Ljava_2Flang_2FThread_3B>> (dread ref %Reg1_R43702)) intrinsiccall MCCIncRef (dread ref %Reg1_R1610) intrinsiccall MCCDecRef (regread ptr %1) #Call function:Ljava_2Flang_2FThread_3B_7C_3Cinit_3E_7C_28_29V dassign %__muid_symptr 0 (iread ptr <* <$MUIDUnifiedUndefTabEntry>> 1 (array 0 ptr <* <[48] <$MUIDUnifiedUndefTabEntry>>> (addrof ptr $__muid_func_undef_tab$$ThreadTest_jar, constval i64 30))) icallassigned (dread ptr %__muid_symptr, dread ref %Reg1_R1610) {} #INSTIDX : 4||0004: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg1_R43702, dread ref %Reg1_R1610) return () } func &LThreadTest_24SecondThread_3B_7Crun_7C_28_29V public virtual (var %_this <* <$LThreadTest_24SecondThread_3B>>) void { funcid 48159 var %Reg2_R43702 <* <$LThreadTest_24SecondThread_3B>> localrefvar var %Reg0_I i32 var %Reg0_J i64 var %__muid_funcptr <* void> intrinsiccall MCCIncRef (dread ref %_this) intrinsiccall MCCDecRef (dread ref %Reg2_R43702) dassign %Reg2_R43702 0 (dread ref %_this) #INSTIDX : 0||0000: bipush dassign %Reg0_I 0 (constval i32 42) #INSTIDX : 2||0002: putstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_3B) #Assign to: LThreadTest_3B_7Cnumber dassign %__muid_funcptr 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 1))) iassign <* i32> 0 (dread ptr %__muid_funcptr, dread i32 %Reg0_I) #INSTIDX : 5||0005: ldc2_w dassign %Reg0_J 0 (constval i64 0x7fffffffffffffff) #INSTIDX : 8||0008: putstatic intrinsiccall MPL_CLINIT_CHECK (addrof ptr $__cinf_LThreadTest_3B) #Assign to: LThreadTest_3B_7Cflag dassign %__muid_funcptr 0 (iread ptr <* <$MUIDDataDefTabEntry>> 1 (array 0 ptr <* <[5] <$MUIDDataDefTabEntry>>> (addrof ptr $__muid_data_def_tab$$ThreadTest_jar, constval i64 0))) iassign <* i64> 0 (dread ptr %__muid_funcptr, dread i64 %Reg0_J) #INSTIDX : 11||000b: return intrinsiccall MPL_CLEANUP_LOCALREFVARS (dread ref %Reg2_R43702) return () }
import FOL.lindenbaum data.set.basic universes u v namespace fol open_locale logic_symbol open formula term variables {L L₁ L₂ L₃ : language.{u}} namespace language protected def pempty : language.{u} := ⟨λ n, pempty, λ n, pempty⟩ instance : has_emptyc (language.{u}) := ⟨fol.language.pempty⟩ @[simp] lemma pempty_fn_def (n) : (∅ : language.{u}).fn n = pempty := rfl @[simp] lemma pempty_pr_def (n) : (∅ : language.{u}).pr n = pempty := rfl structure language_translation (L₁ : language) (L₂ : language) := (fn : Π n, L₁.fn n → L₂.fn n) (pr : Π n, L₁.pr n → L₂.pr n) infix ` ↝ᴸ `:25 := language_translation structure language_equiv (L₁ : language) (L₂ : language) := (ltr : L₁ ↝ᴸ L₂) (inv : L₂ ↝ᴸ L₁) (left_inv_fn : ∀ n, function.left_inverse (inv.fn n) (ltr.fn n)) (left_inv_pr : ∀ n, function.left_inverse (inv.pr n) (ltr.pr n)) (right_inv_fn : ∀ n, function.right_inverse (inv.fn n) (ltr.fn n)) (right_inv_pr : ∀ n, function.right_inverse (inv.pr n) (ltr.pr n)) infix ` ↭ᴸ `:25 := language_equiv class language_translation_coe (L₁ : language) (L₂ : language) := (ltr : L₁ ↝ᴸ L₂) (fn_inj : ∀ n (f g : L₁.fn n), ltr.fn n f = ltr.fn n g → f = g) (pr_inj : ∀ n (p q : L₁.pr n), ltr.pr n p = ltr.pr n q → p = q) class has_predecessor (L : language) := (pred : language) (ltc : language_translation_coe pred L) class synonym (L₁ L₂ : language) (leq : L₁ ↭ᴸ L₂) structure formula_homomorphism (L₁ : language) (L₂ : language.{v}) := (to_fun : ℕ → formula L₁ → formula L₂) (map_verum : ∀ i, to_fun i ⊤ = ⊤) (map_imply : ∀ (p q : formula L₁) (i : ℕ), to_fun i (p ⟶ q) = to_fun i p ⟶ to_fun i q) (map_neg : ∀ (p : formula L₁) (i), to_fun i (∼p) = ∼to_fun i p) (map_univ : ∀ (p : formula L₁) (i), to_fun i (∀.p) = ∀.to_fun (i + 1) p) structure translation (L₁ : language) (L₂ : language.{v}) extends formula_homomorphism L₁ L₂ := (map_pow : ∀ (p : formula L₁) (i), to_fun (i + 1) (p^1) = (to_fun i p)^1) infix ` ↝ `:25 := translation instance {L₁ L₂ : language} : has_coe_to_fun (formula_homomorphism L₁ L₂) (λ _, ℕ → formula L₁ → formula L₂) := ⟨@formula_homomorphism.to_fun L₁ L₂⟩ instance {L₁ L₂ : language} : has_coe_to_fun (translation L₁ L₂) (λ _, ℕ → formula L₁ → formula L₂) := ⟨λ τ, @formula_homomorphism.to_fun L₁ L₂ τ.to_formula_homomorphism⟩ structure term_homomorphism (L₁ : language) (L₂ : language) := (to_fun_chr : ℕ → Π {n}, L₁.fn n → finitary (term L₂) n → term L₂) (to_fun : ℕ → term L₁ → term L₂) (map_fn : Π (k : ℕ) {n} (f : L₁.fn n) (v : finitary (term L₁) n), to_fun k (term.app f v) = to_fun_chr k f (λ i, to_fun k (v i))) infix ` ↝ᵀ `:25 := term_homomorphism instance {L₁ L₂ : language} : has_coe_to_fun (term_homomorphism L₁ L₂) (λ _, ℕ → term L₁ → term L₂) := ⟨λ τ, τ.to_fun⟩ structure term_formula_translation (L₁ : language) (L₂ : language) := (p : translation L₁ L₂) (t : ℕ → term L₁ → term L₂) (chr : Π {n} (r : L₁.pr n), L₂.pr n) (equal : ∀ (t₁ t₂ : term L₁) (k), p k (t₁ =' t₂ : formula L₁) = (t k t₁ =' t k t₂)) (app : ∀ (k) {n} (r : L₁.pr n) (v), p k (app r v) = app (chr r) (λ i, t k (v i))) (map_pow : ∀ u s, t (s + 1) (u^1) = (t s u)^1) def tr_Theory {L₁ L₂ : language} (τ : translation L₁ L₂) (i) (T : Theory L₁) : Theory L₂ := τ i '' T @[simp] lemma mem_Theory_tr_of_mem {L₁ L₂ : language} {τ : translation L₁ L₂} {i} {T : Theory L₁} {p} (mem : p ∈ T) : τ i p ∈ tr_Theory τ i T := ⟨p, mem, rfl⟩ class translation.conservative (τ : translation L₁ L₂) := (ax : ℕ → Theory L₁ → Theory L₂ := tr_Theory τ) (ax_ss : ∀ T k, tr_Theory τ k T ⊆ ax k T) (specialize : ∀ (k) (p : formula L₁) (t : term L₁) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (∀.p ⟶ p.rew ı[0 ⇝ t])) (eq_reflexivity : ∀ (k) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (∀.(#0 =' #0))) (eq_symmetry : ∀ (k) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (∀.∀.((#0 =' #1) ⟶ (#1 =' #0)))) (eq_transitive : ∀ (k) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (∀.∀.∀.((#0 =' #1) ⟶ (#1 =' #2) ⟶ (#0 =' #2)))) (function_ext : ∀ (k) {n} (f : L₁.fn n) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (eq_axiom4 f)) (predicate_ext : ∀ (k) {n} (r : L₁.pr n) (T : Theory L₁) (i : ℕ), (ax k T)^i ⊢ τ (k + i) (eq_axiom5 r)) namespace formula_homonorphism variables (τ : formula_homomorphism L₁ L₂) (i : ℕ) @[simp] lemma map_verum' : τ i ⊤ = ⊤ := τ.map_verum i @[simp] lemma map_imply' (p q : formula L₁) : τ i (p ⟶ q) = τ i p ⟶ τ i q := τ.map_imply p q i @[simp] lemma map_neg' (p : formula L₁) : τ i (∼p) = ∼τ i p := τ.map_neg p i @[simp] lemma map_univ' (p : formula L₁) : τ i (∀.p) = ∀.τ (i + 1) p := τ.map_univ p i lemma map_pow'_aux (H_pr : ∀ {n} (r : L₁.pr n) (v) (i s k : ℕ) (le : s ≤ i), τ (i + k) ((app r v).rew ((λ x, #(x + k))^s)) = (τ i (app r v)).rew ((λ x, #(x + k))^s)) (H_eq : ∀ (t u : term L₁) (i s k : ℕ) (le : s ≤ i), τ (i + k) ((t =' u : formula L₁).rew ((λ x, #(x + k))^s)) = (τ i (t =' u)).rew ((λ x, #(x + k))^s)) (p : formula L₁) (i s k : ℕ) (hs : s ≤ i) : τ (i + k) (p.rew ((λ x, #(x + k))^s)) = (τ i p).rew ((λ x, #(x + k))^s) := begin induction p generalizing i s k, case app : n r v { exact H_pr r v i s k hs }, case equal : t u i s k { exact H_eq t u i s k hs }, case verum { simp }, case imply : p q IH_p IH_q { simp, exact ⟨IH_p i s k hs, IH_q i s k hs⟩ }, case neg : p IH { simp, exact IH i s k hs}, case fal : p IH { simp[rewriting_sf_itr.pow_add, show i + k + 1 = i + 1 + k, by omega], exact IH (i + 1) (s + 1) k (by simp[hs]) } end def mk_translation (H_pr : ∀ {n} (r : L₁.pr n) (v) (i s k : ℕ) (le : s ≤ i), τ (i + k) ((app r v).rew ((λ x, #(x + k))^s)) = (τ i (app r v)).rew ((λ x, #(x + k))^s)) (H_eq : ∀ (t u : term L₁) (i s k : ℕ) (le : s ≤ i), τ (i + k) ((t =' u : formula L₁).rew ((λ x, #(x + k))^s)) = (τ i (t =' u)).rew ((λ x, #(x + k))^s)) : translation L₁ L₂ := { map_pow := λ p i, by { simp, have : τ (i + 1) (p.rew (λ x, #(x + 1))) = rew (λ x, #(x + 1)) (τ i p), { have := map_pow'_aux τ (@H_pr) (@H_eq) p i 0 1 (by simp), simp at this, exact this }, simp[formula.pow_eq], exact this }, ..τ } end formula_homonorphism namespace translation @[simp] lemma app_eq (to_fun) (map_verum) (map_imply) (map_neg) (map_univ) (map_pow) (p : formula L₁) (i) : ({ to_fun := to_fun, map_verum := map_verum, map_imply := map_imply, map_neg := map_neg, map_univ := map_univ, map_pow := map_pow} : translation L₁ L₂) i p = to_fun i p := rfl @[simp] def fun_of_atom {L₁ L₂ : language} (tr_pr : ℕ → Π {n}, L₁.pr n → finitary (term L₁) n → formula L₂) (tr_eq : ℕ → term L₁ → term L₁ → formula L₂) : ℕ → formula L₁ → formula L₂ | k ⊤ := ⊤ | k (app p v) := tr_pr k p v | k ((t : term L₁) =' u) := tr_eq k t u | k (p ⟶ q) := fun_of_atom k p ⟶ fun_of_atom k q | k (∼p) := ∼fun_of_atom k p | k (∀.(p : formula L₁)) := ∀.fun_of_atom (k + 1) p def mk_of_atom' {L₁ L₂ : language} (tr_pr : ℕ → Π {n}, L₁.pr n → finitary (term L₁) n → formula L₂) (tr_eq : ℕ → term L₁ → term L₁ → formula L₂) (map_pow : ∀ (p : formula L₁) (k : ℕ), fun_of_atom @tr_pr @tr_eq (k + 1) (p^1) = (fun_of_atom @tr_pr @tr_eq k p)^1) : translation L₁ L₂ := { to_fun := fun_of_atom @tr_pr @tr_eq, map_verum := by simp, map_imply := by simp, map_neg := by simp, map_univ := by simp, map_pow := map_pow } variables (τ : translation L₁ L₂) (i : ℕ) @[simp] lemma map_verum' : τ i ⊤ = ⊤ := τ.map_verum i @[simp] lemma map_imply' (p q : formula L₁) : τ i (p ⟶ q) = τ i p ⟶ τ i q := τ.map_imply p q i @[simp] lemma map_neg' (p : formula L₁) : τ i (∼p) = ∼τ i p := τ.map_neg p i @[simp] lemma map_univ' (p : formula L₁) : τ i (∀.p) = ∀.τ (i + 1) p := τ.map_univ p i lemma map_pow' (p : formula L₁) (k : ℕ) : τ (i + k) (p^k) = (τ i p)^k := by { induction k with k IH; simp[←nat.add_one, ←add_assoc], have : τ (i + k + 1) (p^(k + 1)) = τ (i + k) (p^k)^1, simp[←formula.pow_add], from map_pow τ (p^k) (i + k), simp[IH, formula.pow_add] at this, exact this } @[simp] lemma map_falsum' : τ i ⊥ = ⊥ := by { unfold has_bot.bot, simp } @[simp] lemma map_ex' (p : formula L₁) : τ i (∃.p) = ∃.(τ (i + 1) p) := by { unfold has_exists_quantifier.ex formula.ex, simp } @[simp] lemma map_and' (p q : formula L₁) : τ i (p ⊓ q) = τ i p ⊓ τ i q := by { unfold has_inf.inf formula.and, simp } @[simp] lemma map_or' (p q : formula L₁) : τ i (p ⊔ q) = τ i p ⊔ τ i q := by { unfold has_sup.sup formula.or, simp } @[simp] lemma map_equiv' (p q : formula L₁) : τ i (p ⟷ q) = τ i p ⟷ τ i q := by simp[lrarrow_def] @[simp] lemma map_nfal' (p : formula L₁) (k : ℕ) : τ i (∀.[k] p) = ∀.[k] τ (i + k) p := by { induction k with k IH generalizing i; simp[*], { simp[show i + k.succ = i + 1 + k, by omega] } } @[simp] lemma map_conjunction'' {n} (P : finitary (formula L₁) n) : τ i (⋀ j, P j) = ⋀ j, (τ i (P j)) := by { induction n with n IH generalizing P; simp* } @[simp] lemma map_disjunction'' {n} (P : finitary (formula L₁) n) : τ i (⋁ j, P j) = ⋁ j, (τ i (P j)) := by { induction n with n IH generalizing P; simp* } variables (L₁) (L₂) (L₃) protected def refl : translation L₁ L₁ := { to_fun := λ _, id, map_verum := by simp, map_imply := by simp, map_neg := by simp, map_univ := by simp, map_pow := by simp } def shift (k : ℕ) : translation L₁ L₁ := { to_fun := λ i p, p.rew (λ x, if x < i then #x else #(x + k)), map_verum := by simp, map_imply := by simp, map_neg := by simp, map_univ := λ p i, by { simp[rewriting_sf_itr.pow_eq], congr, funext x, cases x; simp[←nat.add_one], by_cases C : x < i; simp[C], omega }, map_pow := λ p i, by { simp[formula.pow_eq, formula.nested_rew], congr, funext x, by_cases C : x < i; simp[C], omega } } variables {L₁} {L₂} {L₃} def comp : translation L₂ L₃ → translation L₁ L₂ → translation L₁ L₃ := λ τ₂₃ τ₁₂, { to_fun := λ i, τ₂₃ i ∘ τ₁₂ i, map_verum := by simp, map_imply := by simp, map_neg := by simp, map_univ := by simp, map_pow := by simp[map_pow'] } end translation namespace term_homomorphism @[simp] lemma translation.map_imply' (τ : term_homomorphism L₁ L₂) {n} (f : L₁.fn n) (v : finitary (term L₁) n) (k) : τ k (term.app f v) = τ.to_fun_chr k f (λ i, τ k (v i)) := τ.map_fn k f v @[simp] lemma app_eq (fc) (f) (map_fn) (t : term L₁) (i) : ({to_fun_chr := fc, to_fun := f, map_fn := map_fn} : term_homomorphism L₁ L₂) i t = f i t := rfl @[simp] def mk_fun_of_atom {L₁ L₂ : language} (to_fun_chr : ℕ → Π {n}, L₁.fn n → finitary (term L₂) n → term L₂) : ℕ → term L₁ → term L₂ | _ #n := #n | k (app f v) := to_fun_chr k f (λ i, mk_fun_of_atom k (v i)) @[simp] def mk_of_atom {L₁ L₂ : language} (to_fun_chr : ℕ → Π {n}, L₁.fn n → finitary (term L₂) n → term L₂) : term_homomorphism L₁ L₂ := { to_fun_chr := @to_fun_chr, to_fun := mk_fun_of_atom @to_fun_chr, map_fn := by simp } end term_homomorphism namespace term_formula_translation open translation variables (τ : term_formula_translation L₁ L₂) (k : ℕ) @[simp] lemma map_equal (t₁ t₂ : term L₁) : τ.p k (t₁ =' t₂ : formula L₁) = (τ.t k t₁ =' τ.t k t₂) := τ.equal t₁ t₂ k @[simp] lemma map_app {n} (r : L₁.pr n) (v) : τ.p k (formula.app r v) = formula.app (τ.chr r) (λ i, τ.t k (v i)) := τ.app k r v lemma map_pow' (t : term L₁) (k s : ℕ) : τ.t (k + s) (t^s) = (τ.t k t)^s := by { induction s with s IH; simp[←nat.add_one, ←add_assoc], have : τ.t (k + s + 1) ((t ^ s) ^ 1) = τ.t (k + s) (t ^ s) ^ 1, from map_pow τ (t^s) (k + s), simp[IH, term.pow_add] at this, exact this } lemma tr_subst_of_subst (H : ∀ (t u : term L₁) (s m : ℕ) (le : m ≤ s), τ.t s (t.rew ı[m ⇝ u]) = (τ.t (s + 1) t).rew ı[m ⇝ τ.t s u]) (p : formula L₁) (t : term L₁) (s m : ℕ) (le : m ≤ s) : τ.p s (p.rew ı[m ⇝ t]) = (τ.p (s + 1) p).rew ı[m ⇝ τ.t s t] := begin induction p generalizing t s m, case app : n r v { simp, funext i, exact H (v i) t s m le }, case equal : u₁ u₂ { simp, exact ⟨H u₁ t s m le, H u₂ t s m le⟩ }, case verum { simp }, case imply : p q IH_p IH_q { simp, exact ⟨IH_p t s m le, IH_q t s m le⟩ }, case neg : p IH { simp, exact IH t s m le }, case fal : p IH { simp[subst_pow, ←map_pow'], exact IH (t^1) (s + 1) (m + 1) (by simp[le]) }, end open provable axiomatic_classical_logic axiomatic_classical_logic' def conservative_of (H : ∀ (t u : term L₁) (s m) (le : m ≤ s), τ.t s (t.rew ı[m ⇝ u]) = (τ.t (s + 1) t).rew ı[m ⇝ τ.t s u]) (function_ext : ∀ (s) {n} (f : L₁.fn n) (T : Theory L₁) (k : ℕ), (tr_Theory τ.p s T)^k ⊢ τ.p (s + k) (eq_axiom4 f)) (predicate_ext : ∀ (s) {n} (r : L₁.pr n) (T : Theory L₁) (k : ℕ), (tr_Theory τ.p s T)^k ⊢ τ.p (s + k) (eq_axiom5 r)) : conservative τ.p := { ax_ss := λ _ _, by refl, specialize := λ s p t T k, by simp[tr_subst_of_subst τ H], eq_reflexivity := λ s T k, by { simp, refine generalize (by simp) }, eq_symmetry := λ s T k, by { simp, refine generalize (generalize _), have : ⤊⤊(tr_Theory τ.p s T ^ k) ⊢ _, from eq_symmetry ⊚ (τ.t (s + k + 1 + 1) #1) ⊚ τ.t (s + k + 1 + 1) #0, simp at this, simp at this, exact this }, eq_transitive := λ s T k, by { simp, refine generalize (generalize (generalize _)), have : ⤊⤊⤊(tr_Theory τ.p s T ^ k) ⊢ _, from eq_transitivity ⊚ τ.t (s + k + 1 + 1 + 1) #2 ⊚ τ.t (s + k + 1 + 1 + 1) #1 ⊚ τ.t (s + k + 1 + 1 + 1) #0, simp at this, simp at this, exact this }, function_ext := λ s n f T k, by { exact function_ext s f T k }, predicate_ext := λ s n f T k, by { exact predicate_ext s f T k } } end term_formula_translation namespace language_translation lemma mk.eta : Π (τ : L₁ ↝ᴸ L₂), ({fn := τ.fn, pr := τ.pr} : L₁ ↝ᴸ L₂) = τ | ⟨fn, pr⟩ := rfl lemma eq_iff {τ σ : L₁ ↝ᴸ L₂} : τ = σ ↔ (∀ n f, τ.fn n f = σ.fn n f) ∧ (∀ n r, τ.pr n r = σ.pr n r) := by { rw[←mk.eta τ, ←mk.eta σ], simp, split, { rintros ⟨eq_fn, eq_pr⟩, simp* }, { rintros ⟨hfn, hpr⟩, refine ⟨_, _⟩; { funext, simp* } } } @[ext] lemma ext {τ σ : L₁ ↝ᴸ L₂} (eq_fn : ∀ n f, τ.fn n f = σ.fn n f) (eq_pr : ∀ n r, τ.pr n r = σ.pr n r) : τ = σ := by { simp[eq_iff], exact ⟨eq_fn, eq_pr⟩ } def from_empty : ∅ ↝ᴸ L := { fn := λ n f, by rcases f, pr := λ n r, by rcases r } def one (L : language) : L ↝ᴸ L := { fn := λ n, id, pr := λ n, id } instance : has_one (L ↝ᴸ L) := ⟨one L⟩ def comp : L₂ ↝ᴸ L₃ → L₁ ↝ᴸ L₂ → L₁ ↝ᴸ L₃ := λ τ₂₃ τ₁₂, { fn := λ n, (τ₂₃.fn n) ∘ (τ₁₂.fn n), pr := λ n, (τ₂₃.pr n) ∘ (τ₁₂.pr n) } variables (τ : L₁ ↝ᴸ L₂) @[simp] def fun_t : term L₁ → term L₂ | #n := #n | (app f v) := app (τ.fn _ f) (λ i, fun_t (v i)) def tr_term : term_homomorphism L₁ L₂ := { to_fun_chr := λ k n f v, app (τ.fn _ f) v, to_fun := λ k, τ.fun_t, map_fn := λ k n f v, by simp } @[simp] def fun_p : formula L₁ → formula L₂ | ⊤ := ⊤ | (app p v) := app (τ.pr _ p) (λ i, fun_t τ (v i)) | ((t : term L₁) =' u) := fun_t τ t =' fun_t τ u | (p ⟶ q) := fun_p p ⟶ fun_p q | (∼p) := ∼fun_p p | (∀.(p : formula L₁)) := ∀.fun_p p def fun_Theory (T : Theory L₁) : Theory L₂ := τ.fun_p '' T lemma fun_t_rew_var : ∀ (t : term L₁) (s : ℕ → ℕ), (fun_t τ t).rew (λ x, #(s x)) = fun_t τ (t.rew (λ x, #(s x))) | (#n) s := by simp | (@term.app _ n f v) s := by { simp, funext i, exact @fun_t_rew_var (v i) _ } lemma fun_p_rew_var : ∀ (p : formula L₁) (s : ℕ → ℕ), (fun_p τ p).rew (λ x, #(s x)) = fun_p τ (p.rew (λ x, #(s x))) | ⊤ _ := by simp | (@formula.app _ n r v) s := by { simp, funext i, simp[fun_t_rew_var] } | ((t : term L₁) =' u) s := by simp[fun_t_rew_var] | (p ⟶ q) s := by simp[fun_p_rew_var p, fun_p_rew_var q] | (∼p) s := by simp[fun_p_rew_var p] | (∀.(p : formula L₁)) s := by { have eqn₁ : ((λ x, #(s x))^1 : ℕ → term L₁) = (λ x, #(if x = 0 then 0 else s (x - 1) + 1)), { funext x, cases x; simp }, have eqn₂ : ((λ x, #(s x))^1 : ℕ → term L₂) = (λ x, #(if x = 0 then 0 else s (x - 1) + 1)), { funext x, cases x; simp }, simp[fal_pow, eqn₁, eqn₂, fun_p_rew_var p] } def tr : translation L₁ L₂ := { to_fun := λ _, τ.fun_p, map_verum := by simp, map_imply := by simp, map_neg := by simp, map_univ := by simp, map_pow := λ p i, eq.symm (τ.fun_p_rew_var p (λ x, x + 1)) } @[simp] lemma fun_t_arity (t : term L₁) : (τ.fun_t t).arity = t.arity := by induction t; simp* @[simp] lemma fun_p_arity (p : formula L₁) : (τ.fun_p p).arity = p.arity := by induction p; simp* lemma tr_term_app_eq (k) (t) : τ.tr_term k t = τ.fun_t t := by refl lemma tr_app_eq (k) (p) : τ.tr k p = τ.fun_p p := by refl @[simp] lemma tr_term_to_fun_chr_app_eq (k) {n} (f : L₁.fn n) (v : finitary (term L₂) n) : τ.tr_term.to_fun_chr k f v = app (τ.fn _ f) v := rfl @[simp] lemma fun_t_pow (t : term L₁) (i : ℕ) : (τ.fun_t (t^i) : term L₂) = (τ.fun_t t)^i := eq.symm (τ.fun_t_rew_var t (λ x, x + i)) @[simp] lemma fun_p_pow (p : formula L₁) (i : ℕ) : (τ.fun_p (p^i) : formula L₂) = (τ.fun_p p)^i := eq.symm (τ.fun_p_rew_var p (λ x, x + i)) @[simp] lemma fun_p_and (p q : formula L₁) : τ.fun_p (p ⊓ q) = τ.fun_p p ⊓ τ.fun_p q := rfl @[simp] lemma fun_p_or (p q : formula L₁) : τ.fun_p (p ⊔ q) = τ.fun_p p ⊔ τ.fun_p q := rfl @[simp] lemma fun_p_ex (p : formula L₁) : τ.fun_p (∃.p) = ∃.τ.fun_p p := rfl @[simp] lemma fun_p_bot : τ.fun_p (⊥ : formula L₁) = ⊥ := rfl @[simp] lemma fun_p_conjunction (P : list (formula L₁)) : τ.fun_p P.conjunction = list.conjunction (P.map τ.fun_p) := by induction P with p P IH; simp[*] @[simp] lemma fun_p_nfal (p : formula L₁) (k : ℕ) : τ.fun_p (∀.[k] p) = ∀.[k] τ.fun_p p := by { induction k with k IH; simp[*] } @[simp] lemma fun_p_fal_complete (p : formula L₁) : τ.fun_p (∀.* p) = ∀.* τ.fun_p p := by simp[fal_complete] @[simp] lemma fun_p_conjunction' {n : ℕ} (P : finitary (formula L₁) n) : τ.fun_p (⋀ j, P j) = ⋀ j, τ.fun_p (P j) := by { induction n with n IH generalizing P; simp* } @[simp] lemma fun_p_disjunction' {n : ℕ} (P : finitary (formula L₁) n) : τ.fun_p (⋁ j, P j) = ⋁ j, τ.fun_p (P j) := by { induction n with n IH generalizing P; simp* } lemma fun_t_rew : ∀ (t : term L₁) (s : ℕ → term L₁), τ.fun_t (t.rew s) = (τ.fun_t t).rew (λ x, τ.fun_t (s x)) | (#x) s := by simp | (term.app p v) s := by simp[λ i, fun_t_rew (v i)] @[simp] lemma fun_t_subst (t u : term L₁) (s) : τ.fun_t (t.rew ı[s ⇝ u]) = (τ.fun_t t).rew ı[s ⇝ τ.fun_t u] := begin have : (λ x, τ.fun_t (ı[s ⇝ u] x)) = ı[s ⇝ τ.fun_t u], { funext x, have : x < s ∨ x = s ∨ s < x, exact trichotomous x s, rcases this with (lt | rfl | lt); simp* }, simp[fun_t_rew, this] end lemma fun_p_rew : ∀ (p : formula L₁) (s : ℕ → term L₁), τ.fun_p (p.rew s) = (τ.fun_p p).rew (λ x, τ.fun_t (s x)) | ⊤ s := by simp | (formula.app f v) s := by simp[fun_t_rew] | (t =' u) s := by simp[fun_t_rew] | (p ⟶ q) s := by simp[fun_p_rew p, fun_p_rew q] | (∼p) s := by simp[fun_p_rew p] | (∀.p) s := by { simp[fun_p_rew p, rewriting_sf_itr.pow_eq'], congr, funext x, cases x; simp } @[simp] lemma fun_p_subst (p : formula L₁) (u : term L₁) (s) : τ.fun_p (p.rew ı[s ⇝ u]) = (τ.fun_p p).rew ı[s ⇝ τ.fun_t u] := begin have : (λ x, τ.fun_t (ı[s ⇝ u] x)) = ı[s ⇝ τ.fun_t u], { funext x, have : x < s ∨ x = s ∨ s < x, exact trichotomous x s, rcases this with (lt | rfl | lt); simp* }, simp[fun_p_rew, this] end lemma fun_t_inversion_of_le {t₁ : term L₁} {u₂ : term L₂} (le : u₂ ≤ τ.fun_t t₁) : ∃ (u₁ : term L₁) (le : u₁ ≤ t₁), u₂ = τ.fun_t u₁ := begin induction t₁ generalizing u₂, case var : n { simp at le, refine ⟨#n, by simp[le]⟩ }, case app : n f v IH { rcases le_iff_lt_or_eq.mp le with (lt | rfl), { simp at lt, rcases lt with ⟨i, le⟩, rcases IH i le with ⟨t, t_le', rfl⟩, refine ⟨t, le_trans t_le' (by simp), rfl⟩ }, { refine ⟨app f v, by refl, rfl⟩ } } end lemma fun_p_inversion_of_le {p₁ : formula L₁} {q₂ : formula L₂} (le : q₂ ≤ τ.fun_p p₁) : ∃ (q₁ : formula L₁) (le : q₁ ≤ p₁), q₂ = τ.fun_p q₁ := begin induction p₁ generalizing q₂, case app : n r v { simp at le, refine ⟨app r v, by simp[le]⟩ }, case equal : t u { simp at le, refine ⟨t =' u, by simp[le]⟩ }, case verum { simp at le, refine ⟨⊤, by simp[le]⟩ }, case imply : p q IH_p IH_q { rcases le_iff_lt_or_eq.mp le with (lt | rfl), { simp at lt, rcases lt with (le | le), { rcases IH_p le with ⟨q₁, le', rfl⟩, refine ⟨q₁, le_trans le' (le_of_lt (by simp)), rfl⟩ }, { rcases IH_q le with ⟨q₁, le', rfl⟩, refine ⟨q₁, le_trans le' (le_of_lt (by simp)), rfl⟩ } }, { refine ⟨p ⟶ q, by simp⟩ } }, case neg : p IH { rcases le_iff_lt_or_eq.mp le with (lt | rfl), { simp at lt, rcases IH lt with ⟨q₁, le', rfl⟩, refine ⟨q₁, le_trans le' (le_of_lt (by simp)), rfl⟩ }, { refine ⟨∼p, by simp⟩ } }, case fal : p IH { rcases le_iff_lt_or_eq.mp le with (lt | rfl), { simp at lt, rcases IH lt with ⟨q₁, le', rfl⟩, refine ⟨q₁, le_trans le' (le_of_lt (by simp)), rfl⟩ }, { refine ⟨∀.p, by simp⟩ } }, end lemma fun_p_inversion_of_mem {p₁ : formula L₁} {t₂ : term L₂} (mem : t₂ ∈ τ.fun_p p₁) : ∃ (t₁ : term L₁) (mem : t₁ ∈ p₁), t₂ = τ.fun_t t₁ := begin induction p₁ generalizing t₂, case app : n r v { simp at mem, rcases mem with ⟨i, le⟩, rcases fun_t_inversion_of_le τ le with ⟨t₁, le', rfl⟩, refine ⟨t₁, by simp; exact ⟨i, le'⟩, rfl⟩ }, case equal : t u { simp at mem, rcases mem with (le | le), { rcases fun_t_inversion_of_le τ le with ⟨t₁, le', rfl⟩, refine ⟨t₁, by simp[le'], rfl⟩ }, { rcases fun_t_inversion_of_le τ le with ⟨t₁, le', rfl⟩, refine ⟨t₁, by simp[le'], rfl⟩ } }, case verum { simp at mem, contradiction }, case imply : p q IH_p IH_q { simp at mem, rcases mem with (mem | mem), { rcases IH_p mem with ⟨t', mem', rfl⟩, refine ⟨t', by simp[mem'], rfl⟩ }, { rcases IH_q mem with ⟨t', mem', rfl⟩, refine ⟨t', by simp[mem'], rfl⟩ } }, case neg : p IH { simp at mem ⊢, rcases IH mem with ⟨t', mem', rfl⟩, refine ⟨t', mem', rfl⟩ }, case fal : p IH { simp at mem ⊢, rcases IH mem with ⟨t', mem', rfl⟩, refine ⟨t', mem', rfl⟩ } end variables (τ₁₂ σ₁₂ : L₁ ↝ᴸ L₂) (τ₂₃ : L₂ ↝ᴸ L₃) {L₄ : language.{u}} (τ₃₄ : L₃ ↝ᴸ L₄) @[simp] lemma one_fn {n} (f : L.fn n) : fn 1 n f = f := rfl @[simp] lemma one_pr {n} (r : L.pr n) : pr 1 n r = r := rfl @[simp] lemma comp_fn {n} (f : L₁.fn n) : (τ₂₃.comp τ₁₂).fn n f = τ₂₃.fn n (τ₁₂.fn n f) := rfl @[simp] lemma comp_pr {n} (r : L₁.pr n) : (τ₂₃.comp τ₁₂).pr n r = τ₂₃.pr n (τ₁₂.pr n r) := rfl @[simp] lemma one_fun_t (t : term L) : fun_t 1 t = t := by induction t; simp* @[simp] lemma one_fun_p (p : formula L) : fun_p 1 p = p := by induction p; simp* lemma comp_fun_t : (τ₂₃.comp τ₁₂).fun_t = τ₂₃.fun_t ∘ τ₁₂.fun_t := by funext t; induction t; simp* lemma comp_fun_p : (τ₂₃.comp τ₁₂).fun_p = τ₂₃.fun_p ∘ τ₁₂.fun_p := by funext p; induction p; simp[*, comp_fun_t] lemma comp_fun_Theory : (τ₂₃.comp τ₁₂).fun_Theory = τ₂₃.fun_Theory ∘ τ₁₂.fun_Theory := by ext q; simp[fun_Theory, comp_fun_p] @[simp] lemma comp_one : τ.comp 1 = τ := by ext; simp @[simp] lemma one_comp : comp 1 τ = τ := by ext; simp @[simp] lemma comp_assoc : (τ₃₄.comp τ₂₃).comp τ₁₂ = τ₃₄.comp (τ₂₃.comp τ₁₂) := by ext; simp @[simp] lemma fun_p_is_sentence (p : formula L₁) : is_sentence (τ.fun_p p) ↔ is_sentence p := by simp[is_sentence] variables (T : Theory L₁) instance [closed_Theory T] : closed_Theory (τ.fun_Theory T) := ⟨λ p mem, by { rcases mem with ⟨p, mem, rfl⟩, simp[closed_Theory.cl mem] }⟩ lemma fun_Theory_insert (p : formula L₁) : τ.fun_Theory (T+{p}) = τ.fun_Theory T +{τ.fun_p p} := set.image_insert_eq end language_translation namespace has_predecessor variables {L} [has_predecessor L] end has_predecessor namespace language_translation_coe open language_translation instance : language_translation_coe ∅ L := {ltr := from_empty, fn_inj := λ n f g, by rcases f, pr_inj := λ n r s, by rcases r } instance coe_one : language_translation_coe L L := {ltr := 1, fn_inj := λ n f g, by simp, pr_inj := λ n r s, by simp } section variables [language_translation_coe L₁ L₂] instance {n} : has_coe (L₁.fn n) (L₂.fn n) := ⟨λ f, ltr.fn n f⟩ lemma coe_fn_def {n} (f : L₁.fn n) : (↑f : L₂.fn n) = ltr.fn n f := rfl instance {n} : has_coe (L₁.pr n) (L₂.pr n) := ⟨λ n, ltr.pr _ n⟩ lemma coe_pr_def {n} (r : L₁.pr n) : (↑r : L₂.pr n) = ltr.pr n r := rfl instance : has_coe (term L₁) (term L₂) := ⟨ltr.fun_t⟩ lemma coe_t_def (t : term L₁) : (↑t : term L₂) = ltr.fun_t t := rfl lemma app_term_extension_eq (t : term L₁) (i : ℕ) : (ltr.tr_term i t : term L₂) = ↑t := rfl instance : has_coe (formula L₁) (formula L₂) := ⟨ltr.fun_p⟩ lemma coe_p_def (p : formula L₁) : (↑p : formula L₂) = ltr.fun_p p := rfl lemma app_formula_extension_eq (p : formula L₁) (i : ℕ) : (ltr.tr i p : formula L₂) = ↑p := rfl lemma coe_def_p (p : formula L₁) : (↑p : formula L₂) = ltr.fun_p p := rfl instance : has_coe (Theory L₁) (Theory L₂) := ⟨tr_Theory ltr.tr 0⟩ instance zero [has_zero_symbol L₁] : has_zero_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).fn _ has_zero_symbol.zero⟩ instance succ [has_succ_symbol L₁] : has_succ_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).fn _ has_succ_symbol.succ⟩ instance add [has_add_symbol L₁] : has_add_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).fn _ has_add_symbol.add⟩ instance mul [has_mul_symbol L₁] : has_mul_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).fn _ has_mul_symbol.mul⟩ instance le [has_le_symbol L₁] : has_le_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).pr _ has_le_symbol.le⟩ instance mem [has_mem_symbol L₁] : has_mem_symbol L₂ := ⟨(ltr : L₁ ↝ᴸ L₂).pr _ has_mem_symbol.mem⟩ lemma app_formula_extension_eq_coe (k) (p : formula L₁) : (ltr.tr : L₁ ↝ L₂) k p = ↑p := rfl lemma app_term_extension_eq_coe (k) (t : term L₁) : (ltr.tr_term : term_homomorphism L₁ L₂) k t = ↑t := rfl @[simp] lemma add_tr_v1_var (n) : ((#n : term L₁) : term L₂) = #n := rfl lemma add_tr_v1_app {n} (f : L₁.fn n) (v : finitary (term L₁) n) : ((❨f❩ v : term L₁) : term L₂) = ❨↑f❩ (λ i, (v i)) := by refl @[simp] lemma coe_tr_v1_zero [has_zero_symbol L₁] : ((0 : term L₁) : term L₂) = 0 := by { unfold has_zero.zero has_zero_symbol.zero, simp [←app_term_extension_eq_coe 0] } @[simp] lemma coe_tr_v1_succ [has_succ_symbol L₁] (t : term L₁) : ((Succ t : term L₁) : term L₂) = Succ t := by { unfold has_succ.succ, simp [←app_term_extension_eq_coe 0], split, { refl }, { ext; simp } } @[simp] lemma coe_tr_v1_numeral [has_zero_symbol L₁] [has_succ_symbol L₁] (n : ℕ) : ((n˙ : term L₁) : term L₂) = n˙ := by induction n; simp[*, numeral, coe_tr_v1_zero] @[simp] lemma coe_tr_v1_add [has_add_symbol L₁] (t u : term L₁) : ((t + u : term L₁) : term L₂) = t + u := by { unfold has_add.add, simp [←app_term_extension_eq_coe 0], split, { refl }, { ext; simp } } @[simp] lemma coe_tr_v1_mul [has_mul_symbol L₁] (t u : term L₁) : ((t * u : term L₁) : term L₂) = t * u := by { unfold has_mul.mul, simp [←app_term_extension_eq_coe 0], split, { refl }, { ext; simp } } @[simp] lemma coe_tr_v1_le [has_le_symbol L₁] (t u : term L₁) : ((t ≼ u : formula L₁) : formula L₂) = ((t : term L₂) ≼ u) := by { unfold has_preceq.preceq, simp [←app_formula_extension_eq_coe 0, tr_app_eq], split, { refl }, { ext; simp; refl } } @[simp] lemma coe_tr_v1_mem [has_mem_symbol L₁] (t u : term L₁) : ((t ∊ u : formula L₁) : formula L₂) = ((t : term L₂) ∊ u) := by { unfold has_elem.elem, simp [←app_formula_extension_eq_coe 0, tr_app_eq], split, { refl }, { ext; simp; refl } } @[simp] lemma function_inj {n} {f g : L₁.fn n} : (ltr : L₁ ↝ᴸ L₂).fn n f = (ltr : L₁ ↝ᴸ L₂).fn n g ↔ f = g := ⟨by { have := fn_inj, exact this _ f g }, congr_arg _⟩ @[simp] lemma predicate_inj {n} {r s : L₁.pr n} : (ltr : L₁ ↝ᴸ L₂).pr n r = (ltr : L₁ ↝ᴸ L₂).pr n s ↔ r = s := ⟨by { have := pr_inj, exact this _ r s }, congr_arg _⟩ @[simp] lemma function_coe_inj {n} {f g : L₁.fn n} : (f : L₂.fn n) = g ↔ f = g := ⟨by { have := fn_inj, exact this _ f g }, congr_arg _⟩ @[simp] lemma predicate_coe_inj {n} {r s : L₁.pr n} : (r : L₂.pr n) = s ↔ r = s := ⟨by { have := pr_inj, exact this _ r s }, congr_arg _⟩ end variables [language_translation_coe L₁ L₂] @[simp] lemma coe_term_app {i} (f : L₁.fn i) (v : finitary (term L₁) i) : (↑(term.app f v : term L₁) : term L₂) = term.app (f : L₂.fn i) (λ i, v i) := rfl @[simp] lemma coe_term_app_nullary (c : L₁.fn 0) (v : finitary (term L₁) 0) : (↑(term.app c v : term L₁) : term L₂) = term.app (c : L₂.fn 0) finitary.nil := by simp @[simp] lemma coe_term_app_unary (f : L₁.fn 1) (v : finitary (term L₁) 1) : (↑(term.app f v : term L₁) : term L₂) = term.app (f : L₂.fn 1) ‹v 0› := by simp; ext; simp @[simp] lemma coe_term_app_binary (f : L₁.fn 2) (v : finitary (term L₁) 2) : (↑(term.app f v : term L₁) : term L₂) = term.app (f : L₂.fn 2) ‹v 0, v 1› := by simp; ext; simp @[simp] lemma coe_formula_app {i} (p : L₁.pr i) (v : finitary (term L₁) i) : (↑(formula.app p v : formula L₁) : formula L₂) = formula.app (p : L₂.pr i) (λ i, v i) := rfl @[simp] lemma coe_formula_app_nullary (p : L₁.pr 0) (v : finitary (term L₁) 0) : (↑(formula.app p v : formula L₁) : formula L₂) = formula.app (p : L₂.pr 0) finitary.nil := by simp @[simp] lemma coe_formula_app_uniary (p : L₁.pr 1) (v : finitary (term L₁) 1) : (↑(formula.app p v : formula L₁) : formula L₂) = formula.app (p : L₂.pr 1) ‹v 0› := by simp; ext; simp @[simp] lemma coe_formula_app_biary (p : L₁.pr 2) (v : finitary (term L₁) 2) : (↑(formula.app p v : formula L₁) : formula L₂) = formula.app (p : L₂.pr 2) ‹v 0, v 1› := by simp; ext; simp @[simp] lemma coe_equal (t u : term L₁) : (↑(t =' u : formula L₁) : formula L₂) = ((↑t : term L₂) =' ↑u) := rfl @[simp] lemma coe_imply (p q : formula L₁) : (↑(p ⟶ q) : formula L₂) = (↑p ⟶ ↑q) := rfl @[simp] lemma coe_and (p q : formula L₁) : (↑(p ⊓ q) : formula L₂) = (↑p ⊓ ↑q) := rfl @[simp] lemma coe_or (p q : formula L₁) : (↑(p ⊔ q) : formula L₂) = (↑p ⊔ ↑q) := rfl @[simp] lemma coe_neg (p : formula L₁) : (↑(∼p) : formula L₂) = ∼(↑p) := rfl @[simp] lemma coe_equiv (p q : formula L₁) : (↑(p ⟷ q) : formula L₂) = (↑p ⟷ ↑q) := rfl @[simp] lemma coe_pow_term (t : term L₁) (i : ℕ) : (↑(t^i) : term L₂) = (↑t)^i := by simp [tr_term_app_eq, ←app_term_extension_eq_coe 0] @[simp] lemma coe_pow_formula (p : formula L₁) (i : ℕ) : (↑(p^i) : formula L₂) = (↑p)^i := by simp [tr_app_eq, ←app_formula_extension_eq_coe 0] @[simp] lemma coe_fal (p : formula L₁) : (↑(∀.p : formula L₁) : formula L₂) = ∀.(↑p : formula L₂) := rfl @[simp] lemma coe_ex (p : formula L₁) : (↑(∃.p : formula L₁) : formula L₂) = ∃.(↑p : formula L₂) := rfl @[simp] lemma coe_top : (↑(⊤ : formula L₁) : formula L₂) = ⊤ := rfl @[simp] lemma coe_bot : (↑(⊥ : formula L₁) : formula L₂) = ⊥ := rfl @[simp] lemma coe_conjunction (P : list (formula L₁)) : (↑P.conjunction : formula L₂) = list.conjunction (P.map coe) := fun_p_conjunction _ P @[simp] lemma coe_nfal (p : formula L₁) (k : ℕ) : (↑(∀.[k] p) : formula L₂) = ∀.[k] ↑p := fun_p_nfal _ p k @[simp] lemma coe_fal_complete (p : formula L₁) : (↑(∀.* p) : formula L₂) = ∀.* ↑p := fun_p_fal_complete _ p @[simp] lemma coe_conjunction' {n : ℕ} (P : finitary (formula L₁) n) : (↑(⋀ j, P j) : formula L₂) = ⋀ j, P j := fun_p_conjunction' _ P @[simp] lemma coe_disjunction' {n : ℕ} (P : finitary (formula L₁) n) : (↑(⋁ j, P j) : formula L₂) = ⋁ j, P j := fun_p_disjunction' _ P @[simp] lemma coe_t_rew (t : term L₁) (s : ℕ → term L₁) : (↑(t.rew s) : term L₂) = (↑t : term L₂).rew (λ x, ↑(s x)) := fun_t_rew _ t s @[simp] lemma coe_t_subst (t u : term L₁) (s) : (↑(t.rew ı[s ⇝ u]) : term L₂) = (↑t : term L₂).rew ı[s ⇝ ↑u] := fun_t_subst _ t u s @[simp] lemma coe_p_rew (p : formula L₁) (s : ℕ → term L₁) : (↑(p.rew s) : formula L₂) = (↑p : formula L₂).rew (λ x, ↑(s x)) := fun_p_rew _ p s @[simp] lemma fun_p_subst (p : formula L₁) (u : term L₁) (s) : (↑(p.rew ı[s ⇝ u]) : formula L₂) = (↑p : formula L₂).rew ı[s ⇝ ↑u] := fun_p_subst _ p u s @[simp] lemma coe_t_arity (t : term L₁) : (t : term L₂).arity = t.arity := fun_t_arity _ t @[simp] lemma coe_p_arity (p : formula L₁) : (p : formula L₂).arity = p.arity := fun_p_arity _ p @[simp] lemma coe_is_open (p : formula L₁) : (p : formula L₂).is_open ↔ p.is_open := by { induction p; simp[*] } @[simp] lemma term_coe_inj : ∀ {t u : term L₁}, (t : term L₂) = u ↔ t = u | (#m) (#n) := by simp | (#m) (term.app f v) := by simp | (term.app f v) (#n) := by simp | (@term.app _ n₁ f₁ v₁) (@term.app _ n₂ f₂ v₂) := by { simp, rintros rfl, simp, rintros rfl, have IH : ∀ i, ↑(v₁ i) = ↑(v₂ i) ↔ v₁ i = v₂ i, from λ i, @term_coe_inj (v₁ i) (v₂ i), refine ⟨λ h, funext (λ i, (IH i).mp (congr_fun h i)), by { rintros rfl, refl }⟩ } @[simp] lemma formula_coe_inj : ∀ {p q : formula L₁}, (p : formula L₂) = q ↔ p = q | (@formula.app _ n₁ r₁ v₁) (@formula.app _ n₂ r₂ v₂) := by { simp, rintros rfl, simp, rintros rfl, refine ⟨λ h, funext (λ i, term_coe_inj.mp (congr_fun h i)), by { rintros rfl, refl }⟩ } | ⊤ q := by simp; cases q; simp | (formula.app r₁ v₁) (t =' u) := by simp | (formula.app r₁ v₁) ⊤ := by simp | (formula.app r₁ v₁) (p ⟶ q) := by simp | (formula.app r₁ v₁) ∼p := by simp | (formula.app r₁ v₁) (∀.p) := by simp | (t =' u) p := by cases p; simp | (p ⟶ q) r := by cases r; simp[@formula_coe_inj p, @formula_coe_inj q] | (∼p) q := by cases q; simp[@formula_coe_inj p] | (∀.p) q := by cases q; simp[@formula_coe_inj p] @[simp] lemma coe_mem_coe_iff {T : Theory L₁} {p} : ↑p ∈ (↑T : Theory L₂) ↔ p ∈ T := ⟨λ ⟨p', h, eqn⟩, by { simp [formula_coe_inj.mp eqn] at h, exact h }, λ h, ⟨p, h, rfl⟩⟩ lemma mem_coe_iff {T : Theory L₁} {p : formula L₂} : p ∈ (↑T : Theory L₂) ↔ ∃ p₁ ∈ T, p = ↑p₁ := ⟨λ ⟨p₁, h, eqn⟩, ⟨p₁, h, eq.symm eqn⟩, by { rintros ⟨p₁, mem, rfl⟩, simp[mem] }⟩ @[simp] lemma Theory_coe_empty : (↑(∅ : Theory L₁) : Theory L₂) = ∅ := set.ext (λ p, by unfold_coes; simp[tr_Theory]) @[simp] lemma Theory_coe_union (T U : Theory L₁) : (↑(T ∪ U) : Theory L₂) = ↑T ∪ ↑U := set.ext (λ p, by { unfold_coes, simp[tr_Theory], split, { rintros ⟨p, (mem_p | mem_p), rfl⟩, refine or.inl ⟨p, mem_p, rfl⟩, refine or.inr ⟨p, mem_p, rfl⟩ }, { rintros (⟨p, mem_p, rfl⟩ | ⟨p, mem_p, rfl⟩), refine ⟨p, or.inl mem_p, rfl⟩, refine ⟨p, or.inr mem_p, rfl⟩ } }) @[simp] lemma Theory_coe_sf (T : Theory L₁) : (↑⤊T : Theory L₂) = ⤊(↑T : Theory L₂) := set.ext (λ p, by { unfold_coes,simp[tr_Theory, Theory.sf], refine ⟨_, _⟩, { rintros ⟨_, ⟨q₁, mem_q₁, rfl⟩, rfl⟩, refine ⟨q₁, mem_q₁, by simp[app_formula_extension_eq_coe]⟩ }, { rintros ⟨p₁, mem_p₁, rfl⟩, refine ⟨p₁^1, ⟨p₁, mem_p₁, rfl⟩, by simp[app_formula_extension_eq_coe]⟩ } }) @[simp] lemma Theory_coe_pow {T : Theory L₁} {i : ℕ} : (↑T : Theory L₂)^i = ↑(T^i) := begin ext p, simp[Theory_sf_itr_eq, mem_coe_iff], split, { rintros ⟨p', ⟨p₁, mem, rfl⟩, rfl⟩, refine ⟨p₁^i, ⟨p₁, mem, rfl⟩, by simp⟩ }, { rintros ⟨_, ⟨p₁, mem, rfl⟩, rfl⟩, refine ⟨p₁, ⟨p₁, mem, rfl⟩, by simp⟩ } end lemma Theory_mem_coe_pow_iff {p : formula L₂} {T : Theory L₁} {i : ℕ} : p ∈ (↑(T^i) : Theory L₂) ↔ ∃ p' ∈ T, p = (↑p' : formula L₂)^i := begin rw [←Theory_coe_pow, Theory_sf_itr_eq], simp, split, { rintros ⟨q, q_mem, rfl⟩, rcases q_mem with ⟨q, q_mem, rfl⟩, refine ⟨q, q_mem, rfl⟩ }, { rintros ⟨q, q_mem, rfl⟩, refine ⟨↑q, by simp[q_mem]⟩ } end lemma destruct_of_eq_imply {p : formula L₁} {q r : formula L₂} (h : ↑p = q ⟶ r) : ∃ p₁ p₂, p = p₁ ⟶ p₂ := begin rcases p; try { simp at h, contradiction }, { simp at h, rcases h with ⟨rfl, rfl⟩, simp } end lemma destruct_of_eq_neg {p : formula L₁} {q : formula L₂} (h : ↑p = ∼q) : ∃ p₁, p = ∼p₁ := begin rcases p; try { simp at h, contradiction }, { simp at h, rcases h with ⟨rfl, rfl⟩, simp } end lemma fun_t_inversion_of_le {t₁ : term L₁} {u₂ : term L₂} (le : u₂ ≤ ↑t₁) : ∃ (u₁ : term L₁) (le : u₁ ≤ t₁), u₂ = ↑u₁ := fun_t_inversion_of_le _ le lemma fun_p_inversion_of_le {p₁ : formula L₁} {q₂ : formula L₂} (le : q₂ ≤ ↑p₁) : ∃ (q₁ : formula L₁) (le : q₁ ≤ p₁), q₂ = ↑q₁ := fun_p_inversion_of_le _ le lemma fun_p_inversion_of_mem {p₁ : formula L₁} {t₂ : term L₂} (mem : t₂ ∈ (↑p₁ : formula L₂)) : ∃ (t₁ : term L₁) (mem : t₁ ∈ p₁), t₂ = ↑t₁ := fun_p_inversion_of_mem _ mem variables (L₁ L₂ L₃) [language_translation_coe L₁ L₂] [language_translation_coe L₂ L₃] @[reducible] def comp : language_translation_coe L₁ L₃ := { ltr := (ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂), fn_inj := λ n f g, by simp, pr_inj := λ n r s, by simp } variables {L₁} (T : Theory L₁) instance [c : closed_Theory T] : closed_Theory (↑T : Theory L₂) := language_translation.fun_Theory.fol.closed_Theory _ _ lemma fun_Theory_insert (p : formula L₁) : (↑(T+{p}) : Theory L₂) = ↑T +{↑p} := set.image_insert_eq @[simp] lemma ltc_self_eq_one : (ltr : L₁ ↝ᴸ L₁) = 1 := by { ext; simp, { refl }, { intros n r, refl } } @[simp] lemma coe_fn_eq_self {n} (f : L.fn n) : (coe : L.fn n → L.fn n) f = f := by refl @[simp] lemma coe_pr_eq_self {n} (r : L.pr n) : (coe : L.pr n → L.pr n) r = r := by refl @[simp] lemma coe_t_eq_self (t : term L) : (coe : term L → term L) t = t := one_fun_t t @[simp] lemma coe_t_eq_id : (coe : term L → term L) = id := by funext t; simp @[simp] lemma coe_p_eq_self (p : formula L) : (coe : formula L → formula L) p = p := one_fun_p p @[simp] lemma coe_p_eq_id : (coe : formula L → formula L) = id := by funext t; simp end language_translation_coe class commutes (L₁ L₂ L₃) [language_translation_coe L₁ L₂] [language_translation_coe L₂ L₃] [language_translation_coe L₁ L₃] := (comm : (language_translation_coe.ltr : L₂ ↝ᴸ L₃).comp (language_translation_coe.ltr : L₁ ↝ᴸ L₂) = language_translation_coe.ltr) namespace commutes open language_translation language_translation_coe variables {L₁ L₂ L₃} variables {L₁ L₂ L₃} [language_translation_coe L₁ L₂] [language_translation_coe L₂ L₃] [language_translation_coe L₁ L₃] [commutes L₁ L₂ L₃] @[simp] lemma fn_fn_of_commute {n} (f : L₁.fn n) : (ltr.fn n (ltr.fn n f : L₂.fn n) : L₃.fn n) = ltr.fn n f := by { have : ((ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂)).fn n f = ltr.fn n f, from congr (congr_fun (congr_arg language_translation.fn comm) n) rfl, simpa using this } @[simp] lemma pr_pr_of_commute {n} (r : L₁.pr n) : (ltr.pr n (ltr.pr n r : L₂.pr n) : L₃.pr n) = ltr.pr n r := by { have : ((ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂)).pr n r = ltr.pr n r, from congr (congr_fun (congr_arg language_translation.pr comm) n) rfl, simpa using this } @[simp] lemma coe_coe_fn_of_commute {n} (f : L₁.fn n) : (↑(↑f : L₂.fn n) : L₃.fn n) = ↑f := fn_fn_of_commute f @[simp] lemma coe_coe_pr_of_commute {n} (r : L₁.pr n) : (↑(↑r : L₂.pr n) : L₃.pr n) = ↑r := pr_pr_of_commute r @[simp] lemma coe_coe_t_of_commute (t : term L₁) : (↑(↑t : term L₂) : term L₃) = ↑t := by { have : ((ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂)).fun_t t = ltr.fun_t t, from congr (congr_arg language_translation.fun_t comm) rfl, simpa[comp_fun_t] using this } @[simp] lemma coe_coe_p_of_commute (p : formula L₁) : (↑(↑p : formula L₂) : formula L₃) = ↑p := by { have : ((ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂)).fun_p p = ltr.fun_p p, from congr (congr_arg language_translation.fun_p comm) rfl, simpa[comp_fun_p] using this } @[simp] lemma coe_coe_th_of_commute (T : Theory L₁) : (↑(↑T : Theory L₂) : Theory L₃) = ↑T := by { have : ((ltr : L₂ ↝ᴸ L₃).comp (ltr : L₁ ↝ᴸ L₂)).fun_Theory T = ltr.fun_Theory T, from congr (congr_arg language_translation.fun_Theory comm) rfl, simpa[comp_fun_Theory] using this } @[simp] protected lemma zero [has_zero_symbol L₁] : @has_zero.zero _ (@term.has_zero _ (@language_translation_coe.zero L₂ L₃ _ _)) = 0 := by { unfold has_zero.zero has_zero_symbol.zero, simp } @[simp] protected lemma succ [has_succ_symbol L₁] (t : term L₃) : @has_succ.succ _ (@term.has_succ _ (@language_translation_coe.succ L₂ L₃ _ _)) t = Succ t := by { unfold has_succ.succ has_succ_symbol.succ, simp } @[simp] protected lemma numeral [has_zero_symbol L₁] [has_succ_symbol L₁] (n : ℕ) : @numeral _ (@term.has_zero _ (@language_translation_coe.zero L₂ L₃ _ _)) (@term.has_succ _ (@language_translation_coe.succ L₂ L₃ _ _)) n = n˙ := by induction n with n IH; simp[numeral, *] @[simp] protected lemma add [has_add_symbol L₁] (t u : term L₃) : @has_add.add _ (@term.has_add _ (@language_translation_coe.add L₂ L₃ _ _)) t u = t + u := by { unfold has_add.add has_add_symbol.add, simp } @[simp] protected lemma mul [has_mul_symbol L₁] (t u : term L₃) : @has_mul.mul _ (@term.has_mul _ (@language_translation_coe.mul L₂ L₃ _ _)) t u = t * u := by { unfold has_mul.mul has_mul_symbol.mul, simp } @[simp] protected lemma le [has_le_symbol L₁] (t u : term L₃) : @has_preceq.preceq _ _ (@formula.has_preceq L₃ (@language_translation_coe.le L₂ L₃ _ _)) t u = (t ≼ u) := by { unfold has_preceq.preceq has_le_symbol.le, simp } @[simp] protected lemma mem [has_mem_symbol L₁] (t u : term L₃) : @has_elem.elem _ _ (@formula.has_elem L₃ (@language_translation_coe.mem L₂ L₃ _ _)) t u = (t ∊ u) := by { unfold has_elem.elem has_mem_symbol.mem, simp } instance comp_commutes : @commutes L₁ L₂ L₃ _ _ (comp L₁ L₂ L₃) := { comm := by refl } instance self_commutes : commutes L₁ L₁ L₂ := ⟨by simp⟩ instance commutes_self : commutes L₁ L₂ L₂ := ⟨by simp⟩ end commutes namespace language_translation variables (τ : L₁ ↝ᴸ L₂) instance conservative : τ.tr.conservative := { ax := λ k T, tr_Theory τ.tr k T, ax_ss := by { intros, refl }, specialize := λ k p t T i, by { have : (λ (x : ℕ), τ.fun_t (ı[0 ⇝ t] x)) = ı[0 ⇝ τ.fun_t t], { funext x, cases x; simp }, simp[tr_app_eq, fun_p_rew, this] }, eq_reflexivity := by simp[tr_app_eq], eq_symmetry := by simp[tr_app_eq], eq_transitive := by simp[tr_app_eq], function_ext := λ k n f T i, by { simp[eq_axiom4], simp[tr_app_eq], exact (show _ ⊢ eq_axiom4 (τ.fn _ f), by simp) }, predicate_ext := λ k n f T i, by { simp[eq_axiom5], simp[tr_app_eq], exact (show _ ⊢ eq_axiom5 (τ.pr _ f), by simp) } } end language_translation namespace translation open provable axiomatic_classical_logic' translation.conservative variables {L₁} {L₂} variables (τ : translation L₁ L₂) [conservative τ] (i : ℕ) @[simp] lemma mem_pow_Theory_tr_of_mem_pow {T : Theory L₁} {k : ℕ} {p} {i : ℕ} (mem : p ∈ T^k) : (τ (i + k) p) ∈ (tr_Theory τ i T : Theory L₂)^k := by { simp[Theory_sf_itr_eq] at mem ⊢, rcases mem with ⟨q, mem, rfl⟩, refine ⟨τ i q, mem_Theory_tr_of_mem mem, _⟩, simp[translation.map_pow'] } lemma provability_pow (T : Theory L₁) (p : formula L₁) (i k : ℕ) (h : T^i ⊢ p) : (ax τ k T)^i ⊢ τ (k + i) p := begin refine provable.rec'_on h _ _ _ _ _ _ _ _ _ _ _ _ _ _ _, { intros i p _ h, simp[add_assoc] at h ⊢, exact generalize h }, { intros i p q _ _ hpq hp, simp at hpq, exact hpq ⨀ hp }, { intros i p mem, suffices : (tr_Theory τ k T)^i ⊢ τ (k + i) p, { exact weakening this (by simp[ax_ss]) }, refine (by_axiom (by {simp[mem]})) }, { intros, simp }, { intros, simp }, { intros, simp }, { intros, simp }, { intros, refine specialize _ _ _ _ _ }, { intros, simp }, { intros, simp[translation.map_pow'] }, { intros, refine eq_reflexivity _ _ _ }, { intros, exact eq_symmetry _ _ _ }, { intros, exact eq_transitive _ _ _ }, { intros, exact function_ext _ _ _ _ }, { intros, exact predicate_ext _ _ _ _ }, end lemma provability (T : Theory L₁) (p : formula L₁) (k : ℕ) : T ⊢ p → ax τ k T ⊢ τ k p := by { have := provability_pow τ T p 0, simp at this, exact this k } lemma provability_tautology (p : formula L₁) (k : ℕ): (∀ T, T ⊢ p) → ∀ T, ax τ k T ⊢ τ k p := λ h T, provability τ T p k (h T) lemma consistency (T : Theory L₁) (k : ℕ) : (ax τ k T).consistent → T.consistent := by { simp[logic.Theory.consistent_iff_bot], contrapose, simp, have := provability τ T ⊥ k, simp at this, exact this } instance refl_conservative : conservative (fol.language.translation.refl L₁) := { ax := λ k T, tr_Theory (fol.language.translation.refl L₁) k T, ax_ss := by { intros, refl }, specialize := by simp[translation.refl], eq_reflexivity := by simp[translation.refl], eq_symmetry := by simp[translation.refl], eq_transitive := by simp[translation.refl], function_ext := by { intros, simp[translation.refl] }, predicate_ext := by { intros, simp[translation.refl] } } instance shift_conservative (k : ℕ) : conservative (shift L₁ k) := { ax := λ l T, tr_Theory (shift L₁ k) l T, ax_ss := by { intros, refl }, specialize := λ l p t T i, by {simp[translation.shift], have : ∀ l, (p.rew ı[0 ⇝ t]).rew (λ x, ite (x < l) #x #(x + k)) = (p.rew (λ x, ite (x < l + 1) #x #(x + k))).rew ı[0 ⇝ (t.rew (λ x, ite (x < l) #x #(x + k)))], { intros l, simp[formula.nested_rew], congr, funext x, cases x with x; simp[←nat.add_one], by_cases C : x < l; simp[C, show x + 1 + k = x + k + 1, by omega] }, simp [this] }, eq_reflexivity := by simp[translation.shift], eq_symmetry := by simp[translation.shift], eq_transitive := λ _ _ _, by simp[translation.shift, show ∀ l, 2 < l + 1 + 1 + 1, by omega], function_ext := λ _ _ _ _, by simp[translation.shift], predicate_ext := λ _ _ _ _, by simp[translation.shift] } end translation namespace language_translation open language_translation logic variables (τ : L₁ ↝ᴸ L₂) lemma provability_pow {T : Theory L₁} {p : formula L₁} {i : ℕ} : T^i ⊢ p → (τ.fun_Theory T)^i ⊢ τ.fun_p p := translation.provability_pow τ.tr T p i 0 lemma provability {T : Theory L₁} {p : formula L₁} : T ⊢ p → τ.fun_Theory T ⊢ τ.fun_p p := translation.provability τ.tr T p 0 lemma consistency (T : Theory L₁) : Theory.consistent (τ.fun_Theory T) → T.consistent := translation.consistency τ.tr T 0 end language_translation namespace language_translation_coe open language_translation logic variables [σ : language_translation_coe L₁ L₂] include σ lemma provability_pow {T : Theory L₁} {p : formula L₁} {i : ℕ} : T^i ⊢ p → (↑T : Theory L₂)^i ⊢ ↑p := translation.provability_pow σ.ltr.tr T p i 0 lemma provability {T : Theory L₁} {p : formula L₁} : T ⊢ p → (↑T : Theory L₂) ⊢ ↑p := translation.provability σ.ltr.tr T p 0 lemma consistency (T : Theory L₁) : Theory.consistent (↑T : Theory L₂) → T.consistent := translation.consistency σ.ltr.tr T 0 end language_translation_coe -------------------------------------------------------------------------------- instance : has_add language := ⟨λ L₁ L₂ : language.{u}, ⟨λ n, L₁.fn n ⊕ L₂.fn n, λ n, L₁.pr n ⊕ L₂.pr n⟩⟩ def direct_sum {ι : Type*} (l : ι → language) : language := ⟨λ n, Σ i, (l i).fn n, λ n, Σ i, (l i).pr n⟩ def consts (α : Type u) : language.{u} := ⟨λ n, match n with | 0 := α | (n + 1) := pempty end, λ n, pempty⟩ namespace consts variables {α : Type u} def c (a : α) : (consts α).fn 0 := a instance : has_coe α (term (consts α)) := ⟨λ a, term.app (consts.c a) finitary.nil⟩ lemma coe_def (a : α) : (a : term (consts α)) = term.app (consts.c a) finitary.nil := rfl @[simp] lemma arity_eq_0 (a : α) : (a : term (consts α)).arity = 0 := by simp[coe_def] end consts def singleton_fn (m : ℕ) : language.{u} := ⟨λ n, if n = m then punit else pempty, λ n, pempty⟩ namespace singleton_fn variables {m : ℕ} def star : (singleton_fn m).fn m := by { simp[singleton_fn]; simp[show (m = m) ↔ true, by simp], refine punit.star } end singleton_fn @[simp] lemma sum_fn_def {ι : Type*} (l : ι → language) (n : ℕ) : (direct_sum l).fn n = Σ i, (l i).fn n := rfl @[simp] lemma sum_pr_def {ι : Type*} (l : ι → language) (n : ℕ) : (direct_sum l).pr n = Σ i, (l i).pr n := rfl namespace extension open language_translation language_translation_coe def add_left : L₁ ↝ᴸ L₁ + L₂ := ⟨λ n f, sum.inl f, λ n p, sum.inl p⟩ instance ltr₁ : language_translation_coe L₁ (L₁ + L₂) := { ltr := add_left, fn_inj := λ n f g, sum.inl.inj, pr_inj := λ n f g, sum.inl.inj } lemma coe_fn₁ {n} (f : L₁.fn n) : (↑f : (L₁ + L₂).fn n) = sum.inl f:= rfl lemma coe_pr₁ {n} (r : L₁.pr n) : (↑r : (L₁ + L₂).pr n) = sum.inl r:= rfl lemma zero_symbol_eq₁ [has_zero_symbol L₁] : (has_zero_symbol.zero : (L₁ + L₂).fn 0) = sum.inl has_zero_symbol.zero := rfl lemma succ_symbol_eq₁ [has_succ_symbol L₁] : (has_succ_symbol.succ : (L₁ + L₂).fn 1) = sum.inl has_succ_symbol.succ := rfl lemma add_symbol_eq₁ [has_add_symbol L₁] : (has_add_symbol.add : (L₁ + L₂).fn 2) = sum.inl has_add_symbol.add := rfl lemma mul_symbol_eq₁ [has_mul_symbol L₁] : (has_mul_symbol.mul : (L₁ + L₂).fn 2) = sum.inl has_mul_symbol.mul := rfl lemma le_symbol_eq₁ [has_le_symbol L₁] : (has_le_symbol.le : (L₁ + L₂).pr 2) = sum.inl has_le_symbol.le := rfl lemma add_left_fn_to_coe {n} (f : L₁.fn n) : (add_left.fn _ f : (L₁ + L₂).fn n) = f := rfl lemma add_left_pr_to_coe {n} (r : L₁.pr n) : (add_left.pr _ r : (L₁ + L₂).pr n) = r := rfl def add_right : L₂ ↝ᴸ L₁ + L₂ := ⟨λ n f, sum.inr f, λ n p, sum.inr p⟩ instance ltr₂ : language_translation_coe L₂ (L₁ + L₂) := { ltr := add_right, fn_inj := λ n f g, sum.inr.inj, pr_inj := λ n f g, sum.inr.inj } lemma coe_fn₂ {n} (f : L₂.fn n) : (↑f : (L₁ + L₂).fn n) = sum.inr f:= rfl lemma coe_pr₂ {n} (r : L₂.pr n) : (↑r : (L₁ + L₂).pr n) = sum.inr r:= rfl lemma zero_symbol_eq₂ [has_zero_symbol L₂] : (has_zero_symbol.zero : (L₁ + L₂).fn 0) = sum.inr has_zero_symbol.zero := rfl lemma succ_symbol_eq₂ [has_succ_symbol L₂] : (has_succ_symbol.succ : (L₁ + L₂).fn 1) = sum.inr has_succ_symbol.succ := rfl lemma add_symbol_eq₂ [has_add_symbol L₂] : (has_add_symbol.add : (L₁ + L₂).fn 2) = sum.inr has_add_symbol.add := rfl lemma mul_symbol_eq₂ [has_mul_symbol L₂] : (has_mul_symbol.mul : (L₁ + L₂).fn 2) = sum.inr has_mul_symbol.mul := rfl lemma le_symbol_eq₂ [has_le_symbol L₂] : (has_le_symbol.le : (L₁ + L₂).pr 2) = sum.inr has_le_symbol.le := rfl lemma add_right_fn_to_coe {n} (f : L₂.fn n) : (add_right.fn _ f : (L₁ + L₂).fn n) = f := rfl lemma add_right_pr_to_coe {n} (r : L₂.pr n) : (add_right.pr _ r : (L₁ + L₂).pr n) = r := rfl class sublanguage (L₀ : language.{u}) (L : language.{u}) := (map_fn : Π {n}, L.fn n → L₀.fn n) (map_pr : Π {n}, L.pr n → L₀.pr n) variables {ι : Type*} (l : ι → language) def to_extension (i : ι) : l i ↝ᴸ direct_sum l := ⟨λ n f, ⟨i, f⟩, λ n r, ⟨i, r⟩⟩ instance ltr (i : ι) : language_translation_coe (l i) (direct_sum l) := { ltr := to_extension l i, fn_inj := λ n f g, by simp[to_extension], pr_inj := λ n f g, by simp[to_extension] } def ext_ss {s t : set ι} (ss : s ⊆ t) : direct_sum (λ i : s, l i) ↝ᴸ direct_sum (λ i : t, l i) := ⟨λ n ⟨⟨i, hi⟩, f⟩, ⟨⟨i, ss hi⟩, f⟩, λ n ⟨⟨i, hi⟩, f⟩, ⟨⟨i, ss hi⟩, f⟩⟩ def ltr_ss {s t : set ι} (ss : s ⊆ t) : language_translation_coe (direct_sum (λ i : s, l i)) (direct_sum (λ i : t, l i)) := { ltr := ext_ss l ss, fn_inj := λ n ⟨⟨i, pi⟩, f⟩ ⟨⟨j, pj⟩, g⟩, by { simp[ext_ss], rintros rfl, simp }, pr_inj := λ n ⟨⟨i, pi⟩, f⟩ ⟨⟨j, pj⟩, g⟩, by { simp[ext_ss], rintros rfl, simp } } def to_extension_subtype (s : set ι) : direct_sum (λ i : s, l i) ↝ᴸ direct_sum l := ⟨λ n ⟨i, f⟩, ⟨i, f⟩, λ n ⟨i, r⟩, ⟨i, r⟩⟩ instance ltr_subtype (s : set ι) : language_translation_coe (direct_sum (λ i : s, l i)) (direct_sum l) := { ltr := to_extension_subtype l s, fn_inj := λ n ⟨⟨i, pi⟩, f⟩ ⟨⟨j, pj⟩, g⟩, by { simp[to_extension_subtype], rintros rfl, simp }, pr_inj := λ n ⟨⟨i, pi⟩, f⟩ ⟨⟨j, pj⟩, g⟩, by { simp[to_extension_subtype], rintros rfl, simp } } @[simp] lemma ext_ss_subtype_consistence_term {s t : set ι} (ss : s ⊆ t) : ∀ (u : term (direct_sum (λ i : s, l i))), ((ext_ss l ss).fun_t u : term (direct_sum l)) = u | #n := by simp | (@term.app _ n f v) := by { rcases f with ⟨⟨i, hi⟩, f⟩, simp[ext_ss], refine ⟨rfl, funext (λ i, ext_ss_subtype_consistence_term (v i))⟩} @[simp] lemma ext_ss_subtype_consistence {s t : set ι} (ss : s ⊆ t) : ∀ (p : formula (direct_sum (λ i : s, l i))), ((ext_ss l ss).fun_p p : formula (direct_sum l)) = p | ⊤ := by simp | (app r v) := by { simp, rcases r with ⟨⟨i, hi⟩, r⟩, simp[ext_ss], refl } | ((t : term (direct_sum (λ (i : s), l i))) =' u) := by simp | (p ⟶ q) := by simp[ext_ss_subtype_consistence p, ext_ss_subtype_consistence q] | (∼p) := by simp[ext_ss_subtype_consistence p] | (∀.p) := by simp[ext_ss_subtype_consistence p] @[simp] lemma Theory_ext_ss_subtype_consistence {s t : set ι} (ss : s ⊆ t) (T : Theory (direct_sum (λ i : s, l i))) : (↑((ext_ss l ss).fun_Theory T) : Theory (direct_sum l)) = ↑T := set.ext (λ p, by { unfold_coes, simp[tr_Theory, app_formula_extension_eq_coe, fun_Theory] }) end extension namespace language_translation variables {L₁} {L₂} {L₃} {L₄ : language.{u}} def add (τ : L₁ ↝ᴸ L₂) (σ : L₃ ↝ᴸ L₄) : L₁ + L₃ ↝ᴸ L₂ + L₄ := { fn := λ n f, by { rcases f, { exact sum.inl (τ.fn _ f) }, { exact sum.inr (σ.fn _ f) } }, pr := λ n r, by { rcases r, { exact sum.inl (τ.pr _ r) }, { exact sum.inr (σ.pr _ r) } } } section variables (τ : L₁ ↝ᴸ L₂) (σ : L₃ ↝ᴸ L₄) @[simp] lemma add_fnl {n} (f : L₁.fn n) : (τ.add σ).fn n ↑f = ↑(τ.fn n f) := rfl @[simp] lemma add_prl {n} (r : L₁.pr n) : (τ.add σ).pr n ↑r = ↑(τ.pr n r) := rfl @[simp] lemma add_fnr {n} (f : L₃.fn n) : (τ.add σ).fn n ↑f = ↑(σ.fn n f) := rfl @[simp] lemma add_prr {n} (r : L₃.pr n) : (τ.add σ).pr n ↑r = ↑(σ.pr n r) := rfl end def sum (τ : L₁ ↝ᴸ L₂) (σ : L₃ ↝ᴸ L₂) : L₁ + L₃ ↝ᴸ L₂ := { fn := λ n f, by { rcases f, { refine τ.fn n f }, { refine σ.fn n f } }, pr := λ n r, by { rcases r, { refine τ.pr n r }, { refine σ.pr n r } } } section variables (τ : L₁ ↝ᴸ L₂) (σ : L₃ ↝ᴸ L₂) @[simp] lemma sum_fnl {n} (f : L₁.fn n) : (τ.sum σ).fn n ↑f = (τ.fn n f) := rfl @[simp] lemma sum_prl {n} (r : L₁.pr n) : (τ.sum σ).pr n ↑r = (τ.pr n r) := rfl @[simp] lemma sum_fnr {n} (f : L₃.fn n) : (τ.sum σ).fn n ↑f = (σ.fn n f) := rfl @[simp] lemma sum_prr {n} (r : L₃.pr n) : (τ.sum σ).pr n ↑r = (σ.pr n r) := rfl end variables (L₁ L₂ L₃) def add_comm' : L₁ + L₂ ↝ᴸ L₂ + L₁ := { fn := λ n f, by { rcases f, { refine sum.inr f }, { refine sum.inl f } }, pr := λ n r, by { rcases r, { refine sum.inr r }, { refine sum.inl r } } } @[simp] lemma add_comm'_fnl {n} (f : L₁.fn n) : (add_comm' L₁ L₂).fn n ↑f = f := rfl @[simp] lemma add_comm'_prl {n} (r : L₁.pr n) : (add_comm' L₁ L₂).pr n ↑r = r := rfl @[simp] lemma add_comm'_fnr {n} (f : L₂.fn n) : (add_comm' L₁ L₂).fn n ↑f = f := rfl @[simp] lemma add_comm'_prr {n} (r : L₂.pr n) : (add_comm' L₁ L₂).pr n ↑r = r := rfl def add_assoc' : L₁ + L₂ + L₃ ↝ᴸ L₁ + (L₂ + L₃) := { fn := λ n f, by { rcases f, { rcases f, { refine sum.inl f }, { refine sum.inr (sum.inl f) } }, { refine sum.inr (sum.inr f) } }, pr := λ n r, by { rcases r, { rcases r, { refine sum.inl r }, { refine sum.inr (sum.inl r) } }, { refine sum.inr (sum.inr r) } } } @[simp] lemma add_assoc'_fn₁ {n} (f : L₁.fn n) : (add_assoc' L₁ L₂ L₃).fn n (↑(↑f : (L₁ + L₂).fn n)) = (↑f : (L₁ + (L₂ + L₃)).fn n) := rfl @[simp] lemma add_assoc'_fn₂ {n} (f : L₂.fn n) : (add_assoc' L₁ L₂ L₃).fn n (↑(↑f : (L₁ + L₂).fn n)) = ↑(↑f : (L₂ + L₃).fn n) := rfl @[simp] lemma add_assoc'_fn₃ {n} (f : L₃.fn n) : (add_assoc' L₁ L₂ L₃).fn n (↑f : (L₁ + L₂ + L₃).fn n) = ↑(↑f : (L₂ + L₃).fn n) := rfl @[simp] lemma add_assoc'_pr₁ {n} (r : L₁.pr n) : (add_assoc' L₁ L₂ L₃).pr n (↑(↑r : (L₁ + L₂).pr n)) = (↑r : (L₁ + (L₂ + L₃)).pr n) := rfl @[simp] lemma add_assoc'_pr₂ {n} (r : L₂.pr n) : (add_assoc' L₁ L₂ L₃).pr n (↑(↑r : (L₁ + L₂).pr n)) = ↑(↑r : (L₂ + L₃).pr n) := rfl @[simp] lemma add_assoc'_pr₃ {n} (r : L₃.pr n) : (add_assoc' L₁ L₂ L₃).pr n (↑r : (L₁ + L₂ + L₃).pr n) = ↑(↑r : (L₂ + L₃).pr n) := rfl def add_assoc'_inv : L₁ + (L₂ + L₃) ↝ᴸ L₁ + L₂ + L₃ := { fn := λ n f, by { rcases f, { refine sum.inl f }, { rcases f, { refine sum.inl (sum.inr f) }, { refine sum.inr f } } }, pr := λ n r, by { rcases r, { refine sum.inl r }, { rcases r, { refine sum.inl (sum.inr r) }, { refine sum.inr r } } } } @[simp] lemma add_assoc'_inv_fn₁ {n} (f : L₁.fn n) : (add_assoc'_inv L₁ L₂ L₃).fn n (↑f : (L₁ + (L₂ + L₃)).fn n) = ↑(↑f : (L₁ + L₂).fn n) := rfl @[simp] lemma add_assoc'_inv_fn₂ {n} (f : L₂.fn n) : (add_assoc'_inv L₁ L₂ L₃).fn n (↑(↑f : (L₂ + L₃).fn n)) = ↑(↑f : (L₁ + L₂).fn n) := rfl @[simp] lemma add_assoc'_inv_fn₃ {n} (f : L₃.fn n) : (add_assoc'_inv L₁ L₂ L₃).fn n ↑(↑f : (L₂ + L₃).fn n) = (↑f : (L₁ + L₂ + L₃).fn n) := rfl @[simp] lemma add_assoc'_inv_pr₁ {n} (r : L₁.pr n) : (add_assoc'_inv L₁ L₂ L₃).pr n (↑r : (L₁ + (L₂ + L₃)).pr n) = (↑(↑r : (L₁ + L₂).pr n)) := rfl @[simp] lemma add_assoc'_inv_pr₂ {n} (r : L₂.pr n) : (add_assoc'_inv L₁ L₂ L₃).pr n ↑(↑r : (L₂ + L₃).pr n) = (↑(↑r : (L₁ + L₂).pr n)) := rfl @[simp] lemma add_assoc'_inv_pr₃ {n} (r : L₃.pr n) : (add_assoc'_inv L₁ L₂ L₃).pr n ↑(↑r : (L₂ + L₃).pr n) = (↑r : (L₁ + L₂ + L₃).pr n) := rfl section variables {α β : Type*} def consts_of_fun (f : α → β) : consts α ↝ᴸ consts β := { fn := λ n c, by { rcases n, { exact f c }, { rcases c } }, pr := λ n r, by { rcases r } } @[simp] lemma consts_fn (f : α → β) (c : (consts α).fn 0) : (consts_of_fun f).fn 0 c = f c := rfl end variables {L₁} {L₂} (τ : L₁ ↝ᴸ L₂) end language_translation namespace language_translation_coe variables (L₁ L₂) [language_translation_coe L₂ L₁] def sub : language.{u} := { fn := λ n, ↥(has_compl.compl $ set.range (coe : L₂.fn n → L₁.fn n)), pr := λ n, ↥(has_compl.compl $ set.range (coe : L₂.pr n → L₁.pr n)) } end language_translation_coe namespace language_equiv open language_translation language_translation_coe extension variables {L₁ L₂} def of_equivs (Fn : Π n, equiv (L₁.fn n) (L₂.fn n)) (Pr : Π n, equiv (L₁.pr n) (L₂.pr n)) : language_equiv L₁ L₂ := { ltr := { fn := λ n f, (Fn n).to_fun f, pr := λ n r, (Pr n).to_fun r }, inv := { fn := λ n f, (Fn n).inv_fun f, pr := λ n r, (Pr n).inv_fun r }, left_inv_fn := λ n, equiv.left_inverse_symm (Fn n), left_inv_pr := λ n, equiv.left_inverse_symm (Pr n), right_inv_fn := λ n, equiv.right_inverse_symm (Fn n), right_inv_pr := λ n, equiv.right_inverse_symm (Pr n) } variables (L₁ L₂ L₃) def add_comm' : L₁ + L₂ ↭ᴸ L₂ + L₁ := { ltr := add_comm' L₁ L₂, inv := add_comm' L₂ L₁, left_inv_fn := λ n f, by rcases f; simp[←coe_fn₁, ←coe_fn₂], left_inv_pr := λ n r, by rcases r; simp[←coe_pr₁, ←coe_pr₂], right_inv_fn := λ n f, by rcases f; simp[←coe_fn₁, ←coe_fn₂], right_inv_pr := λ n r, by rcases r; simp[←coe_pr₁, ←coe_pr₂] } def add_assoc' : L₁ + L₂ + L₃ ↭ᴸ L₁ + (L₂ + L₃) := { ltr := add_assoc' L₁ L₂ L₃, inv := add_assoc'_inv L₁ L₂ L₃, left_inv_fn := λ n f, by { rcases f; simp[←coe_fn₁, ←coe_fn₂], rcases f; simp[←coe_fn₁, ←coe_fn₂] }, left_inv_pr := λ n r, by { rcases r; simp[←coe_pr₁, ←coe_pr₂], rcases r; simp[←coe_pr₁, ←coe_pr₂] }, right_inv_fn := λ n f, by { rcases f; simp[←coe_fn₁, ←coe_fn₂], rcases f; simp[←coe_fn₁, ←coe_fn₂] }, right_inv_pr := λ n r, by { rcases r; simp[←coe_pr₁, ←coe_pr₂], rcases r; simp[←coe_pr₁, ←coe_pr₂] } } @[simp] lemma of_equivs_fn (Fn : Π n, equiv (L₁.fn n) (L₂.fn n)) (Pr : Π n, equiv (L₁.pr n) (L₂.pr n)) {n} (f : L₁.fn n) : (of_equivs Fn Pr).ltr.fn n f = (Fn n) f := rfl @[simp] lemma of_equivs_pr (Fn : Π n, equiv (L₁.fn n) (L₂.fn n)) (Pr : Π n, equiv (L₁.pr n) (L₂.pr n)) {n} (r : L₁.pr n) : (of_equivs Fn Pr).ltr.pr n r = (Pr n) r := rfl @[simp] lemma of_equivs_inv_fn (Fn : Π n, equiv (L₁.fn n) (L₂.fn n)) (Pr : Π n, equiv (L₁.pr n) (L₂.pr n)) {n} (f : L₂.fn n) : (of_equivs Fn Pr).inv.fn n f = (Fn n).inv_fun f := rfl @[simp] lemma of_equivs_inv_pr (Fn : Π n, equiv (L₁.fn n) (L₂.fn n)) (Pr : Π n, equiv (L₁.pr n) (L₂.pr n)) {n} (r : L₂.pr n) : (of_equivs Fn Pr).inv.pr n r = (Pr n).inv_fun r := rfl section variables (τ : L₁ ↭ᴸ L₂) @[simp] lemma inv_ltr_fn {n} (f : L₁.fn n) : τ.inv.fn n (τ.ltr.fn n f) = f := τ.left_inv_fn n f @[simp] lemma inv_ltr_pr {n} (r : L₁.pr n) : τ.inv.pr n (τ.ltr.pr n r) = r := τ.left_inv_pr n r @[simp] lemma ltr_inv_fn {n} (f : L₂.fn n) : τ.ltr.fn n (τ.inv.fn n f) = f := τ.right_inv_fn n f @[simp] lemma ltr_inv_pr {n} (r : L₂.pr n) : τ.ltr.pr n (τ.inv.pr n r) = r := τ.right_inv_pr n r @[simp] lemma inv_ltr_t (t : term L₁) : τ.inv.fun_t (τ.ltr.fun_t t) = t := by induction t; simp* @[simp] lemma ltr_inv_t (t : term L₂) : τ.ltr.fun_t (τ.inv.fun_t t) = t := by induction t; simp* @[simp] lemma inv_ltr_p (p : formula L₁) : τ.inv.fun_p (τ.ltr.fun_p p) = p := by induction p; simp* @[simp] lemma ltr_inv_p (p : formula L₂) : τ.ltr.fun_p (τ.inv.fun_p p) = p := by induction p; simp* end section variables [τ : language.language_translation_coe L₁ L₂] include τ @[reducible] noncomputable def add_sub' : L₁ + sub L₂ L₁ ↭ᴸ L₂ := of_equivs (λ n, let F : L₂.fn n → (L₁ + sub L₂ L₁).fn n := λ f, if h : f ∈ set.range (τ.ltr.fn n) then by { have : nonempty (L₁.fn n), from nonempty_of_exists h, exact ↑(by exactI classical.epsilon (λ y, τ.ltr.fn n y = f)) } else sum.inr ⟨f, h⟩ in { to_fun := λ f, by { rcases f, { exact τ.ltr.fn _ f }, { rcases f with ⟨f, hf⟩, exact f } }, inv_fun := F, left_inv := λ f, by{ rcases f with (f | ⟨f, hf⟩); simp, { simp[F, ←coe_fn₁], exact classical.epsilon_singleton f }, { simp[F, -set.mem_range, show f ∉ (set.range (τ.ltr.fn n)), from hf], refl } }, right_inv := λ f, by{ simp, by_cases C : f ∈ set.range (τ.ltr.fn n), { rcases C with ⟨f, rfl⟩, have : F (τ.ltr.fn n f) = sum.inl f, { simp[F, ←coe_fn₁], exact classical.epsilon_singleton f }, rw[this] }, { have : F f = sum.inr ⟨f, C⟩, by simp[F, -set.mem_range, C], rw[this] } } }) (λ n, let F : L₂.pr n → (L₁ + sub L₂ L₁).pr n := λ f, if h : f ∈ set.range (τ.ltr.pr n) then by { have : nonempty (L₁.pr n), from nonempty_of_exists h, exact ↑(by exactI classical.epsilon (λ y, τ.ltr.pr n y = f)) } else sum.inr ⟨f, h⟩ in { to_fun := λ f, by { rcases f, { exact τ.ltr.pr _ f }, { rcases f with ⟨f, hf⟩, exact f } }, inv_fun := F, left_inv := λ f, by{ rcases f with (f | ⟨f, hf⟩); simp, { simp[F, ←coe_pr₁], exact classical.epsilon_singleton f }, { simp[F, -set.mem_range, show f ∉ (set.range (τ.ltr.pr n)), from hf], refl } }, right_inv := λ f, by{ simp, by_cases C : f ∈ set.range (τ.ltr.pr n), { rcases C with ⟨f, rfl⟩, have : F (τ.ltr.pr n f) = sum.inl f, { simp[F, ←coe_pr₁], exact classical.epsilon_singleton f }, rw[this] }, { have : F f = sum.inr ⟨f, C⟩, by simp[F, -set.mem_range, C], rw[this] } } }) lemma add_sub'_add_left_commute : (add_sub' L₁ L₂).ltr.comp (extension.add_left) = τ.ltr := by ext n f; simp[add_sub', add_left] end end language_equiv namespace language_translation open extension def seq (l : ℕ → language.{u}) := Π n, l n ↝ᴸ l (n + 1) variables {l : ℕ → language.{u}} structure seq_limit (l : ℕ → language.{u}) (L : language):= (seq : seq l) (to_limit : Π n, l n ↝ᴸ L) (commutes : ∀ n, (to_limit (n + 1)).comp (seq n) = to_limit n) (rank_fn : Π {n} (f : L.fn n), ℕ) (rank_pr : Π {n} (r : L.pr n), ℕ) (fn : Π {n} (f : L.fn n), (l $ rank_fn f).fn n) (pr : Π {n} (r : L.pr n), (l $ rank_pr r).pr n) (fn_spec : ∀ {n} (f : L.fn n), (to_limit _).fn _ (fn f) = f) (pr_spec : ∀ {n} (r : L.pr n), (to_limit _).pr _ (pr r) = r) namespace seq_limit variables {L} (s : seq_limit l L) include s def seqs : Π n m, l n ↝ᴸ l (n + m) | n 0 := (1 : l n ↝ᴸ l n) | n (m + 1) := (s.seq (n + m)).comp (seqs n m) def seqs_le {n m} (h : n ≤ m) : l n ↝ᴸ l m := by { rw [show m = n + (m - n), by omega], exact s.seqs n (m - n) } @[simp] lemma to_limit_seq_commutes' (n : ℕ) : (s.to_limit (n + 1)).comp (s.seq n) = s.to_limit n := s.commutes n @[simp] lemma to_limit_seqs_commuts (n m : ℕ) : (s.to_limit (n + m)).comp (s.seqs n m) = s.to_limit n := by { induction m with m IH; simp[seqs], { refl }, { suffices : (s.to_limit (n + m + 1)).comp ((s.seq (n + m)).comp (s.seqs n m)) = s.to_limit n, by simpa, rw ← comp_assoc, simp[IH] } } lemma seqs_le_commuts {n m : ℕ} (le : n ≤ m) : (s.to_limit m).comp (s.seqs_le le) = s.to_limit n := by { have := s.to_limit_seqs_commuts n (m - n), rw ←this, congr; simp[show n + (m - n) = m, by omega, seqs_le] } @[simp] lemma seqs_le_commuts'_fn {n m : ℕ} (le : n ≤ m) {k} (f : (l n).fn k) : (s.to_limit m).fn _ ((s.seqs_le le).fn _ f) = (s.to_limit n).fn _ f := by { rw[←s.seqs_le_commuts le], simp } @[simp] lemma seqs_le_commuts'_pr {n m : ℕ} (le : n ≤ m) {k} (r : (l n).pr k) : (s.to_limit m).pr _ ((s.seqs_le le).pr _ r) = (s.to_limit n).pr _ r := by { rw[←s.seqs_le_commuts le], simp } @[simp] lemma seqs_le_commuts'_t {n m : ℕ} (le : n ≤ m) (t : term (l n)) : (s.to_limit m).fun_t ((s.seqs_le le).fun_t t) = (s.to_limit n).fun_t t := by { rw[←s.seqs_le_commuts le], simp[comp_fun_t] } @[simp] lemma seqs_le_commuts'_p {n m : ℕ} (le : n ≤ m) (p : formula (l n)) : (s.to_limit m).fun_p ((s.seqs_le le).fun_p p) = (s.to_limit n).fun_p p := by { rw[←s.seqs_le_commuts le], simp[comp_fun_p] } @[simp] def rank_t : term L → ℕ | #n := 0 | (app f v) := max (s.rank_fn f) (⨆ᶠ i, rank_t (v i)) @[simp, reducible] def retruct_t : Π t : term L, term (l $ s.rank_t t) | #n := #n | (@term.app L m f v) := let n := max (s.rank_fn f) (⨆ᶠ i, s.rank_t (v i)), tr₀ : l (s.rank_fn f) ↝ᴸ l n := s.seqs_le (by simp[n]), tr : Π i, l (s.rank_t $ v i) ↝ᴸ l n := λ i, s.seqs_le (by { simp[n], refine or.inr (le_fintype_sup _ i)}) in app (tr₀.fn _ (s.fn f)) (λ i, (tr i).fun_t (retruct_t (v i))) @[simp] def rank_p : formula L → ℕ | (app r v) := max (s.rank_pr r) (⨆ᶠ i, s.rank_t (v i)) | (t =' u) := max (s.rank_t t) (s.rank_t u) | ⊤ := 0 | (p ⟶ q) := max (rank_p p) (rank_p q) | (∼p) := rank_p p | (∀.p) := rank_p p @[simp, reducible] def retruct_p : Π p : formula L, formula (l $ s.rank_p p) | (app r v) := let tr₀ : l (s.rank_pr r) ↝ᴸ l (s.rank_p (app r v)) := s.seqs_le (by simp), tr : Π i, l (s.rank_t $ v i) ↝ᴸ l (s.rank_p (app r v)) := λ i, s.seqs_le (by { simp, refine or.inr (le_fintype_sup _ i)}) in app (tr₀.pr _ (s.pr r)) (λ i, (tr i).fun_t (s.retruct_t (v i))) | (equal t u) := let tr₁ : l (s.rank_t t) ↝ᴸ l (s.rank_p (equal t u)) := s.seqs_le (by simp), tr₂ : l (s.rank_t u) ↝ᴸ l (s.rank_p (equal t u)) := s.seqs_le (by simp) in (tr₁.fun_t $ s.retruct_t t) =' (tr₂.fun_t $ s.retruct_t u) | ⊤ := ⊤ | (p ⟶ q) := let tr₁ : l (s.rank_p p) ↝ᴸ l (s.rank_p (p ⟶ q)) := s.seqs_le (by simp), tr₂ : l (s.rank_p q) ↝ᴸ l (s.rank_p (p ⟶ q)) := s.seqs_le (by simp) in (tr₁.fun_p $ retruct_p p) ⟶ (tr₂.fun_p $ retruct_p q) | (∼p) := let tr₁ : l (s.rank_p p) ↝ᴸ l (s.rank_p (∼p)) := s.seqs_le (by simp) in ∼(tr₁.fun_p $ retruct_p p) | (∀.p) := let tr₁ : l (s.rank_p p) ↝ᴸ l (s.rank_p (∀.p)) := s.seqs_le (by simp) in ∀.(tr₁.fun_p $ retruct_p p) lemma retruct_t_spec (t : term L) : (s.to_limit (s.rank_t t)).fun_t (s.retruct_t t) = t := by induction t; simp[s.fn_spec]; case app : n f v IH { funext i, exact IH i } lemma retruct_p_spec (p : formula L) : (s.to_limit (s.rank_p p)).fun_p (s.retruct_p p) = p := by induction p; simp[s.pr_spec, retruct_t_spec, *] end seq_limit end language_translation end language def def_fn {n} (f : L₂.fn n) (p : formula L₁) : formula (L₁ + L₂) := ∀.[n] rew ı[0 ⇝ app (sum.inr f) ##] ↑p def def_pr {n} (r : L₂.pr n) (p : formula L₁) : formula (L₁ + L₂) := ∀.[n] (app (sum.inr r) ## ⟷ ↑p) @[simp] lemma def_fn_is_sentence {n} (f : L₂.fn n) (p : formula L₁) (hp : p.arity ≤ n + 1) : is_sentence (def_fn f p) := begin simp[def_fn, is_sentence] at hp ⊢, refine le_trans ((p : formula (L₁ + L₂)).rew_arity ı[0 ⇝ app (sum.inr f) (λ i, #i)]) (fintype_sup_le _), rintros ⟨i, hi⟩, cases i; simp at hi ⊢, { refine fintype_sup_le _, rintros ⟨i, hi⟩, simp[nat.succ_le_iff.mpr hi] }, { have : i + 1 < n + 1, from lt_of_lt_of_le hi hp, exact nat.lt_succ_iff.mp this } end @[simp] lemma def_pr_is_sentence {n} (r : L₂.pr n) (p : formula L₁) (hp : p.arity ≤ n) : is_sentence (def_pr r p) := by { simp[def_pr, is_sentence, hp], refine fintype_sup_le _, rintros ⟨i, hi⟩, simpa using nat.succ_le_iff.mpr hi } variables (L₁ L₂) structure language.definitions := (df_fn : Π {n : ℕ}, L₂.fn n → formula L₁) (hdf_fn : ∀ {n} {f : L₂.fn n}, (df_fn f).arity ≤ n + 1) (df_pr : Π {n : ℕ}, L₂.pr n → formula L₁) (hdf_pr : ∀ {n} {r : L₂.pr n}, (df_pr r).arity ≤ n) variables {L₁ L₂} (D : L₁.definitions L₂) def language.definitions.thy : Theory (L₁ + L₂) := (⋃ n, (set.range (λ (f : L₂.fn n), def_fn f (D.df_fn f)))) ∪ (⋃ n, (set.range (λ (r : L₂.pr n), def_pr r (D.df_pr r)))) lemma definitions_def : D.thy = (⋃ n, (set.range (λ (f : L₂.fn n), def_fn f (D.df_fn f)))) ∪ (⋃ n, (set.range (λ (r : L₂.pr n), def_pr r (D.df_pr r)))) := rfl instance language.definitions.closed : closed_Theory D.thy := ⟨by { simp[definitions_def], rintros p (⟨n, f, rfl⟩ | ⟨n, r, rfl⟩), { simp[D.hdf_fn] }, { simp[D.hdf_pr] } }⟩ @[simp] lemma language.definitions.mem_fn {n} (f : L₂.fn n) : (∀.[n] (D.df_fn f : formula (L₁ + L₂)).rew ı[0 ⇝ app (sum.inr f) ##]) ∈ D.thy := by simp[definitions_def, def_fn]; refine or.inl ⟨n, f, by refl⟩ @[simp] lemma language.definitions.fn {n} (f : L₂.fn n) (v : finitary (term (L₁ + L₂)) n) : D.thy ⊢ (D.df_fn f : formula (L₁ + L₂)).rew (app (sum.inr f) v ⌢ of_fin v) := by { have := provable.nfal_subst'_finitary (axiomatic_classical_logic'.by_axiom (language.definitions.mem_fn D f)) v, simp[formula.nested_rew] at this, refine cast (by { congr, funext x, rcases x; simp }) this } @[simp] lemma language.definitions.mem_pr {n} (r : L₂.pr n) : (∀.[n] ((app (sum.inr r) ## : formula (L₁ + L₂)) ⟷ (D.df_pr r))) ∈ D.thy := by simp[definitions_def, def_pr]; refine or.inr ⟨n, r, by refl⟩ @[simp] lemma language.definitions.pr {n} (r : L₂.pr n) (v : finitary (term (L₁ + L₂)) n) : D.thy ⊢ app (sum.inr r) v ⟷ (D.df_pr r).rew (of_fin v) := by { have := provable.nfal_subst'_finitary (axiomatic_classical_logic'.by_axiom (language.definitions.mem_pr D r)) v, simpa using this } section variables [language.predicate L₂] def term.coe_inv : term (L₁ + L₂) → term L₁ | (#n) := #n | (app f v) := by { rcases f, { refine app f (λ i, term.coe_inv (v i)) }, { exfalso, exact is_empty.false f } } @[simp] lemma coe_inv_coe (t : term L₁) : term.coe_inv (↑t : term (L₁ + L₂)) = t := by { induction t; simp[term.coe_inv], case app : n f v IH { rw [language.extension.coe_fn₁ f], simp, funext i, exact IH i } } @[simp] lemma coe_coe_inv (t : term (L₁ + L₂)) : (↑(term.coe_inv t) : term (L₁ + L₂)) = t := by { induction t; simp[term.coe_inv], case app : n f v IH { rcases f; simp, { refine ⟨rfl, _⟩, funext i, exact IH i }, { exfalso, exact is_empty.false f } } } def formula.coe_inv (D : L₁.definitions L₂) : formula (L₁ + L₂) → formula L₁ | (app r v) := by { rcases r, { exact app r (λ i, (v i).coe_inv) }, { exact (D.df_pr r).rew (of_fin (λ i, (v i).coe_inv)) } } | ((t : term (L₁ + L₂)) =' u) := t.coe_inv =' u.coe_inv | ⊤ := ⊤ | (p ⟶ q) := p.coe_inv ⟶ q.coe_inv | (∼p) := ∼p.coe_inv | (∀.p) := ∀.p.coe_inv lemma coe_inv_equiv (p : formula (L₁ + L₂)) : D.thy ⊢ p ⟷ ↑(formula.coe_inv D p) := begin induction p; simp[formula.coe_inv], case app : n r v { rcases r; simp[language.extension.coe_pr₁, language.language_translation_coe.coe_p_rew], have : (λ x, ↑(of_fin (λ i, (v i).coe_inv) x)) = of_fin v, { funext x, have : x < n ∨ n ≤ x, exact lt_or_ge x n, rcases this with (C | C); simp[C] }, simp[this] }, case imply : p q IH_p IH_q { simp[Lindenbaum.eq_of_provable_equiv_0, Lindenbaum.eq_of_provable_equiv_0.mp IH_p, Lindenbaum.eq_of_provable_equiv_0.mp IH_q] }, case neg : p IH { refine Lindenbaum.eq_of_provable_equiv_0.mpr (by simp[IH]) }, case fal : p IH { have : D.thy^1 ⊢ p ⟷ ↑(formula.coe_inv D p), by simpa using IH, simp[Lindenbaum.eq_of_provable_equiv_0, Lindenbaum.eq_of_provable_equiv.mp this] } end @[simp] def formula.coe_inv_is_open (D : L₁.definitions L₂) : Theory (L₁ + L₂) | (app r v) := by { rcases r, { exact true }, { exact (D.df_pr r).is_open } } | ((t : term (L₁ + L₂)) =' u) := true | ⊤ := true | (p ⟶ q) := p.coe_inv_is_open ∧ q.coe_inv_is_open | (∼p) := p.coe_inv_is_open | (∀.p) := false @[simp] lemma coe_inv_open (p : formula (L₁ + L₂)) : (formula.coe_inv D p).is_open ↔ formula.coe_inv_is_open D p := by { induction p; simp[formula.coe_inv, *], case app : n r v { rcases r; simp, } } end namespace Structure variables {L₁ L₂} (M₁ : Structure L₁) open language language.extension @[reducible] def extend (fn : Π {n} (f : L₂.fn n) (v : finitary M₁.dom n), M₁.dom) (pr : Π {n} (r : L₂.pr n) (v : finitary M₁.dom n), Prop) : Structure (L₁ + L₂) := { dom := M₁.dom, inhabited := M₁.inhabited, fn := λ n f v, by { rcases f, { exact M₁.fn f v }, { exact fn f v } }, pr := λ n r v, by { rcases r, { exact M₁.pr r v }, { exact pr r v } } } lemma extend_val_coe_term (fn : Π {n} (f : L₂.fn n) (v : finitary M₁.dom n), M₁.dom) (pr : Π {n} (r : L₂.pr n) (v : finitary M₁.dom n), Prop) {t : term L₁} {e : ℕ → M₁.dom} : @term.val (L₁ + L₂) (M₁.extend @fn @pr) e (t : term (L₁ + L₂)) = @term.val L₁ M₁ e t := by induction t; simp[*, coe_fn₁] lemma extend_val_coe_iff (fn : Π {n} (f : L₂.fn n) (v : finitary M₁.dom n), M₁.dom) (pr : Π {n} (r : L₂.pr n) (v : finitary M₁.dom n), Prop) {p : formula L₁} {e : ℕ → M₁.dom} : M₁.extend @fn @pr ⊧[e] ↑p ↔ M₁ ⊧[e] p := by induction p generalizing e; simp[coe_pr₁, extend_val_coe_term, *] lemma extend_models_coe_iff (fn : Π {n} (f : L₂.fn n) (v : finitary M₁.dom n), M₁.dom) (pr : Π {n} (r : L₂.pr n) (v : finitary M₁.dom n), Prop) {p : formula L₁} : M₁.extend @fn @pr ⊧ (p : formula (L₁ + L₂)) ↔ M₁ ⊧ p := ⟨λ h e, (M₁.extend_val_coe_iff @fn @pr).mp (h e), λ h e, (M₁.extend_val_coe_iff @fn @pr).mpr (h e)⟩ lemma extend_modelsth_coe_iff (fn : Π {n} (f : L₂.fn n) (v : finitary M₁.dom n), M₁.dom) (pr : Π {n} (r : L₂.pr n) (v : finitary M₁.dom n), Prop) {T : Theory L₁} : M₁.extend @fn @pr ⊧ (↑T : Theory (L₁ + L₂)) ↔ M₁ ⊧ T := ⟨λ h p mem, (M₁.extend_models_coe_iff @fn @pr).mp (h (show ↑p ∈ ↑T, by simp[mem])), λ h p mem, by { rcases language_translation_coe.mem_coe_iff.mp mem with ⟨p, pmem, rfl⟩, exact (M₁.extend_models_coe_iff @fn @pr).mpr (h pmem) }⟩ variables (τ : L₁ ↭ᴸ L₂) @[reducible] def of_equiv : Structure L₂ := { dom := M₁.dom, inhabited := M₁.inhabited, fn := λ n f, M₁.fn (τ.inv.fn _ f), pr := λ n r, M₁.pr (τ.inv.pr _ r) } variables {M₁} @[simp] lemma equiv_term {t : term L₁} {e : ℕ → M₁.dom} : @term.val L₂ (M₁.of_equiv τ) e (τ.ltr.fun_t t) = @term.val L₁ M₁ e t := by induction t; simp* lemma equiv_val_iff {p : formula L₁} {e : ℕ → M₁.dom} : M₁.of_equiv τ ⊧[e] τ.ltr.fun_p p ↔ M₁ ⊧[e] p := by induction p generalizing e; simp[of_equiv, *] @[simp] lemma equiv_models_iff {p : formula L₁} : M₁.of_equiv τ ⊧ τ.ltr.fun_p p ↔ M₁ ⊧ p := ⟨λ h e, (equiv_val_iff τ).mp (h e), λ h e, (equiv_val_iff τ).mpr (h e)⟩ @[simp] lemma equiv_modelsth_iff {T : Theory L₁} : M₁.of_equiv τ ⊧ τ.ltr.fun_Theory T ↔ M₁ ⊧ T := ⟨λ h p mem, (equiv_models_iff τ).mp (h ⟨p, by simp[mem]⟩), λ h p mem, by { rcases mem with ⟨p', mem, rfl⟩, exact (equiv_models_iff τ).mpr (h mem) }⟩ end Structure def Theory_of (M : Structure L) : Theory L := {p | M ⊧ p} class Theory_of_Structure (M : Structure L) (T : Theory L) := (models : M ⊧ T) namespace language namespace language_translation variables {L₁ L₂} {τ : L₁ ↝ᴸ L₂} {M₂ : Structure L₂} @[reducible] def of_ltr (τ : L₁ ↝ᴸ L₂) (M₂ : Structure L₂) : Structure L₁ := { dom := M₂.dom, inhabited := M₂.inhabited, fn := λ n f v, M₂.fn (τ.fn _ f) v, pr := λ n r v, M₂.pr (τ.pr _ r) v } lemma of_ltr_val_t (e : ℕ → M₂.dom) (t : term L₁) : (τ.fun_t t).val M₂ e = t.val (τ.of_ltr M₂) e := by induction t; simp* lemma models_val_iff {e : ℕ → M₂.dom} {p : formula L₁} : τ.of_ltr M₂ ⊧[e] p ↔ M₂ ⊧[e] τ.fun_p p := by induction p generalizing e; try { simp[*, of_ltr_val_t] } theorem models_iff {p : formula L₁} : τ.of_ltr M₂ ⊧ p ↔ M₂ ⊧ τ.fun_p p:= ⟨λ h e, models_val_iff.mp (h e), λ h e, models_val_iff.mpr (h e)⟩ theorem Theory_models_iff {T : Theory L₁} : τ.of_ltr M₂ ⊧ T ↔ M₂ ⊧ τ.fun_Theory T := by simp[fun_Theory, logic.semantics.Models_def, models_iff] end language_translation end language end fol
(*File: ContextVS.thy*) (*Authors: Lennart Beringer and Martin Hofmann, LMU Munich 2008*) theory ContextVS imports VS begin subsection\<open>Contextual closure\<close> text\<open>\label{sec:contextVS}We show that the notion of security is closed w.r.t.~low attacking contexts, i.e.~contextual programs into which a secure program can be substituted and which itself employs only \emph{obviously} low variables.\<close> text\<open>Contexts are {\bf IMP} programs with (multiple) designated holes (represented by constructor $\mathit{Ctxt\_Here}$).\<close> datatype CtxtProg = Ctxt_Hole | Ctxt_Skip | Ctxt_Assign Var Expr | Ctxt_Comp CtxtProg CtxtProg | Ctxt_If BExpr CtxtProg CtxtProg | Ctxt_While BExpr CtxtProg | Ctxt_Call text\<open>We let $C$, $D$ range over contextual programs. The substitution operation is defined by structural recursion.\<close> primrec Fill::"CtxtProg \<Rightarrow> IMP \<Rightarrow> IMP" where "Fill Ctxt_Hole c = c" | "Fill Ctxt_Skip c = Skip" | "Fill (Ctxt_Assign x e) c = Assign x e" | "Fill (Ctxt_Comp C1 C2) c = Comp (Fill C1 c) (Fill C2 c)" | "Fill (Ctxt_If b C1 C2) c = Iff b (Fill C1 c) (Fill C2 c)" | "Fill (Ctxt_While b C) c = While b (Fill C c)" | "Fill Ctxt_Call c = Call" text\<open>Equally obvious are the definitions of the (syntactically) mentioned variables of arithmetic and boolean expressions.\<close> primrec EVars::"Expr \<Rightarrow> Var set" where "EVars (varE x) = {x}" | "EVars (valE v) = {}" | "EVars (opE f e1 e2) = EVars e1 \<union> EVars e2" lemma low_Eval[rule_format]: "(\<forall> x . x \<in> EVars e \<longrightarrow> CONTEXT x = low) \<longrightarrow> (\<forall> s t . s \<approx> t \<longrightarrow> evalE e s = evalE e t)" (*<*) apply (induct e) apply (simp add: twiddle_def) apply simp apply clarsimp done (*>*) primrec BVars::"BExpr \<Rightarrow> Var set" where "BVars (compB f e1 e2) = EVars e1 \<union> EVars e2" lemma low_EvalB[rule_format]: "(\<forall> x . x \<in> BVars b \<longrightarrow> CONTEXT x = low) \<longrightarrow> (\<forall> s t . s \<approx> t \<longrightarrow> evalB b s = evalB b t)" (*<*) apply (induct b) apply (rename_tac Expr1 Expr2) apply clarsimp apply (subgoal_tac "evalE Expr1 s = evalE Expr1 t") prefer 2 apply (rule low_Eval) apply fast apply assumption apply (subgoal_tac "evalE Expr2 s = evalE Expr2 t") prefer 2 apply (rule low_Eval) apply fast apply assumption apply simp done (*>*) text\<open>The variables possibly read from during the evaluation of $c$ are denoted by $\mathit{Vars\; c}$. Note that in the clause for assignments the variable that is assigned to is not included in the set.\<close> primrec Vars::"IMP \<Rightarrow> Var set" where "Vars Skip = {}" | "Vars (Assign x e) = EVars e" | "Vars (Comp c d) = Vars c \<union> Vars d" | "Vars (While b c) = BVars b \<union> Vars c" | "Vars (Iff b c d) = BVars b \<union> Vars c \<union> Vars d" | "Vars Call = {}" text\<open>For contexts, we define when a set $X$ of variables is an upper bound for the variables read from.\<close> primrec CtxtVars::"Var set \<Rightarrow> CtxtProg \<Rightarrow> bool" where "CtxtVars X Ctxt_Hole = True" | "CtxtVars X Ctxt_Skip = True" | "CtxtVars X (Ctxt_Assign x e) = (EVars e \<subseteq> X)" | "CtxtVars X (Ctxt_Comp C1 C2) = (CtxtVars X C1 \<and> CtxtVars X C2)" | "CtxtVars X (Ctxt_If b C1 C2) = (BVars b \<subseteq> X \<and> CtxtVars X C1 \<and> CtxtVars X C2)" | "CtxtVars X (Ctxt_While b C) = (BVars b \<subseteq> X \<and> CtxtVars X C)" | "CtxtVars X Ctxt_Call = True" (*<*) lemma Secure_comp: "\<lbrakk>secure c1; secure c2\<rbrakk> \<Longrightarrow> secure (Comp c1 c2)" apply (unfold secure_def) apply (rule, rule, rule, rule) apply (rule, rule, rule) apply (unfold Sem_def) apply (erule exE)+ apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) apply (erule_tac x=s in allE, rotate_tac -1) apply (erule_tac x=t in allE, rotate_tac -1) apply (erule_tac x=r in allE, rotate_tac -1) apply (erule_tac x=ra in allE) apply (erule impE, assumption) apply (erule impE, rule, assumption) apply (erule impE, rule, assumption) apply (erule_tac x=r in allE, rotate_tac -1) apply (erule_tac x=ra in allE, rotate_tac -1) apply (erule_tac x=ss in allE, rotate_tac -1) apply (erule_tac x=tt in allE) apply (erule impE, assumption) apply (erule impE, rule, assumption) apply (erule impE, rule, assumption) apply assumption done lemma Secure_iff: " \<lbrakk>secure c1; secure c2; \<forall> s ss. s \<approx> ss \<longrightarrow> evalB b s = evalB b ss\<rbrakk> \<Longrightarrow> secure (Iff b c1 c2)" apply (unfold secure_def) apply (rule, rule, rule, rule) apply (rule, rule, rule) apply (unfold Sem_def) apply (erule exE)+ apply (erule_tac x=s in allE, erule_tac x=t in allE, erule impE, assumption) apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) apply (erule_tac x=s in allE, rotate_tac -1) apply (erule_tac x=t in allE, rotate_tac -1) apply (erule_tac x=ss in allE, rotate_tac -1) apply (erule_tac x=tt in allE) apply (erule impE, assumption) apply (erule impE, rule, assumption) apply (erule impE, rule, assumption) apply assumption apply fast apply (erule Sem_eval_cases) apply fast apply (erule thin_rl) apply (erule_tac x=s in allE, rotate_tac -1) apply (erule_tac x=t in allE, rotate_tac -1) apply (erule_tac x=ss in allE, rotate_tac -1) apply (erule_tac x=tt in allE) apply (erule impE, assumption) apply (erule impE, rule, assumption) apply (erule impE, rule, assumption) apply assumption done lemma secure_while_aux[rule_format]: "\<forall> n m . n \<le> k \<longrightarrow> m \<le> k \<longrightarrow> (\<forall> s t ss tt . (s , While b c \<rightarrow>\<^sub>n ss) \<longrightarrow> (t , While b c \<rightarrow>\<^sub>m tt) \<longrightarrow> secure c \<longrightarrow> (\<forall>s ss. s \<approx> ss \<longrightarrow> evalB b s = evalB b ss) \<longrightarrow> s \<approx> t \<longrightarrow> ss \<approx> tt)" apply (induct k) apply clarsimp apply (drule Sem_no_zero_height_derivs, clarsimp) apply clarsimp apply (subgoal_tac "evalB b s = evalB b t") prefer 2 apply (erule thin_rl, fast) apply (erule Sem_eval_cases) prefer 2 apply (erule Sem_eval_cases, simp, simp) apply (erule Sem_eval_cases) prefer 2 apply simp apply clarsimp apply (subgoal_tac "r \<approx> ra", clarsimp) apply (erule thin_rl, unfold secure_def Sem_def) apply fast done lemma Secure_while: " \<lbrakk>secure c; \<forall> s ss. s \<approx> ss \<longrightarrow> evalB b s = evalB b ss\<rbrakk> \<Longrightarrow> secure (While b c)" apply (simp (no_asm_simp) add: secure_def) apply (rule, rule, rule, rule) apply (rule, rule, rule) apply (unfold Sem_def) apply (erule exE)+ apply (rule secure_while_aux) prefer 3 apply assumption prefer 6 apply assumption prefer 3 apply assumption prefer 3 apply assumption prefer 3 apply fast apply (subgoal_tac "n \<le> n + na", assumption) apply (simp, simp) done (*>*) text\<open>A constant representing the procedure body with holes.\<close> consts Ctxt_Body::CtxtProg text\<open>The following predicate expresses that all variables read from by a command $c$ are contained in the set $X$ of low variables.\<close> definition LOW::"Var set \<Rightarrow> CtxtProg \<Rightarrow> bool" where "LOW X C = (CtxtVars X C \<and> (\<forall> x . x : X \<longrightarrow> CONTEXT x = low))" (*<*) lemma secureI_secureFillI_Aux[rule_format]: "\<forall> n m . n \<le> k \<longrightarrow> m \<le> k \<longrightarrow> (\<forall> C d s t ss tt X . (s , d \<rightarrow>\<^sub>n t) \<longrightarrow> (ss , d \<rightarrow>\<^sub>m tt) \<longrightarrow> s \<approx> ss \<longrightarrow> d = Fill C c \<longrightarrow> LOW X C \<longrightarrow> LOW X Ctxt_Body \<longrightarrow> body = Fill Ctxt_Body c \<longrightarrow> secure c \<longrightarrow> t \<approx> tt)" apply (induct k) apply clarsimp apply (drule Sem_no_zero_height_derivs, clarsimp) apply clarsimp apply (case_tac C) (*Ctxt_Hole*) apply clarsimp defer 1 (*Ctxt_Skip*) apply clarsimp apply (erule Sem_eval_cases)+ apply clarsimp (*Ctxt_Assign*) apply clarsimp apply (erule thin_rl) apply (erule Sem_eval_cases)+ apply clarsimp apply (simp add: update_def LOW_def twiddle_def) apply clarsimp apply (rule low_Eval) apply fast apply (simp add: twiddle_def) (*Ctxt_Comp*) apply clarsimp apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) apply clarsimp apply (subgoal_tac "r \<approx> ra") prefer 2 apply (simp add: LOW_def) apply (erule_tac x=na in allE, clarsimp) apply (simp add: LOW_def) apply (erule_tac x=ma in allE, clarsimp) (*Ctxt_If*) apply (rename_tac BExpr u v) apply clarsimp apply (subgoal_tac "evalB BExpr s = evalB BExpr ss") prefer 2 apply (erule thin_rl, case_tac BExpr, clarsimp) apply (rename_tac Expr1 Expr2) apply (subgoal_tac "evalE Expr1 s = evalE Expr1 ss", clarsimp) apply (subgoal_tac "evalE Expr2 s = evalE Expr2 ss", clarsimp) apply (rule low_Eval) apply (simp add: LOW_def) apply fast apply clarsimp apply (rule low_Eval) apply (simp add: LOW_def) apply fast apply clarsimp apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) prefer 2 apply clarsimp apply clarsimp apply (simp add: LOW_def) apply (erule_tac x=na in allE, clarsimp) apply (erule Sem_eval_cases) apply clarsimp apply (simp add: LOW_def) apply (erule_tac x=na in allE, clarsimp) (*Ctxt_While*) apply (rename_tac BExpr CtxtProg) apply clarsimp apply (subgoal_tac "evalB BExpr s = evalB BExpr ss") prefer 2 apply (erule thin_rl, case_tac BExpr, clarsimp) apply (rename_tac Expr1 Expr2) apply (subgoal_tac "evalE Expr1 s = evalE Expr1 ss", clarsimp) apply (subgoal_tac "evalE Expr2 s = evalE Expr2 ss", clarsimp) apply (rule low_Eval) apply (simp add: LOW_def) apply fast apply clarsimp apply (rule low_Eval) apply (simp add: LOW_def) apply fast apply clarsimp apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) prefer 2 apply clarsimp apply (subgoal_tac "r \<approx> ra") prefer 2 apply (simp add: LOW_def) apply (erule_tac x=na in allE, clarsimp) apply (erule_tac x=ma in allE, clarsimp) apply (erule_tac x=mb in allE, clarsimp) apply (erule_tac x="Ctxt_While BExpr CtxtProg" in allE) apply (erule_tac x="While BExpr (Fill CtxtProg c)" in allE, clarsimp) apply (erule Sem_eval_cases) apply clarsimp apply clarsimp (*Ctxt_Call*) apply clarsimp apply (erule Sem_eval_cases) apply (erule Sem_eval_cases) apply (erule_tac x=na in allE, clarsimp) (*The deferred goal from Ctxt\_Hole*) apply (unfold secure_def Sem_def) apply (erule thin_rl) apply fast done (*>*) text\<open>By induction on the maximal height of the operational judgement (hidden in the definition of $\mathit{secure}$) we can prove that the security of $c$ implies that of $\mathit{Fill}\ C\ c$, provided that the context and the procedure-context satisfy the $\mathit{LOW}$ predicate for some $X$, and that the "real" body is obtained by substituting $c$ into the procedure context.\<close> lemma secureI_secureFillI: "\<lbrakk>secure c; LOW X C; LOW X Ctxt_Body; body = Fill Ctxt_Body c\<rbrakk> \<Longrightarrow> secure (Fill C c)" (*<*) apply (simp (no_asm_simp) add: secure_def Sem_def) apply clarsimp apply (rule secureI_secureFillI_Aux) prefer 3 apply assumption prefer 4 apply assumption prefer 3 apply assumption apply (subgoal_tac "n \<le> n+na", assumption) apply (erule thin_rl, simp) apply (erule thin_rl, simp) apply (erule thin_rl,fastforce) apply assumption apply assumption apply assumption apply assumption done (*>*) text\<open>Consequently, a (low) variable representing the result of the attacking context does not leak any unwanted information.\<close> consts res::Var theorem "\<lbrakk> secure c; LOW X C; LOW X Ctxt_Body; s \<approx> ss; s,(Fill C c)\<Down>t; ss,(Fill C c)\<Down>tt; body = Fill Ctxt_Body c; CONTEXT res = low\<rbrakk> \<Longrightarrow> t res = tt res" (*<*) apply (drule secureI_secureFillI) apply assumption apply assumption apply assumption apply (unfold secure_def) apply (erule_tac x=s in allE, erule_tac x=ss in allE) apply (erule_tac x=t in allE, erule_tac x=tt in allE, clarsimp) apply (simp add: twiddle_def) done (*>*) text\<open>End of theory ContextVS\<close> end
@defcomp impactextratropicalstorms begin regions = Index() extratropicalstormsdam = Variable(index=[time,regions]) extratropicalstormsdead = Variable(index=[time,regions]) extratropicalstormsbasedam = Parameter(index=[regions]) extratropicalstormsdamel = Parameter(default = -0.514) extratropicalstormspar = Parameter(index=[regions]) extratropicalstormsbasedead = Parameter(index=[regions]) extratropicalstormsdeadel = Parameter(default = -0.501) extratropicalstormsnl = Parameter(default = 1) gdp90 = Parameter(index=[regions]) pop90 = Parameter(index=[regions]) population = Parameter(index=[time,regions]) income = Parameter(index=[time,regions]) acco2 = Parameter(index=[time]) co2pre = Parameter() function run_timestep(p, v, d, t) for r in d.regions ypc = p.income[t, r] / p.population[t, r] * 1000.0 ypc90 = p.gdp90[r] / p.pop90[r] * 1000.0 v.extratropicalstormsdam[t, r] = p.extratropicalstormsbasedam[r] * p.income[t, r] * (ypc / ypc90)^p.extratropicalstormsdamel * ((1.0 + (p.extratropicalstormspar[r] * (p.acco2[t] / p.co2pre)))^p.extratropicalstormsnl - 1.0) v.extratropicalstormsdead[t, r] = 1000.0 * p.extratropicalstormsbasedead[r] * p.population[t, r] * (ypc / ypc90)^p.extratropicalstormsdeadel * ((1.0 + (p.extratropicalstormspar[r] * (p.acco2[t] / p.co2pre)))^p.extratropicalstormsnl - 1.0) end end end
<!--- <div style="text-align: center;"> <font size="5"> <b>Data-driven Design and Analyses of Structures and Materials (3dasm)</b> </font> </div> <br> </br> <div style="text-align: center;"> <font size="5"> <b>Lecture 1</b> </font> </div> <center> </center> <div style="text-align: center;"> <font size="4"> <b>Miguel A. Bessa | <a href = "mailto: [email protected]">[email protected]</a> | Associate Professor</b> </font> </div> --> ## Data-driven Design and Analyses of Structures and Materials (3dasm) ## Lecture 1 ### Miguel A. Bessa | <a href = "mailto: [email protected]">[email protected]</a> | Associate Professor ## Introduction **What:** A lecture of the "3dasm" course **Where:** This notebook comes from this [repository](https://github.com/bessagroup/3dasm_course) **Reference for entire course:** Murphy, Kevin P. *Probabilistic machine learning: an introduction*. MIT press, 2022. Available online [here](https://probml.github.io/pml-book/book1.html) **How:** We try to follow Murphy's book closely, but the sequence of Chapters and Sections is different. The intention is to use notebooks as an introduction to the topic and Murphy's book as a resource. * If working offline: Go through this notebook and read the book. * If attending class in person: listen to me (!) but also go through the notebook in your laptop at the same time. Read the book. * If attending lectures remotely: listen to me (!) via Zoom and (ideally) use two screens where you have the notebook open in 1 screen and you see the lectures on the other. Read the book. **Optional reference (the "bible" by the "bishop"... pun intended 😆) :** Bishop, Christopher M. *Pattern recognition and machine learning*. Springer Verlag, 2006. **References/resources to create this notebook:** * [Figure (Car stopping distance)](https://korkortonline.se/en/theory/reaction-braking-stopping/) * Snippets of code from this awesome [repo](https://github.com/gerdm/prml) by Gerardo Duran-Martin that replicates many figures in Bishop's book Apologies in advance if I missed some reference used in this notebook. Please contact me if that is the case, and I will gladly include it here. ## **OPTION 1**. Run this notebook **locally in your computer**: 1. Install miniconda3 [here](https://docs.conda.io/en/latest/miniconda.html) 2. Open a command window and create a virtual environment called "3dasm": ``` conda create -n 3dasm python=3 numpy scipy jupyter nb_conda matplotlib pandas scikit-learn rise tensorflow -c conda-forge ``` 3. Install [git](https://github.com/git-guides/install-git), open command window & clone the repository to your computer: ``` git clone https://github.com/bessagroup/3dasm_course ``` 4. Load jupyter notebook by typing in (anaconda) command window (it will open in your internet browser): ``` conda activate 3dasm jupyter notebook ``` 5. Open notebook (3dasm_course/Lectures/Lecture1/3dasm_Lecture1.ipynb) **Short note:** My personal environment also has other packages that help me while teaching. > conda install -n 3dasm -c conda-forge jupyter_contrib_nbextensions hide_code Then in the 3dasm conda environment: > jupyter nbextension install --py hide_code --sys-prefix > > jupyter nbextension enable --py hide_code > > jupyter serverextension enable --py hide_code > > jupyter nbextension enable splitcell/splitcell ## **OPTION 2**. Use **Google's Colab** (no installation required, but times out if idle): 1. go to https://colab.research.google.com 2. login 3. File > Open notebook 4. click on Github (no need to login or authorize anything) 5. paste the git link: https://github.com/bessagroup/3dasm_course 6. click search and then click on the notebook (*3dasm_course/Lectures/Lecture1/3dasm_Lecture1.ipynb*) ```python # Basic plotting tools needed in Python. import matplotlib.pyplot as plt # import plotting tools to create figures import numpy as np # import numpy to handle a lot of things! %config InlineBackend.figure_format = "retina" # render higher resolution images in the notebook plt.style.use("seaborn") # style for plotting that comes from seaborn plt.rcParams["figure.figsize"] = (8,4) # rescale figure size appropriately for slides ``` ## Outline for today * Introduction - Taking a probabilistic perspective on machine learning * Basics of univariate statistics - Continuous random variables - Probabilities vs probability densities - Moments of a probability distribution * The mindblowing Bayes' rule - The rule that spawns almost every ML model (even when we don't realize it) **Reading material**: This notebook + Chapter 2 until Section 2.3 ## Get hyped about Artificial Intelligence... ```python from IPython.display import display, YouTubeVideo, HTML YouTubeVideo('RNnZwvklwa8', width=512, height=288) # show that slides are interactive: # rescale video to 768x432 and back to 512x288 ``` **Well...** This class *might* not make you break the world (yet!). Let's focus on the fundamentals: * Probabilistic perspective on machine learning * Supervised learning (especially regression) ## Machine learning (ML) * **ML definition**: A computer program that learns from experience $E$ wrt tasks $T$ such that the performance $P$ at those tasks improves with experience $E$. * We'll treat ML from a **probabilistic perspective**: - Treat all unknown quantities as **random variables** * What are random variables? - Variables endowed with probability distributions! ## The car stopping distance problem <br></br> Car stopping distance ${\color{red}y}$ as a function of its velocity ${\color{green}x}$ before it starts braking: ${\color{red}y} = {\color{blue}z} x + \frac{1}{2\mu g} {\color{green}x}^2 = {\color{blue}z} x + 0.1 {\color{green}x}^2$ - ${\color{blue}z}$ is the driver's reaction time (in seconds) - $\mu$ is the road/tires coefficient of friction (assume $\mu=0.5$) - $g$ is the acceleration of gravity (assume $g=10$ m/s$^2$). ## The car stopping distance problem ### How to obtain this formula? $y = d_r + d_{b}$ where $d_r$ is the reaction distance, and $d_b$ is the braking distance. ### Reaction distance $d_r$ $d_r = z x$ with $z$ being the driver's reaction time, and $x$ being the velocity of the car at the start of braking. ## The car stopping distance problem ### Braking distance $d_b$ Kinetic energy of moving car: $E = \frac{1}{2}m x^2$ &nbsp; &nbsp; &nbsp; where $m$ is the car mass. Work done by braking: $W = \mu m g d_b$ &nbsp; &nbsp; &nbsp; where $\mu$ is the coefficient of friction between the road and the tire, $g$ is the acceleration of gravity, and $d_b$ is the car braking distance. The braking distance follows from $E=W$: $d_b = \frac{1}{2\mu g}x^2$ Therefore, if we add the reacting distance $d_r$ to the braking distance $d_b$ we get the stopping distance $y$: $$y = d_r + d_b = z x + \frac{1}{2\mu g} x^2$$ ## The car stopping distance problem $y = {\color{blue}z} x + 0.1 x^2$ The driver's reaction time ${\color{blue}z}$ is a **random variable (rv)** * Every driver has its own reaction time $z$ * Assume the distribution associated to $z$ is Gaussian with **mean** $\mu_z=1.5$ seconds and **variance** $\sigma_z^2=0.5$ seconds$^2$ $$ z \sim \mathcal{N}(\mu_z=1.5,\sigma_z^2=0.5^2) $$ where $\sim$ means "sampled from", and $\mathcal{N}$ indicates a Gaussian **probability density function (pdf)** ## Univariate Gaussian <a title="probability density function">pdf</a> The gaussian <a title="probability density function">pdf</a> is defined as: $$ \mathcal{N}(z | \mu_z, \sigma_z^2) = \frac{1}{\sqrt{2\pi\sigma_z^2}}e^{-\frac{1}{2\sigma_z^2}(z - \mu_z)^2} $$ Alternatively, we can write it using the **precision** term $\lambda_z := 1 / \sigma_z^2$ instead of using $\sigma_z^2$: $$ \mathcal{N}(z | \mu_z, \lambda_z^{-1}) = \frac{\lambda_z^{1/2}}{\sqrt{2\pi}}e^{-\frac{\lambda_z}{2}(z - \mu_z)^2} $$ Anyway, recall how this <a title="probability density function">pdf</a> looks like... ```python def norm_pdf(z, mu_z, sigma_z2): return 1 / np.sqrt(2 * np.pi * sigma_z2) * np.exp(-(z - mu_z)**2 / (2 * sigma_z2)) zrange = np.linspace(-8, 4, 200) # create a list of 200 z points between z=-8 and z=4 fig, ax = plt.subplots() # create a plot ax.plot(zrange, norm_pdf(zrange, 0, 1), label=r"$\mu_z=0; \ \sigma_z^2=1$") # plot norm_pdf(z|0,1) ax.plot(zrange, norm_pdf(zrange, 1.5, 0.5**2), label=r"$\mu_z=1.5; \ \sigma_z^2=0.5^2$") # plot norm_pdf(z|1.5,0.5^2) ax.plot(zrange, norm_pdf(zrange, -1, 2**2), label=r"$\mu_z=-1; \ \sigma_z^2=2^2$") # plot norm_pdf(z|-1,2^2) ax.set_xlabel("z", fontsize=20) # create x-axis label with font size 20 ax.set_ylabel("probability density", fontsize=20) # create y-axis label with font size 20 ax.legend(fontsize=15) # create legend with font size 15 ax.set_title("Three different Gaussian pdfs", fontsize=20); # create title with font size 20 ``` The <span style="color:green">green</span> curve shows the Gaussian <a title="probability density function">pdf</a> of the <a title="random variable">rv</a> $z$ **conditioned** on the mean $\mu_z=1.5$ and variance $\sigma_z^2=0.5^2$ for the car stopping distance problem. ## Univariate Gaussian <a title="probability density function">pdf</a> $$ p(z) = \mathcal{N}(z | \mu_z, \sigma_z^2) = \frac{1}{\sqrt{2\pi\sigma_z^2}}e^{-\frac{1}{2\sigma_z^2}(z - \mu_z)^2} $$ The output of this expression is the **PROBABILITY DENSITY** of $z$ **given** (or conditioned to) a particular $\mu_z$ and $\sigma_z^2$. * **Important**: Probability Density $\neq$ Probability So, what is a probability? ## Probability The probability of an event $A$ is denoted by $\text{Pr}(A)$. * $\text{Pr}(A)$ means the probability with which we believe event A is true * An event $A$ is a binary variable saying whether or not some state of the world holds. Probability is defined such that: $0 \leq \text{Pr}(A) \leq 1$ where $\text{Pr}(A)=1$ if the event will definitely happen and $\text{Pr}(A)=0$ if it definitely will not happen. ## Joint probability **Joint probability** of two events: $\text{Pr}(A \wedge B)= \text{Pr}(A, B)$ If $A$ and $B$ are **independent**: $\text{Pr}(A, B)= \text{Pr}(A) \text{Pr}(B)$ For example, suppose $z_1$ and $z_2$ are chosen uniformly at random from the set $\mathcal{Z} = \{1, 2, 3, 4\}$. Let $A$ be the event that $z_1 \in \{1, 2\}$ and $B$ be the event that **another** <a title="random variable">rv</a> denoted as $z_2 \in \{3\}$. Then we have: $\text{Pr}(A, B) = \text{Pr}(A) \text{Pr}(B) = \frac{1}{2} \cdot \frac{1}{4}$. ## Probability of a union of two events Probability of event $A$ or $B$ happening is: $\text{Pr}(A \vee B)= \text{Pr}(A) + \text{Pr}(B) - \text{Pr}(A \wedge B)$ If these events are mutually exclusive (they can't happen at the same time): $$ \text{Pr}(A \vee B)= \text{Pr}(A) + \text{Pr}(B) $$ For example, suppose an <a title="random variable">rv</a> denoted as $z_1$ is chosen uniformly at random from the set $\mathcal{Z} = \{1, 2, 3, 4\}$. Let $A$ be the event that $z_1 \in \{1, 2\}$ and $B$ be the event that the **same** <a title="random variable">rv</a> $z_1 \in \{3\}$. Then we have $\text{Pr}(A \vee B) = \frac{2}{4} + \frac{1}{4}$. ## Conditional probability of one event given another We define the **conditional probability** of event $B$ happening given that $A$ has occurred as follows: $$ \text{Pr}(B | A)= \frac{\text{Pr}(A,B)}{\text{Pr}(A)} $$ This is not defined if $\text{Pr}(A) = 0$, since we cannot condition on an impossible event. ## Conditional independence of one event given another We say that event $A$ is conditionally independent of event $B$ if we have $\text{Pr}(A | B)= \text{Pr}(A)$ This implies $\text{Pr}(B|A) = \text{Pr}(B)$. Hence, the joint probability becomes $\text{Pr}(A, B) = \text{Pr}(A) \text{Pr}(B)$ The book uses the notation $A \perp B$ to denote this property. ## Coming back to our car stopping distance problem $y = {\color{blue}z} x + 0.1 x^2$ where $z$ is a **continuous** <a title="random variable">rv</a> such that $z \sim \mathcal{N}(\mu_z=1.5,\sigma_z^2=0.5^2)$. * What is the probability of an event $Z$ defined by a reaction time $z \leq 0.52$ seconds? $$ \text{Pr}(Z)=\text{Pr}(z \leq 0.52)= P(z=0.52) $$ where $P(z)$ denotes the **cumulative distribution function (cdf)**. Note that <a title="cumulative distribution function">cdf</a> is denoted with a capital $P$. Likewise, we can compute the probability of being in any interval as follows: $\text{Pr}(a \leq z \leq b)= P(z=b)-P(z=a)$ * But how do we compute the cdf at a particular value $b$, e.g. $P(z=b)$? ## <a title="Cumulative distribution functions">Cdf's</a> result from <a title="probability density functions">pdf's</a> A <a title="probability density functions">pdf</a> $p(z)$ is defined as the derivative of the <a title="cumulative distribution functions">cdf</a> $P(z)$: $$ p(z)=\frac{d}{d z}P(z) $$ So, given a <a title="probability density function">pdf</a> $p(z)$, we can compute the following probabilities: $$\text{Pr}(z \leq b)=\int_{-\infty}^b p(z) dz = P(b)$$ $$\text{Pr}(z \geq a)=\int_a^{\infty} p(z) dz = 1 - P(a)$$ $$\text{Pr}(a \leq z \leq b)=\int_a^b p(z) dz = P(b) - P(a)$$ **IMPORTANT**: $\int_{-\infty}^{\infty} p(z) dz = 1$ ### Some notes about <a title="probability density functions">pdf's</a> The integration to unity is important! $$\int_{-\infty}^{\infty} p(z) dz = 1$$ **Remember:** the integral of a <a title="probability density function">pdf</a> leads to a probability, and probabilities cannot be larger than 1. For example, from this property we can derive the following: $$ \int_{-\infty}^{\infty} p(z) dz = \int_{-\infty}^{a} p(z) dz + \int_{a}^{\infty} p(z) dz $$ $$ \Rightarrow \text{Pr}(z \geq a)= 1 - \text{Pr}(z \leq a) = 1 - \text{P}(a) = 1 - \int_{-\infty}^a p(z) dz $$ In some cases we will work with probability distributions that are **unnormalized**, so this comment is important! * Being unnormalized means that the probability density of the distribution does not integrate to 1. * In this case, we cannot call such function a <a title="probability density function">pdf</a>, even though its output is a probability density. ## <a title="Cumulative distribution functions">Cdf's</a> result from <a title="probability density functions">pdf's</a> Key point? * Given a <a title="probability density function">pdf</a> $p(z)$, we can compute the probability of a continuous <a title="random variable">rv</a> $z$ being in a finite interval as follows: $$ \text{Pr}(a \leq z \leq b)=\int_a^b p(z) dz = P(b) - P(a) $$ As the size of the interval gets smaller, we can write $$ \text{Pr}\left(z - \frac{dz}{2} \leq z \leq z + \frac{dz}{2}\right) \approx p(z) dz $$ Intuitively, this says the probability of $z$ being in a small interval around $z$ is the density at $z$ times the width of the interval. ```python from scipy.stats import norm # import from scipy.stats the normal distribution zrange = np.linspace(-3, 3, 100) # 100 values for plot fig_std_norm, (ax1, ax2) = plt.subplots(1, 2) # create a plot with 2 subplots side-by-side ax1.plot(zrange, norm.cdf(zrange, 0, 1), label=r"$\mu_z=0; \ \sigma_z=1$") # plot cdf of standard normal ax1.set_xlabel("z", fontsize=20) ax1.set_ylabel("probability", fontsize=20) ax1.legend(fontsize=15) ax1.set_title("Standard Gaussian cdf", fontsize=20) ax2.plot(zrange, norm.pdf(zrange, 0, 1), label=r"$\mu_z=0; \ \sigma_z=1$") # plot pdf of standard normal ax2.set_xlabel("z", fontsize=20) ax2.set_ylabel("probability density", fontsize=20) ax2.legend(fontsize=15) ax2.set_title("Standard Gaussian pdf", fontsize=20) fig_std_norm.set_size_inches(25, 5) # scale figure to be wider (since there are 2 subplots) ``` ## Note about scipy.stats [scipy](https://docs.scipy.org/doc/scipy/index.html) is an open-source software for mathematics, science, and engineering. It's brilliant and widely used for many things! **In particular**, [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html) is a simple module within scipy that has statistical functions and operations that are very useful. This way, we don't need to code all the functions ourselves. That's why we are using it to plot the cdf and pdf of the Gaussian distribution from now on, and we will use it for other things later. * In case you are interested, scipy.stats has a nice [tutorial](https://docs.scipy.org/doc/scipy/tutorial/stats.html) ## Coming back to our car stopping distance problem $y = {\color{blue}z} x + 0.1 x^2$ where $z$ is a continuous <a title="random variable">rv</a> such that $p(z)= \mathcal{N}(z | \mu_z=1.5,\sigma_z^2=0.5^2)$. * What is the probability of an event $Z$ defined by a reaction time $z \leq 0.52$ seconds? $$ \text{Pr}(Z) = \text{Pr}(z \leq 0.52) = P(z=0.52) = \int_{-\infty}^{0.52} p(z) dz $$ ```python Pr_Z = norm.cdf(0.52, 1.5, 0.5) # using scipy norm.cdf(z=0.52 | mu_z=1.5, sigma_z=0.5) print("The probability of event Z is: Pr(Z) = ",round(Pr_Z,3)) ``` The probability of event Z is: Pr(Z) = 0.025 ```python z_value = 0.52 # z = 0.52 seconds zrange = np.linspace(0, 3, 200) # 200 values for plot fig_car_norm, (ax1, ax2) = plt.subplots(1, 2) # create subplot (two figures in 1) ax1.plot(zrange, norm.cdf(zrange, 1.5, 0.5), label=r"$\mu_z=1.5; \ \sigma_z=0.5$") # Figure 1 is cdf ax1.plot(z_value, norm.cdf(z_value, 1.5, 0.5), 'r*',markersize=15, linewidth=2, label=u'$P(z=0.52~|~\mu_z=1.5, \sigma_z^2=0.5^2)$') ax1.set_xlabel("z", fontsize=20) ax1.set_ylabel("probability", fontsize=20) ax1.legend(fontsize=15) ax1.set_title("Gaussian cdf of $z$ for car problem", fontsize=20) ax2.plot(zrange, norm.pdf(zrange, 1.5, 0.5), label=r"$\mu_z=1.5; \ \sigma_z=0.5$") # figure 2 is pdf ax2.plot(z_value, norm.pdf(z_value, 1.5, 0.5), 'r*', markersize=15, linewidth=2, label=u'$p(z=0.52~|~\mu_z=1.5, \sigma_z^2=0.5^2)$') ax2.set_xlabel("z", fontsize=20) ax2.set_ylabel("probability density", fontsize=20) ax2.legend(fontsize=15) ax2.set_title("Gaussian pdf of $z$ for car problem", fontsize=20) fig_car_norm.set_size_inches(25, 5) # scale figure to be wider (since there are 2 subplots) ``` ### Why is the Gaussian distribution so widely used? Several reasons: 1. It has two parameters which are easy to interpret, and which capture some of the most basic properties of a distribution, namely its mean and variance. 2. The central limit theorem (Sec. 2.8.6 of the book) tells us that sums of independent random variables have an approximately Gaussian distribution, making it a good choice for modeling residual errors or “noise”. 3. The Gaussian distribution makes the least number of assumptions (has maximum entropy), subject to the constraint of having a specified mean and variance (Sec. 3.4.4 of the book); this makes it a good default choice in many cases. 4. It has a simple mathematical form, which results in easy to implement, but often highly effective, methods. ## Car stopping distance problem $y = {\color{blue}z} x + 0.1 x^2$ where $z$ is a continuous <a title="random variable">rv</a> such that $z \sim \mathcal{N}(\mu_z=1.5,\sigma_z^2=0.5^2)$. * What is the **expected** value for the reaction time $z$? This is not a trick question! It's the mean $\mu_z$, of course! * But how do we compute the expected value for any distribution? ## Moments of a distribution ### First moment: Expected value or mean The expected value (mean) of a distribution is the **first moment** of the distribution: $$ \mathbb{E}[z]= \int_{\mathcal{Z}}z p(z) dz $$ where $\mathcal{Z}$ indicates the support of the distribution (the $z$ domain). * Often, $\mathcal{Z}$ is omitted as it is usually between $-\infty$ to $\infty$ * The expected value $\mathbb{E}[z]$ is often denoted by $\mu_z$ As you might expect (pun intended 😆), the expected value is a linear operator: $$ \mathbb{E}[az+b]= a\mathbb{E}[z] + b $$ where $a$ and $b$ are fixed variables (NOT rv's). Additionally, for a set of $n$ rv's, one can show that the expectation of their sum is as follows: $\mathbb{E}\left[\sum_{i=1}^n z_i\right]= \sum_{i=1}^n \mathbb{E}[z_i]$ If they are **independent**, the expectation of their product is given by $\mathbb{E}\left[\prod_{i=1}^n z_i\right]= \prod_{i=1}^n \mathbb{E}[z_i]$ ## Moments of a distribution ### Second moment (and relation to Variance) The 2nd moment of a distribution $p(z)$ is: $$ \mathbb{E}[z^2]= \int_{\mathcal{Z}}z^2 p(z) dz $$ #### Variance can be obtained from the 1st and 2nd moments The variance is a measure of the “spread” of the distribution: $$ \mathbb{V}[z] = \mathbb{E}[(z-\mu_z)^2] = \int (z-\mu_z)^2 p(z) dz = \mathbb{E}[z^2] - \mu_z^2 $$ * It is often denoted by the square of the standard deviation, i.e. $\sigma_z^2 = \mathbb{V}[z] = \mathbb{E}[(z-\mu_z)^2]$ #### Elaboration of the variance as a result of the first two moments of a distribution $$ \begin{align} \mathbb{V}[z] & = \mathbb{E}[(z-\mu_z)^2] \\ & = \int (z-\mu_z)^2 p(z) dz \\ & = \int z^2 p(z) dz + \mu_z^2 \int p(z) dz - 2\mu_z \int zp(z) dz \\ & = \mathbb{E}[z^2] - \mu_z^2 \end{align} $$ where $\mu_z = \mathbb{E}[z]$ is the first moment, and $\mathbb{E}[z^2]$ is the second moment. Therefore, we can also write the second moment of a distribution as $$\mathbb{E}[z^2] = \sigma_z^2 + \mu_z^2$$ #### Variance and standard deviation properties The standard deviation is defined as $ \sigma_z = \text{std}[z] = \sqrt{\mathbb{V}[z]}$ The variance of a shifted and scaled version of a random variable is given by $\mathbb{V}[a z + b] = a^2\mathbb{V}[z]$ where $a$ and $b$ are fixed variables (NOT rv's). If we have a set of $n$ independent rv's, the variance of their sum is given by the sum of their variances $$ \mathbb{V}\left[\sum_{i=1}^n z_i\right] = \sum_{i=1}^n \mathbb{V}[z_i] $$ The variance of their product can also be derived, as follows: $$ \begin{align} \mathbb{V}\left[\prod_{i=1}^n z_i\right] & = \mathbb{E}\left[ \left(\prod_i z_i\right)^2 \right] - \left( \mathbb{E}\left[\prod_i z_i \right]\right)^2\\ & = \mathbb{E}\left[ \prod_i z_i^2 \right] - \left( \prod_i\mathbb{E}\left[ z_i \right]\right)^2\\ & = \prod_i \mathbb{E}\left[ z_i^2 \right] - \prod_i\left( \mathbb{E}\left[ z_i \right]\right)^2\\ & = \prod_i \left( \mathbb{V}\left[ z_i \right] +\left( \mathbb{E}\left[ z_i \right]\right)^2 \right)- \prod_i\left( \mathbb{E}\left[ z_i \right]\right)^2\\ & = \prod_i \left( \sigma_{z,\,i}^2 + \mu_{z,\,i}^2 \right)- \prod_i\mu_{z,\,i}^2 \\ \end{align} $$ ## Note about higher-order moments * The $k$-th moment of a distribution $p(z)$ is defined as the expected value of the $k$-th power of $z$, i.e. $z^k$: $$ \mathbb{E}[z^k]= \int_{\mathcal{Z}}z^k p(z) dz $$ ## Mode of a distribution The mode of an <a title="random variable">rv</a> $z$ is the value of $z$ for which $p(z)$ is maximum. Formally, this is written as, $$ \mathbf{z}^* = \underset{z}{\mathrm{argmax}}~p(z)$$ If the distribution is multimodal, this may not be unique: * That's why $\mathbf{z}^*$ is in **bold**, to denote that in general it is a vector that is retrieved! * However, if the distribution is unimodal (one maximum), like the univariate Gaussian distribution, then it retrieves a scalar $z^*$ Note that even if there is a unique mode, this point may not be a good summary of the distribution. ## Mean vs mode for a non-symmetric distribution ```python # 1. Create a gamma pdf with parameter a = 2.0 from scipy.stats import gamma # import from scipy.stats the Gamma distribution a = 2.0 # this is the only input parameter needed for this distribution # Define the support of the distribution (its domain) by using the # inverse of the cdf (called ppf) to get the lowest z of the plot that # corresponds to Pr = 0.01 and the highest z of the plot that corresponds # to Pr = 0.99: zrange = np.linspace(gamma.ppf(0.01, a), gamma.ppf(0.99, a), 200) mu_z, var_z = gamma.stats(2.0, moments='mv') # This computes the mean and variance of the pdf fig_gamma_pdf, ax = plt.subplots() # a trick to save the figure for later use ax.plot(zrange, gamma.pdf(zrange, a), label=r"$\Gamma(z|a=2.0)$") ax.set_xlabel("z", fontsize=20) ax.set_ylabel("probability density", fontsize=20) ax.legend(fontsize=15) ax.set_title("Gamma pdf for $a=2.0$", fontsize=20) plt.close(fig_gamma_pdf) # do not plot the figure now. We will show it in a later cell ``` ```python # 2. Plot the expected value (mean) for this pdf ax.plot(mu_z, gamma.pdf(mu_z, a), 'r*', markersize=15, linewidth=2, label=u'$\mu_z = \mathbb{E}[z]$') ``` [<matplotlib.lines.Line2D at 0x7f80bcb1c4f0>] ```python # 3. Calculate the mode and plot it from scipy.optimize import minimize # import minimizer # Finding the maximum of the gamma pdf can be done by minimizing # the negative gamma pdf. So, we create a function that outputs # the negative of the gamma pdf given the parameter a=2.0: def neg_gamma_given_a(z): return -gamma.pdf(z,a) # Use the default optimizer of scipy (L-BFGS) to find the # maximum (by minimizing the negative gamma pdf). Note # that we need to give an initial guess for the value of z, # so we can use, for example, z=mu_z: mode_z = minimize(neg_gamma_given_a,mu_z).x ax.plot(mode_z, np.max(gamma.pdf(mode_z, a)),'g^', markersize=15, linewidth=2,label=u'mode $\mathbf{z}^*=\mathrm{argmax}~p(z)$') ax.legend() # show legend ``` <matplotlib.legend.Legend at 0x7f80bc769f40> ```python # Code to generate this Gamma distribution hidden during presentation (it's shown as notes) print('The mean is ',mu_z) # print the mean calculated for this gamma pdf print('The mode is approximately ',mode_z) # print the mode fig_gamma_pdf # show figure of this gamma pdf ``` ## The amazing Bayes' rule <font color='red'>Bayesian</font> <font color='blue'>inference</font> definition: * <font color='blue'>Inference</font> means “the act of passing from sample data to generalizations, usually with calculated degrees of certainty”. * <font color='red'>Bayesian</font> is used to refer to inference methods that represent “degrees of certainty” using probability theory, and which leverage Bayes’ rule to update the degree of certainty given data. **Bayes’ rule** is a formula for computing the probability distribution over possible values of an unknown (or hidden) quantity $z$ given some observed data $y$: $$ p(z|y) = \frac{p(y|z) p(z)}{p(y)} $$ Bayes' rule follows automatically from the identity: $p(z|y) p(y) = p(y|z) p(z) = p(y,z) = p(z,y)$ ## The amazing Bayes' rule * I know... You don't find it very amazing (yet!). * Wait until you realize that almost all ML methods can be derived from this simple formula $$ p(z|y) = \frac{p(y|z) p(z)}{p(y)} $$ ### See you next class Have fun!
[STATEMENT] lemma valid_split2: "\<lbrakk>valid fg c; valid fg c'; mon_c fg c \<inter> mon_c fg c' = {}\<rbrakk> \<Longrightarrow> valid fg (c+c')" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>valid fg c; valid fg c'; mon_c fg c \<inter> mon_c fg c' = {}\<rbrakk> \<Longrightarrow> valid fg (c + c') [PROOF STEP] apply (unfold valid_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}\<rbrakk> \<Longrightarrow> \<forall>s s'. {#s, s'#} \<subseteq># c + c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} [PROOF STEP] apply (intro impI allI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; {#s, s'#} \<subseteq># c + c'\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} [PROOF STEP] apply (erule mset_2dist2_cases) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; {#s, s'#} \<subseteq># c\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} 2. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; {#s, s'#} \<subseteq># c'\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} 3. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; s \<in># c; s' \<in># c'\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} 4. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; s \<in># c'; s' \<in># c\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} [PROOF STEP] apply simp_all [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; s \<in># c; s' \<in># c'\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} 2. \<And>s s'. \<lbrakk>\<forall>s s'. {#s, s'#} \<subseteq># c \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; \<forall>s s'. {#s, s'#} \<subseteq># c' \<longrightarrow> mon_s fg s \<inter> mon_s fg s' = {}; mon_c fg c \<inter> mon_c fg c' = {}; s \<in># c'; s' \<in># c\<rbrakk> \<Longrightarrow> mon_s fg s \<inter> mon_s fg s' = {} [PROOF STEP] apply (blast intro: mon_cI)+ [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
# Optimization of a State-to-State Transfer in a Lambda System in the RWA ```python # NBVAL_IGNORE_OUTPUT %load_ext watermark import os import numpy as np import scipy import matplotlib import matplotlib.pylab as plt import krotov import qutip from qutip import Qobj %watermark -v --iversions ``` Python implementation: CPython Python version : 3.7.6 IPython version : 7.19.0 krotov : 1.2.1 matplotlib: 3.3.3 qutip : 4.5.0 numpy : 1.17.2 scipy : 1.3.1 $\newcommand{tr}[0]{\operatorname{tr}} \newcommand{diag}[0]{\operatorname{diag}} \newcommand{abs}[0]{\operatorname{abs}} \newcommand{pop}[0]{\operatorname{pop}} \newcommand{aux}[0]{\text{aux}} \newcommand{opt}[0]{\text{opt}} \newcommand{tgt}[0]{\text{tgt}} \newcommand{init}[0]{\text{init}} \newcommand{lab}[0]{\text{lab}} \newcommand{rwa}[0]{\text{rwa}} \newcommand{bra}[1]{\langle#1\vert} \newcommand{ket}[1]{\vert#1\rangle} \newcommand{Bra}[1]{\left\langle#1\right\vert} \newcommand{Ket}[1]{\left\vert#1\right\rangle} \newcommand{Braket}[2]{\left\langle #1\vphantom{#2}\mid{#2}\vphantom{#1}\right\rangle} \newcommand{ketbra}[2]{\vert#1\rangle\!\langle#2\vert} \newcommand{op}[1]{\hat{#1}} \newcommand{Op}[1]{\hat{#1}} \newcommand{dd}[0]{\,\text{d}} \newcommand{Liouville}[0]{\mathcal{L}} \newcommand{DynMap}[0]{\mathcal{E}} \newcommand{identity}[0]{\mathbf{1}} \newcommand{Norm}[1]{\lVert#1\rVert} \newcommand{Abs}[1]{\left\vert#1\right\vert} \newcommand{avg}[1]{\langle#1\rangle} \newcommand{Avg}[1]{\left\langle#1\right\rangle} \newcommand{AbsSq}[1]{\left\vert#1\right\vert^2} \newcommand{Re}[0]{\operatorname{Re}} \newcommand{Im}[0]{\operatorname{Im}}$ This example is illustrates the use of complex-valued control fields. This is accomplished by rewriting the Hamiltonian as the sum of two independent controls (real and imaginary parts). We consider a 3-level system in a $\Lambda$ configuration, and seek control pulses that implement a (phase-sensitive) state-to-state transition $\ket{1} \rightarrow \ket{3}$. ## The rotating wave Hamiltonian The system consists of three levels $\ket{1}$, $\ket{2}$ and $\ket{3}$ with energy levels $E_{1}, E_{2}$ and $E_{3}$ which interact with a pair of laser pulses $\epsilon_{P}(t)$ ("pump laser") and $\epsilon_{S}(t)$ ("Stokes laser"), respectively, see Chapter 15.4.2 in ["Introduction to Quantum Mechanics: A Time-Dependent Perspective" by David Tannor][Tannor] for details. [Tannor]: http://www.weizmann.ac.il/chemphys/tannor/Book/ In the lab frame, the Hamiltonian reads $$ \Op{H}_{\text{lab}} = \begin{pmatrix} E_1 & -\mu_{12} \epsilon_P(t) & 0 \\ -\mu_{12} \epsilon_P(t) & E_2 & - \mu_{23} \epsilon_S(t) \\ 0 & -\mu_{23} \epsilon_S(t) & E_2 \end{pmatrix}\,. $$ with the dipole values $\mu_{12}$, $\mu_{23}$ describing the coupling to the (real-valued) control fields $\epsilon_P(t)$, $\epsilon_S(t)$. The "rotating frame" is defined as $$\ket{\Psi_{\text{rot}}} = \Op{U}_0^\dagger \ket{\Psi_{\text{lab}}}$$ with the transformation $$\op{U}_{0} = \ketbra{1}{1} e^{-i\left(E_{2} - \omega_{P} \right)t} + \ketbra{2}{2} e^{-iE_{2}t} + \ketbra{3}{3} e^{-i\left(E_{2}-\omega_{S}\right)t}\,,$$ where $\omega_{P}$ and $\omega_{S}$ are the two central frequencies defining the rotating frame. The condition of having to fulfill the Schrödinger equation in the rotating frame implies a rotating frame Hamiltonian defined as $$\op{H}_{\text{rot}} = \op{U}_{0}^{\dagger} \op{H}_{\text{lab}} \op{U}_{0} - i \op{U}_{0}^{\dagger} \dot{\op{U}}_{0}\,.$$ Note that most textbooks use $\Op{U}$ instead of $\Op{U}^\dagger$, and thus the adjoint of the above equation to define the rotating frame transformation, but we follow the example of Tannor's book here. The rotating frame Hamiltonian reads $$ \Op{H}_\text{rot} = \begin{pmatrix} E_1 + \omega_P - E_2 & -\mu_{12} \epsilon_P(t) e^{-i \omega_P t} & 0 \\ -\mu_{12} \epsilon_P(t) e^{+i \omega_P t} & 0 & - \mu_{23} \epsilon_S(t) e^{-i \omega_S t}\\ 0 & -\mu_{23} \epsilon_S(t) e^{+i \omega_S t} & E3 + \omega_S -E_2 \end{pmatrix}\,. $$ We can now write the fields as $$ \begin{split} \mu_{12} \epsilon_{P}(t) &= \Omega_{P}^{(1)}(t) \cos{(\omega_P t)} - \Omega_{P}^{(2)}(t) \sin{(\omega_P t)} \\ &= \Omega_{P}^{(1)}(t) \left( e^{i \omega_P t} + e^{-i \omega_P t}\right) + i \Omega_{P}^{(2)}(t) \left( e^{i \omega_P t} - e^{-i \omega_P t} \right) \,, \end{split} $$ and similarly for $\epsilon_{S}(t)$, where we have split each field into two arbitrary (real-valued) auxiliary fields $\Omega_{P}^{(1)}(t), \Omega_{P}^{(2)}(t)$, and $\Omega_{S}^{(1)}(t), \Omega_{S}^{(2)}(t)$. This rewriting is suggestive of controls being spectrally centered around $\omega_P$ and $\omega_S$, respectively, in which case any oscillations in $\Omega_{P,S}^{(1,2)}(t)$ are on a much slower time scale than $\omega_{P, S}$. Mathematically, however, *any* control fields can written in the above form. Thus, we have not placed any restriction on the controls at this time. Plugging this into $\Op{H}_\text{rot}$ and invoking the rotating wave approximation that neglects all fast oscillating terms $\propto e^{\pm i 2 \omega_{P,S} t}$, we find $$ \Op{H}_\text{RWA} = \begin{pmatrix} \Delta_P & -\frac{1}{2} \Omega_P(t) & 0 \\ -\frac{1}{2} \Omega_P^*(t) & 0 & -\frac{1}{2} \Omega_S(t) \\ 0 & -\frac{1}{2} \Omega_S^*(t) & \Delta_S \end{pmatrix}\,, $$ with the detunings $\Delta_P \equiv E_1 + \omega_P - E_2$, $\Delta_S \equiv E3 + \omega_S -E_2$ and the complex-valued control fields $\Omega_P(t) \equiv \Omega_{P}^{(1)}(t) + i \Omega_{P}^{(2)}(t)$ and $\Omega_S(t) \equiv \Omega_{S}^{(1)}(t) + i \Omega_{S}^{(2)}(t)$, illustrated in the following diagram: Most textbooks (including Tannor's) only allow control fields of the form $\epsilon_{P,S}(t) \propto \Omega_{P,S}(t) \cos{(\omega_{P,S} t)}$ with the pulse envelopes $\Omega_{P,S}(t) \in \mathbb{R}^+$. This will result in the same $\Op{H}_\text{RWA}$ as above, but with the positive real-valued envelopes instead of the complex-valued $\Omega_{P,S}(t)$. However, this restriction is unnecessary: complex-valued control fields in the RWA are more general and entirely physical, with the relation to the real-valued field in the lab frame as defined above. The spectra of the optimized pulses are free to deviate from the frequencies of the rotating frame, limited only by the numerical resolution of the time grid and the RWA. The `krotov` package requires that all control pulses are real-valued. Therefore, the real and imaginary parts of $\Omega_{P}$ and $\Omega_{S}$ are treated as independent Hamiltonians, and we write $$ \Op{H}_\text{RWA} = \Op{H_0} + \Omega_{P}^{(1)}(t) \Op{H}_{P,\text{re}} + \Omega_{P}^{(2)}(t) \Op{H}_{P,\text{im}} + \Omega_{S}^{(1)}(t) \Op{H}_{S,\text{re}} + \Omega_{S}^{(2)}(t) \Op{H}_{S,\text{im}} $$ for the purpose of the optimization, with $$ \begin{align} \Op{H_0} &= \Delta_P \ketbra{1}{1} + \Delta_S \ketbra{3}{3}\,, \\ \Op{H}_{P,\text{re}} &= -\frac{1}{2} \left(\ketbra{1}{2} + \ketbra{2}{1}\right)\,, \\ \Op{H}_{P,\text{im}} &= -\frac{i}{2} \left(\ketbra{1}{2} - \ketbra{2}{1}\right)\,, \\ \Op{H}_{S,\text{re}} &= -\frac{1}{2} \left(\ketbra{2}{3} + \ketbra{3}{2}\right)\,, \\ \Op{H}_{S,\text{im}} &= -\frac{i}{2} \left(\ketbra{2}{3} - \ketbra{3}{2}\right)\,. \end{align} $$ ## Guess controls We choose the initial guess for the four control fields based on the intuition of the "stimulated Raman adiabatic passage" (STIRAP) scheme. STIRAP allows to transfer the population in $\ket{1}$ $\ket{3}$ without having to pass through $\ket{2}$; it requires the Stokes-pulse to precede but overlap the pump-pulse. Here, we leave it up to Krotov's method to find appropriate pulses for a STIRAP-like transfer (without requiring that the $\ket{2}$ level remains unpopulated). We start from a low intensity real-valued $\Omega_S(t)$ pulse with a Blackman shape, followed by an overlapping real-valued $\Omega_P(t)$ of the same shape. The entire scheme is in the time interval [0, 5]. ```python def Omega_P1(t, args): """Guess for the real part of the pump pulse""" Ω0 = 5.0 return Ω0 * krotov.shapes.blackman(t, t_start=2.0, t_stop=5.0) def Omega_P2(t, args): """Guess for the imaginary part of the pump pulse""" return 0.0 def Omega_S1(t, args): """Guess for the real part of the Stokes pulse""" Ω0 = 5.0 return Ω0 * krotov.shapes.blackman(t, t_start=0.0, t_stop=3.0) def Omega_S2(t, args): """Guess for the imaginary part of the Stokes pulse""" return 0.0 ``` We can now instantiate the Hamiltonian including these guess controls: ```python def hamiltonian(E1=0.0, E2=10.0, E3=5.0, omega_P=9.5, omega_S=4.5): """Lambda-system Hamiltonian in the RWA""" # detunings ΔP = E1 + omega_P - E2 ΔS = E3 + omega_S - E2 H0 = Qobj([[ΔP, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, ΔS]]) HP_re = -0.5 * Qobj([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) HP_im = -0.5 * Qobj([[0.0, 1.0j, 0.0], [-1.0j, 0.0, 0.0], [0.0, 0.0, 0.0]]) HS_re = -0.5 * Qobj([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]) HS_im = -0.5 * Qobj([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0j], [0.0, -1.0j, 0.0]]) return [ H0, [HP_re, Omega_P1], [HP_im, Omega_P2], [HS_re, Omega_S1], [HS_im, Omega_S2], ] ``` ```python H = hamiltonian() ``` ## Target state in the rotating frame The basis states of the $\Lambda$-system are defined as ```python ket1 = qutip.Qobj(np.array([1.0, 0.0, 0.0])) ket2 = qutip.Qobj(np.array([0.0, 1.0, 0.0])) ket3 = qutip.Qobj(np.array([0.0, 0.0, 1.0])) ``` We would like to implement a phase-sensitive transition $\ket{1} \rightarrow \ket{3}$ *in the lab frame*. Since we are defining the dynamics in the RWA, this means we have to adjust the target state to be in the rotating frame as well (the initial state at $t=0$ is not affected by the RWA). As defined earlier, the states in the rotating frame are obtained from the states in the lab frame by the transformation $\ket{\Psi_{\text{rot}}} = \Op{U}_0^\dagger \ket{\Psi_{\text{lab}}}$. In our case, this means that we get $\ket{3}$ with and additional phase factor: ```python def rwa_target_state(ket3, E2=10.0, omega_S=4.5, T=5): return np.exp(1j * (E2 - omega_S) * T) * ket3 ``` ```python psi_target = rwa_target_state(ket3) ``` We can now instantiate the control objective: ```python objective = krotov.Objective(initial_state=ket1, target=psi_target, H=H) objective ``` Objective[|Ψ₀(3)⟩ to |Ψ₁(3)⟩ via [H₀[3,3], [H₁[3,3], u₁(t)], [H₂[3,3], u₂(t)], [H₃[3,3], u₃(t)], [H₄[3,3], u₄(t)]]] ## Simulate dynamics under the guess field We use a time grid with 500 steps between $t=0$ and $T=5$: ```python tlist = np.linspace(0, 5, 500) ``` Before propagating, we visually verify the guess pulses we defined earlier: ```python def plot_pulse(pulse, tlist, label): fig, ax = plt.subplots() if callable(pulse): pulse = np.array([pulse(t, args=None) for t in tlist]) ax.plot(tlist, pulse) ax.set_xlabel('time') ax.set_ylabel('%s pulse amplitude' % label) plt.show(fig) ``` ```python plot_pulse(H[1][1], tlist, 'Ωₚ') plot_pulse(H[3][1], tlist, 'Ωₛ') ``` The imaginary parts are zero: ```python assert np.all([H[2][1](t, None) == 0 for t in tlist]) assert np.all([H[4][1](t, None) == 0 for t in tlist]) ``` We introduce projectors $\op{P}_{i} = \ketbra{i}{i}$ for each of the three energy levels, allowing use to plot the population dynamics: ```python proj1 = qutip.ket2dm(ket1) proj2 = qutip.ket2dm(ket2) proj3 = qutip.ket2dm(ket3) ``` ```python guess_dynamics = objective.mesolve(tlist, e_ops=[proj1,proj2,proj3]) ``` ```python def plot_population(result): fig, ax = plt.subplots() ax.plot(result.times, result.expect[0], label='1') ax.plot(result.times, result.expect[1], label='2') ax.plot(result.times, result.expect[2], label='3') ax.legend() ax.set_xlabel('time') ax.set_ylabel('population') plt.show(fig) ``` ```python plot_population(guess_dynamics) ``` We find that our guess pulses are too disjoint to implement the STIRAP scheme. Thus, the Stokes pulse has no effect, whilst the pump pulse merely transfers population out of $\ket{1}$ into $\ket{2}$ and back again. ## Optimize In order to invoke `optimize_pulses`, we must define the required parameters for each control, a pulse shape (used to ensure that the controls remain 0 at $t=0$ and $t=T$), and the parameter $\lambda_a$ that determines the overall magnitude of the pulse updates in each iteration. ```python def S(t): """Scales the Krotov methods update of the pulse value at the time t""" return krotov.shapes.flattop( t, t_start=0.0, t_stop=5.0, t_rise=0.3, func='sinsq' ) ``` ```python pulse_options = { H[1][1]: dict(lambda_a=0.5, update_shape=S), H[2][1]: dict(lambda_a=0.5, update_shape=S), H[3][1]: dict(lambda_a=0.5, update_shape=S), H[4][1]: dict(lambda_a=0.5, update_shape=S) } ``` We now run the optimization, using the phase-sensitive functional $J_{T, \text{re}} = 1 - \Re\Braket{\Psi(t)}{\Psi_{\tgt}}$, printing the integrated pulse update for each control in each iteration. The optimization stops when $J_T$ falls below $10^{-3}$, changes by less than $10^{-5}$, or after at most 15 iterations. We also check for monotonic convergence. ```python opt_result = krotov.optimize_pulses( [objective], pulse_options, tlist, propagator=krotov.propagators.expm, chi_constructor=krotov.functionals.chis_re, info_hook=krotov.info_hooks.print_table( J_T=krotov.functionals.J_T_re, show_g_a_int_per_pulse=True, unicode=False, ), check_convergence=krotov.convergence.Or( krotov.convergence.value_below(1e-3, name='J_T'), krotov.convergence.delta_below(1e-5), krotov.convergence.check_monotonic_error, ), iter_stop=15, ) ``` iter. J_T g_a_int_1 g_a_int_2 g_a_int_3 g_a_int_4 g_a_int J Delta J_T Delta J secs 0 1.01e+00 0.00e+00 0.00e+00 0.00e+00 0.00e+00 0.00e+00 1.01e+00 n/a n/a 1 1 6.72e-01 1.72e-01 5.72e-04 1.63e-01 7.44e-04 3.37e-01 1.01e+00 -3.37e-01 -2.15e-06 2 2 4.02e-01 1.44e-01 8.42e-04 1.24e-01 8.40e-04 2.70e-01 6.72e-01 -2.70e-01 -1.23e-05 3 3 2.22e-01 9.81e-02 9.26e-04 7.98e-02 7.75e-04 1.80e-01 4.02e-01 -1.80e-01 -2.16e-05 2 4 1.17e-01 5.78e-02 7.70e-04 4.58e-02 6.02e-04 1.05e-01 2.22e-01 -1.05e-01 -2.30e-05 2 5 6.00e-02 3.13e-02 5.35e-04 2.46e-02 4.20e-04 5.68e-02 1.17e-01 -5.69e-02 -1.86e-05 2 6 3.05e-02 1.62e-02 3.40e-04 1.27e-02 2.78e-04 2.95e-02 6.00e-02 -2.95e-02 -1.28e-05 2 7 1.54e-02 8.16e-03 2.11e-04 6.47e-03 1.82e-04 1.50e-02 3.05e-02 -1.50e-02 -8.10e-06 2 8 7.85e-03 4.08e-03 1.33e-04 3.25e-03 1.20e-04 7.58e-03 1.54e-02 -7.59e-03 -4.87e-06 2 9 4.02e-03 2.03e-03 8.59e-05 1.63e-03 8.01e-05 3.82e-03 7.85e-03 -3.83e-03 -2.86e-06 2 10 2.09e-03 1.01e-03 5.76e-05 8.13e-04 5.45e-05 1.93e-03 4.02e-03 -1.94e-03 -1.66e-06 2 11 1.10e-03 5.03e-04 3.97e-05 4.06e-04 3.76e-05 9.86e-04 2.09e-03 -9.87e-04 -9.67e-07 3 12 5.90e-04 2.51e-04 2.79e-05 2.03e-04 2.62e-05 5.08e-04 1.10e-03 -5.09e-04 -5.66e-07 3 ```python opt_result ``` Krotov Optimization Result -------------------------- - Started at 2021-01-13 14:17:05 - Number of objectives: 1 - Number of iterations: 12 - Reason for termination: Reached convergence: J_T < 0.001 - Ended at 2021-01-13 14:17:40 (0:00:35) We dump the result of the optimization to disk for later use in the [Ensemble Optimization for Robust Pulses](08_example_ensemble.ipynb). ```python if not os.path.isfile('lambda_rwa_opt_result.dump'): opt_result.dump('lambda_rwa_opt_result.dump') ``` The optimized complex pulses look as follows: ```python def plot_pulse_amplitude_and_phase(pulse_real, pulse_imaginary,tlist): ax1 = plt.subplot(211) ax2 = plt.subplot(212) amplitudes = [np.sqrt(x*x + y*y) for x,y in zip(pulse_real,pulse_imaginary)] phases = [np.arctan2(y,x)/np.pi for x,y in zip(pulse_real,pulse_imaginary)] ax1.plot(tlist,amplitudes) ax1.set_xlabel('time') ax1.set_ylabel('pulse amplitude') ax2.plot(tlist,phases) ax2.set_xlabel('time') ax2.set_ylabel('pulse phase (π)') plt.show() print("pump pulse amplitude and phase:") plot_pulse_amplitude_and_phase( opt_result.optimized_controls[0], opt_result.optimized_controls[1], tlist) print("Stokes pulse amplitude and phase:") plot_pulse_amplitude_and_phase( opt_result.optimized_controls[2], opt_result.optimized_controls[3], tlist) ``` We can convert the complex controls in the rotating frame back into the real-valued pulses in the lab frame: ```python def plot_physical_field(pulse_re, pulse_im, tlist, case=None): if case == 'pump': w = 9.5 elif case == 'stokes': w = 4.5 else: print('Error: selected case is not a valid option') return ax = plt.subplot(111) ax.plot(tlist,pulse_re*np.cos(w*tlist)-pulse_im*np.sin(w*tlist), 'r') ax.set_xlabel('time', fontsize = 16) if case == 'pump': ax.set_ylabel(r'$\mu_{12}\,\epsilon_{P}$') elif case == 'stokes': ax.set_ylabel(r'$ \mu_{23}\,\epsilon_{S}$') plt.show() print('Physical electric pump pulse in the lab frame:') plot_physical_field( opt_result.optimized_controls[0], opt_result.optimized_controls[1], tlist, case = 'pump') print('Physical electric Stokes pulse in the lab frame:') plot_physical_field( opt_result.optimized_controls[2], opt_result.optimized_controls[3], tlist, case = 'stokes') ``` Lastly, we check the population dynamics to verify that we indeed implement the desired state-to-state transfer: ```python opt_dynamics = opt_result.optimized_objectives[0].mesolve( tlist, e_ops=[proj1, proj2, proj3]) ``` ```python plot_population(opt_dynamics) ```
{-# OPTIONS --without-K --rewriting #-} open import HoTT renaming (pt to ⊙pt) open import cw.CW open import cw.FinCW open import cohomology.Theory open import groups.Int open import groups.DisjointlyPointedSet module cw.cohomology.cochainequiv.AugmentCommSquare (OT : OrdinaryTheory lzero) (⊙fin-skel : ⊙FinSkeleton 0) where open OrdinaryTheory OT open import cw.cohomology.reconstructed.TipAndAugment OT ⊙⦉ ⊙fin-skel ⦊ private I = ⊙FinSkeleton.skel ⊙fin-skel ac = ⊙FinSkeleton-has-cells-with-choice 0 ⊙fin-skel lzero pt = ⊙FinSkeleton.skel ⊙fin-skel abstract augment-comm-sqr : CommSquareEquiv (GroupHom.f cw-coε) (_∘ᴳ FreeAbGroup-extend (Lift-abgroup {j = lzero} ℤ-abgroup) λ _ → lift 1) ((_∘ᴳ lower-hom {j = lzero}) ∘ <– (ℤ→ᴳ-equiv-idf (C2 0))) (FreeAbGroup-extend (C2-abgroup 0) ∘ GroupIso.f (C2×CX₀-diag-β ac)) augment-comm-sqr = comm-sqr (λ g → equiv-adj' (GroupIso.f-equiv (FreeAbGroup-extend-iso (C2-abgroup 0) ∘eᴳ C2×CX₀-diag-β ac)) (! $ pair×= idp ( ap (GroupIso.g (CX₀-diag-β ac)) (λ= λ _ → Group.inv-r (C2 0) g) ∙ GroupHom.pres-ident (GroupIso.g-hom (CX₀-diag-β ac))))) , (GroupIso.f-is-equiv (pre∘ᴳ-iso (C2-abgroup 0) (lower-iso {j = lzero}) ∘eᴳ ℤ→ᴳ-iso-idf (C2-abgroup 0) ⁻¹ᴳ)) , (GroupIso.f-is-equiv (FreeAbGroup-extend-iso (C2-abgroup 0) ∘eᴳ C2×CX₀-diag-β ac)) augment-comm-sqrᴳ : CommSquareEquivᴳ cw-coε (pre∘ᴳ-hom (C2-abgroup 0) (FreeAbGroup-extend (Lift-abgroup {j = lzero} ℤ-abgroup) λ _ → lift 1)) (pre∘ᴳ-hom (C2-abgroup 0) (lower-hom {j = lzero}) ∘ᴳ GroupIso.g-hom (ℤ→ᴳ-iso-idf (C2-abgroup 0))) (FreeAbGroup-extend-hom (C2-abgroup 0) ∘ᴳ GroupIso.f-hom (C2×CX₀-diag-β ac)) augment-comm-sqrᴳ = comm-sqrᴳ (fst augment-comm-sqr □$_) , snd augment-comm-sqr
lemma approx_from_below_dense_linorder: fixes x::"'a::{dense_linorder, linorder_topology, first_countable_topology}" assumes "x > y" shows "\<exists>u. (\<forall>n. u n < x) \<and> (u \<longlonglongrightarrow> x)"
\chapter{Program} The logic within MOPAC is best understood by use of flow-diagrams. There are two main sequences, geometric and electronic. These join only at one common subroutine COMPFG. It is possible, therefore, to understand the geometric or electronic sections in isolation, without having studied the other section. \section{Main geometric sequence} \index{MOPAC! geometric structure} The main geometric sequence in MOPAC is given in Figure~\ref{picgeo}. \begin{figure} \begin{makeimage} \end{makeimage} \begin{center} \hspace*{-1.0in} \input{picgeo.tex} \end{center} \caption{\label{picgeo}Diagram of Main Geometric Sequence in MOPAC} \end{figure} \section{Main electronic flow} \index{MOPAC!electronic structure} The main conventional electronic sequence in MOPAC is given in Figure~\ref{picelec}. \begin{figure} \begin{makeimage} \end{makeimage} \begin{center} \hspace*{-0.5in} \input{picelec.tex} \end{center} \caption{\label{picelec}Diagram of Main Conventional Electronic Sequence in MOPAC} \end{figure} The LMO method is similar to the conventional method. The main changes are: \begin{itemize} \item \comp{HQRII} and \comp{DIAG} are replaced by \comp{DIAGG} (the annihilation operation). \item \comp{MECI}, \comp{MECIP}, etc, and \comp{INTERP} are not available. \item Extra subroutines, used in creating the initial LMOs, are present. \end{itemize} \section{Control within MOPAC} \index{MOPAC!programming policy} Almost all the control information is passed {\em via} the single datum ``KEYWRD'', a string of 241 characters, which is read in at the start of the job. Each subroutine is made independent, as far as possible, even at the expense of extra code or calculation. Thus, for example, the SCF \index{SCF!criterion}\index{ITER}\index{DERIV} criterion is set in subroutine ITER, and nowhere else. Similarly, subroutine DERIV has exclusive control of the step size in the finite-difference calculation of the energy derivatives. If the default values are to be reset, then the new value is supplied in KEYWRD, and \index{KEYWRD}\index{READA}\index{INDEX} extracted {\em via} INDEX and READA. The flow of control is decided by the presence of various keywords in KEYWRD. When a subroutine is called, it assumes that all data required for its operation are available in either modules or arguments. Normally no check is made as to the validity of the data received. All data are ``owned'' by one, and only one, subroutine. Ownership means the \index{STATE} implied permission and ability to change the data. Thus STATE ``owns'' the number of atomic orbitals, in that it calculates this number, and \index{NORBS} stores it in the variable NORBS. Many subroutines use NORBS, but none of them is allowed to change it. For obvious reasons no exceptions should be made to this rule. To illustrate the usefulness of this convention, consider the eigenvectors, \comp{C} and \comp{CBETA}. These are owned by ITER. Before ITER is called, \comp{C} and \comp{CBETA} are not calculated, after ITER has been called \comp{C} and \comp{CBETA} are known, so any subroutine which needs to use the eigenvectors can do so in the certain knowledge that they exist. Any variables which are only used within a subroutine are not passed outside the subroutine unless an overriding reason exists. This \index{PULAY}\index{CNVG} is found in PULAY and CNVG, among others where arrays used to hold spin-dependent data are used, and these cannot conveniently be defined within the subroutines. In these examples, the relevant arrays are ``owned'' by ITER. A general subroutine, of which ITER is a good example, handles three kinds of data: First, data which the subroutine is going to work on, for example the one and two electron matrices; second, data necessary to manipulate the first set of data, such as the number of atomic orbitals; third, the calculated quantities, here the electronic energy, and the density and Fock matrices. Reference data are entered into a subroutine by way of modules. \index{Reference data} This is to emphasize their peripheral role. Thus the number of orbitals, while essential to ITER, is not central to the task it has to perform, and is passed through a module. Data the subroutine is going to work on are passed via the argument list. Thus the one and two electron matrices, which are the main reason for ITER's existence, are entered as two of the four arguments. As ITER does not own these matrices it can use them but may not change their contents. The other argument is EE, the electronic energy. EE is owned by ITER even though it first appears before ITER is called. \section{Arrays.} \subsection{Array Specification.}\index{Array specification} In MOPAC, most arrays are created dynamically. The main exceptions are a few module arrays: \comp{GEO}, \comp{COORD}, \comp{LABELS}, \comp{NAT}, \comp{NA}, \comp{NB}, and \comp{NC}. These arrays are only used at the start of the run, and once the job is fully running, they are abandoned. These arrays have the same names as dynamic arrays, but, because they are used only at the very start of the run, there is no ambiguity. The size of these arrays is defined by \comp{NUMATM} in the included file \comp{sizes.F90}. This quantity, \comp{NUMATM} is equivalent to the MOPAC~93 parameters \comp{MAXHEV} and \comp{MAXLIT}. By default, MOPAC can run systems of up to 20,000 atoms. Although this is large, the small number of static arrays means that the memory required for a small system is still small---less than 8 megabytes. Most of the memory is assigned dynamically. Once the data are read in---using the static arrays---the dynamic memory arrays are created as needed. \section{Names and Storage of Variables in MOPAC} Most subroutines in MOPAC contain the module \comp{common\_systm}. This module contains variables that are central to the transmission of information throughout the program. %\input{ncore} \input{ksts} \input{rksts} \input{ifiles}
lemma has_contour_integral_reversepath: assumes "valid_path g" and f: "(f has_contour_integral i) g" shows "(f has_contour_integral (-i)) (reversepath g)"
function vl_compilenn(varargin) %VL_COMPILENN Compile the MatConvNet toolbox. % The `vl_compilenn()` function compiles the MEX files in the % MatConvNet toolbox. See below for the requirements for compiling % CPU and GPU code, respectively. % % `vl_compilenn('OPTION', ARG, ...)` accepts the following options: % % `EnableGpu`:: `false` % Set to true in order to enable GPU support. % % `Verbose`:: 0 % Set the verbosity level (0, 1 or 2). % % `Debug`:: `false` % Set to true to compile the binaries with debugging % information. % % `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc` % Choose the method used to compile the CUDA code. There are two % methods: % % * The **`mex`** method uses the MATLAB MEX command with the % configuration file % `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]` % This configuration file is in XML format since MATLAB 8.3 % (R2014a) and is a Shell script for earlier versions. This % is, principle, the preferred method as it uses the % MATLAB-sanctioned compiler options. % % * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc` % directly to compile CUDA source code into object files. % % This method allows to use a CUDA toolkit version that is not % the one that officially supported by a particular MATALB % version (see below). It is also the default method for % compilation under Windows and with CuDNN. % % `CudaRoot`:: guessed automatically % This option specifies the path to the CUDA toolkit to use for % compilation. % % `EnableImreadJpeg`:: `true` % Set this option to `true` to compile `vl_imreadjpeg`. % % `EnableDouble`:: `true` % Set this option to `true` to compile the support for DOUBLE % data types. % % `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac) % The image library to use for `vl_impreadjpeg`. % % `ImageLibraryCompileFlags`:: platform dependent % A cell-array of additional flags to use when compiling % `vl_imreadjpeg`. % % `ImageLibraryLinkFlags`:: platform dependent % A cell-array of additional flags to use when linking % `vl_imreadjpeg`. % % `EnableCudnn`:: `false` % Set to `true` to compile CuDNN support. See CuDNN % documentation for the Hardware/CUDA version requirements. % % `CudnnRoot`:: `'local/'` % Directory containing the unpacked binaries and header files of % the CuDNN library. % % ## Compiling the CPU code % % By default, the `EnableGpu` option is switched to off, such that % the GPU code support is not compiled in. % % Generally, you only need a 64bit C/C++ compiler (usually Xcode, GCC or % Visual Studio for Mac, Linux, and Windows respectively). The % compiler can be setup in MATLAB using the % % mex -setup % % command. % % ## Compiling the GPU code % % In order to compile the GPU code, set the `EnableGpu` option to % `true`. For this to work you will need: % % * To satisfy all the requirements to compile the CPU code (see % above). % % * A NVIDIA GPU with at least *compute capability 2.0*. % % * The *MATALB Parallel Computing Toolbox*. This can be purchased % from Mathworks (type `ver` in MATLAB to see if this toolbox is % already comprised in your MATLAB installation; it often is). % % * A copy of the *CUDA Devkit*, which can be downloaded for free % from NVIDIA. Note that each MATLAB version requires a % particular CUDA Devkit version: % % | MATLAB version | Release | CUDA Devkit | % |----------------|---------|--------------| % | 8.2 | 2013b | 5.5 | % | 8.3 | 2014a | 5.5 | % | 8.4 | 2014b | 6.0 | % | 8.6 | 2015b | 7.0 | % | 9.0 | 2016a | 7.5 | % % Different versions of CUDA may work using the hack described % above (i.e. setting the `CudaMethod` to `nvcc`). % % The following configurations have been tested successfully: % % * Windows 7 x64, MATLAB R2014a, Visual C++ 2010, 2013 and CUDA Toolkit % 6.5. VS 2015 CPU version only (not supported by CUDA Toolkit yet). % * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA % Toolkit 6.5. % * Mac OS X 10.9, 10.10, 10.11, MATLAB R2013a to R2016a, Xcode, CUDA % Toolkit 5.5 to 7.5. % * GNU/Linux, MATALB R2014a/R2015a/R2015b/R2016a, gcc/g++, CUDA Toolkit 5.5/6.5/7.5. % % Compilation on Windows with MinGW compiler (the default mex compiler in % Matlab) is not supported. For Windows, please reconfigure mex to use % Visual Studio C/C++ compiler. % Furthermore your GPU card must have ComputeCapability >= 2.0 (see % output of `gpuDevice()`) in order to be able to run the GPU code. % To change the compute capabilities, for `mex` `CudaMethod` edit % the particular config file. For the 'nvcc' method, compute % capability is guessed based on the GPUDEVICE output. You can % override it by setting the 'CudaArch' parameter (e.g. in case of % multiple GPUs with various architectures). % % See also: [Compliling MatConvNet](../install.md#compiling), % [Compiling MEX files containing CUDA % code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html), % `vl_setup()`, `vl_imreadjpeg()`. % Copyright (C) 2014-16 Karel Lenc and Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). % Get MatConvNet root directory root = fileparts(fileparts(mfilename('fullpath'))) ; addpath(fullfile(root, 'matlab')) ; % -------------------------------------------------------------------- % Parse options % -------------------------------------------------------------------- opts.enableGpu = false; opts.enableImreadJpeg = true; opts.enableCudnn = false; opts.enableDouble = true; opts.imageLibrary = [] ; opts.imageLibraryCompileFlags = {} ; opts.imageLibraryLinkFlags = [] ; opts.verbose = 0; opts.debug = false; opts.cudaMethod = [] ; opts.cudaRoot = [] ; opts.cudaArch = [] ; opts.defCudaArch = [... '-gencode=arch=compute_20,code=\"sm_20,compute_20\" '... '-gencode=arch=compute_30,code=\"sm_30,compute_30\"']; opts.cudnnRoot = 'local/cudnn' ; opts = vl_argparse(opts, varargin); % -------------------------------------------------------------------- % Files to compile % -------------------------------------------------------------------- arch = computer('arch') ; if isempty(opts.imageLibrary) switch arch case 'glnxa64', opts.imageLibrary = 'libjpeg' ; case 'maci64', opts.imageLibrary = 'quartz' ; case 'win64', opts.imageLibrary = 'gdiplus' ; end end if isempty(opts.imageLibraryLinkFlags) switch opts.imageLibrary case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ; case 'quartz', opts.imageLibraryLinkFlags = {'-framework Cocoa -framework ImageIO'} ; case 'gdiplus', opts.imageLibraryLinkFlags = {'gdiplus.lib'} ; end end lib_src = {} ; mex_src = {} ; % Files that are compiled as CPP or CU depending on whether GPU support % is enabled. if opts.enableGpu, ext = 'cu' ; else ext='cpp' ; end lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbilinearsampler.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnroipooling.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbilinearsampler.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnroipool.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src',['vl_taccummex.' ext]) ; switch arch case {'glnxa64','maci64'} % not yet supported in windows mex_src{end+1} = fullfile(root,'matlab','src',['vl_tmove.' ext]) ; end % CPU-specific files lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_cpu.cpp') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','imread.cpp') ; % GPU-specific files if opts.enableGpu lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_gpu.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ; mex_src{end+1} = fullfile(root,'matlab','src','vl_cudatool.cu') ; end % cuDNN-specific files if opts.enableCudnn lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbilinearsampler_cudnn.cu') ; lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbnorm_cudnn.cu') ; end % Other files if opts.enableImreadJpeg mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ; mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg_old.' ext]) ; lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ; end % -------------------------------------------------------------------- % Setup CUDA toolkit % -------------------------------------------------------------------- if opts.enableGpu opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ; % Find the CUDA Devkit if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts) ; end opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ... mfilename, opts.cudaRoot) ; opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ; switch arch case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ; case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ; case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ; otherwise, error('Unsupported architecture ''%s''.', arch) ; end % Set the nvcc method as default for Win platforms if strcmp(arch, 'win64') && isempty(opts.cudaMethod) opts.cudaMethod = 'nvcc'; end % Activate the CUDA Devkit cuver = activate_nvcc(opts.nvccPath) ; opts.verbose && fprintf('%s:\tCUDA: using NVCC ''%s'' (%d).\n', ... mfilename, opts.nvccPath, cuver) ; % Set the CUDA arch string (select GPU architecture) if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ... mfilename, opts.cudaArch) ; end if opts.enableCudnn opts.cudnnIncludeDir = fullfile(opts.cudnnRoot, 'include') ; switch arch case 'win64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib', 'x64') ; case 'maci64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib') ; case 'glnxa64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib64') ; otherwise, error('Unsupported architecture ''%s''.', arch) ; end end % -------------------------------------------------------------------- % Compiler options % -------------------------------------------------------------------- % Build directories mex_dir = fullfile(root, 'matlab', 'mex') ; bld_dir = fullfile(mex_dir, '.build'); if ~exist(fullfile(bld_dir,'bits','impl'), 'dir') mkdir(fullfile(bld_dir,'bits','impl')) ; end % Compiler flags flags.cc = {} ; flags.ccpass = {} ; flags.ccoptim = {} ; flags.link = {} ; flags.linklibs = {} ; flags.linkpass = {} ; flags.nvccpass = {char(opts.cudaArch)} ; if opts.verbose > 1 flags.cc{end+1} = '-v' ; end if opts.debug flags.cc{end+1} = '-g' ; flags.nvccpass{end+1} = '-O0' ; else flags.cc{end+1} = '-DNDEBUG' ; flags.nvccpass{end+1} = '-O3' ; end if opts.enableGpu flags.cc{end+1} = '-DENABLE_GPU' ; end if opts.enableCudnn flags.cc{end+1} = '-DENABLE_CUDNN' ; flags.cc{end+1} = ['-I"' opts.cudnnIncludeDir '"'] ; end if opts.enableDouble flags.cc{end+1} = '-DENABLE_DOUBLE' ; end flags.link{end+1} = '-lmwblas' ; switch arch case {'maci64'} case {'glnxa64'} flags.linklibs{end+1} = '-lrt' ; case {'win64'} % VisualC does not pass this even if available in the CPU architecture flags.cc{end+1} = '-D__SSSE3__' ; end if opts.enableImreadJpeg flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ; flags.linklibs = horzcat(flags.linklibs, opts.imageLibraryLinkFlags) ; end if opts.enableGpu flags.link = horzcat(flags.link, {['-L"' opts.cudaLibDir '"'], '-lcudart', '-lcublas'}) ; switch arch case {'maci64', 'glnxa64'} flags.link{end+1} = '-lmwgpu' ; case 'win64' flags.link{end+1} = '-lgpu' ; end if opts.enableCudnn flags.link{end+1} = ['-L"' opts.cudnnLibDir '"'] ; flags.link{end+1} = '-lcudnn' ; end end switch arch case {'maci64'} flags.ccpass{end+1} = '-mmacosx-version-min=10.9' ; flags.linkpass{end+1} = '-mmacosx-version-min=10.9' ; flags.ccoptim{end+1} = '-mssse3 -ffast-math' ; flags.nvccpass{end+1} = '-Xcompiler -fPIC' ; if opts.enableGpu flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ; end if opts.enableGpu && opts.enableCudnn flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ; end if opts.enableGpu && cuver < 70000 % CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native % clang libc++. This should go away in the future. flags.ccpass{end+1} = '-stdlib=libstdc++' ; flags.linkpass{end+1} = '-stdlib=libstdc++' ; if ~verLessThan('matlab', '8.5.0') % Complicating matters, MATLAB 8.5.0 links to clang's libc++ by % default when linking MEX files overriding the option above. We % force it to use GCC libstdc++ flags.linkpass{end+1} = '-L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ; end end case {'glnxa64'} flags.ccoptim{end+1} = '-mssse3 -ftree-vect-loop-version -ffast-math -funroll-all-loops' ; flags.nvccpass{end+1} = '-Xcompiler -fPIC -D_FORCE_INLINES' ; if opts.enableGpu flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ; end if opts.enableGpu && opts.enableCudnn flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ; end case {'win64'} flags.nvccpass{end+1} = '-Xcompiler /MD' ; cl_path = fileparts(check_clpath()); % check whether cl.exe in path flags.nvccpass{end+1} = sprintf('--compiler-bindir "%s"', cl_path) ; end % -------------------------------------------------------------------- % Command flags % -------------------------------------------------------------------- flags.mexcc = horzcat(flags.cc, ... {'-largeArrayDims'}, ... {['CXXFLAGS=$CXXFLAGS ' strjoin(flags.ccpass)]}, ... {['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' strjoin(flags.ccoptim)]}) ; if ~ispc, flags.mexcc{end+1} = '-cxx'; end % mex: compile GPU flags.mexcu= horzcat({'-f' mex_cuda_config(root)}, ... flags.cc, ... {'-largeArrayDims'}, ... {['CXXFLAGS=$CXXFLAGS ' quote_nvcc(flags.ccpass) ' ' strjoin(flags.nvccpass)]}, ... {['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' quote_nvcc(flags.ccoptim)]}) ; % mex: link flags.mexlink = horzcat(flags.cc, flags.link, ... {'-largeArrayDims'}, ... {['LDFLAGS=$LDFLAGS ', strjoin(flags.linkpass)]}, ... {['LINKLIBS=', strjoin(flags.linklibs), ' $LINKLIBS']}) ; % nvcc: compile GPU flags.nvcc = horzcat(flags.cc, ... {opts.cudaArch}, ... {sprintf('-I"%s"', fullfile(matlabroot, 'extern', 'include'))}, ... {sprintf('-I"%s"', fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include'))}, ... {quote_nvcc(flags.ccpass)}, ... {quote_nvcc(flags.ccoptim)}, ... flags.nvccpass) ; if opts.verbose fprintf('%s: * Compiler and linker configurations *\n', mfilename) ; fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ; fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ; fprintf('%s: \tMEX options [CC CPU]: %s\n', mfilename, strjoin(flags.mexcc)) ; fprintf('%s: \tMEX options [LINK]: %s\n', mfilename, strjoin(flags.mexlink)) ; end if opts.verbose && opts.enableGpu fprintf('%s: \tMEX options [CC GPU]: %s\n', mfilename, strjoin(flags.mexcu)) ; end if opts.verbose && opts.enableGpu && strcmp(opts.cudaMethod,'nvcc') fprintf('%s: \tNVCC options [CC GPU]: %s\n', mfilename, strjoin(flags.nvcc)) ; end if opts.verbose && opts.enableImreadJpeg fprintf('%s: * Reading images *\n', mfilename) ; fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ; fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ; fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ; fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ; end % -------------------------------------------------------------------- % Compile % -------------------------------------------------------------------- % Intermediate object files srcs = horzcat(lib_src,mex_src) ; for i = 1:numel(horzcat(lib_src, mex_src)) [~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ; objfile = toobj(bld_dir,srcs{i}); if strcmp(ext,'cu') if strcmp(opts.cudaMethod,'nvcc') nvcc_compile(opts, srcs{i}, objfile, flags.nvcc) ; else mex_compile(opts, srcs{i}, objfile, flags.mexcu) ; end else mex_compile(opts, srcs{i}, objfile, flags.mexcc) ; end assert(exist(objfile, 'file') ~= 0, 'Compilation of %s failed.', objfile); end % Link into MEX files for i = 1:numel(mex_src) objs = toobj(bld_dir, [mex_src(i), lib_src]) ; mex_link(opts, objs, mex_dir, flags.mexlink) ; end % Reset path adding the mex subdirectory just created vl_setupnn() ; % -------------------------------------------------------------------- % Utility functions % -------------------------------------------------------------------- % -------------------------------------------------------------------- function objs = toobj(bld_dir,srcs) % -------------------------------------------------------------------- str = fullfile('matlab','src') ; multiple = iscell(srcs) ; if ~multiple, srcs = {srcs} ; end objs = cell(1, numel(srcs)); for t = 1:numel(srcs) i = strfind(srcs{t},str); objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ; end if ~multiple, objs = objs{1} ; end objs = regexprep(objs,'.cpp$',['.' objext]) ; objs = regexprep(objs,'.cu$',['.' objext]) ; objs = regexprep(objs,'.c$',['.' objext]) ; % -------------------------------------------------------------------- function mex_compile(opts, src, tgt, mex_opts) % -------------------------------------------------------------------- mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ; opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ; mex(mopts{:}) ; % -------------------------------------------------------------------- function nvcc_compile(opts, src, tgt, nvcc_opts) % -------------------------------------------------------------------- nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc'); nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ... nvcc_path, src, ... strjoin(nvcc_opts), tgt); opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ; status = system(nvcc_cmd); if status, error('Command %s failed.', nvcc_cmd); end; % -------------------------------------------------------------------- function mex_link(opts, objs, mex_dir, mex_flags) % -------------------------------------------------------------------- mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ; opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ; mex(mopts{:}) ; % -------------------------------------------------------------------- function ext = objext() % -------------------------------------------------------------------- % Get the extension for an 'object' file for the current computer % architecture switch computer('arch') case 'win64', ext = 'obj'; case {'maci64', 'glnxa64'}, ext = 'o' ; otherwise, error('Unsupported architecture %s.', computer) ; end % -------------------------------------------------------------------- function conf_file = mex_cuda_config(root) % -------------------------------------------------------------------- % Get mex CUDA config file mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ; if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end arch = computer('arch') ; switch arch case {'win64'} config_dir = fullfile(matlabroot, 'toolbox', ... 'distcomp', 'gpu', 'extern', ... 'src', 'mex', arch) ; case {'maci64', 'glnxa64'} config_dir = fullfile(root, 'matlab', 'src', 'config') ; end conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]); fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file); % -------------------------------------------------------------------- function cl_path = check_clpath() % -------------------------------------------------------------------- % Checks whether the cl.exe is in the path (needed for the nvcc). If % not, tries to guess the location out of mex configuration. cc = mex.getCompilerConfigurations('c++'); if isempty(cc) error(['Mex is not configured.'... 'Run "mex -setup" to configure your compiler. See ',... 'http://www.mathworks.com/support/compilers ', ... 'for supported compilers for your platform.']); end cl_path = fullfile(cc.Location, 'VC', 'bin', 'amd64'); [status, ~] = system('cl.exe -help'); if status == 1 warning('CL.EXE not found in PATH. Trying to guess out of mex setup.'); prev_path = getenv('PATH'); setenv('PATH', [prev_path ';' cl_path]); status = system('cl.exe'); if status == 1 setenv('PATH', prev_path); error('Unable to find cl.exe'); else fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ... cl_path); end end % ------------------------------------------------------------------------- function paths = which_nvcc() % ------------------------------------------------------------------------- switch computer('arch') case 'win64' [~, paths] = system('where nvcc.exe'); paths = strtrim(paths); paths = paths(strfind(paths, '.exe')); case {'maci64', 'glnxa64'} [~, paths] = system('which nvcc'); paths = strtrim(paths) ; end % ------------------------------------------------------------------------- function cuda_root = search_cuda_devkit(opts) % ------------------------------------------------------------------------- % This function tries to to locate a working copy of the CUDA Devkit. opts.verbose && fprintf(['%s:\tCUDA: searching for the CUDA Devkit' ... ' (use the option ''CudaRoot'' to override):\n'], mfilename); % Propose a number of candidate paths for NVCC paths = {getenv('MW_NVCC_PATH')} ; paths = [paths, which_nvcc()] ; for v = {'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0'} switch computer('arch') case 'glnxa64' paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ; case 'maci64' paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ; case 'win64' paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ; end end paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ; % Validate each candidate NVCC path for i=1:numel(paths) nvcc(i).path = paths{i} ; [nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(paths{i}) ; end if opts.verbose fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ; for i=1:numel(paths) fprintf('\t| %5d | %5d | %-70s |\n', ... nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ; end end % Pick an entry index = find([nvcc.isvalid]) ; if isempty(index) error('Could not find a valid NVCC executable\n') ; end [~, newest] = max([nvcc(index).version]); nvcc = nvcc(index(newest)) ; cuda_root = fileparts(fileparts(nvcc.path)) ; if opts.verbose fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ... mfilename, nvcc.path, nvcc.version) ; end % ------------------------------------------------------------------------- function [valid, cuver] = validate_nvcc(nvccPath) % ------------------------------------------------------------------------- [status, output] = system(sprintf('"%s" --version', nvccPath)) ; valid = (status == 0) ; if ~valid cuver = 0 ; return ; end match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ; if isempty(match), valid = false ; return ; end cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ; % -------------------------------------------------------------------- function cuver = activate_nvcc(nvccPath) % -------------------------------------------------------------------- % Validate the NVCC compiler installation [valid, cuver] = validate_nvcc(nvccPath) ; if ~valid error('The NVCC compiler ''%s'' does not appear to be valid.', nvccPath) ; end % Make sure that NVCC is visible by MEX by setting the MW_NVCC_PATH % environment variable to the NVCC compiler path if ~strcmp(getenv('MW_NVCC_PATH'), nvccPath) warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', nvccPath) ; setenv('MW_NVCC_PATH', nvccPath) ; end % In some operating systems and MATLAB versions, NVCC must also be % available in the command line search path. Make sure that this is% % the case. [valid_, cuver_] = validate_nvcc('nvcc') ; if ~valid_ || cuver_ ~= cuver warning('NVCC not found in the command line path or the one found does not matches ''%s''.', nvccPath); nvccDir = fileparts(nvccPath) ; prevPath = getenv('PATH') ; switch computer case 'PCWIN64', separator = ';' ; case {'GLNXA64', 'MACI64'}, separator = ':' ; end setenv('PATH', [nvccDir separator prevPath]) ; [valid_, cuver_] = validate_nvcc('nvcc') ; if ~valid_ || cuver_ ~= cuver setenv('PATH', prevPath) ; error('Unable to set the command line path to point to ''%s'' correctly.', nvccPath) ; else fprintf('Location of NVCC (%s) added to your command search PATH.\n', nvccDir) ; end end % ------------------------------------------------------------------------- function str = quote_nvcc(str) % ------------------------------------------------------------------------- if iscell(str), str = strjoin(str) ; end str = strrep(strtrim(str), ' ', ',') ; if ~isempty(str), str = ['-Xcompiler ' str] ; end % -------------------------------------------------------------------- function cudaArch = get_cuda_arch(opts) % -------------------------------------------------------------------- opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename); try gpu_device = gpuDevice(); arch_code = strrep(gpu_device.ComputeCapability, '.', ''); cudaArch = ... sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ... arch_code, arch_code, arch_code) ; catch opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU; ' ... 'falling back to default\n'], mfilename); cudaArch = opts.defCudaArch; end
%kcmaxlik_printsig 'Print a Maximum Likelihood Signature ' % This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cmaxlik_printsig.pane file % % Parameters: % InputFile: isig 'Input Signature', required: 'input signature file' % MultiChoice: omode 'Output Mode', default: 1: 'output mode toggle' % Choices are: % 1: 'Text' % 2: 'LaTeX' % 3: 'HTML' % 4: 'CSV' % OutputFile: o 'Output', optional: 'output signature info' % % Example: o = kcmaxlik_printsig(isig, {'isig','';'omode',1;'o',''}) % % Khoros helpfile follows below: % % PROGRAM % cmaxlik_printsig - Print a Maximum Likelihood Signature % % DESCRIPTION % This operator prints out the contents of a Maximum Likelihood Signature file created with "cmaxlik_signature". It expects a valid Maximum Likelihood signature file (passed with the parameter [-isig]), so its input must be either the output of a \fIcmaxlik_signature\fP or the output of \fIkappend\fP which appended several signatures together in the time dimension. Its output (passed with the parameter [-o], or redirected to kstdout) can be formatted so it can be used in reports, etc. % The output of this program can be in four formats, depending on the value of the parameter [-omode] : % The Text (ASCII) format option ([-omode 1]) formats the output so it can be viewed with simple text editors or in kstdout. % The LaTeX format option ([-omode 2]) formats the output so it can be included in a LaTeX file with the \\input command. % The HTML format option ([-omode 3]) formats the output in a HTML table so it can be read into a HTML file. % The CSV format option ([-omode 4]) formats the output in a Comma-delimited format so it can be read by spreadsheets, etc. % % % % EXAMPLES % All examples for the Classify toolbox are listed on the Classify Toolbox Manual. For an example of this routine, please see the example workspace Classify:workspaces:MAXLIK-Signatures. % % "SEE ALSO" % cmaxlik_signature % % RESTRICTIONS % Expect the input to be a valid signature file for the Maximum Likelihood classifier. % % REFERENCES % All references for the Classify toolbox are listed on the Classify Toolbox Manual. % % COPYRIGHT % Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc. % function varargout = kcmaxlik_printsig(varargin) if nargin ==0 Inputs={};arglist={'',''}; elseif nargin ==1 Inputs=varargin{1};arglist={'',''}; elseif nargin ==2 Inputs=varargin{1}; arglist=varargin{2}; else error('Usage: [out1,..] = kcmaxlik_printsig(Inputs,arglist).'); end if size(arglist,2)~=2 error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}') end narglist={'isig', '__input';'omode', 1;'o', '__output'}; maxval={0,0,1}; minval={0,0,1}; istoggle=[0,0,1]; was_set=istoggle * 0; paramtype={'InputFile','MultiChoice','OutputFile'}; % identify the input arrays and assign them to the arguments as stated by the user if ~iscell(Inputs) Inputs = {Inputs}; end NumReqOutputs=0; nextinput=1; nextoutput=1; for ii=1:size(arglist,1) wasmatched=0; for jj=1:size(narglist,1) if strcmp(arglist{ii,1},narglist{jj,1}) % a given argument was matched to the possible arguments wasmatched = 1; was_set(jj) = 1; if strcmp(narglist{jj,2}, '__input') if (nextinput > length(Inputs)) error(['Input ' narglist{jj,1} ' has no corresponding input!']); end narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; elseif strcmp(narglist{jj,2}, '__output') if (nextoutput > nargout) error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); end if (isempty(arglist{ii,2})) narglist{jj,2} = 'OK_out'; else narglist{jj,2} = arglist{ii,2}; end nextoutput = nextoutput + 1; if (minval{jj} == 0) NumReqOutputs = NumReqOutputs - 1; end elseif isstr(arglist{ii,2}) narglist{jj,2} = arglist{ii,2}; else if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2}) error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']); end if (minval{jj} ~= 0 | maxval{jj} ~= 0) if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0) error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']); elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0) error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']); elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0) error(['Argument ' arglist{ii,1} ' must be bigger than zero!']); elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0) error(['Argument ' arglist{ii,1} ' must be smaller than zero!']); elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj}) error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]); elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj}) error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]); end end end if ~strcmp(narglist{jj,2},'OK_out') & ~strcmp(narglist{jj,2},'OK_in') narglist{jj,2} = arglist{ii,2}; end end end if (wasmatched == 0 & ~strcmp(arglist{ii,1},'')) error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']); end end % match the remaining inputs/outputs to the unused arguments and test for missing required inputs for jj=1:size(narglist,1) if strcmp(paramtype{jj}, 'Toggle') if (narglist{jj,2} ==0) narglist{jj,1} = ''; end; narglist{jj,2} = ''; end; if ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj) narglist{jj,1} = ''; narglist{jj,2} = ''; end; if strcmp(narglist{jj,2}, '__input') if (minval{jj} == 0) % meaning this input is required if (nextinput > size(Inputs)) error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); else narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; end else % this is an optional input if (nextinput <= length(Inputs)) narglist{jj,2} = 'OK_in'; nextinput = nextinput + 1; else narglist{jj,1} = ''; narglist{jj,2} = ''; end; end; else if strcmp(narglist{jj,2}, '__output') if (minval{jj} == 0) % this is a required output if (nextoutput > nargout & nargout > 1) error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); else narglist{jj,2} = 'OK_out'; nextoutput = nextoutput + 1; NumReqOutputs = NumReqOutputs-1; end else % this is an optional output if (nargout - nextoutput >= NumReqOutputs) narglist{jj,2} = 'OK_out'; nextoutput = nextoutput + 1; else narglist{jj,1} = ''; narglist{jj,2} = ''; end; end end end end if nargout varargout = cell(1,nargout); else varargout = cell(1,1); end global KhorosRoot if exist('KhorosRoot') && ~isempty(KhorosRoot) w=['"' KhorosRoot]; else if ispc w='"C:\Program Files\dip\khorosBin\'; else [s,w] = system('which cantata'); w=['"' w(1:end-8)]; end end [varargout{:}]=callKhoros([w 'cmaxlik_printsig" '],Inputs,narglist);
Formal statement is: proposition Liouville_weak_inverse: assumes "f holomorphic_on UNIV" and unbounded: "\<And>B. eventually (\<lambda>x. norm (f x) \<ge> B) at_infinity" obtains z where "f z = 0" Informal statement is: If $f$ is a holomorphic function on $\mathbb{C}$ and $f$ is unbounded, then $f$ has a zero.
= = = Awards and nominations = = =
(** * Laws about composition of functors *) Require Import Category.Core Functor.Core Functor.Identity Functor.Composition.Core NaturalTransformation.Core NaturalTransformation.Identity NaturalTransformation.Composition.Core NaturalTransformation.Paths. Set Universe Polymorphism. Set Implicit Arguments. Generalizable All Variables. Set Asymmetric Patterns. Local Open Scope morphism_scope. Local Open Scope natural_transformation_scope. Section natural_transformation_identity. Context `{Funext}. Variables C D : PreCategory. (** ** left identity : [1 ∘ T = T] *) Lemma left_identity (F F' : Functor C D) (T : NaturalTransformation F F') : 1 o T = T. Proof. path_natural_transformation; auto with morphism. Qed. (** ** right identity : [T ∘ 1 = T] *) Lemma right_identity (F F' : Functor C D) (T : NaturalTransformation F F') : T o 1 = T. Proof. path_natural_transformation; auto with morphism. Qed. (** ** right whisker left identity : [1 ∘ᴿ F = 1] *) Definition whisker_r_left_identity E (G : Functor D E) (F : Functor C D) : identity G oR F = 1. Proof. path_natural_transformation; auto with morphism. Qed. (** ** left whisker right identity : [G ∘ᴸ 1 = 1] *) Definition whisker_l_right_identity E (G : Functor D E) (F : Functor C D) : G oL identity F = 1. Proof. path_natural_transformation; auto with functor. Qed. End natural_transformation_identity. Hint Rewrite @left_identity @right_identity : category. Hint Rewrite @left_identity @right_identity : natural_transformation. Section whisker. Context `{fs : Funext}. (** ** whisker exchange law : [(G' ∘ᴸ T) ∘ (T' ∘ᴿ F) = (T' ∘ᴿ F') ∘ (G ∘ᴸ T)] *) Section exch. Variables C D E : PreCategory. Variables G G' : Functor D E. Variables F F' : Functor C D. Variable T' : NaturalTransformation G G'. Variable T : NaturalTransformation F F'. Lemma exchange_whisker : (G' oL T) o (T' oR F) = (T' oR F') o (G oL T). Proof. path_natural_transformation; simpl. symmetry. apply NaturalTransformation.Core.commutes. Qed. End exch. Section whisker. Variables C D : PreCategory. Variables F G H : Functor C D. Variable T : NaturalTransformation G H. Variable T' : NaturalTransformation F G. (** ** left whisker composition : [F ∘ᴸ (T ∘ T') = (F ∘ᴸ T) ∘ (F ∘ᴸ T')] *) Lemma composition_of_whisker_l E (I : Functor D E) : I oL (T o T') = (I oL T) o (I oL T'). Proof. path_natural_transformation; apply composition_of. Qed. (** ** right whisker composition : [(T ∘ T') ∘ᴿ F = (T ∘ᴿ F) ∘ (T' ∘ᴿ F)] *) Lemma composition_of_whisker_r B (I : Functor B C) : (T o T') oR I = (T oR I) o (T' oR I). Proof. path_natural_transformation; apply idpath. Qed. End whisker. End whisker. Section associativity. (** ** associators - natural transformations between [F ∘ (G ∘ H)] and [(F ∘ G) ∘ H] *) Section functors. Variables B C D E : PreCategory. Variable F : Functor D E. Variable G : Functor C D. Variable H : Functor B C. Local Notation F0 := ((F o G) o H)%functor. Local Notation F1 := (F o (G o H))%functor. Definition associator_1 : NaturalTransformation F0 F1 := Eval simpl in generalized_identity F0 F1 idpath idpath. Definition associator_2 : NaturalTransformation F1 F0 := Eval simpl in generalized_identity F1 F0 idpath idpath. End functors. (** ** associativity : [(T ∘ U) ∘ V = T ∘ (U ∘ V)] *) Section nt. Context `{fs : Funext}. Local Open Scope natural_transformation_scope. Definition associativity C D F G H I (V : @NaturalTransformation C D F G) (U : @NaturalTransformation C D G H) (T : @NaturalTransformation C D H I) : (T o U) o V = T o (U o V). Proof. path_natural_transformation. apply associativity. Qed. End nt. End associativity. Section functor_identity. Context `{Funext}. Variables C D : PreCategory. Local Ltac nt_id_t := split; path_natural_transformation; autorewrite with morphism; reflexivity. (** ** left unitors : natural transformations between [1 ∘ F] and [F] *) Section left. Variable F : Functor D C. Definition left_identity_natural_transformation_1 : NaturalTransformation (1 o F) F := Eval simpl in generalized_identity (1 o F) F idpath idpath. Definition left_identity_natural_transformation_2 : NaturalTransformation F (1 o F) := Eval simpl in generalized_identity F (1 o F) idpath idpath. Theorem left_identity_isomorphism : left_identity_natural_transformation_1 o left_identity_natural_transformation_2 = 1 /\ left_identity_natural_transformation_2 o left_identity_natural_transformation_1 = 1. Proof. nt_id_t. Qed. End left. (** ** right unitors : natural transformations between [F ∘ 1] and [F] *) Section right. Variable F : Functor C D. Definition right_identity_natural_transformation_1 : NaturalTransformation (F o 1) F := Eval simpl in generalized_identity (F o 1) F idpath idpath. Definition right_identity_natural_transformation_2 : NaturalTransformation F (F o 1) := Eval simpl in generalized_identity F (F o 1) idpath idpath. Theorem right_identity_isomorphism : right_identity_natural_transformation_1 o right_identity_natural_transformation_2 = 1 /\ right_identity_natural_transformation_2 o right_identity_natural_transformation_1 = 1. Proof. nt_id_t. Qed. End right. End functor_identity. (** ** Tactics for inserting appropriate associators, whiskers, and unitors *) Ltac nt_solve_associator' := repeat match goal with | _ => exact (associator_1 _ _ _) | _ => exact (associator_2 _ _ _) | _ => exact (left_identity_natural_transformation_1 _) | _ => exact (left_identity_natural_transformation_2 _) | _ => exact (right_identity_natural_transformation_1 _) | _ => exact (right_identity_natural_transformation_2 _) | [ |- NaturalTransformation (?F o _) (?F o _) ] => refine (whisker_l F _) | [ |- NaturalTransformation (_ o ?F) (_ o ?F) ] => refine (whisker_r _ F) end. Ltac nt_solve_associator := repeat first [ progress nt_solve_associator' | refine (compose (associator_1 _ _ _) _); progress nt_solve_associator' | refine (compose _ (associator_1 _ _ _)); progress nt_solve_associator' | refine (compose (associator_2 _ _ _) _); progress nt_solve_associator' | refine (compose _ (associator_2 _ _ _)); progress nt_solve_associator' ].
function [event] = read_yokogawa_event(filename, varargin) % READ_YOKOGAWA_EVENT reads event information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows those events to be used in % combination with FieldTrip. % % Use as % [event] = read_yokogawa_event(filename) % % See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_DATA % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip 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. % % FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ event = []; handles = definehandles; % get the options, the default is set below chanindx = ft_getopt(varargin, 'chanindx'); threshold = ft_getopt(varargin, 'threshold'); detectflank = ft_getopt(varargin, 'detectflank'); combinebinary = ft_getopt(varargin, 'combinebinary', false); trigshift = ft_getopt(varargin, 'trigshift'); if isempty(combinebinary) combinebinary = false; end % ensure that the required toolbox is on the path if ft_hastoolbox('yokogawa_meg_reader') % read the dataset header hdr = read_yokogawa_header_new(filename); ch_info = hdr.orig.channel_info.channel; type = [ch_info.type]; % determine the trigger channels (if not specified by the user) if isempty(chanindx) chanindx = find(type==handles.TriggerChannel); end % Use the MEG Reader documentation if more detailed support is required. if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials event = getYkgwHdrEvent(filename); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = event(i).code; end end % Use the MEG Reader documentation if more detailed support is required. elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % Events annotated by users during measurements bookmark_tmp = getYkgwHdrBookmark(filename); if ~isempty(bookmark_tmp) for i = 1:length(bookmark_tmp) event(end+1).sample = bookmark_tmp(i).sample_no + 1; event(end ).type = 'bookmarks'; if ~isempty(bookmark_tmp(i).label) event(end ).value = bookmark_tmp(i).label; %% 0 in default else event(end ).value = 99; end end end clear bookmark_tmp; end elseif ft_hastoolbox('yokogawa') % read the dataset header hdr = read_yokogawa_header(filename); % determine the trigger channels (if not specified by the user) if isempty(chanindx) chanindx = find(hdr.orig.channel_info(:,2)==handles.TriggerChannel); end if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials fid = fopen_or_error(filename, 'r'); value = GetMeg160TriggerEventM(fid); fclose(fid); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = value(i); end end elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % the data structure does not contain events, but flank detection on the trigger channel might reveal them % this is done below end else ft_error('cannot determine whether the required Yokogawa toolbox is present'); end % read the trigger channels and detect the flanks if ~isempty(chanindx) trigger = read_trigger(filename, 'header', hdr, 'denoise', false, 'chanindx', chanindx, 'detectflank', detectflank, 'threshold', threshold, 'combinebinary', combinebinary, 'trigshift', trigshift); % combine the triggers and the other events event = appendstruct(event, trigger); end if isempty(event) ft_warning('no triggers were detected, please specify the "trigindx" option'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
Require Import VST.floyd.proofauto. Require Import incr. #[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined. Definition Vprog : varspecs. mk_varspecs prog. Defined. Definition incr1_spec := DECLARE _incr1 WITH i: Z, a: val, sh: share, private: list val PRE [ tint, tptr tuint ] PROP (0 <= i < Int.max_signed; writable_share sh) PARAMS (Vint (Int.repr i); a) GLOBALS () SEP(data_at sh (tarray tuint 10) private a) POST [ tint ] EX private':list val, PROP() LOCAL(temp ret_temp (Vint (Int.repr (i+1)))) SEP(data_at sh (tarray tuint 10) private' a). Definition incr2_spec := DECLARE _incr2 WITH i: Z, a: val PRE [ tint, tptr tuint ] PROP (0 <= i < Int.max_signed) PARAMS (Vint (Int.repr i); a) GLOBALS () SEP() POST [ tint ] PROP() LOCAL(temp ret_temp (Vint (Int.repr (i+1)))) SEP(). Lemma sub_incr12: funspec_sub (snd incr2_spec) (snd incr1_spec). Proof. do_funspec_sub. destruct w as [[[i a] sh] data]. clear H. Exists (i,a) (data_at sh (tarray tuint 10) data a). simpl; entailer!. intros tau ? ?. Exists data. entailer!. Qed. Definition incr3_spec := DECLARE _incr3 WITH i: Z, gv: globals, sh: share, private: list val PRE [ tint ] PROP (0 <= i < Int.max_signed; writable_share sh) PARAMS (Vint (Int.repr i)) GLOBALS (gv) SEP(data_at sh (tarray tuint 10) private (gv _global_auxdata)) POST [ tint ] EX private':list val, PROP() LOCAL(temp ret_temp (Vint (Int.repr (i+1)))) SEP(data_at sh (tarray tuint 10) private' (gv _global_auxdata)). Definition incr4_spec := DECLARE _incr4 WITH i: Z PRE [ tint ] PROP (0 <= i < Int.max_signed) PARAMS (Vint (Int.repr i)) GLOBALS () SEP() POST [ tint ] PROP() LOCAL(temp ret_temp (Vint (Int.repr (i+1)))) SEP(). Lemma sub_incr34: funspec_sub (snd incr4_spec) (snd incr3_spec). Proof. do_funspec_sub. destruct w as [[[i gv] sh] data]. clear H. Exists i (data_at sh (tarray tuint 10) data (gv _global_auxdata)). simpl; entailer!. intros tau ? ?. Exists data. entailer!. Qed.