Datasets:
AI4M
/

text
stringlengths
0
3.34M
workspace.clear = function() { lib.toclear = setdiff( search(),lib.init ) if (length(lib.toclear) > 0) { for (pkg in lib.toclear ) detach( pos=match( pkg, search() ) ) } rm ( lib.toclear) obj.toclear = setdiff( ls(), obj.init ) try( rm( list=obj.toclear ), silent=T ) rm (obj.toclear) namespace.toclear = setdiff( loadedNamespaces(), namespaces.init ) try(unloadNamespace( namespace.toclear ), silent=T) rm (namespace.toclear) gc() cat( "Namespaces still in memory due to dependencies: \n") cat ( setdiff( loadedNamespaces(), namespaces.init ), "\n" ) }
Jira is a popular issue tracking product developed by Atlassian. It provides bug tracking, issue tracking, and project management functions. According to a 2017 survey, Jira is the most popular issue management tool.
If $f$ and $g$ are inverse homeomorphisms, then $f(g(x)) = x$.
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_on_inv__23.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_g2kAbsAfter Protocol Case Study*} theory n_g2kAbsAfter_lemma_on_inv__23 imports n_g2kAbsAfter_base begin section{*All lemmas on causal relation between inv__23 and some rule r*} lemma n_n_SendInvAck_i1Vsinv__23: assumes a1: "(r=n_n_SendInvAck_i1 )" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Ident ''Chan2_1'') ''Cmd'')) (Const Inv)) (eqn (IVar (Ident ''ShrSet_1'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_n_RecvInvAck_i1Vsinv__23: assumes a1: "(r=n_n_RecvInvAck_i1 )" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_n_SendGntS_i1Vsinv__23: assumes a1: "(r=n_n_SendGntS_i1 )" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_n_SendGntE_i1Vsinv__23: assumes a1: "(r=n_n_SendGntE_i1 )" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_n_RecvReq_i1Vsinv__23: assumes a1: "r=n_n_RecvReq_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendInvS_i1Vsinv__23: assumes a1: "r=n_n_SendInvS_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendReqEI_i1Vsinv__23: assumes a1: "r=n_n_SendReqEI_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendReqEI_i1Vsinv__23: assumes a1: "r=n_n_ASendReqEI_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendReqIS_j1Vsinv__23: assumes a1: "r=n_n_ASendReqIS_j1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendReqES_i1Vsinv__23: assumes a1: "r=n_n_ASendReqES_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ARecvGntE_i1Vsinv__23: assumes a1: "r=n_n_ARecvGntE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendGntS_i1Vsinv__23: assumes a1: "r=n_n_ASendGntS_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ARecvGntS_i1Vsinv__23: assumes a1: "r=n_n_ARecvGntS_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendInvE_i1Vsinv__23: assumes a1: "r=n_n_ASendInvE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendInvS_i1Vsinv__23: assumes a1: "r=n_n_ASendInvS_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendReqES_i1Vsinv__23: assumes a1: "r=n_n_SendReqES_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendInvE_i1Vsinv__23: assumes a1: "r=n_n_SendInvE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendReqSE_j1Vsinv__23: assumes a1: "r=n_n_ASendReqSE_j1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_RecvGntS_i1Vsinv__23: assumes a1: "r=n_n_RecvGntS_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendReqEE_i1Vsinv__23: assumes a1: "r=n_n_SendReqEE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_RecvGntE_i1Vsinv__23: assumes a1: "r=n_n_RecvGntE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ARecvReq_i1Vsinv__23: assumes a1: "r=n_n_ARecvReq_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_Store_i1Vsinv__23: assumes a1: "\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_AStore_i1Vsinv__23: assumes a1: "\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d" and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_SendReqS_j1Vsinv__23: assumes a1: "r=n_n_SendReqS_j1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ARecvInvAck_i1Vsinv__23: assumes a1: "r=n_n_ARecvInvAck_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendInvAck_i1Vsinv__23: assumes a1: "r=n_n_ASendInvAck_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_n_ASendGntE_i1Vsinv__23: assumes a1: "r=n_n_ASendGntE_i1 " and a2: "(f=inv__23 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
function disp(sncl) % DISP - scnl disp overloaded operator % VERSION: 1.0 of filter objects % AUTHOR: Celso Reyes % LASTUPDATE: 1/30/2007 if numel(sncl) > 1; disp(' '); DispStr = sprintf('%d',size(sncl,1)); for n = 2 : numel(size(sncl)) DispStr = sprintf('%sx%d', DispStr, size(sncl,n)); end disp(sprintf('%s %s object with fields:', DispStr, class(sncl))); disp(' station'); disp(' channel'); disp(' network'); disp(' location'); else disp([' station: ' sncl.tag.station]); disp([' channel: ' sncl.tag.channel]); disp([' network: ' sncl.tag.network]); disp([' location: ' sncl.tag.location]); end;
Require Export compcert.lib.Coqlib. Require Export msl.seplog. Require Export msl.log_normalize. Require Export msl.ramification_lemmas. Require Export Coq.Logic.JMeq. Parameter ident: Type. Parameter ident_eq: forall (a b: ident), {a = b} + {a <> b}. Parameter val: Type. Parameter Vundef: val. Inductive type: Type := | Tint: type | Tstruct: forall (id: ident) (fs: fieldlist), type with fieldlist: Type := | Fnil: fieldlist | Fcons: forall (hd: ident * type) (tl: fieldlist), fieldlist. Parameter sizeof: forall (t: type), Z. Fixpoint in_members (id: ident) (fs: fieldlist) : Prop := match fs with | Fnil => False | Fcons (id', t) fs_tl => (id = id') \/ in_members id fs_tl end. Fixpoint field_type (id: ident) (fs: fieldlist) : type := match fs with | Fnil => Tint (* default return value *) | Fcons (id', t) fs_tl => if ident_eq id id' then t else field_type id fs_tl end. Fixpoint field_offset (id: ident) (fs: fieldlist) : Z := match fs with | Fnil => 0 (* default return value *) | Fcons (id', t) fs_tl => if ident_eq id id' then 0 else field_offset id fs_tl + sizeof t end. Fixpoint members_no_replicate (fs: fieldlist): Prop := match fs with | Fnil => True | Fcons (i, t) fs_tl => ~ in_members i fs_tl /\ members_no_replicate fs_tl end. Parameter Pred: Type. Parameter NPred: NatDed Pred. Parameter SPred: SepLog Pred. Parameter CPred: ClassicalSep Pred. Parameter CSLPred: CorableSepLog Pred. Parameter mapsto: val -> val -> Pred. Parameter offset_val: Z -> val -> val. Axiom offset_offset_val: forall ofs1 ofs2 p, offset_val ofs2 (offset_val ofs1 p) = offset_val (ofs1 + ofs2) p. (* Fixpoint sizeof (t: type): Z := match t with | Tint => 1 | Tstruct _ fs => sizeof_fieldlist fs end with sizeof_fieldlist (fs: fieldlist) : Z := match fs with | Fnil => 0 | Fcons (_, t) fs_tl => sizeof t + sizeof_fieldlist fs_tl end. *)
(* Utility to defer subgoals into an isolated part of the proof state, and recover them later. *) theory Defer_Slot imports Basic_Imports begin definition "DEFER_SLOT (x::prop) \<equiv> x" lemma DEFER_SLOT_cong[cong]: "PROP DEFER_SLOT x \<equiv> PROP DEFER_SLOT x" . (* TODO: Find something better than True to put in empty slot! Perhaps "A\<Longrightarrow>A" *) abbreviation "EMPTY_DEFER_SLOT \<equiv> PROP (DEFER_SLOT (Trueprop True))" lemma insert_slot_rl1: assumes "PROP P \<Longrightarrow> PROP EMPTY_DEFER_SLOT \<Longrightarrow> PROP Q" shows "PROP (DEFER_SLOT (PROP P)) \<Longrightarrow> PROP Q" using assms unfolding DEFER_SLOT_def by simp lemma insert_slot_rl2: assumes "PROP P \<Longrightarrow> PROP (DEFER_SLOT S) \<Longrightarrow> PROP Q" shows "PROP (DEFER_SLOT (PROP S &&& PROP P)) \<Longrightarrow> PROP Q" using assms unfolding DEFER_SLOT_def conjunction_def . lemma remove_slot: "PROP (EMPTY_DEFER_SLOT)" unfolding DEFER_SLOT_def by (rule TrueI) lemmas split_constraint_rls = atomize_conj[symmetric] imp_conjunction all_conjunction conjunction_imp ML \<open> signature DEFER_SLOT = sig (******** Defer Slot *) (* Tactic with slot subgoal *) val WITH_SLOT: tactic' -> tactic (* Process all goals in slot *) val ON_SLOT: tactic -> tactic (* Create slot as last subgoal. Fail if slot already present. *) val create_slot_tac: tactic (* Create slot if there isn't one already *) val ensure_slot_tac: tactic (* Remove empty slot *) val remove_slot_tac: tactic (* Move slot to first subgoal *) val prefer_slot_tac: tactic (* Destruct slot *) val dest_slot_tac: tactic' (* Check if goal state has slot *) val has_slot: thm -> bool (* Defer subgoal to slot *) val to_slot_tac: tactic' (* Print slot contents *) val print_slot_tac: Proof.context -> tactic (* Focus on goals in slot *) val focus: tactic (* Unfocus goals in slot *) val unfocus: tactic (* Unfocus goals, and insert them as first subgoals *) val unfocus_ins:tactic (* Focus on some goals in slot *) val cond_focus: (term -> bool) -> tactic (* Move some goals to slot *) val some_to_slot_tac: (term -> bool) -> tactic end structure Defer_Slot: DEFER_SLOT = struct fun is_slot_goal @{mpat "DEFER_SLOT _"} = true | is_slot_goal _ = false fun slot_goal_num st = let val i = find_index is_slot_goal (Thm.prems_of st) + 1 in i end fun has_slot st = slot_goal_num st > 0 fun WITH_SLOT tac st = let val si = slot_goal_num st in if si>0 then tac si st else ( if Thm.nprems_of st > 0 then warning "No defer slot" else (); Seq.empty) end val to_slot_tac = IF_EXGOAL (fn i => WITH_SLOT (fn si => if i<si then prefer_tac si THEN prefer_tac (i+1) THEN ( PRIMITIVE (fn st => Drule.comp_no_flatten (st, 0) 1 @{thm insert_slot_rl1}) ORELSE PRIMITIVE (fn st => Drule.comp_no_flatten (st, 0) 1 @{thm insert_slot_rl2}) ) THEN defer_tac 1 else no_tac)) val create_slot_tac = COND (has_slot) no_tac (PRIMITIVE (Thm.implies_intr @{cterm "EMPTY_DEFER_SLOT"}) THEN defer_tac 1) val ensure_slot_tac = TRY create_slot_tac val prefer_slot_tac = WITH_SLOT prefer_tac val dest_slot_tac = SELECT_GOAL ( ALLGOALS ( CONVERSION (Conv.rewr_conv @{thm DEFER_SLOT_def}) THEN' Goal.conjunction_tac THEN' TRY o resolve0_tac @{thms TrueI}) THEN distinct_subgoals_tac ) val remove_slot_tac = WITH_SLOT (resolve0_tac @{thms remove_slot}) val focus = WITH_SLOT (fn i => PRIMITIVE (Goal.restrict i 1) THEN ALLGOALS dest_slot_tac THEN create_slot_tac) val unfocus_ins = PRIMITIVE (Goal.unrestrict 1) THEN WITH_SLOT defer_tac fun some_to_slot_tac cond = (ALLGOALS (COND' (fn t => is_slot_goal t orelse not (cond t)) ORELSE' to_slot_tac)) val unfocus = some_to_slot_tac (K true) THEN unfocus_ins fun cond_focus cond = focus THEN some_to_slot_tac (not o cond) fun ON_SLOT tac = focus THEN tac THEN unfocus fun print_slot_tac ctxt = ON_SLOT (print_tac ctxt "SLOT:") end \<close> method_setup defer_slot_print = \<open>Scan.succeed (fn ctxt => SIMPLE_METHOD (Defer_Slot.print_slot_tac ctxt))\<close> method_setup defer_slot_ensure = \<open>Scan.succeed (fn _ => SIMPLE_METHOD (Defer_Slot.ensure_slot_tac))\<close> method_setup defer_slot_defer = \<open>Scan.succeed (fn _ => SIMPLE_METHOD' (Defer_Slot.to_slot_tac))\<close> method_setup defer_slot_dest = \<open>Scan.succeed (fn _ => SIMPLE_METHOD' Defer_Slot.dest_slot_tac)\<close> method_setup defer_slot_dest' = \<open>Scan.succeed (fn _ => SIMPLE_METHOD (Defer_Slot.prefer_slot_tac THEN FIRSTGOAL (Defer_Slot.dest_slot_tac)))\<close> end
module Optimisation.StaticProcessing.StaticTracker import Core.Context import CairoCode.CairoCode import CairoCode.CairoCodeUtils import Data.List import Data.SortedSet import Data.SortedMap import Primitives.Primitives import Primitives.Externals import Primitives.Common import CairoCode.Traversal.Base import CairoCode.Traversal.ValueTracker import CairoCode.Traversal.Composition import Utils.Helpers import Utils.Lens import Debug.Trace %hide Prelude.toList -- Internal enriched definitions mutual public export data StaticValue : Type where Unknown : StaticValue Error : String -> StaticValue -- values are all possible values Const : (values: SortedSet CairoConst) -> StaticValue -- ctrs are all possible constructors Constructed : (ctrs: SortedMap Int (List StaticInfo)) -> StaticValue Closure : (name: Maybe (Name, Nat)) -> (arguments: List StaticInfo) -> StaticValue -- Allows repacking of Unknown Projections Field : (source: StaticInfo) -> (tag: Maybe Int) -> (fieldIndex: Nat) -> StaticValue public export record StaticInfo where constructor MKStaticInfo sources: SortedSet CairoReg value: StaticValue -- for debugging export Show StaticValue where show Unknown = "Unknown" show (Error e) = "Error: "++ (show e) show (Const cs) = "Constant: "++ (show cs) show (Constructed ctrs) = assert_total ("Constructed: "++ (show ctrs)) show (Closure name args) = assert_total ("Closure: "++ (show name) ++ "(" ++ (show args) ++ ")") show (Field source tag pos) = assert_total ("Field: "++ (show source) ++ "[" ++ (show tag) ++ ", " ++ (show pos) ++"]") export Show StaticInfo where show (MKStaticInfo sources value) = "{" ++ (show sources) ++ "} = " ++ (show value) -- Conversions export toValueInfo : StaticInfo -> ValueInfo toValueInfo (MKStaticInfo _ (Const cs)) = extractConst $ toList cs where extractConst : List CairoConst -> ValueInfo extractConst (c::Nil) = ConstValue c extractConst _ = UnknownValue toValueInfo (MKStaticInfo _ (Constructed ctrs)) = extractConst $ toList ctrs where extractConst : List (Int,List StaticInfo) -> ValueInfo extractConst ((t,fields)::Nil) = CompositeValue t (map toValueInfo fields) extractConst _ = UnknownValue toValueInfo (MKStaticInfo _ (Closure (Just (name, missing)) captures)) = ClosureValue name missing (map toValueInfo captures) toValueInfo (MKStaticInfo regs _) = process (toList regs) where process : List CairoReg -> ValueInfo process [Const c] = ConstValue c process _ = UnknownValue export fromValueInfo : ValueInfo -> StaticInfo fromValueInfo UnknownValue = MKStaticInfo empty Unknown fromValueInfo (ConstValue c) = MKStaticInfo (singleton (Const c)) (Const (singleton c)) fromValueInfo (CompositeValue tag fields) = MKStaticInfo empty (Constructed (fromList [(tag, map fromValueInfo fields)])) fromValueInfo (ClosureValue name miss captures) = MKStaticInfo empty (Closure (Just (name,miss)) (map fromValueInfo captures)) fromEvalRes : EvalRes -> List StaticInfo -> StaticInfo fromEvalRes (Failure s) _ = MKStaticInfo empty (Error s) fromEvalRes (NewValue val) _ = fromValueInfo val fromEvalRes (ArgValue Z) (x::xs) = x fromEvalRes (ArgValue (S rem)) (x::xs) = fromEvalRes (ArgValue rem) xs fromEvalRes _ _ = assert_total $ idris_crash "can not process eval res" mutual mergeStaticValue : StaticValue -> StaticValue -> StaticValue mergeStaticValue (Error _) other = other -- The error would crash program so if we arrive here it is the other mergeStaticValue other (Error _) = other -- The error would crash program so if we arrive here it is the other mergeStaticValue (Const vs1) (Const vs2) = Const (union vs1 vs2) mergeStaticValue (Constructed c1) (Constructed c2) = Constructed (mergeWith mergeFields c1 c2) where mergeFields: List StaticInfo -> List StaticInfo -> List StaticInfo mergeFields f1 f2 = zipWith mergeStaticInfo f1 f2 mergeStaticValue (Closure n1 f1) (Closure n2 f2) = Closure (mergeNames n1 n2) (zipWith mergeStaticInfo f1 f2) where mergeNames : Maybe (Name, Nat) -> Maybe (Name, Nat) -> Maybe (Name, Nat) mergeNames (Just (n1, m1)) (Just (n2, m2)) = if n1 == n2 && m1 == m2 then Just (n1, m1) else Nothing mergeNames _ _ = Nothing -- todo: shall we go to Unknown if both tags are diff and remove maybe? mergeStaticValue (Field s1 t1 p1) (Field s2 t2 p2) = if p1 /= p2 then Unknown else Field (mergeStaticInfo s1 s2) (mergeTag t1 t2) p1 where mergeTag : Maybe Int -> Maybe Int -> Maybe Int mergeTag (Just t1) (Just t2) = if t1 == t2 then Just t1 else Nothing mergeTag _ _ = Nothing mergeStaticValue _ _ = Unknown export mergeStaticInfo : StaticInfo -> StaticInfo -> StaticInfo mergeStaticInfo (MKStaticInfo regs1 vals1) (MKStaticInfo regs2 vals2) = MKStaticInfo (intersection regs1 regs2) (mergeStaticValue vals1 vals2) export Semigroup StaticInfo where (<+>) = mergeStaticInfo export addBinding : StaticInfo -> CairoReg -> StaticInfo addBinding (MKStaticInfo sources Unknown) r@(Const c) = MKStaticInfo (insert r sources) (Const (singleton c)) addBinding (MKStaticInfo sources (Const cs)) r@(Const c) = MKStaticInfo (insert r sources) (Const (insert c cs)) addBinding (MKStaticInfo sources value) r = MKStaticInfo (insert r sources) value -- this checks if all the args are the fields 0 to N of the same value with the same tag as the new construct and if so returns the regs storing the original value -- basically it reorganizes that unpacking all fields and then repacking them with the same tag produces the same value export findRepackedSrcs : Int -> List StaticInfo -> SortedSet CairoReg findRepackedSrcs tag Nil = empty findRepackedSrcs tag args@(f::fs) = if isCons (toList combinedSrcRegs) && (isJust (foldl checkPosIncrementAndTag (Just 0) args)) then combinedSrcRegs else empty where extractFieldSource : StaticInfo -> SortedSet CairoReg extractFieldSource (MKStaticInfo _ (Field src _ _ )) = src.sources extractFieldSource _ = empty combinedSrcRegs : SortedSet CairoReg combinedSrcRegs = foldl1 intersection (map extractFieldSource (f::fs)) checkPosIncrementAndTag : Maybe Nat -> StaticInfo -> Maybe Nat checkPosIncrementAndTag (Just expectedPos) (MKStaticInfo _ (Field _ (Just t) pos )) = if expectedPos == pos && t == tag then Just (expectedPos+1) else Nothing checkPosIncrementAndTag _ _ = Nothing -- extract the constant value from StaticInfo if it has one export extractSingleConstant : StaticInfo -> Maybe CairoConst extractSingleConstant (MKStaticInfo _ (Const cs)) = extractIfSameConstant (toList cs) where extractIfSameConstant : List CairoConst -> Maybe CairoConst extractIfSameConstant Nil = Nothing extractIfSameConstant (x::Nil) = Just x extractIfSameConstant _ = Nothing -- as is sorted set more then 1 elem means unequal extractSingleConstant (MKStaticInfo srcs _) = if isCons allConstants then head' allConstants -- if they are more it is given that they are the same (otherwise the tracker screwed up) else Nothing where toConst : CairoReg -> List CairoConst toConst (Const c) = [c] toConst _ = [] allConstants : List CairoConst allConstants = (toList srcs) >>= toConst export asConstants : List StaticInfo -> Maybe (List CairoConst) asConstants args = if (all isJust mappedConstants) then Just (mappedConstants >>= maybeToList) else Nothing where mappedConstants : List (Maybe CairoConst) mappedConstants = (map extractSingleConstant args) maybeToList : Maybe CairoConst -> List CairoConst maybeToList (Just a) = [a] maybeToList Nothing = [] export extractField : SortedMap Int (List StaticInfo) -> Nat -> StaticInfo extractField ctrs pos = mergeAll (map (extract pos) (values ctrs)) where extract : Nat -> List StaticInfo -> StaticInfo extract _ Nil = MKStaticInfo empty Unknown extract Z (f::fs) = f extract (S rem) (f::fs) = extract rem fs mergeAll : List StaticInfo -> StaticInfo mergeAll Nil = MKStaticInfo empty Unknown mergeAll (i::is) = foldl1 mergeStaticInfo (i::is) extractSingleTag : SortedMap Int (List StaticInfo) -> Maybe Int extractSingleTag s = extract (keys s) where extract : List Int -> Maybe Int extract (x::Nil) = Just x extract _ = Nothing export resolveTag : Maybe Int -> Int resolveTag Nothing = 0 resolveTag (Just t) = t -- Just the tracking part for generating the optim infos export staticImplTracker : SortedMap LinearImplicit (StaticInfo, CairoReg) -> SortedMap LinearImplicit StaticInfo staticImplTracker impls = mapValueMap (\(_, reg) => MKStaticInfo (singleton reg) Unknown) impls export staticValueTracker : (v:InstVisit StaticInfo) -> Traversal (ScopedBindings StaticInfo) (ValBindType v StaticInfo) staticValueTracker (VisitFunction _ params impls _) = pure (map paramInit params, mapValueMap paramInit impls) where paramInit : CairoReg -> StaticInfo paramInit reg = MKStaticInfo (singleton reg) Unknown staticValueTracker (VisitForeignFunction _ _ _ _) = pure () staticValueTracker (VisitAssign r constInfo) = pure $ addBinding constInfo r staticValueTracker (VisitMkCon r tag args) = pure $ addBinding (MKStaticInfo (findRepackedSrcs (resolveTag tag) args) (Constructed (singleton (resolveTag tag) args))) r staticValueTracker (VisitMkClosure r name missing args) = pure $ MKStaticInfo (singleton r) (Closure (Just (name, missing)) args) staticValueTracker (VisitApply r impls (MKStaticInfo regs (Closure (Just (name, Z)) args)) arg) = pure (MKStaticInfo (singleton r) Unknown, staticImplTracker impls) staticValueTracker (VisitApply r impls (MKStaticInfo regs (Closure (Just (name, (S rem))) args)) arg) = pure (MKStaticInfo (singleton r) (Closure (Just (name, rem)) (args ++ [arg])), staticImplTracker impls) staticValueTracker (VisitApply r impls _ _) = pure (MKStaticInfo (singleton r) Unknown, staticImplTracker impls) staticValueTracker (VisitMkConstant r const) = pure $ MKStaticInfo (singleton r) (Const (singleton const)) staticValueTracker (VisitCall rs impls _ _) = pure (map (\r => MKStaticInfo (singleton r) Unknown) rs, staticImplTracker impls) staticValueTracker (VisitExtprim rs impls name args) = pure (result (externalEval name (length rs) (map toValueInfo args)), staticImplTracker impls) where result : Maybe (List EvalRes) -> List StaticInfo result Nothing = map (\r => MKStaticInfo (singleton r) Unknown) rs result (Just res) = if (length res) == (length rs) then zipWith (\r,res => addBinding (fromEvalRes res args) r) rs res else assert_total $ idris_crash "constant evaluation returned wrong number of results" staticValueTracker (VisitOp r impls fn args) = pure (result (evaluateConstantOp fn (map toValueInfo args)), staticImplTracker impls) where result : Maybe EvalRes -> StaticInfo result Nothing = MKStaticInfo (singleton r) Unknown result (Just res) = addBinding (fromEvalRes res args) r staticValueTracker (VisitProject r src@(MKStaticInfo _ (Constructed ctrs)) pos) = pure $ result (extractField ctrs pos) where result : StaticInfo -> StaticInfo result (MKStaticInfo _ Unknown) = MKStaticInfo (singleton r) (Field src (extractSingleTag ctrs) pos) result field = addBinding field r staticValueTracker (VisitProject r src pos) = pure $ MKStaticInfo (singleton r) (Field src Nothing pos) -- As we are not in a case we have no tag (otherwise case would have spezialized) staticValueTracker (VisitNull r) = pure $ MKStaticInfo (singleton r) Unknown staticValueTracker (VisitError r err) = pure $ MKStaticInfo (singleton r) (Error err) staticValueTracker (VisitReturn _ _) = pure () staticValueTracker (VisitCase _) = pure () staticValueTracker (VisitConBranch Nothing) = pure $ Nothing staticValueTracker (VisitConBranch (Just tag)) = pure $ case !getCaseBinding of Just (MKStaticInfo binds (Constructed ctrs)) => Just $ MKStaticInfo binds (Constructed (singleton tag (fromMaybe Nil (lookup tag ctrs)))) Just (MKStaticInfo binds _ ) => Just $ MKStaticInfo binds (Constructed (singleton tag Nil)) Nothing => Nothing staticValueTracker (VisitConstBranch Nothing) = pure $ Nothing staticValueTracker (VisitConstBranch (Just const)) = pure $ case !getCaseBinding of Just (MKStaticInfo binds _ ) => Just $ MKStaticInfo binds (Const (singleton const)) Nothing => Nothing staticValueTracker VisitBranchEnd = pure () staticValueTracker VisitCaseEnd = pure () staticValueTracker VisitEndFunction = pure () -- This is non generic/local folder -- we keep for now: as it is simpler and more efficient export localStaticTrackDef : (Name, CairoDef) -> List StaticInfo localStaticTrackDef def = collect $ snd $ runVisitConcatCairoDef (valueCollector idLens (dbgDef def) staticValueTracker extractReturn, initialTrackerState) def where dbgDef : (Name, CairoDef) -> CairoReg -> StaticInfo dbgDef (name, def) reg = trace "Register not bound in \{show name}: \{show reg}" (MKStaticInfo (singleton reg) Unknown) extractReturn : InstVisit StaticInfo -> Traversal (ScopedBindings StaticInfo) (List (List StaticInfo)) extractReturn (VisitReturn rets _) = pure [rets] extractReturn _ = pure Nil collect : (List (List StaticInfo)) -> (List StaticInfo) collect Nil = trace "Tracked function has no return statement" Nil collect (x::Nil) = x collect (x1::x2::xs) = collect ((zipWith mergeStaticInfo x1 x2)::xs) -- A version witch allows generified call handling -- public export record GlobalStaticTrackerState s where constructor MkGlobalStaticTrackerState bindingState : ScopedBindings StaticInfo globalState : s -- Lenses for leaner and more readable main definitions bindingStateLens : Lens (GlobalStaticTrackerState s) (ScopedBindings StaticInfo) bindingStateLens = MkLens bindingState (\ts,fn => {bindingState $= fn} ts) globalStateLens : Lens (GlobalStaticTrackerState s) s globalStateLens = MkLens globalState (\ts,fn => {globalState $= fn} ts) public export record CallData where constructor MKCallData function: Name implicits: SortedMap LinearImplicit (StaticInfo, CairoReg) arguments : List StaticInfo returns: List CairoReg public export interface CallTracker s where -- Binds values of function value context : (List CairoReg, SortedMap LinearImplicit CairoReg) -> s -> (List StaticInfo, SortedMap LinearImplicit StaticInfo) -- Binds returns of a function process_return : List StaticInfo -> SortedMap LinearImplicit StaticInfo -> s -> s -- Process nested function process : CallData -> s -> s -- Extract tracked values from processed function track : CallData -> s -> (List StaticInfo, SortedMap LinearImplicit StaticInfo) -- defaults (same as unmodified value Tracker) context (params, impls) _ = (map paramInit params, mapValueMap paramInit impls) where paramInit : CairoReg -> StaticInfo paramInit reg = MKStaticInfo (singleton reg) Unknown process_return _ _ s = s process _ s = s track (MKCallData _ impls _ rs) _ = (map (\r => MKStaticInfo (singleton r) Unknown) rs, staticImplTracker impls) export trackCall : CallTracker s => CallData -> Traversal (GlobalStaticTrackerState s) (List StaticInfo, SortedMap LinearImplicit StaticInfo) trackCall callData = update >>= (\_ => compute) where update : Traversal (GlobalStaticTrackerState s) () update = updateStateL globalStateLens (process callData) compute : Traversal (GlobalStaticTrackerState s) (List StaticInfo, SortedMap LinearImplicit StaticInfo) compute = map (track callData) (readStateL globalStateLens) export globalStaticTrackDef : CallTracker s => SortedMap Name CairoDef -> s -> (Name, CairoDef) -> (s, List StaticInfo) globalStaticTrackDef defs globalState def = collect $ runVisitConcatCairoDef (valueCollector bindingStateLens (dbgDef def) customizedStaticValueTracker extractReturn, initialState) def -- these just lift traversals defined on (ScopedBindings StaticInfo) to work with (GlobalStaticTrackerState s) by using a lense to point to the LocalStaticOptimState where liftedStaticValueTracker: (v:InstVisit StaticInfo) -> Traversal (GlobalStaticTrackerState s) (ValBindType v StaticInfo) liftedStaticValueTracker inst = composeState bindingStateLens (staticValueTracker inst) -- These use the CallTracker to customize the value Tracker -- we use explicit branching for 'customizedStaticValueTracker' because 'fallbackTraversal' has problems handling dependent type 'ValBindType v StaticInfo' customizedStaticValueTracker : (v:InstVisit StaticInfo) -> Traversal (GlobalStaticTrackerState s) (ValBindType v StaticInfo) customizedStaticValueTracker (VisitCall rs impls name args) = trackCall (MKCallData name impls args rs) customizedStaticValueTracker (VisitFunction _ params impls _) = map (context (params, impls)) (readStateL globalStateLens) customizedStaticValueTracker (VisitReturn res impls) = updateStateL globalStateLens (process_return res impls) customizedStaticValueTracker inst = liftedStaticValueTracker inst dbgDef : (Name, CairoDef) -> CairoReg -> StaticInfo dbgDef (name, def) reg = trace "Register not bound in \{show name}: \{show reg}" (MKStaticInfo (singleton reg) Unknown) extractReturn : InstVisit StaticInfo -> Traversal (GlobalStaticTrackerState s) (List (List StaticInfo)) extractReturn (VisitReturn rets _) = pure [rets] extractReturn _ = pure Nil initialState : GlobalStaticTrackerState s initialState = MkGlobalStaticTrackerState initialTrackerState globalState collect : (GlobalStaticTrackerState s, List (List StaticInfo)) -> (s, List StaticInfo) collect (s, Nil) = trace "Tracked function has no return statement" (s.globalState, Nil) collect (s, x::Nil) = (s.globalState, x) collect (s, x1::x2::xs) = collect (s, (zipWith mergeStaticInfo x1 x2)::xs)
------------------------------------------------------------------------ -- The Agda standard library -- -- A categorical view of Stream ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe --sized-types #-} module Codata.Stream.Categorical where open import Data.Product using (<_,_>) open import Codata.Stream open import Function open import Category.Functor open import Category.Applicative open import Category.Comonad functor : ∀ {ℓ i} → RawFunctor {ℓ} (λ A → Stream A i) functor = record { _<$>_ = λ f → map f } applicative : ∀ {ℓ i} → RawApplicative {ℓ} (λ A → Stream A i) applicative = record { pure = repeat ; _⊛_ = ap } comonad : ∀ {ℓ} → RawComonad {ℓ} (λ A → Stream A _) comonad = record { extract = head ; extend = unfold ∘′ < tail ,_> }
[STATEMENT] lemma S'_approx: "S' n x = ln (real n + x) - ln x + p n x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] proof (cases "n = 0") [PROOF STATE] proof (state) goal (2 subgoals): 1. n = 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x 2. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] case True [PROOF STATE] proof (state) this: n = 0 goal (2 subgoals): 1. n = 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x 2. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: n = 0 goal (1 subgoal): 1. S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] by (simp add: p_def S'_def) [PROOF STATE] proof (state) this: S' n x = ln (real n + x) - ln x + p n x goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] case False [PROOF STATE] proof (state) this: n \<noteq> 0 goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] hence "S' n x = (\<Sum>r<n. T (real r + x))" [PROOF STATE] proof (prove) using this: n \<noteq> 0 goal (1 subgoal): 1. S' n x = (\<Sum>r<n. T (real r + x)) [PROOF STEP] by (subst S'_telescope_trapezium) simp_all [PROOF STATE] proof (state) this: S' n x = (\<Sum>r<n. T (real r + x)) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] also [PROOF STATE] proof (state) this: S' n x = (\<Sum>r<n. T (real r + x)) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] have "\<dots> = (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>r<n. T (real r + x)) = (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) [PROOF STEP] by (simp add: D_def) [PROOF STATE] proof (state) this: (\<Sum>r<n. T (real r + x)) = (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] also [PROOF STATE] proof (state) this: (\<Sum>r<n. T (real r + x)) = (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] have "\<dots> = (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) + p n x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) = (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) + p n x [PROOF STEP] using False [PROOF STATE] proof (prove) using this: n \<noteq> 0 goal (1 subgoal): 1. (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) = (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) + p n x [PROOF STEP] by (simp add: sum.distrib add_ac p_def) [PROOF STATE] proof (state) this: (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) = (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) + p n x goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] also [PROOF STATE] proof (state) this: (\<Sum>r<n. ln (real r + x + 1) - ln (real r + x) + D (real r + x)) = (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) + p n x goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] have "(\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) = ln (real n + x) - ln x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) = ln (real n + x) - ln x [PROOF STEP] by (subst sum_lessThan_telescope) simp_all [PROOF STATE] proof (state) this: (\<Sum>r<n. ln (real (Suc r) + x) - ln (real r + x)) = ln (real n + x) - ln x goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: S' n x = ln (real n + x) - ln x + p n x goal (1 subgoal): 1. S' n x = ln (real n + x) - ln x + p n x [PROOF STEP] . [PROOF STATE] proof (state) this: S' n x = ln (real n + x) - ln x + p n x goal: No subgoals! [PROOF STEP] qed
(* * Copyright 2022, Proofcraft Pty Ltd * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) (* Proofs about untyped invocations. *) theory Untyped_AI imports ArchDetype_AI "Lib.MonadicRewrite" begin unbundle l4v_word_context (* because of Lib.MonadicRewrite *) context begin interpretation Arch . requalify_consts region_in_kernel_window arch_default_cap second_level_tables safe_ioport_insert requalify_facts set_cap_valid_arch_caps_simple set_cap_kernel_window_simple set_cap_ioports' safe_ioport_insert_triv end primrec valid_untyped_inv_wcap :: "Invocations_A.untyped_invocation \<Rightarrow> cap option \<Rightarrow> 'z::state_ext state \<Rightarrow> bool" where "valid_untyped_inv_wcap (Retype slot reset ptr_base ptr ty us slots dev) = (\<lambda>co s. \<exists>sz idx. (cte_wp_at (\<lambda>c. c = (cap.UntypedCap dev ptr_base sz idx) \<and> (co = None \<or> co = Some c)) slot s \<and> range_cover ptr sz (obj_bits_api ty us) (length slots) \<and> (idx \<le> unat (ptr - ptr_base) \<or> (reset \<and> ptr = ptr_base)) \<and> (ptr && ~~ mask sz) = ptr_base) \<and> (reset \<longrightarrow> descendants_of slot (cdt s) = {}) \<and> (ty = CapTableObject \<longrightarrow> us > 0) \<and> (ty = Untyped \<longrightarrow> us \<ge> untyped_min_bits) \<and> distinct (slot#slots) \<and> (\<forall>slot\<in>set slots. cte_wp_at ((=) cap.NullCap) slot s \<and> ex_cte_cap_wp_to is_cnode_cap slot s \<and> real_cte_at slot s) \<and> ty \<noteq> ArchObject ASIDPoolObj \<and> 0 < length slots \<and> (dev \<longrightarrow> ((ty = Untyped) \<or> is_frame_type ty)))" abbreviation "valid_untyped_inv ui \<equiv> valid_untyped_inv_wcap ui None" lemma valid_untyped_inv_wcap: "valid_untyped_inv ui = (\<lambda>s. \<exists>sz idx. valid_untyped_inv_wcap ui (Some (case ui of Retype slot reset ptr_base ptr ty us slots dev \<Rightarrow> UntypedCap dev (ptr && ~~ mask sz) sz idx)) s)" apply (cases ui) apply (clarsimp simp: fun_eq_iff cte_wp_at_caps_of_state intro!: arg_cong[where f=Ex] conj_cong[OF refl]) apply auto done locale Untyped_AI_of_bl_nat_to_cref = assumes of_bl_nat_to_cref: "\<lbrakk> x < 2 ^ bits; bits < word_bits \<rbrakk> \<Longrightarrow> (of_bl (nat_to_cref bits x) :: machine_word) = of_nat x" lemma cnode_cap_bits_range: "\<lbrakk> cte_wp_at P p s; invs s \<rbrakk> \<Longrightarrow> (\<exists>c. P c \<and> (is_cnode_cap c \<longrightarrow> (\<lambda>n. n > 0 \<and> n < (word_bits - cte_level_bits) \<and> is_aligned (obj_ref_of c) (n + cte_level_bits)) (bits_of c)))" apply (frule invs_valid_objs) apply (drule(1) cte_wp_at_valid_objs_valid_cap) apply clarsimp apply (rule exI, erule conjI) apply (clarsimp simp: is_cap_simps valid_cap_def bits_of_def) apply (erule (1) obj_at_valid_objsE) apply (case_tac ko, simp_all add: is_cap_table_def)[1] apply (clarsimp simp: valid_obj_def valid_cs_def well_formed_cnode_n_def valid_cs_size_def length_set_helper word_bits_def) apply (drule invs_psp_aligned) apply (unfold pspace_aligned_def) apply (frule domI, drule (1) bspec) apply (clarsimp simp: ex_with_length add.commute split: if_split_asm) done (* FIXME: move *) lemma cte_wp_at_wellformed_strengthen: "cte_at p s \<and> valid_objs s \<longrightarrow> cte_wp_at wellformed_cap p s" apply (clarsimp simp: cte_wp_at_caps_of_state) apply (frule (1) caps_of_state_valid_cap) apply (simp add: valid_cap_def2) done (* FIXME: move *) lemma get_cap_cte_wp_at_P: "\<lbrace>cte_wp_at P p\<rbrace> get_cap p \<lbrace>\<lambda>rv s. cte_wp_at (%c. c = rv) p s \<and> P rv\<rbrace>" apply (rule hoare_weaken_pre) apply (rule get_cap_wp) apply (clarsimp simp: cte_wp_at_caps_of_state) done lemma lookup_cap_ex: "\<lbrace>valid_objs\<rbrace> lookup_cap t x \<lbrace>\<lambda>rv s. valid_objs s \<and> (\<exists>p1 p2 m c'. rv = mask_cap m c' \<and> cte_wp_at (\<lambda>c. c = c') (p1, p2) s)\<rbrace>,-" apply (simp add: lookup_cap_def split_def) apply wp apply (rule_tac P1=wellformed_cap in hoare_strengthen_post[OF get_cap_cte_wp_at_P]) apply clarsimp apply (rule exI)+ apply (subst cap_mask_UNIV, simp) apply fastforce apply (wpsimp|strengthen cte_wp_at_wellformed_strengthen)+ done lemma is_cnode_mask: "is_cnode_cap (mask_cap m c) = is_cnode_cap c" by (case_tac c, simp_all add: mask_cap_def cap_rights_update_def is_cap_simps split:bool.splits) lemma Suc_length_not_empty: "length xs = length xs' \<Longrightarrow> Suc 0 \<le> length xs' = (xs \<noteq> [])" by (fastforce simp: le_simps) lemmas Suc_length_not_empty' = Suc_length_not_empty [OF refl] (* FIXME: hides Invariants_AI.caps_of_state_valid, FIXME: duplicate of Invariants_AI.caps_of_state_valid_cap *) lemma caps_of_state_valid: "\<lbrakk>invs s; caps_of_state s p = Some cap \<rbrakk> \<Longrightarrow> s \<turnstile> cap" apply (rule cte_wp_valid_cap) apply (simp add: cte_wp_at_caps_of_state) apply clarsimp done lemma mask_CNodeD: "mask_cap M' cap = cap.CNodeCap r bits g \<Longrightarrow> cap = cap.CNodeCap r bits g" by (cases cap, auto simp: mask_cap_def cap_rights_update_def split:bool.splits) (* FIXME: move *) lemma unat_2p_sub_1: "k < len_of TYPE('a) \<Longrightarrow> unat (2 ^ k - 1 :: 'a :: len word) = unat (2 ^ k :: 'a word) - 1" by (simp add: unat_minus_one) lemma compute_free_index_wp: "\<lbrace>\<top>\<rbrace> const_on_failure idx (doE y \<leftarrow> ensure_no_children slot; returnOk (0::nat) odE) \<lbrace>\<lambda>rv s. rv \<le> idx\<rbrace>" apply (rule hoare_pre) apply (wp const_on_failure_wp) apply clarsimp done lemma dui_inv[wp]: "\<lbrace>P\<rbrace> decode_untyped_invocation label args slot (cap.UntypedCap dev w n idx) cs \<lbrace>\<lambda>rv. P\<rbrace>" apply (simp add: decode_untyped_invocation_def whenE_def split_def data_to_obj_type_def unlessE_def split del: if_split cong: if_cong) apply (rule hoare_pre) apply (simp split del: if_split | wp (once) mapME_x_inv_wp hoare_drop_imps const_on_failure_wp | assumption | simp add: lookup_target_slot_def | wpcw | wp)+ done lemma map_ensure_empty_cte_wp_at: "\<lbrace>cte_wp_at P p\<rbrace> mapME_x ensure_empty xs \<lbrace>\<lambda>rv. cte_wp_at P p\<rbrace>,-" unfolding mapME_x_def sequenceE_x_def by (induct xs; wpsimp) lemma map_ensure_empty: "\<lbrace>P\<rbrace> mapME_x ensure_empty xs \<lbrace>\<lambda>rv s. (\<forall>x \<in> set xs. cte_wp_at ((=) cap.NullCap) x s) \<and> P s\<rbrace>,-" apply (induct xs) apply (simp add: mapME_x_def sequenceE_x_def) apply wp apply (simp add: mapME_x_def sequenceE_x_def) apply (unfold validE_R_def) apply (rule seqE[rotated]) apply (rule hoare_vcg_conj_liftE1) apply (fold sequenceE_x_def mapME_x_def)[1] apply (rule map_ensure_empty_cte_wp_at) apply assumption apply (simp add: ensure_empty_def whenE_def) apply (rule hoare_pre, wp get_cap_wp) apply clarsimp done lemma ensure_no_children_sp: "\<lbrace>P\<rbrace> ensure_no_children slot \<lbrace>\<lambda>rv s. descendants_of slot (cdt s) = {} \<and> P s\<rbrace>,-" apply (simp add: ensure_no_children_descendants) apply (clarsimp simp: valid_def validE_def validE_R_def split_def in_monad | rule conjI)+ done lemma data_to_obj_type_inv: "\<lbrace>P\<rbrace> data_to_obj_type v \<lbrace>\<lambda>rv. P\<rbrace>" apply (simp add: data_to_obj_type_def) apply (intro conjI impI; wpsimp) done lemma data_to_obj_type_inv2 [wp]: "\<lbrace>P\<rbrace> data_to_obj_type v \<lbrace>\<lambda>rv. P\<rbrace>,-" by (wp data_to_obj_type_inv) lemma get_cap_gets: "\<lbrace>valid_objs\<rbrace> get_cap ptr \<lbrace>\<lambda>rv s. \<exists>cref msk. cte_wp_at (\<lambda>cap. rv = mask_cap msk cap) cref s\<rbrace>" apply (wp get_cap_wp) apply (intro allI impI) apply (rule_tac x=ptr in exI) apply (rule_tac x=UNIV in exI) apply (simp add: cte_wp_at_caps_of_state) apply (frule (1) caps_of_state_valid_cap) apply (clarsimp simp add: valid_cap_def2) done lemma lookup_cap_gets: "\<lbrace>valid_objs\<rbrace> lookup_cap t c \<lbrace>\<lambda>rv s. \<exists>cref msk. cte_wp_at (\<lambda>cap. rv = mask_cap msk cap) cref s\<rbrace>,-" unfolding lookup_cap_def fun_app_def split_def apply (rule hoare_pre, wp get_cap_gets) apply simp done lemma dui_sp_helper: "(\<And>s. P s \<Longrightarrow> valid_objs s) \<Longrightarrow> \<lbrace>P\<rbrace> if val = 0 then returnOk root_cap else doE node_slot \<leftarrow> lookup_target_slot root_cap (to_bl (args ! 2)) (unat (args ! 3)); liftE $ get_cap node_slot odE \<lbrace>\<lambda>rv s. (rv = root_cap \<or> (\<exists>slot. cte_wp_at ((=) rv) slot s)) \<and> P s\<rbrace>, -" apply (simp add: split_def lookup_target_slot_def) apply (intro impI conjI) apply wpsimp apply (wp get_cap_wp) apply (rule hoare_post_imp_R [where Q'="\<lambda>rv. valid_objs and P"] ; wpsimp simp: cte_wp_at_caps_of_state) apply simp done locale Untyped_AI_arch = fixes state_ext_t :: "('state_ext::state_ext) itself" assumes data_to_obj_type_sp: "\<And>P x. \<lbrace>P\<rbrace> data_to_obj_type x \<lbrace>\<lambda>ts (s::'state_ext state). ts \<noteq> ArchObject ASIDPoolObj \<and> P s\<rbrace>, -" assumes dui_inv_wf[wp]: "\<And>w sz idx slot cs label args dev.\<lbrace>invs and cte_wp_at ((=) (cap.UntypedCap dev w sz idx)) slot and (\<lambda>(s::'state_ext state). \<forall>cap \<in> set cs. is_cnode_cap cap \<longrightarrow> (\<forall>r\<in>cte_refs cap (interrupt_irq_node s). ex_cte_cap_wp_to is_cnode_cap r s)) and (\<lambda>s. \<forall>x \<in> set cs. s \<turnstile> x)\<rbrace> decode_untyped_invocation label args slot (cap.UntypedCap dev w sz idx) cs \<lbrace>valid_untyped_inv\<rbrace>,-" assumes retype_ret_valid_caps_captable: "\<And>ptr sz dev us n s.\<lbrakk>pspace_no_overlap_range_cover ptr sz (s::'state_ext state) \<and> 0 < us \<and> range_cover ptr sz (obj_bits_api CapTableObject us) n \<and> ptr \<noteq> 0 \<rbrakk> \<Longrightarrow> \<forall>y\<in>{0..<n}. s \<lparr>kheap := foldr (\<lambda>p kh. kh(p \<mapsto> default_object CapTableObject dev us)) (map (\<lambda>p. ptr_add ptr (p * 2 ^ obj_bits_api CapTableObject us)) [0..<n]) (kheap s)\<rparr> \<turnstile> CNodeCap (ptr_add ptr (y * 2 ^ obj_bits_api CapTableObject us)) us []" assumes retype_ret_valid_caps_aobj: "\<And>ptr sz s x6 us n dev. \<lbrakk>pspace_no_overlap_range_cover ptr sz (s::'state_ext state) \<and> x6 \<noteq> ASIDPoolObj \<and> range_cover ptr sz (obj_bits_api (ArchObject x6) us) n \<and> ptr \<noteq> 0 \<comment> \<open>; tp = ArchObject x6\<close>\<rbrakk> \<Longrightarrow> \<forall>y\<in>{0..<n}. s \<lparr>kheap := foldr (\<lambda>p kh. kh(p \<mapsto> default_object (ArchObject x6) dev us)) (map (\<lambda>p. ptr_add ptr (p * 2 ^ obj_bits_api (ArchObject x6) us)) [0..<n]) (kheap s)\<rparr> \<turnstile> ArchObjectCap (arch_default_cap x6 (ptr_add ptr (y * 2 ^ obj_bits_api (ArchObject x6) us)) us dev)" assumes init_arch_objects_descendants_range[wp]: "\<And>x cref ty ptr n us y. \<lbrace>\<lambda>(s::'state_ext state). descendants_range x cref s \<rbrace> init_arch_objects ty ptr n us y \<lbrace>\<lambda>rv s. descendants_range x cref s\<rbrace>" assumes init_arch_objects_caps_overlap_reserved[wp]: "\<And>S ty ptr n us y. \<lbrace>\<lambda>(s::'state_ext state). caps_overlap_reserved S s\<rbrace> init_arch_objects ty ptr n us y \<lbrace>\<lambda>rv s. caps_overlap_reserved S s\<rbrace>" assumes delete_objects_rewrite: "\<And>sz ptr. \<lbrakk> word_size_bits \<le> sz; sz\<le> word_bits; ptr && ~~ mask sz = ptr \<rbrakk> \<Longrightarrow> delete_objects ptr sz = do y \<leftarrow> modify (clear_um {ptr + of_nat k |k. k < 2 ^ sz}); modify (detype {ptr && ~~ mask sz..ptr + 2 ^ sz - 1} :: 'state_ext state \<Rightarrow> 'state_ext state) od" assumes obj_is_device_vui_eq: "valid_untyped_inv ui (s :: 'state_ext state) \<Longrightarrow> case ui of Retype slot reset ptr_base ptr tp us slots dev \<Rightarrow> obj_is_device tp dev = dev" lemmas is_aligned_triv2 = Aligned.is_aligned_triv lemma strengthen_imp_ex2: "(P \<longrightarrow> Q x y) \<Longrightarrow> (P \<longrightarrow> (\<exists>x y. Q x y))" by auto lemma p2_minus: "sz < len_of TYPE('a) \<Longrightarrow> of_nat (2 ^ len_of TYPE('a) - 2 ^ sz) = ((mask (len_of TYPE('a)) && ~~ mask sz):: 'a :: len word)" apply (rule word_unat.Rep_inverse') apply (simp add: mask_out_sub_mask) apply (simp add: unat_sub word_and_le2 mask_and_mask) apply (simp add: min_def mask_def word_size unat_minus) done lemma range_cover_bound': fixes ptr :: "'a :: len word" assumes cover: "range_cover ptr sz sbit n" assumes le : "x < n" shows "unat (ptr + of_nat x * 2 ^ sbit) + 2 ^ sbit \<le> 2 ^ len_of TYPE('a)" proof - have l: "unat (ptr && ~~ mask sz) + 2^ sz \<le> 2^ len_of TYPE('a)" using cover apply - apply (rule le_diff_conv2[THEN iffD1]) apply (simp add: range_cover_def) apply (rule unat_le_helper) apply (subst p2_minus) apply (erule range_cover.sz) apply (rule neg_mask_mono_le) apply (simp add: mask_def) done have n: "unat ((ptr && mask sz) + of_nat x * 2 ^ sbit) + 2^sbit \<le> 2 ^ sz" apply (rule le_trans[OF _ range_cover.range_cover_compare_bound[OF cover]]) apply (rule le_trans[where j = "(x+1) * 2^sbit + unat (ptr && mask sz)"]) apply clarsimp apply (rule le_trans[OF unat_plus_gt]) using le apply (simp add: range_cover.unat_of_nat_shift[OF cover]) apply simp using le apply (case_tac n,simp+) done show ?thesis using cover le apply - apply (frule iffD1[OF meta_eq_to_obj_eq[OF range_cover_def]]) apply (clarsimp) apply (frule range_cover_le[where n=x]) apply simp apply (subst word_plus_and_or_coroll2[symmetric,where w = "mask sz"]) apply (subst add.commute) apply (subst add.assoc) apply (subst unat_plus_simple[THEN iffD1]) apply (rule is_aligned_no_wrap') apply (rule is_aligned_neg_mask[OF le_refl]) apply (simp add: range_cover_def) apply (simp add: word_less_nat_alt) apply (rule le_less_trans[OF unat_plus_gt]) apply (erule range_cover.range_cover_compare[OF cover]) apply (subst add.assoc) apply (rule le_trans[OF _ l]) apply simp apply (simp add: n) done qed lemma range_cover_stuff: notes unat_power_lower_machine = unat_power_lower[where 'a=machine_word_len] notes unat_of_nat_machine = unat_of_nat_eq[where 'a=machine_word_len] notes is_aligned_neg_mask_eq[simp del] notes is_aligned_neg_mask_weaken[simp del] shows "\<lbrakk>0 < n;n \<le> unat ((2::machine_word) ^ sz - of_nat rv >> bits); rv \<le> 2^ sz; sz < word_bits; is_aligned w sz\<rbrakk> \<Longrightarrow> rv \<le> unat (alignUp (w + of_nat rv) bits - w) \<and> (alignUp (w + of_nat rv) bits) && ~~ mask sz = w \<and> range_cover (alignUp (w + ((of_nat rv)::machine_word)) bits) sz bits n" apply (clarsimp simp: range_cover_def) proof (intro conjI) assume not_0 : "0<n" assume bound : "n \<le> unat ((2::machine_word) ^ sz - of_nat rv >> bits)" "rv\<le> 2^sz" "sz < word_bits" assume al: "is_aligned w sz" have space: "(2::machine_word) ^ sz - of_nat rv \<le> 2^ sz" apply (rule word_sub_le[OF word_of_nat_le]) apply (clarsimp simp: bound unat_power_lower_machine) done show cmp: "bits \<le> sz" using not_0 bound apply - apply (rule ccontr) apply (clarsimp simp: not_le) apply (drule le_trans) apply (rule word_le_nat_alt[THEN iffD1]) apply (rule le_shiftr[OF space]) apply (subgoal_tac "(2::machine_word)^sz >> bits = 0") apply simp apply (rule and_mask_eq_iff_shiftr_0[THEN iffD1]) apply (simp add: and_mask_eq_iff_le_mask) apply (case_tac "word_bits \<le> bits") apply (simp add: word_bits_def mask_def power_overflow) apply (subst le_mask_iff_lt_2n[THEN iffD1]) apply (simp add: word_bits_def) apply (simp add: word_less_nat_alt[THEN iffD2] unat_power_lower_machine) done have shiftr_t2n[simp]:"(2::machine_word)^sz >> bits = 2^ (sz - bits)" using bound cmp apply (case_tac "sz = 0",simp) apply (subgoal_tac "(1::machine_word) << sz >> bits = 2^ (sz -bits)") apply simp apply (subst shiftl_shiftr1) apply (simp_all add: word_size) apply (word_eqI_solve simp: word_bits_conv) done have cmp2[simp]: "alignUp (of_nat rv) bits < (2 :: machine_word) ^ sz" using bound cmp not_0 apply - apply (case_tac "rv = 0") apply simp apply (clarsimp simp: alignUp_def2) apply (subst mask_eq_x_eq_0[THEN iffD1]) apply (simp add: and_mask_eq_iff_le_mask mask_def) apply (simp add: p2_gt_0[where 'a=machine_word_len, folded word_bits_def]) apply (simp add: alignUp_def3) apply (subgoal_tac "1 \<le> unat (2 ^ sz - of_nat rv >> bits)") prefer 2 apply (erule le_trans[rotated]) apply clarsimp apply (thin_tac "n \<le> M" for M) apply (simp add: shiftr_div_2n') apply (simp add: td_gal[symmetric]) apply (subst (asm) unat_sub) apply (simp add: word_of_nat_le unat_power_lower_machine) apply (simp add: le_diff_conv2 word_of_nat_le unat_le_helper word_less_nat_alt) apply (rule le_less_trans[OF unat_plus_gt]) apply (rule less_le_trans[where y = "2^bits + unat (of_nat rv)"]) apply simp apply (rule le_less_trans[OF _ measure_unat]) apply (rule word_le_nat_alt[THEN iffD1]) apply (rule word_and_le2) apply (erule of_nat_neq_0) apply (subst word_bits_def[symmetric]) apply (erule le_less_trans) apply simp apply simp done show "n + unat (alignUp (w + ((of_nat rv)::machine_word)) bits && mask sz >> bits) \<le> 2 ^ (sz - bits)" using not_0 bound cmp apply - apply (erule le_trans[OF add_le_mono]) apply (rule le_refl) apply (clarsimp simp: power_sub field_simps td_gal[symmetric]) apply (subst (2) mult.commute) apply (subst unat_shiftl_absorb) apply (rule order_trans[OF le_shiftr]) apply (rule word_and_le1) apply (simp add: shiftr_mask2 word_bits_def) apply (simp add: mask_def) apply (rule word_sub_1_le) apply (simp add: word_bits_def)+ apply (simp add: shiftl_t2n[symmetric] field_simps shiftr_shiftl1) apply (subst is_aligned_neg_mask_eq) apply (rule is_aligned_andI1,simp) apply (subst mult.commute) apply (subst unat_shiftl_absorb[where p = "sz - bits"]) apply (rule order_trans[OF le_shiftr]) apply (rule space) apply (simp add: word_bits_def power_minus_is_div)+ apply (simp add: shiftl_t2n[symmetric] field_simps shiftr_shiftl1) apply (subst is_aligned_diff_neg_mask[OF is_aligned_weaken]) apply (rule is_aligned_triv) apply (simp add: word_bits_def)+ apply (subst unat_sub) apply (rule order_trans[OF word_and_le2]) apply (simp add: less_imp_le) apply (subst diff_add_assoc[symmetric]) apply (rule unat_le_helper) apply (rule order_trans[OF word_and_le2]) apply (simp add: less_imp_le[OF cmp2]) apply (clarsimp simp: field_simps word_bits_def is_aligned_neg_mask_eq) apply (simp add: le_diff_conv word_le_nat_alt[symmetric] word_and_le2) apply (simp add: alignUp_plus[OF is_aligned_weaken[OF al]] is_aligned_add_helper[THEN conjunct1, OF al cmp2]) done show "rv \<le> unat (alignUp (w + of_nat rv) bits - w)" using bound not_0 cmp al apply - apply (clarsimp simp: alignUp_plus[OF is_aligned_weaken]) apply (case_tac "rv = 0") apply simp apply (rule le_trans[OF _ word_le_nat_alt[THEN iffD1,OF alignUp_ge]]) apply (subst unat_of_nat_machine) apply (erule le_less_trans) apply (rule power_strict_increasing) apply (simp_all add: word_bits_def)[4] apply (rule alignUp_is_aligned_nz[where x = "2^sz"]) apply (rule is_aligned_weaken[OF is_aligned_triv2]) apply (simp_all add: word_bits_def)[2] apply (subst word_of_nat_le) apply (subst unat_power_lower_machine) apply ((simp add: word_bits_def)+)[3] apply simp apply (erule of_nat_neq_0) apply (erule le_less_trans) apply (rule power_strict_increasing) apply (simp add: word_bits_def)+ done show "alignUp (w + of_nat rv) bits && ~~ mask sz = w" using bound not_0 cmp al apply (clarsimp simp: alignUp_plus[OF is_aligned_weaken] mask_out_add_aligned[symmetric]) apply (clarsimp simp: and_not_mask) apply (subgoal_tac "alignUp ((of_nat rv)::machine_word) bits >> sz = 0") apply simp apply (simp add: le_mask_iff[symmetric] mask_def) done qed (simp add: word_bits_def) context Arch begin (*FIXME: generify proof that uses this *) lemmas range_cover_stuff_arch = range_cover_stuff[unfolded word_bits_def, simplified] end lemma cte_wp_at_range_cover: "\<lbrakk>bits < word_bits; rv\<le> 2^ sz; invs s; cte_wp_at ((=) (cap.UntypedCap dev w sz idx)) p s; 0 < n; n \<le> unat ((2::machine_word) ^ sz - of_nat rv >> bits)\<rbrakk> \<Longrightarrow> range_cover (alignUp (w + of_nat rv) bits) sz bits n" apply (clarsimp simp: cte_wp_at_caps_of_state) apply (frule(1) caps_of_state_valid) apply (clarsimp simp: valid_cap_def valid_untyped_def cap_aligned_def) apply (drule range_cover_stuff) apply simp_all apply clarsimp done lemma le_mask_le_2p: "\<lbrakk>idx \<le> unat ((ptr::machine_word) && mask sz);sz < word_bits\<rbrakk> \<Longrightarrow> idx < 2^ sz" apply (erule le_less_trans) apply (rule unat_less_helper) apply simp apply (rule le_less_trans) apply (rule word_and_le1) apply (simp add: mask_def) done lemma diff_neg_mask[simp]: "ptr - (ptr && ~~ mask sz) = (ptr && mask sz)" apply (subst word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr]) apply simp done lemma cte_wp_at_caps_descendants_range_inI: "\<lbrakk> invs s;cte_wp_at (\<lambda>c. c = cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz);sz < word_bits \<rbrakk> \<Longrightarrow> descendants_range_in {ptr .. (ptr && ~~mask sz) + 2^sz - 1} cref s" apply (frule invs_mdb) apply (frule(1) le_mask_le_2p) apply (clarsimp simp: descendants_range_in_def cte_wp_at_caps_of_state ) apply (frule(1) descendants_of_cte_at) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (drule untyped_cap_descendants_range[rotated]) apply simp+ apply (simp add: invs_valid_pspace) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (erule disjoint_subset2[rotated]) apply clarsimp apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) done lemma nasty_range: fixes word :: "'a :: len word" assumes szb: "bz < len_of TYPE('a)" and al: "is_aligned word bz" and br: "ptr \<in> {word.. word+2^bz - 1}" and sr: "sz \<le> bz" shows "\<exists>idx::'a :: len word. idx < (2::'a :: len word)^(bz - sz) \<and> ptr \<in> {word + idx * 2^ sz .. word + (idx * 2^ sz) + (2^ sz - 1)}" proof - have offset: "ptr - word < 2^ bz" using br szb apply (subst word_less_sub_le[symmetric],simp) apply (rule word_diff_ls') apply (clarsimp simp: field_simps)+ done have t2n_sym: "\<And>z. (2::'a :: len word)^z = (1:: 'a :: len word)<<z" by (simp add: shiftl_t2n) have le_helper: "\<And>b c. \<lbrakk>\<And>a. (a::'a :: len word)< b \<Longrightarrow> a< c\<rbrakk> \<Longrightarrow> b\<le>c" apply (rule ccontr) apply (clarsimp simp: not_le dest!: meta_spec) by auto have ptr_word: "(ptr - word >> sz) * 2 ^ sz = (ptr &&~~ mask sz) - word" apply (subst mult.commute) apply (clarsimp simp: shiftl_t2n[symmetric] shiftr_shiftl1 word_and_le2) apply (simp only: diff_conv_add_uminus) apply (subst add.commute[where a = "ptr && ~~ mask sz"]) apply (subst mask_out_add_aligned) defer apply (simp add: field_simps) apply (rule is_aligned_minus) apply (rule is_aligned_weaken[OF al sr]) done show ?thesis using szb sr br apply clarsimp apply (rule_tac x = "(ptr - word) >> sz" in exI) apply (intro conjI) apply (rule less_le_trans) apply (rule shiftr_less_t2n[where m = "bz - sz"]) apply (simp add: offset) apply simp apply (rule le_plus) apply (subst mult.commute) apply (simp add: shiftl_t2n[symmetric] shiftr_shiftl1 word_and_le2) apply clarsimp apply (simp add: ptr_word p_assoc_help) apply (rule order_trans[OF _ word_plus_mono_right]) apply (rule order_eq_refl) apply (subst word_plus_and_or_coroll2[where x = "ptr",symmetric]) apply (subst add.commute) apply simp apply (rule order_trans[OF word_and_le1]) apply (clarsimp simp: mask_def) apply (rule is_aligned_no_overflow'[OF is_aligned_neg_mask]) apply simp+ done qed lemma check_children_wp: "\<lbrace>\<lambda>s. if descendants_of slot (cdt s) = {} then Q True s else Q False s \<rbrace> const_on_failure False (doE y \<leftarrow> ensure_no_children slot; returnOk True odE) \<lbrace>Q\<rbrace>" including no_pre apply (clarsimp simp: const_on_failure_def ensure_no_children_descendants bindE_assoc) apply wp apply (clarsimp simp: valid_def validE_def if_splits) apply (intro conjI impI) apply (clarsimp simp: in_monad free_index_of_def)+ done lemma alignUp_eq: "\<lbrakk>is_aligned (w :: 'a :: len word) sz; a \<le> 2^ sz; us \<le> sz; sz < len_of TYPE('a); alignUp (w + a) us = w\<rbrakk> \<Longrightarrow> a = 0" apply (clarsimp simp: alignUp_plus[OF is_aligned_weaken]) apply (rule ccontr) apply (drule alignUp_is_aligned_nz[rotated -1,where x = "2^ sz"]) apply (rule is_aligned_weaken[OF is_aligned_triv2]) apply simp+ done lemma map_ensure_empty_wp: "\<lbrace> \<lambda>s. (\<forall>x\<in>set xs. cte_wp_at ((=) NullCap) x s) \<longrightarrow> P () s \<rbrace> mapME_x ensure_empty xs \<lbrace>P\<rbrace>, -" by (rule hoare_post_imp_R, rule map_ensure_empty, simp) lemma cases_imp_eq: "((P \<longrightarrow> Q \<longrightarrow> R) \<and> (\<not> P \<longrightarrow> Q \<longrightarrow> S)) = (Q \<longrightarrow> (P \<longrightarrow> R) \<and> (\<not> P \<longrightarrow> S))" by blast lemma inj_bits: "\<lbrakk> of_nat x * 2^bits = of_nat y * (2^bits :: machine_word); x < bnd; y < bnd; bits \<le> word_bits; bnd \<le> 2 ^ (word_bits - bits) \<rbrakk> \<Longrightarrow> of_nat x = (of_nat y :: machine_word)" apply (cases "bits = 0", simp) apply (fold shiftl_t2n [where n=bits, simplified, simplified mult.commute]) apply (simp only: word_bl.Rep_inject[symmetric] bl_shiftl) apply (drule(1) order_less_le_trans)+ apply (drule of_nat_mono_maybe[rotated, where 'a=machine_word_len]) apply (rule power_strict_increasing) apply (simp add: word_bits_def) apply simp apply (drule of_nat_mono_maybe[rotated, where 'a=machine_word_len]) apply (rule power_strict_increasing) apply (simp add: word_bits_def) apply simp apply (simp only: word_unat_power[symmetric]) apply (erule ssubst [OF less_is_drop_replicate])+ apply (simp add: word_bits_def word_size) done lemma of_nat_shiftR: "a < 2 ^ word_bits \<Longrightarrow> unat (of_nat (shiftR a b)::machine_word) = unat ((of_nat a :: machine_word) >> b)" apply (subst shiftr_div_2n') apply (clarsimp simp: shiftR_nat) apply (subst unat_of_nat_eq[where 'a=machine_word_len]) apply (simp only: word_bits_def) apply (erule le_less_trans[OF div_le_dividend]) apply (subst unat_of_nat_eq[where 'a=machine_word_len]) apply (simp only: word_bits_def) apply simp done lemma valid_untypedD: "\<lbrakk> s \<turnstile> cap.UntypedCap dev ptr bits idx; kheap s p = Some ko; pspace_aligned s\<rbrakk> \<Longrightarrow> obj_range p ko \<inter> cap_range (cap.UntypedCap dev ptr bits idx) \<noteq> {} \<longrightarrow> obj_range p ko \<subseteq> cap_range (cap.UntypedCap dev ptr bits idx) \<and> obj_range p ko \<inter> usable_untyped_range (cap.UntypedCap dev ptr bits idx) = {}" by (clarsimp simp: valid_untyped_def valid_cap_def cap_range_def obj_range_def) (meson order_trans) lemma pspace_no_overlap_detype': "\<lbrakk> s \<turnstile> cap.UntypedCap dev ptr bits idx; pspace_aligned s; valid_objs s \<rbrakk> \<Longrightarrow> pspace_no_overlap {ptr .. ptr + 2 ^ bits - 1} (detype {ptr .. ptr + 2 ^ bits - 1} s)" apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff simp: obj_range_def add_diff_eq[symmetric] pspace_no_overlap_def) apply (frule(2) valid_untypedD) apply (rule ccontr) apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff is_aligned_neg_mask_eq simp: valid_cap_def cap_aligned_def obj_range_def cap_range_def is_aligned_neg_mask_eq p_assoc_help) apply (drule_tac c= x in set_mp) apply simp+ done lemma pspace_no_overlap_detype: "\<lbrakk> s \<turnstile> cap.UntypedCap dev ptr bits idx; pspace_aligned s; valid_objs s \<rbrakk> \<Longrightarrow> pspace_no_overlap_range_cover ptr bits (detype {ptr .. ptr + 2 ^ bits - 1} s)" apply (drule(2) pspace_no_overlap_detype'[rotated]) apply (drule valid_cap_aligned) apply (clarsimp simp: cap_aligned_def field_simps) done lemma zip_take_length[simp]: "zip (take (length ys) xs) ys = zip xs ys" apply (induct xs arbitrary: ys) apply simp apply (case_tac ys) apply simp apply simp done (* FIXME: move *) lemma int_not_empty_subsetD: "\<lbrakk> A\<inter> B = {}; A\<noteq> {};B\<noteq> {}\<rbrakk> \<Longrightarrow> \<not> A \<subset> B \<and> \<not> B\<subset> A \<and> \<not> A = B" by auto (* FIXME: move *) lemma subset_not_psubset: " A \<subseteq> B \<Longrightarrow> \<not> B \<subset> A" by clarsimp lemma mdb_Null_descendants: "\<lbrakk> cte_wp_at ((=) cap.NullCap) p s; valid_mdb s \<rbrakk> \<Longrightarrow> descendants_of p (cdt s) = {}" apply (clarsimp simp add: valid_mdb_def cte_wp_at_caps_of_state swp_def) apply (erule(1) mdb_cte_at_Null_descendants) done lemma mdb_Null_None: "\<lbrakk> cte_wp_at ((=) cap.NullCap) p s; valid_mdb s \<rbrakk> \<Longrightarrow> cdt s p = None" apply (clarsimp simp add: valid_mdb_def cte_wp_at_caps_of_state swp_def) apply (erule(1) mdb_cte_at_Null_None) done lemma not_waiting_reply_slot_no_descendants: "\<lbrakk> st_tcb_at (Not \<circ> awaiting_reply) t s; valid_reply_caps s; valid_objs s; valid_mdb s \<rbrakk> \<Longrightarrow> descendants_of (t, tcb_cnode_index 2) (cdt s) = {}" apply (rule ccontr, erule nonemptyE) apply (clarsimp simp: valid_mdb_def reply_mdb_def reply_masters_mdb_def) apply (frule_tac ref="tcb_cnode_index 2" in tcb_at_cte_at[OF st_tcb_at_tcb_at]) apply (simp add: domI) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (frule(1) tcb_cap_valid_caps_of_stateD) apply (clarsimp simp: tcb_cap_valid_def st_tcb_at_tcb_at) apply (clarsimp simp: st_tcb_def2) apply (erule disjE) apply (clarsimp simp: cte_wp_at_caps_of_state is_cap_simps) apply (elim allE impE) apply fastforce apply (clarsimp) apply (drule(1) bspec) apply (subgoal_tac "has_reply_cap t s") apply (erule notE[rotated], strengthen reply_cap_doesnt_exist_strg) apply (simp add: st_tcb_def2) apply (erule exE) apply (drule caps_of_state_cteD)+ apply (fastforce simp add:has_reply_cap_def is_reply_cap_to_def elim:cte_wp_at_lift intro: caps_of_state_cteD) apply clarsimp apply (frule mdb_Null_descendants[OF caps_of_state_cteD]) apply (simp add: valid_mdb_def reply_mdb_def reply_masters_mdb_def) apply simp done crunch ups[wp]: set_cdt "\<lambda>s. P (ups_of_heap (kheap s))" crunch cns[wp]: set_cdt "\<lambda>s. P (cns_of_heap (kheap s))" (* FIXME: move *) lemma list_all2_zip_split: "\<lbrakk> list_all2 P as cs; list_all2 Q bs ds \<rbrakk> \<Longrightarrow> list_all2 (\<lambda>x y. P (fst x) (fst y) \<and> Q (snd x) (snd y)) (zip as bs) (zip cs ds)" apply (induct as arbitrary: bs cs ds) apply simp apply (case_tac cs; simp) apply (case_tac bs; simp) apply (case_tac ds; simp) done lemma set_cdt_tcb_valid[wp]: "\<lbrace>tcb_cap_valid cap ptr\<rbrace> set_cdt m \<lbrace>\<lambda>rv. tcb_cap_valid cap ptr\<rbrace>" by (simp add: set_cdt_def, wp, simp add: tcb_cap_valid_def) lemma tcb_cap_valid_rvk[simp]: "tcb_cap_valid cap ptr (is_original_cap_update f s) = tcb_cap_valid cap ptr s" by (simp add: tcb_cap_valid_def) lemma tcb_cap_valid_more_update[simp]: "tcb_cap_valid cap ptr (trans_state f s) = tcb_cap_valid cap ptr s" by (simp add: tcb_cap_valid_def) lemma create_cap_wps[wp]: "\<lbrace>pspace_aligned\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. pspace_aligned\<rbrace>" "\<lbrace>pspace_distinct\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. pspace_distinct\<rbrace>" "\<lbrace>cte_wp_at P p' and K (p' \<noteq> cref)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. cte_wp_at P p'\<rbrace>" "\<lbrace>valid_objs and valid_cap (default_cap tp oref sz dev) and real_cte_at cref\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_objs\<rbrace>" "\<lbrace>valid_cap cap\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_cap cap\<rbrace>" apply (safe intro!: hoare_gen_asm) apply (simp_all add: create_cap_def) apply (wp set_cap_cte_wp_at' set_cdt_cte_wp_at set_cap_valid_objs set_cdt_valid_objs set_cdt_valid_cap set_cap_valid_cap | simp split del: if_split add: real_cte_tcb_valid)+ done lemma default_non_Null[simp]: "cap.NullCap \<noteq> default_cap tp oref sz dev" by (cases tp, simp_all) locale vo_abs = vmdb_abs + assumes valid_objs: "valid_objs s" begin lemma cs_valid_cap: "cs p = Some c \<Longrightarrow> s \<turnstile> c" using valid_objs apply (simp add: cs_def) apply (drule cte_wp_at_valid_objs_valid_cap [rotated, where P="(=) c"]) apply (simp add: cte_wp_at_caps_of_state) apply clarsimp done lemma cs_cap_aligned: "cs p = Some c \<Longrightarrow> cap_aligned c" apply (drule cs_valid_cap) apply (simp add: valid_cap_def) done end lemma untyped_ranges_aligned_disjoing_or_subset: "\<lbrakk>cap_aligned c1;cap_aligned c2\<rbrakk> \<Longrightarrow> untyped_range c1 \<subseteq> untyped_range c2 \<or> untyped_range c2 \<subseteq> untyped_range c1 \<or> untyped_range c1 \<inter> untyped_range c2 = {}" apply (simp add: cap_aligned_def) apply (elim conjE) apply (drule(1) aligned_ranges_subset_or_disjoint) apply (case_tac c1) apply simp_all apply (case_tac c2) apply simp_all done locale mdb_create_cap = vo_abs + mdb_insert_abs + fixes cap assumes c_dest: "cs dest = Some cap.NullCap" assumes c_src: "cs src = Some cap" assumes ut: "is_untyped_cap cap" begin lemmas no_dest_mdb [simp] = null_no_mdb [OF c_dest] lemma d_rangeD: "\<lbrakk>descendants_range ac p s; m \<Turnstile> p \<rightarrow> p'\<rbrakk> \<Longrightarrow> \<exists>c. cs p' = Some c \<and> untyped_range c \<inter> untyped_range ac = {}" apply (drule(1) descendants_rangeD[where s= s,folded m_def cs_def]) apply clarsimp apply (drule disjoint_subset2[OF untyped_range_in_cap_range]) apply (drule disjoint_subset[OF untyped_range_in_cap_range]) apply simp done lemma subseteq_imp_not_subset: "A \<subseteq> B \<Longrightarrow> \<not> B \<subset> A" by fastforce lemma cap_bits_default_untyped_cap: "is_untyped_cap (default_cap tp oref sz dev) \<Longrightarrow> cap_bits (default_cap tp oref sz dev) = sz" by (case_tac tp,simp_all) lemma untyped_inc': assumes inc: "untyped_inc m cs" assumes d: "descendants_range (default_cap tp oref sz dev) src s" assumes r: "untyped_range (default_cap tp oref sz dev) \<subseteq> untyped_range cap" assumes al: "cap_aligned (default_cap tp oref sz dev)" assumes noint: "untyped_range (default_cap tp oref sz dev) \<inter> usable_untyped_range cap = {}" shows "untyped_inc (m(dest \<mapsto> src)) (cs(dest \<mapsto> default_cap tp oref sz dev))" using inc r c_src al ut noint unfolding untyped_inc_def descendants_of_def apply (intro allI impI) apply (rule conjI) apply (simp add: parency del: split_paired_All split: if_split_asm) apply (rule untyped_ranges_aligned_disjoing_or_subset[OF _ cs_cap_aligned]) apply simp apply simp apply (rule untyped_ranges_aligned_disjoing_or_subset[OF cs_cap_aligned _ ]) apply simp apply simp apply (case_tac "p' = src") apply (simp add: parency del: split_paired_All split: if_split_asm) apply (erule_tac x=src in allE) apply (erule_tac x=p in allE) apply (simp add: c_dest) apply (simp add: subseteq_imp_not_subset) apply (intro impI) apply (drule(1) usable_range_subseteq[OF cs_cap_aligned]) apply simp apply (drule Int_absorb1) apply simp apply (simp add: c_dest) apply (erule_tac x = src in allE) apply (erule_tac x = p in allE) apply simp apply (elim conjE) apply (rule conjI) apply (intro impI) apply (elim disjE) apply (clarsimp+)[3] apply (erule subset_splitE) apply clarsimp apply (intro conjI impI) apply simp+ apply (intro conjI impI,clarsimp+)[1] apply (intro conjI impI,clarsimp+)[1] apply (simp add: parency del: split_paired_All split: if_split_asm) apply (erule_tac x=src in allE) apply (erule_tac x=p' in allE) apply simp apply (elim conjE) apply (erule subset_splitE) apply (intro conjI) apply (intro impI) apply blast apply blast apply (intro conjI) apply (intro impI) apply (drule trancl_trans) apply fastforce apply simp apply (intro impI) apply (cut_tac p' = p' in d_rangeD[OF d]) apply simp+ apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned]) apply (drule(1) untyped_range_non_empty) apply (rule int_not_empty_subsetD) apply (simp add:Int_ac) apply simp apply simp apply simp apply (intro conjI) apply (intro impI) apply (erule disjE) apply (drule trancl_trans) apply fastforce apply simp apply (simp add: subseteq_imp_not_subset) apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned]) apply (drule(1) untyped_range_non_empty) apply (elim disjE) apply (cut_tac p' = p' in d_rangeD[OF d]) apply clarsimp apply simp apply fastforce apply clarsimp apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned]) apply (drule(1) untyped_range_non_empty) apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply blast apply (erule_tac x = src in allE) apply (erule_tac x = p in allE) apply simp apply (elim conjE) apply (erule subset_splitE) apply simp apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply blast apply (intro conjI) apply (intro impI) apply (drule trancl_trans) apply fastforce apply simp apply clarsimp apply simp apply (elim conjE) apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (thin_tac "P \<inter> Q = {}" for P Q)+ apply (intro impI) apply (drule d_rangeD[OF d]) apply simp apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned])+ apply (drule(1) untyped_range_non_empty)+ apply (intro conjI) apply (rule notI) apply (drule(1) disjoint_subset2[OF psubset_imp_subset,rotated]) apply simp apply (rule notI) apply (drule(1) disjoint_subset[OF psubset_imp_subset,rotated]) apply simp apply blast apply simp apply (intro conjI) apply (intro impI) apply (erule disjE) apply (drule trancl_trans) apply fastforce apply simp apply fastforce apply (clarsimp simp: subseteq_imp_not_subset) apply (drule(1) usable_range_subseteq[OF cs_cap_aligned] ) apply blast apply (rule impI) apply simp apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned])+ apply (drule(1) untyped_range_non_empty)+ apply (elim conjE | simp)+ apply (drule d_rangeD[OF d]) apply simp apply (intro conjI) apply (rule notI) apply (drule(1) disjoint_subset2[OF psubset_imp_subset,rotated]) apply simp apply (rule notI) apply (drule(1) disjoint_subset[OF psubset_imp_subset,rotated]) apply simp apply blast apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (drule disjoint_subset2) apply (simp (no_asm) add:Int_ac) apply (drule(1) untyped_range_non_empty[OF _ cs_cap_aligned])+ apply (drule(1) untyped_range_non_empty)+ apply blast apply (erule_tac x= src in allE) apply (erule_tac x = p' in allE) apply simp apply (intro impI conjI) apply simp+ done end lemma default_cap_replies[simp]: "\<not> is_reply_cap (default_cap otype oref sz dev)" "\<not> is_master_reply_cap (default_cap otype oref sz dev)" by (cases otype, simp_all add: is_cap_simps)+ lemma inter_non_emptyD: "\<lbrakk>A \<subseteq> B; A \<inter> C \<noteq> {}\<rbrakk> \<Longrightarrow> B \<inter> C \<noteq> {}" by blast lemma cap_class_default_cap: "cap_class (default_cap tp oref sz dev) = PhysicalClass" apply (case_tac tp) apply (simp_all add: default_cap_def physical_arch_cap_has_ref aobj_ref_default) done lemma untyped_incD2: "\<lbrakk>cs p = Some c; is_untyped_cap c; cs p' = Some c'; is_untyped_cap c'; untyped_inc m cs\<rbrakk> \<Longrightarrow> untyped_range c \<inter> untyped_range c' \<noteq> {} \<longrightarrow> p \<in> descendants_of p' m \<and> untyped_range c \<subseteq> untyped_range c' \<or> p' \<in> descendants_of p m \<and> untyped_range c'\<subseteq> untyped_range c \<or> p = p'" apply (drule(4) untyped_incD) apply (rule ccontr) apply (elim conjE subset_splitE) apply clarsimp+ done lemma create_cap_mdb[wp]: "\<lbrace>valid_mdb and valid_objs and cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_refs (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> untyped_range (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> untyped_range (default_cap tp oref sz dev) \<inter> usable_untyped_range c = {}) p and descendants_range (default_cap tp oref sz dev) p and cte_wp_at ((=) cap.NullCap) cref and K (cap_aligned (default_cap tp oref sz dev))\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_mdb\<rbrace>" apply (simp add: valid_mdb_def2 create_cap_def set_cdt_def) apply (wp set_cap_caps_of_state2 | simp)+ apply clarsimp apply (subgoal_tac "mdb_insert_abs (cdt s) p cref") prefer 2 apply (rule mdb_insert_abs.intro) apply (clarsimp simp: cte_wp_at_def) apply (clarsimp simp: valid_mdb_def2 elim!: mdb_Null_None mdb_Null_descendants)+ apply (clarsimp simp: cte_wp_at_caps_of_state) apply (fold fun_upd_def) apply (intro conjI) apply (rule mdb_cte_atI) apply (simp add: is_cap_simps split: if_split_asm) apply (drule(1) mdb_cte_atD,clarsimp)+ apply (simp add: untyped_mdb_def descendants_of_def mdb_insert_abs.parency del: split_paired_All) apply (intro allI conjI impI) apply (clarsimp simp: is_cap_simps) apply (clarsimp simp: is_cap_simps) apply (erule_tac x=p in allE) apply (erule_tac x=ptr' in allE) apply (simp del: split_paired_All) apply (erule impE, blast) apply (erule (1) trancl_trans) apply (simp del: split_paired_All) apply (erule_tac x=p in allE) apply (erule_tac x=ptr' in allE) apply (simp del: split_paired_All) apply (erule impE, blast) apply (drule(1) descendants_rangeD) apply (simp del: split_paired_All add: cap_range_def) apply blast apply (drule_tac x=ptr in spec) apply (drule_tac x=cref in spec) apply (simp del: split_paired_All) apply (frule(1) inter_non_emptyD[rotated]) apply (drule_tac c = cap and c' = capa in untyped_incD2) apply simp+ apply (clarsimp simp add: descendants_of_def simp del: split_paired_All) apply (drule(1) descendants_rangeD) apply (clarsimp simp del: split_paired_All simp: cap_range_def) apply blast apply (erule(1) mdb_insert_abs.descendants_inc) apply simp apply (clarsimp simp: is_cap_simps cap_range_def cap_class_default_cap) apply (clarsimp simp: no_mloop_def) apply (frule_tac p = "(a,b)" and p'="(a,b)" in mdb_insert_abs.parency) apply (simp split: if_split_asm) apply (erule disjE) apply (drule_tac m = "cdt s" in mdb_cte_at_Null_descendants) apply (clarsimp simp: untyped_mdb_def) apply (clarsimp simp: descendants_of_def simp del: split_paired_All) apply clarsimp apply (rule mdb_create_cap.untyped_inc') apply (rule mdb_create_cap.intro) apply (rule vo_abs.intro) apply (rule vmdb_abs.intro) apply (simp add: valid_mdb_def swp_def cte_wp_at_caps_of_state) apply (erule vo_abs_axioms.intro) apply assumption apply (erule (2) mdb_create_cap_axioms.intro) apply assumption+ apply (simp add: ut_revocable_def del: split_paired_All) apply (simp add: irq_revocable_def del: split_paired_All) apply (simp add: reply_master_revocable_def del: split_paired_All) apply (simp add: reply_mdb_def) apply (subgoal_tac "\<And>t m R. default_cap tp oref sz dev \<noteq> cap.ReplyCap t m R") apply (rule conjI) apply (fastforce simp: reply_caps_mdb_def descendants_of_def mdb_insert_abs.parency simp del: split_paired_All split_paired_Ex elim!: allEI exEI) apply (fastforce simp: reply_masters_mdb_def descendants_of_def mdb_insert_abs.parency simp del: split_paired_All split_paired_Ex elim!: allEI) apply (cases tp, simp_all)[1] apply (erule valid_arch_mdb_untypeds) done lemma create_cap_descendants_range[wp]: "\<lbrace>descendants_range c p and K (cap_range c \<inter> cap_range (default_cap tp oref sz dev) = {}) and cte_wp_at ((\<noteq>) cap.NullCap) p and cte_wp_at ((=) cap.NullCap) cref and valid_mdb\<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>\<lambda>rv. descendants_range c p\<rbrace>" apply (simp add: create_cap_def descendants_range_def cte_wp_at_caps_of_state set_cdt_def) apply (wp set_cap_caps_of_state2 | simp del: fun_upd_apply)+ apply (clarsimp simp: cte_wp_at_caps_of_state swp_def valid_mdb_def simp del: fun_upd_apply) apply (subst (asm) mdb_insert_abs.descendants_child) apply (rule mdb_insert_abs.intro) apply clarsimp apply (erule (1) mdb_cte_at_Null_None) apply (erule (1) mdb_cte_at_Null_descendants) apply clarsimp apply (rule conjI, clarsimp) apply blast apply clarsimp done (* FIXME: Move to top *) lemma caps_overlap_reservedD: "\<lbrakk>caps_overlap_reserved S s; caps_of_state s slot = Some cap; is_untyped_cap cap\<rbrakk> \<Longrightarrow> usable_untyped_range cap \<inter> S = {}" apply (simp add: caps_overlap_reserved_def) apply (erule ballE) apply (erule(1) impE) apply simp apply fastforce done lemma cap_range_inter_emptyD: "cap_range a \<inter> cap_range b = {} \<Longrightarrow> untyped_range a \<inter> untyped_range b = {}" apply (drule disjoint_subset2[OF untyped_range_in_cap_range]) apply (drule disjoint_subset[OF untyped_range_in_cap_range]) apply simp done lemma create_cap_overlap_reserved [wp]: "\<lbrace>caps_overlap_reserved (untyped_range c) and K (cap_range c \<inter> cap_range (default_cap tp oref sz dev) = {}) and cte_wp_at ((\<noteq>) cap.NullCap) p and cte_wp_at ((=) cap.NullCap) cref and valid_mdb and K (cap_aligned (default_cap tp oref sz dev))\<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>\<lambda>rv s. caps_overlap_reserved (untyped_range c) s\<rbrace>" apply (simp add: create_cap_def caps_overlap_reserved_def cte_wp_at_caps_of_state set_cdt_def) apply (wp set_cap_caps_of_state2 | simp del: fun_upd_apply)+ apply (clarsimp simp: ran_def split: if_splits) apply (case_tac "cref = (a,b)") apply simp apply (erule(1) disjoint_subset[OF usable_range_subseteq]) apply (simp add:Int_ac cap_range_inter_emptyD) apply simp apply (erule(2) caps_overlap_reservedD) done crunch typ_at[wp]: create_cap "\<lambda>s. P (typ_at T p s)" (simp: crunch_simps) lemmas create_cap_cap_table_at[wp] = cap_table_at_lift_valid [OF create_cap_typ_at] lemma retype_region_invs_extras: "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev\<lbrace>\<lambda>rv. pspace_aligned\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev\<lbrace>\<lambda>rv. valid_objs\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. pspace_distinct\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. valid_mdb\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev\<lbrace>\<lambda>rv. valid_global_objs\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. valid_arch_state\<rbrace>" "\<lbrace>invs and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api ty us - 1} and region_in_kernel_window {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1} and (\<lambda>s. \<exists>slot. cte_wp_at (\<lambda>c. {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} \<subseteq> cap_range c \<and> cap_is_device c = dev) slot s) and K (ty = CapTableObject \<longrightarrow> 0 < us) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. valid_vspace_objs\<rbrace>" apply (wp hoare_strengthen_post [OF retype_region_post_retype_invs], auto simp: post_retype_invs_def split: if_split_asm)+ done lemma set_tuple_pick: "\<lbrace>P\<rbrace> f \<lbrace>\<lambda>rv s. \<forall>x \<in> set (xs rv s). Q x rv s\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>rv s. \<forall>tup \<in> set (zip (xs rv s) (ys rv s)). Q (fst tup) rv s\<rbrace>" "\<lbrace>P\<rbrace> f \<lbrace>\<lambda>rv s. \<forall>y \<in> set (ys rv s). R y rv s\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>rv s. \<forall>tup \<in> set (zip (xs rv s) (ys rv s)). R (snd tup) rv s\<rbrace>" apply (safe elim!: hoare_strengthen_post) apply (clarsimp simp: set_zip)+ done lemma obj_at_foldr_intro: "P obj \<and> p \<in> set xs \<Longrightarrow> obj_at P p (s \<lparr> kheap := foldr (\<lambda>p ps. ps (p \<mapsto> obj)) xs (kheap s) \<rparr>)" by (clarsimp simp: obj_at_def foldr_upd_app_if) context Untyped_AI_arch begin lemma retype_ret_valid_caps: "\<lbrace>pspace_no_overlap_range_cover ptr sz and K (tp = Structures_A.CapTableObject \<longrightarrow> us > 0) and K (tp = Untyped \<longrightarrow> untyped_min_bits \<le> us) and K (tp \<noteq> ArchObject ASIDPoolObj) and K (range_cover ptr sz (obj_bits_api tp us) n \<and> ptr \<noteq> 0)\<rbrace> retype_region ptr n us tp dev\<lbrace>\<lambda>rv (s::'state_ext state). \<forall>y\<in>set rv. s \<turnstile> default_cap tp y us dev\<rbrace>" apply (simp add: retype_region_def split del: if_split cong: if_cong) apply wp apply (simp only: trans_state_update[symmetric] more_update.valid_cap_update) apply wp apply (case_tac tp,simp_all) defer apply ((clarsimp simp:valid_cap_def default_object_def cap_aligned_def is_obj_defs well_formed_cnode_n_def empty_cnode_def dom_def ptr_add_def | rule conjI | intro conjI obj_at_foldr_intro imageI | rule is_aligned_add_multI[OF _ le_refl], (simp add:range_cover_def word_bits_def obj_bits_api_def)+)+)[3] apply (rule_tac ptr=ptr and sz=sz in retype_ret_valid_caps_captable; simp) apply (rule_tac ptr=ptr and sz=sz in retype_ret_valid_caps_aobj; simp) apply (clarsimp simp:valid_cap_def default_object_def cap_aligned_def is_obj_defs well_formed_cnode_n_def empty_cnode_def dom_def ptr_add_def | intro conjI obj_at_foldr_intro imageI | rule is_aligned_add_multI[OF _ le_refl] | fastforce simp:range_cover_def obj_bits_api_def word_bits_def a_type_def)+ apply (clarsimp simp:valid_cap_def valid_untyped_def) apply (drule(1) pspace_no_overlap_obj_range) apply (frule range_cover_cell_subset) apply (erule of_nat_mono_maybe[rotated]) apply (drule range_cover.range_cover_n_less) apply (simp add:word_bits_def) apply (simp add:obj_bits_api_def field_simps del:atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff) apply blast apply (erule(2) range_cover_no_0) done end (* FIXME: move to Lib *) lemma set_zip_helper: "t \<in> set (zip xs ys) \<Longrightarrow> fst t \<in> set xs \<and> snd t \<in> set ys" by (clarsimp simp add: set_zip) lemma ex_cte_cap_protects: "\<lbrakk> ex_cte_cap_wp_to P p s; cte_wp_at ((=) (cap.UntypedCap dev ptr bits idx)) p' s; descendants_range_in S p' s; untyped_children_in_mdb s; S\<subseteq> untyped_range (cap.UntypedCap dev ptr bits idx); valid_global_refs s \<rbrakk> \<Longrightarrow> fst p \<notin> S" apply (drule ex_cte_cap_to_obj_ref_disj, erule disjE) apply clarsimp apply (erule(1) untyped_children_in_mdbEE[where P="\<lambda>c. fst p \<in> obj_refs c" for c]) apply simp apply assumption apply (rule notemptyI[where x="fst p"]) apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex) apply blast apply (clarsimp simp:cte_wp_at_caps_of_state) apply (drule(2) descendants_range_inD) apply (clarsimp simp:cap_range_def) apply blast apply clarsimp apply (drule_tac irq=irq in valid_globals_irq_node, assumption) apply (clarsimp simp del:atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex) apply blast done lemma untyped_range_default_empty: "tp \<noteq> Untyped \<Longrightarrow> untyped_range (default_cap tp sz us dev) = {}" by (cases tp, auto) lemma obj_refs_default_cap: "obj_refs (default_cap tp oref sz dev) \<subseteq> {oref}" apply (cases tp, simp_all add: aobj_ref_default) done lemma obj_refs_default_nut: "tp \<noteq> Untyped \<Longrightarrow> obj_refs (default_cap tp oref sz dev) = {oref}" apply (cases tp, simp_all add: aobj_ref_default) done lemma range_cover_subset': "\<lbrakk>range_cover ptr sz sbit n; n \<noteq> 0\<rbrakk> \<Longrightarrow> {ptr ..ptr + of_nat n * 2 ^ sbit - 1} \<subseteq> {ptr..(ptr && ~~ mask sz) + 2^ sz - 1}" apply clarsimp apply (frule range_cover_cell_subset[OF _ of_nat_mono_maybe,where y1 = "(n - 1)"]) apply (drule range_cover.range_cover_n_less) apply (simp add:word_bits_def) apply simp apply (clarsimp simp:range_cover_def) apply (erule impE) apply (clarsimp simp:p_assoc_help) apply (rule is_aligned_no_wrap'[OF is_aligned_add_multI[OF _ le_refl refl ]]) apply (fastforce simp:range_cover_def)+ apply (clarsimp) apply (subst (asm) add.assoc) apply (subst (asm) distrib_right[where b = "1::'a::len word",simplified,symmetric]) apply simp done context Untyped_AI_arch begin lemma retype_region_ranges': "\<lbrace>K (range_cover ptr sz (obj_bits_api tp us) n)\<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. \<forall>y\<in>set rv. cap_range (default_cap tp y us dev) \<subseteq> {ptr..ptr + of_nat (n * 2 ^ (obj_bits_api tp us)) - 1}\<rbrace>" apply (simp add:valid_def) apply clarify apply (drule use_valid[OF _ retype_region_ret]) apply simp apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff) apply (rule subsetD[OF subset_trans]) apply (rule range_cover_subset,assumption) apply clarsimp apply assumption apply fastforce apply simp apply (case_tac tp) apply (simp_all add: cap_range_def obj_bits_api_def ptr_add_def) apply (subst add.commute, rule is_aligned_no_wrap'[OF aligned_add_aligned[OF _ _ le_refl]]) apply (fastforce simp: range_cover_def) apply (simp_all add: word_bits_def is_aligned_mult_triv2[where n=tcb_bits, simplified])[2] apply (subst add.commute, rule is_aligned_no_wrap'[OF aligned_add_aligned[OF _ _ le_refl]]) apply (fastforce simp: range_cover_def) apply (simp add: word_bits_def is_aligned_mult_triv2[where n=endpoint_bits, simplified])+ apply (subst add.commute, rule is_aligned_no_wrap'[OF aligned_add_aligned[OF _ _ le_refl]]) apply (fastforce simp: range_cover_def) apply (simp add: word_bits_def is_aligned_mult_triv2[where n=ntfn_bits, simplified])+ apply (clarsimp simp: is_aligned_def) apply (simp add: p_assoc_help) apply (rule is_aligned_no_wrap'[OF aligned_add_aligned[OF _ _ le_refl]]) apply (fastforce simp: range_cover_def) apply (rule is_aligned_mult_triv2) apply (simp add: range_cover_def) apply (simp add: p_assoc_help) apply (rule is_aligned_no_wrap'[OF is_aligned_add_multI[OF _ le_refl refl]]) apply (simp add: range_cover_def)+ done lemma retype_region_ranges: "\<lbrace>cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> obj_ref_of c = ptr && ~~ mask sz) p and pspace_no_overlap_range_cover ptr sz and valid_pspace and K (range_cover ptr sz (obj_bits_api tp us) n) \<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. \<forall>y\<in>set rv. cte_wp_at (\<lambda>c. cap_range (default_cap tp y us dev) \<subseteq> untyped_range c ) p s\<rbrace>" apply (clarsimp simp: cte_wp_at_caps_of_state valid_def) apply (frule_tac P1 = "(=) cap" in use_valid[OF _ retype_region_cte_at_other]) apply simp apply (fastforce simp: cte_wp_at_caps_of_state) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (frule use_valid[OF _ retype_region_ranges']) apply (fastforce simp: cte_wp_at_caps_of_state) apply (drule(1) bspec) apply (drule(1) subsetD) apply (rule_tac A = "{x..y}" for x y in subsetD[rotated]) apply assumption apply simp apply (erule subset_trans[OF range_cover_subset']) apply (frule use_valid[OF _ retype_region_ret]) apply simp apply fastforce apply (clarsimp simp: is_cap_simps) apply (erule order_trans[OF word_and_le2]) done end lemma map_snd_zip_prefix_help: "map (\<lambda>tup. cap_range (default_cap tp (snd tup) us dev)) (zip xs ys) \<le> map (\<lambda>x. cap_range (default_cap tp x us dev)) ys" apply (induct xs arbitrary: ys) apply simp apply (case_tac ys) apply auto done context Untyped_AI_arch begin lemma retype_region_distinct_sets: "\<lbrace>K (range_cover ptr sz (obj_bits_api tp us) n)\<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. distinct_sets (map (\<lambda>tup. cap_range (default_cap tp (snd tup) us dev)) (zip xs rv))\<rbrace>" apply (simp add: distinct_sets_prop) apply (rule hoare_gen_asm[where P'="\<top>", simplified]) apply (rule hoare_strengthen_post [OF retype_region_ret]) apply (rule distinct_prop_prefixE [rotated]) apply (rule map_snd_zip_prefix_help [unfolded less_eq_list_def]) apply (clarsimp simp: retype_addrs_def distinct_prop_map) apply (rule distinct_prop_distinct) apply simp apply (subgoal_tac "of_nat y * (2::machine_word) ^ obj_bits_api tp us \<noteq> of_nat x * 2 ^ obj_bits_api tp us") apply (case_tac tp) defer apply (simp add:cap_range_def ptr_add_def)+ apply (clarsimp simp: ptr_add_def word_unat_power[symmetric] shiftl_t2n[simplified mult.commute, symmetric]) apply (erule(2) of_nat_shift_distinct_helper[where 'a=machine_word_len and n = "obj_bits_api tp us"]) apply simp apply (simp add:range_cover_def) apply (erule range_cover.range_cover_n_le) apply (clarsimp simp: add_diff_eq[symmetric] simp del: Int_atLeastAtMost dest!: less_two_pow_divD) apply (simp add: obj_bits_api_def ptr_add_def shiftl_t2n[simplified mult.commute, symmetric] del: Int_atLeastAtMost) apply (rule aligned_neq_into_no_overlap) apply simp apply (simp_all add:range_cover_def shiftl_t2n mult.commute) apply (rule is_aligned_add_multI[OF _ le_refl refl]) apply (simp add:range_cover_def)+ apply (rule is_aligned_add_multI[OF _ le_refl refl]) apply (simp add:range_cover_def) done end declare dmo_aligned [wp] crunch pdistinct[wp]: do_machine_op "pspace_distinct" crunch vmdb[wp]: do_machine_op "valid_mdb" crunch mdb[wp]: do_machine_op "\<lambda>s. P (cdt s)" lemmas dmo_valid_cap[wp] = valid_cap_typ [OF do_machine_op_obj_at] lemma delete_objects_pspace_no_overlap[wp]: "\<lbrace>\<lambda>s. (\<exists>dev idx. s \<turnstile> (cap.UntypedCap dev ptr bits idx)) \<and> pspace_aligned s \<and> valid_objs s \<and> (S = {ptr .. ptr + 2 ^ bits - 1})\<rbrace> delete_objects ptr bits \<lbrace>\<lambda>_. pspace_no_overlap S\<rbrace>" apply (unfold delete_objects_def) apply wp apply (simp add: do_machine_op_def split_def) apply wp apply (clarsimp simp: pspace_no_overlap_detype') done lemma retype_region_descendants_range: "\<lbrace>\<lambda>s. descendants_range x cref s \<and> pspace_no_overlap_range_cover ptr sz s \<and> valid_pspace s \<and> range_cover ptr sz (obj_bits_api ty us) n\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv s. descendants_range x cref s\<rbrace>" apply (simp add:descendants_range_def) apply (rule hoare_pre) apply (wps retype_region_mdb) apply (wp hoare_vcg_ball_lift retype_cte_wp_at) apply fastforce done lemma cap_range_def2: "cap_range (default_cap ty ptr us dev) = (if ty = Untyped then {ptr..ptr + 2 ^ us - 1} else {ptr})" apply (case_tac ty) by (simp_all add: cap_range_def) context Untyped_AI_arch begin lemma retype_region_descendants_range_ret: "\<lbrace>\<lambda>s. (range_cover ptr sz (obj_bits_api ty us) n) \<and> pspace_no_overlap_range_cover ptr sz s \<and> valid_pspace s \<and> range_cover ptr sz (obj_bits_api ty us) n \<and> descendants_range_in {ptr..ptr + of_nat n * 2^(obj_bits_api ty us) - 1} cref s \<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv (s::'state_ext state). \<forall>y\<in>set rv. descendants_range (default_cap ty y us dev) cref s\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp: valid_def) apply (frule retype_region_ret[unfolded valid_def,simplified,THEN spec,THEN bspec]) apply (clarsimp) apply (rename_tac x) apply (erule use_valid[OF _ retype_region_descendants_range]) apply (intro conjI,simp_all) apply (clarsimp simp: descendants_range_def descendants_range_in_def) apply (drule(1) bspec) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (erule disjoint_subset2[rotated]) apply (frule(1) range_cover_subset) apply simp apply (erule subset_trans[rotated]) apply (subgoal_tac "ptr + of_nat x * 2 ^ obj_bits_api ty us \<le> ptr + of_nat x * 2 ^ obj_bits_api ty us + 2 ^ obj_bits_api ty us - 1") prefer 2 apply (rule is_aligned_no_overflow) apply (rule is_aligned_add_multI) apply (fastforce simp: range_cover_def)+ apply (auto simp add: cap_range_def2 ptr_add_def obj_bits_api_def) done end lemma caps_overlap_reserved_def2: "caps_overlap_reserved S = (\<lambda>s. (\<forall>cap \<in> ran (null_filter (caps_of_state s)). is_untyped_cap cap \<longrightarrow> usable_untyped_range cap \<inter> S = {}))" apply (rule ext) apply (clarsimp simp: caps_overlap_reserved_def) apply (intro iffI ballI impI) apply (elim ballE impE) apply simp apply simp apply (simp add: ran_def null_filter_def split: if_split_asm option.splits) apply (elim ballE impE) apply simp apply simp apply (clarsimp simp: ran_def null_filter_def is_cap_simps simp del: split_paired_All split_paired_Ex split: if_splits) apply (drule_tac x = "(a,b)" in spec) apply simp done lemma set_cap_valid_mdb_simple: "\<lbrace>\<lambda>s. valid_objs s \<and> valid_mdb s \<and> descendants_range_in {ptr .. ptr+2^sz - 1} cref s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> obj_ref_of c = ptr \<and> cap_is_device c = dev) cref s\<rbrace> set_cap (cap.UntypedCap dev ptr sz idx) cref \<lbrace>\<lambda>rv s'. valid_mdb s'\<rbrace>" apply (simp add: valid_mdb_def) apply (rule hoare_pre) apply (wp set_cap_mdb_cte_at) apply (wps set_cap_rvk_cdt_ct_ms) apply wp apply (clarsimp simp: cte_wp_at_caps_of_state is_cap_simps reply_master_revocable_def irq_revocable_def reply_mdb_def) unfolding fun_upd_def[symmetric] apply clarsimp proof(intro conjI impI) fix s f r bits dev assume obj:"valid_objs s" assume mdb:"untyped_mdb (cdt s) (caps_of_state s)" assume cstate:"caps_of_state s cref = Some (cap.UntypedCap dev r bits f)" (is "?m cref = Some ?srccap") show "untyped_mdb (cdt s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" apply (rule untyped_mdb_update_free_index [where capa = ?srccap and m = "caps_of_state s" and src = cref, unfolded free_index_update_def,simplified,THEN iffD2]) apply (simp add: cstate mdb)+ done assume inc: "untyped_inc (cdt s) (caps_of_state s)" assume drange: "descendants_range_in {r..r + 2 ^ bits - 1} cref s" have untyped_range_simp: "untyped_range (cap.UntypedCap dev r bits f) = untyped_range (cap.UntypedCap dev r bits idx)" by simp note blah[simp del] = untyped_range.simps usable_untyped_range.simps atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex show "untyped_inc (cdt s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" using inc cstate drange apply (unfold untyped_inc_def) apply (intro allI impI) apply (drule_tac x = p in spec) apply (drule_tac x = p' in spec) apply (case_tac "p = cref") apply (simp) apply (case_tac "p' = cref") apply simp apply (simp add: untyped_range_simp) apply (intro conjI impI) apply (simp) apply (elim conjE) apply (thin_tac "Q \<longrightarrow> P" for P Q)+ apply (frule(2) descendants_range_inD[rotated]) apply (drule caps_of_state_valid_cap[OF _ obj]) apply (drule sym) apply (rule disjoint_subset2[OF usable_range_subseteq]) apply (simp add: valid_cap_def cap_aligned_def untyped_range.simps)+ apply (elim disjE conjE) apply (frule(2) descendants_range_inD[rotated]) apply (drule caps_of_state_valid_cap[OF _ obj])+ apply (drule sym) apply (simp add: untyped_range.simps) apply (drule(1) untyped_range_non_empty[OF _ valid_cap_aligned]) apply simp+ apply (case_tac "p' = cref") apply simp apply (intro conjI) apply (elim conjE) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (simp add: untyped_range_simp)+ apply (intro impI) apply (elim conjE | simp)+ apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (frule(2) descendants_range_inD[rotated]) apply (drule caps_of_state_valid_cap[OF _ obj]) apply (drule sym) apply (rule disjoint_subset2[OF usable_range_subseteq]) apply ((clarsimp simp: valid_cap_def cap_aligned_def untyped_range.simps)+)[3] apply (intro impI) apply (elim conjE subset_splitE | simp)+ apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (clarsimp simp: untyped_range.simps) apply simp apply (elim conjE) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (clarsimp simp: untyped_range.simps) apply simp apply (erule disjE) apply (clarsimp simp: blah) apply (clarsimp simp: blah) apply (drule_tac t = c' in sym) apply (simp add: untyped_range.simps) apply (drule_tac t= c' in sym) apply (intro impI) apply (simp add: untyped_range.simps) apply (elim disjE conjE) apply simp apply (frule(2) descendants_range_inD[rotated]) apply (drule caps_of_state_valid_cap[OF _ obj])+ apply simp apply (drule(1) untyped_range_non_empty[OF _ valid_cap_aligned]) apply simp+ done assume "ut_revocable (is_original_cap s) (caps_of_state s)" thus "ut_revocable (is_original_cap s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" using cstate by (fastforce simp: ut_revocable_def) assume "valid_arch_mdb (is_original_cap s) (caps_of_state s)" thus "valid_arch_mdb (is_original_cap s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" using cstate by (fastforce elim!: valid_arch_mdb_untypeds) assume "reply_caps_mdb (cdt s) (caps_of_state s)" thus "reply_caps_mdb (cdt s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" using cstate apply (simp add: reply_caps_mdb_def del: split_paired_All) apply (intro allI impI conjI) apply (drule spec)+ apply (erule(1) impE) apply (erule exE)+ apply (rule_tac x = ptr' in exI) apply clarsimp done assume "reply_masters_mdb (cdt s) (caps_of_state s)" thus "reply_masters_mdb (cdt s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" apply (simp add: reply_masters_mdb_def del: split_paired_All) apply (intro allI impI ballI) apply (erule exE) apply (elim allE impE) apply simp using cstate apply fastforce done assume misc: "mdb_cte_at (swp (cte_wp_at ((\<noteq>) cap.NullCap)) s) (cdt s)" "descendants_inc (cdt s) (caps_of_state s)" "caps_of_state s cref = Some (cap.UntypedCap dev r bits f)" thus "descendants_inc (cdt s) (caps_of_state s(cref \<mapsto> cap.UntypedCap dev r bits idx))" apply - apply (erule descendants_inc_minor) apply (clarsimp simp: swp_def cte_wp_at_caps_of_state) apply (clarsimp simp: untyped_range.simps) done qed lemma set_free_index_valid_pspace_simple: "\<lbrace>\<lambda>s. valid_mdb s \<and> valid_pspace s \<and> pspace_no_overlap_range_cover ptr sz s \<and> descendants_range_in {ptr .. ptr+2^sz - 1} cref s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> obj_ref_of c = ptr) cref s \<and> idx \<le> 2^ sz\<rbrace> set_cap (cap.UntypedCap dev ptr sz idx) cref \<lbrace>\<lambda>rv s'. valid_pspace s'\<rbrace>" apply (clarsimp simp: valid_pspace_def) apply (wp set_cap_valid_objs update_cap_iflive set_cap_zombies') apply (clarsimp simp: cte_wp_at_caps_of_state is_cap_simps)+ apply (frule(1) caps_of_state_valid_cap) apply (clarsimp simp: valid_cap_def cap_aligned_def ) apply (intro conjI) apply (simp add: valid_untyped_def) apply (intro impI allI) apply (elim allE allE impE) apply simp+ apply (drule(1) pspace_no_overlap_obj_range) apply (simp add: field_simps) apply (clarsimp simp add: pred_tcb_at_def tcb_cap_valid_def obj_at_def is_tcb valid_ipc_buffer_cap_def split: option.split) apply (drule(2) tcb_cap_slot_regular) apply (clarsimp simp: tcb_cap_cases_def is_cap_simps split: if_splits) apply (fastforce simp: is_nondevice_page_cap_simps) apply (clarsimp split: thread_state.splits simp: is_reply_cap_def) done lemma set_untyped_cap_refs_respects_device_simple: "\<lbrace>K (is_untyped_cap cap) and cte_wp_at ((=) cap) cref and cap_refs_respects_device_region \<rbrace> set_cap (UntypedCap (cap_is_device cap) (obj_ref_of cap) (cap_bits cap) idx) cref \<lbrace>\<lambda>rv s. cap_refs_respects_device_region s\<rbrace>" apply (wp set_cap_cap_refs_respects_device_region) apply (clarsimp simp del: split_paired_Ex) apply (rule_tac x = cref in exI) apply (erule cte_wp_at_weakenE) apply (case_tac cap,auto) done lemma set_untyped_cap_caps_overlap_reserved: "\<lbrace>\<lambda>s. invs s \<and> S \<subseteq> {ptr..ptr + 2 ^ sz - 1} \<and> usable_untyped_range (cap.UntypedCap dev ptr sz idx') \<inter> S = {} \<and> descendants_range_in S cref s \<and> cte_wp_at ((=) (cap.UntypedCap dev ptr sz idx)) cref s\<rbrace> set_cap (cap.UntypedCap dev ptr sz idx') cref \<lbrace>\<lambda>rv s. caps_overlap_reserved S s\<rbrace>" apply (unfold caps_overlap_reserved_def) apply wp apply (clarsimp simp: cte_wp_at_caps_of_state caps_overlap_reserved_def simp del: usable_untyped_range.simps split: if_split_asm) apply (frule invs_mdb) apply (erule ranE) apply (simp split: if_split_asm del: usable_untyped_range.simps add: valid_mdb_def) apply (drule untyped_incD) apply ((simp add: is_cap_simps)+)[4] apply clarify apply (erule subset_splitE) apply (simp del: usable_untyped_range.simps) apply (thin_tac "P \<longrightarrow> Q" for P Q)+ apply (elim conjE) apply blast apply (simp del: usable_untyped_range.simps) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (elim conjE) apply (drule(2) descendants_range_inD) apply simp apply (drule_tac B = S in disjoint_subset[rotated,OF _ usable_range_subseteq]) apply (rule valid_cap_aligned) apply (erule(1) caps_of_state_valid) apply simp+ apply (elim disjE) apply clarsimp apply (drule(2) descendants_range_inD) apply simp apply (drule_tac B=S in disjoint_subset[rotated,OF _ usable_range_subseteq]) apply (rule valid_cap_aligned) apply (erule(1) caps_of_state_valid) apply simp+ apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (rule disjoint_subset[OF usable_range_subseteq]) apply (rule valid_cap_aligned) apply (erule(1) caps_of_state_valid) apply simp+ apply blast done lemma set_cap_caps_no_overlap: "\<lbrace>cte_wp_at (\<lambda>c. untyped_range c = untyped_range cap) cref and caps_no_overlap ptr sz\<rbrace> set_cap cap cref \<lbrace>\<lambda>r s. caps_no_overlap ptr sz s\<rbrace>" apply (simp add: caps_no_overlap_def) apply wp apply (clarsimp simp: cte_wp_at_caps_of_state caps_no_overlap_def simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff ) apply (erule ranE) apply (simp split: if_splits del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff ) apply (drule bspec) apply fastforce apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff ) apply (erule(1) set_mp) apply (drule_tac x = capa in bspec) apply fastforce apply (clarsimp simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff ) apply (erule(1) set_mp) done lemma caps_overlap_reserved_detype: "caps_overlap_reserved S s \<Longrightarrow> caps_overlap_reserved S (detype H s)" apply (clarsimp simp: caps_overlap_reserved_def ) apply (erule ranE) apply (clarsimp split: if_splits) apply (drule bspec) apply fastforce apply simp done lemma caps_no_overlap_detype: "caps_no_overlap ptr sz s \<Longrightarrow> caps_no_overlap ptr sz (detype H s)" apply (clarsimp simp: caps_no_overlap_def) apply (erule ranE) apply (clarsimp split: if_splits) apply (drule bspec,fastforce) apply clarsimp apply (erule subsetD) apply simp done lemma not_inD:"\<lbrakk>x \<notin> A; y \<in> A\<rbrakk> \<Longrightarrow>x \<noteq> y" by clarsimp lemma caps_of_state_no_overlapD: "\<lbrakk>caps_of_state s slot = Some cap; valid_objs s; pspace_aligned s; pspace_no_overlap S s\<rbrakk> \<Longrightarrow> (fst slot) \<notin> S" apply (drule caps_of_state_cteD) apply (clarsimp simp: cte_wp_at_cases obj_at_def simp del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost) apply (elim disjE) apply clarify apply (frule(2) p_in_obj_range) apply (erule(1) pspace_no_overlapE) apply (drule(1) IntI) unfolding obj_range_def apply (drule notemptyI)+ apply (simp add: Int_ac p_assoc_help del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost) apply clarify apply (frule(2) p_in_obj_range) apply (erule(1) pspace_no_overlapE) apply (drule(1) IntI) unfolding obj_range_def apply (drule notemptyI)+ apply (simp add: Int_ac p_assoc_help add.commute del: atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost) done lemma op_equal: "(\<lambda>x. x = c) = ((=) c)" by (rule ext) auto lemma descendants_range_in_subseteq: "\<lbrakk>descendants_range_in A p ms ;B\<subseteq> A\<rbrakk> \<Longrightarrow> descendants_range_in B p ms" by (auto simp: descendants_range_in_def cte_wp_at_caps_of_state dest!: bspec) lemma cte_wp_at_pspace_no_overlapI: "\<lbrakk>invs s; cte_wp_at (\<lambda>c. c = cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz); sz < word_bits\<rbrakk> \<Longrightarrow> pspace_no_overlap_range_cover ptr sz s" apply (clarsimp simp: cte_wp_at_caps_of_state) apply (frule caps_of_state_valid_cap) apply (simp add: invs_valid_objs) apply (clarsimp simp: valid_cap_def valid_untyped_def) apply (unfold pspace_no_overlap_def) apply (intro allI impI) apply (drule spec)+ apply (erule(1) impE) apply (simp only: obj_range_def[symmetric] p_assoc_help[symmetric]) apply (frule(1) le_mask_le_2p) apply (rule ccontr) apply (erule impE) apply (rule ccontr) apply simp apply (drule disjoint_subset2[rotated, where B'="{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply clarsimp apply (rule word_and_le2) apply simp apply clarsimp apply (drule_tac A'="{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}" in disjoint_subset[rotated]) apply clarsimp apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) apply blast done lemma descendants_range_caps_no_overlapI: "\<lbrakk>invs s; cte_wp_at ((=) (cap.UntypedCap dev (ptr && ~~ mask sz) sz idx)) cref s; descendants_range_in {ptr .. (ptr && ~~ mask sz) +2^sz - 1} cref s\<rbrakk> \<Longrightarrow> caps_no_overlap ptr sz s" apply (frule invs_mdb) apply (clarsimp simp: valid_mdb_def cte_wp_at_caps_of_state) apply (unfold caps_no_overlap_def) apply (intro ballI impI) apply (erule ranE) apply (subgoal_tac "is_untyped_cap cap") prefer 2 apply (rule untyped_range_is_untyped_cap) apply blast apply (drule untyped_incD) apply simp+ apply (elim conjE) apply (erule subset_splitE) apply (erule subset_trans[OF _ psubset_imp_subset,rotated]) apply (clarsimp simp: word_and_le2) apply simp apply (elim conjE) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule(2) descendants_range_inD) apply simp apply simp apply (erule subset_trans[OF _ equalityD1,rotated]) apply (clarsimp simp: word_and_le2) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule disjoint_subset[rotated, where A' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply (clarsimp simp: word_and_le2 Int_ac)+ done lemma shiftr_then_mask_commute: "(x >> n) && mask m = (x && mask (m + n)) >> n" using test_bit_size[where w=x] by (auto intro: word_eqI simp add: word_size nth_shiftr) lemma cte_wp_at_caps_no_overlapI: "\<lbrakk> invs s;cte_wp_at (\<lambda>c. c = cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) cref s; idx \<le> unat (ptr && mask sz);sz < word_bits \<rbrakk> \<Longrightarrow> caps_no_overlap ptr sz s" apply (frule invs_mdb) apply (frule(1) le_mask_le_2p) apply (clarsimp simp: valid_mdb_def cte_wp_at_caps_of_state) apply (frule caps_of_state_valid_cap) apply (simp add: invs_valid_objs) apply (unfold caps_no_overlap_def) apply (intro ballI impI) apply (erule ranE) apply (subgoal_tac "is_untyped_cap cap") prefer 2 apply (rule untyped_range_is_untyped_cap) apply blast apply (drule untyped_incD) apply simp+ apply (elim conjE) apply (erule subset_splitE) apply (erule subset_trans[OF _ psubset_imp_subset,rotated]) apply (clarsimp simp: word_and_le2) apply simp apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (elim conjE) apply (drule disjoint_subset2[rotated, where B' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply clarsimp apply (rule le_plus'[OF word_and_le2]) apply simp apply (erule word_of_nat_le) apply simp apply simp apply (erule subset_trans[OF _ equalityD1,rotated]) apply (clarsimp simp: word_and_le2) apply (thin_tac "P\<longrightarrow>Q" for P Q)+ apply (drule disjoint_subset[rotated, where A' = "{ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}"]) apply (clarsimp simp: word_and_le2 Int_ac)+ done lemma add_minus_neg_mask: "ptr + a - (ptr && ~~ mask sz) = (ptr && mask sz) + a" apply (subst word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr]) apply simp done lemma range_cover_idx_compare: "\<lbrakk>range_cover ptr sz sbit n; unat ((ptr && mask sz) + of_nat n * 2 ^ sbit) < 2 ^ sz; ptr \<noteq> ptr && ~~ mask sz; idx \<le> 2 ^ sz; idx \<le> unat (ptr && mask sz)\<rbrakk> \<Longrightarrow> (ptr && ~~ mask sz) + of_nat idx \<le> ptr + (of_nat n << sbit)" apply (subst not_less[symmetric]) apply (subst word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr]) apply (subst add.commute) apply (simp add: not_less) apply (subst add.assoc) apply (rule word_add_le_mono2) apply (rule order_trans[OF word_of_nat_le]) apply simp apply (erule range_cover.range_cover_base_le) apply (subst unat_plus_simple[THEN iffD1]) apply (erule range_cover.range_cover_base_le) apply (subst unat_add_lem[THEN iffD1,symmetric]) apply (frule range_cover.unat_of_nat_shift[OF _ le_refl le_refl]) apply (simp add: shiftl_t2n field_simps del: add.commute add.assoc) apply (rule le_less_trans) apply (subst add.commute) apply (erule range_cover.range_cover_compare_bound) apply (simp add: range_cover_def) apply (rule less_diff_conv[THEN iffD1]) apply (rule less_le_trans) apply (simp add: shiftl_t2n field_simps) apply (subst le_diff_conv2) apply (rule less_imp_le[OF unat_lt2p]) apply (subst add.commute) apply (subst unat_power_lower[where 'a='a, symmetric]) apply (simp add: range_cover_def) apply (rule is_aligned_no_wrap_le[OF is_aligned_neg_mask[OF le_refl]]) apply (simp add: range_cover_def)+ done locale invoke_untyped_proofs = fixes s cref reset ptr_base ptr tp us slots ptr' sz idx dev assumes vui: "valid_untyped_inv_wcap (Retype cref reset ptr_base ptr tp us slots dev) (Some (UntypedCap dev (ptr && ~~ mask sz) sz idx)) s" and misc: "ct_active s" "invs s" notes blah[simp del] = untyped_range.simps usable_untyped_range.simps atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex begin abbreviation(input) "retype_range == {ptr..ptr + of_nat (length slots) * 2 ^ (obj_bits_api tp us) - 1}" abbreviation(input) "usable_range == {ptr..(ptr && ~~ mask sz) + 2 ^ sz - 1}" lemma not_0_ptr[simp]: "ptr\<noteq> 0" using misc vui apply (clarsimp simp: cte_wp_at_caps_of_state) apply (drule(1) caps_of_state_valid) apply (clarsimp simp: valid_cap_def) done lemma cover: "range_cover ptr sz (obj_bits_api tp us) (length slots)" using vui by (clarsimp simp:cte_wp_at_caps_of_state) lemma misc2: "distinct slots" "slots \<noteq> []" using vui by (auto simp:cte_wp_at_caps_of_state) lemma subset_stuff[simp]: "retype_range \<subseteq> usable_range" apply (rule range_cover_subset'[OF cover]) apply (simp add:misc2) done lemma cte_wp_at: "cte_wp_at ((=) (cap.UntypedCap dev (ptr && ~~ mask sz) sz idx)) cref s" using vui by (clarsimp simp: cte_wp_at_caps_of_state) lemma idx_cases: "(idx \<le> unat (ptr - (ptr && ~~ mask sz)) \<or> reset \<and> ptr = ptr && ~~ mask sz)" using vui by (clarsimp simp: cte_wp_at_caps_of_state) lemma desc_range: "reset \<longrightarrow> descendants_range_in S cref s" using vui by (clarsimp simp: empty_descendants_range_in) lemma descendants_range[simp]: "descendants_range_in usable_range cref s" "descendants_range_in retype_range cref s" proof - have "descendants_range_in usable_range cref s" using misc idx_cases cte_wp_at cover apply - apply (erule disjE) apply (erule cte_wp_at_caps_descendants_range_inI[OF _ _ _ range_cover.sz(1) [where 'a=machine_word_len, folded word_bits_def]]) apply (simp add:cte_wp_at_caps_of_state desc_range)+ done thus "descendants_range_in usable_range cref s" by simp thus "descendants_range_in retype_range cref s" by (rule descendants_range_in_subseteq[OF _ subset_stuff]) qed lemma vc[simp] : "s \<turnstile>cap.UntypedCap dev (ptr && ~~ mask sz) sz idx" using misc cte_wp_at apply (clarsimp simp: cte_wp_at_caps_of_state) apply (erule caps_of_state_valid) apply simp done lemma ps_no_overlap[simp]: "\<not> reset \<longrightarrow> pspace_no_overlap_range_cover ptr sz s" using misc cte_wp_at cover idx_cases apply clarsimp apply (erule cte_wp_at_pspace_no_overlapI[OF _ _ _ range_cover.sz(1)[where 'a=machine_word_len, folded word_bits_def]]) apply (simp add: cte_wp_at_caps_of_state) apply simp+ done lemma caps_no_overlap[simp]: "caps_no_overlap ptr sz s" using cte_wp_at misc cover idx_cases apply - apply (erule disjE) apply (erule cte_wp_at_caps_no_overlapI[OF _ _ _ range_cover.sz(1) [where 'a=machine_word_len, folded word_bits_def]]) apply (simp add:cte_wp_at_caps_of_state)+ apply (erule descendants_range_caps_no_overlapI) apply (simp add:cte_wp_at_caps_of_state desc_range)+ done lemma idx_compare'[simp]:"unat ((ptr && mask sz) + (of_nat (length slots)<< (obj_bits_api tp us))) \<le> 2 ^ sz" apply (rule le_trans[OF unat_plus_gt]) apply (simp add:range_cover.unat_of_nat_n_shift[OF cover] range_cover_unat) apply (insert range_cover.range_cover_compare_bound[OF cover]) apply simp done lemma ex_cte_no_overlap: "\<And>P slot. ex_cte_cap_wp_to P slot s \<Longrightarrow> fst slot \<notin> usable_range" using cte_wp_at apply clarsimp apply (drule ex_cte_cap_to_obj_ref_disj,erule disjE) using misc apply clarsimp apply (rule_tac ptr' = "(aa,b)" in untyped_children_in_mdbEE[OF invs_untyped_children]) apply simp+ apply (clarsimp simp:untyped_range.simps) apply (drule_tac B'="usable_range" in disjoint_subset2[rotated]) apply (clarsimp simp:blah word_and_le2) apply blast apply (drule descendants_range_inD[OF descendants_range(1)]) apply (simp add:cte_wp_at_caps_of_state)+ apply (clarsimp simp:cap_range_def) apply blast apply clarsimp apply (drule_tac irq = irq in valid_globals_irq_node[rotated]) using misc apply (clarsimp simp: invs_def valid_state_def ) apply (clarsimp simp:untyped_range.simps) apply (drule_tac B = "{ptr && ~~ mask sz..(ptr && ~~ mask sz) + 2 ^ sz - 1}" in subsetD[rotated]) apply (clarsimp simp:blah word_and_le2) apply simp done lemma cref_inv: "fst cref \<notin> usable_range" apply (insert misc cte_wp_at) apply (drule if_unsafe_then_capD) apply (simp add:invs_def valid_state_def) apply clarsimp apply (drule ex_cte_no_overlap) apply simp done lemma slots_invD: "\<And>x. x \<in> set slots \<Longrightarrow> x \<noteq> cref \<and> fst x \<notin> usable_range \<and> ex_cte_cap_wp_to (\<lambda>_. True) x s" using misc cte_wp_at vui apply (clarsimp simp: cte_wp_at_caps_of_state) apply (drule(1) bspec)+ apply clarsimp apply (frule ex_cte_no_overlap) apply (auto elim: ex_cte_cap_wp_to_weakenE) done lemma usable_range_disjoint: "usable_untyped_range (cap.UntypedCap dev (ptr && ~~ mask sz) sz (unat ((ptr && mask sz) + of_nat (length slots) * 2 ^ obj_bits_api tp us))) \<inter> {ptr..ptr + of_nat (length slots) * 2 ^ obj_bits_api tp us - 1} = {}" proof - have idx_compare''[simp]: "unat ((ptr && mask sz) + (of_nat (length slots) * (2::machine_word) ^ obj_bits_api tp us)) < 2 ^ sz \<Longrightarrow> ptr + of_nat (length slots) * 2 ^ obj_bits_api tp us - 1 < ptr + of_nat (length slots) * 2 ^ obj_bits_api tp us" apply (rule word_leq_le_minus_one,simp) apply (rule neq_0_no_wrap) apply (rule machine_word_plus_mono_right_split) apply (simp add:shiftl_t2n range_cover_unat[OF cover] field_simps) apply (simp add:range_cover.sz[where 'a=machine_word_len, folded word_bits_def, OF cover])+ done show ?thesis apply (clarsimp simp:mask_out_sub_mask blah) apply (drule idx_compare'') apply (simp add:not_le[symmetric]) done qed lemma detype_locale:"ptr && ~~ mask sz = ptr \<Longrightarrow> detype_locale (cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) cref s" using cte_wp_at descendants_range misc by (simp add:detype_locale_def descendants_range_def2 blah invs_untyped_children) lemma detype_descendants_range_in: "ptr && ~~ mask sz = ptr \<Longrightarrow> descendants_range_in usable_range cref (detype usable_range s)" using misc cte_wp_at apply - apply (frule detype_invariants) apply (simp) using descendants_range apply (clarsimp simp: blah descendants_range_def2) apply (simp add: invs_untyped_children blah invs_valid_reply_caps invs_valid_reply_masters)+ apply (subst valid_mdb_descendants_range_in) apply (clarsimp dest!:invs_mdb simp:detype_clear_um_independent) apply (frule detype_locale) apply (drule detype_locale.non_filter_detype[symmetric]) apply (simp add:blah) using descendants_range(1) apply - apply (subst (asm)valid_mdb_descendants_range_in) apply (simp add:invs_mdb) apply simp done lemma detype_invs: "ptr && ~~ mask sz = ptr \<Longrightarrow> invs (detype usable_range (clear_um usable_range s))" apply (insert misc cte_wp_at descendants_range) apply clarsimp apply (frule detype_invariants, simp_all) apply (clarsimp simp:blah descendants_range_def2) apply ((simp add: invs_untyped_children blah invs_valid_reply_caps invs_valid_reply_masters)+) done lemmas simps = caps_no_overlap descendants_range slots_invD cref_inv ps_no_overlap subset_stuff lemma szw: "sz < word_bits" using cte_wp_at_valid_objs_valid_cap[OF cte_wp_at] misc by (clarsimp simp: valid_cap_def cap_aligned_def invs_valid_objs) lemma idx_le_new_offs: "\<not> reset \<Longrightarrow> idx \<le> unat ((ptr && mask sz) + (of_nat (length slots) << obj_bits_api tp us))" using misc idx_cases range_cover.range_cover_base_le[OF cover] apply (simp only: simp_thms) apply (erule order_trans) apply (simp add: word_le_nat_alt[symmetric]) done end lemmas aligned_after_mask = is_aligned_andI1[where x=ptr and n=a and y="mask sz" for ptr sz a] lemma detype_clear_um_simps[simp]: "caps_no_overlap ptr sz (clear_um H s) = caps_no_overlap ptr sz s" "pspace_no_overlap S (clear_um H s) = pspace_no_overlap S s" "descendants_range_in S p (clear_um H s) = descendants_range_in S p s" apply (clarsimp simp: caps_no_overlap_def pspace_no_overlap_def clear_um.pspace descendants_range_in_def cong: if_cong)+ apply (simp add: clear_um_def) done crunch pred_tcb_at[wp]: create_cap "pred_tcb_at proj P t" (simp: crunch_simps) crunch tcb[wp]: create_cap "tcb_at t" (simp: crunch_simps) lemma valid_untyped_cap_inc: "\<lbrakk>s \<turnstile> cap.UntypedCap dev (ptr&&~~ mask sz) sz idx; idx \<le> unat (ptr && mask sz); range_cover ptr sz sb n\<rbrakk> \<Longrightarrow> s \<turnstile> cap.UntypedCap dev (ptr && ~~ mask sz) sz (unat ((ptr && mask sz) + of_nat n * 2 ^ sb))" apply (clarsimp simp: valid_cap_def cap_aligned_def valid_untyped_def simp del: usable_untyped_range.simps) apply (intro conjI allI impI) apply (elim allE conjE impE) apply simp apply simp apply (erule disjoint_subset[rotated]) apply (frule(1) le_mask_le_2p[OF _ range_cover.sz(1)[where 'a=machine_word_len, folded word_bits_def]]) apply clarsimp apply (rule word_plus_mono_right) apply (rule word_of_nat_le) apply (simp add: unat_of_nat_eq[where 'a=machine_word_len] range_cover_unat field_simps) apply (rule is_aligned_no_wrap'[OF is_aligned_neg_mask[OF le_refl]]) apply (simp add: word_less_nat_alt) apply (simp add: range_cover_unat range_cover.unat_of_nat_shift shiftl_t2n field_simps) apply (subst add.commute) apply (simp add: range_cover.range_cover_compare_bound) done (* FIXME: move maybe *) lemma tcb_cap_valid_untyped_cong: "tcb_cap_valid (cap.UntypedCap dev1 a1 b1 c) = tcb_cap_valid (cap.UntypedCap dev2 a2 b2 c2)" apply (rule ext)+ apply (clarsimp simp:tcb_cap_valid_def valid_ipc_buffer_cap_def split:option.splits) apply (simp add: tcb_cap_cases_def is_arch_cap_def is_nondevice_page_cap_simps is_cap_simps split: thread_state.split) done lemma tcb_cap_valid_untyped_to_thread: "tcb_cap_valid (cap.UntypedCap dev a1 b1 c) = tcb_cap_valid (cap.ThreadCap 0)" apply (rule ext)+ apply (clarsimp simp:tcb_cap_valid_def valid_ipc_buffer_cap_def split:option.splits) apply (simp add: tcb_cap_cases_def is_cap_simps is_arch_cap_def is_nondevice_page_cap_simps split: thread_state.split) done (* FIXME: move *) lemma ex_nonz_cap_to_overlap: "\<lbrakk>ex_nonz_cap_to t s; cte_wp_at ((=) cap) p s; is_untyped_cap cap; invs s; descendants_range cap p s \<rbrakk> \<Longrightarrow> \<not> t \<in> untyped_range cap" apply (rule ccontr) apply (clarsimp simp: ex_nonz_cap_to_def descendants_range_def2 cte_wp_at_caps_of_state caps_no_overlap_def zobj_refs_to_obj_refs) apply (frule invs_mdb) apply (clarsimp simp: valid_mdb_def) apply (frule_tac cap' = capa in untyped_mdbD) apply simp+ apply blast apply simp apply (drule(2) descendants_range_inD) apply (simp add: cap_range_def) apply blast done lemma detype_valid_untyped: "\<lbrakk>invs s; detype S s \<turnstile> cap.UntypedCap dev ptr sz idx1; {ptr .. ptr + 2 ^ sz - 1} \<subseteq> S; idx2 \<le> 2 ^ sz\<rbrakk> \<Longrightarrow> detype S s \<turnstile> cap.UntypedCap dev ptr sz idx2" apply (clarsimp simp: detype_def valid_cap_def valid_untyped_def cap_aligned_def) apply (drule_tac x = p in spec) apply clarsimp apply (drule p_in_obj_range) apply (simp add: invs_psp_aligned invs_valid_objs)+ apply (drule(1) subset_trans[rotated]) apply blast done lemma do_machine_op_pspace_no_overlap[wp]: "\<lbrace>pspace_no_overlap S\<rbrace> do_machine_op f \<lbrace>\<lambda>r. pspace_no_overlap S\<rbrace>" apply (clarsimp simp: pspace_no_overlap_def do_machine_op_def) apply (wp hoare_vcg_all_lift) apply (simp add: split_def) apply wp+ apply clarsimp done lemma mapME_append: "mapME f (xs @ ys) = doE xs_r \<leftarrow> mapME f xs; ys_r \<leftarrow> mapME f ys; returnOk (xs_r @ ys_r) odE" by (induct xs, simp_all add: mapME_Nil mapME_Cons bindE_assoc) lemma mapME_validE_nth_induct: "\<lbrakk> \<And>i ys. i < length xs \<Longrightarrow> \<lbrace>P i ys\<rbrace> f (zs ! i) \<lbrace>\<lambda>y. P (Suc i) (y # ys)\<rbrace>, \<lbrace>E\<rbrace>; \<And>i. i < length xs \<Longrightarrow> zs ! i = xs ! i \<rbrakk> \<Longrightarrow> \<lbrace>P 0 []\<rbrace> mapME f xs \<lbrace>\<lambda>ys. P (length xs) (rev ys)\<rbrace>, \<lbrace>E\<rbrace>" proof (induct xs rule: rev_induct) case Nil show ?case by (wp | simp add: mapME_Nil)+ next case (snoc x xs) from snoc.prems have x: "x = zs ! length xs" by simp from snoc.prems have zs: "\<And>i. i < length xs \<Longrightarrow> xs ! i = zs ! i" by (metis length_append_singleton less_SucI nth_append) show ?case apply (simp add: mapME_append mapME_Cons mapME_Nil bindE_assoc x) apply (wp snoc.hyps snoc.prems | simp add: zs)+ done qed lemma mapME_x_mapME: "mapME_x m l = (mapME m l >>=E (%_. returnOk ()))" apply (simp add: mapME_x_def sequenceE_x_def mapME_def sequenceE_def) apply (induct l, simp_all add: Let_def bindE_assoc) done lemmas mapME_validE_nth = mapME_validE_nth_induct[OF _ refl] lemma mapME_x_validE_nth: "\<lbrakk> \<And>i. i < length xs \<Longrightarrow> \<lbrace>P i\<rbrace> f (xs ! i) \<lbrace>\<lambda>y. P (Suc i)\<rbrace>, \<lbrace>E\<rbrace> \<rbrakk> \<Longrightarrow> \<lbrace>P 0\<rbrace> mapME_x f xs \<lbrace>\<lambda>_. P (length xs)\<rbrace>, \<lbrace>E\<rbrace>" by (wp mapME_validE_nth | simp add: mapME_x_mapME)+ lemma alignUp_ge_nat: "0 < m \<Longrightarrow> (n :: nat) \<le> ((n + m - 1) div m) * m" apply (cases n) apply (simp_all add: Suc_le_eq) apply (metis add.commute add_less_cancel_left dividend_less_div_times) done lemma alignUp_le_nat: "0 < m \<Longrightarrow> n \<le> (b :: nat) \<Longrightarrow> m dvd b \<Longrightarrow> ((n + m - 1) div m) * m \<le> b" apply (clarsimp simp: dvd_def) apply (rule less_Suc_eq_le[THEN iffD1]) apply (simp add: td_gal_lt[symmetric]) apply (subst less_eq_Suc_le, simp add: mult.commute) done lemma filter_upt_eq: assumes mono: "\<forall>a b. a \<le> b \<longrightarrow> f b \<longrightarrow> f a" and preds: "\<not> f k" "k \<noteq> 0 \<longrightarrow> f (k - 1)" "k \<le> j" shows "filter f (upt i j) = upt i k" proof - have mono': "\<And>a b. a \<le> b \<longrightarrow> f b \<longrightarrow> f a" by (metis mono) have f: "f = (\<lambda>x. x < k)" apply (rule ext) apply (cut_tac a=k and b=x in mono') apply (cut_tac a=x and b="k - 1" in mono') apply (cut_tac preds(1)) apply (cases "k = 0") apply (simp add: preds) apply (simp add: preds[simplified]) apply (cases k, auto) done show ?thesis apply (rule sorted_distinct_set_unique, simp_all add: sorted_filter[where f=id, simplified]) apply (cut_tac preds) apply (auto simp add: f) done qed lemma nat_diff_less2: fixes x :: nat shows "\<lbrakk> x < y + z; 0 < y\<rbrakk> \<Longrightarrow> x - z < y" apply (cases "z \<le> x") apply (metis nat_diff_less) apply simp done lemma upt_mult_lt_prop: assumes n: "n \<le> 2 ^ a" assumes b: "b \<le> a" shows "\<exists>bd. [i\<leftarrow>[0..<2 ^ (a - b)]. i * 2 ^ b < n] = [0 ..< bd] \<and> n \<le> bd * 2 ^ b \<and> bd * 2 ^ b \<le> 2 ^ a \<and> (bd - 1) * 2 ^ b \<le> n" proof - let ?al = "(n + (2 ^ b - 1)) div 2 ^ b" have sub1: "0 < n \<Longrightarrow> (?al - 1) * 2 ^ b < n" apply (cases "?al = 0") apply simp apply (simp add: diff_mult_distrib) apply (rule nat_diff_less2, simp_all) apply (rule order_le_less_trans, rule div_mult_le) apply simp done have le1: "(n + 2 ^ b - Suc 0) div 2 ^ b * 2 ^ b \<le> 2 ^ a" apply (rule alignUp_le_nat[simplified], simp_all add: n) apply (simp add: b le_imp_power_dvd) done note le2 = div_le_mono[OF le1, where k="2 ^ b", simplified] show ?thesis apply (cases "n = 0") apply (simp add: exI[where x=0]) apply (rule exI[where x="?al"]) apply (strengthen filter_upt_eq) apply (simp add: linorder_not_less conj.commute) apply (simp add: alignUp_ge_nat[simplified] sub1[simplified] sub1[THEN order_less_imp_le, simplified] power_minus_is_div[OF b] le1 le2) apply (auto elim: order_le_less_trans[rotated]) done qed lemma delete_objects_ex_cte_cap_wp_to: notes untyped_range.simps[simp del] shows "\<lbrace>ex_cte_cap_wp_to P slot and invs and cte_wp_at (\<lambda>cp. is_untyped_cap cp \<and> {ptr_base .. ptr_base + 2 ^ sz - 1} \<subseteq> untyped_range cp) src_slot and (\<lambda>s. descendants_of src_slot (cdt s) = {})\<rbrace> delete_objects ptr_base sz \<lbrace>\<lambda>rv s. ex_cte_cap_wp_to P slot s\<rbrace>" apply (simp add: delete_objects_def ex_cte_cap_wp_to_def) apply (rule hoare_pre) apply (rule hoare_lift_Pf2 [where f="interrupt_irq_node"]) apply (wp hoare_vcg_ex_lift | simp)+ apply (clarsimp simp: cte_wp_at_caps_of_state) apply (intro exI conjI, assumption+) apply (frule if_unsafe_then_capD[OF caps_of_state_cteD], clarsimp+) apply (case_tac "the (caps_of_state s src_slot)", simp_all) apply (frule ex_cte_cap_protects, simp add: cte_wp_at_caps_of_state, rule empty_descendants_range_in, (assumption | clarsimp)+) done lemma do_machine_op_ex_cte_cap_wp_to[wp]: "\<lbrace>ex_cte_cap_wp_to P slot\<rbrace> do_machine_op oper \<lbrace>\<lambda>rv s. ex_cte_cap_wp_to P slot s\<rbrace>" apply (simp add: do_machine_op_def split_def) apply wp apply (clarsimp simp: ex_cte_cap_wp_to_def) done lemma delete_objects_real_cte_at[wp]: "\<lbrace>\<lambda>s. real_cte_at p s \<and> fst p \<notin> {ptr_base .. ptr_base + 2 ^ sz - 1}\<rbrace> delete_objects ptr_base sz \<lbrace>\<lambda>rv. real_cte_at p\<rbrace>" by (wp | simp add: delete_objects_def)+ lemma delete_objects_ct_in_state[wp]: "\<lbrace>\<lambda>s. ct_in_state P s \<and> cur_thread s \<notin> {ptr_base .. ptr_base + 2 ^ sz - 1}\<rbrace> delete_objects ptr_base sz \<lbrace>\<lambda>rv. ct_in_state P\<rbrace>" apply (rule hoare_pre) apply (wp | simp add: delete_objects_def ct_in_state_def st_tcb_at_def | simp add: detype_def)+ apply (rule hoare_lift_Pf2[where f=cur_thread]) apply wp+ apply (clarsimp simp: ct_in_state_def st_tcb_at_def) done (* FIXME: move? *) lemma pspace_no_overlap_subset: "pspace_no_overlap S s \<Longrightarrow> T \<subseteq> S \<Longrightarrow> pspace_no_overlap T s" by (clarsimp simp: pspace_no_overlap_def disjoint_subset2) crunch cur_thread[wp]: delete_objects "\<lambda>s. P (cur_thread s)" (simp: detype_def) lemma ct_in_state_trans_state[simp]: "ct_in_state P (trans_state a s) = ct_in_state P s" by (simp add: ct_in_state_def) lemmas unat_of_nat_word_bits = unat_of_nat_eq[where 'a = machine_word_len, unfolded word_bits_len_of, simplified] lemma caps_of_state_pspace_no_overlapD: "\<lbrakk> caps_of_state s cref = Some (cap.UntypedCap dev ptr sz idx); invs s; idx < 2 ^ sz \<rbrakk> \<Longrightarrow> pspace_no_overlap_range_cover (ptr + of_nat idx) sz s" apply (frule(1) caps_of_state_valid) apply (clarsimp simp: valid_cap_simps cap_aligned_def) apply (cut_tac neg_mask_add_aligned[where p=ptr and q="of_nat idx" and n=sz]) apply (rule cte_wp_at_pspace_no_overlapI[where idx=idx and cref=cref], simp_all) apply (simp add: cte_wp_at_caps_of_state) apply (simp add: mask_out_sub_mask) apply (subst unat_of_nat_word_bits, erule order_less_le_trans, simp_all) apply (rule word_of_nat_less) apply (erule order_less_le_trans) apply simp done lemma set_untyped_cap_invs_simple: "\<lbrace>\<lambda>s. descendants_range_in {ptr .. ptr+2^sz - 1} cref s \<and> pspace_no_overlap_range_cover ptr sz s \<and> invs s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> cap_is_device c = dev\<and> obj_ref_of c = ptr) cref s \<and> idx \<le> 2^ sz\<rbrace> set_cap (cap.UntypedCap dev ptr sz idx) cref \<lbrace>\<lambda>rv s. invs s\<rbrace>" apply (rule hoare_name_pre_state) apply (clarsimp simp:cte_wp_at_caps_of_state invs_def valid_state_def) apply (rule hoare_pre) apply (wp set_free_index_valid_pspace_simple set_cap_valid_mdb_simple set_cap_idle update_cap_ifunsafe set_cap_valid_arch_caps_simple) apply (simp add:valid_irq_node_def) apply wps apply (wp hoare_vcg_all_lift set_cap_irq_handlers set_cap_irq_handlers cap_table_at_lift_valid set_cap_ioports' set_cap_typ_at set_cap_valid_arch_caps_simple set_cap_kernel_window_simple set_cap_cap_refs_respects_device_region) apply (clarsimp simp del: split_paired_Ex) apply (strengthen exI[where x=cref]) apply (clarsimp simp:cte_wp_at_caps_of_state is_cap_simps valid_pspace_def) apply (intro conjI; clarsimp?) apply (clarsimp simp: fun_eq_iff) apply (clarsimp split:cap.splits simp:is_cap_simps appropriate_cte_cap_def) apply (drule(1) if_unsafe_then_capD[OF caps_of_state_cteD]) apply clarsimp apply (clarsimp simp: is_cap_simps ex_cte_cap_wp_to_def appropriate_cte_cap_def cte_wp_at_caps_of_state) apply (clarsimp dest!:valid_global_refsD2 simp:cap_range_def) apply (simp add:valid_irq_node_def) apply (clarsimp simp:valid_irq_node_def) apply (clarsimp intro!: safe_ioport_insert_triv simp: is_cap_simps) done lemma reset_untyped_cap_invs_etc: "\<lbrace>invs and valid_untyped_inv_wcap ui (Some (UntypedCap dev ptr sz idx)) and ct_active and K (\<exists>ptr_base ptr' ty us slots. ui = Retype slot True ptr_base ptr' ty us slots dev)\<rbrace> reset_untyped_cap slot \<lbrace>\<lambda>_. invs and valid_untyped_inv_wcap ui (Some (UntypedCap dev ptr sz 0)) and ct_active and pspace_no_overlap {ptr .. ptr + 2 ^ sz - 1}\<rbrace>, \<lbrace>\<lambda>_. invs\<rbrace>" (is "\<lbrace>invs and valid_untyped_inv_wcap ?ui (Some ?cap) and ct_active and _\<rbrace> ?f \<lbrace>\<lambda>_. invs and ?vu2 and ct_active and ?psp\<rbrace>, \<lbrace>\<lambda>_. invs\<rbrace>") apply (simp add: reset_untyped_cap_def) apply (rule hoare_vcg_seqE[rotated]) apply ((wp (once) get_cap_sp)+)[1] apply (rule hoare_name_pre_stateE) apply (clarsimp simp: cte_wp_at_caps_of_state bits_of_def split del: if_split) apply (subgoal_tac "is_aligned ptr sz") prefer 2 apply (frule caps_of_state_valid_cap, clarsimp) apply auto[1] apply (cases "idx = 0") apply (clarsimp simp: free_index_of_def) apply wp apply clarsimp apply (frule(1) caps_of_state_pspace_no_overlapD, simp+) apply (simp add: word_bw_assocs field_simps) apply (clarsimp simp: free_index_of_def split del: if_split) apply (rule_tac B="\<lambda>_. invs and valid_untyped_inv_wcap ?ui (Some ?cap) and ct_active and ?psp" in hoare_vcg_seqE[rotated]) apply clarsimp apply (rule hoare_pre) apply (wp hoare_vcg_ex_lift hoare_vcg_const_Ball_lift delete_objects_ex_cte_cap_wp_to[where src_slot=slot] ) apply (clarsimp simp: cte_wp_at_caps_of_state ct_in_state_def) apply (frule if_unsafe_then_capD[OF caps_of_state_cteD], clarsimp+) apply (drule(1) ex_cte_cap_protects[OF _ caps_of_state_cteD _ _ order_refl]) apply (simp add: empty_descendants_range_in) apply clarsimp+ apply (strengthen ballEI[mk_strg I E] refl) apply (strengthen exI[where x="fst slot"], strengthen exI[where x="snd slot"]) apply (strengthen ex_cte_cap_protects[OF _ caps_of_state_cteD _ _ order_refl, mk_strg D E]) apply (simp add: empty_descendants_range_in invs_untyped_children invs_valid_global_refs descendants_range_def bits_of_def) apply (strengthen refl) apply (drule st_tcb_ex_cap, clarsimp, fastforce) apply (drule ex_nonz_cap_to_overlap[where p=slot], (simp add: cte_wp_at_caps_of_state descendants_range_def)+) apply (drule caps_of_state_valid_cap | clarify)+ apply (intro conjI; clarify?; blast)[1] apply (cases "dev \<or> sz < resetChunkBits") apply (simp add: bits_of_def) apply (simp add: unless_def) apply (rule hoare_pre) apply (wp set_untyped_cap_invs_simple set_cap_cte_wp_at set_cap_no_overlap hoare_vcg_const_Ball_lift set_cap_cte_cap_wp_to ct_in_state_thread_state_lift) apply (strengthen empty_descendants_range_in) apply (rule hoare_lift_Pf2 [where f="interrupt_irq_node"]) apply (wp hoare_vcg_const_Ball_lift hoare_vcg_const_imp_lift hoare_vcg_ex_lift ct_in_state_thread_state_lift)+ apply (clarsimp simp add: bits_of_def field_simps cte_wp_at_caps_of_state empty_descendants_range_in) apply (cut_tac a=sz and b=resetChunkBits and n=idx in upt_mult_lt_prop) apply (frule caps_of_state_valid_cap, clarsimp+) apply (simp add: valid_cap_def) apply simp apply (clarsimp simp: bits_of_def free_index_of_def) apply (rule hoare_pre, rule hoare_post_impErr, rule_tac P="\<lambda>i. invs and ?psp and ct_active and valid_untyped_inv_wcap ?ui (Some (UntypedCap dev ptr sz (if i = 0 then idx else (bd - i) * 2 ^ resetChunkBits)))" and E="\<lambda>_. invs" in mapME_x_validE_nth) apply (rule hoare_pre) apply (wp set_untyped_cap_invs_simple set_cap_no_overlap set_cap_cte_wp_at preemption_point_inv hoare_vcg_ex_lift hoare_vcg_const_imp_lift hoare_vcg_const_Ball_lift set_cap_cte_cap_wp_to | strengthen empty_descendants_range_in | simp | rule irq_state_independent_A_conjI | simp add: cte_wp_at_caps_of_state | wp (once) ct_in_state_thread_state_lift | (rule irq_state_independent_A_def[THEN meta_eq_to_obj_eq, THEN iffD2], simp add: ex_cte_cap_wp_to_def ct_in_state_def))+ apply (clarsimp simp: bits_of_def field_simps cte_wp_at_caps_of_state nth_rev) apply (strengthen order_trans[where z="2 ^ sz", rotated, mk_strg I E]) apply (clarsimp split: if_split_asm) apply auto[1] apply (auto elim: order_trans[rotated])[1] apply (clarsimp simp: cte_wp_at_caps_of_state split: if_split_asm) apply simp apply (clarsimp simp: cte_wp_at_caps_of_state) done lemma get_cap_prop_known: "\<lbrace>cte_wp_at (\<lambda>cp. f cp = v) slot and Q v\<rbrace> get_cap slot \<lbrace>\<lambda>rv. Q (f rv)\<rbrace>" apply (wp get_cap_wp) apply (clarsimp simp: cte_wp_at_caps_of_state) done lemma reset_untyped_cap_pred_tcb_at: "\<lbrace>invs and pred_tcb_at proj P t and cte_wp_at (\<lambda>cp. t \<notin> cap_range cp \<and> is_untyped_cap cp) slot\<rbrace> reset_untyped_cap slot \<lbrace>\<lambda>_. pred_tcb_at proj P t\<rbrace>, \<lbrace>\<lambda>_. pred_tcb_at proj P t\<rbrace>" apply (simp add: reset_untyped_cap_def) apply (rule hoare_pre) apply (wp mapME_x_inv_wp preemption_point_inv | simp add: unless_def)+ apply (simp add: delete_objects_def) apply (wp get_cap_wp hoare_vcg_const_imp_lift | simp)+ apply (auto simp: cte_wp_at_caps_of_state cap_range_def bits_of_def is_cap_simps) done lemma create_cap_iflive[wp]: "\<lbrace>if_live_then_nonz_cap and cte_wp_at ((=) cap.NullCap) cref\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. if_live_then_nonz_cap\<rbrace>" apply (simp add: create_cap_def) apply (wp new_cap_iflive set_cdt_cte_wp_at | simp)+ done crunch cap_to_again[wp]: set_cdt "ex_cte_cap_wp_to P p" (simp: ex_cte_cap_wp_to_def) lemma create_cap_ifunsafe[wp]: "\<lbrace>if_unsafe_then_cap and ex_cte_cap_wp_to (appropriate_cte_cap (default_cap tp oref sz dev)) cref and cte_wp_at ((=) cap.NullCap) cref\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. if_unsafe_then_cap\<rbrace>" apply (simp add: create_cap_def) apply (wp new_cap_ifunsafe set_cdt_cte_wp_at | simp)+ done lemma set_cdt_state_refs_of[wp]: "\<lbrace>\<lambda>s. P (state_refs_of s)\<rbrace> set_cdt m \<lbrace>\<lambda>rv s. P (state_refs_of s)\<rbrace>" apply (simp add: set_cdt_def) apply wp apply (clarsimp elim!: state_refs_of_pspaceI) done lemma set_cdt_state_hyp_refs_of[wp]: "\<lbrace>\<lambda>s. P (state_hyp_refs_of s)\<rbrace> set_cdt m \<lbrace>\<lambda>rv s. P (state_hyp_refs_of s)\<rbrace>" apply (simp add: set_cdt_def) apply wp apply (clarsimp elim!: state_hyp_refs_of_pspaceI) done lemma state_refs_of_rvk[simp]: "state_refs_of (is_original_cap_update f s) = state_refs_of s" by (simp add: state_refs_of_def) lemma create_cap_state_refs_of[wp]: "\<lbrace>\<lambda>s. P (state_refs_of s)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv s. P (state_refs_of s)\<rbrace>" unfolding create_cap_def by wpsimp lemma create_cap_state_hyp_refs_of[wp]: "\<lbrace>\<lambda>s. P (state_hyp_refs_of s)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv s. P (state_hyp_refs_of s)\<rbrace>" apply (simp add: create_cap_def) apply (wp | simp)+ done lemma create_cap_zombies[wp]: "\<lbrace>zombies_final and cte_wp_at ((=) cap.NullCap) cref and (\<lambda>s. \<forall>r\<in>obj_refs (default_cap tp oref sz dev). \<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> obj_refs cap) p' s)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. zombies_final\<rbrace>" unfolding create_cap_def set_cdt_def by (wpsimp wp: new_cap_zombies) lemma create_cap_cur_tcb[wp]: "\<lbrace>cur_tcb\<rbrace> create_cap tp sz p dev tup \<lbrace>\<lambda>rv. cur_tcb\<rbrace>" unfolding create_cap_def split_def set_cdt_def by wpsimp lemma create_cap_valid_idle[wp]: "\<lbrace>valid_idle\<rbrace> create_cap tp sz p dev tup \<lbrace>\<lambda>rv. valid_idle\<rbrace>" unfolding create_cap_def split_def set_cdt_def by (wpsimp wp: set_cap_idle) crunch it[wp]: create_cap "\<lambda>s. P (idle_thread s)" (simp: crunch_simps) lemma default_cap_reply: "default_cap tp ptr sz dev \<noteq> cap.ReplyCap ptr' bool R" by (cases tp; simp) lemma create_cap_valid_reply_caps[wp]: "\<lbrace>valid_reply_caps\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_reply_caps\<rbrace>" apply (simp add: valid_reply_caps_def has_reply_cap_def cte_wp_at_caps_of_state create_cap_def is_reply_cap_to_def set_cdt_def) apply (simp only: imp_conv_disj) apply (rule hoare_pre) apply (wp hoare_vcg_all_lift hoare_vcg_disj_lift | simp)+ apply (clarsimp simp: default_cap_reply) apply (erule conjI [OF allEI], fastforce) apply (simp add: unique_reply_caps_def default_cap_reply) done lemma create_cap_valid_reply_masters[wp]: "\<lbrace>valid_reply_masters\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_reply_masters\<rbrace>" apply (simp add: valid_reply_masters_def cte_wp_at_caps_of_state create_cap_def is_master_reply_cap_to_def) apply (wp | simp add: default_cap_reply)+ done lemma create_cap_valid_global_refs[wp]: "\<lbrace>valid_global_refs and cte_wp_at (\<lambda>c. cap_range (default_cap tp oref sz dev) \<subseteq> cap_range c) p\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_global_refs\<rbrace>" apply (simp add: valid_global_refs_def valid_refs_def cte_wp_at_caps_of_state create_cap_def pred_conj_def) apply (simp only: imp_conv_disj) apply (wpsimp wp: hoare_vcg_all_lift hoare_vcg_disj_lift) apply (subgoal_tac "global_refs s \<inter> cap_range (default_cap tp oref sz dev) = {}") apply auto[1] apply (erule disjoint_subset2) apply (cases p, simp) done crunch arch_state[wp]: create_cap "\<lambda>s. P (arch_state s)" (simp: crunch_simps) lemma create_cap_aobj_at: "arch_obj_pred P' \<Longrightarrow> \<lbrace>\<lambda>s. P (obj_at P' pd s)\<rbrace> create_cap type bits ut is_dev cref \<lbrace>\<lambda>r s. P (obj_at P' pd s)\<rbrace>" unfolding create_cap_def split_def set_cdt_def by (wpsimp wp: set_cap.aobj_at) lemma create_cap_valid_arch_state[wp]: "\<lbrace>valid_arch_state\<rbrace> create_cap type bits ut is_dev cref \<lbrace>\<lambda>_. valid_arch_state\<rbrace>" by (wp valid_arch_state_lift_aobj_at create_cap_aobj_at) crunch irq_node[wp]: create_cap "\<lambda>s. P (interrupt_irq_node s)" (simp: crunch_simps) lemmas create_cap_valid_irq_node[wp] = valid_irq_node_typ [OF create_cap_typ_at create_cap_irq_node] lemma default_cap_irqs[simp]: "cap_irqs (default_cap tp oref sz dev) = {}" by (cases tp, simp_all) lemma create_cap_irq_handlers[wp]: "\<lbrace>valid_irq_handlers\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_irq_handlers\<rbrace>" apply (simp add: valid_irq_handlers_def irq_issued_def) apply (simp add: create_cap_def Ball_def) apply (simp only: imp_conv_disj) apply (wpsimp wp: hoare_vcg_all_lift hoare_vcg_disj_lift) apply (auto simp: ran_def split: if_split_asm) done crunch valid_vspace_objs[wp]: create_cap "valid_vspace_objs" (simp: crunch_simps) locale Untyped_AI_nonempty_table = fixes state_ext_t :: "('state_ext::state_ext) itself" fixes nonempty_table :: "machine_word set \<Rightarrow> Structures_A.kernel_object \<Rightarrow> bool" assumes create_cap_valid_arch_caps[wp]: "\<And>tp oref sz dev cref p.\<lbrace>valid_arch_caps and valid_cap (default_cap tp oref sz dev) and (\<lambda>(s::'state_ext state). \<forall>r\<in>obj_refs (default_cap tp oref sz dev). (\<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> obj_refs cap) p' s) \<and> \<not> obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) and cte_wp_at ((=) cap.NullCap) cref and K (tp \<noteq> ArchObject ASIDPoolObj)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_arch_caps\<rbrace>" assumes create_cap_cap_refs_in_kernel_window[wp]: "\<And>tp oref sz p dev cref.\<lbrace>cap_refs_in_kernel_window and cte_wp_at (\<lambda>c. cap_range (default_cap tp oref sz dev) \<subseteq> cap_range c) p\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. (cap_refs_in_kernel_window::'state_ext state \<Rightarrow> bool)\<rbrace>" assumes nonempty_default[simp]: "\<And>tp S us dev. tp \<noteq> Untyped \<Longrightarrow> \<not> nonempty_table S (default_object tp dev us)" assumes nonempty_table_caps_of: "\<And>S ko. nonempty_table S ko \<Longrightarrow> caps_of ko = {}" assumes init_arch_objects_nonempty_table: "\<lbrace>(\<lambda>s. \<not> (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) \<and> valid_global_objs s \<and> valid_arch_state s \<and> pspace_aligned s) and K (\<forall>ref\<in>set refs. is_aligned ref (obj_bits_api tp us))\<rbrace> init_arch_objects tp ptr bits us refs \<lbrace>\<lambda>rv. \<lambda>s :: 'state_ext state. \<not> (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s)\<rbrace>" assumes create_cap_ioports[wp]: "\<And>tp oref sz dev cref p. \<lbrace>valid_ioports and cte_wp_at (\<lambda>_. True) cref\<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>\<lambda>rv (s::'state_ext state). valid_ioports s\<rbrace>" crunch v_ker_map[wp]: create_cap "valid_kernel_mappings" (simp: crunch_simps) crunch eq_ker_map[wp]: create_cap "equal_kernel_mappings" (simp: crunch_simps) lemma create_cap_asid_map[wp]: "\<lbrace>valid_asid_map\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. valid_asid_map\<rbrace>" unfolding create_cap_def set_cdt_def by wpsimp crunch only_idle[wp]: create_cap only_idle (simp: crunch_simps) crunch pspace_in_kernel_window[wp]: create_cap "pspace_in_kernel_window" (simp: crunch_simps) lemma set_original_valid_ioc[wp]: "\<lbrace>valid_ioc\<rbrace> create_cap tp sz p dev slot \<lbrace>\<lambda>_. valid_ioc\<rbrace>" apply (cases slot) apply (wpsimp wp: set_cdt_cos_ioc set_cap_caps_of_state simp: create_cap_def set_original_set_cap_comm cte_wp_at_caps_of_state) apply (cases tp; simp) done interpretation create_cap: non_vspace_non_mem_op "create_cap tp sz p slot dev" apply (cases slot) apply (simp add: create_cap_def set_cdt_def) apply unfold_locales apply (rule hoare_pre, (wp set_cap.vsobj_at | wpc |simp add: create_cap_def set_cdt_def bind_assoc)+)+ done (* by (wp set_cap.vsobj_at | simp)+ *) (* ARMHYP might need this *) crunch valid_irq_states[wp]: create_cap "valid_irq_states" crunch pspace_respects_device_region[wp]: create_cap pspace_respects_device_region lemma cap_range_subseteq_weaken: "\<lbrakk>obj_refs c \<subseteq> untyped_range cap; untyped_range c \<subseteq> untyped_range cap\<rbrakk> \<Longrightarrow> cap_range c \<subseteq> cap_range cap" by (fastforce simp add: cap_range_def) lemma create_cap_refs_respects_device: "\<lbrace>cap_refs_respects_device_region and cte_wp_at (\<lambda>c. cap_is_device (default_cap tp oref sz dev) = cap_is_device c \<and>is_untyped_cap c \<and> cap_range (default_cap tp oref sz dev) \<subseteq> cap_range c) p\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv s. cap_refs_respects_device_region s\<rbrace>" apply (simp add: create_cap_def) apply (rule hoare_pre) apply (wp set_cap_cap_refs_respects_device_region hoare_vcg_ex_lift set_cdt_cte_wp_at | simp del: split_paired_Ex)+ apply (rule_tac x = p in exI) apply clarsimp apply (erule cte_wp_at_weakenE) apply (fastforce simp: is_cap_simps) done lemma (in Untyped_AI_nonempty_table) create_cap_invs[wp]: "\<lbrace>invs and cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_is_device (default_cap tp oref sz dev) = cap_is_device c \<and> obj_refs (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> untyped_range (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> untyped_range (default_cap tp oref sz dev) \<inter> usable_untyped_range c = {}) p and descendants_range (default_cap tp oref sz dev) p and cte_wp_at ((=) cap.NullCap) cref and valid_cap (default_cap tp oref sz dev) and ex_cte_cap_wp_to (appropriate_cte_cap (default_cap tp oref sz dev)) cref and real_cte_at cref and (\<lambda>(s::'state_ext state). \<forall>r\<in>obj_refs (default_cap tp oref sz dev). (\<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> obj_refs cap) p' s) \<and> \<not> obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) and K (p \<noteq> cref \<and> tp \<noteq> ArchObject ASIDPoolObj)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. invs\<rbrace>" apply (rule hoare_pre) apply (simp add: invs_def valid_state_def valid_pspace_def) apply (wp create_cap_refs_respects_device | simp add: valid_cap_def)+ apply clarsimp apply (clarsimp simp: cte_wp_at_caps_of_state valid_pspace_def) apply (frule_tac p1 = p in valid_cap_aligned[OF caps_of_state_valid]) apply simp apply (simp add: invs_def valid_state_def valid_pspace_def ) apply (simp add: cap_range_def) done lemma create_cap_ex_cap_to[wp]: "\<lbrace>ex_cte_cap_wp_to P p' and cte_wp_at ((=) cap.NullCap) cref\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv. ex_cte_cap_wp_to P p'\<rbrace>" apply (simp add: create_cap_def) apply (wp set_cap_cte_cap_wp_to set_cdt_cte_wp_at | simp | wps set_cdt_irq_node)+ apply (clarsimp elim!: cte_wp_at_weakenE) done (* FIXME: move *) lemma hoare_vcg_split_lift[wp]: "\<lbrace>P\<rbrace> f x y \<lbrace>Q\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> case (x, y) of (a, b) \<Rightarrow> f a b \<lbrace>Q\<rbrace>" by simp lemma create_cap_no_cap[wp]: "\<lbrace>\<lambda>s. (\<forall>p'. \<not> cte_wp_at P p' s) \<and> \<not> P (default_cap tp oref sz dev)\<rbrace> create_cap tp sz p dev (cref, oref) \<lbrace>\<lambda>rv s. \<forall>oref' cref'. \<not> cte_wp_at P (oref', cref') s\<rbrace>" unfolding create_cap_def cte_wp_at_caps_of_state by wpsimp lemma (in Untyped_AI_nonempty_table) create_cap_nonempty_tables[wp]: "\<lbrace>\<lambda>s. P (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) p s)\<rbrace> create_cap tp sz p' dev (cref, oref) \<lbrace>\<lambda>rv s. P (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) p s)\<rbrace>" apply (rule hoare_pre) apply (rule hoare_use_eq [where f=arch_state, OF create_cap_arch_state]) apply (simp add: create_cap_def set_cdt_def) apply (wp set_cap_obj_at_impossible|simp)+ apply (clarsimp simp: nonempty_table_caps_of) done lemma cap_range_not_untyped: "\<not> is_untyped_cap c \<Longrightarrow> cap_range c = obj_refs c" apply (case_tac c) apply (simp_all add: is_cap_simps cap_range_def) done lemma cap_range_inter_emptyI: "\<lbrakk>is_untyped_cap a = is_untyped_cap b; untyped_range a \<inter> untyped_range b ={}; obj_refs a \<inter> obj_refs b = {}\<rbrakk> \<Longrightarrow> cap_range a \<inter> cap_range b = {}" apply (case_tac "is_untyped_cap a") apply (simp_all add: cap_range_not_untyped) done lemma (in Untyped_AI_nonempty_table) create_caps_invs_inv: assumes create_cap_Q[wp]: "\<lbrace>invs and Q and cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_range (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> {oref .. oref + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c) p and cte_wp_at ((=) NullCap) cref and valid_cap (default_cap tp oref sz dev)\<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>\<lambda>_. Q \<rbrace>" shows "\<lbrace>(\<lambda>s. invs (s::('state_ext::state_ext) state) \<and> Q s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_is_device tp dev = cap_is_device c) p s \<and> (\<forall>tup \<in> set ((cref,oref)#list). cte_wp_at (\<lambda>c. cap_range (default_cap tp (snd tup) sz dev) \<subseteq> untyped_range c \<and> {snd tup .. snd tup + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c \<and> (untyped_range (default_cap tp (snd tup) sz dev) \<inter> usable_untyped_range c = {})) p s) \<and> (\<forall>tup \<in> set ((cref,oref)#list). descendants_range (default_cap tp (snd tup) sz dev) p s) \<and> distinct_sets (map (\<lambda>tup. cap_range (default_cap tp (snd tup) sz dev)) ((cref,oref)#list)) \<and> (\<forall>tup \<in> set ((cref,oref)#list). cte_wp_at ((=) cap.NullCap) (fst tup) s) \<and> (\<forall>tup \<in> set ((cref,oref)#list). valid_cap (default_cap tp (snd tup) sz dev) s) \<and> (\<forall>tup \<in> set ((cref,oref)#list). ex_cte_cap_wp_to is_cnode_cap (fst tup) s) \<and> (\<forall>tup \<in> set ((cref,oref)#list). real_cte_at (fst tup) s) \<and> (\<forall>tup \<in> set ((cref,oref)#list). \<forall>r \<in> obj_refs (default_cap tp (snd tup) sz dev). (\<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> Structures_A.obj_refs cap) p' s) \<and> \<not> obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) \<and> distinct (p # (map fst ((cref,oref)#list))) \<and> tp \<noteq> ArchObject ASIDPoolObj) \<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>(\<lambda>r s. invs s \<and> Q s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_is_device tp dev = cap_is_device c) p s \<and> (\<forall>tup \<in> set list. cte_wp_at (\<lambda>c. cap_range (default_cap tp (snd tup) sz dev) \<subseteq> untyped_range c \<and> {snd tup .. snd tup + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c \<and> (untyped_range (default_cap tp (snd tup) sz dev) \<inter> usable_untyped_range c = {})) p s) \<and> (\<forall>tup \<in> set list. descendants_range (default_cap tp (snd tup) sz dev) p s) \<and> distinct_sets (map (\<lambda>tup. cap_range (default_cap tp (snd tup) sz dev)) list) \<and> (\<forall>tup \<in> set list. cte_wp_at ((=) cap.NullCap) (fst tup) s) \<and> (\<forall>tup \<in> set list. valid_cap (default_cap tp (snd tup) sz dev) s) \<and> (\<forall>tup \<in> set list. ex_cte_cap_wp_to is_cnode_cap (fst tup) s) \<and> (\<forall>tup \<in> set list. real_cte_at (fst tup) s) \<and> (\<forall>tup \<in> set list. \<forall>r \<in> obj_refs (default_cap tp (snd tup) sz dev). (\<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> Structures_A.obj_refs cap) p' s) \<and> \<not> obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) \<and> distinct (p # (map fst list)) \<and> tp \<noteq> ArchObject ASIDPoolObj) \<rbrace>" apply (rule hoare_pre) apply (wp hoare_vcg_const_Ball_lift | clarsimp)+ apply (clarsimp simp: conj_comms invs_mdb distinct_sets_prop distinct_prop_map ex_cte_cap_to_cnode_always_appropriate_strg) apply (simp add: cte_wp_at_caps_of_state[where p=p] | erule exE conjE)+ apply (intro conjI) apply (clarsimp simp:image_def) apply (drule(1) bspec)+ apply simp apply (fastforce simp:cap_range_def) apply (clarsimp simp:is_cap_simps) apply (simp only: UN_extend_simps UNION_empty_conv) apply (drule(1) bspec)+ apply clarsimp apply blast apply (clarsimp simp: cap_range_def) apply (clarsimp simp: cap_range_def) done lemma (in Untyped_AI_nonempty_table) create_caps_invs: assumes create_cap_Q[wp]: "\<And>cref oref. \<lbrace>invs and Q and cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_range (default_cap tp oref sz dev) \<subseteq> untyped_range c \<and> {oref .. oref + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c) p and cte_wp_at ((=) NullCap) cref and valid_cap (default_cap tp oref sz dev) and K (cref \<in> set crefs \<and> oref \<in> set (retype_addrs ptr tp (length slots) us))\<rbrace> create_cap tp sz p dev (cref,oref) \<lbrace>\<lambda>_. Q \<rbrace>" shows "\<lbrace>(\<lambda>s. invs (s::('state_ext::state_ext) state) \<and> (Q::('state_ext::state_ext) state \<Rightarrow> bool) s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> obj_is_device tp dev = cap_is_device c) p s \<and> (\<forall>tup \<in> set (zip crefs orefs). cte_wp_at (\<lambda>c. cap_range (default_cap tp (snd tup) sz dev) \<subseteq> untyped_range c \<and> {snd tup .. snd tup + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c \<and> (untyped_range (default_cap tp (snd tup) sz dev) \<inter> usable_untyped_range c = {})) p s) \<and> (\<forall>tup \<in> set (zip crefs orefs). descendants_range (default_cap tp (snd tup) sz dev) p s) \<and> distinct_sets (map (\<lambda>tup. cap_range (default_cap tp (snd tup) sz dev)) (zip crefs orefs)) \<and> (\<forall>tup \<in> set (zip crefs orefs). cte_wp_at ((=) cap.NullCap) (fst tup) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). valid_cap (default_cap tp (snd tup) sz dev) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). ex_cte_cap_wp_to is_cnode_cap (fst tup) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). real_cte_at (fst tup) s) \<and> (\<forall>tup \<in> set (zip crefs orefs). \<forall>r \<in> obj_refs (default_cap tp (snd tup) sz dev). (\<forall>p'. \<not> cte_wp_at (\<lambda>cap. r \<in> Structures_A.obj_refs cap) p' s) \<and> \<not> obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s) \<and> distinct (p # (map fst (zip crefs orefs))) \<and> tp \<noteq> ArchObject ASIDPoolObj) and K (set orefs \<subseteq> set (retype_addrs ptr tp (length slots) us))\<rbrace> mapM_x (create_cap tp sz p dev) (zip crefs orefs) \<lbrace>\<lambda>rv s. invs s \<and> Q s\<rbrace>" apply (rule hoare_gen_asm) apply (subgoal_tac "set (zip crefs orefs) \<subseteq> set crefs \<times> set (retype_addrs ptr tp (length slots) us)") prefer 2 apply (auto dest!: set_zip_helper)[1] apply (induct ("zip crefs orefs")) apply (simp add: mapM_x_def sequence_x_def) apply wpsimp apply (clarsimp simp add: mapM_x_def sequence_x_def) apply (rule hoare_seq_ext) apply assumption apply (thin_tac "valid a b c" for a b c) apply (rule hoare_pre) apply (rule hoare_strengthen_post) apply (rule_tac list=list and us=us in create_caps_invs_inv) apply (rule hoare_pre, rule create_cap_Q) apply (clarsimp | drule(1) bspec)+ done lemma retype_region_cte_at_other': "\<lbrace>pspace_no_overlap_range_cover ptr sz and cte_wp_at P p and valid_pspace and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. cte_wp_at P p\<rbrace>" apply (rule hoare_gen_asm) apply (wpsimp wp: retype_region_cte_at_other) done lemma retype_region_ex_cte_cap_to: "\<lbrace>pspace_no_overlap_range_cover ptr sz and ex_cte_cap_wp_to P p and valid_pspace and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv. ex_cte_cap_wp_to P p\<rbrace>" apply (simp add: ex_cte_cap_wp_to_def) apply (wp hoare_vcg_ex_lift retype_region_cte_at_other' | wps retype_region_irq_node)+ apply auto done lemma retype_region_obj_ref_range: "\<lbrakk> \<And>r. \<lbrace>P r\<rbrace> retype_region ptr n us ty dev\<lbrace>\<lambda>rv. Q r\<rbrace> \<rbrakk> \<Longrightarrow> \<lbrace>(\<lambda>s. \<forall>r \<in> {ptr .. (ptr && ~~ mask sz) + 2 ^ sz - 1}. P r s) and K (range_cover ptr sz (obj_bits_api ty us) n)\<rbrace> retype_region ptr n us ty dev \<lbrace>\<lambda>rv s. \<forall>x \<in> set rv. \<forall>r \<in> obj_refs (default_cap tp x us dev). Q r s\<rbrace>" apply (rule hoare_gen_asm) apply (rule hoare_strengthen_post) apply (rule hoare_vcg_conj_lift [OF retype_region_ret, simplified]) apply (rule hoare_vcg_const_Ball_lift) apply assumption apply (clarsimp) apply (drule subsetD[OF obj_refs_default_cap]) apply (drule_tac x = r in bspec) apply (simp add: ptr_add_def) apply (drule(1) range_cover_mem) apply simp apply simp done lemma retype_region_not_cte_wp_at: "\<lbrace>(\<lambda>s. \<not> cte_wp_at P p s) and valid_pspace and caps_overlap_reserved {ptr..ptr + of_nat n * 2 ^ obj_bits_api tp us - 1} and valid_mdb and pspace_no_overlap_range_cover ptr sz and caps_no_overlap ptr sz and (\<lambda>s. \<exists>cref. cte_wp_at (\<lambda>c. up_aligned_area ptr sz \<subseteq> cap_range c \<and> cap_is_device c = dev) cref s) and K (\<not> P cap.NullCap \<and> (tp = CapTableObject \<longrightarrow> 0 < us) \<and> range_cover ptr sz (obj_bits_api tp us) n)\<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. \<not> cte_wp_at P p s\<rbrace>" apply (rule hoare_gen_asm) apply (clarsimp simp: P_null_filter_caps_of_cte_wp_at[symmetric]) apply (wpsimp wp: retype_region_caps_of) apply auto done lemma retype_region_refs_distinct[wp]: "\<lbrace>K (range_cover ptr sz (obj_bits_api tp us) n)\<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. distinct_prop (\<lambda>x y. obj_refs (default_cap tp (snd x) us dev) \<inter> obj_refs (default_cap tp (snd y) us dev) = {}) (zip xs rv)\<rbrace>" apply simp apply (rule hoare_gen_asm[where P'="\<top>", simplified]) apply (rule hoare_strengthen_post [OF retype_region_ret]) apply (subst distinct_prop_map[symmetric, where f=snd]) apply (rule distinct_prop_prefixE [OF _ map_snd_zip_prefix [unfolded less_eq_list_def]]) apply (clarsimp simp: retype_addrs_def distinct_prop_map word_unat_power[symmetric] power_sub[symmetric] power_add[symmetric] mult.commute | rule conjI distinct_prop_distinct [where xs="upt a b" for a b] set_eqI diff_le_mono | erule(3) ptr_add_distinct_helper ptr_add_distinct_helper [OF _ not_sym] | drule subsetD [OF obj_refs_default_cap] less_two_pow_divD)+ apply (simp add: range_cover_def word_bits_def) apply (erule range_cover.range_cover_n_le[where 'a=machine_word_len]) done lemma unsafe_protected: "\<lbrakk> cte_wp_at P p s; cte_wp_at ((=) (cap.UntypedCap dev ptr bits idx)) p' s; descendants_range_in S p' s; invs s; S \<subseteq> untyped_range (cap.UntypedCap dev ptr bits idx); \<And>cap. P cap \<Longrightarrow> cap \<noteq> cap.NullCap \<rbrakk> \<Longrightarrow> fst p \<notin> S" apply (rule ex_cte_cap_protects) apply (erule if_unsafe_then_capD) apply (clarsimp simp: invs_def valid_state_def) apply simp apply assumption+ apply clarsimp+ done lemma cap_to_protected: "\<lbrakk> ex_cte_cap_wp_to P p s; cte_wp_at ((=) (cap.UntypedCap dev ptr bits idx)) p' s; descendants_range (cap.UntypedCap dev ptr bits idx) p' s; invs s \<rbrakk> \<Longrightarrow> ex_cte_cap_wp_to P p (detype {ptr .. ptr + 2 ^ bits - 1} s)" apply (clarsimp simp: ex_cte_cap_wp_to_def, simp add: detype_def descendants_range_def2) apply (intro exI conjI, assumption) apply (case_tac "a = fst p") apply (frule(1) ex_cte_cap_protects [rotated,where P=P]) apply clarsimp+ apply (simp add: ex_cte_cap_wp_to_def) apply fastforce+ apply (drule(2) unsafe_protected[rotated]) apply simp+ apply (clarsimp simp: cte_wp_at_caps_of_state) apply auto done (* FIXME: move *) lemma ge_mask_eq: "len_of TYPE('a) \<le> n \<Longrightarrow> (x::'a::len word) && mask n = x" by (simp add: mask_def p2_eq_0[THEN iffD2]) (* FIXME: replace do_machine_op_obj_at in KHeap_R by the lemma below *) lemma do_machine_op_obj_at_arch_state[wp]: "\<lbrace>\<lambda>s. P (obj_at (Q (arch_state s)) p s)\<rbrace> do_machine_op f \<lbrace>\<lambda>_ s. P (obj_at (Q (arch_state s)) p s)\<rbrace>" by (clarsimp simp: do_machine_op_def split_def | wp)+ lemma (in Untyped_AI_nonempty_table) retype_nonempty_table[wp]: "\<lbrace>\<lambda>(s::('state_ext::state_ext) state). \<not> (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s)\<rbrace> retype_region ptr sz us tp dev \<lbrace>\<lambda>rv s. \<not> (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) r s)\<rbrace>" apply (simp add: retype_region_def split del: if_split) apply (rule hoare_pre) apply (wp|simp del: fun_upd_apply)+ apply (clarsimp simp del: fun_upd_apply) apply (simp add: foldr_upd_app_if) apply (clarsimp simp: obj_at_def split: if_split_asm) done lemma invs_arch_state_strg: "invs s \<longrightarrow> valid_arch_state s" by (clarsimp simp: invs_def valid_state_def) lemma invs_psp_aligned_strg: "invs s \<longrightarrow> pspace_aligned s" by (clarsimp simp: invs_def valid_state_def) (* FIXME: move *) lemma invs_cap_refs_in_kernel_window[elim!]: "invs s \<Longrightarrow> cap_refs_in_kernel_window s" by (simp add: invs_def valid_state_def) lemma (in Untyped_AI_nonempty_table) set_cap_nonempty_tables[wp]: "\<lbrace>\<lambda>s. P (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) p s)\<rbrace> set_cap cap cref \<lbrace>\<lambda>rv s. P (obj_at (nonempty_table (set (second_level_tables (arch_state s)))) p s)\<rbrace>" apply (rule hoare_pre) apply (rule hoare_use_eq [where f=arch_state, OF set_cap_arch]) apply (wp set_cap_obj_at_impossible) apply (clarsimp simp: nonempty_table_caps_of) done lemma ex_cte_cap_wp_to_def_msu[simp]: "ex_cte_cap_wp_to P x (machine_state_update f s) = ex_cte_cap_wp_to P x s" by (simp add: ex_cte_cap_wp_to_def) lemma (in Untyped_AI_arch) retype_region_caps_reserved: "\<lbrace>cte_wp_at (is_untyped_cap) p and caps_overlap_reserved {ptr..ptr + of_nat (n * 2 ^ obj_bits_api tp us) - 1} and K (range_cover ptr sz (obj_bits_api tp us) n) and pspace_no_overlap_range_cover ptr sz and valid_pspace \<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv (s::('state_ext::state_ext) state). \<forall>y\<in>set rv. cte_wp_at (\<lambda>a. untyped_range (default_cap tp y us dev) \<inter> usable_untyped_range a = {}) p s\<rbrace>" apply (clarsimp simp: valid_def cte_wp_at_caps_of_state) apply (frule use_valid[OF _ retype_region_ranges']) apply fastforce apply (drule(1) bspec) apply (frule_tac P1 = "(=) cap" in use_valid[OF _ retype_region_cte_at_other]) apply simp+ apply (fastforce simp: cte_wp_at_caps_of_state) apply (clarsimp simp: cte_wp_at_caps_of_state caps_overlap_reserved_def) apply (drule bspec) apply fastforce apply (clarsimp simp: cap_range_def) apply blast done lemma untyped_mdb_descendants_range: "\<lbrakk>caps_of_state s p = Some ucap; is_untyped_cap ucap; valid_mdb s; descendants_range_in S p s; S \<subseteq> untyped_range ucap; caps_of_state s slot = Some cap; x\<in> obj_refs cap \<rbrakk>\<Longrightarrow> x\<notin> S" apply (clarsimp simp: valid_mdb_def) apply (drule untyped_mdbD) apply simp+ apply (rule ccontr) apply (clarsimp) apply blast apply simp apply (drule(2) descendants_range_inD) apply (simp add: cap_range_def,blast) done lemma global_refs_detype[simp]: "global_refs (detype S s) = global_refs s" by (simp add: detype_def) lemma ex_cte_cap_wp_to_clear_um[simp]: "ex_cte_cap_wp_to P p (clear_um T s) = ex_cte_cap_wp_to P p s" by (clarsimp simp: ex_cte_cap_wp_to_def clear_um_def) locale Untyped_AI = Untyped_AI_of_bl_nat_to_cref + Untyped_AI_arch state_ext_t + Untyped_AI_nonempty_table state_ext_t nonempty_table for state_ext_t :: "'state_ext :: state_ext itself" and nonempty_table lemma set_cap_device_and_range: "\<lbrace>\<top>\<rbrace> set_cap (UntypedCap dev (ptr && ~~ mask sz) sz idx) aref \<lbrace>\<lambda>rv s. (\<exists>slot. cte_wp_at (\<lambda>c. cap_is_device c = dev \<and> up_aligned_area ptr sz \<subseteq> cap_range c) slot s)\<rbrace>" apply (rule hoare_pre) apply (clarsimp simp: cte_wp_at_caps_of_state simp del: split_paired_All split_paired_Ex) apply (wp set_cap_cte_wp_at' hoare_vcg_ex_lift) apply (rule_tac x="aref" in exI) apply (auto intro: word_and_le2 simp: p_assoc_help) done lemma set_free_index_invs_UntypedCap: "\<lbrace>\<lambda>s. invs s \<and> (\<exists>cap. free_index_of cap \<le> idx \<and> is_untyped_cap cap \<and> idx \<le> 2^cap_bits cap \<and> free_index_update (\<lambda>_. idx) cap = UntypedCap dev ptr sz idx \<and> cte_wp_at ((=) cap) cref s)\<rbrace> set_cap (UntypedCap dev ptr sz idx) cref \<lbrace>\<lambda>rv s'. invs s'\<rbrace>" apply (rule hoare_name_pre_state) apply clarsimp apply (cut_tac cap=cap and idx=idx in set_free_index_invs) apply clarsimp apply (erule hoare_pre) apply (clarsimp simp: cte_wp_at_caps_of_state) apply (case_tac cap, simp_all add: free_index_of_def) done lemma retype_region_aligned_for_init_sz: "\<lbrace>\<lambda>s. range_cover ptr sz (obj_bits_api new_type obj_sz) n \<and> obj_bits_api new_type obj_sz = some_us_sz\<rbrace> retype_region ptr n obj_sz new_type is_dev \<lbrace>\<lambda>rv s. \<forall>ref \<in> set rv. is_aligned ref some_us_sz\<rbrace>" apply (rule hoare_name_pre_state) apply (rule hoare_pre, rule hoare_strengthen_post, rule retype_region_aligned_for_init, auto) done lemma (in strengthen_implementation) strengthen_Not[strg]: "\<lbrakk> st (\<not> F) (\<longrightarrow>) P P' \<rbrakk> \<Longrightarrow> st F (\<longrightarrow>) (\<not> P) (\<not> P')" by (cases F, auto) lemma retype_region_ret_folded_general: "\<lbrace>\<lambda>s. P (retype_addrs y ty n bits)\<rbrace> retype_region y n bits ty dev \<lbrace>\<lambda>r s. P r\<rbrace>" apply (rule hoare_name_pre_state) apply (rule hoare_pre, rule hoare_strengthen_post, rule retype_region_ret_folded, auto) done lemma retype_region_post_retype_invs_folded: "\<lbrace>P\<rbrace> retype_region y n bits ty dev \<lbrace>\<lambda>r. post_retype_invs ty r\<rbrace> \<Longrightarrow> \<lbrace>P\<rbrace> retype_region y n bits ty dev \<lbrace>\<lambda>r. post_retype_invs ty (retype_addrs y ty n bits)\<rbrace>" apply (rule hoare_strengthen_post, rule hoare_vcg_conj_lift[OF retype_region_ret_folded, simplified], assumption) apply clarsimp done lemma tup_in_fst_image_set_zipD: "x \<in> fst ` set (zip xs ys) \<Longrightarrow> x \<in> set xs" by (auto dest!: set_zip_helper) lemma distinct_map_fst_zip: "distinct xs \<Longrightarrow> distinct (map fst (zip xs ys))" apply (induct xs arbitrary: ys, simp_all) apply (case_tac ys, simp_all) apply (metis tup_in_fst_image_set_zipD) done lemma retype_region_ranges_obj_bits_api: "\<lbrace>cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> obj_ref_of c = ptr && ~~ mask sz) p and pspace_no_overlap_range_cover ptr sz and valid_pspace and K (range_cover ptr sz (obj_bits_api tp us) n) \<rbrace> retype_region ptr n us tp dev \<lbrace>\<lambda>rv s. \<forall>y\<in>set rv. cte_wp_at (\<lambda>c. {y .. y + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c ) p s\<rbrace>" apply (clarsimp simp:cte_wp_at_caps_of_state valid_def) apply (frule_tac P1 = "(=) cap" in use_valid[OF _ retype_region_cte_at_other]) apply simp apply (fastforce simp:cte_wp_at_caps_of_state) apply (clarsimp simp:cte_wp_at_caps_of_state del: subsetI) apply (frule use_valid[OF _ retype_region_ret_folded], simp+) apply (rule order_trans, erule(1) retype_addrs_range_subset) apply (clarsimp simp: is_cap_simps word_and_le2 del: subsetI) done context Untyped_AI begin lemma invoke_untyp_invs': assumes create_cap_Q: "\<And>tp sz cref slot oref reset ptr us slots dev. ui = Invocations_A.Retype slot reset (ptr && ~~ mask sz) ptr tp us slots dev \<Longrightarrow> \<lbrace>invs and Q and cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_range (default_cap tp oref us dev) \<subseteq> untyped_range c \<and> {oref .. oref + 2 ^ (obj_bits_api tp us) - 1} \<subseteq> untyped_range c) slot and cte_wp_at ((=) NullCap) cref and K (cref \<in> set slots \<and> oref \<in> set (retype_addrs ptr tp (length slots) us)) and K (range_cover ptr sz (obj_bits_api tp us) (length slots))\<rbrace> create_cap tp us slot dev (cref,oref) \<lbrace>\<lambda>_. Q\<rbrace>" assumes init_arch_Q: "\<And>tp slot reset sz slots ptr n us refs dev. ui = Invocations_A.Retype slot reset (ptr && ~~ mask sz) ptr tp us slots dev \<Longrightarrow> \<lbrace>Q and post_retype_invs tp refs and cte_wp_at (\<lambda>c. \<exists>idx. c = cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) slot and K (refs = retype_addrs ptr tp n us \<and> range_cover ptr sz (obj_bits_api tp us) n)\<rbrace> init_arch_objects tp ptr n us refs \<lbrace>\<lambda>_. Q\<rbrace>" assumes retype_region_Q: "\<And>ptr us tp slot reset sz slots dev. ui = Invocations_A.Retype slot reset (ptr && ~~ mask sz) ptr tp us slots dev \<Longrightarrow> \<lbrace>\<lambda>s. invs s \<and> Q s \<and> cte_wp_at (\<lambda>c. \<exists>idx. c = cap.UntypedCap dev (ptr && ~~ mask sz) sz idx) slot s \<and> pspace_no_overlap {ptr..(ptr && ~~ mask sz) + (2 ^ sz - 1)} s \<and> range_cover ptr sz (obj_bits_api tp us) (length slots) \<and> (tp = CapTableObject \<longrightarrow> 0 < us) \<and> caps_overlap_reserved {ptr..ptr + of_nat ((length slots) * 2 ^ obj_bits_api tp us) - 1} s \<and> caps_no_overlap ptr sz s \<rbrace> retype_region ptr (length slots) us tp dev \<lbrace>\<lambda>_.Q\<rbrace>" assumes set_cap_Q[wp]: "\<And>ptr sz idx cref dev. \<lbrace>\<lambda>s. Q s \<and> invs s \<and> cte_wp_at (\<lambda>c. is_untyped_cap c \<and> cap_bits c = sz \<and> obj_ref_of c = ptr) cref s \<and> (case ui of Invocations_A.Retype slot reset ptr' ptr tp us slots dev' \<Rightarrow> cref = slot \<and> dev' = dev) \<and> idx \<le> 2^ sz\<rbrace> set_cap (cap.UntypedCap dev ptr sz idx) cref \<lbrace>\<lambda>rv. Q\<rbrace>" assumes reset_Q: "\<lbrace>Q'\<rbrace> reset_untyped_cap (case ui of Retype src_slot _ _ _ _ _ _ _ \<Rightarrow> src_slot) \<lbrace>\<lambda>_. Q\<rbrace>" shows "\<lbrace>(invs ::'state_ext state \<Rightarrow> bool) and (\<lambda>s. (case ui of Retype _ reset _ _ _ _ _ _ \<Rightarrow> reset) \<longrightarrow> Q' s) and Q and valid_untyped_inv ui and ct_active\<rbrace> invoke_untyped ui \<lbrace>\<lambda>rv s. invs s \<and> Q s\<rbrace>, \<lbrace>\<lambda>_ s. invs s \<and> Q s\<rbrace>" apply (cases ui) apply (rule hoare_name_pre_stateE) apply (clarsimp simp only: valid_untyped_inv_wcap untyped_invocation.simps) proof - fix cref oref reset ptr_base ptr tp us slots s sz idx dev assume ui: "ui = Retype (cref, oref) reset ptr_base ptr tp us slots dev" assume Q: "Q s" and Q': "reset \<longrightarrow> Q' s" assume invs: "invs s" "ct_active s" assume vui: "valid_untyped_inv_wcap (Retype (cref, oref) reset ptr_base ptr tp us slots dev) (Some (UntypedCap dev (ptr && ~~ mask sz) sz idx)) s" (is "valid_untyped_inv_wcap _ (Some ?orig_cap) s") have cte_at: "cte_wp_at ((=) ?orig_cap) (cref,oref) s" (is "?cte_cond s") using vui by (clarsimp simp add:cte_wp_at_caps_of_state) note blah[simp del] = untyped_range.simps usable_untyped_range.simps atLeastAtMost_iff atLeastatMost_subset_iff atLeastLessThan_iff Int_atLeastAtMost atLeastatMost_empty_iff split_paired_Ex note neg_mask_add_mask = word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr,symmetric] have p_neq_0:"ptr \<noteq> 0" using cte_at invs apply (clarsimp simp:cte_wp_at_caps_of_state) apply (drule(1) caps_of_state_valid)+ apply (simp add:valid_cap_def) done have cover: "range_cover ptr sz (obj_bits_api tp us) (length slots)" using vui by (clarsimp simp:cte_wp_at_caps_of_state) note neg_mask_add_mask = word_plus_and_or_coroll2[symmetric,where w = "mask sz" and t = ptr,symmetric] note set_cap_free_index_invs_spec = set_free_index_invs[where cap = "cap.UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx)", unfolded free_index_update_def free_index_of_def,simplified] have slot_not_in: "(cref, oref) \<notin> set slots" using vui cte_at by (auto simp: cte_wp_at_caps_of_state) note reset_Q' = reset_Q[simplified ui, simplified] have ptr_base: "ptr_base = ptr && ~~ mask sz" using vui by (clarsimp simp: cte_wp_at_caps_of_state) note ui' = ui[unfolded ptr_base] note msimp[simp] = neg_mask_add_mask let ?ui = "Retype (cref, oref) reset ptr_base ptr tp us slots dev" show "\<lbrace>(=) s\<rbrace> invoke_untyped ?ui \<lbrace>\<lambda>rv s. invs s \<and> Q s\<rbrace>, \<lbrace>\<lambda>_ s. invs s \<and> Q s\<rbrace>" using cover apply (simp add:mapM_x_def[symmetric] invoke_untyped_def) apply (rule_tac B="\<lambda>_ s. invs s \<and> Q s \<and> ct_active s \<and> valid_untyped_inv_wcap ?ui (Some (UntypedCap dev (ptr && ~~ mask sz) sz (if reset then 0 else idx))) s \<and> (reset \<longrightarrow> pspace_no_overlap {ptr && ~~ mask sz..(ptr && ~~ mask sz) + 2 ^ sz - 1} s) " in hoare_vcg_seqE[rotated]) apply (simp only: whenE_def) apply (rule hoare_pre, wp) apply (rule hoare_post_impErr, rule combine_validE, rule reset_untyped_cap_invs_etc, rule valid_validE, rule reset_Q') apply (clarsimp simp only: pred_conj_def if_True, blast) apply (wp | simp)+ apply (cut_tac vui Q Q' invs) apply (clarsimp simp: cte_wp_at_caps_of_state slot_not_in) apply blast apply (simp add: cte_wp_at_conj ball_conj_distrib split del: if_split | wp hoare_vcg_const_Ball_lift set_tuple_pick retype_region_ex_cte_cap_to [where sz = sz] retype_region_obj_ref_range [where sz = sz] hoare_vcg_all_lift [of _ _ "%a _ p. \<forall>b. ~ cte_wp_at P (a,b) p" for P] hoare_vcg_all_lift [of _ _ "%b _ p. ~ cte_wp_at P (a,b) p" for P a] retype_region_not_cte_wp_at [where sz = sz] init_arch_objects_invs_from_restricted retype_ret_valid_caps [where sz = sz] retype_region_global_refs_disjoint [where sz = sz] retype_region_post_retype_invs [where sz = sz] retype_region_cte_at_other[where sz = sz] retype_region_invs_extras[where sz = sz] retype_region_ranges [where sz = sz] retype_region_ranges_obj_bits_api[where sz=sz] retype_region_caps_reserved [where sz = sz] retype_region_distinct_sets [where sz = sz] create_caps_invs[where ptr=ptr and slots=slots and us=us] create_cap_Q[OF ui'] init_arch_Q[OF ui'] retype_region_Q[OF ui'] retype_region_descendants_range_ret[where sz = sz] retype_region_obj_at_other2 [where P="is_cap_table n" for n] distinct_tuple_helper init_arch_objects_wps init_arch_objects_nonempty_table | wp (once) retype_region_ret_folded_general)+ apply ((wp hoare_vcg_const_imp_lift hoare_drop_imp retype_region_invs_extras[where sz = sz] retype_region_aligned_for_init[where sz = sz] set_free_index_invs_UntypedCap set_cap_caps_no_overlap set_cap_no_overlap set_untyped_cap_caps_overlap_reserved | strengthen tup_in_fst_image_set_zipD[mk_strg D] distinct_map_fst_zip | simp add: ptr_base | wp (once) retype_region_ret_folded_general)+)[1] apply (clarsimp simp:conj_comms,simp cong:conj_cong) apply (simp add:ball_conj_distrib conj_comms) apply (strengthen invs_mdb invs_valid_pspace caps_region_kernel_window_imp[where p="(cref, oref)"] invs_cap_refs_in_kernel_window exI[where x="(cref, oref)"] | clarsimp simp: conj_comms | simp cong: conj_cong)+ apply (rule_tac P = "bits_of cap = sz" in hoare_gen_asm) apply (simp add:bits_of_def) apply (wp set_cap_no_overlap hoare_vcg_ball_lift set_free_index_invs_UntypedCap set_cap_cte_wp_at set_cap_descendants_range_in set_cap_caps_no_overlap set_untyped_cap_caps_overlap_reserved[where idx="if reset then 0 else idx"] set_cap_cte_cap_wp_to hoare_vcg_ex_lift | wp (once) hoare_drop_imps)+ apply (wp set_cap_cte_wp_at_neg hoare_vcg_all_lift get_cap_wp)+ apply (clarsimp simp: slot_not_in field_simps ui free_index_of_def split del: if_split) apply ((strengthen cover refl)+)? apply (simp only: cte_wp_at_caps_of_state, clarify, simp only: option.simps, simp(no_asm_use) split del: if_split, clarify) apply (clarsimp simp: bits_of_def untyped_range.simps if_split[where P="\<lambda>v. v \<le> unat x" for x]) apply (frule(1) valid_global_refsD2[OF _ invs_valid_global_refs]) apply (clarsimp simp:cte_wp_at_caps_of_state untyped_range.simps conj_comms split del: if_split) apply (frule invoke_untyped_proofs.intro[where cref="(cref, oref)" and reset=reset, rotated 1], simp_all add: cte_wp_at_caps_of_state split del: if_split) apply (rule conjI, (rule refl | assumption))+ apply clarsimp apply (simp add: invoke_untyped_proofs.simps p_neq_0) apply (simp add: arg_cong[OF mask_out_sub_mask, where f="\<lambda>y. x - y" for x] field_simps invoke_untyped_proofs.idx_le_new_offs invoke_untyped_proofs.idx_compare' exI invoke_untyped_proofs.simps word_bw_assocs) apply (frule cte_wp_at_pspace_no_overlapI, simp add: cte_wp_at_caps_of_state, simp+, simp add: invoke_untyped_proofs.szw) apply (cut_tac s=s in obj_is_device_vui_eq[where ui=ui]) apply (clarsimp simp: ui cte_wp_at_caps_of_state) apply (simp_all add: field_simps ui) apply (intro conjI) (* slots not in retype_addrs *) apply (clarsimp dest!:retype_addrs_subset_ptr_bits) apply (drule(1) invoke_untyped_proofs.slots_invD) apply (drule(1) subsetD) apply (simp add:p_assoc_help) (* not global refs*) apply (simp add: Int_commute, erule disjoint_subset2[rotated]) apply (simp add: atLeastatMost_subset_iff word_and_le2) (* idx less_eq new offs *) apply (auto dest: invoke_untyped_proofs.idx_le_new_offs)[1] (* not empty tables *) apply clarsimp apply (drule(1) pspace_no_overlap_obj_not_in_range, clarsimp+)[1] (* set ineqs *) apply (simp add: atLeastatMost_subset_iff word_and_le2) apply (erule order_trans[OF invoke_untyped_proofs.subset_stuff]) apply (simp add: atLeastatMost_subset_iff word_and_le2) (* new untyped range disjoint *) apply (drule invoke_untyped_proofs.usable_range_disjoint) apply (clarsimp simp: field_simps mask_out_sub_mask shiftl_t2n) (* something about caps *) apply clarsimp apply (frule untyped_mdb_descendants_range, clarsimp+, erule invoke_untyped_proofs.descendants_range, simp_all+)[1] apply (simp add: untyped_range_def atLeastatMost_subset_iff word_and_le2) done qed lemmas invoke_untyp_invs[wp] = invoke_untyp_invs'[where Q=\<top> and Q'=\<top>, simplified, simplified hoare_post_taut, simplified] lemmas invoke_untyped_Q = invoke_untyp_invs'[THEN validE_valid, THEN hoare_conjD2[unfolded pred_conj_def]] lemma invoke_untyped_pred_tcb_at: "\<lbrace>\<lambda>s. pred_tcb_at proj Q t s \<and> invs s \<and> st_tcb_at ((Not \<circ> inactive) and (Not \<circ> idle)) t s \<and> ct_active s \<and> valid_untyped_inv ui s\<rbrace> invoke_untyped ui \<lbrace>\<lambda>_ s :: 'state_ext state. pred_tcb_at proj Q t s\<rbrace>" apply (rule hoare_pre, rule invoke_untyped_Q, (wp init_arch_objects_wps | simp)+) apply (rule hoare_name_pre_state, clarsimp) apply (wp retype_region_st_tcb_at) apply fastforce apply (wp reset_untyped_cap_pred_tcb_at | simp)+ apply (cases ui, clarsimp) apply (frule(1) st_tcb_ex_cap[OF _ invs_iflive]) apply (clarsimp split: Structures_A.thread_state.splits) apply (drule ex_nonz_cap_to_overlap, ((simp add: cte_wp_at_caps_of_state is_cap_simps descendants_range_def2 empty_descendants_range_in)+)) done lemma invoke_untyped_st_tcb_at[wp]: "\<lbrace>invs and st_tcb_at (P and (Not \<circ> inactive) and (Not \<circ> idle)) t and ct_active and valid_untyped_inv ui\<rbrace> invoke_untyped ui \<lbrace>\<lambda>_. \<lambda>s :: 'state_ext state. st_tcb_at P t s\<rbrace>" apply (rule hoare_pre, rule invoke_untyped_pred_tcb_at) by (fastforce simp: pred_tcb_at_def obj_at_def) lemma invoked_untyp_tcb[wp]: "\<lbrace>invs and st_tcb_at active tptr and valid_untyped_inv ui and ct_active\<rbrace> invoke_untyped ui \<lbrace>\<lambda>rv. \<lambda>s :: 'state_ext state. tcb_at tptr s\<rbrace>" apply (simp add: tcb_at_st_tcb_at) apply (rule hoare_pre, wp invoke_untyped_st_tcb_at) apply (clarsimp elim!: pred_tcb_weakenE) apply fastforce done end lemma sts_mdb[wp]: "\<lbrace>\<lambda>s. P (cdt s)\<rbrace> set_thread_state t st \<lbrace>\<lambda>rv s. P (cdt s)\<rbrace>" by (simp add: set_thread_state_def | wp)+ lemma sts_ex_cap[wp]: "\<lbrace>ex_cte_cap_wp_to P p\<rbrace> set_thread_state t st \<lbrace>\<lambda>rv. ex_cte_cap_wp_to P p\<rbrace>" by (wp ex_cte_cap_to_pres) lemmas sts_real_cte_at[wp] = cap_table_at_lift_valid [OF set_thread_state_typ_at] lemma sts_valid_untyped_inv: "\<lbrace>valid_untyped_inv ui\<rbrace> set_thread_state t st \<lbrace>\<lambda>rv. valid_untyped_inv ui\<rbrace>" apply (cases ui, simp add: descendants_range_in_def) apply (wp hoare_vcg_const_Ball_lift hoare_vcg_ex_lift hoare_vcg_imp_lift | wps)+ apply clarsimp done lemma update_untyped_cap_valid_objs: "\<lbrace> valid_objs and valid_cap cap and cte_wp_at (is_untyped_cap) p and K (is_untyped_cap cap)\<rbrace> set_cap cap p \<lbrace> \<lambda>rv. valid_objs \<rbrace>" apply (wp set_cap_valid_objs) apply (clarsimp simp: is_cap_simps cte_wp_at_caps_of_state) apply (drule tcb_cap_valid_caps_of_stateD, simp+) apply (simp add: tcb_cap_valid_untyped_to_thread) done lemma valid_untyped_pspace_no_overlap: "pspace_no_overlap {ptr .. ptr + 2 ^ sz - 1} s \<Longrightarrow> valid_untyped (cap.UntypedCap dev ptr sz idx) s" apply (clarsimp simp: valid_untyped_def split del: if_split) apply (drule(1) pspace_no_overlap_obj_range) apply simp done (* FIXME: move *) lemma snd_set_zip_in_set: "x\<in> snd ` set (zip a b) \<Longrightarrow> x\<in> set b" apply (clarsimp) apply (erule in_set_zipE) apply simp done end
import pandas as pd import numpy as np """ Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end: """ prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV') print("\n prng:") print(prng) ts = pd.Series(np.random.randn(len(prng)), prng) print("\n ts:") print(ts) ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9 head = ts.head() print("\n head:") print(head)
-- -------------------------------------------------------------- [ Common.idr ] -- Module : Common.idr -- Copyright : (c) Jan de Muijnck-Hughes -- License : see LICENSE -- --------------------------------------------------------------------- [ EOH ] module Readability.Process.Common import Effects import Effect.State import Readability.WordTypes import Readability.Stats import Readability.Metrics import Readability.Process.Effs %access export ||| Process a sentence. processSentence : List String -> Eff () ReadEffs processSentence Nil = pure () processSentence (x::xs) = do let syls = countSyllables x let lenstr = cast $ length x let sws = if lenstr == 1 then 1 else 0 let lws = if lenstr > 6 then 1 else 0 let bws = if syls > 3 then 1 else 0 updateReadState (\st => updateRStats lenstr syls sws lws bws st) processSentence xs ||| Calculate the readability scores using different metrics. calcScores : RStats -> ReadResult calcScores st = MkReadResult (flesch ws sens sys) (ari cs ws sens) (kincaid ws sens sys) (coleman cs ws sens) (fog ws sens bwords) (smog bwords sens) where cs = cast $ chars st sys = cast $ sylls st ws = cast $ nowords st sens = cast $ sentances st bwords = cast $ bigwords st -- --------------------------------------------------------------------- [ EOF ]
function test_corenums end
using SymbolicUtils using Test using SymbolicUtils: showraw const leaf_funcs = [()->100*randn(), ()->rand(-100:100), ()->rand(@syms a b c d e f), ()->rand(@syms a b c d e f)] const fns = vcat(1 .=> SymbolicUtils.monadic, 2 .=> vcat(SymbolicUtils.diadic, fill(+, 5), [-,-], fill(*, 5)), 3 .=> [+, *]) function gen_rand_expr(inputs; leaf_prob=0.92, depth=0, min_depth=1, max_depth=5) if depth > max_depth || (min_depth <= depth && rand() < leaf_prob) leaf = rand(leaf_funcs)() if leaf isa SymbolicUtils.Sym push!(inputs, leaf) end return leaf end arity, f = rand(fns) args = [gen_rand_expr(inputs, leaf_prob=leaf_prob, depth=depth+1, min_depth=min_depth, max_depth=max_depth) for i in 1:arity] try return f(args...) catch err if err isa DomainError return gen_rand_expr(inputs, leaf_prob=leaf_prob, depth=depth, min_depth=min_depth, max_depth=max_depth) else rethrow(err) end end end struct Errored err end function fuzz_test(ntrials) inputs = Set() expr = gen_rand_expr(inputs) inputs = collect(inputs) unsimplifiedstr = """ function $(tuple(inputs...)) $(sprint(io->showraw(io, expr))) end """ simplifiedstr = """ function $(tuple(inputs...)) $(sprint(io->showraw(io, simplify(expr)))) end """ f = include_string(Main, unsimplifiedstr) g = include_string(Main, simplifiedstr) for i=1:ntrials args = [randn() for j in 1:length(inputs)] unsimplified = try Base.invokelatest(f, args...) catch err Errored(err) end simplified = try Base.invokelatest(g, args...) catch err Errored(err) end if unsimplified isa Errored @test typeof(simplified.err) == typeof(unsimplified.err) else try @test unsimplified ≈ simplified if !(unsimplified ≈ simplified) error("Failed") end catch err println("""Test failed for expression $(sprint(io->showraw(io, expr))) = $unsimplified Simplified to: $(sprint(io->showraw(io, simplify(expr)))) = $simplified On inputs: $inputs = $args """) end end end end using Random: seed! @testset "Fuzz test" begin seed!(6174) for i=1:2000 fuzz_test(10) end end
\section{Laurent Series, Isolated Singularities and the Residue Theorem} \begin{theorem} Consider an open annulus $A=\{z\in\mathbb C:r<|z-a|<R\}$ and let $f$ be holomorphic on $A$. Then $f$ has a Laurent series expansion $$f(z)=\sum_{n\in\mathbb Z}c_n(z-a)^n=\left( \sum_{n=0}^\infty c_n(z-a)^n \right)+\left( \sum_{n=1}^\infty c_{-n}(z-a)^{-n} \right)$$ for every $z\in A$. In addition, for any $r<\rho<R$, we have $$c_n=\frac{1}{2\pi i}\oint_{\partial D_\rho(a)}\frac{f(z)}{(z-a)^{n+1}}\,\mathrm dz$$ Also for any $r<\rho_1<\rho_2<R$ the series converges uniformly on $\{z\in\mathbb C:\rho_1<|z-a|<\rho_2\}$ \end{theorem} \begin{proof} Let $w\in A$, and choose $r<\rho_2<|w-a|<\rho_1<R$ and let $\gamma_1$ be the anticlockwise curve as the boundary of the a polar slice of the annulus $\{z\in\mathbb C:\rho_2<|z-a|<\rho_1\}$ that contains $w$, and $\gamma_2$ be the boundary of the rest such that $\gamma_{1,2}$ agrees on the slices. Now $$\oint_{\gamma_2}\frac{f(z)}{z-w}\,\mathrm dz=0,\frac{1}{2\pi i}\oint_{\gamma_1}\frac{f(z)}{z-w}\,\mathrm dz=I(\gamma,w)f(w)$$ But since $\gamma_1$ is homotopic to a circle around $w$, $I(\gamma,w)=1$. Hence \begin{align*} f(w)&=\frac{1}{2\pi i}\left( \oint_{\gamma_1}\frac{f(z)}{z-w}+\oint_{\gamma_2}\frac{f(z)}{z-w} \right)\\ &=\frac{1}{2\pi i}\left( \oint_{\partial D_{\rho_1}(a)}\frac{f(z)}{z-w}\,\mathrm dz-\oint_{\partial D_{\rho_2}(a)}\frac{f(z)}{z-w}\,\mathrm dz \right)\\ &=f_1(w)+f_2(w)\\ f_1(w)&=\frac{1}{2\pi i}\oint_{\partial D_{\rho_1}(a)}\frac{f(z)}{z-w}\,\mathrm dz\\ f_2(w)&=-\frac{1}{2\pi i}\oint_{\partial D_{\rho_2}(a)}\frac{f(z)}{z-w}\,\mathrm dz \end{align*} Expanding $f_1$ as Taylor series about $a$ would give the nonnegative terms of the Laurent series. We shall produce the negative terms from $f_2$ by a trick we used before. Observe $$-\frac{1}{z-w}=\frac{1}{w-a}\frac{1}{1-(z-a)/(w-a)}=\sum_{m=1}^\infty\frac{(z-a)^{m-1}}{(w-a)^m}$$ which converges uniformly as a geometric series. So we can change the order of integration and get $$f_2(w)=\sum_{m=1}^\infty\left(\frac{1}{2\pi i}\oint_{\partial D_{\rho_2}(a)}f(z)(z-a)^{m-1}\,\mathrm dz\right)(w-a)^{-m}$$ writing $m=-n$ gives the existence of the Laurent series. The rest is trivial. \end{proof} \begin{definition} A complex valued function $f$ has an isolated singularity at a point $a\in\mathbb C$ if $f$ is defined and holomorphic in a punctured disk $D_r(a)\setminus\{a\}$ for some $r>0$ but not in $D_r(a)$ (i.e. either not defined at $a$ or not holomorphic there). \end{definition} \begin{example} 1. $f(z)=1/z$ has an isolated singularity at $z=0$.\\ 2. $f(z)=(e^z-1)/z$ also has one at $0$.\\ 3. $f(z)=e^{1/z}$ has one at $0$. \end{example} \begin{definition} An isolated singularity $a$ of $f$ is removable if there is a holomorphic $g$ defined on $D_r(a)$ for some $r>0$ and $f=g$ on $D_r(a)\setminus\{a\}$. \end{definition} \begin{proposition} $f$ has a removable singularity at $a$ iff $\lim_{z\to a}(z-a)f(z)=0$. \end{proposition} \begin{proof} The ``only if'' part is immediate. For the other direction, Suppose $f$ is holomorphic on $D_r(a)\setminus\{a\}$ and $\lim_{z\to a}(z-a)f(z)=0$, then let $$h(z)=\begin{cases} (z-a)^2f(z)\text{, if $z\neq 0$}\\ 0\text{, if $z=0$} \end{cases}$$ So $h$ is holomorphic in some disk $D_r(a)\setminus\{a\}$. Also $$\frac{h(z)-h(a)}{z-a}=(z-a)f(z)\to 0$$ as $z\to a$, so $h$ is actually holomorphic on $D_r(a)$ with $h^\prime(a)=0$. But $h$ has a zero of order at least $2$, hence there is a holomorphic $g$ on $D_r(a)$ such that $h(z)=(z-a)^2g(z)$, but then $g$ equals $f$ on $D_r(a)\setminus\{a\}$. \end{proof} So the isolated singularities of bounded functions are removable. \begin{definition} Let $a$ be an isolated singularity of $f:D_r(a)\to\mathbb C$, then $a$ is a pole if the limit $\lim_{z\to a}|f(z)|=\infty$.\\ If $a$ is neither a pole nor a removable singularity, we say $a$ is an essential singularity. \end{definition} \begin{proposition}\label{pole_equiv} Let $U$ be a domain and $f:U\setminus\{a\}\to\mathbb C$ is holomorphic for $a\neq U$. Then the followings are equivalent:\\ 1. $a$ is a pole of $f$.\\ 2. There is $\epsilon>0$ such that there is a holomophic $h:D_\epsilon(a)\to\mathbb C$ with $h(z)=0\iff z=a$ and $\forall z\in D_\epsilon(a)\setminus\{a\},f(z)=1/h(z)$.\\ 3. There is a holomorphic $g:U\to\mathbb C$ such that $g(a)\neq 0$ and $$f(z)=(z-a)^{-k}g(z)$$ for some integer $k\ge 1$. Also such $g,k$ are uniquely determined by $f$. \end{proposition} \begin{proof} $1\implies 2$: Choose $\epsilon$ such that $|f(z)|\ge 1$ whenever $0<|z-a|<\epsilon$, so $1/f$ is holomorphic on $D_\epsilon(a)\setminus\{a\}$. But $a$ becomes a removable singularity of $1/f$ by the preceding proposition, so the extension of $1/f$ to the entire disk $D_\epsilon(a)$ would be the desired $h$.\\ $2\implies 3$: Suppose $h$ has a zero of order $k$, then $h(z)=(z-a)^kq(z)$ where $q$ is holomorphic and $q(a)\neq 0$, so $q$ is nonzero in a disk $D\subset D_\epsilon(a)$ around $a$, hence $$g(z)=\begin{cases} 1/q(z)\text{, if $z\in D$}\\ (z-a)^kf(z)\text{, if $z\in U\setminus\{a\}$} \end{cases}$$ which is well-defined by the definition of $h$ and is holomorphic. Uniqueness follows.\\ $3\implies 1$ is trivial. \end{proof} \begin{corollary} If $z\in\mathbb C$ is an essential singularity of $f$, then the limit of $|f(z)|$ as $z\to a$ does not exist, either as a real number or infinity. \end{corollary} \begin{example} If we compute $e^{1/z}$ as $z\to 0$, we will find that it does not exist, so $0$ is an essential singularity of it. \end{example} \begin{definition} If $f$ has a pole at $a$, then the integer $k$ as stated in Proposition \ref{pole_equiv} is called the order of the pole $a$. If $k=1$, then we call $a$ a simple pole.\\ Let $U$ be a domain and $S\subset U$ is a set of isolated points in $U$. If $f$ is holomorphic on $U\setminus S$ and each $s\in S$ is either a removable singularity or a pole of $f$, we say $f$ is meromorphic on $U$. \end{definition} Meromorphic functions can be taken (maybe) as holomorphic functions from $U$ to $\mathbb C_\infty$. \begin{remark} By the preceding corollary, at an isolated essential singularity $a$ of $f$, then $f$ oscillates around $a$. More precisely we have the Cosorati-Weierstrass Theorem (proven in example sheet), where we find that the image of any punctured neighbourhood around $a$ has dense image in $\mathbb C$. A much much harder theorem will show that this image is the entire complex plane $\mathbb C$ except possibly one point. \end{remark} \begin{proposition} Let $f$ be holomorphic in $D_R(a)\setminus\{a\}$, then we have the series $$f(z)=\sum_{n\in\mathbb Z}c_n(z-a)^n,\forall z\in D_R(a)\setminus\{a\}$$ Also, $\forall n<0,c_n=0$ implies that $a$ is removable.\\ If now $c_{-k}\neq 0$ for some $k>0$ and $c_n=0$ for $n<-k$, then there is a holomorphic $g:D_R(a)\to\mathbb C$ such that $$f(z)=\sum_{n=-k}^\infty c_n(z-a)^n=\frac{g(z)}{(z-a)^k}$$ So $f$ has a pole of order $k$ at $a$. \end{proposition} \begin{proof} Trivial. \end{proof} Let rhe series expansion be as above, then by uniform convergence, the integral $$\int_{\partial D_\rho(a)}f(z)\,\mathrm dz=2\pi ic_{-1}$$ So we define \begin{definition} $c_{-1}$ is defined as the residue $\operatorname{Res}_f(a)$ of $f$ at $a$. And the series $$\sum_{n=-\infty}^{-1}c_n(z-a)^n$$ is called the principal part of $f$. \end{definition} \begin{theorem}[Residue Theorem] Let $U$ be a domain and $S=\{a_1,\ldots,a_k\}\subset U$. Suppose $f$ is holomorphic on $U\setminus S$, then for any closed piecewise $C^1$ curve $\gamma:[0,1]\to U\setminus S$ homologous to $0$ in $U$, we have $$\int_\gamma f(z)\,\mathrm dz=2\pi i\sum_{j=1}^kI(\gamma;a_j)\operatorname{Res}_f(a_j)$$ \end{theorem} \begin{proof} Let $g$ be the principal part of $f$ at $a_i$. Then $g$ is holomorphic on $\mathbb C\setminus\{a_i\}$, so $f-(g_1+\cdots+g_k)$ is holomorphic in $U$ except at removable singularities, so by Cauchy's Theorem, $$\int_\gamma f(z)\,\mathrm dz=\sum_{j=1}^k\int_\gamma g_j(z)\,\mathrm dz=2\pi i\sum_{j=1}I(\gamma,a_j)\operatorname{Res}_f(a)$$ as desired. \end{proof} There are some useful facts about residues. \begin{proposition} If $f$ has a simple pole at $a$, then $\operatorname{Res}_f(a)=\lim_{z\to a}(z-a)f(a)$. More generally, if $f$ has a pole of order $k$, then if we write $f(z)=(z-a)^{-k}g(z)$ for a holomorphic $g$, then $\operatorname{Res}_f(a)=g^{(k-1)}(a)/(k-1)!$. If $f=g/h$ with $g,h$ holomorphic and at $a$, $g(a)\neq 0$ and $h$ has a simple zero at $a$, then $f(a)=g(a)/h^\prime(a)$. \end{proposition} \begin{proof} Easy. \end{proof} \begin{proposition}[Jordan's Lemma] If $f$ is holomorphic in $\{z\in\mathbb C:|z|>r\}$ for some $r>0$ and if $zf(z)$ is bounded for large $|z|$, then $$\int_{\gamma_R}f(z)e^{i\alpha z}\,\mathrm dz\to 0,\gamma_R:[0,\pi]\ni t\mapsto Re^{it}$$ as $R\to\infty$. \end{proposition} \begin{proof} Example sheet. Use the fact that $\sin t/t\ge 2/\pi$ for $t\in (0,\pi/2]$. \end{proof} \begin{proposition} Let $f$ be holomorphic on $D_R(a)\setminus\{a\}$ with a simple pole at $z=a$ and $\gamma_\epsilon:[\alpha,\beta]\ni t\mapsto a+\epsilon e^{it}$, then $$\lim_{\epsilon\to 0^+}\int_{\gamma_\epsilon}f(z)\,\mathrm dz=(\beta-\alpha)i\operatorname{Res}_f(a)$$ \end{proposition} \begin{proof} Just write $f(z)=\operatorname{Res}_f(a)/(z-a)+g(z)$. \end{proof} \begin{example} Let $R>\epsilon>0$. Consider $f(z)=e^{iz}/z$ along the contour $\gamma=\gamma_1-\gamma_\epsilon+\gamma_2+\gamma_R$ where $\gamma_1$ is the segment $[-R,-\epsilon]$, $\gamma_2$ is $[\epsilon,R]$, and $\gamma_R(t)=Re^{it},\gamma_\epsilon(t)=\epsilon e^{it},t\in [0,\pi]$. Now by Jordan's Lemma and the preceding proposition respectively, we have $$\lim_{R\to\infty}\int_{\gamma_R}f(z)\,\mathrm dz=0,\lim_{\epsilon\to 0}\int_{\gamma_\epsilon}f(z)\,\mathrm dz=\pi i\operatorname{Res}_f(a)=\pi i$$ Now for $\epsilon,R$ as before we have $$0=\int_\gamma f(z)\,\mathrm dz=\int_{-R}^{-\epsilon}\frac{e^{ix}}{x}\,\mathrm dx+\int_{-\gamma_\epsilon}f(z)\,\mathrm dz+\int_\epsilon^R\frac{e^{ix}}{x}\,\mathrm dx+\int_{\gamma_R}f(z)\,\mathrm dz$$ Now let $R\to\infty,\epsilon\to 0$, we get $$2i\int_0^\infty\frac{\sin x}{x}\,\mathrm dx=\pi i\implies\int_0^\infty\frac{\sin x}{x}\,\mathrm dx=\frac{\pi}{2}$$ \end{example}
State Before: α : Type u_1 β : Type ?u.667113 inst✝ : DecidableEq α l : List α x✝ x : α xs : List α ⊢ ↑(formPerm (x :: xs)) (getLast (x :: xs) (_ : x :: xs ≠ [])) = x State After: no goals Tactic: induction' xs using List.reverseRecOn with xs y _ generalizing x <;> simp
# Systems of Equations Imagine you are at a casino, and you have a mixture of £10 and £25 chips. You know that you have a total of 16 chips, and you also know that the total value of chips you have is £250. Is this enough information to determine how many of each denomination of chip you have? Well, we can express each of the facts that we have as an equation. The first equation deals with the total number of chips - we know that this is 16, and that it is the number of £10 chips (which we'll call ***x*** ) added to the number of £25 chips (***y***). The second equation deals with the total value of the chips (£250), and we know that this is made up of ***x*** chips worth £10 and ***y*** chips worth £25. Here are the equations \begin{equation}x + y = 16 \end{equation} \begin{equation}10x + 25y = 250 \end{equation} Taken together, these equations form a *system of equations* that will enable us to determine how many of each chip denomination we have. ## Graphing Lines to Find the Intersection Point One approach is to determine all possible values for x and y in each equation and plot them. A collection of 16 chips could be made up of 16 £10 chips and no £25 chips, no £10 chips and 16 £25 chips, or any combination between these. Similarly, a total of £250 could be made up of 25 £10 chips and no £25 chips, no £10 chips and 10 £25 chips, or a combination in between. Let's plot each of these ranges of values as lines on a graph: ```python %matplotlib inline from matplotlib import pyplot as plt # Get the extremes for number of chips chipsAll10s = [16, 0] chipsAll25s = [0, 16] # Get the extremes for values valueAll10s = [25,0] valueAll25s = [0,10] # Plot the lines plt.plot(chipsAll10s,chipsAll25s, color='blue') plt.plot(valueAll10s, valueAll25s, color="orange") plt.xlabel('x (£10 chips)') plt.ylabel('y (£25 chips)') plt.grid() plt.show() ``` Looking at the graph, you can see that there is only a single combination of £10 and £25 chips that is on both the line for all possible combinations of 16 chips and the line for all possible combinations of £250. The point where the line intersects is (10, 6); or put another way, there are ten £10 chips and six £25 chips. ### Solving a System of Equations with Elimination You can also solve a system of equations mathematically. Let's take a look at our two equations: \begin{equation}x + y = 16 \end{equation} \begin{equation}10x + 25y = 250 \end{equation} We can combine these equations to eliminate one of the variable terms and solve the resulting equation to find the value of one of the variables. Let's start by combining the equations and eliminating the x term. We can combine the equations by adding them together, but first, we need to manipulate one of the equations so that adding them will eliminate the x term. The first equation includes the term ***x***, and the second includes the term ***10x***, so if we multiply the first equation by -10, the two x terms will cancel each other out. So here are the equations with the first one multiplied by -10: \begin{equation}-10(x + y) = -10(16) \end{equation} \begin{equation}10x + 25y = 250 \end{equation} After we apply the multiplication to all of the terms in the first equation, the system of equations look like this: \begin{equation}-10x + -10y = -160 \end{equation} \begin{equation}10x + 25y = 250 \end{equation} Now we can combine the equations by adding them. The ***-10x*** and ***10x*** cancel one another, leaving us with a single equation like this: \begin{equation}15y = 90 \end{equation} We can isolate ***y*** by dividing both sides by 15: \begin{equation}y = \frac{90}{15} \end{equation} So now we have a value for ***y***: \begin{equation}y = 6 \end{equation} So how does that help us? Well, now we have a value for ***y*** that satisfies both equations. We can simply use it in either of the equations to determine the value of ***x***. Let's use the first one: \begin{equation}x + 6 = 16 \end{equation} When we work through this equation, we get a value for ***x***: \begin{equation}x = 10 \end{equation} So now we've calculated values for ***x*** and ***y***, and we find, just as we did with the graphical intersection method, that there are ten £10 chips and six £25 chips. You can run the following Python code to verify that the equations are both true with an ***x*** value of 10 and a ***y*** value of 6. ```python x = 10 y = 6 print ((x + y == 16) & ((10*x) + (25*y) == 250)) ``` True
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro ! This file was ported from Lean 3 source module data.finset.powerset ! leanprover-community/mathlib commit 9003f28797c0664a49e4179487267c494477d853 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Finset.Lattice import Mathlib.Data.Multiset.Powerset /-! # The powerset of a finset -/ namespace Finset open Function Multiset variable {α : Type _} {s t : Finset α} /-! ### powerset -/ section Powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : Finset α) : Finset (Finset α) := ⟨(s.1.powerset.pmap Finset.mk) fun _t h => nodup_of_le (mem_powerset.1 h) s.nodup, s.nodup.powerset.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩ #align finset.powerset Finset.powerset @[simp] theorem mem_powerset {s t : Finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s simp [powerset, mem_mk, mem_pmap, mk.injEq, mem_powerset, exists_prop, exists_eq_right, ← val_le_iff] #align finset.mem_powerset Finset.mem_powerset @[simp, norm_cast] theorem coe_powerset (s : Finset α) : (s.powerset : Set (Finset α)) = ((↑) : Finset α → Set α) ⁻¹' (s : Set α).powerset := by ext simp #align finset.coe_powerset Finset.coe_powerset --Porting note: remove @[simp], simp can prove it --Porting note: remove @[simp], simp can prove it theorem mem_powerset_self (s : Finset α) : s ∈ powerset s := mem_powerset.2 Subset.rfl #align finset.mem_powerset_self Finset.mem_powerset_self theorem powerset_nonempty (s : Finset α) : s.powerset.Nonempty := ⟨∅, empty_mem_powerset _⟩ #align finset.powerset_nonempty Finset.powerset_nonempty @[simp] theorem powerset_mono {s t : Finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨fun h => mem_powerset.1 <| h <| mem_powerset_self _, fun st _u h => mem_powerset.2 <| Subset.trans (mem_powerset.1 h) st⟩ #align finset.powerset_mono Finset.powerset_mono theorem powerset_injective : Injective (powerset : Finset α → Finset (Finset α)) := (injective_of_le_imp_le _) powerset_mono.1 #align finset.powerset_injective Finset.powerset_injective @[simp] theorem powerset_inj : powerset s = powerset t ↔ s = t := powerset_injective.eq_iff #align finset.powerset_inj Finset.powerset_inj @[simp] theorem powerset_empty : (∅ : Finset α).powerset = {∅} := rfl #align finset.powerset_empty Finset.powerset_empty @[simp] theorem powerset_eq_singleton_empty : s.powerset = {∅} ↔ s = ∅ := by rw [← powerset_empty, powerset_inj] #align finset.powerset_eq_singleton_empty Finset.powerset_eq_singleton_empty /-- **Number of Subsets of a Set** -/ @[simp] theorem card_powerset (s : Finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (Multiset.card_powerset s.1) #align finset.card_powerset Finset.card_powerset theorem not_mem_of_mem_powerset_of_not_mem {s t : Finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by apply mt _ h apply mem_powerset.1 ht #align finset.not_mem_of_mem_powerset_of_not_mem Finset.not_mem_of_mem_powerset_of_not_mem theorem powerset_insert [DecidableEq α] (s : Finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := by ext t simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff] by_cases h : a ∈ t · constructor · exact fun H => Or.inr ⟨_, H, insert_erase h⟩ · intro H cases' H with H H · exact Subset.trans (erase_subset a t) H · rcases H with ⟨u, hu⟩ rw [← hu.2] exact Subset.trans (erase_insert_subset a u) hu.1 · have : ¬∃ u : Finset α, u ⊆ s ∧ insert a u = t := by simp [Ne.symm (ne_insert_of_not_mem _ _ h)] simp [Finset.erase_eq_of_not_mem h, this] #align finset.powerset_insert Finset.powerset_insert /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/ instance decidableExistsOfDecidableSubsets {s : Finset α} {p : ∀ (t) (_ : t ⊆ s), Prop} [∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∃ (t : _)(h : t ⊆ s), p t h) := decidable_of_iff (∃ (t : _)(hs : t ∈ s.powerset), p t (mem_powerset.1 hs)) ⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_powerset.2 hs, hp⟩⟩ #align finset.decidable_exists_of_decidable_subsets Finset.decidableExistsOfDecidableSubsets /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/ instance decidableForallOfDecidableSubsets {s : Finset α} {p : ∀ (t) (_ : t ⊆ s), Prop} [∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∀ (t) (h : t ⊆ s), p t h) := decidable_of_iff (∀ (t) (h : t ∈ s.powerset), p t (mem_powerset.1 h)) ⟨fun h t hs => h t (mem_powerset.2 hs), fun h _ _ => h _ _⟩ #align finset.decidable_forall_of_decidable_subsets Finset.decidableForallOfDecidableSubsets /-- A version of `Finset.decidableExistsOfDecidableSubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableExistsOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ (t) (_h : t ⊆ s), Decidable (p t)) : Decidable (∃ (t : _)(_h : t ⊆ s), p t) := @Finset.decidableExistsOfDecidableSubsets _ _ _ hu #align finset.decidable_exists_of_decidable_subsets' Finset.decidableExistsOfDecidableSubsets' /-- A version of `Finset.decidableForallOfDecidableSubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableForallOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ (t) (_h : t ⊆ s), Decidable (p t)) : Decidable (∀ (t) (_h : t ⊆ s), p t) := @Finset.decidableForallOfDecidableSubsets _ _ _ hu #align finset.decidable_forall_of_decidable_subsets' Finset.decidableForallOfDecidableSubsets' end Powerset section Ssubsets variable [DecidableEq α] /-- For `s` a finset, `s.ssubsets` is the finset comprising strict subsets of `s`. -/ def ssubsets (s : Finset α) : Finset (Finset α) := erase (powerset s) s #align finset.ssubsets Finset.ssubsets @[simp] theorem mem_ssubsets {s t : Finset α} : t ∈ s.ssubsets ↔ t ⊂ s := by rw [ssubsets, mem_erase, mem_powerset, ssubset_iff_subset_ne, and_comm] #align finset.mem_ssubsets Finset.mem_ssubsets theorem empty_mem_ssubsets {s : Finset α} (h : s.Nonempty) : ∅ ∈ s.ssubsets := by rw [mem_ssubsets, ssubset_iff_subset_ne] exact ⟨empty_subset s, h.ne_empty.symm⟩ #align finset.empty_mem_ssubsets Finset.empty_mem_ssubsets /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for any ssubset. -/ instance decidableExistsOfDecidableSsubsets {s : Finset α} {p : ∀ (t) (_ : t ⊂ s), Prop} [∀ (t) (h : t ⊂ s), Decidable (p t h)] : Decidable (∃ t h, p t h) := decidable_of_iff (∃ (t : _)(hs : t ∈ s.ssubsets), p t (mem_ssubsets.1 hs)) ⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_ssubsets.2 hs, hp⟩⟩ #align finset.decidable_exists_of_decidable_ssubsets Finset.decidableExistsOfDecidableSsubsets /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for every ssubset. -/ instance decidableForallOfDecidableSsubsets {s : Finset α} {p : ∀ (t) (_ : t ⊂ s), Prop} [∀ (t) (h : t ⊂ s), Decidable (p t h)] : Decidable (∀ t h, p t h) := decidable_of_iff (∀ (t) (h : t ∈ s.ssubsets), p t (mem_ssubsets.1 h)) ⟨fun h t hs => h t (mem_ssubsets.2 hs), fun h _ _ => h _ _⟩ #align finset.decidable_forall_of_decidable_ssubsets Finset.decidableForallOfDecidableSsubsets /-- A version of `Finset.decidableExistsOfDecidableSsubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableExistsOfDecidableSsubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ (t) (_h : t ⊂ s), Decidable (p t)) : Decidable (∃ (t : _)(_h : t ⊂ s), p t) := @Finset.decidableExistsOfDecidableSsubsets _ _ _ _ hu #align finset.decidable_exists_of_decidable_ssubsets' Finset.decidableExistsOfDecidableSsubsets' /-- A version of `Finset.decidableForallOfDecidableSsubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidableForallOfDecidableSsubsets' {s : Finset α} {p : Finset α → Prop} (hu : ∀ (t) (_h : t ⊂ s), Decidable (p t)) : Decidable (∀ (t) (_h : t ⊂ s), p t) := @Finset.decidableForallOfDecidableSsubsets _ _ _ _ hu #align finset.decidable_forall_of_decidable_ssubsets' Finset.decidableForallOfDecidableSsubsets' end Ssubsets section PowersetLen /-- Given an integer `n` and a finset `s`, then `powersetLen n s` is the finset of subsets of `s` of cardinality `n`. -/ def powersetLen (n : ℕ) (s : Finset α) : Finset (Finset α) := ⟨((s.1.powersetLen n).pmap Finset.mk) fun _t h => nodup_of_le (mem_powersetLen.1 h).1 s.2, s.2.powersetLen.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩ #align finset.powerset_len Finset.powersetLen /-- **Formula for the Number of Combinations** -/ theorem mem_powersetLen {n} {s t : Finset α} : s ∈ powersetLen n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powersetLen, val_le_iff.symm] #align finset.mem_powerset_len Finset.mem_powersetLen @[simp] theorem powersetLen_mono {n} {s t : Finset α} (h : s ⊆ t) : powersetLen n s ⊆ powersetLen n t := fun _u h' => mem_powersetLen.2 <| And.imp (fun h₂ => Subset.trans h₂ h) id (mem_powersetLen.1 h') #align finset.powerset_len_mono Finset.powersetLen_mono /-- **Formula for the Number of Combinations** -/ @[simp] theorem card_powersetLen (n : ℕ) (s : Finset α) : card (powersetLen n s) = Nat.choose (card s) n := (card_pmap _ _ _).trans (Multiset.card_powersetLen n s.1) #align finset.card_powerset_len Finset.card_powersetLen @[simp] theorem powersetLen_zero (s : Finset α) : Finset.powersetLen 0 s = {∅} := by ext; rw [mem_powersetLen, mem_singleton, card_eq_zero] refine' ⟨fun h => h.2, fun h => by rw [h] exact ⟨empty_subset s, rfl⟩⟩ #align finset.powerset_len_zero Finset.powersetLen_zero @[simp] theorem powersetLen_empty (n : ℕ) {s : Finset α} (h : s.card < n) : powersetLen n s = ∅ := Finset.card_eq_zero.mp (by rw [card_powersetLen, Nat.choose_eq_zero_of_lt h]) #align finset.powerset_len_empty Finset.powersetLen_empty theorem powersetLen_eq_filter {n} {s : Finset α} : powersetLen n s = (powerset s).filter fun x => x.card = n := by ext simp [mem_powersetLen] #align finset.powerset_len_eq_filter Finset.powersetLen_eq_filter theorem powersetLen_succ_insert [DecidableEq α] {x : α} {s : Finset α} (h : x ∉ s) (n : ℕ) : powersetLen n.succ (insert x s) = powersetLen n.succ s ∪ (powersetLen n s).image (insert x) := by rw [powersetLen_eq_filter, powerset_insert, filter_union, ← powersetLen_eq_filter] congr rw [powersetLen_eq_filter, image_filter] congr 1 ext t simp only [mem_powerset, mem_filter, Function.comp_apply, and_congr_right_iff] intro ht have : x ∉ t := fun H => h (ht H) simp [card_insert_of_not_mem this, Nat.succ_inj'] #align finset.powerset_len_succ_insert Finset.powersetLen_succ_insert theorem powersetLen_nonempty {n : ℕ} {s : Finset α} (h : n ≤ s.card) : (powersetLen n s).Nonempty := by classical induction' s using Finset.induction_on with x s hx IH generalizing n · rw [card_empty, le_zero_iff] at h rw [h, powersetLen_zero] exact Finset.singleton_nonempty _ · cases n · simp · rw [card_insert_of_not_mem hx, Nat.succ_le_succ_iff] at h rw [powersetLen_succ_insert hx] refine' Nonempty.mono _ ((IH h).image (insert x)) exact subset_union_right _ _ #align finset.powerset_len_nonempty Finset.powersetLen_nonempty @[simp] theorem powersetLen_self (s : Finset α) : powersetLen s.card s = {s} := by ext rw [mem_powersetLen, mem_singleton] constructor · exact fun ⟨hs, hc⟩ => eq_of_subset_of_card_le hs hc.ge · rintro rfl simp #align finset.powerset_len_self Finset.powersetLen_self theorem pairwise_disjoint_powersetLen (s : Finset α) : Pairwise fun i j => Disjoint (s.powersetLen i) (s.powersetLen j) := fun _i _j hij => Finset.disjoint_left.mpr fun _x hi hj => hij <| (mem_powersetLen.mp hi).2.symm.trans (mem_powersetLen.mp hj).2 #align finset.pairwise_disjoint_powerset_len Finset.pairwise_disjoint_powersetLen theorem powerset_card_disjUnionᵢ (s : Finset α) : Finset.powerset s = (range (s.card + 1)).disjUnionᵢ (fun i => powersetLen i s) (s.pairwise_disjoint_powersetLen.set_pairwise _) := by refine' ext fun a => ⟨fun ha => _, fun ha => _⟩ · rw [mem_disjUnionᵢ] exact ⟨a.card, mem_range.mpr (Nat.lt_succ_of_le (card_le_of_subset (mem_powerset.mp ha))), mem_powersetLen.mpr ⟨mem_powerset.mp ha, rfl⟩⟩ · rcases mem_disjUnionᵢ.mp ha with ⟨i, _hi, ha⟩ exact mem_powerset.mpr (mem_powersetLen.mp ha).1 #align finset.powerset_card_disj_Union Finset.powerset_card_disjUnionᵢ theorem powerset_card_bunionᵢ [DecidableEq (Finset α)] (s : Finset α) : Finset.powerset s = (range (s.card + 1)).bunionᵢ fun i => powersetLen i s := by simpa only [disjUnionᵢ_eq_bunionᵢ] using powerset_card_disjUnionᵢ s #align finset.powerset_card_bUnion Finset.powerset_card_bunionᵢ theorem powerset_len_sup [DecidableEq α] (u : Finset α) (n : ℕ) (hn : n < u.card) : (powersetLen n.succ u).sup id = u := by apply le_antisymm · simp_rw [Finset.sup_le_iff, mem_powersetLen] rintro x ⟨h, -⟩ exact h · rw [sup_eq_bunionᵢ, le_iff_subset, subset_iff] cases' (Nat.succ_le_of_lt hn).eq_or_lt with h' h' · simp [h'] · intro x hx simp only [mem_bunionᵢ, exists_prop, id.def] obtain ⟨t, ht⟩ : ∃ t, t ∈ powersetLen n (u.erase x) := powersetLen_nonempty (le_trans (Nat.le_pred_of_lt hn) pred_card_le_card_erase) · refine' ⟨insert x t, _, mem_insert_self _ _⟩ rw [← insert_erase hx, powersetLen_succ_insert (not_mem_erase _ _)] exact mem_union_right _ (mem_image_of_mem _ ht) #align finset.powerset_len_sup Finset.powerset_len_sup @[simp] theorem powersetLen_card_add (s : Finset α) {i : ℕ} (hi : 0 < i) : s.powersetLen (s.card + i) = ∅ := Finset.powersetLen_empty _ (lt_add_of_pos_right (Finset.card s) hi) #align finset.powerset_len_card_add Finset.powersetLen_card_add @[simp] theorem map_val_val_powersetLen (s : Finset α) (i : ℕ) : (s.powersetLen i).val.map Finset.val = s.1.powersetLen i := by simp [Finset.powersetLen, map_pmap, pmap_eq_map, map_id'] #align finset.map_val_val_powerset_len Finset.map_val_val_powersetLen theorem powersetLen_map {β : Type _} (f : α ↪ β) (n : ℕ) (s : Finset α) : powersetLen n (s.map f) = (powersetLen n s).map (mapEmbedding f).toEmbedding := ext <| fun t => by simp only [card_map, mem_powersetLen, le_eq_subset, gt_iff_lt, mem_map, mapEmbedding_apply] constructor . classical intro h have : map f (filter (fun x => (f x ∈ t)) s) = t := by ext x simp only [mem_map, mem_filter, decide_eq_true_eq] exact ⟨fun ⟨_y, ⟨_hy₁, hy₂⟩, hy₃⟩ => hy₃ ▸ hy₂, fun hx => let ⟨y, hy⟩ := mem_map.1 (h.1 hx); ⟨y, ⟨hy.1, hy.2 ▸ hx⟩, hy.2⟩⟩ refine' ⟨_, _, this⟩ rw [← card_map f, this, h.2]; simp . rintro ⟨a, ⟨has, rfl⟩, rfl⟩ simp [*] #align finset.powerset_len_map Finset.powersetLen_map end PowersetLen end Finset
{-# OPTIONS --without-K --safe #-} -- Pi combinators inspired by duals and traced monoidal categories module PiPointedFracTrace where open import Data.Unit open import Data.Sum open import Data.Product open import Relation.Binary.PropositionalEquality open import PiPointedFrac ------------------------------------------------------------------ dual : {A B : ∙𝕌} → (f : A ∙⟶ B) → (Recipᵤ B ∙⟶ Recipᵤ A) dual {A} {B} f = ∙uniti⋆l ∙⊚ (η A ∙⊗ ∙id⟷) ∙⊚ ((∙Singᵤ f ∙⊗ ∙id⟷) ∙⊗ ∙id⟷) ∙⊚ ∙assocr⋆ ∙⊚ (∙id⟷ ∙⊗ ∙swap⋆) ∙⊚ ∙assocl⋆ ∙⊚ (ε B ∙⊗ ∙id⟷) ∙⊚ ∙unite⋆l -- name, coname name : {A B : ∙𝕌} → (f : A ∙⟶ B) → ∙𝟙 ∙⟶ Singᵤ B ∙×ᵤ Recipᵤ A name {A} {B} f = η A ∙⊚ (∙Singᵤ f ∙⊗ ∙id⟷) coname : {A B : ∙𝕌} → (f : A ∙⟶ B) → Singᵤ A ∙×ᵤ Recipᵤ B ∙⟶ ∙𝟙 coname {A} {B} f = (∙Singᵤ f ∙⊗ ∙id⟷) ∙⊚ ε B -- and 'trace' reveals something neat: we can't choose just any random 'a' and 'c' -- to start with, but we need that make a coherence choice of a and c !! trace : {A B C : ∙𝕌} → (f : A ∙×ᵤ C ∙⟶ B ∙×ᵤ C) → A ∙⟶ B trace {A} {B} {C} f = ∙uniti⋆r ∙⊚ -- A ×ᵤ 1 (return _ ∙⊗ η C) ∙⊚ -- A ×ᵤ (C ×ᵤ 1/C) ∙assocl⋆ ∙⊚ -- (A ×ᵤ C) ×ᵤ 1/C (tensor ∙⊗ ∙id⟷) ∙⊚ -- bring in the ● (∙Singᵤ f ∙⊗ ∙id⟷) ∙⊚ -- (B ×ᵤ C) ×ᵤ 1/C (untensor ∙⊗ ∙id⟷) ∙⊚ -- bring out the ● ∙assocr⋆ ∙⊚ -- B ×ᵤ (C ×ᵤ 1/C) (extract _ ∙⊗ ε C) ∙⊚ ∙unite⋆r -- Trace terminates! The type C is pointed with point c; trace uses c -- as the initial value for C. So f gets two values (a,c). It can do -- whatever to produce (b',c'). But f is reversible so it is limited -- to essentially either id or swap. Makes sense??? 𝔹 : 𝕌 𝔹 = 𝟙 +ᵤ 𝟙 𝔽 𝕋 : ⟦ 𝔹 ⟧ 𝔽 = inj₁ tt 𝕋 = inj₂ tt zz1 : (A : 𝕌) (v : ⟦ A ⟧) → Σ (⟦ A ⟧ → ⟦ A ⟧) (λ f → f v ≡ v) zz1 A v = ∙eval (trace {A # v} ∙swap⋆) zz3 : (A : 𝕌) (v : ⟦ A ⟧) (T : ∙𝕌) → Σ (⟦ A ⟧ → ⟦ A ⟧) (λ f → f v ≡ v) zz3 A v T = ∙eval (trace {A # v} {_} {T} ∙id⟷) -- There are more thing you can put in trace as long as c is the fixpoint NOT : 𝔹 ⟷ 𝔹 NOT = swap₊ CONTROLLED : {A : 𝕌} → (A ⟷ A) → 𝔹 ×ᵤ A ⟷ 𝔹 ×ᵤ A CONTROLLED c = dist ⊚ (id⟷ ⊕ (id⟷ ⊗ c)) ⊚ factor CNOT : 𝔹 ×ᵤ 𝔹 ⟷ 𝔹 ×ᵤ 𝔹 CNOT = CONTROLLED NOT ex1 : ∀ {b} → 𝔹 # b ∙⟶ 𝔹 # b ex1 = trace {C = 𝔹 # 𝔽} (∙swap⋆ ∙⊚ ∙#times ∙⊚ ∙c CNOT ∙⊚ ∙times# ∙⊚ ∙swap⋆) -- Example in Sec. 4.3 from Abramsky's paper -- http://www.cs.ox.ac.uk/files/341/calco05.pdf ∙q : {A1 A2 A3 A4 B1 B2 B3 B4 : ∙𝕌} → (f1 : A1 ∙⟶ B2) → (f2 : A2 ∙⟶ B4) → (f3 : A3 ∙⟶ B3) → (f4 : A4 ∙⟶ B1) → A1 ∙×ᵤ (A2 ∙×ᵤ (A3 ∙×ᵤ A4)) ∙⟶ B1 ∙×ᵤ (B2 ∙×ᵤ (B3 ∙×ᵤ B4)) ∙q {A1} {A2} {A3} {A4} {B1} {B2} {B3} {B4} f1 f2 f3 f4 = (f1 ∙⊗ (f2 ∙⊗ (f3 ∙⊗ f4))) ∙⊚ ∙assocl⋆ ∙⊚ ∙swap⋆ ∙⊚ ∙swap⋆ ∙⊗ ∙id⟷ ∙⊚ ∙assocr⋆ ∙⊚ (∙id⟷ ∙⊗ ∙assocl⋆) ∙⊚ ∙id⟷ ∙⊗ (∙swap⋆ ∙⊗ ∙id⟷ ∙⊚ ∙assocr⋆) ∙q' : {A1 U2 U3 U4 B1 : ∙𝕌} → (f1 : A1 ∙⟶ U2) → (f2 : U2 ∙⟶ U4) → (f3 : U3 ∙⟶ U3) → (f4 : U4 ∙⟶ B1) → A1 ∙⟶ B1 ∙q' f1 f2 f3 f4 = trace (∙q f1 f2 f3 f4) _⊸_ : (A B : ∙𝕌) → ∙𝕌 A ⊸ B = Recipᵤ A ∙×ᵤ Singᵤ B id⊸ : {A : ∙𝕌} → (A ⊸ A) ∙⟶ ∙𝟙 id⊸ {A} = ∙swap⋆ ∙⊚ ε A comp⊸ : (A B C : ∙𝕌) → (A ⊸ B) ∙×ᵤ (B ⊸ C) ∙⟶ (A ⊸ C) comp⊸ A B C = ∙assocr⋆ ∙⊚ ∙id⟷ ∙⊗ ∙assocl⋆ ∙⊚ ∙id⟷ ∙⊗ (ε B ∙⊗ ∙id⟷) ∙⊚ ∙id⟷ ∙⊗ ∙unite⋆l app : (A B : ∙𝕌) → (A ⊸ B) ∙×ᵤ Singᵤ A ∙⟶ Singᵤ B app A B = ∙swap⋆ ∙⊗ ∙id⟷ ∙⊚ ∙assocr⋆ ∙⊚ (∙id⟷ ∙⊗ (∙swap⋆ ∙⊚ ε A)) ∙⊚ ∙unite⋆r -- B/A × D/C ⟷ B × D / A × C dist×/ : {A B C D : ∙𝕌} → (A ⊸ B) ∙×ᵤ (C ⊸ D) ∙⟶ ((A ∙×ᵤ C) ⊸ (B ∙×ᵤ D)) dist×/ {A} {B} {C} {D} = ∙assocr⋆ ∙⊚ (∙id⟷ ∙⊗ ∙assocl⋆) ∙⊚ ∙id⟷ ∙⊗ (∙swap⋆ ∙⊗ ∙id⟷) ∙⊚ (∙id⟷ ∙⊗ ∙assocr⋆) ∙⊚ ∙assocl⋆ ∙⊚ c ∙⊗ tensor where c : (Recipᵤ A ∙×ᵤ Recipᵤ C) ∙⟶ Recipᵤ (A ∙×ᵤ C) c = ∙uniti⋆l ∙⊚ (η (A ∙×ᵤ C) ∙⊗ ∙id⟷) ∙⊚ (∙swap⋆ ∙⊗ ∙id⟷) ∙⊚ ∙assocr⋆ ∙⊚ (∙id⟷ ∙⊗ (untensor ∙⊗ ∙id⟷)) ∙⊚ (∙id⟷ ∙⊗ (∙swap⋆ ∙⊗ ∙id⟷)) ∙⊚ (∙id⟷ ∙⊗ ∙assocr⋆) ∙⊚ (∙id⟷ ∙⊗ (∙id⟷ ∙⊗ ∙assocl⋆)) ∙⊚ (∙id⟷ ∙⊗ (∙id⟷ ∙⊗ ((ε A ∙⊗ ∙id⟷) ∙⊚ ∙unite⋆l))) ∙⊚ (∙id⟷ ∙⊗ ε C) ∙⊚ ∙unite⋆r -- 1/A x 1/B <-> 1 / (A x B) rev× : {A B : ∙𝕌} → (A ⊸ ∙𝟙) ∙×ᵤ (B ⊸ ∙𝟙) ∙⟶ (A ∙×ᵤ B ⊸ ∙𝟙) rev× {A} {B} = dist×/ ∙⊚ (∙id⟷ ∙⊗ ∙Singᵤ ∙unite⋆l) -- (A <-> B) -> (1/A <-> 1/B) rev : {A B : ∙𝕌} → (f : A ∙⟶ B) → Recipᵤ B ∙⟶ Recipᵤ A rev {A} {B} f = dual f -- A <-> 1 / (1/A) revrev : {A : ∙𝕌} → Singᵤ A ∙⟶ Recipᵤ (Recipᵤ A) revrev {A} = ∙uniti⋆r ∙⊚ ∙id⟷ ∙⊗ η (Recipᵤ A) ∙⊚ ∙assocl⋆ ∙⊚ ((∙id⟷ ∙⊗ extract (Recipᵤ A)) ∙⊗ ∙id⟷) ∙⊚ (ε A ∙⊗ ∙id⟷) ∙⊚ ∙unite⋆l
Townsend returned to the stage in January 2010 , touring North America with headliner Between the Buried and Me as well as Cynic and Scale the Summit . This was followed by a headlining tour in Australia and a series of high @-@ profile shows in Europe ( for example co @-@ headlining the Brutal Assault festival in Czech Republic ) . He headlined a North American tour with UK label mates <unk> supporting , which began in October 2010 , and toured in Europe with support from Aeon Zen and Anneke van Giersbergen .
= = = World War II = = =
= = = World War II = = =
= = = World War II = = =
In this chapter, the origin of blockchain, its concepts, terms, related technique will be introduced, which lays the foundation of the whole master thesis. It starts from Bitcoin, where the blockchain technology was originated. Then followed by the process of its development and derivatives. \section{Bitcoin} Digital currencies (e.g. Flooz, Beenz) appeared with the tech tide in the 90s, which would have made the online payment and transaction more convenient, however, most of those systems utilized a trusted third party (TTP) approach, meaning that the two-party trusted company verified and facilitated the transactions. On the one hand, this method will inevitable encounter single-failure problem, on the other hand, usual framework of digital currency made from digital signature may cause the double-spending problem. \textbf{Double-spending} \\ This problem is a potential flaw in a cryptocurrency or other digital cash scheme whereby the same single digital token can be spent more than once, and this is possible because a digital token consists of a digital file that can be duplicated or falsified. \cite{DoubleSpend} \begin{figure}[H]% order of placement preference: here, top, bottom \includegraphics[width=\textwidth]{charts/DoubleSpend} \caption{Alice and Bob received repeated transaction } \end{figure} In 2008, a paper "Bitcoin: A Peer-to-Peer Electronic Cash System", written by Satoshi Nakamoto appeared on a US mailing list. This is the very beginning of Bitcoin. It proposed a mechanism based on the peer-to-peer network, using proof-of-work to record the public history of a transaction that quickly becomes computationally impractical for an attacker to change if honest nodes control a majority of CPU power. The network timestamps transactions by hashing them into an ongoing chain of hash-based proof-of-work, forming a record that cannot be changed without redoing the proof-of-work.\cite{sn} Bitcoin brought together a set of techniques to enable the distrusting entities to transact directly with a digital currency. The following several elements are very important to help build Bitcoin system. \subsection{Peer-to-peer network} In a general client-server network, a server takes charge of preservation and operation of data while clients request the server for the access of data and resource. On the contrary, in a P2P network, all participating nodes (referring to computers, also called "peers") hold data respectively and create an autonomous network wherein data are requested, meaning that each node acts both of server and client. P2P nodes have significant or total autonomy from central servers. P2P networking technology has contributed to developing a base for a complete distributed network and eliminating single point of failure in Bitcoin. \subsection{Cryptographic hash function} A Cryptographic hash function is any function that can be used to map data of arbitrary size to data of a fixed size. This mechanism is characterized by the fact that the same hash value is obtained from the same data but only a slight difference in the original data results in a completely different hash value. It is extremely difficult to infer the original data based on a hash value (non-invertible feature). Taking advantage of such characteristics, this mechanism is used for the detection of falsification of data, and in the Bitcoin system, it is used for the verification and guarantee the continuity of blockchain data and the creation of blockchain through Proof of Work utilizing the calculation of hash value. \subsection{Consensus Mechanism} The distributed nature of the peer-to-peer network requires the members (nodes) in the network to reach a consensus which validates the new coming data blocks which contain transactions by following a set of rules. The rules are specified in the algorithmic design of the blockchain system and can vary depending on its nature, purpose, and underlying asset. In Bitcoin system, participants begin to propose the transactions. Before a transaction is allowed to be added to the global ledgers, other participants (also called miners) in the network first verify the validation of the transaction by solving a computational problem, once it is solved, they propagate answers to other miners along with the block of transactions. The other miners will accept the solutions along with the block of transactions and add those transactions to the global ledger. The Bitcoin transaction process is explained in the Figure 2.2. The Bitcoin system, uses "Proof of work" (PoW) algorithm to establish consensus. Other frequently are used algorithms like Proof of Stake(PoS), Practical Byzantine Fault Tolerance (PBFT). \begin{figure}[!htb]% order of placement preference: here, top, bottom \includegraphics[width=\textwidth]{charts/BitcoinTx} \caption{Overview: Path of a Bitcoin Transaction\cite{sn}} \end{figure} \begin{itemize} \item \textbf{Proof-of-Work} Proof-of-Work (PoW) generally refers to a mechanism to confirm a node’s request for add a block (a block might contain several transactions) to the blockchain that involves solving a computational challenging puzzle in order to create a new block. PoW is also called mining in Bitcoin. \item \textbf{Proof-of-Stake} The Proof of Stake (PoS) algorithm is an energy-saving generalization of the Proof of Work algorithm. In PoS, the nodes are known as the "validators" and, rather than mining the blockchain they validate the transactions to earn a transaction fee. It based on the idea that the more stake of a node has, the more capable it can mine a block successfully. Thus nodes are randomly selected to validate blocks, and the probability of this random selection depends on the amount of stake held. \item \textbf{ Practical Byzantine Fault Tolerance (PBFT)} PBFT is an algorithm for solving a \textbf{Byzantine Fault} resulting from a failure in building a consensus caused by the Byzantine Generals Problem. Simply speaking, this algorithm ensures the consistency of consensus as long as two thirds of the network’s nodes are safe (i.e., not malicious or faulty). This is enabled by replicating behaviors (i.e., state machines) of generating nodes and applying protocols for choosing a leader among them. However, this method requires that all the generating nodes know each other since they need to communicate. In other words, all the parties have to agree on the exact list of participants. \cite{pbft} \item \textbf{Tendermint \cite{tendermint}} Tendermint is another byzantine consensus algorithm without mining work. It makes the assumption that the network is partially synchronized since the time factor is central to this protocol. For each new block, a validator node is selected in a round-robbin manner which has to propose a block. This block is then spread into the network and has to gather more than two thirds of votes of members within a given time period before being added to the blockchain. However, these members are selected based on their stake and thus ties trust to resource ownership. \end{itemize} \begin{table}[H] \centering % \includegraphics[scale=0.9]{charts/consensus} \ra{1.3} \begin{tabular}{{m}{3cm}ccccc}\toprule[0.5mm] Property & PoW & PoS & PBFT & Tendermint\\ \midrule[0.3mm] Use case & Bitcoin & Gridcoin & Hyperledger Fabric& Tendermint\\ Energy saving & No&Partly&Yes&Yes\\ Mining process & Yes & No & No & No\\ Block creating speed& Slow&Fast&Fast&Fast\\ Forking& Yes, very likely&hard&No&No\\ \bottomrule[0.5mm] \end{tabular} \caption{Typical Consensus Algorithms Comparison} \end{table} In the PoW the mining process is a brute-force approach, thus that is rather energy-consuming. While other algorithms without the mining process will be much more efficient. It also reflects on the speed of generating blocks. In the PoW, forking can happen if two miners find a suitable nonce at the same time. Meanwhile with PoS, it is very difficult, happening only when a miner can own up to 51\% of all stake in the whole verifying network. In the BFT-like consensus, e.g. PBFT and Tendermint, the validation essentially bases on the voting, it hardly forks. \section{Blockchain Technology} Blockchain originally came from Bitcoin's basic technology, referring a series of blocks created through PoW, and those blocks compiling transaction data for a certain period of time are linked into a chain. With the generalization of blockchain technology, it has more wide definition. Blockchain is a particular type of data structure used in some distributed ledgers which stores and transmits data in packages called "blocks" that are connected to each other in a "chain". Blockchain employs cryptographic and algorithmic methods to record and synchronize data across a network in an immutable manner. \cite{WBank} \begin{figure}[!htb]% order of placement preference: here, top, bottom \includegraphics[width=\textwidth]{charts/blocks} \caption{blockchain appeared in Satoshi Nakamoto's paper} \end{figure} \subsection{Distributed Ledger Technology(DLT)} Whenever the term blockchain is talked, frequently the related key word DTL would be mentioned. Distributed Ledger Technology actually exists prior to Bitcoin, at least those techniques it represents are quite mature then. DLT is actually an umbrella term to the technology which is simply a decentralized database that is managed by various participants. Bitcoin blockchain is a milestone, which indicates the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer networks, cryptography, and shared computational power, along with a new consensus algorithm. Distributed Ledger Technology generally consists of three basic components\cite{sawtooth} \begin{description} \item [$\bullet$ A data model]that captures the current state of the ledger \item [$\bullet$ A transactions flow] that changes the ledger state \item [$\bullet$ A protocol] used to build consensus among participants around which transactions will be accepted, and in what order, by the ledger. \end{description} \textbf{Blockchain}, a particular type of DLT, uses cryptographic and algorithmic methods to create and verify a continuously growing, append-only data structure that takes the form of a chain of so called 'transaction blocks' – the blockchain – which serves the function of a ledger.\cite{WBank} \subsection{Components of Blockchain system} Having the foundation of Bitcoin's concept and DLT's structure, if we want to build a blockchain system, those components are likely required. \begin{outline} \1 \textbf{Peer-to-peer network architecture}\\ Due to the distributed nature, that each node in the network should keep a copy of the ledger. p2p network is the essential innovation shift to decentralized system. \1 \textbf{Consensus mechanism}\\ As mentioned above, how consensus mechanism impacts the success of a blockchain system. It helps to validate the transaction, without the trusted third party. \1 \textbf{Smart contract}\\ Smart contracts are simply predefined computer programs that execute actions when pre-agreed conditions within the system are met. Smart contracts provide the language of transactions that allow the ledger state to be modified. They can facilitate the business logic (e.g. the exchange of shares, money, content, property). Smart contracts can be done in traditional centralized ledger systems as well, but the design of centralized ledger systems require such actions to be implemented only after the concerned parties have agreed to the underlying transaction as recorded in the central system. \2 \textbf{Decentralized Autonomous Organization(DAO)}\\ A DAO can be seen as the most complex form of a smart contract, where the bylaws of the decentralized organization are embedded into the code of the smart contract, using complex token governance rules. At today’s evolutionary stage, a DAO materializes as a smart contract – a piece of code – executed on top of an increasingly opaque stack of distributed networking and consensus technology like the Ethereum blockchain or similar blockchains.\cite{dao} \1 \textbf{Cryptography}\\ Cryptography has a key role to play both in the security, as well as in the immutability of the transactions recorded on blockchain . Cryptography is the study of the techniques used to allow secure communication between different parties and to ensure the authenticity and immutability of the data being communicated. For blockchain technology, cryptography is used to prove that a transaction was created by the right person. It is also used to link transactions into a block in a tamper-proof way, as well as create the links between blocks, to form a blockchain. \end{outline} \subsection{Types of Blockchain System} Blockchain systems can be categorized as permissionless and permissioned. \textbf{Permissioned blockchain system} means that the parties that join the network are authenticated and authorized by an entity or an administrator of the ledgers to participate on the network. while in \textbf{permissionless blockchain systems}, there is no central owner who controls network access. All that is needed to join the network and add transactions to the ledger is a server with the software. The detailed comparisons are in the following Figure 2.4.\\ \begin{figure}[!htb]% order of placement preference: here, top, bottom \includegraphics[width=\textwidth]{charts/permission} \caption{Comparison of permissioned and permissionless DLT} \end{figure} In permissionless blockchain systems, like the Bitcoin or the Ethereum, anyone can join the network, as well as write and read transactions. The actors in the system are not known, which means there could be some malicious actors within the network. Permissioned blockchain reduces these security risks and ensures that only the parties with valid identification can transact. There are several examples which base on the essential blockchain concepts and establish customized blockchain systems, which provide developers and companies with the architecture, where they can develop their own Dapps (Decentralized Applications). \begin{itemize} \item \textbf{Ethereum} is an open blockchain platform(permissionless) that lets anyone build and use decentralized applications that run on blockchain technology.\cite{EthereumWhitePaper} As the most popular blockchain for smart contracts, it facilitates the scripting functionality, or smart contracts which are run through the nodes in the network. \item \textbf{Hyperledger Fabric} is a permissioned blockchain framework and one of the Hyperledger projects hosted by The Linux Foundation. Intended to create enterprise grade, open source, distributed framework for developing applications or solutions with a modular architecture. \item \textbf{Corda} is permissioned platform developed by R3 in collaboration with over 200 technology and industry partners. Smart contracts allow Corda to do this using complex agreements and any asset type. This capability has broad applications across industries including finance, supply chain and healthcare. \item \textbf{IOTA} refers not only a cryptocurrency, but also a platform that entails a generalization of the blockchain protocol (the technology called Tangle) that sits at the backend of the IOTA platform. It enables machine-to-machine (M2M) transactions, which enhances the use of connected devices or the Internet of Things. \end{itemize} \subsection{Application of Blockchain Technology} Deriving from Bitcoin, blockchain technology has a breadth of potential applications beyond cryptocurrencies in the financial field and in a wide variety of other industries. According to World Bank's white paper, The two biggest trends in the development of blockchain applications are: 1) commercial Fintech start-ups are developing digital applications for a variety of purposes that utilize the public blockchain infrastructure, mostly Bitcoin and Ethereum; 2) industry consortia are forming to research and develop private, permissioned blockchain to solve industry-specific enterprise solutions. Actually the blockchain technology has been widely tried, in 2016 Nomura Research Institute have alreday conduct a survey on Blockchain Technologies, it visualized those applications based on Blockchain. \begin{figure}[!htb]% order of placement preference: here, top, bottom \includegraphics[width=\textwidth]{charts/Fields} \caption{Use cases and exmaples of services using blockchains\cite{JapanS}} \end{figure} \begin{itemize} \item \textbf{Finance}\\ Ripple is one of the representative blockchains in this field. \item \textbf{Loyalty points and reward}\\ GyftBlock, which provides an exchange service of gift cards using a blockchain. \item \textbf{Funding}\\ Swarm provides a service to procure funds through cloud funding on a blockchain. \item \textbf{Communication}\\ Messaging services and social networking services (SNS) have been made available using blockchains. \item \textbf{Asset management}\\ Factom, etc. commenced the provision of a service. \item \textbf{Storage} Storj provides a service to manage various electronic files using a blockchain. Similar application like BigchainDB. \item \textbf{Authentication}\\ uPort is a self-sovereign identity and user-centric data platform. \item \textbf{Sharing}\\ LaZooZ aims to provide a sharing service using a blockchain. At present, it provides a ride sharing application like Uber. \item \textbf{Commercial distribution management:}\\ Everledger provides a system to manage diamonds. The serial number and carat, various commodity information, ownership and distribution record of each diamond are managed. \item \textbf{Content}\\ Streamium provides a service to support content delivery, having established a system to charge by the second (paid with bitcoins) for video delivery, etc. \item \textbf{Prediction}\\ Augur provides a decentralized prediction market platform where participants cast votes on various events to predict the future through the wisdom of the crowd. \item \textbf{Public}\\ Neutral Voting Bloc (NVB) is a service provided in Australia, advocating itself as a new political party. \item \textbf{Medical services}\\ BitHealth aims to achieve its goal to enable users to safely check their own health records from anywhere in the world using a blockchain. \item \textbf{IoT}\\ Such services as ADEPT by IBM and Samsung are attracting attention. \end{itemize}
State Before: α : Type u_1 α✝ : Type u_2 f : α✝ → α → α✝ init : α✝ t : RBNode.Stream α ⊢ foldl f init t = List.foldl f init (toList t) State After: no goals Tactic: induction t generalizing init <;> simp [-List.foldl] <;> simp [*, RBNode.foldl_eq_foldl_toList]
$ \begin{align} a_1&=b_1+c_1 \tag{1}\\ a_2&=b_2+c_2+d_2 \tag{2}\\ a_3&=b_3+c_3 \tag{3} \end{align} $ [Euler](https://krasjet.github.io/quaternion/bonus_gimbal_lock.pdf) [Quaternion](https://krasjet.github.io/quaternion/bonus_gimbal_lock.pdf) [Source](https://github.com/Krasjet/quaternion) ```python ``` ```python ```
-- Idris2 import System import System.Concurrency -- Test `conditionBroadcast` wakes the child with 1 main and 1 child thread main : IO () main = do cvMutex <- makeMutex cv <- makeCondition t <- fork $ do mutexAcquire cvMutex conditionWait cv cvMutex putStrLn "Hello mother" putStrLn "Hello child" sleep 1 conditionBroadcast cv threadWait t
\subsection{Marshallian demand} We can write a demand function: \(x_i=f(I, \mathbf p)\) We can derive this from the first-order conditions of a specific utility function.
Andrew was promoted to sergeant the day after his VC @-@ winning action . He continued to serve on the front until early 1918 , when he was sent to England for officer training . He was commissioned as a second lieutenant in March 1918 , but remained in England until the end of the war .
lemma degree_diff_le_max: "degree (p - q) \<le> max (degree p) (degree q)" for p q :: "'a::ab_group_add poly"
Load LFindLoad. From lfind Require Import LFind. Unset Printing Notations. Set Printing Implicit. Require Import Nat. Inductive lst : Type := | Nil : lst | Cons : nat -> lst -> lst. Fixpoint len (l : lst) : nat := match l with | Nil => 0 | Cons a l1 => 1 + (len l1) end. Fixpoint rev (l1 l2: lst): lst := match l1 with | Nil => l2 | Cons x l1' => rev l1' (Cons x l2) end. Lemma list_rev2_len_lem: forall l1 l2, len (rev l1 l2) = (len l1) + (len l2). Proof. induction l1. - simpl. reflexivity. - simpl. intros. rewrite IHl1. simpl. rewrite <- plus_n_Sm. reflexivity. Qed. Theorem list_rev2_len: forall l: lst, len (rev l Nil) = len l. Proof. induction l. - simpl. reflexivity. - lfind. Admitted.
module Text.CSS import public Text.CSS.Color import public Text.CSS.Dir import public Text.CSS.Declaration import public Text.CSS.Flexbox import public Text.CSS.Grid import public Text.CSS.Length import public Text.CSS.ListStyleType import public Text.CSS.Percentage import public Text.CSS.Property import public Text.CSS.Render import public Text.CSS.Rule import public Text.CSS.Selector
# NRPy+'s Reference Metric Interface ## Author: Zach Etienne ### Formatting improvements courtesy Brandon Clark ### NRPy+ Source Code for this module: [reference_metric.py](../edit/reference_metric.py) ## Introduction: ### Why use a reference metric? Benefits of choosing the best coordinate system for the problem When solving a partial differential equation on the computer, it is useful to first pick a coordinate system well-suited to the geometry of the problem. For example, if we are modeling a spherically-symmetric star, it would be hugely wasteful to model the star in 3-dimensional Cartesian coordinates ($x$,$y$,$z$). This is because in Cartesian coordinates, we would need to choose high sampling in all three Cartesian directions. If instead we chose to model the star in spherical coordinates ($r$,$\theta$,$\phi$), so long as the star is centered at $r=0$, we would not need to model the star with more than one point in the $\theta$ and $\phi$ directions! A similar argument holds for stars that are *nearly* spherically symmetric. Such stars may exhibit density distributions that vary slowly in $\theta$ and $\phi$ directions (e.g., isolated neutron stars or black holes). In these cases the number of points needed to sample the angular directions will still be much smaller than in the radial direction. Thus choice of an appropriate reference metric may directly mitigate the [Curse of Dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality). <a id='toc'></a> # Table of Contents $$\label{toc}$$ This notebook is organized as follow 1. [Step 1](#define_ref_metric): Defining a reference metric, [`reference_metric.py`](../edit/reference_metric.py) 1. [Step 2](#define_geometric): Defining geometric quantities, **`ref_metric__hatted_quantities()`** 1. [Step 3](#prescribed_ref_metric): Prescribed reference metrics in [`reference_metric.py`](../edit/reference_metric.py) 1. [Step 3.a](#sphericallike): Spherical-like coordinate systems 1. [Step 3.a.i](#spherical): **`reference_metric::CoordSystem = "Spherical"`** 1. [Step 3.a.ii](#sinhspherical): **`reference_metric::CoordSystem = "SinhSpherical"`** 1. [Step 3.a.iii](#sinhsphericalv2): **`reference_metric::CoordSystem = "SinhSphericalv2"`** 1. [Step 3.b](#cylindricallike): Cylindrical-like coordinate systems 1. [Step 3.b.i](#cylindrical): **`reference_metric::CoordSystem = "Cylindrical"`** 1. [Step 3.b.ii](#sinhcylindrical): **`reference_metric::CoordSystem = "SinhCylindrical"`** 1. [Step 3.b.iii](#sinhcylindricalv2): **`reference_metric::CoordSystem = "SinhCylindricalv2"`** 1. [Step 3.c](#cartesianlike): Cartesian-like coordinate systems 1. [Step 3.c.i](#cartesian): **`reference_metric::CoordSystem = "Cartesian"`** 1. [Step 3.c.ii](#sinhcartesian): **`reference_metric::CoordSystem = "SinhCartesian"`** 1. [Step 3.d](#prolatespheroidal): Prolate spheroidal coordinates 1. [Step 3.d.i](#symtp): **`reference_metric::CoordSystem = "SymTP"`** 1. [Step 3.d.ii](#sinhsymtp): **`reference_metric::CoordSystem = "SinhSymTP"`** 1. [Step 4](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file <a id='define_ref_metric'></a> # Step 1: Defining a reference metric, [`reference_metric.py`](../edit/reference_metric.py) \[Back to [top](#toc)\] $$\label{define_ref_metric}$$ ***Note that currently only orthogonal reference metrics of dimension 3 or fewer are supported. This can be extended if desired.*** NRPy+ assumes all curvilinear coordinate systems map directly from a uniform, Cartesian numerical grid with coordinates $(x,y,z)$=(`xx[0]`,`xx[1]`,`xx[2]`). Thus when defining reference metrics, all defined coordinate quantities must be in terms of the `xx[]` array. As we will see, this adds a great deal of flexibility For example, [**reference_metric.py**](../edit/reference_metric.py) requires that the *orthogonal coordinate scale factors* be defined. As described [here](https://en.wikipedia.org/wiki/Curvilinear_coordinates), the $i$th scale factor is the positive root of the metric element $g_{ii}$. In ordinary spherical coordinates $(r,\theta,\phi)$, with line element $ds^2 = g_{ij} dx^i dx^j = dr^2+ r^2 d \theta^2 + r^2 \sin^2\theta \ d\phi^2$, we would first define * $r = xx_0$ * $\theta = xx_1$ * $\phi = xx_2$, so that the scale factors are defined as * `scalefactor_orthog[0]` = $1$ * `scalefactor_orthog[1]` = $r$ * `scalefactor_orthog[2]` = $r \sin \theta$ Here is the corresponding code: ```python import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends import NRPy_param_funcs as par # NRPy+: parameter interface import reference_metric as rfm # NRPy+: Reference metric support r = rfm.xx[0] th = rfm.xx[1] ph = rfm.xx[2] rfm.scalefactor_orthog[0] = 1 rfm.scalefactor_orthog[1] = r rfm.scalefactor_orthog[2] = r*sp.sin(th) # Notice that the scale factor will be given # in terms of the fundamental Cartesian # grid variables, and not {r,th,ph}: print("r*sin(th) = "+str(rfm.scalefactor_orthog[2])) ``` r*sin(th) = xx0*sin(xx1) Next suppose we wish to modify our radial coordinate $r(xx_0)$ to be an exponentially increasing function, so that our numerical grid $(xx_0,xx_1,xx_2)$ will map to a spherical grid with radial grid spacing ($\Delta r$) that *increases* with $r$. Generally we will find it useful to define $r(xx_0)$ to be an odd function, so let's choose $$r(xx_0) = a \sinh(xx_0/s),$$ where $a$ is an overall radial scaling factor, and $s$ denotes the scale (in units of $xx_0$) over which exponential growth will take place. In our implementation below, note that we use the relation $$\sinh(x) = \frac{e^x - e^{-x}}{2},$$ as SymPy finds it easier to evaluate exponentials than hyperbolic trigonometric functions. ```python a,s = sp.symbols('a s',positive=True) xx0_rescaled = rfm.xx[0] / s r = a*(sp.exp(xx0_rescaled) - sp.exp(-xx0_rescaled))/2 # Must redefine the scalefactors since 'r' has been updated! rfm.scalefactor_orthog[0] = 1 rfm.scalefactor_orthog[1] = r rfm.scalefactor_orthog[2] = r*sp.sin(th) print(rfm.scalefactor_orthog[2]) ``` a*(exp(xx0/s) - exp(-xx0/s))*sin(xx1)/2 Often we will find it useful to also define the appropriate mappings from (`xx[0]`,`xx[1]`,`xx[2]`) to Cartesian coordinates (for plotting purposes) and ordinary spherical coordinates (e.g., in case initial data when solving a PDE are naturally written in spherical coordinates). For this purpose, reference_metric.py also declares lists **`xx_to_Cart[]`** and **`xxSph[]`**, which in this case are defined as ```python rfm.xxSph[0] = r rfm.xxSph[1] = th rfm.xxSph[2] = ph rfm.xx_to_Cart[0] = r*sp.sin(th)*sp.cos(ph) rfm.xx_to_Cart[1] = r*sp.sin(th)*sp.sin(ph) rfm.xx_to_Cart[2] = r*sp.cos(th) # Here we show off SymPy's pretty_print() # and simplify() functions. Nice, no? sp.pretty_print(sp.simplify(rfm.xx_to_Cart[0])) ``` ⎛xx₀⎞ a⋅sin(xx₁)⋅cos(xx₂)⋅sinh⎜───⎟ ⎝ s ⎠ <a id='define_geometric'></a> # Step 2: Define geometric quantities, `ref_metric__hatted_quantities()` \[Back to [top](#toc)\] $$\label{define_geometric}$$ Once `scalefactor_orthog[]` has been defined, the function **`ref_metric__hatted_quantities()`** within [reference_metric.py](../edit/reference_metric.py) can be called to define a number of geometric quantities useful for solving PDEs in curvilinear coordinate systems. Adopting the notation of [Baumgarte, Montero, Cordero-Carrión, and Müller, PRD 87, 044026 (2012)](https://arxiv.org/abs/1211.6632), geometric quantities related to the reference metric are named "hatted" quantities, . For example, the reference metric is defined as $\hat{g}_{ij}$=`ghatDD[i][j]`: ```python rfm.ref_metric__hatted_quantities() sp.pretty_print(sp.Matrix(rfm.ghatDD)) ``` ⎡1 0 0 ⎤ ⎢ ⎥ ⎢ 2 ⎥ ⎢ ⎛ xx₀ -xx₀ ⎞ ⎥ ⎢ ⎜ ─── ─────⎟ ⎥ ⎢ 2 ⎜ s s ⎟ ⎥ ⎢ a ⋅⎝ℯ - ℯ ⎠ ⎥ ⎢0 ─────────────────── 0 ⎥ ⎢ 4 ⎥ ⎢ ⎥ ⎢ 2 ⎥ ⎢ ⎛ xx₀ -xx₀ ⎞ ⎥ ⎢ ⎜ ─── ─────⎟ ⎥ ⎢ 2 ⎜ s s ⎟ 2 ⎥ ⎢ a ⋅⎝ℯ - ℯ ⎠ ⋅sin (xx₁)⎥ ⎢0 0 ─────────────────────────────⎥ ⎣ 4 ⎦ In addition to $\hat{g}_{ij}$, **`ref_metric__hatted_quantities()`** also provides: * The rescaling "matrix" `ReDD[i][j]`, used for separating singular (due to chosen coordinate system) pieces of smooth rank-2 tensor components from the smooth parts, so that the smooth parts can be used within temporal and spatial differential operators. * Inverse reference metric: $\hat{g}^{ij}$=`ghatUU[i][j]`. * Reference metric determinant: $\det\left(\hat{g}_{ij}\right)$=`detgammahat`. * First and second derivatives of the reference metric: $\hat{g}_{ij,k}$=`ghatDD_dD[i][j][k]`; $\hat{g}_{ij,kl}$=`ghatDD_dDD[i][j][k][l]` * Christoffel symbols associated with the reference metric, $\hat{\Gamma}^i_{jk}$ = `GammahatUDD[i][j][k]` and their first derivatives $\hat{\Gamma}^i_{jk,l}$ = `GammahatUDD_dD[i][j][k][l]` For example, the Christoffel symbol $\hat{\Gamma}^{xx_1}_{xx_2 xx_2}=\hat{\Gamma}^1_{22}$ is given by `GammahatUDD[1][2][2]`: ```python sp.pretty_print(sp.simplify(rfm.GammahatUDD[1][2][2])) ``` -sin(2⋅xx₁) ──────────── 2 Given the trigonometric identity $2\sin(x)\cos(x) = \sin(2x)$, notice that the above expression is equivalent to Eq. 18 of [Baumgarte, Montero, Cordero-Carrión, and Müller, PRD 87, 044026 (2012)](https://arxiv.org/abs/1211.6632). This is expected since the sinh-radial spherical coordinate system is equivalent to ordinary spherical coordinates in the angular components. <a id='prescribed_ref_metric'></a> # Step 3: Prescribed reference metrics in [`reference_metric.py`](../edit/reference_metric.py) \[Back to [top](#toc)\] $$\label{prescribed_ref_metric}$$ One need not manually define scale factors or other quantities for reference metrics, as a number of prescribed reference metrics are already defined in [reference_metric.py](../edit/reference_metric.py). These can be accessed by first setting the parameter **reference_metric::CoordSystem** to one of the following, and then calling the function **`rfm.reference_metric()`**. ```python import indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support import grid as gri # NRPy+: Functions having to do with numerical grids # Step 0a: Initialize parameters thismodule = __name__ par.initialize_param(par.glb_param("char", thismodule, "CoordSystem", "Spherical")) # Step 0b: Declare global variables xx = gri.xx xx_to_Cart = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s Cart_to_xx = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s Cartx,Carty,Cartz = sp.symbols("Cartx Carty Cartz", real=True) Cart = [Cartx,Carty,Cartz] xxSph = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s scalefactor_orthog = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s have_already_called_reference_metric_function = False CoordSystem = par.parval_from_str("reference_metric::CoordSystem") M_PI,M_SQRT1_2 = par.Cparameters("#define",thismodule,["M_PI","M_SQRT1_2"],"") global xxmin global xxmax global UnitVectors UnitVectors = ixp.zerorank2(DIM=3) ``` We will find the following plotting function useful for analyzing coordinate systems in which the radial coordinate is rescaled. ```python def create_r_of_xx0_plots(CoordSystem, r_of_xx0,rprime_of_xx0): import matplotlib.pyplot as plt # matplotlib: Python module specializing in plotting capabilities plt.clf() Nr = 20 dxx0 = 1.0 / float(Nr) xx0s = [] rs = [] deltars = [] rprimes = [] for i in range(Nr): xx0 = (float(i) + 0.5)*dxx0 xx0s.append(xx0) rs.append( sp.sympify(str(r_of_xx0 ).replace("xx0",str(xx0)))) rprimes.append(sp.sympify(str(rprime_of_xx0).replace("xx0",str(xx0)))) if i>0: deltars.append(sp.log(rs[i]-rs[i-1],10)) else: deltars.append(sp.log(2*rs[0],10)) # fig, ax = plt.subplots() fig = plt.figure(figsize=(12,12)) # 8 in x 8 in ax = fig.add_subplot(221) ax.set_title('$r(xx_0)$ for '+CoordSystem,fontsize='x-large') ax.set_xlabel('$xx_0$',fontsize='x-large') ax.set_ylabel('$r(xx_0)$',fontsize='x-large') ax.plot(xx0s, rs, 'k.', label='Spacing between\nadjacent gridpoints') # legend = ax.legend(loc='lower right', shadow=True, fontsize='x-large') # legend.get_frame().set_facecolor('C1') ax = fig.add_subplot(222) ax.set_title('Grid spacing for '+CoordSystem,fontsize='x-large') ax.set_xlabel('$xx_0$',fontsize='x-large') ax.set_ylabel('$\log_{10}(\Delta r)$',fontsize='x-large') ax.plot(xx0s, deltars, 'k.', label='Spacing between\nadjacent gridpoints\nin $r(xx_0)$ plot') legend = ax.legend(loc='lower right', shadow=True, fontsize='x-large') legend.get_frame().set_facecolor('C1') ax = fig.add_subplot(223) ax.set_title('$r\'(xx_0)$ for '+CoordSystem,fontsize='x-large') ax.set_xlabel('$xx_0$',fontsize='x-large') ax.set_ylabel('$r\'(xx_0)$',fontsize='x-large') ax.plot(xx0s, rprimes, 'k.', label='Nr=96') # legend = ax.legend(loc='upper left', shadow=True, fontsize='x-large') # legend.get_frame().set_facecolor('C1') plt.tight_layout(pad=2) plt.show() ``` <a id='sphericallike'></a> ## Step 3.a: Spherical-like coordinate systems \[Back to [top](#toc)\] $$\label{sphericallike}$$ <a id='spherical'></a> ### Step 3.a.i: **`reference_metric::CoordSystem = "Spherical"`** \[Back to [top](#toc)\] $$\label{spherical}$$ Standard spherical coordinates, with $(r,\theta,\phi)=(xx_0,xx_1,xx_2)$ ```python if CoordSystem == "Spherical": # Adding assumption real=True can help simplify expressions involving xx[0] & xx[1] below. xx[0] = sp.symbols("xx0", real=True) xx[1] = sp.symbols("xx1", real=True) RMAX = par.Cparameters("REAL", thismodule, ["RMAX"],10.0) xxmin = [sp.sympify(0), sp.sympify(0), -M_PI] xxmax = [ RMAX, M_PI, M_PI] r = xx[0] th = xx[1] ph = xx[2] Cart_to_xx[0] = sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2) Cart_to_xx[1] = sp.acos(Cartz / Cart_to_xx[0]) Cart_to_xx[2] = sp.atan2(Carty, Cartx) xxSph[0] = r xxSph[1] = th xxSph[2] = ph # Now define xCart, yCart, and zCart in terms of x0,xx[1],xx[2]. # Note that the relation between r and x0 is not necessarily trivial in SinhSpherical coordinates. See above. xx_to_Cart[0] = xxSph[0]*sp.sin(xxSph[1])*sp.cos(xxSph[2]) xx_to_Cart[1] = xxSph[0]*sp.sin(xxSph[1])*sp.sin(xxSph[2]) xx_to_Cart[2] = xxSph[0]*sp.cos(xxSph[1]) scalefactor_orthog[0] = sp.diff(xxSph[0],xx[0]) scalefactor_orthog[1] = xxSph[0] scalefactor_orthog[2] = xxSph[0]*sp.sin(xxSph[1]) # Set the unit vectors UnitVectors = [[ sp.sin(xxSph[1])*sp.cos(xxSph[2]), sp.sin(xxSph[1])*sp.sin(xxSph[2]), sp.cos(xxSph[1])], [ sp.cos(xxSph[1])*sp.cos(xxSph[2]), sp.cos(xxSph[1])*sp.sin(xxSph[2]), -sp.sin(xxSph[1])], [ -sp.sin(xxSph[2]), sp.cos(xxSph[2]), sp.sympify(0) ]] ``` Now let's analyze $r(xx_0)$ for **"Spherical"** coordinates. ```python %matplotlib inline CoordSystem = "Spherical" par.set_parval_from_str("reference_metric::CoordSystem",CoordSystem) rfm.reference_metric() RMAX = 10.0 r_of_xx0 = sp.sympify(str(rfm.xxSph[0] ).replace("RMAX",str(RMAX))) rprime_of_xx0 = sp.sympify(str(sp.diff(rfm.xxSph[0],rfm.xx[0])).replace("RMAX",str(RMAX))) create_r_of_xx0_plots(CoordSystem, r_of_xx0,rprime_of_xx0) ``` <a id='sinhspherical'></a> ### Step 3.a.ii: **`reference_metric::CoordSystem = "SinhSpherical"`** \[Back to [top](#toc)\] $$\label{sinhspherical}$$ Spherical coordinates, but with $$r(xx_0) = \text{AMPL} \frac{\sinh\left(\frac{xx_0}{\text{SINHW}}\right)}{\sinh\left(\frac{1}{\text{SINHW}}\right)}.$$ SinhSpherical uses two parameters: `AMPL` and `SINHW`. `AMPL` sets the outer boundary distance; and `SINHW` sets the focusing of the coordinate points near $r=0$, where a small `SINHW` ($\sim 0.125$) will greatly focus the points near $r=0$ and a large `SINHW` will look more like an ordinary spherical polar coordinate system. ```python if CoordSystem == "SinhSpherical": xxmin = [sp.sympify(0), sp.sympify(0), -M_PI] xxmax = [sp.sympify(1), M_PI, M_PI] AMPL, SINHW = par.Cparameters("REAL",thismodule,["AMPL","SINHW"],[10.0,0.2]) # Set SinhSpherical radial coordinate by default; overwrite later if CoordSystem == "SinhSphericalv2". r = AMPL * (sp.exp(xx[0] / SINHW) - sp.exp(-xx[0] / SINHW)) / \ (sp.exp(1 / SINHW) - sp.exp(-1 / SINHW)) th = xx[1] ph = xx[2] Cart_to_xx[0] = SINHW*sp.asinh(sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2)*sp.sinh(1/SINHW)/AMPL) Cart_to_xx[1] = sp.acos(Cartz / sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2)) Cart_to_xx[2] = sp.atan2(Carty, Cartx) xxSph[0] = r xxSph[1] = th xxSph[2] = ph # Now define xCart, yCart, and zCart in terms of x0,xx[1],xx[2]. # Note that the relation between r and x0 is not necessarily trivial in SinhSpherical coordinates. See above. xx_to_Cart[0] = xxSph[0]*sp.sin(xxSph[1])*sp.cos(xxSph[2]) xx_to_Cart[1] = xxSph[0]*sp.sin(xxSph[1])*sp.sin(xxSph[2]) xx_to_Cart[2] = xxSph[0]*sp.cos(xxSph[1]) scalefactor_orthog[0] = sp.diff(xxSph[0],xx[0]) scalefactor_orthog[1] = xxSph[0] scalefactor_orthog[2] = xxSph[0]*sp.sin(xxSph[1]) # Set the unit vectors UnitVectors = [[ sp.sin(xxSph[1])*sp.cos(xxSph[2]), sp.sin(xxSph[1])*sp.sin(xxSph[2]), sp.cos(xxSph[1])], [ sp.cos(xxSph[1])*sp.cos(xxSph[2]), sp.cos(xxSph[1])*sp.sin(xxSph[2]), -sp.sin(xxSph[1])], [ -sp.sin(xxSph[2]), sp.cos(xxSph[2]), sp.sympify(0) ]] ``` Now we explore $r(xx_0)$ for `SinhSpherical` assuming `AMPL=10.0` and `SINHW=0.2`: ```python %matplotlib inline CoordSystem = "SinhSpherical" par.set_parval_from_str("reference_metric::CoordSystem",CoordSystem) rfm.reference_metric() AMPL = 10.0 SINHW = 0.2 r_of_xx0 = sp.sympify(str(rfm.xxSph[0] ).replace("AMPL",str(AMPL)).replace("SINHW",str(SINHW))) rprime_of_xx0 = sp.sympify(str(sp.diff(rfm.xxSph[0],rfm.xx[0])).replace("AMPL",str(AMPL)).replace("SINHW",str(SINHW))) create_r_of_xx0_plots(CoordSystem, r_of_xx0,rprime_of_xx0) ``` <a id='sinhsphericalv2'></a> ### Step 3.a.iii: **`reference_metric::CoordSystem = "SinhSphericalv2"`** \[Back to [top](#toc)\] $$\label{sinhsphericalv2}$$ The same as SinhSpherical coordinates, but with an additional `AMPL*const_dr*xx_0` term: $$r(xx_0) = \text{AMPL} \left[\text{const_dr}\ xx_0 + \frac{\sinh\left(\frac{xx_0}{\text{SINHW}}\right)}{\sinh\left(\frac{1}{\text{SINHW}}\right)}\right].$$ ```python if CoordSystem == "SinhSphericalv2": # SinhSphericalv2 adds the parameter "const_dr", which allows for a region near xx[0]=0 to have # constant radial resolution of const_dr, provided the sinh() term does not dominate near xx[0]=0. xxmin = [sp.sympify(0), sp.sympify(0), -M_PI] xxmax = [sp.sympify(1), M_PI, M_PI] AMPL, SINHW = par.Cparameters("REAL",thismodule,["AMPL","SINHW"],[10.0,0.2]) const_dr = par.Cparameters("REAL",thismodule,["const_dr"],0.0625) r = AMPL*( const_dr*xx[0] + (sp.exp(xx[0] / SINHW) - sp.exp(-xx[0] / SINHW)) / (sp.exp(1 / SINHW) - sp.exp(-1 / SINHW)) ) th = xx[1] ph = xx[2] # NO CLOSED-FORM EXPRESSION FOR RADIAL INVERSION. # Cart_to_xx[0] = "NewtonRaphson" # Cart_to_xx[1] = sp.acos(Cartz / sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2)) # Cart_to_xx[2] = sp.atan2(Carty, Cartx) xxSph[0] = r xxSph[1] = th xxSph[2] = ph # Now define xCart, yCart, and zCart in terms of x0,xx[1],xx[2]. # Note that the relation between r and x0 is not necessarily trivial in SinhSpherical coordinates. See above. xx_to_Cart[0] = xxSph[0]*sp.sin(xxSph[1])*sp.cos(xxSph[2]) xx_to_Cart[1] = xxSph[0]*sp.sin(xxSph[1])*sp.sin(xxSph[2]) xx_to_Cart[2] = xxSph[0]*sp.cos(xxSph[1]) scalefactor_orthog[0] = sp.diff(xxSph[0],xx[0]) scalefactor_orthog[1] = xxSph[0] scalefactor_orthog[2] = xxSph[0]*sp.sin(xxSph[1]) # Set the unit vectors UnitVectors = [[ sp.sin(xxSph[1])*sp.cos(xxSph[2]), sp.sin(xxSph[1])*sp.sin(xxSph[2]), sp.cos(xxSph[1])], [ sp.cos(xxSph[1])*sp.cos(xxSph[2]), sp.cos(xxSph[1])*sp.sin(xxSph[2]), -sp.sin(xxSph[1])], [ -sp.sin(xxSph[2]), sp.cos(xxSph[2]), sp.sympify(0) ]] ``` Now we explore $r(xx_0)$ for `SinhSphericalv2` assuming `AMPL=10.0`, `SINHW=0.2`, and `const_dr=0.05`. Notice that the `const_dr` term significantly increases the grid spacing near $xx_0=0$ relative to `SinhSpherical` coordinates. ```python %matplotlib inline CoordSystem = "SinhSphericalv2" par.set_parval_from_str("reference_metric::CoordSystem",CoordSystem) rfm.reference_metric() AMPL = 10.0 SINHW = 0.2 const_dr = 0.05 r_of_xx0 = sp.sympify(str(rfm.xxSph[0] ).replace("AMPL",str(AMPL)).replace("SINHW",str(SINHW)).replace("const_dr",str(const_dr))) rprime_of_xx0 = sp.sympify(str(sp.diff(rfm.xxSph[0],rfm.xx[0])).replace("AMPL",str(AMPL)).replace("SINHW",str(SINHW)).replace("const_dr",str(const_dr))) create_r_of_xx0_plots(CoordSystem, r_of_xx0,rprime_of_xx0) ``` <a id='cylindricallike'></a> ## Step 3.b: Cylindrical-like coordinate systems \[Back to [top](#toc)\] $$\label{cylindricallike}$$ <a id='cylindrical'></a> ### Step 3.b.i: **`reference_metric::CoordSystem = "Cylindrical"`** \[Back to [top](#toc)\] $$\label{cylindrical}$$ Standard cylindrical coordinates, with $(\rho,\phi,z)=(xx_0,xx_1,xx_2)$ ```python if CoordSystem == "Cylindrical": # Assuming the cylindrical radial coordinate # is positive makes nice simplifications of # unit vectors possible. xx[0] = sp.symbols("xx0", real=True) RHOMAX,ZMIN,ZMAX = par.Cparameters("REAL",thismodule,["RHOMAX","ZMIN","ZMAX"],[10.0,-10.0,10.0]) xxmin = [sp.sympify(0), -M_PI, ZMIN] xxmax = [ RHOMAX, M_PI, ZMAX] RHOCYL = xx[0] PHICYL = xx[1] ZCYL = xx[2] Cart_to_xx[0] = sp.sqrt(Cartx ** 2 + Carty ** 2) Cart_to_xx[1] = sp.atan2(Carty, Cartx) Cart_to_xx[2] = Cartz xx_to_Cart[0] = RHOCYL*sp.cos(PHICYL) xx_to_Cart[1] = RHOCYL*sp.sin(PHICYL) xx_to_Cart[2] = ZCYL xxSph[0] = sp.sqrt(RHOCYL**2 + ZCYL**2) xxSph[1] = sp.acos(ZCYL / xxSph[0]) xxSph[2] = PHICYL scalefactor_orthog[0] = sp.diff(RHOCYL,xx[0]) scalefactor_orthog[1] = RHOCYL scalefactor_orthog[2] = sp.diff(ZCYL,xx[2]) # Set the unit vectors UnitVectors = [[ sp.cos(PHICYL), sp.sin(PHICYL), sp.sympify(0)], [-sp.sin(PHICYL), sp.cos(PHICYL), sp.sympify(0)], [ sp.sympify(0), sp.sympify(0), sp.sympify(1)]] ``` Next let's plot **"Cylindrical"** coordinates. ```python %matplotlib inline import numpy as np # NumPy: A numerical methods module for Python import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D R = np.linspace(0, 2, 24) h = 2 u = np.linspace(0, 2*np.pi, 24) x = np.outer(R, np.cos(u)) y = np.outer(R, np.sin(u)) z = h * np.outer(np.ones(np.size(u)), np.ones(np.size(u))) r = np.arange(0,2,0.25) theta = 2*np.pi*r*0 fig = plt.figure(figsize=(12,12)) # 8 in x 8 in fig, (ax1, ax2) = plt.subplots(1, 2) ax1 = plt.axes(projection='polar') ax1.set_rmax(2) ax1.set_rgrids(r,labels=[]) thetas = np.linspace(0,360,24, endpoint=True) ax1.set_thetagrids(thetas,labels=[]) # ax.grid(True) ax1.grid(True,linewidth='1.0') ax1.set_title("Top Down View") plt.show() ax2 = plt.axes(projection='3d', xticklabels=[], yticklabels=[], zticklabels=[]) #ax2.plot_surface(x,y,z, alpha=.75, cmap = 'viridis') # z in case of disk which is parallel to XY plane is constant and you can directly use h x=np.linspace(-2, 2, 100) z=np.linspace(-2, 2, 100) Xc, Zc=np.meshgrid(x, z) Yc = np.sqrt(4-Xc**2) rstride = 10 cstride = 10 ax2.plot_surface(Xc, Yc, Zc, alpha=1.0, rstride=rstride, cstride=cstride, cmap = 'viridis') ax2.plot_surface(Xc, -Yc, Zc, alpha=1.0, rstride=rstride, cstride=cstride, cmap = 'viridis') ax2.set_title("Standard Cylindrical Grid in 3D") ax2.grid(False) plt.axis('off') plt.show() ``` <a id='sinhcylindrical'></a> ### Step 3.b.ii" **`reference_metric::CoordSystem = "SinhCylindrical"`** \[Back to [top](#toc)\] $$\label{sinhcylindrical}$$ Cylindrical coordinates, but with $$\rho(xx_0) = \text{AMPLRHO} \frac{\sinh\left(\frac{xx_0}{\text{SINHWRHO}}\right)}{\sinh\left(\frac{1}{\text{SINHWRHO}}\right)}$$ and $$z(xx_2) = \text{AMPLZ} \frac{\sinh\left(\frac{xx_2}{\text{SINHWZ}}\right)}{\sinh\left(\frac{1}{\text{SINHWZ}}\right)}$$ ```python if CoordSystem == "SinhCylindrical": # Assuming the cylindrical radial coordinate # is positive makes nice simplifications of # unit vectors possible. xx[0] = sp.symbols("xx0", real=True) xxmin = [sp.sympify(0), -M_PI, sp.sympify(-1)] xxmax = [sp.sympify(1), M_PI, sp.sympify(+1)] AMPLRHO, SINHWRHO, AMPLZ, SINHWZ = par.Cparameters("REAL",thismodule, ["AMPLRHO","SINHWRHO","AMPLZ","SINHWZ"], [ 10.0, 0.2, 10.0, 0.2]) # Set SinhCylindrical radial & z coordinates by default; overwrite later if CoordSystem == "SinhCylindricalv2". RHOCYL = AMPLRHO * (sp.exp(xx[0] / SINHWRHO) - sp.exp(-xx[0] / SINHWRHO)) / (sp.exp(1 / SINHWRHO) - sp.exp(-1 / SINHWRHO)) # phi coordinate remains unchanged. PHICYL = xx[1] ZCYL = AMPLZ * (sp.exp(xx[2] / SINHWZ) - sp.exp(-xx[2] / SINHWZ)) / (sp.exp(1 / SINHWZ) - sp.exp(-1 / SINHWZ)) Cart_to_xx[0] = SINHWRHO*sp.asinh(sp.sqrt(Cartx ** 2 + Carty ** 2)*sp.sinh(1/SINHWRHO)/AMPLRHO) Cart_to_xx[1] = sp.atan2(Carty, Cartx) Cart_to_xx[2] = SINHWZ*sp.asinh(Cartz*sp.sinh(1/SINHWZ)/AMPLZ) xx_to_Cart[0] = RHOCYL*sp.cos(PHICYL) xx_to_Cart[1] = RHOCYL*sp.sin(PHICYL) xx_to_Cart[2] = ZCYL xxSph[0] = sp.sqrt(RHOCYL**2 + ZCYL**2) xxSph[1] = sp.acos(ZCYL / xxSph[0]) xxSph[2] = PHICYL scalefactor_orthog[0] = sp.diff(RHOCYL,xx[0]) scalefactor_orthog[1] = RHOCYL scalefactor_orthog[2] = sp.diff(ZCYL,xx[2]) # Set the unit vectors UnitVectors = [[ sp.cos(PHICYL), sp.sin(PHICYL), sp.sympify(0)], [-sp.sin(PHICYL), sp.cos(PHICYL), sp.sympify(0)], [ sp.sympify(0), sp.sympify(0), sp.sympify(1)]] ``` Next let's plot **"SinhCylindrical"** coordinates. ```python fig=plt.figure() plt.clf() fig = plt.figure() ax = plt.subplot(1,1,1, projection='polar') ax.set_rmax(2) Nr = 20 xx0s = np.linspace(0,2,Nr, endpoint=True) + 1.0/(2.0*Nr) rs = [] AMPLRHO = 1.0 SINHW = 0.4 for i in range(Nr): rs.append(AMPLRHO * (np.exp(xx0s[i] / SINHW) - np.exp(-xx0s[i] / SINHW)) / \ (np.exp(1.0 / SINHW) - np.exp(-1.0 / SINHW))) ax.set_rgrids(rs,labels=[]) thetas = np.linspace(0,360,25, endpoint=True) ax.set_thetagrids(thetas,labels=[]) # ax.grid(True) ax.grid(True,linewidth='1.0') plt.show() ``` <a id='sinhcylindricalv2'></a> ### Step 3.b.iii: **`reference_metric::CoordSystem = "SinhCylindricalv2"`** \[Back to [top](#toc)\] $$\label{sinhcylindricalv2}$$ Cylindrical coordinates, but with $$\rho(xx_0) = \text{AMPLRHO} \left[\text{const_drho}\ xx_0 + \frac{\sinh\left(\frac{xx_0}{\text{SINHWRHO}}\right)}{\sinh\left(\frac{1}{\text{SINHWRHO}}\right)}\right]$$ and $$z(xx_2) = \text{AMPLZ} \left[\text{const_dz}\ xx_2 + \frac{\sinh\left(\frac{xx_2}{\text{SINHWZ}}\right)}{\sinh\left(\frac{1}{\text{SINHWZ}}\right)}\right]$$ ```python if CoordSystem == "SinhCylindricalv2": # Assuming the cylindrical radial coordinate # is positive makes nice simplifications of # unit vectors possible. xx[0] = sp.symbols("xx0", real=True) # SinhCylindricalv2 adds the parameters "const_drho", "const_dz", which allows for regions near xx[0]=0 # and xx[2]=0 to have constant rho and z resolution of const_drho and const_dz, provided the sinh() terms # do not dominate near xx[0]=0 and xx[2]=0. xxmin = [sp.sympify(0), -M_PI, sp.sympify(-1)] xxmax = [sp.sympify(1), M_PI, sp.sympify(+1)] AMPLRHO, SINHWRHO, AMPLZ, SINHWZ = par.Cparameters("REAL",thismodule, ["AMPLRHO","SINHWRHO","AMPLZ","SINHWZ"], [ 10.0, 0.2, 10.0, 0.2]) const_drho, const_dz = par.Cparameters("REAL",thismodule,["const_drho","const_dz"],[0.0625,0.0625]) RHOCYL = AMPLRHO * ( const_drho*xx[0] + (sp.exp(xx[0] / SINHWRHO) - sp.exp(-xx[0] / SINHWRHO)) / (sp.exp(1 / SINHWRHO) - sp.exp(-1 / SINHWRHO)) ) PHICYL = xx[1] ZCYL = AMPLZ * ( const_dz *xx[2] + (sp.exp(xx[2] / SINHWZ ) - sp.exp(-xx[2] / SINHWZ )) / (sp.exp(1 / SINHWZ ) - sp.exp(-1 / SINHWZ )) ) # NO CLOSED-FORM EXPRESSION FOR RADIAL OR Z INVERSION. # Cart_to_xx[0] = "NewtonRaphson" # Cart_to_xx[1] = sp.atan2(Carty, Cartx) # Cart_to_xx[2] = "NewtonRaphson" xx_to_Cart[0] = RHOCYL*sp.cos(PHICYL) xx_to_Cart[1] = RHOCYL*sp.sin(PHICYL) xx_to_Cart[2] = ZCYL xxSph[0] = sp.sqrt(RHOCYL**2 + ZCYL**2) xxSph[1] = sp.acos(ZCYL / xxSph[0]) xxSph[2] = PHICYL scalefactor_orthog[0] = sp.diff(RHOCYL,xx[0]) scalefactor_orthog[1] = RHOCYL scalefactor_orthog[2] = sp.diff(ZCYL,xx[2]) # Set the unit vectors UnitVectors = [[ sp.cos(PHICYL), sp.sin(PHICYL), sp.sympify(0)], [-sp.sin(PHICYL), sp.cos(PHICYL), sp.sympify(0)], [ sp.sympify(0), sp.sympify(0), sp.sympify(1)]] ``` For example, let's set up **`SinhCylindricalv2`** coordinates and output the Christoffel symbol $\hat{\Gamma}^{xx_2}_{xx_2 xx_2}$, or more simply $\hat{\Gamma}^2_{22}$: ```python par.set_parval_from_str("reference_metric::CoordSystem","SinhCylindricalv2") rfm.reference_metric() sp.pretty_print(sp.simplify(rfm.GammahatUDD[2][2][2])) ``` ⎛ 2⋅xx₂ ⎞ 1 ⎜ ────── ⎟ ────── ⎜ SINHWZ ⎟ SINHWZ -⎝ℯ - 1⎠⋅ℯ ──────────────────────────────────────────────────────────────────────── ⎛ ⎛ 2 ⎞ xx₂ ⎛ 2⋅xx₂ ⎞ 1 ⎞ ⎜ ⎜ ────── ⎟ ────── ⎜ ────── ⎟ ──────⎟ ⎜ ⎜ SINHWZ ⎟ SINHWZ ⎜ SINHWZ ⎟ SINHWZ⎟ SINHWZ⋅⎝- SINHWZ⋅const_dz⋅⎝ℯ - 1⎠⋅ℯ - ⎝ℯ + 1⎠⋅ℯ ⎠ As we will soon see, defining these "hatted" quantities will be quite useful when expressing hyperbolic ([wave-equation](https://en.wikipedia.org/wiki/Wave_equation)-like) PDEs in non-Cartesian coordinate systems. <a id='cartesianlike'></a> ## Step 3.c: Cartesian-like coordinate systems \[Back to [top](#toc)\] $$\label{cartesianlike}$$ <a id='cartesian'></a> ### Step 3.c.i: **`reference_metric::CoordSystem = "Cartesian"`** \[Back to [top](#toc)\] $$\label{cartesian}$$ Standard Cartesian coordinates, with $(x,y,z)=$ `(xx0,xx1,xx2)` ```python if CoordSystem == "Cartesian": xmin, xmax, ymin, ymax, zmin, zmax = par.Cparameters("REAL",thismodule, ["xmin","xmax","ymin","ymax","zmin","zmax"], [ -10.0, 10.0, -10.0, 10.0, -10.0, 10.0]) xxmin = ["xmin", "ymin", "zmin"] xxmax = ["xmax", "ymax", "zmax"] xx_to_Cart[0] = xx[0] xx_to_Cart[1] = xx[1] xx_to_Cart[2] = xx[2] xxSph[0] = sp.sqrt(xx[0] ** 2 + xx[1] ** 2 + xx[2] ** 2) xxSph[1] = sp.acos(xx[2] / xxSph[0]) xxSph[2] = sp.atan2(xx[1], xx[0]) Cart_to_xx[0] = Cartx Cart_to_xx[1] = Carty Cart_to_xx[2] = Cartz scalefactor_orthog[0] = sp.sympify(1) scalefactor_orthog[1] = sp.sympify(1) scalefactor_orthog[2] = sp.sympify(1) # Set the transpose of the matrix of unit vectors UnitVectors = [[sp.sympify(1), sp.sympify(0), sp.sympify(0)], [sp.sympify(0), sp.sympify(1), sp.sympify(0)], [sp.sympify(0), sp.sympify(0), sp.sympify(1)]] ``` ```python %matplotlib inline import numpy as np # NumPy: A numerical methods module for Python import matplotlib.pyplot as plt # matplotlib: Python module specializing in plotting capabilities plt.clf() fig = plt.figure() ax = fig.gca() Nx = 16 ax.set_xticks(np.arange(0, 1., 1./Nx)) ax.set_yticks(np.arange(0, 1., 1./Nx)) for tick in ax.get_xticklabels(): tick.set_rotation(60) # plt.scatter(x, y) ax.set_aspect('equal') plt.grid() # plt.savefig("Cartgrid.png",dpi=300) plt.show() # plt.close(fig) ``` <a id='sinhcartesian'></a> ### Step 3.c.ii: **`reference_metric::CoordSystem = "SinhCartesian"`** \[Back to [top](#toc)\] $$\label{sinhcartesian}$$ In this coordinate system, all three coordinates behave like the $z$-coordinate in SinhCylindrical coordinates, i.e. $$ \begin{align} x(xx_0) &= \text{AMPLXYZ} \left[\frac{\sinh\left(\frac{xx_0}{\text{SINHWXYZ}}\right)}{\sinh\left(\frac{1}{\text{SINHWXYZ}}\right)}\right]\ ,\\ y(xx_1) &= \text{AMPLXYZ} \left[\frac{\sinh\left(\frac{xx_1}{\text{SINHWXYZ}}\right)}{\sinh\left(\frac{1}{\text{SINHWXYZ}}\right)}\right]\ ,\\ z(xx_2) &= \text{AMPLXYZ} \left[\frac{\sinh\left(\frac{xx_2}{\text{SINHWXYZ}}\right)}{\sinh\left(\frac{1}{\text{SINHWXYZ}}\right)}\right] \end{align} $$ ```python if CoordSystem == "SinhCartesian": # SinhCartesian coordinates allows us to push the outer boundary of the # computational domain a lot further away, while keeping reasonably high # resolution towards the center of the computational grid. # Set default values for min and max (x,y,z) xxmin = [sp.sympify(-1), sp.sympify(-1), sp.sympify(-1)] xxmax = [sp.sympify(+1), sp.sympify(+1), sp.sympify(+1)] # Declare basic parameters of the coordinate system and their default values AMPLXYZ, SINHWXYZ = par.Cparameters("REAL", thismodule, ["AMPLXYZ", "SINHWXYZ"], [ 10.0, 0.2]) # Compute (xx_to_Cart0,xx_to_Cart1,xx_to_Cart2) from (xx0,xx1,xx2) for ii in [0, 1, 2]: xx_to_Cart[ii] = AMPLXYZ*(sp.exp(xx[ii]/SINHWXYZ) - sp.exp(-xx[ii]/SINHWXYZ))/(sp.exp(1/SINHWXYZ) - sp.exp(-1/SINHWXYZ)) # Compute (r,th,ph) from (xx_to_Cart2,xx_to_Cart1,xx_to_Cart2) xxSph[0] = sp.sqrt(xx_to_Cart[0] ** 2 + xx_to_Cart[1] ** 2 + xx_to_Cart[2] ** 2) xxSph[1] = sp.acos(xx_to_Cart[2] / xxSph[0]) xxSph[2] = sp.atan2(xx_to_Cart[1], xx_to_Cart[0]) # Compute (xx0,xx1,xx2) from (Cartx,Carty,Cartz) Cart_to_xx[0] = SINHWXYZ*sp.asinh(Cartx*sp.sinh(1/SINHWXYZ)/AMPLXYZ) Cart_to_xx[1] = SINHWXYZ*sp.asinh(Carty*sp.sinh(1/SINHWXYZ)/AMPLXYZ) Cart_to_xx[2] = SINHWXYZ*sp.asinh(Cartz*sp.sinh(1/SINHWXYZ)/AMPLXYZ) # Compute scale factors scalefactor_orthog[0] = sp.diff(xx_to_Cart[0], xx[0]) scalefactor_orthog[1] = sp.diff(xx_to_Cart[1], xx[1]) scalefactor_orthog[2] = sp.diff(xx_to_Cart[2], xx[2]) # Set the transpose of the matrix of unit vectors UnitVectors = [[sp.sympify(1), sp.sympify(0), sp.sympify(0)], [sp.sympify(0), sp.sympify(1), sp.sympify(0)], [sp.sympify(0), sp.sympify(0), sp.sympify(1)]] ``` ```python %matplotlib inline import numpy as np # NumPy: A numerical methods module for Python import matplotlib.pyplot as plt # matplotlib: Python module specializing in plotting capabilities plt.clf() fig = plt.figure(dpi=160) ax = fig.gca() # Set plot title ax.set_title(r"$z=0$ slice of the 3D grid") # Set SINH parameters. Here we assume: # # AMPLX = AMPLY = SINHA # SINHWX = SINHWY = SINHW SINHA = 10.0 SINHW = 0.45 # Set number of points. We assume the same point # distribution along the (x,y)-directions Nxxs = 24 xxis = np.linspace(-1,1,Nxxs, endpoint=True) # Compute axis ticks by evaluating x and y using SinhCartesian coordinates axis_ticks = [] for i in range(Nxxs): axis_ticks.append(SINHA * (np.exp(xxis[i] / SINHW) - np.exp(-xxis[i] / SINHW)) / \ (np.exp(1.0 / SINHW) - np.exp(-1.0 / SINHW))) # Set the axis ticks ax.set_xticks(axis_ticks) ax.set_yticks(axis_ticks) # Set x and y labels. Initialize array with empty strings labelsx = ["" for i in range(Nxxs)] labelsy = ["" for i in range(Nxxs)] # Set x_min and x_max tick label labelsx[0] = r"-AMPLX" labelsx[-1] = r"AMPLX" # Set y_min and y_max tick label labelsy[0] = r"-AMPLY" labelsy[-1] = r"AMPLY" # Set tick labels ax.set_xticklabels(labelsx) ax.set_yticklabels(labelsy) # Rotate x labels by 60 degrees for tick in ax.get_xticklabels(): tick.set_rotation(60) # Draw the x=0 and y=0 ticklabel ax.text(0,-11,"0",ha="center",va="center") ax.text(-11,0,"0",ha="center",va="center") # plt.scatter(x, y) ax.set_aspect('equal') plt.grid(color='black',linewidth=0.3) plt.show() # plt.savefig("Cartgrid.png",dpi=400) # plt.close(fig) ``` <a id='prolatespheroidal'></a> ## Step 3.d: [Prolate spheroidal](https://en.wikipedia.org/wiki/Prolate_spheroidal_coordinates)-like coordinate systems \[Back to [top](#toc)\] $$\label{prolatespheroidal}$$ <a id='symtp'></a> ### Step 3.d.i: **`reference_metric::CoordSystem = "SymTP"`** \[Back to [top](#toc)\] $$\label{symtp}$$ The Symmetric TwoPuncture (SymTP) coordinate system is obtained by slightly modifying [prolate spheroidal coordinates](https://en.wikipedia.org/wiki/Prolate_spheroidal_coordinates) (PSC). Standard PSC are related to Cartesian coordinates $(x,y,z)$ via $$ \begin{aligned} x &= a\sinh\mu\sin\nu\cos\varphi,\\ y &= a\sinh\mu\sin\nu\sin\varphi,\\ z &= a\cosh\mu\cos\nu = \left(a^{2}\sinh^{2}\mu + a^{2}\right)^{1/2}\cos\nu, \end{aligned} $$ where $\mu\in[0,\infty)$, $\nu\in[0,\pi]$, and $\varphi\in[0,2\pi]$, and we have used the [identity](https://en.wikipedia.org/wiki/Hyperbolic_functions) $$ \cosh^{2}\mu - \sinh^{2}\mu = 1. $$ PSC have two foci located at $z=\pm a$, where the grid lines get more dense and the grid resolution increases. However, note that the parameter $a$ controls both the foci position *and* the grid scaling, which is not a particularly interesting property. In order to remedy this, we introduce new coordinates $(xx_{0},xx_{1},xx_{2})$, such that $$ \begin{aligned} xx_{0} &= \frac{1}{a}\sinh\mu,\\ xx_{1} &= \nu,\\ xx_{2} &= \varphi, \end{aligned} $$ and change $a\to \text{bScale}$, so that we obtain $$ \begin{aligned} x &= xx_{0}\sin(xx_{1})\cos(xx_{2}),\\ y &= xx_{0}\sin(xx_{1})\sin(xx_{2}),\\ z &= \left(xx_{0}^{2}+\text{bScale}^{2}\right)\cos(xx_{1}), \end{aligned} $$ Note that, for numerical convenience, we change the range of $xx_{2}$ to $[-\pi,\pi]$. Comparing SymTP coordinates with Cylindrical coordinates, we find that $(\rho,\phi,z)=(xx_{0}\sin(xx_{1}), xx_{2}, \sqrt{xx_{0}^2 + \text{bScale}^2}\cos(xx_{1}))$. ```python if CoordSystem == "SymTP": var1, var2= sp.symbols('var1 var2',real=True) bScale, AW, AMAX, RHOMAX, ZMIN, ZMAX = par.Cparameters("REAL",thismodule, ["bScale","AW","AMAX","RHOMAX","ZMIN","ZMAX"], [0.5, 0.2, 10.0, 10.0, -10.0, 10.0]) # Assuming xx0, xx1, and bScale # are positive makes nice simplifications of # unit vectors possible. xx[0],xx[1] = sp.symbols("xx0 xx1", real=True) xxmin = [sp.sympify(0), sp.sympify(0),-M_PI] xxmax = [ AMAX, M_PI, M_PI] AA = xx[0] var1 = sp.sqrt(AA**2 + (bScale * sp.sin(xx[1]))**2) var2 = sp.sqrt(AA**2 + bScale**2) RHOSYMTP = AA*sp.sin(xx[1]) PHSYMTP = xx[2] ZSYMTP = var2*sp.cos(xx[1]) xx_to_Cart[0] = AA *sp.sin(xx[1])*sp.cos(xx[2]) xx_to_Cart[1] = AA *sp.sin(xx[1])*sp.sin(xx[2]) xx_to_Cart[2] = ZSYMTP xxSph[0] = sp.sqrt(RHOSYMTP**2 + ZSYMTP**2) xxSph[1] = sp.acos(ZSYMTP / xxSph[0]) xxSph[2] = PHSYMTP rSph = sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2) thSph = sp.acos(Cartz / rSph) phSph = sp.atan2(Carty, Cartx) # Mathematica script to compute Cart_to_xx[] # AA = x1; # var2 = Sqrt[AA^2 + bScale^2]; # RHOSYMTP = AA*Sin[x2]; # ZSYMTP = var2*Cos[x2]; # Solve[{rSph == Sqrt[RHOSYMTP^2 + ZSYMTP^2], # thSph == ArcCos[ZSYMTP/Sqrt[RHOSYMTP^2 + ZSYMTP^2]], # phSph == x3}, # {x1, x2, x3}] Cart_to_xx[0] = sp.sqrt(-bScale**2 + rSph**2 + sp.sqrt(bScale**4 + 2*bScale**2*rSph**2 + rSph**4 - 4*bScale**2*rSph**2*sp.cos(thSph)**2))*M_SQRT1_2 # M_SQRT1_2 = 1/sqrt(2); define this way for UnitTesting # The sign() function in the following expression ensures the correct root is taken. Cart_to_xx[1] = sp.acos(sp.sign(Cartz)*( sp.sqrt(1 + rSph**2/bScale**2 - sp.sqrt(bScale**4 + 2*bScale**2*rSph**2 + rSph**4 - 4*bScale**2*rSph**2*sp.cos(thSph)**2)/bScale**2)*M_SQRT1_2)) # M_SQRT1_2 = 1/sqrt(2); define this way for UnitTesting Cart_to_xx[2] = phSph ``` ```python %matplotlib inline Nxxs = 24 xx0 = np.linspace(-2,2,Nxxs,endpoint=True) xx1 = np.linspace(0,np.pi,Nxxs,endpoint=True) xx2 = 0 bScale = 1 def x(xx0,xx1): return xx0 * np.sin(xx1) def z(xx0,xx1,bScale): return np.sqrt(xx0**2 + bScale**2) * np.cos(xx1) import numpy as np # NumPy: A numerical methods module for Python import matplotlib.pyplot as plt # matplotlib: Python module specializing in plotting capabilities plt.clf() fig = plt.figure(dpi=160) ax = fig.gca() # Set plot title ax.set_title(r"""SymTP Coordinates: zx-plane ($xx_{2}$=0 and $xx_{2}=\pi$) Blue (red) lines have constant $xx_{0}$ ($xx_{1}$)""") ax.set_xlim(-2.5,2.5) ax.set_ylim(-2.5,2.5) ax.set_aspect('equal') ax.axis('off') for i0 in range(Nxxs): plt.plot(x(xx0[i0],xx1),z(xx0[i0],xx1,bScale),'b',lw=0.75) for i1 in range(Nxxs): plt.plot(x(xx0,xx1[i1]),z(xx0,xx1[i1],bScale),'r',lw=0.75) plt.show() ``` <a id='sinhsymtp'></a> ### Step 3.d.ii: **`reference_metric::CoordSystem = "SinhSymTP"`** \[Back to [top](#toc)\] $$\label{sinhsymtp}$$ SinhSymTP coordinates are obtained from SymTP coordinates by making the substitution $$ xx0 \to \mathcal{A}\frac{\sinh(xx_{0}/w)}{\sinh(1/w)}, $$ with the further modification that $xx_{0}\in[0,1]$. The parameter $\mathcal{A}$ controls the scale of the grid, while the parameter $w$ controls how densily sampled the region around the foci are. ```python if CoordSystem == "SinhSymTP": var1, var2= sp.symbols('var1 var2',real=True) bScale, AW, AMAX, RHOMAX, ZMIN, ZMAX = par.Cparameters("REAL",thismodule, ["bScale","AW","AMAX","RHOMAX","ZMIN","ZMAX"], [0.5, 0.2, 10.0, 10.0, -10.0, 10.0]) # Assuming xx0, xx1, and bScale # are positive makes nice simplifications of # unit vectors possible. xx[0],xx[1] = sp.symbols("xx0 xx1", real=True) xxmin = [sp.sympify(0), sp.sympify(0),-M_PI] xxmax = [sp.sympify(1), M_PI, M_PI] AA = AMAX * (sp.exp(xx[0]/SINHWAA) - sp.exp(-xx[0]/SINHWAA)) / (sp.exp(1/SINHWAA) - sp.exp(-1/SINHWAA)) var1 = sp.sqrt(AA**2 + (bScale * sp.sin(xx[1]))**2) var2 = sp.sqrt(AA**2 + bScale**2) RHOSYMTP = AA*sp.sin(xx[1]) PHSYMTP = xx[2] ZSYMTP = var2*sp.cos(xx[1]) xx_to_Cart[0] = AA*sp.sin(xx[1])*sp.cos(xx[2]) xx_to_Cart[1] = AA*sp.sin(xx[1])*sp.sin(xx[2]) xx_to_Cart[2] = ZSYMTP xxSph[0] = sp.sqrt(RHOSYMTP**2 + ZSYMTP**2) xxSph[1] = sp.acos(ZSYMTP / xxSph[0]) xxSph[2] = PHSYMTP rSph = sp.sqrt(Cartx ** 2 + Carty ** 2 + Cartz ** 2) thSph = sp.acos(Cartz / rSph) phSph = sp.atan2(Carty, Cartx) # Mathematica script to compute Cart_to_xx[] # AA = x1; # var2 = Sqrt[AA^2 + bScale^2]; # RHOSYMTP = AA*Sin[x2]; # ZSYMTP = var2*Cos[x2]; # Solve[{rSph == Sqrt[RHOSYMTP^2 + ZSYMTP^2], # thSph == ArcCos[ZSYMTP/Sqrt[RHOSYMTP^2 + ZSYMTP^2]], # phSph == x3}, # {x1, x2, x3}] Cart_to_xx[0] = sp.sqrt(-bScale**2 + rSph**2 + sp.sqrt(bScale**4 + 2*bScale**2*rSph**2 + rSph**4 - 4*bScale**2*rSph**2*sp.cos(thSph)**2))*M_SQRT1_2 # M_SQRT1_2 = 1/sqrt(2); define this way for UnitTesting # The sign() function in the following expression ensures the correct root is taken. Cart_to_xx[1] = sp.acos(sp.sign(Cartz)*( sp.sqrt(1 + rSph**2/bScale**2 - sp.sqrt(bScale**4 + 2*bScale**2*rSph**2 + rSph**4 - 4*bScale**2*rSph**2*sp.cos(thSph)**2)/bScale**2)*M_SQRT1_2)) # M_SQRT1_2 = 1/sqrt(2); define this way for UnitTesting Cart_to_xx[2] = phSph scalefactor_orthog[0] = sp.diff(AA,xx[0]) * var1 / var2 scalefactor_orthog[1] = var1 scalefactor_orthog[2] = AA * sp.sin(xx[1]) # Set the transpose of the matrix of unit vectors UnitVectors = [[sp.sin(xx[1]) * sp.cos(xx[2]) * var2 / var1, sp.sin(xx[1]) * sp.sin(xx[2]) * var2 / var1, AA * sp.cos(xx[1]) / var1], [AA * sp.cos(xx[1]) * sp.cos(xx[2]) / var1, AA * sp.cos(xx[1]) * sp.sin(xx[2]) / var1, -sp.sin(xx[1]) * var2 / var1], [-sp.sin(xx[2]), sp.cos(xx[2]), sp.sympify(0)]] ``` ```python %matplotlib inline import numpy as np # NumPy: A numerical methods module for Python import matplotlib.pyplot as plt # matplotlib: Python module specializing in plotting capabilities Nxx0 = 12 Nxx1 = 24 xx0 = np.linspace(0,1,Nxx0,endpoint=True) xx1 = np.linspace(0,np.pi,Nxx1,endpoint=True) xx2 = 0 bScale = 1 sinhA = 2.2 sinhW = 0.3 def rtilde(xx0,sinhA,sinhW): return sinhA * np.sinh(xx0/sinhW) / np.sinh(1.0/sinhW) def x(xx0,xx1,sinhA,sinhW): return rtilde(xx0,sinhA,sinhW) * np.sin(xx1) def z(xx0,xx1,bScale,sinhA,sinhW): return np.sqrt(rtilde(xx0,sinhA,sinhW)**2 + bScale**2) * np.cos(xx1) plt.clf() fig = plt.figure(dpi=160) ax = fig.gca() # Set plot title ax.set_title(r"""SinhSymTP Coordinates: zx-plane ($xx_{2}$=0 and $xx_{2}=\pi$) Blue (red) lines have constant $xx_{0}$ ($xx_{1}$)""") ax.set_xlim(-2.5,2.5) ax.set_ylim(-2.5,2.5) ax.set_aspect('equal') ax.axis('off') for i0 in range(Nxx0): plt.plot(x(xx0[i0],xx1,sinhA,sinhW),z(xx0[i0],xx1,bScale,sinhA,sinhW),'b',lw=0.75) plt.plot(-x(xx0[i0],xx1,sinhA,sinhW),z(xx0[i0],xx1,bScale,sinhA,sinhW),'b',lw=0.75) for i1 in range(Nxx1): plt.plot(x(xx0,xx1[i1],sinhA,sinhW),z(xx0,xx1[i1],bScale,sinhA,sinhW),'r',lw=0.75) plt.plot(-x(xx0,xx1[i1],sinhA,sinhW),z(xx0,xx1[i1],bScale,sinhA,sinhW),'r',lw=0.75) plt.show() ``` <a id='latex_pdf_output'></a> # Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\] $$\label{latex_pdf_output}$$ The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename [Tutorial-Reference_Metric.pdf](Tutorial-Reference_Metric.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.) ```python import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-Reference_Metric") ``` Created Tutorial-Reference_Metric.tex, and compiled LaTeX file to PDF file Tutorial-Reference_Metric.pdf
State Before: 𝕜 : Type u_1 inst✝ : LinearOrderedField 𝕜 s : Set 𝕜 f : 𝕜 → 𝕜 hf : StrictConcaveOn 𝕜 s f x y z : 𝕜 hx : x ∈ s hz : z ∈ s hxy : x < y hyz : y < z ⊢ (f z - f y) / (z - y) < (f y - f x) / (y - x) State After: 𝕜 : Type u_1 inst✝ : LinearOrderedField 𝕜 s : Set 𝕜 f : 𝕜 → 𝕜 hf : StrictConcaveOn 𝕜 s f x y z : 𝕜 hx : x ∈ s hz : z ∈ s hxy : x < y hyz : y < z this : -(((-f) z - (-f) y) / (z - y)) < -(((-f) y - (-f) x) / (y - x)) ⊢ (f z - f y) / (z - y) < (f y - f x) / (y - x) Tactic: have := neg_lt_neg (StrictConvexOn.slope_strict_mono_adjacent hf.neg hx hz hxy hyz) State Before: 𝕜 : Type u_1 inst✝ : LinearOrderedField 𝕜 s : Set 𝕜 f : 𝕜 → 𝕜 hf : StrictConcaveOn 𝕜 s f x y z : 𝕜 hx : x ∈ s hz : z ∈ s hxy : x < y hyz : y < z this : -(((-f) z - (-f) y) / (z - y)) < -(((-f) y - (-f) x) / (y - x)) ⊢ (f z - f y) / (z - y) < (f y - f x) / (y - x) State After: 𝕜 : Type u_1 inst✝ : LinearOrderedField 𝕜 s : Set 𝕜 f : 𝕜 → 𝕜 hf : StrictConcaveOn 𝕜 s f x y z : 𝕜 hx : x ∈ s hz : z ∈ s hxy : x < y hyz : y < z this : (f z - f y) / (z - y) < (f y - f x) / (y - x) ⊢ (f z - f y) / (z - y) < (f y - f x) / (y - x) Tactic: simp only [Pi.neg_apply, ← neg_div, neg_sub', neg_neg] at this State Before: 𝕜 : Type u_1 inst✝ : LinearOrderedField 𝕜 s : Set 𝕜 f : 𝕜 → 𝕜 hf : StrictConcaveOn 𝕜 s f x y z : 𝕜 hx : x ∈ s hz : z ∈ s hxy : x < y hyz : y < z this : (f z - f y) / (z - y) < (f y - f x) / (y - x) ⊢ (f z - f y) / (z - y) < (f y - f x) / (y - x) State After: no goals Tactic: exact this
lemma cball_min_Int: "cball a (min r s) = cball a r \<inter> cball a s"
------------------------------------------------------------------------------ -- Axiomatic PA propositional equality ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module PA.Axiomatic.Mendelson.Relation.Binary.PropositionalEqualityATP where open import PA.Axiomatic.Mendelson.Base ------------------------------------------------------------------------------ -- Identity properties postulate ≈-refl : ∀ {n} → n ≈ n {-# ATP prove ≈-refl #-} postulate ≈-sym : ∀ {m n} → m ≈ n → n ≈ m {-# ATP prove ≈-sym #-} postulate ≈-trans : ∀ {m n o} → m ≈ n → n ≈ o → m ≈ o {-# ATP prove ≈-trans #-}
# imports_dummy.r # # Copyright (c) 2020 VIB (Belgium) & Babraham Institute (United Kingdom) # # Software written by Carlos P. Roca, as research funded by the European Union. # # This software may be modified and distributed under the terms of the MIT # license. See the LICENSE file for details. # Definition of functions imported from packages. #' @importFrom deldir deldir tile.list which.tile #' #' @importFrom fields interp.surface #' #' @importFrom flowCore colnames compensate compensation description exprs #' read.FCS transform transformList #' #' @importFrom flowWorkspace flowjo_biexp #' #' @importFrom ggplot2 aes annotate element_blank element_line element_rect #' element_text expansion geom_abline geom_blank geom_density geom_hline #' geom_path geom_point geom_segment geom_text geom_vline ggplot ggsave #' guide_colorbar labs margin scale_color_gradientn scale_color_manual #' scale_fill_manual scale_linetype_manual scale_shape_manual #' scale_x_continuous scale_y_continuous scale_y_log10 sec_axis theme #' theme_bw #' #' @importFrom grDevices colorRampPalette #' #' @importFrom MASS bandwidth.nrd kde2d rlm #' #' @importFrom moments skewness #' #' @importFrom parallel detectCores mclapply #' #' @importFrom RColorBrewer brewer.pal #' #' @importFrom rlang .data #' #' @importFrom sp point.in.polygon #' #' @importFrom stats density ecdf kmeans lm mad median optimize pt sd splinefun #' #' @importFrom tripack convex.hull tri.mesh #' #' @importFrom utils read.csv read.table write.csv write.table imports.dummy <- function() {}
module WebServer import WebServer.JS import public WebServer.Requests %lib Node "http" %default total IORequestHandler : Type IORequestHandler = (req : Ptr) -> (res : Ptr) -> JS_IO () time : String -> JS_IO () time = js "console.time(%0)" (String -> JS_IO ()) timeLog : String -> Code -> JS_IO () timeLog label code = js "console.timeLog(%0, %1)" (String -> Int -> JS_IO ()) label (cast code) pureHandler2IOHandler : RequestHandler -> IORequestHandler pureHandler2IOHandler f ptrReq ptrRes = do let req = requestFromRaw !(method ptrReq) !(url ptrReq) let res = f req let label = show (method req) ++ " " ++ path req time label setHeaders ptrRes !(parseHeader `traverse` headers res) writeHead ptrRes (code res) write ptrRes (body res) end ptrRes timeLog label (code res) pureHandler2TwoArgChain : RequestHandler -> TwoArgChain pureHandler2TwoArgChain f = MkJsFn $ MkJsFn . pureHandler2IOHandler f export partial startServer : (port : Nat) -> (onListening: JS_IO ()) -> RequestHandler -> JS_IO () startServer port onListening onRequest = do server <- js "http.createServer()" (JS_IO Ptr) js "%0.listen(%1)" SendInt server (cast port) js "%0.on('request', (req, res) => { %1(req)(res)() })" (Ptr -> TwoArgChain -> JS_IO Ptr) server (pureHandler2TwoArgChain onRequest) js "%0.on('listening', %1)" (Ptr -> JsFn (() -> JS_IO ()) -> JS_IO ()) server (MkJsFn (\_ => onListening)) js "process.on('SIGTERM', process.exit)" (JS_IO ()) -- Local Variables: -- idris-load-packages: ("contrib") -- End:
Set Implicit Arguments. Require Import TLC.LibTactics. (* Load the CFML library, with time credits. *) Require Import CFML.CFLibCredits. Require Pervasives_ml. Require Array_ml. Require Import Pervasives_proof. Require Import ArrayCredits_proof. (* Load the big-O library. *) Require Import Dominated. Require Import UltimatelyGreater. Require Import Monotonic. Require Import LibZExtra. (* Load the custom CFML tactics with support for big-Os *) Require Import CFMLBigO. (* FIXME: coq bug *) Lemma L: forall A B (x : (A * B)%type) (f g : A -> B -> Z), f (fst x) (snd x) = g (fst x) (snd x) -> (let (y,z) := x in f y z) = (let (y,z) := x in g y z). Proof. intros ? ? x_ ? ? ?. destruct x_. simpl in *. assumption. Qed. Goal specO (product_filterType Z_filterType Z_filterType) eq (fun _ => True) (fun '(n,m) => 0). Proof. xspecO. admit. unfold cleanup_cost. splits. intro x. unfold costf. eapply L. (* simpl. *) Abort. (* For later: what to think about the following unification problem: x + y = ?f(x,y) + ?g(x,y) Coq doesn't know how to solve it (and there are at least two different solutions, (eg inserting a let or using projections)). Is it a feature? Is it a limitation that may be lifted in the future? *)
If $f$ is a continuous function from a set $S$ to a normed vector space $V$ such that for every $x \in S$, there exists an $\epsilon > 0$ such that for all $y \in S$ with $f(y) \neq f(x)$, we have $\epsilon \leq \|f(y) - f(x)\|$, then the image of $f$ is a discrete set.
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall A B C Aprime Bprime Cprime O : Universe, ((wd_ B O /\ (wd_ C O /\ (wd_ Bprime O /\ (wd_ Cprime O /\ (wd_ A O /\ (wd_ Aprime O /\ (wd_ A B /\ (wd_ A Aprime /\ (wd_ A C /\ (col_ O A B /\ (col_ O B C /\ (col_ O Aprime Bprime /\ (col_ O Bprime Cprime /\ (col_ O A C /\ (col_ O B Cprime /\ col_ A B C))))))))))))))) -> col_ O A Aprime)). Proof. time tac. Qed. End FOFProblem.
Set Implicit Arguments. Inductive AExp : Type := | ANum : nat -> AExp | APlus : AExp -> AExp -> AExp | AMinus : AExp -> AExp -> AExp | AMult : AExp -> AExp -> AExp. Inductive BExp : Type := | BTrue : BExp | BFalse : BExp | BLess : AExp -> AExp -> BExp. Notation "e1 :<: e2" := (BLess e1 e2) (at level 40, left associativity). Notation "e1 :+: e2" := (APlus e1 e2) (at level 40, left associativity). Notation "e1 :-: e2" := (AMinus e1 e2) (at level 40, left associativity). Notation "e1 :*: e2" := (AMult e1 e2) (at level 40, left associativity). Fixpoint aeval (e : AExp) : nat := match e with | ANum n => n | APlus e1 e2 => aeval e1 + aeval e2 | AMinus e1 e2 => aeval e1 - aeval e2 | AMult e1 e2 => aeval e1 * aeval e2 end. Fixpoint beval (e : BExp) : bool := match e with | BTrue => true | BFalse => false | BLess e1 e2 => Nat.leb (aeval e1) (aeval e2) end.
#' @export lengthHist <-function(x,by="spp",level="all",fraction=c("DIS","LAN"),title=TRUE,...) { #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lengthHist # function that plots histograms # of the length frequency data # in the hl table of csData objects # Borrows heavily from MM's lenDisPlot code #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #library(COSTeda) #data(ASFIS) if(class(x)%in%c("csPi","csData","csDataVal")==FALSE)stop("x is not csData") spp <-ifelse(length(table(x@hl$spp))==1,x@hl$spp[1],"multiple species") dots <-list(...) if(class(x) %in%c("csPi")) { data(ASFIS) object <-suppressWarnings(mergecsPi(x))@hl } if(class(x) %in%c("csData","csDataVal")) { data(code.list) ASFIS <-code.list$spp object <-suppressWarnings(mergecsData(x))@hl } if((by %in% names(object))!=TRUE)stop("by not a recognised grouping variable") #if(all((fraction %in% names(table(object$catchCat)))==FALSE)) if(all(names(table(object$catchCat))=="DIS")) { fraction <-"DIS" warning("Only DIS fraction present in data") } if(all(names(table(object$catchCat))=="LAN")) { fraction <-"LAN" warning("Only LAN fraction present in data") } if(all(fraction %in% names(table(object$catchCat)))==FALSE) { stop(paste(fraction,"fraction not in the data")) } lgthCode <- as.character(x@sl$lenCode[1]) stepp <- c(1,5,10,25) names(stepp) <- c("mm","scm","cm","25mm") ste <- stepp[lgthCode] varlevs <-as.character(level) if(level[1]=="all")varlevs <-levels(factor(object[[by]])) if(any(as.character(varlevs) %in% as.character(object[[by]])==FALSE)) { stop("level not present in the variable") } df <-object # a call to hist to get the breaks over the length class range alllengths <-rep(df$lenCls,df$lenNum) vals <-hist(alllengths,plot=F,breaks=seq(min(df$lenCls),max(df$lenCls),by=ste)) # running through the levels to get the ylimits allcounts <-NULL for(i in 1:length(varlevs)) { df <- object[(as.character(object[[by]])%in%as.character(varlevs[i]))&(object$catchCat %in% fraction),] if(dim(df)[1]==0)next alllengths <-rep(df$lenCls,df$lenNum) allcounts <-append(allcounts,hist(alllengths,breaks=seq(min(df$lenCls) ,max(df$lenCls),by=ste),plot=F)$counts) } # doing some defaults for the dots argument addtitle <-FALSE if(is.null(dots$main))addtitle <-TRUE if(is.null(dots$axes))dots$axes <-TRUE if(is.null(dots$add))dots$add <-FALSE if(is.null(dots$angle))dots$angle <-45 if(is.null(dots$freq))dots$freq <-TRUE if(is.null(dots$ylim))dots$ylim <-c(min(allcounts),max(allcounts)) if(dots$freq==FALSE)dots$ylim <-NULL if(is.null(dots$xlab))dots$xlab <-"Length class (mm)" if(is.null(dots$ylab)&dots$freq==TRUE)dots$ylab <-"Frequency" if(is.null(dots$ylab)&dots$freq==FALSE)dots$ylab <-"Density" # and finally plotting out the levels out <-NULL for(i in 1:length(varlevs)) { if(addtitle)dots$main <-paste(by,varlevs[i],sep=" ") if(addtitle&&by=="month")dots$main <-month.abb[as.numeric(varlevs)][i] df <- object[(as.character(object[[by]])%in%as.character(varlevs[i]))&(object$catchCat %in% fraction),] alllengths <-rep(df$lenCls,df$lenNum) out[[i]] <-hist(alllengths,main=dots$main,sub=dots$sub,xlab=dots$xlab,ylab=dots$ylab,breaks=vals$breaks ,ylim=dots$ylim,freq=dots$freq,col=dots$col,border=dots$border, density=dots$density,angle=dots$angle,axes=dots$axes,add=dots$add, cex.main=dots$cex.main ,line=dots$line,cex.axis=dots$cex.axis,cex.lab=dots$cex.lab) } # adding the outer margin title fishname <-spp if(fishname!="multiple species") { fishname <- as.character(ASFIS$English_name[ASFIS$Scientific_name == spp]) } if(title) { title(paste("Length distribution for ",fishname," by ",by, sep=""),outer=TRUE,line=-1,cex.main=dots$cex.main) } names(out) <-varlevs invisible(out) } #------------end of lengthHist------------------------
[STATEMENT] lemma c_out_list_correct_cf: fixes t defines "h \<equiv> (\<lambda>a. sel_r (first_node t) a * cf' a)" assumes "valid_tree t" and "no_cross_products t" and "left_deep t" shows "c_list_r h (first_node t) (revorder t) = c_out cf match_sel t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. c_list_r h (first_node t) (revorder t) = c_out cf match_sel t [PROOF STEP] using c_out_list_correct_cf' c_out_cf'_eq' assms [PROOF STATE] proof (prove) using this: \<lbrakk>valid_tree ?t; no_cross_products ?t; left_deep ?t\<rbrakk> \<Longrightarrow> c_list_r (\<lambda>a. sel_r (first_node ?t) a * cf' a) (first_node ?t) (revorder ?t) = c_out cf' match_sel ?t valid_tree ?t \<Longrightarrow> c_out cf' ?sf ?t = c_out cf ?sf ?t h \<equiv> \<lambda>a. sel_r (first_node t) a * cf' a valid_tree t no_cross_products t left_deep t goal (1 subgoal): 1. c_list_r h (first_node t) (revorder t) = c_out cf match_sel t [PROOF STEP] by simp
data Vect : Nat -> Type -> Type where Nil : Vect Z a (::) : a -> Vect k a -> Vect (S k) a %name Vect xs, ys, zs append : Vect n a -> Vect m a -> Vect (n + m) a append {n} xs ys = ?foo vadd : Num a => Vect n a -> Vect n a -> Vect n a vadd [] ys = ?bar vadd (x :: xs) ys = ?baz suc : (x : Nat) -> (y : Nat) -> x = y -> S x = S y suc x y prf = ?quux suc' : x = y -> S x = S y suc' {x} {y} prf = ?quuz
\documentclass[final,5p,times,twocolumn]{elsarticle} \usepackage{lineno,hyperref} \usepackage{amssymb} \usepackage{array} \usepackage{graphicx} \usepackage{float} \usepackage{supertabular} \usepackage[table]{xcolor} % Some very useful LaTeX packages include: % (uncomment the ones you want to load) \providecommand{\tabularnewline}{\\} \usepackage{booktabs, multicol, multirow} \usepackage[acronym,nomain]{glossaries} \usepackage[inline]{enumitem} \usepackage{algorithm} \usepackage{algorithmicx} \usepackage{algpseudocode} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{subfigure} \usepackage{grffile} \usepackage{tabularx} \usepackage{colortbl} \usepackage{hhline} \usepackage{hyperref} \usepackage{here} \usepackage{graphicx} % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % new commands % % % \usepackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes} % % Convenience commands for the paper editing process % \newcommand{\comment}[1]{{\textbf{\color{red}[#1]}}} \newcommand{\fixed}[1]{{\textbf{\color{blue}[#1]}}} % % Convenience commands for references % \newcommand{\secref}[1]{Section~\ref{sec:#1}} \newcommand{\tabref}[1]{Table~\ref{tab:#1}} \newcommand{\figref}[1]{Figure~\ref{fig:#1}} \newcommand{\quotes}[1]{``#1''} \newcommand{\argmin}{\arg\!\min} \newcommand{\argmax}{\arg\!\max} \newtheorem{definition}{Definition} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % Acronym definitions \newacronym{sps}{SPS}{Stream Processing Systems} \newacronym{pe}{PE}{Processing Elements} \newacronym{dag}{DAG}{Directed Acyclic Graph} % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % Some very useful LaTeX packages include: % (uncomment the ones you want to load) % *** MISC UTILITY PACKAGES *** % %\usepackage{ifpdf} % Heiko Oberdiek's ifpdf.sty is very useful if you need conditional % compilation based on whether the output is pdf or dvi. % usage: % \ifpdf % % pdf code % \else % % dvi code % \fi % The latest version of ifpdf.sty can be obtained from: % http://www.ctan.org/pkg/ifpdf % Also, note that IEEEtran.cls V1.7 and later provides a builtin % \ifCLASSINFOpdf conditional that works the same way. % When switching from latex to pdflatex and vice-versa, the compiler may % have to be run twice to clear warning/error messages. % *** CITATION PACKAGES *** % %\usepackage{cite} % cite.sty was written by Donald Arseneau % V1.6 and later of IEEEtran pre-defines the format of the cite.sty package % \cite{} output to follow that of the IEEE. Loading the cite package will % result in citation numbers being automatically sorted and properly % "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using % cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's % \cite will automatically add leading space, if needed. Use cite.sty's % noadjust option (cite.sty V3.8 and later) if you want to turn this off % such as if a citation ever needs to be enclosed in parenthesis. % cite.sty is already installed on most LaTeX systems. Be sure and use % version 5.0 (2009-03-20) and later if using hyperref.sty. % The latest version can be obtained at: % http://www.ctan.org/pkg/cite % The documentation is contained in the cite.sty file itself. % *** GRAPHICS RELATED PACKAGES *** % % declare the path(s) where your graphic files are % \graphicspath{{../pdf/}{../jpeg/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics % \DeclareGraphicsExtensions{.pdf,.jpeg,.png} % or other class option (dvipsone, dvipdf, if not using dvips). graphicx % will default to the driver specified in the system graphics.cfg if no % driver is specified. % \usepackage[dvips]{graphicx} % declare the path(s) where your graphic files are % \graphicspath{{../eps/}} % and their extensions so you won't have to specify these with % every instance of \includegraphics % \DeclareGraphicsExtensions{.eps} % graphicx was written by David Carlisle and Sebastian Rahtz. It is % required if you want graphics, photos, etc. graphicx.sty is already % installed on most LaTeX systems. The latest version and documentation % can be obtained at: % http://www.ctan.org/pkg/graphicx % Another good source of documentation is "Using Imported Graphics in % LaTeX2e" by Keith Reckdahl which can be found at: % http://www.ctan.org/pkg/epslatex % % latex, and pdflatex in dvi mode, support graphics in encapsulated % postscript (.eps) format. pdflatex in pdf mode supports graphics % in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure % that all non-photo figures use a vector format (.eps, .pdf, .mps) and % not a bitmapped formats (.jpeg, .png). The IEEE frowns on bitmapped formats % which can result in "jaggedy"/blurry rendering of lines and letters as % well as large increases in file sizes. % % You can find documentation about the pdfTeX application at: % http://www.tug.org/applications/pdftex \usepackage{pgf} \usepackage{tikz} \usetikzlibrary{arrows,automata} \usetikzlibrary{shapes.misc} \tikzset{cross/.style={cross out, draw=black, minimum size=3*(#1-\pgflinewidth), inner sep=0pt, outer sep=0pt}, %default radius will be 1pt. cross/.default={10pt}} % *** MATH PACKAGES *** % %\usepackage{amsmath} % A popular package from the American Mathematical Society that provides % many useful and powerful commands for dealing with mathematics. % % Note that the amsmath package sets \interdisplaylinepenalty to 10000 % thus preventing page breaks from occurring within multiline equations. Use: %\interdisplaylinepenalty=2500 % after loading amsmath to restore such page breaks as IEEEtran.cls normally % does. amsmath.sty is already installed on most LaTeX systems. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/amsmath % *** SPECIALIZED LIST PACKAGES *** % % algorithmic.sty was written by Peter Williams and Rogerio Brito. % This package provides an algorithmic environment fo describing algorithms. % You can use the algorithmic environment in-text or within a figure % environment to provide for a floating algorithm. Do NOT use the algorithm % floating environment provided by algorithm.sty (by the same authors) or % algorithm2e.sty (by Christophe Fiorio) as the IEEE does not use dedicated % algorithm float types and packages that provide these will not provide % correct IEEE style captions. The latest version and documentation of % algorithmic.sty can be obtained at: % http://www.ctan.org/pkg/algorithms % Also of interest may be the (relatively newer and more customizable) % algorithmicx.sty package by Szasz Janos: % http://www.ctan.org/pkg/algorithmicx % *** ALIGNMENT PACKAGES *** % \usepackage{array} % Frank Mittelbach's and David Carlisle's array.sty patches and improves % the standard LaTeX2e array and tabular environments to provide better % appearance and additional user controls. As the default LaTeX2e table % generation code is lacking to the point of almost being broken with % respect to the quality of the end results, all users are strongly % advised to use an enhanced (at the very least that provided by array.sty) % set of table tools. array.sty is already installed on most systems. The % latest version and documentation can be obtained at: % http://www.ctan.org/pkg/array % IEEEtran contains the IEEEeqnarray family of commands that can be used to % generate multiline equations as well as matrices, tables, etc., of high % quality. % *** SUBFIGURE PACKAGES *** %\ifCLASSOPTIONcompsoc % \usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig} %\else % \usepackage[caption=false,font=footnotesize]{subfig} %\fi % subfig.sty, written by Steven Douglas Cochran, is the modern replacement % for subfigure.sty, the latter of which is no longer maintained and is % incompatible with some LaTeX packages including fixltx2e. However, % subfig.sty requires and automatically loads Axel Sommerfeldt's caption.sty % which will override IEEEtran.cls' handling of captions and this will result % in non-IEEE style figure/table captions. To prevent this problem, be sure % and invoke subfig.sty's "caption=false" package option (available since % subfig.sty version 1.3, 2005/06/28) as this is will preserve IEEEtran.cls % handling of captions. % Note that the Computer Society format requires a larger sans serif font % than the serif footnote size font used in traditional IEEE formatting % and thus the need to invoke different subfig.sty package options depending % on whether compsoc mode has been enabled. % % The latest version and documentation of subfig.sty can be obtained at: % http://www.ctan.org/pkg/subfig % *** FLOAT PACKAGES *** % %\usepackage{fixltx2e} % fixltx2e, the successor to the earlier fix2col.sty, was written by % Frank Mittelbach and David Carlisle. This package corrects a few problems % in the LaTeX2e kernel, the most notable of which is that in current % LaTeX2e releases, the ordering of single and double column floats is not % guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a % single column figure to be placed prior to an earlier double column % figure. % Be aware that LaTeX2e kernels dated 2015 and later have fixltx2e.sty's % corrections already built into the system in which case a warning will % be issued if an attempt is made to load fixltx2e.sty as it is no longer % needed. % The latest version and documentation can be found at: % http://www.ctan.org/pkg/fixltx2e %\usepackage{stfloats} % stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e % the ability to do double column floats at the bottom of the page as well % as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in % LaTeX2e). It also provides a command: %\fnbelowfloat % to enable the placement of footnotes below bottom floats (the standard % LaTeX2e kernel puts them above bottom floats). This is an invasive package % which rewrites many portions of the LaTeX2e float routines. It may not work % with other packages that modify the LaTeX2e float routines. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/stfloats % Do not use the stfloats baselinefloat ability as the IEEE does not allow % \baselineskip to stretch. Authors submitting work to the IEEE should note % that the IEEE rarely uses double column equations and that authors should try % to avoid such use. Do not be tempted to use the cuted.sty or midfloat.sty % packages (also by Sigitas Tolusis) as the IEEE does not format its papers in % such ways. % Do not attempt to use stfloats with fixltx2e as they are incompatible. % Instead, use Morten Hogholm'a dblfloatfix which combines the features % of both fixltx2e and stfloats: % % \usepackage{dblfloatfix} % The latest version can be found at: % http://www.ctan.org/pkg/dblfloatfix % *** PDF, URL AND HYPERLINK PACKAGES *** % % *** MISC UTILITY PACKAGES *** % %\usepackage{ifpdf} % Heiko Oberdiek's ifpdf.sty is very useful if you need conditional % compilation based on whether the output is pdf or dvi. % usage: % \ifpdf % % pdf code % \else % % dvi code % \fi % The latest version of ifpdf.sty can be obtained from: % http://www.ctan.org/tex-archive/macros/latex/contrib/oberdiek/ % Also, note that IEEEtran.cls V1.7 and later provides a builtin % \ifCLASSINFOpdf conditional that works the same way. % When switching from latex to pdflatex and vice-versa, the compiler may % have to be run twice to clear warning/error messages. \usepackage{balance} \usepackage{url} \usepackage{rotating} % Some very useful LaTeX packages include: % (uncomment the ones you want to load) % *** MISC UTILITY PACKAGES *** % %\usepackage{ifpdf} % Heiko Oberdiek's ifpdf.sty is very useful if you need conditional % compilation based on whether the output is pdf or dvi. % usage: % \ifpdf % % pdf code % \else % % dvi code % \fi % The latest version of ifpdf.sty can be obtained from: % http://www.ctan.org/pkg/ifpdf % Also, note that IEEEtran.cls V1.7 and later provides a builtin % \ifCLASSINFOpdf conditional that works the same way. % When switching from latex to pdflatex and vice-versa, the compiler may % have to be run twice to clear warning/error messages. % *** CITATION PACKAGES *** % %\usepackage{cite} % cite.sty was written by Donald Arseneau % V1.6 and later of IEEEtran pre-defines the format of the cite.sty package % \cite{} output to follow that of the IEEE. Loading the cite package will % result in citation numbers being automatically sorted and properly % "compressed/ranged". e.g., [1], [9], [2], [7], [5], [6] without using % cite.sty will become [1], [2], [5]--[7], [9] using cite.sty. cite.sty's % \cite will automatically add leading space, if needed. Use cite.sty's % noadjust option (cite.sty V3.8 and later) if you want to turn this off % such as if a citation ever needs to be enclosed in parenthesis. % cite.sty is already installed on most LaTeX systems. Be sure and use % version 5.0 (2009-03-20) and later if using hyperref.sty. % The latest version can be obtained at: % http://www.ctan.org/pkg/cite % The documentation is contained in the cite.sty file itself. % *** GRAPHICS RELATED PACKAGES *** % % graphicx was written by David Carlisle and Sebastian Rahtz. It is % required if you want graphics, photos, etc. graphicx.sty is already % installed on most LaTeX systems. The latest version and documentation % can be obtained at: % http://www.ctan.org/pkg/graphicx % Another good source of documentation is "Using Imported Graphics in % LaTeX2e" by Keith Reckdahl which can be found at: % http://www.ctan.org/pkg/epslatex % % latex, and pdflatex in dvi mode, support graphics in encapsulated % postscript (.eps) format. pdflatex in pdf mode supports graphics % in .pdf, .jpeg, .png and .mps (metapost) formats. Users should ensure % that all non-photo figures use a vector format (.eps, .pdf, .mps) and % not a bitmapped formats (.jpeg, .png). The IEEE frowns on bitmapped formats % which can result in "jaggedy"/blurry rendering of lines and letters as % well as large increases in file sizes. % % You can find documentation about the pdfTeX application at: % http://www.tug.org/applications/pdftex % *** MATH PACKAGES *** % %\usepackage{amsmath} % A popular package from the American Mathematical Society that provides % many useful and powerful commands for dealing with mathematics. % % Note that the amsmath package sets \interdisplaylinepenalty to 10000 % thus preventing page breaks from occurring within multiline equations. Use: %\interdisplaylinepenalty=2500 % after loading amsmath to restore such page breaks as IEEEtran.cls normally % does. amsmath.sty is already installed on most LaTeX systems. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/amsmath % *** SPECIALIZED LIST PACKAGES *** % %\usepackage{algorithmic} % algorithmic.sty was written by Peter Williams and Rogerio Brito. % This package provides an algorithmic environment fo describing algorithms. % You can use the algorithmic environment in-text or within a figure % environment to provide for a floating algorithm. Do NOT use the algorithm % floating environment provided by algorithm.sty (by the same authors) or % algorithm2e.sty (by Christophe Fiorio) as the IEEE does not use dedicated % algorithm float types and packages that provide these will not provide % correct IEEE style captions. The latest version and documentation of % algorithmic.sty can be obtained at: % http://www.ctan.org/pkg/algorithms % Also of interest may be the (relatively newer and more customizable) % algorithmicx.sty package by Szasz Janos: % http://www.ctan.org/pkg/algorithmicx % *** ALIGNMENT PACKAGES *** % %\usepackage{array} % Frank Mittelbach's and David Carlisle's array.sty patches and improves % the standard LaTeX2e array and tabular environments to provide better % appearance and additional user controls. As the default LaTeX2e table % generation code is lacking to the point of almost being broken with % respect to the quality of the end results, all users are strongly % advised to use an enhanced (at the very least that provided by array.sty) % set of table tools. array.sty is already installed on most systems. The % latest version and documentation can be obtained at: % http://www.ctan.org/pkg/array % IEEEtran contains the IEEEeqnarray family of commands that can be used to % generate multiline equations as well as matrices, tables, etc., of high % quality. % *** SUBFIGURE PACKAGES *** %\ifCLASSOPTIONcompsoc % \usepackage[caption=false,font=normalsize,labelfont=sf,textfont=sf]{subfig} %\else % \usepackage[caption=false,font=footnotesize]{subfig} %\fi % subfig.sty, written by Steven Douglas Cochran, is the modern replacement % for subfigure.sty, the latter of which is no longer maintained and is % incompatible with some LaTeX packages including fixltx2e. However, % subfig.sty requires and automatically loads Axel Sommerfeldt's caption.sty % which will override IEEEtran.cls' handling of captions and this will result % in non-IEEE style figure/table captions. To prevent this problem, be sure % and invoke subfig.sty's "caption=false" package option (available since % subfig.sty version 1.3, 2005/06/28) as this is will preserve IEEEtran.cls % handling of captions. % Note that the Computer Society format requires a larger sans serif font % than the serif footnote size font used in traditional IEEE formatting % and thus the need to invoke different subfig.sty package options depending % on whether compsoc mode has been enabled. % % The latest version and documentation of subfig.sty can be obtained at: % http://www.ctan.org/pkg/subfig % *** FLOAT PACKAGES *** % %\usepackage{fixltx2e} % fixltx2e, the successor to the earlier fix2col.sty, was written by % Frank Mittelbach and David Carlisle. This package corrects a few problems % in the LaTeX2e kernel, the most notable of which is that in current % LaTeX2e releases, the ordering of single and double column floats is not % guaranteed to be preserved. Thus, an unpatched LaTeX2e can allow a % single column figure to be placed prior to an earlier double column % figure. % Be aware that LaTeX2e kernels dated 2015 and later have fixltx2e.sty's % corrections already built into the system in which case a warning will % be issued if an attempt is made to load fixltx2e.sty as it is no longer % needed. % The latest version and documentation can be found at: % http://www.ctan.org/pkg/fixltx2e %\usepackage{stfloats} % stfloats.sty was written by Sigitas Tolusis. This package gives LaTeX2e % the ability to do double column floats at the bottom of the page as well % as the top. (e.g., "\begin{figure*}[!b]" is not normally possible in % LaTeX2e). It also provides a command: %\fnbelowfloat % to enable the placement of footnotes below bottom floats (the standard % LaTeX2e kernel puts them above bottom floats). This is an invasive package % which rewrites many portions of the LaTeX2e float routines. It may not work % with other packages that modify the LaTeX2e float routines. The latest % version and documentation can be obtained at: % http://www.ctan.org/pkg/stfloats % Do not use the stfloats baselinefloat ability as the IEEE does not allow % \baselineskip to stretch. Authors submitting work to the IEEE should note % that the IEEE rarely uses double column equations and that authors should try % to avoid such use. Do not be tempted to use the cuted.sty or midfloat.sty % packages (also by Sigitas Tolusis) as the IEEE does not format its papers in % such ways. % Do not attempt to use stfloats with fixltx2e as they are incompatible. % Instead, use Morten Hogholm'a dblfloatfix which combines the features % of both fixltx2e and stfloats: % % \usepackage{dblfloatfix} % The latest version can be found at: % http://www.ctan.org/pkg/dblfloatfix %\ifCLASSOPTIONcaptionsoff % \usepackage[nomarkers]{endfloat} % \let\MYoriglatexcaption\caption % \renewcommand{\caption}[2][\relax]{\MYoriglatexcaption[#2]{#2}} %\fi % endfloat.sty was written by James Darrell McCauley, Jeff Goldberg and % Axel Sommerfeldt. This package may be useful when used in conjunction with % IEEEtran.cls' captionsoff option. Some IEEE journals/societies require that % submissions have lists of figures/tables at the end of the paper and that % figures/tables without any captions are placed on a page by themselves at % the end of the document. If needed, the draftcls IEEEtran class option or % \CLASSINPUTbaselinestretch interface can be used to increase the line % spacing as well. Be sure and use the nomarkers option of endfloat to % prevent endfloat from "marking" where the figures would have been placed % in the text. The two hack lines of code above are a slight modification of % that suggested by in the endfloat docs (section 8.4.1) to ensure that % the full captions always appear in the list of figures/tables - even if % the user used the short optional argument of \caption[]{}. % IEEE papers do not typically make use of \caption[]'s optional argument, % so this should not be an issue. A similar trick can be used to disable % captions of packages such as subfig.sty that lack options to turn off % the subcaptions: % For subfig.sty: % \let\MYorigsubfloat\subfloat % \renewcommand{\subfloat}[2][\relax]{\MYorigsubfloat[]{#2}} % However, the above trick will not work if both optional arguments of % the \subfloat command are used. Furthermore, there needs to be a % description of each subfigure *somewhere* and endfloat does not add % subfigure captions to its list of figures. Thus, the best approach is to % avoid the use of subfigure captions (many IEEE journals avoid them anyway) % and instead reference/explain all the subfigures within the main caption. % The latest version of endfloat.sty and its documentation can obtained at: % http://www.ctan.org/pkg/endfloat % % The IEEEtran \ifCLASSOPTIONcaptionsoff conditional can also be used % later in the document, say, to conditionally put the References on a % page by themselves. % *** PDF, URL AND HYPERLINK PACKAGES *** % %\usepackage{url} % url.sty was written by Donald Arseneau. It provides better support for % handling and breaking URLs. url.sty is already installed on most LaTeX % systems. The latest version and documentation can be obtained at: % http://www.ctan.org/pkg/url % Basically, \url{my_url_here}. % *** Do not adjust lengths that control margins, column widths, etc. *** % *** Do not use packages that alter fonts (such as pslatex). *** % There should be no need to do such things with IEEEtran.cls V1.6 and later. % (Unless specifically asked to do so by the journal or conference you plan % to submit to, of course. ) \modulolinenumbers[5] \journal{Journal of Systems and Software} %%%%%%%%%%%%%%%%%%%%%%% %% Elsevier bibliography styles %%%%%%%%%%%%%%%%%%%%%%% %% To change the style, put a % in front of the second line of the current style and %% remove the % from the second line of the style you would like to use. %%%%%%%%%%%%%%%%%%%%%%% %% Numbered %\bibliographystyle{model1-num-names} %% Numbered without titles %\bibliographystyle{model1a-num-names} %% Harvard %\bibliographystyle{model2-names.bst}\biboptions{authoryear} %% Vancouver numbered %\usepackage{numcompress}\bibliographystyle{model3-num-names} %% Vancouver name/year %\usepackage{numcompress}\bibliographystyle{model4-names}\biboptions{authoryear} %% APA style %\bibliographystyle{model5-names}\biboptions{authoryear} %% AMA style %\usepackage{numcompress}\bibliographystyle{model6-num-names} %% `Elsevier LaTeX' style \bibliographystyle{elsarticle-num} %%%%%%%%%%%%%%%%%%%%%%% \begin{document} \begin{frontmatter} \title{Supporting Continuous Architecting of Data-Intensive Applications} %\tnotetext[mytitlenote]{Fully documented templates are available in the elsarticle package on \href{http://www.ctan.org/tex-archive/macros/latex/contrib/elsarticle}{CTAN}.} %% Group authors per affiliation: \author{Marcello M. Bersani, Francesco Marconi, Damian A. Tamburri} \address{Politecnico di Milano, Milan, Italy} \address{$[$marcellomaria.bersani, francesco.marconi, damianandrew.tamburri$][email protected]} %% or include affiliations in footnotes: %\author[mymainaddress,mysecondaryaddress]{Elsevier Inc} %\ead[url]{www.elsevier.com} \author{Andrea Nodari, Pooyan Jamshidi} \address[mymainaddress]{Imperial College London, UK} \address{$[$p.jamshidi,a.nodari15$][email protected]} \begin{abstract} Big data architectures have been gaining momentum in recent years. For instance, Twitter uses stream processing frameworks like Storm to analyse billions of tweets per minute and learn the trending topics. However, architectures that process big data involve many different components interconnected via semantically different connectors making it a difficult task for software architects to refactor the initial designs. As an aid to designers and developers, we developed OSTIA that stands for ``On-the-fly Static Topology Inference Analysis"; OSTIA is a tool that allows: (a) recovering big data architectures for the purpose of design-time refactoring while maintaining constraints that would only be evaluated at later stages (deployment, run-time); (b) detecting the occurrence of common anti-patterns across big data architectures; (c) exploiting software verification techniques to evaluate the safety of the elicited architectural models. This paper illustrates OSTIA and evaluates its uses and benefits using industrial and open-source case study research. \end{abstract} \begin{keyword} DevOps \sep Continuous Architecting\sep Big Data \end{keyword} \end{frontmatter} \linenumbers \section{Introduction} \label{intro} \input{intro} \section{Terminological Reflections on Continuous Architecting} With respect to the typical definition of software architectures, namely, \emph{[...] a set of interconnected and inter-communicating components across a series of connectors and other architecture elements} \cite{kazmanbook}, data-intensive application topologies are not properly \emph{software architectures}. Rather, DIA topologies are graphs of operations to be applied on raw big data. However, for the sake of designing their data-intensive applications, data-intensive architects need to use those topologies as subjects of the same rigorous architecting principles, practices, analyses and trade-offs inherited from software architecture research and practice. Much in the same vein, in designing OSTIA, we inherited tools, practices and approaches from software architecture recovery \cite{DobricaN02} to enable DIA topology reverse-engineering. This parallel between software architectures and data-intensive topologies is reasonable for two reasons. On one hand, DIA topologies bear the same weight on overall DIA performance and application properties since they contain the architecture decisions (e.g., DIA middleware interconnections and dependencies) and middleware configurations (e.g., memory footprint, resource management, scheduling policies, degrees of parallelism) that dictate the visible DIA architecture properties. On the other hand, multiple middleware with different topologies may be merged within the same DIA -- in this instance it is in fact the combination of several topologies, typically one per each data-processing middleware, that dictates visible DIA architecture properties. As a result in the scope of OSTIA, the tool recovers *all distinct topology graphs* for supported technologies (Apache Hadoop and Apache Storm) that it finds in the namespace provided as input. With this premise, \emph{we advocate that an analogy exists between the classical notion of software architecture and our notion of DIA topology, and, for this reason from now on we use the terms topology and architecture interchangeably.} Under the above premise, we aim to support DIA \emph{*continuous*} architecting; In the big data domain, such continuous architecting means supporting the continuous and incremental improvement of big data topologies - e.g., according to the following iterative process: \begin{enumerate} \item changing the topological arrangement of data-processing elements in the topology, as well as tuning any of their properties (e.g., replication and parallelisation factors); \item changing the data-intensive middleware configuration parameters (e.g., queues and their lengths); \item using on-the-fly analyses on running applications (e.g., queue safety given a certain workload); \item exploiting platform and infrastructure monitoring data -- for example, the industrial partner that aided the evaluation of the results in this paper is currently facing the issue of continuously changing and re-arranging their stream processing application in response to: (a) types of content that need analysis (multimedia images, audios as opposed to news articles and text); (b) types of users that need recommendation (e.g., governments as opposed to single users); \item evaluate results and improvements, iterating back to step 1, if and where necessary; \end{enumerate} With OSTIA, we aimed at providing automated support to the above continuous architecting exercise in the scope of data-intensive architectures. OSTIA supports the (re-)design steps 1 to 3 with algorithmic manipulation, heuristics, and design anti-pattern matching; also, the tool supports step 5 with formal verification techniques. \section{Research Design and Context of Study} \label{ra} \input{ra} \section{Research Solution} \label{rs} \input{rs} \input{anti-pattern} \section{Evaluation} \label{eval} \input{eval} \section{Discussion} \label{disc} \input{disc} \section{Related Work} \label{rw} \input{rw} \section{Conclusion} \input{conc} \label{conc} %\clearpage % conference papers do not normally have an appendix % trigger a \newpage just before the given reference % number - used to balance the columns on the last page % adjust value as needed - may need to be readjusted if % the document is modified later %\IEEEtriggeratref{8} % The triggered command can be changed if desired: %\IEEEtriggercmd{\enlargethispage{-5in}} % references section % can use a bibliography generated by BibTeX as a .bbl file % BibTeX documentation can be easily obtained at: % http://www.ctan.org/tex-archive/biblio/bibtex/contrib/doc/ % The IEEEtran BibTeX style support page is at: % http://www.michaelshell.org/tex/ieeetran/bibtex/ %\balance \bibliography{ostia} \end{document}
module TestBuffer import Data.Buffer import System.File put : Show a => IO a -> IO () put = (>>= putStrLn . show) main : IO () main = do Just buf <- newBuffer 31 | Nothing => pure () setByte buf 0 1 setBits8 buf 1 2 setInt buf 2 0x1122334455667788 setDouble buf 10 (sqrt 2) let helloWorld = "Hello, world" Just helloWorldBuf <- newBuffer (stringByteLength helloWorld) | Nothing => pure () setString helloWorldBuf 0 "Hello, world" copyData helloWorldBuf 0 12 buf 18 put $ rawSize buf put $ getByte buf 0 put $ getBits8 buf 1 put $ getInt buf 2 put $ getDouble buf 10 put $ getString buf 18 12 put $ bufferData buf Just readBuf <- newBuffer 8 | Nothing => pure () Right f <- openFile "testRead.buf" Read | Left err => put $ pure err Right () <- readBufferData f readBuf 0 8 | Left err => put $ pure err put $ bufferData readBuf Just writeBuf <- newBuffer 8 | Nothing => pure () setInt writeBuf 0 0x7766554433221100 Right f <- openFile "testWrite.buf" WriteTruncate | Left err => put $ pure err Right () <- writeBufferData f writeBuf 0 8 | Left err => put $ pure err pure ()
Formal statement is: lemma cis_arg: "z \<noteq> 0 \<Longrightarrow> cis (arg z) = sgn z" Informal statement is: If $z \neq 0$, then $\text{cis}(\text{arg}(z)) = \text{sgn}(z)$.
function vol=elemvolume(node,elem,option) % % vol=elemvolume(node,elem,option) % % calculate the volume for a list of simplexes % % author: Qianqian Fang, <q.fang at neu.edu> % date: 2007/11/21 % % input: % node: node coordinates % elem: element table of a mesh % option: if option='signed', the volume is the raw determinant, % else, the results will be the absolute values % % output: % vol: volume values for all elements % % -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net) % if(size(elem,2)==size(node,2)) enum=size(elem,1); vol=zeros(enum,1); acol=ones(3,1); for i=1:enum e1=det([node(elem(i,:),2),node(elem(i,:),3),acol]); e2=det([node(elem(i,:),3),node(elem(i,:),1),acol]); e3=det([node(elem(i,:),1),node(elem(i,:),2),acol]); vol(i)=sqrt(e1*e1+e2*e2+e3*e3)/2; end return; end dim=size(elem,2); enum=size(elem,1); vol=zeros(enum,1); for i=1:enum detmat=[node(elem(i,:),:)';ones(1,dim)]; vol(i)=det(detmat); end if(nargin==3 && strcmp(option,'signed')) vol=vol/prod(1:size(node,2)); else vol=abs(vol)/prod(1:size(node,2)); end
Industry: Federal contractor / consulting firm. Founded in 2005, H2 Performance Consulting's focus is on improving business and technology performance for our clients. Our professionals have a sterling reputation as experts in IT project, program and portfolio management with substantial experience in technology solutions, performance, communications, change, training and acquisitions consulting, We partner with clients in all sectors and regions to identify their highest-value opportunities, address their most critical challenges, and transform their businesses. Our consultants hold a variety of industry certifications and many have advanced degrees. This coupled with significant industry consulting and military experience, culminates into a powerhouse of consulting delivery capability readily available to our clients. HPC2 is a small women-owned business based in Pensacola, FL and holds 8(a) disadvantaged SBA designation. To fill positions: Any available positions posted on our website. Additional information: Friendly working environment alongside many other veterans from all the Armed Forces.
Formal statement is: lemma contractible_Times: fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set" assumes S: "contractible S" and T: "contractible T" shows "contractible (S \<times> T)" Informal statement is: If $S$ and $T$ are contractible sets, then $S \times T$ is contractible.
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, [email protected] * Thu, Aug 4, 2016 */ /*! * \file smooth.c * \brief smoothing functions using FFT provided by GSL. * * References: Press et al., Numerical Recipes, Chapter 13.1. * GSL documents */ ///////////////THIS FILE IS DEPRECATED/////////////////////////// #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <mpi.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include "brains.h" int nd_fft; double *resp, *data_fft; double *resp_cmp, *data_fft_cmp, *data_fft_inverse; gsl_fft_real_wavetable * real_data, *real_resp; gsl_fft_complex_wavetable * cmp_data; gsl_fft_real_workspace * work_data, *work_resp; gsl_fft_complex_workspace * work_cmp; /*! * This function initiates workspace for FFT. */ void smooth_init(int nv, const double *transv) { //nd_fft = parset.n_vel_recon>=n_vel_data? parset.n_vel_recon : n_vel_data; nd_fft = nv; //printf("%d\n", nd_fft); real_data = gsl_fft_real_wavetable_alloc (nd_fft); real_resp = gsl_fft_real_wavetable_alloc (nd_fft); cmp_data = gsl_fft_complex_wavetable_alloc (nd_fft); work_data = gsl_fft_real_workspace_alloc (nd_fft); work_resp = gsl_fft_real_workspace_alloc (nd_fft); work_cmp = gsl_fft_complex_workspace_alloc (nd_fft); resp = malloc(nd_fft * sizeof(double)); data_fft = malloc(nd_fft * sizeof(double)); resp_cmp = malloc(nd_fft * 2 * sizeof(double)); data_fft_cmp = malloc(nd_fft *2 * sizeof(double)); data_fft_inverse = malloc(nd_fft *2 * sizeof(double)); // initialize response and its fft. int i; double sigV, dV, tot; sigV = parset.InstRes / VelUnit; dV = transv[1] - transv[0]; /* setup response, whose negective-time part is wrapped around and stored at the right hand*/ tot = 0.0; for (i = 0; i<nd_fft/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*(i*dV)*(i*dV)/sigV/sigV); tot += resp[i]; } for (i = nd_fft-1; i>= nd_fft/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV); tot += resp[i]; } /* normalize response */ for(i=0; i<nd_fft; i++) { //resp[i] /= (tot * dV); resp[i] /= (tot); } /* FFT of response */ gsl_fft_real_transform(resp, 1, nd_fft, real_resp, work_resp); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, nd_fft); } /*! * This function finalizes FFT. */ void smooth_end() { gsl_fft_real_wavetable_free(real_data); gsl_fft_real_wavetable_free(real_resp); gsl_fft_complex_wavetable_free(cmp_data); gsl_fft_real_workspace_free(work_data); gsl_fft_real_workspace_free(work_resp); gsl_fft_complex_workspace_free(work_cmp); free(resp); free(data_fft); free(resp_cmp); free(data_fft_cmp); free(data_fft_inverse); } /*! * This function performs FFT-smoothing to 2d line. */ void line_gaussian_smooth_2D_FFT(const double *transv, double *fl2d, int nl, int nv) { int i, j; double dV; dV = transv[1] - transv[0]; for(j=0; j<nl; j++) { memcpy(data_fft, &fl2d[j*nv], nv*sizeof(double)); /* FFT of line */ gsl_fft_real_transform(data_fft, 1, nd_fft, real_data, work_data); gsl_fft_halfcomplex_unpack(data_fft, data_fft_cmp, 1, nd_fft); /* complex multiply and inverse FFT */ for(i=0; i<nd_fft; i++) { data_fft_inverse[i*2] = data_fft_cmp[i*2]*resp_cmp[i*2] - data_fft_cmp[i*2+1]*resp_cmp[i*2+1]; data_fft_inverse[i*2+1] = data_fft_cmp[i*2]*resp_cmp[i*2+1] + data_fft_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(data_fft_inverse, 1, nd_fft, cmp_data, work_cmp); for(i=0; i<nv; i++) { /* take into account the velocity grid width */ //fl2d[j*nv + i] = data_fft_inverse[i*2] * dV; fl2d[j*nv + i] = data_fft_inverse[i*2]; } } return; } /*! * test smoothing function, assumed line profile. */ void line_gaussian_smooth_2D_FFT_test(const double *transv, double *fl2d, int nl, int nv) { int i, j; double sigV, dV, tot; sigV = parset.InstRes / VelUnit; dV = transv[1] - transv[0]; tot = 0.0; for (i = 0; i<nd_fft/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*(i*dV)*(i*dV)/sigV/sigV); tot += resp[i]; } for (i = nd_fft-1; i>= nd_fft/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/sigV * exp(-0.5*((i-nd_fft)*dV)*((i-nd_fft)*dV)/sigV/sigV); tot += resp[i]; } for(i=0; i<nd_fft; i++) { resp[i] /= (tot * dV); } gsl_fft_real_transform(resp, 1, nd_fft, real_resp, work_resp); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, nd_fft); for(j=0; j<nl; j++) { //memcpy(data_fft, &fl2d[j*nv], nv*sizeof(double)); for(i=0; i<nv; i++) { data_fft[i] = exp( - 0.5 * pow(transv[i]/(1500.0/VelUnit), 2.0)); } gsl_fft_real_transform(data_fft, 1, nd_fft, real_data, work_data); gsl_fft_halfcomplex_unpack(data_fft, data_fft_cmp, 1, nd_fft); for(i=0; i<nd_fft; i++) { data_fft_inverse[i*2] = data_fft_cmp[i*2]*resp_cmp[i*2] - data_fft_cmp[i*2+1]*resp_cmp[i*2+1]; data_fft_inverse[i*2+1] = data_fft_cmp[i*2]*resp_cmp[i*2+1] + data_fft_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(data_fft_inverse, 1, nd_fft, cmp_data, work_cmp); for(i=0; i<nv; i++) { // take into account the velocity grid width fl2d[j*nv + i] = data_fft_inverse[i*2] * dV; } } return; } /*! * convolution test. */ void smooth_test() { int i, n = 205; double data[n], resp[n]; double data_cmp[n*2], resp_cmp[n*2]; double ans[n*2]; gsl_fft_real_wavetable * real, *real_resp; gsl_fft_complex_wavetable * hc; gsl_fft_real_workspace * work, *work_resp; gsl_fft_complex_workspace * work_cmp; for (i = 0; i < n; i++) { data[i] = 1.0/sqrt(2.0*M_PI)/6.0 * exp(-0.5*(i-50.0)*(i-50.0)/6.0/6.0); } for (i = 0; i < n/2; i++) { resp[i] = 1.0/sqrt(2.0*M_PI)/10.0 * exp(-0.5*(i-0.0)*(i-0.0)/10.0/10.0); } for (i = n-1; i >= n/2; i--) { resp[i] = 1.0/sqrt(2.0*M_PI)/10.0 * exp(-0.5*(i-n)*(i-n)/10.0/10.0); } for (i = 0; i < n; i++) { printf ("%d: %e\n", i, data[i]); } printf ("\n"); work = gsl_fft_real_workspace_alloc (n); real = gsl_fft_real_wavetable_alloc (n); work_resp = gsl_fft_real_workspace_alloc (n); real_resp = gsl_fft_real_wavetable_alloc (n); work_cmp = gsl_fft_complex_workspace_alloc(n); hc = gsl_fft_complex_wavetable_alloc (n); gsl_fft_real_transform (data, 1, n, real, work); gsl_fft_real_transform (resp, 1, n, real_resp, work_resp); gsl_fft_halfcomplex_unpack(data, data_cmp, 1, n); gsl_fft_halfcomplex_unpack(resp, resp_cmp, 1, n); for(i=0; i<n; i++) { ans[i*2] = data_cmp[i*2]*resp_cmp[i*2] - data_cmp[i*2+1]*resp_cmp[i*2+1]; ans[i*2+1] = data_cmp[i*2]*resp_cmp[i*2+1] + data_cmp[i*2+1]*resp_cmp[i*2]; } gsl_fft_complex_inverse(ans, 1, n, hc, work_cmp); for (i = 0; i < n; i++) { printf ("%d: %e %e\n", i, ans[i*2], ans[i*2+1]); } gsl_fft_real_wavetable_free (real); gsl_fft_real_wavetable_free (real_resp); gsl_fft_real_workspace_free (work); gsl_fft_real_workspace_free (work_resp); gsl_fft_complex_wavetable_free (hc); gsl_fft_complex_workspace_free(work_cmp); return; }
!> Interface handling both fluid and solid equation of state !! !! \author MH, 2016-06. module vls use thermopack_constants use thermopack_var, only: nc, nph use solideos use eos ! implicit none save ! !> Thermo state, used for debugging type state integer :: nd real :: t,p real, allocatable :: Z(:),BETA(:),XX(:,:) integer, allocatable :: phaseVec(:) contains procedure :: set_state procedure :: get_state procedure :: get_state_no_z procedure :: print_state end type state ! private public :: vlsThermo, vlsSpecificVolume, vlsEnthalpy, vlsEntropy public :: mpSpecificVolume, mpEnthalpy, mpEntropy public :: specificEnthalpyVLWS, specificVolumeVLWS, specificEntropyVLWS public :: inversePhaseMappingVLWS public :: printCurrentPhases public :: state ! contains !---------------------------------------------------------------------- !> Calculate fugasity coefficient and differentials given composition, !> temperature and pressure. Interface for vapour, liquid and solid !> !> \author MH, 2016-06 !---------------------------------------------------------------------- subroutine vlsThermo(t,p,z,phase,lnfug,lnfugt,lnfugp,lnfugx,ophase,metaExtremum) use eos, only: thermo use solideos, only: solid_thermo use thermopack_constants, only: SOLIDPH ! Transferred variables integer, intent(in) :: phase !< Phase identifyer integer, optional, intent(out) :: ophase !< Phase identifyer for MINGIBBSPH real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure real, dimension(1:nc), intent(in) :: z !< Compozition real, dimension(1:nc), intent(out) :: lnfug !< Logarithm of fugasity coefficient real, optional, dimension(1:nc), intent(out) :: lnfugt !< 1/K - Logarithm of fugasity coefficient differential wrpt. temperature real, optional, dimension(1:nc), intent(out) :: lnfugp !< 1/Pa - Logarithm of fugasity coefficient differential wrpt. pressure real, optional, dimension(1:nc,1:nc), intent(out) :: lnfugx !< Logarithm of fugasity coefficient differential wrpt. mole numbers logical, optional, intent(in) :: metaExtremum ! Locals integer :: i integer, dimension(1) :: imax real :: lnfugs,lnfugts,lnfugps if (phase == SOLIDPH) then imax = maxloc(z) i = imax(1) call solid_thermo(t,p,z,lnfugs,lnfugts,lnfugps) lnfug = 0.0 lnfug(i) = lnfugs if (present(lnfugt)) then lnfugt = 0.0 lnfugt(i) = lnfugts endif if (present(lnfugp)) then lnfugp = 0.0 lnfugp(i) = lnfugps endif if (present(lnfugx)) then lnfugx = 0.0 endif if (present(ophase)) then ophase = SOLIDPH endif else call thermo(t,p,z,phase,lnfug,lnfugt,lnfugp,lnfugx,ophase,metaExtremum) endif end subroutine vlsThermo !---------------------------------------------------------------------- !> Calculate single-phase specific volume given composition, temperature and !> pressure for fluid and solid phases !> !> \author MH, 2016-06 !---------------------------------------------------------------------- subroutine vlsSpecificVolume(t,p,z,phase,v,dvdt,dvdp,dvdx) use eos, only: specificVolume use solideos, only: solid_specificVolume use thermopack_constants, only: SOLIDPH ! Transferred variables integer, intent(in) :: phase !< Phase identifyer real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure real, dimension(1:nc), intent(in) :: z !< Compozition real, intent(out) :: v !< m3/mol - Specific volume real, optional, intent(out) :: dvdt !< m3/mol/K - Specific volume differential wrpt. temperature real, optional, intent(out) :: dvdp !< m3/mol/Pa - Specific volume differential wrpt. pressure real, optional, dimension(1:nc), intent(out) :: dvdx !< m3/mol - Specific volume differential wrpt. mole numbers ! Locals integer :: i integer, dimension(1) :: imax if (phase == SOLIDPH) then call solid_specificVolume(t,p,z,v,dvdt,dvdp) if (present(dvdx)) then imax = maxloc(z) i = imax(1) dvdx = 0.0 dvdx(i) = v endif else call specificVolume(t,p,z,phase,v,dvdt,dvdp,dvdx) endif end subroutine vlsSpecificVolume !---------------------------------------------------------------------- !> Calculate single-phase specific enthalpy given composition, temperature and !> pressure for fluid and solid phases !> !> \author MH, 2016-06 !---------------------------------------------------------------------- subroutine vlsEnthalpy(t,p,z,phase,h,dhdt,dhdp,dhdx) use eos, only: enthalpy use solideos, only: solid_enthalpy use thermopack_constants, only: SOLIDPH ! Transferred variables integer, intent(in) :: phase !< Phase identifyer real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure real, dimension(1:nc), intent(in) :: z !< Compozition real, intent(out) :: h !< J/mol - Specific enthalpy real, optional, intent(out) :: dhdt !< J/mol/K - Specific enthalpy differential wrpt. temperature real, optional, intent(out) :: dhdp !< J/mol/Pa - Specific enthalpy differential wrpt. pressure real, optional, dimension(1:nc), intent(out) :: dhdx !< J/mol - Specific enthalpy differential wrpt. mole numbers ! Locals integer :: i integer, dimension(1) :: imax if (phase == SOLIDPH) then call solid_enthalpy(t,p,z,h,dhdt,dhdp) if (present(dhdx)) then imax = maxloc(z) i = imax(1) dhdx = 0.0 dhdx(i) = h endif else call enthalpy(t,p,z,phase,h,dhdt,dhdp,dhdx) endif end subroutine vlsEnthalpy !---------------------------------------------------------------------- !> Calculate single-phase specific entropy given composition, temperature and !> pressure for fluid and solid phases !> !> \author MH, 2016-06 !---------------------------------------------------------------------- subroutine vlsEntropy(t,p,z,phase,s,dsdt,dsdp,dsdx) use eos, only: entropy use solideos, only: solid_entropy use thermopack_constants, only: SOLIDPH ! Transferred variables integer, intent(in) :: phase !< Phase identifyer real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure real, dimension(1:nc), intent(in) :: z !< Compozition real, intent(out) :: s !< J/mol/K - Specific entropy real, optional, intent(out) :: dsdt !< J/mol/K^2 - Specific entropy differential wrpt. temperature real, optional, intent(out) :: dsdp !< J/mol/K/Pa - Specific entropy differential wrpt. pressure real, optional, dimension(1:nc), intent(out) :: dsdx !< J/mol/K - Specific enthalpy differential wrpt. mole numbers ! Locals integer :: i integer, dimension(1) :: imax if (phase == SOLIDPH) then call solid_entropy(t,p,z,s,dsdt,dsdp) if (present(dsdx)) then imax = maxloc(z) i = imax(1) dsdx = 0.0 dsdx(i) = s endif else call entropy(t,p,z,phase,s,dsdt,dsdp,dsdx) endif end subroutine vlsEntropy !-------------------------------------------------------------------------- !> Calculate multi-phase entropy given composition, temperature and pressure !> Unit: J/mol/K !> !> \author MH, 2013-02 !-------------------------------------------------------------------------- function mpEntropy(nd,t,p,beta,xx,phase) result(s) use eos, only: entropy use thermopack_constants, only: SOLIDPH use solideos, only: solid_entropy implicit none ! Transferred variables integer, intent(in) :: nd !< Numper of phases real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure integer, dimension(nph) :: phase !< Phase identifyer real, intent(in), dimension(nph) :: beta !< Phase fractions real, intent(in), dimension(nph,nc) :: xx !< Composition real :: s !< J/mol/K - Specific entropy ! Locals integer :: i real :: hph s = 0.0 do i=1,nd if (phase(i) == SOLIDPH) then call solid_entropy(t,p,xx(i,:),hph) else call entropy(t,p,xx(i,:),phase(i),hph) endif s = s + beta(i)*hph enddo end function mpEntropy !-------------------------------------------------------------------------- !> Calculate multi-phase enthalpy given composition, temperature and pressure !> Unit: J/mol !> !> \author MH, 2013-02 !-------------------------------------------------------------------------- function mpEnthalpy(nd,t,p,beta,xx,phase) result(h) use eos, only: enthalpy use thermopack_constants, only: SOLIDPH use solideos, only: solid_enthalpy implicit none ! Transferred variables integer, intent(in) :: nd !< Numper of phases real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure integer, dimension(nph) :: phase !< Phase identifyer real, intent(in), dimension(nph) :: beta !< Phase fractions real, intent(in), dimension(nph,nc) :: xx !< Composition real :: h !< J/mol - Specifc enthalpy ! Locals integer :: i real :: hph h = 0.0 do i=1,nd if (phase(i) == SOLIDPH) then call solid_enthalpy(t,p,xx(i,:),hph) else call enthalpy(t,p,xx(i,:),phase(i),hph) endif h = h + beta(i)*hph enddo end function mpEnthalpy !-------------------------------------------------------------------------- !> Calculate multi-phase entropy given composition, temperature and pressure !> Unit: J/mol/K !> !> \author MH, 2013-02 !-------------------------------------------------------------------------- function mpSpecificVolume(nd,t,p,beta,xx,phase) result(v) use eos, only: specificVolume use thermopack_constants, only: SOLIDPH use solideos, only: solid_specificVolume implicit none ! Transferred variables integer, intent(in) :: nd !< Numper of phases real, intent(in) :: t !< K - Temperature real, intent(in) :: p !< Pa - Pressure integer, dimension(nph) :: phase !< Phase identifyer real, intent(in), dimension(nph) :: beta !< Phase fractions real, intent(in), dimension(nph,nc) :: xx !< Composition real :: v !< m3/mol - Specifc volume ! Locals integer :: i real :: vph v = 0.0 do i=1,nd if (phase(i) == SOLIDPH) then call solid_specificVolume(t,p,xx(i,:),vph) else call specificVolume(t,p,xx(i,:),phase(i),vph) endif v = v + beta(i)*vph enddo end function mpSpecificVolume subroutine inversePhaseMappingVLWS(z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,nd,BETA,XX,phaseVec) use numconstants, only: machine_prec ! Input: real, dimension(nc) :: z logical, intent(in) :: gasPresent, liquidPresent logical, intent(in) :: waterPresent, solidPresent real, intent(in) :: betaGas, betaLiquid, betaWater, betaSolid real, intent(in) :: X(nc), Y(nc), W(nc), Ws(nc) ! Output: integer, intent(out) :: nd !< Number of stabel phases found [-] real, dimension(nph), intent(out) :: BETA !< Phase molar fractions [mol/mol] real, dimension(nph,nc), intent(out) :: XX !< Phase molar compozition [mol/mol] integer, dimension(nph), intent(out) :: phaseVec !< Phase identifier. Not to be trused [-] ! Locals: integer :: i nd = 0 !ns = 0 if (gasPresent) then ! Add gas phase nd = nd + 1 BETA(nd) = betaGas if (BETA(nd) <= 0.0) then call stoperror("multiPhaseFlashUV: Gas phase flagged as present, but not actually present") endif XX(nd,:) = Y phaseVec(nd) = VAPPH endif if (liquidPresent) then ! Add liquid phase nd = nd + 1 BETA(nd) = betaLiquid if (BETA(nd) <= 0.0) then call stoperror("multiPhaseFlashUV: Liquid phase flagged as present, but not actually present") endif XX(nd,:) = X phaseVec(nd) = LIQPH endif if (waterPresent) then ! Add water phase nd = nd + 1 BETA(nd) = betaWater if (BETA(nd) <= 0.0) then call stoperror("multiPhaseFlashUV: Water phase flagged as present, but not actually present") endif XX(nd,:) = W phaseVec(nd) = LIQPH endif if (solidPresent) then ! Add solid phase nd = nd + 1 !ns = ns + 1 BETA(nd) = betaSolid if (BETA(nd) <= 0.0) then call stoperror("multiPhaseFlashUV: Solid phase flagged as present, but not actually present") endif XX(nd,:) = Ws phaseVec(nd) = SOLIDPH endif ! Test input data for consistency if (abs(sum(BETA(1:nd)) - 1.0) > machine_prec*100.0) then call printCurrentPhases(nd,0.0,0.0,Z,XX,BETA,phaseVec) call stoperror("inversePhaseMappingVLWS: Phase fractions don't sum to one.") endif do i=1,nc if (abs(sum(BETA(1:nd)*XX(1:nd,i)) - Z(i)) > Z(i)*machine_prec*1.0e6) then call printCurrentPhases(nd,0.0,0.0,Z,XX,BETA,phaseVec) call stoperror("inversePhaseMappingVLWS: Mass balance not met.") endif enddo end subroutine inversePhaseMappingVLWS !------------------------------------------------------------------------ !> Get the specific enthalpy from VLWS variables. !> Wrapper for mpEnthalpy !> !> \author HLS, 2018-08 !------------------------------------------------------------------------- subroutine specificEnthalpyVLWS(nc,nph,T,P,z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,h) implicit none ! Input: integer, intent(in) :: nc !< Number of components integer, intent(in) :: nph !< Number of possible phases real, intent(in) :: T !< Temperature [K] real, intent(in) :: P !< Pressure [Pa] real, dimension(nc), intent(in) :: z !< Overall molar compozition [-] real, intent(in) :: betaGas !< Gas phase molar fraction [-] real, dimension(nc), intent(in) :: Y !< Gas phase molar composition [-] logical, intent(in) :: gasPresent !< Is gas phase detected? real, intent(in) :: betaLiquid !< Liquid phase molar fraction [-] real, dimension(nc), intent(in) :: X !< Liquid phase molar composition [-] logical, intent(in) :: liquidPresent !< Is liquid phase detected? real, intent(in) :: betaWater !< Water phase molar fraction [-] real, dimension(nc), intent(in) :: W !< Water phase molar composition [-] logical, intent(in) :: waterPresent !< Is water phase detected? real, intent(in) :: betaSolid !< Solid phase molar fraction [-] real, dimension(nc), intent(in) :: Ws !< Solid phase molar composition [-] logical, intent(in) :: solidPresent !< Is solid phase detected? ! Output: real, intent(out) :: h !< Enthalpy [J/mol] ! Locals: real, dimension(nph) :: beta !< Phase molar fractions [mol/mol] real, dimension(nph,nc) :: xx !< Phase molar composition [mol/mol] integer*4, dimension(nph) :: phaseVec !< Phase identifier [-] integer :: nd !< Number of phases [-] call inversePhaseMappingVLWS(z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,nd,beta,xx,phasevec) h = mpEnthalpy(nd,t,p,beta,xx,phasevec) end subroutine specificEnthalpyVLWS !------------------------------------------------------------------------ !> Get the specific enthalpy from VLWS variables. !> Wrapper for mpSpecificVolume !> !> \author HLS, 2018-08 !------------------------------------------------------------------------- subroutine specificVolumeVLWS(nc,nph,T,P,z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,v) implicit none ! Input: integer, intent(in) :: nc !< Number of components integer, intent(in) :: nph !< Number of possible phases real, intent(in) :: T !< Temperature [K] real, intent(in) :: P !< Pressure [Pa] real, dimension(nc), intent(in) :: z !< Overall molar compozition [-] real, intent(in) :: betaGas !< Gas phase molar fraction [-] real, dimension(nc), intent(in) :: Y !< Gas phase molar composition [-] logical, intent(in) :: gasPresent !< Is gas phase detected? real, intent(in) :: betaLiquid !< Liquid phase molar fraction [-] real, dimension(nc), intent(in) :: X !< Liquid phase molar composition [-] logical, intent(in) :: liquidPresent !< Is liquid phase detected? real, intent(in) :: betaWater !< Water phase molar fraction [-] real, dimension(nc), intent(in) :: W !< Water phase molar composition [-] logical, intent(in) :: waterPresent !< Is water phase detected? real, intent(in) :: betaSolid !< Solid phase molar fraction [-] real, dimension(nc), intent(in) :: Ws !< Solid phase molar composition [-] logical, intent(in) :: solidPresent !< Is solid phase detected? ! Output: real, intent(out) :: v !< Specific volume [m^3/mol] ! Locals: real, dimension(nph) :: beta !< Phase molar fractions [mol/mol] real, dimension(nph,nc) :: xx !< Phase molar composition [mol/mol] integer*4, dimension(nph) :: phaseVec !< Phase identifier [-] integer :: nd !< Number of phases [-] call inversePhaseMappingVLWS(z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,nd,beta,xx,phasevec) v = mpSpecificVolume(nd,t,p,beta,xx,phasevec) end subroutine specificVolumeVLWS !------------------------------------------------------------------------ !> Get the entropy from VLWS variables. !> Wrapper for mpEntropy !> !> \author HLS, 2018-08 !------------------------------------------------------------------------- subroutine specificEntropyVLWS(nc,nph,T,P,z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,s) implicit none ! Input: integer, intent(in) :: nc !< Number of components integer, intent(in) :: nph !< Number of possible phases real, intent(in) :: T !< Temperature [K] real, intent(in) :: P !< Pressure [Pa] real, dimension(nc), intent(in) :: z !< Overall molar compozition [-] real, intent(in) :: betaGas !< Gas phase molar fraction [-] real, dimension(nc), intent(in) :: Y !< Gas phase molar composition [-] logical, intent(in) :: gasPresent !< Is gas phase detected? real, intent(in) :: betaLiquid !< Liquid phase molar fraction [-] real, dimension(nc), intent(in) :: X !< Liquid phase molar composition [-] logical, intent(in) :: liquidPresent !< Is liquid phase detected? real, intent(in) :: betaWater !< Water phase molar fraction [-] real, dimension(nc), intent(in) :: W !< Water phase molar composition [-] logical, intent(in) :: waterPresent !< Is water phase detected? real, intent(in) :: betaSolid !< Solid phase molar fraction [-] real, dimension(nc), intent(in) :: Ws !< Solid phase molar composition [-] logical, intent(in) :: solidPresent !< Is solid phase detected? ! Output: real, intent(out) :: s !< Specific volume [J/(mol K)] ! Locals: real, dimension(nph) :: beta !< Phase molar fractions [mol/mol] real, dimension(nph,nc) :: xx !< Phase molar composition [mol/mol] integer*4, dimension(nph) :: phaseVec !< Phase identifier [-] integer :: nd !< Number of phases [-] call inversePhaseMappingVLWS(z,betaGas,Y,gasPresent,& betaLiquid,X,liquidPresent,betaWater,W,waterPresent,& betaSolid,Ws,solidPresent,nd,beta,xx,phasevec) s = mpEntropy(nd,t,p,beta,xx,phasevec) end subroutine specificEntropyVLWS !------------------------------------------------------------------------- !> Print info about current phases !> Used for debugging !> \author MH, 2018-04 !------------------------------------------------------------------------- subroutine printCurrentPhases(nd,T,P,Z,XX,BETA,phaseVec) implicit none real, intent(in) :: T,P real, dimension(nc), intent(in) :: Z real, dimension(nph,nc), intent(in) :: XX real, dimension(nph), intent(in) :: BETA integer, dimension(nph), intent(in) :: phaseVec integer, intent(in) :: nd !< Number of phases ! Locals character(len=10) :: phaseName integer :: i,j real :: lnFug(nc) print *,'' write(*,'(A,es25.16e3)') 'Current temperature: ',T write(*,'(A,es25.16e3)') 'Current pressure:',P write(*,'(A)') 'Overall composition:' do i=1,nc write(*,'(es25.16e3)') Z(i) enddo print *,'Current phases:' do i=1,nd call phaseIntToName(phaseVec(i),phaseName) print *,'Phase: ', trim(phaseName) print *,'beta: ',BETA(i) print *,'Mole weight: ',moleWeight(XX(i,:)) print *,'X: ',XX(i,:) if (T > 0.0 .and. P > 0.0) then call vlsThermo(T,P,XX(i,:),phaseVec(i),lnFug) do j=1,nc if (XX(i,j) > 0.0) then lnFug(j) = lnFug(j) + log(XX(i,j)) else lnFug(j) = 0.0 endif enddo print *,'lnFug + ln(X): ',lnFug endif enddo print *,'' end subroutine printCurrentPhases subroutine set_state(st,nd,t,p,Z,BETA,XX,phaseVec) class(state), intent(inout) :: st integer, intent(in) :: nd !< Number of stabel phases found [-] real, dimension(:), intent(in) :: BETA !< Phase molar fractions [mol/mol] real, dimension(:,:), intent(in) :: XX !< Phase molar compozition [mol/mol] real, dimension(:), intent(in) :: Z !< Overall molar compozition [mol/mol] real, intent(in) :: t !< Temperature [K] real, intent(in) :: p !< Specified pressure [Pa] integer, dimension(:), intent(in) :: phaseVec !< Phase identifier. Not to be trused [-] ! Locals integer :: n, np, istat logical :: do_alloc n = size(z) np = size(BETA) do_alloc = .false. if (allocated(st%z)) then if (size(st%z) /= n) then do_alloc = .true. deallocate(st%z,st%BETA,st%XX,st%phaseVec,stat=istat) if (istat /= 0) call stoperror("Nota able to allocate state variables") endif endif if (do_alloc) then allocate(st%z(n),st%BETA(np),st%XX(np,n),st%phaseVec(np),stat=istat) if (istat /= 0) call stoperror("Nota able to allocate state variables") endif st%nd = nd st%t = t st%p = p st%Z = Z st%BETA = BETA st%XX = XX st%phaseVec = phaseVec end subroutine set_state subroutine get_state(st,nd,t,p,Z,BETA,XX,phaseVec) class(state), intent(in) :: st integer, intent(out) :: nd !< Number of stabel phases found [-] real, dimension(:), intent(out) :: BETA !< Phase molar fractions [mol/mol] real, dimension(:,:), intent(out) :: XX !< Phase molar compozition [mol/mol] real, dimension(:), intent(out) :: Z !< Overall molar compozition [mol/mol] real, intent(out) :: t !< Temperature [K] real, intent(out) :: p !< Specified pressure [Pa] integer, dimension(:), intent(out) :: phaseVec !< Phase identifier. Not to be trused [-] ! Locals integer :: n, np n = size(z) np = size(BETA) if (allocated(st%z)) then if (size(st%z) /= n) then call stoperror("State not initialized") endif endif nd = st%nd t = st%t p = st%p Z = st%Z BETA = st%BETA XX = st%XX phaseVec = st%phaseVec end subroutine get_state subroutine get_state_no_z(st,nd,t,p,BETA,XX,phaseVec) class(state), intent(in) :: st integer, intent(out) :: nd !< Number of stabel phases found [-] real, dimension(:), intent(out) :: BETA !< Phase molar fractions [mol/mol] real, dimension(:,:), intent(out) :: XX !< Phase molar compozition [mol/mol] real, intent(out) :: t !< Temperature [K] real, intent(out) :: p !< Specified pressure [Pa] integer, dimension(:), intent(out) :: phaseVec !< Phase identifier. Not to be trused [-] ! Locals real, dimension(size(XX,dim=2)) :: Z !< Overall molar compozition [mol/mol] call st%get_state(nd,t,p,Z,BETA,XX,phaseVec) end subroutine get_state_no_z subroutine print_state(st) class(state), intent(in) :: st call printCurrentPhases(st%nd,st%T,st%P,st%Z,st%XX,st%BETA,st%phaseVec) end subroutine print_state end module vls
Formal statement is: lemma cball_min_Int: "cball a (min r s) = cball a r \<inter> cball a s" Informal statement is: The intersection of two closed balls is the smallest closed ball that contains both of them.
This is some documentation. More documentation. > module Main > > data Cat = Cas | Luna | Sherlock > > f : (cat: Cat) -> String > > getName : (cat: Cat) -> String > getName Cas = "Cas" > getName Luna = "Luna" An intermission. > plusTwo : (n: Nat) -> Nat > plusTwo n = plus 2 n > > g : (n: Nat) -> (b: Bool) -> String > g n b = ?g_rhs > > n : Nat > n = ?n_rhs Some closing thoughts.
[STATEMENT] lemma poly_limit_aux: fixes p :: "real poly" defines "n \<equiv> degree p" shows "((\<lambda>x. poly p x / x ^ n) \<longlongrightarrow> coeff p n) at_infinity" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<lambda>x. poly p x / x ^ n) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] proof (subst filterlim_cong, rule refl, rule refl) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<forall>\<^sub>F x in at_infinity. poly p x / x ^ n = ?g x 2. (?g \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] show "eventually (\<lambda>x. poly p x / x^n = (\<Sum>i\<le>n. coeff p i / x^(n-i))) at_infinity" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>\<^sub>F x in at_infinity. poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] proof (rule eventually_mono) [PROOF STATE] proof (state) goal (2 subgoals): 1. eventually ?P at_infinity 2. \<And>x. ?P x \<Longrightarrow> poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] show "eventually (\<lambda>x::real. x \<noteq> 0) at_infinity" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>\<^sub>F x in at_infinity. x \<noteq> 0 [PROOF STEP] by (simp add: eventually_at_infinity, rule exI[of _ 1], auto) [PROOF STATE] proof (state) this: \<forall>\<^sub>F x in at_infinity. x \<noteq> 0 goal (1 subgoal): 1. \<And>x. x \<noteq> 0 \<Longrightarrow> poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] fix x :: real [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x. x \<noteq> 0 \<Longrightarrow> poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] assume [simp]: "x \<noteq> 0" [PROOF STATE] proof (state) this: x \<noteq> 0 goal (1 subgoal): 1. \<And>x. x \<noteq> 0 \<Longrightarrow> poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] show "poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) [PROOF STEP] by (simp add: n_def sum_divide_distrib power_diff poly_altdef) [PROOF STATE] proof (state) this: poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<forall>\<^sub>F x in at_infinity. poly p x / x ^ n = (\<Sum>i\<le>n. coeff p i / x ^ (n - i)) goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] let ?a = "\<lambda>i. if i = n then coeff p n else 0" [PROOF STATE] proof (state) goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] have "\<forall>i\<in>{..n}. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> ?a i) at_infinity" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>i\<in>{..n}. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] proof [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i. i \<in> {..n} \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] fix i [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i. i \<in> {..n} \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] assume "i \<in> {..n}" [PROOF STATE] proof (state) this: i \<in> {..n} goal (1 subgoal): 1. \<And>i. i \<in> {..n} \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] hence "i \<le> n" [PROOF STATE] proof (prove) using this: i \<in> {..n} goal (1 subgoal): 1. i \<le> n [PROOF STEP] by simp [PROOF STATE] proof (state) this: i \<le> n goal (1 subgoal): 1. \<And>i. i \<in> {..n} \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] show "((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> ?a i) at_infinity" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] proof (cases "i = n") [PROOF STATE] proof (state) goal (2 subgoals): 1. i = n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity 2. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] case True [PROOF STATE] proof (state) this: i = n goal (2 subgoals): 1. i = n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity 2. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: i = n goal (1 subgoal): 1. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] by (intro tendstoI, subst eventually_at_infinity, intro exI[of _ 1], simp add: dist_real_def) [PROOF STATE] proof (state) this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] case False [PROOF STATE] proof (state) this: i \<noteq> n goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] hence "n - i > 0" [PROOF STATE] proof (prove) using this: i \<noteq> n goal (1 subgoal): 1. 0 < n - i [PROOF STEP] using \<open>i \<le> n\<close> [PROOF STATE] proof (prove) using this: i \<noteq> n i \<le> n goal (1 subgoal): 1. 0 < n - i [PROOF STEP] by simp [PROOF STATE] proof (state) this: 0 < n - i goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] from tendsto_inverse_0 and divide_real_def[of 1] [PROOF STATE] proof (chain) picking this: (inverse \<longlongrightarrow> (0::?'a)) at_infinity 1 / ?y = 1 * inverse ?y [PROOF STEP] have "((\<lambda>x. 1 / x :: real) \<longlongrightarrow> 0) at_infinity" [PROOF STATE] proof (prove) using this: (inverse \<longlongrightarrow> (0::?'a)) at_infinity 1 / ?y = 1 * inverse ?y goal (1 subgoal): 1. ((/) 1 \<longlongrightarrow> 0) at_infinity [PROOF STEP] by simp [PROOF STATE] proof (state) this: ((/) 1 \<longlongrightarrow> 0) at_infinity goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] from tendsto_power[OF this, of "n - i"] [PROOF STATE] proof (chain) picking this: ((\<lambda>x. (1 / x) ^ (n - i)) \<longlongrightarrow> 0 ^ (n - i)) at_infinity [PROOF STEP] have "((\<lambda>x::real. 1 / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity" [PROOF STATE] proof (prove) using this: ((\<lambda>x. (1 / x) ^ (n - i)) \<longlongrightarrow> 0 ^ (n - i)) at_infinity goal (1 subgoal): 1. ((\<lambda>x. 1 / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity [PROOF STEP] using \<open>n - i > 0\<close> [PROOF STATE] proof (prove) using this: ((\<lambda>x. (1 / x) ^ (n - i)) \<longlongrightarrow> 0 ^ (n - i)) at_infinity 0 < n - i goal (1 subgoal): 1. ((\<lambda>x. 1 / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity [PROOF STEP] by (simp add: power_0_left power_one_over) [PROOF STATE] proof (state) this: ((\<lambda>x. 1 / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] from tendsto_mult_right_zero[OF this, of "coeff p i"] [PROOF STATE] proof (chain) picking this: ((\<lambda>x. coeff p i * (1 / x ^ (n - i))) \<longlongrightarrow> 0) at_infinity [PROOF STEP] have "((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity" [PROOF STATE] proof (prove) using this: ((\<lambda>x. coeff p i * (1 / x ^ (n - i))) \<longlongrightarrow> 0) at_infinity goal (1 subgoal): 1. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity [PROOF STEP] by (simp add: field_simps) [PROOF STATE] proof (state) this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity goal (1 subgoal): 1. i \<noteq> n \<Longrightarrow> ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity goal (1 subgoal): 1. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] using False [PROOF STATE] proof (prove) using this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> 0) at_infinity i \<noteq> n goal (1 subgoal): 1. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity [PROOF STEP] by simp [PROOF STATE] proof (state) this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<forall>i\<in>{..n}. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] hence "((\<lambda>x. \<Sum>i\<le>n. coeff p i / x^(n-i)) \<longlongrightarrow> (\<Sum>i\<le>n. ?a i)) at_infinity" [PROOF STATE] proof (prove) using this: \<forall>i\<in>{..n}. ((\<lambda>x. coeff p i / x ^ (n - i)) \<longlongrightarrow> (if i = n then coeff p n else 0)) at_infinity goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> (\<Sum>i\<le>n. if i = n then coeff p n else 0)) at_infinity [PROOF STEP] by (force intro!: tendsto_sum) [PROOF STATE] proof (state) this: ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> (\<Sum>i\<le>n. if i = n then coeff p n else 0)) at_infinity goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] also [PROOF STATE] proof (state) this: ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> (\<Sum>i\<le>n. if i = n then coeff p n else 0)) at_infinity goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] have "(\<Sum>i\<le>n. ?a i) = coeff p n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>i\<le>n. if i = n then coeff p n else 0) = coeff p n [PROOF STEP] by (subst sum.delta, simp_all) [PROOF STATE] proof (state) this: (\<Sum>i\<le>n. if i = n then coeff p n else 0) = coeff p n goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] show "((\<lambda>x. \<Sum>i\<le>n. coeff p i / x^(n-i)) \<longlongrightarrow> coeff p n) at_infinity" [PROOF STATE] proof (prove) using this: ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity goal (1 subgoal): 1. ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity [PROOF STEP] . [PROOF STATE] proof (state) this: ((\<lambda>x. \<Sum>i\<le>n. coeff p i / x ^ (n - i)) \<longlongrightarrow> coeff p n) at_infinity goal: No subgoals! [PROOF STEP] qed
You probably have a lot of feelings about the holiday season. Maybe you love Christmas and all that comes with it, or maybe you celebrate Hanukkah and look forward to it every year. No matter what holiday you celebrate or how much you look forward to it, the truth is that the holiday season can be a time of stress and anxiety. Whether you’re throwing your first holiday dinner or your twentieth, there are a few ways to survive the holidays while still having a great time celebrating with your friends and relatives. Perhaps the most important way to survive the holidays is to create a plan. What meal will you prepare for your celebration? What ingredients will you need? Who do you need to buy presents for? Who is allergic to peanuts? Which relatives don’t like dogs? Write down everything you need to do and know in order to have a successful celebration. The more organized you are, the easier it will be to plan the perfect holiday dinner. Consider investing in a new planner or calendar solely to arrange information for your party. If you need to shop, don’t wait until the day before your holiday dinner to do it. If you wait until the last minute to shop, you run the risk of not being able to find everything you need. Buy as many ingredients, presents, and decorations as soon as reasonably possible. This will save you stress and anxiety in the days leading up to the holiday since you’ll already having your shopping out of the way. Worried Aunt Mildred is going to start a political argument with Uncle David again? Avoid family conflict and survive the holidays by arranging neutral activities that everyone can enjoy. You could have board games available for everyone to play, plan a scavenger hunt, or even suggest a rowdy game of charades. No matter what your family likes to do, planning at least a few activities will give everyone something to look forward to once the meal is over. Planned activities will also reduce the chances of family arguments since your relatives will be too busy having fun to fight. Being a party planner is a huge responsibility, but you don’t have to shoulder the burden alone. Don’t be afraid or embarrassed to ask for help when you need it. Consider asking a few relatives to help you wash the dishes after the meal, requesting that each guest bring a side dish, or even having the kids help clean up the wrapping paper. There is nothing wrong with asking other people to help. Most of your friends and relatives will be glad to pitch it and help you out. If you find yourself in the midst of the celebration and you feel overwhelmed, remember to take a moment for yourself and use healthy coping mechanisms. There is nothing wrong with stepping out for a minute and taking a deep breath, listening to a relaxing song, or even resting for a few minutes. Remind yourself that this is a special event and try to think positive thoughts. Instead of focusing on any negativity during the celebration, try to remember all of the great things you experienced during the party. Celebrating with your family should be a wonderful event, but some anxiety is normal. Take a few minutes for yourself and then rejoin the group. Chances are that you’ll feel more rested, relaxed, and ready to have fun. Morningside Recovery is a leader in the fields of mental health and drug addiction treatment. If you or a loved one are struggling with heroin addiction and need help, please don’t hesitate to call. You may reach us at 855-631-2135.Our helpline is open 24/7 and our treatment specialists will assist you in finding the right treatment option for you.
# Posterior predictive distributions for text stimuli in the experiment $$ \newcommand{\Prob}[1]{\mathrm{P}( #1 )} \newcommand{\given}{\vert} \newcommand{\text}{\mathrm{text}} \newcommand{\xtext}{w_1, w_2 \ldots w_n} $$ The following calculates the posterior prediction over words conditioned a text. Given a text $\text$, the posterior predictive distribution is, informally speaking, the distribution over words that are consistent with the discourse topics of the $\text$. It is calculated as follows: $$ \begin{align} \mathrm{P}(w \given \phi, \text, a, m) &= \int \mathrm{P}(w \given \phi, \pi) \mathrm{P}(\pi \given \text, \phi, a, m) d\pi,\\ &= \int \big[ \sum_{\{x\}} \mathrm{P}(w \given \phi, x)\mathrm{P}(x \given \pi) \big] \mathrm{P}(\pi \given \text, \phi, a, m) d\pi \end{align} $$ where $\mathrm{P}(\pi \given \text, \phi, a, m)$ is the posterior distribution over topic distributions of text $\text$, with $\phi$, $a$, $m$ being the parameters of Topic model ($\phi$ is the set of $K$ component topics and $a$, $m$ are the hyper-parameters of the Dirichlet prior over the per document mixing distribution). Note that we need to infer the posterior $\Prob{\pi \given \text, \phi, a, m}$ by sampling using a Gibbs sampler. Specifically, we iteratively sample as follows: $$ \begin{aligned} x_{1:n} &\sim \Prob{x_{1:n} \given w_{1:n}, \phi, \pi},\\ \pi &\sim \Prob{\pi \given x_{1:n}, a, m}. \end{aligned} $$ The probability distributions in both of these steps can be calculated exactly. ## Preface The simulations here require the use of the ipcluster, e.g. `ipcluster start -n 16`, and will take about 12 hours on a 16 core processor. The simuluations have been started with known random seeds, and so all the results will always be identical. If you set `use_cached_result` to `True` on the two instances below, the simulation results will be loaded from the cache and the simulations will not be re-run. Using this, you can get the print-out of the main results without taking any real time, i.e. in around 30 seconds. ```python from __future__ import division import numpy import os import re import configobj import datetime import cPickle as pickle from itertools import cycle import pandas from gustav import models from utils import topicmodels, utils, datautils ``` ## Check required files * In this notebook, we do the posterior predictions based on the Topic model 2290, which has 1500 topics. We use the Gibbs sampler iterations 19000 to 20000, thinning to every 10 steps. The relevant files are stored in the `cache_directory` and the filenames are in `hdptm_samples.cfg`. * We will also need the `Brismo.cfg` file, which are the settings for the online *Brisbane* experiment and so contain all the texts that were used in that experiment. * We also need the BNC corpus that was used to train Topic model 2290. This is `bnc_texts_78639361_183975_251_499.npz`. ```python cache_directory = 'cache' cache_fullpath = lambda path: os.path.join(cache_directory, path) filenames = { 'experiment_cfg' : [('Brismo.cfg', '909d9f8de483c4547f26fb4c34b91e12908ab5c144e065dc0fe6c1504b1f22c9')], 'corpus' : [('bnc_texts_78639361_183975_251_499.npz', '976d2ba53ecbacd092df21c4c04adf47d033fec3901e884cce69ca66ec280831')], 'samples' : configobj.ConfigObj('hdptm_samples.cfg')\ ['hdptm_201117172636_2290_state_checksums'].items() } utils.verify_cache_files(filenames['experiment_cfg'] +\ filenames['corpus'] +\ filenames['samples'], cache_directory, verbose=False) ``` Load up the corpus used by the topic models. ```python corpus_data = numpy.load(cache_fullpath(filenames['corpus'][0][0])) data = models.BagOfWords(**corpus_data) ``` Confirm which iterations of the Gibbs sampler for model 2290 we are using. ```python sample_indices = [int(x.split('_')[-1].strip('.npz')) for x, y in filenames['samples']] ``` Average over all the posterior samples from iteration {{min(sample_indices)}} to iteration {{max(sample_indices)}}, thinning to every 10th one. If the cached result is not used, then this will take around 10-15 mins. ```python use_cached_result = True cached_posterior_average_fname = 'hdptm_201117172636_2290_posterior_average.pkl' if use_cached_result: cached_posterior_average = utils.load_pkl(cache_fullpath(cached_posterior_average_fname)) Phi = cached_posterior_average['Phi'] am = cached_posterior_average['am'] else: Phi = None am = None for samples_item in filenames['samples']: sample_filename, _ = samples_item state = numpy.load(cache_fullpath(sample_filename)) model = models.HierarchicalDirichletProcessTopicModel.restart(data, state, None, None) model.get_counts() phi = model.S + model.psi*model.b phi = (phi.T/phi.sum(1)).T if Phi is None: Phi = phi else: Phi += phi if am is None: am = model.a * model.m else: am += model.a * model.m n = len(filenames['samples']) Phi /= n am /= n assert numpy.allclose(Phi.sum(1), 1.0) utils.save_pkl(cache_fullpath(cached_posterior_average_fname), Phi = Phi, am = am) assert utils.checksum(cache_fullpath(cached_posterior_average_fname))\ == '0dc86b2ef9f2f53cd38925c7244612470ee16c703d4151943ecb341682c76580' ``` # Review inferred topics Look at some of the inferred topics. ```python seed = 101 K, _ = Phi.shape print('\n'.join([models.showtopic(Phi[k], data.vocabulary, show_probability=False, K=10) for k in numpy.random.RandomState(seed).permutation(K)[:50]]) ) ``` centre, centres, shopping, staff, community, local, facilities, run, activities, time nature, time, flea, natural, idea, fleas, mutilation, delicate, human, passion terms, contract, conditions, standard, parties, contracts, buyer, seller, party, business book, published, books, guide, author, history, written, volume, edition, information pockets, tent, bag, nylon, fabric, jacket, bags, fleece, zip, comfortable killed, government, police, security, people, army, attack, attacks, claimed, forces age, life, ageing, ages, time, people, youth, late, women, average bath, water, bathroom, shower, hot, toilet, taps, cold, towel, soap player, hamlet, pause, king, coin, heads, tragedians, time, upstage, dead nuclear, power, reactor, fuel, plant, reactors, station, plutonium, energy, stations mason, pageant, angel, boy, play, god, stage, wagon, father, time carrier, bill, bills, carriers, cargo, carriage, delivery, party, freight, ocean design, architecture, architect, architects, building, buildings, architectural, style, office, designs party, labour, national, conference, communist, policy, left, movement, government, parties animals, animal, welfare, human, wild, cruelty, species, zoo, suffering, monkeys crisis, crises, system, penal, account, legitimacy, collapse, time, riots, conditions robin, hood, time, people, day, collage, personal, bit, bump, sheriff screening, genetic, congenital, handicap, mental, abnormalities, risk, syndrome, affected, gene chemical, chemicals, products, industry, plant, business, company, production, materials, process paper, white, government, proposals, policy, published, green, report, review, public fishing, community, vessel, vessels, nationality, article, law, court, commission, treaty records, record, diary, diaries, recorded, registers, register, recording, date, entry eyes, body, mouth, lips, arms, hand, hands, head, fingers, hair cat, cats, animal, pet, kitten, feline, kittens, dog, owners, human philosophy, knowledge, ideas, nature, idea, experience, mind, natural, philosophical, real activity, activities, time, level, practice, active, person, range, involved, engage squadron, air, war, flying, bomber, aircraft, time, command, force, crew memory, arousal, driving, studies, performance, task, situations, recall, subjects, memories snow, cold, ice, winter, frozen, wind, freezing, day, warm, weather engineering, engineer, engineers, design, engine, steam, mechanical, machine, engines, electrical history, historical, historians, evidence, sources, past, historian, material, documents, study dot, dear, time, baby, loopy, people, nice, brown, till, pet animals, wild, animal, tiger, hunting, prey, lion, food, lions, goat cake, icing, cakes, marzipan, chocolate, cut, paper, top, dry, royal riven, bicker, hills, gnomes, eyes, giants, people, horses, time, sword dark, elves, world, elf, magic, chaos, power, phoenix, king, ancient costs, cost, incurred, basis, expenses, benefit, benefits, charges, amount, taxation door, stairs, house, window, front, kitchen, heard, floor, inside, stood bike, walk, walking, cycling, route, ride, cycle, miles, mountain, cyclists smell, scent, smells, odour, perfume, air, nose, sense, scents, sweet billy, bit, real, cos, sort, pretty, round, summat, people, nice people, government, lineage, image, peace, tribe, lineages, shaikhs, shaikh, time police, body, found, murder, inspector, death, dead, missing, detective, sergeant tribunal, tribunals, representation, appeal, procedure, adjudication, decision, industrial, hearing, parties crime, criminal, criminology, deviance, classical, positivist, social, behaviour, theories, criminals books, book, publishers, publishing, titles, booksellers, sales, publisher, trade, author spirit, dodge, air, time, spirits, mull, isle, waters, universal, party purchaser, vendor, sale, business, information, agreement, completion, mas, letter, acquisition cent, inflation, recession, rates, economy, growth, rate, economic, recovery, rise glass, window, windows, mirror, doors, double, glazing, mirrors, stained, door ```python use_cached_result = True mcmc_sampler_seed = 20202 cached_sampler_result = 'posterior_predictions.2290.%d.pkl' % mcmc_sampler_seed texts = topicmodels.get_experiment_texts('Brismo.cfg', cache=cache_directory) def get_failed_to_converge(posterior_predictions, threshold=1.01): converged = [] failed_to_converge = [] for x,y in posterior_predictions: if numpy.round(y[1], 2) > threshold: failed_to_converge.append(x) else: converged.append(x) # If we use the same datasets on different cluster # engines, we may have a given dataset converging # on one engine and not another. In that case, we want to # exclude that dataset from the 'failed_to_converge' # dataset. return list(set(failed_to_converge).difference(converged)) def get_arguments(failed_to_converge): arguments = [] for name in cycle(failed_to_converge): arguments.append((name, random.randint(101, 1001))) if len(arguments) >= len(clients): break return arguments if not use_cached_result: from ipyparallel import Client model = topicmodels.PosteriorPredictive2(corpus_data, Phi, am) clients = Client() clients.block = True clients[:].push(dict( model=model, texts=texts) ); view = clients.load_balanced_view() random = numpy.random.RandomState(mcmc_sampler_seed) arguments = zip(texts.keys(), random.randint(1001, 10001, size=len(texts.keys()))) func = lambda argument : (argument[0], model.posterior_prediction(texts[argument[0]], seed=argument[1], burn_in_iterations=100000, iterations=50000, max_attempts_to_converge=15)) _posterior_predictions = view.map(func, arguments) posterior_predictions = {} for x, y in _posterior_predictions: posterior_predictions[x] = y[0] ################################### # Try again with the slow learners retry = 0 while True: failed_to_converge = get_failed_to_converge(_posterior_predictions) if len(failed_to_converge) > 0: retry += 1 print('Retry %d: Number of failures = %d' % (retry, len(failed_to_converge))) print('Failures: %s' % ','.join(failed_to_converge)) arguments_retry = get_arguments(failed_to_converge) _posterior_predictions = view.map(func, arguments_retry) for x, y in _posterior_predictions: posterior_predictions[x] = y[0] else: break timestamp = datetime.datetime.now().strftime('%Y.%m.%d.%s') with open(cache_fullpath(cached_sampler_result), 'wb') as f: pickle.dump(posterior_predictions, f, protocol=2) else: with open(cache_fullpath(cached_sampler_result), 'rb') as f: posterior_predictions = pickle.load(f) assert utils.checksum(cache_fullpath(cached_sampler_result))\ == 'e0941816a08af95379a291af9df93885fcae613e068cc6f6e051e39b78cf2742' ``` ```python for text_name in sorted(posterior_predictions.keys(), key=lambda args: int(args.split('_')[1])): print(text_name) print('-'*len(text_name)) print(texts[text_name]) print('='*10) print(topicmodels.topic2str(posterior_predictions[text_name], corpus_data['vocabulary'], K=100)) print('='*50) print('') ``` text_0 ------ ‘I don't know what I did without it’ is the sentiment. There is a difference between fully automatic washing machines — which change the nature of the task altogether — and ‘twin tub’ machines where the hot wet washing has to be lifted manually into a separate drying compartment. The women who had this type of machine complained about the considerable amount of work still required of the housewife, and the mess on the kitchen floor to be cleared up afterwards. In a similar way the launderette does not remove the physical drudgery of washing. The housewife has to get the washing there in the first place, she has to unload it, sort it, sit and watch it wash and dry (or dash out to shop in the interim) and then pack it all up again. This, when there is a baby in the pram and a two- or three-year-old to attend to, is no mean feat. ========== housework,housewife,water,washing,clean,women,time,clothes,job,wash,day,kitchen,housewives,cleaning,shop,wife,floor,satisfaction,dirty,baby,house,home,vehicles,built,carriage,bed,hot,mother,washed,standards,fitted,bath,dry,bathroom,children,role,machine,wheels,table,social,sink,body,husband,people,coach,ironing,hands,dissatisfaction,mind,train,forty,vehicle,cold,feel,dissatisfied,door,cooking,towel,domestic,hair,trailer,wet,soap,satisfied,tasks,coaches,compartment,hand,woman,iron,steel,left,laundry,feet,sheets,covered,sample,carried,finished,routines,jobs,question,child,wheel,system,roof,trains,days,brake,change,night,morning,dust,warm,saloon,tidy,bogies,factory,special,railway ================================================== text_1 ------ Don Juan today has lost whatever sympathetic press the years of male domination gave him. Feminism and a greater acknowledged (though not necessarily practised) awareness of the equality and independence of sexual rights have becalmed the Don as a fool of time. Psychology has dissected him to death. AIDS has ousted him out of history. But there is little point, for instance, in turning on an artistic, enlightened medieval king because he also enjoyed slaughtering hundreds of deer in a day's hunt and daubing the fresh blood on his own face and those of his friends. Examples can be multiplied. To yank someone entirely out of their time and smack them around for not being of our time is perhaps a salutary but only a limited exercise. Yet the times have indeed changed: and Burton's early sexual insatiability, his later infidelities, his many women and his concurrent devotion to monogamy all need some explaining. ========== women,male,century,woman,female,time,sexual,feminist,sex,life,hunt,bra,hunting,king,nineteenth,world,fox,people,day,underwear,power,gender,society,love,feminism,bras,feminists,rights,deer,found,country,late,body,social,feel,role,left,change,history,times,centuries,position,family,modern,eighteenth,political,twentieth,death,view,period,hounds,public,movement,sexuality,feminine,middle,half,lace,mind,mother,sense,hand,foxes,told,past,experience,strong,nature,control,home,days,image,changed,natural,question,equal,father,simply,book,shooting,don,human,common,brought,land,issues,briefs,class,terms,real,short,lives,stretch,means,form,straps,field,true,set,lost ================================================== text_2 ------ When John Major talks of a ‘nation being at ease with itself’, which particular nation is he speaking about? Is he addressing his comments to all those who have become marginalised and dispossessed as a result of right-wing Conservative policies over the years? Or is he speaking about that nation of complacent and indifferent shopkeepers who long for nothing other than a return to the days of imperial hegemony? The shopkeeper as the centre around which the social world revolves is a commercial image hammered into English consciousness by Mrs Thatcher. Self reliance, individual enterprise, ‘what's in it for me’, as opposed to‘how can we help our neighbour’, was the message. This theology slipped over the iron hand of the capitalist market like a silk glove. England became one nation again, a land of hope and glory, Elgar, teacakes and cricket. This England is not one recognised by many of my friends. ========== government,people,party,labour,world,conservative,political,speech,shop,god,policy,social,time,power,national,policies,economic,country,left,thatcher,conservatives,voice,life,public,human,liberal,election,support,nation,politics,change,words,cricket,war,reform,shops,society,john,trade,speak,free,test,day,future,history,live,radical,christian,sense,language,parties,store,tony,socialism,hand,market,land,lives,west,major,home,hope,business,programme,poor,economy,socialist,governments,popular,means,past,welfare,liberals,speaking,lord,called,stores,real,system,match,community,century,opposition,view,ideas,leaders,form,politicians,nations,unions,unemployment,class,leader,local,word,office,nationalism,living,shopping,freedom ================================================== text_3 ------ The form of animal husbandry adopted depends on the type of facilities available and the nature of the experiments. If an experiment produces animals that are to be kept for a long period, or that are to form the basis of a breeding colony, some form of barrier system is essential. If no precautions are taken to prevent infections it is inevitable that the health of the animals will deteriorate with a resulting decrease in breeding performance or death. A minimal barrier system requires people entering the animal area to remove their laboratory coats worn in other areas, and to put on protective clothing. It is essential that they wash their hands thoroughly before handling the animals and the wearing of surgical gloves and a change of footwear or overshoes should be considered. A more stringent barrier includes the requirement for staff to shower on entering the unit and a complete change of clothes. ========== mice,animals,rats,system,rat,form,animal,equipment,mouse,forms,time,mutant,change,water,systems,clean,maintenance,control,cage,safety,health,building,required,human,welfare,clothes,breeding,people,fire,facilities,washing,cages,storage,ensure,shown,wash,floor,rodents,rearrangement,days,cleaning,house,kitchen,provided,protection,provide,wild,poison,means,strain,installed,access,found,free,species,plant,carried,operation,bred,installation,buildings,cruelty,supply,care,requirements,litter,tail,including,staff,hot,essential,similar,main,natural,standard,vermin,dirty,bed,set,day,construction,designed,zoo,dogs,design,injection,level,sterile,result,bath,dry,infection,risk,bathroom,rodent,conditions,allowed,life,skin,suffering ================================================== text_4 ------ I then took her forward slightly to the evening after the operation, a time when she was fully awake and over the more drastic effects of the anaesthetic. I asked her how she felt now. To my surprise Kirsty burst into tears. No, she told me, she was not in any great pain — simply the discomfort she would have expected to follow surgery. She was not aware of feeling particularly ill. It was just that she knew that there was something seriously wrong with her — something far more dramatic than a grumbling appendix or the normal after- effects of an operation. Oh, the doctors and nurses had assured her again and again that she was fine and would soon be fit and well again. And yet, as she kept repeating, she was convinced that there was something that no one was telling her. ========== hospital,doctor,effect,effects,time,home,told,ill,day,days,life,doctors,died,pain,months,illness,heart,weeks,condition,cancer,treatment,family,bed,left,husband,night,wife,medical,patient,sick,suffered,nurse,health,found,mother,operation,suffering,hours,death,feel,week,people,children,die,ago,disease,eyes,looked,brain,result,started,visit,impact,live,morning,care,affect,direct,clinic,woman,attack,surgery,feeling,bad,wrong,son,patients,called,recovery,suffer,rest,diagnosed,daughter,stay,treated,ward,ambulance,father,affected,heard,admitted,blood,suddenly,chest,unable,difficult,friends,tests,worried,severe,finally,lost,happened,drugs,friend,month,dying,stomach,short,taking ================================================== text_5 ------ It was mentioned above that overflow records arise singly. In addition, an embedded overflow area will usually contain varying numbers of records from several tracks. This leads to overflow records usually being stored in unblocked format, even if the records in the prime data area are blocked. There is some advantage in treating the whole embedded overflow area as a single large blocked record, and manufacturers' software often does transfer the whole track into main storage when an addition is to be made; this allows for the addition itself, creation of link fields, changes of index, etc. However, handling the whole track as a single block would prevent rapid transfer of individual records from the embedded overflow area during direct access reference, which is the reason this method is often not adopted (but see the section on software packages, p. 264). ========== file,records,record,files,index,track,storage,overflow,data,time,access,key,search,stored,address,sequential,additions,required,synonyms,space,direct,processing,cylinder,size,shown,keys,home,bucket,random,average,packing,times,method,indexed,retrieval,addresses,inverted,buckets,indexes,set,added,sequence,table,held,cent,prime,synonym,loaded,device,algorithm,software,technique,main,position,accesses,process,discussed,processed,hold,single,density,start,positions,directly,serial,disk,require,chapter,located,separate,designer,run,allocated,accessed,store,reference,found,due,expected,half,head,information,user,revolution,results,provide,result,figure,pointers,frequently,searching,performance,sequentially,field,handling,read,series,system,tracks,load ================================================== text_6 ------ Though innovation is a very positive term, it is important to remember that any particular innovation is only positive in retrospect, after it has worked. Before that, because change by definition is something no one has seen yet (despite models that may exist elsewhere), it has to be taken at least partially on faith. For example, why a continuing education program now? Why use funds to develop a new product when there are so many already on the market? Why take the risk of decentralizing the accounting office? In short, unless there is somebody behind the idea willing to take the risk of speaking up for it, the idea will evaporate and disappear. One reason there is so little change in most traditional bureaucratic organizations, I argue, is that they have conditioned out of people the willingness to stand up for a new idea. Instead, people learn to back off at the first sign that somebody might disapprove. ========== positive,negative,innovation,people,ideas,creative,creativity,thinking,time,organization,process,technology,innovations,idea,development,product,change,market,innovative,success,successful,organizations,invention,opportunities,organizational,technological,individuals,person,research,critical,effective,company,individual,difficult,industry,lead,knowledge,management,technical,approach,result,risk,education,found,opportunity,products,ability,concept,solutions,means,original,business,highly,essential,resources,project,feel,world,tend,changing,model,solving,form,requires,potential,climate,environment,responsibility,hand,inventions,processes,companies,imagination,focus,imaginative,control,makes,office,entrepreneurs,obvious,activity,developed,solution,difference,economic,positively,managers,entrepreneurial,innovators,talk,money,false,originality,quality,true,system,real,information,involves,practice ================================================== text_7 ------ Some social scientists have conceptualised these workers in terms of a reserve army of labour. In this case, they would constitute a pool of labour which can be utilised in boom periods and disregarded in recessions. This view sees the experience of the Third world as being little different from that of the industrialised countries. The large numbers who are unable to find regular work are not seen as a phenomenon characteristic of underdevelopment, but part of the capitalist division of labour and, therefore, a similar feature to the industrialisation process of European countries, differing in terms of quantity rather than quality. For Marx, however, the function of the reserve army of labour was keeping wages low and, to this end, the absolute size of the reserve army need not be very great. The high numbers and continuing growth of this sector in Latin America would suggest that concepts of European analysis are not sufficient. ========== countries,world,defence,military,workers,labour,forces,economic,theory,growth,army,development,force,international,wages,armed,economy,time,employment,trade,terms,global,developing,differences,analysis,rate,social,period,country,approach,wage,system,national,level,investment,increase,structure,theories,cent,troops,market,capital,aid,women,developed,united,air,industrial,production,view,nations,productivity,war,increased,service,prices,political,demand,employers,real,nature,output,major,governments,based,staff,ministry,rates,theoretical,low,common,western,worker,government,similar,account,pattern,form,industry,skilled,rise,inflation,paid,resources,features,role,chapter,employed,process,poor,conditions,concept,jobs,policy,study,extent,individual,provide,navy,basic ================================================== text_8 ------ In the case of time constant, a production worker tends to be focused on the production schedule for today or this week. An R&D worker is aware that what he does today will not affect company output in this order of time span. It may be months or years before his work today makes an impact: in the case of a project failure it may never do so. Words such as ‘hurriedly’ and ‘quickly’ are likely to be associated with different orders of time spans in the minds of the two people. Salesmen are probably in between these two. They have in some cases a weekly or monthly schedule of orders to win but the long-term relationship with their customer is also of great importance and the weight to be put on the two factors at any one time calls for the exercise of judgement. ========== months,time,production,week,period,weeks,product,month,people,process,company,manufacturing,days,control,products,day,august,quality,design,start,technology,short,produced,factors,stage,management,final,plant,twelve,cost,life,involved,sales,social,set,times,person,workers,costs,materials,factory,organisation,experience,feel,individual,decision,produce,project,summer,machine,half,line,eighteen,required,department,progress,completed,date,difficult,assembly,spent,carried,started,labour,ten,system,manufacture,total,finished,job,beginning,received,task,found,change,care,stock,result,continued,initial,tasks,processes,previous,complex,relationship,march,regular,planning,decided,decisions,earlier,levels,support,main,activities,purchasing,operation,machines,development,home ================================================== text_9 ------ In the afternoon, we have a rehearsal, but without the guests. I just walk through the basic moves so the cameras can plot where everybody's going to be, and we try to work out how long people will take to walk down the stairs so we can play the right amount of music. If they can make it, we like the guests to arrive before the audience starts to go in, so they can walk through it, too. Those steps down to the set can be daunting — I think it's everybody's nightmare, stepping out and falling flat on your face. Dusty Springfield was wearing new shoes, with very high heels, and was terrified that she'd slip, so just before she was due to go on, one of the team was dispatched to look for some scissors to scratch the soles with. Oh, the glamour of it all. ========== shoes,shoe,time,foot,pair,film,door,feet,house,boots,leather,doctor,people,set,series,heel,socks,story,star,front,wear,day,fit,night,script,footwear,movie,left,play,director,television,home,production,floor,life,verity,cast,john,top,inside,air,world,street,found,audience,actor,episode,called,sock,played,party,sole,garden,cushioning,lot,drama,evening,round,idea,hotel,team,pairs,road,looked,shop,running,boot,theatre,stage,role,size,soles,feel,walk,light,heavy,wearing,slippers,rubber,days,worn,window,toes,wall,start,walking,dinner,love,hand,children,studio,producer,head,trainers,stars,characters,stone,screen,shoemaker,stood ================================================== text_10 ------- My understanding of the law is that an adult patient who is capable of doing so must give consent to any medical treatment if that treatment is to be lawful. At the time of the decision the patient needs a capacity commensurate with the gravity of that decision. If the patient lacks the requisite capacity, then the doctors must act in what they perceive to be his or her best interests, with information garnered from previous knowledge of the patient, discussion with family and friends, and taking into account any relevant directive previously made by the patient. What the legal force and effect of any such directive might be is uncertain; it is unclear whether health care staff are required to carry out the terms of the directive or whether those who act in good faith with the terms of the directive are immune from civil or criminal prosecution. There is, apparently, no case law on this point. ========== patient,consent,treatment,law,doctor,medical,legal,decision,doctors,refusal,minor,act,health,person,circumstances,court,community,life,commission,wishes,age,directive,time,duty,situation,section,patients,understanding,authority,information,principle,hospital,request,mental,treat,legislation,refuse,blood,knowledge,care,parents,child,condition,informed,common,question,matter,view,proposed,effect,adult,judgment,euthanasia,die,ill,effective,national,laws,death,accept,issue,criminal,position,competent,form,doubt,transfusion,concerned,risk,terms,guardian,parent,free,ventilator,capacity,mind,required,involved,respect,decisions,refusing,sufficient,measures,continue,pain,terminally,decide,inherent,difficult,market,considered,clinical,courts,giving,council,article,operation,power,jurisdiction,apply ================================================== text_11 ------- The bones are bound to each other by tough, flexible ligaments and are articulated at the joints by muscles. There are just over 600 voluntary muscles in the human body. For our purposes, it is only necessary to mention the larger, superficial muscle groups which affect the shape of the body and are responsible for the movement of the limbs. These are referred to as skeletal muscles, most of which are attached at both ends to bones. The muscles that give expression to the face are also referred to as skeletal muscles, and they link bone to skin. A whole complex system of muscles is brought into play for each movement of the body: bending an arm involves the shortening of the biceps, while the tricep muscles at the back of the arm must relax and lengthen in unison. Meanwhile, others immobilise joints not needed in the action, while others still adjust to stabilize the body's equilibrium. ========== body,bodies,leg,legs,head,arms,human,left,feet,arm,hands,time,foot,position,front,muscles,hand,bodily,pain,straight,shoulder,knees,forward,weight,knee,governing,shoulders,lower,movement,floor,stand,mass,bend,move,subject,hold,exercise,slowly,toes,means,figure,upper,chest,drawing,injury,system,bones,bent,ground,normal,pull,rest,slightly,inside,broken,upright,exercises,elbow,keeping,injuries,neck,hips,height,raise,wound,movements,relation,organs,standing,spine,physical,draw,length,forwards,perfectly,lift,ankle,start,backwards,hard,complex,balance,waist,basic,hip,skin,close,account,flat,muscle,machine,past,sit,holding,organ,understand,functions,main,direction,repeat ================================================== text_12 ------- The extent to which subject coverage on the shelves can be achieved is a matter of library policy, funding, the amount of shelf space available, and the efficiency of interlending systems to which the authority has recourse. These influences are considered in more detail in Chapter 12. The case for immediate shelf representation in a public library is made at some length by Ranganathan, in his fourth library law —‘save the time of the reader’. ‘Mental hunger for books is not compelling in the case of most people. Mental thirst for information is not inexorable in the case of most people. Both of them are fleeting in their nature. They both die out, unless satisfied immediately on their taking shape. No time lag should come between demand and supply. The tempo for reading is often momentary. It should be harnessed at the very moment.’ ========== library,libraries,books,time,people,book,public,stock,subject,information,collection,librarian,librarians,world,collections,material,service,chapter,desire,reference,staff,law,materials,services,pleasure,selection,research,factors,catalogue,life,university,user,experience,titles,literature,provision,mind,sense,users,physical,national,mental,access,publications,main,special,reading,items,knowledge,form,individual,system,found,consciousness,readers,death,academic,catalogues,shelves,periodicals,resources,real,recent,range,bibliography,terms,section,policy,volumes,human,lending,nature,desires,survey,difficult,major,published,revision,instance,journals,matter,copies,music,subjects,view,demand,date,set,space,factor,records,sources,printed,loan,include,common,past,level,spent,simply ================================================== text_13 ------- In Ordinary Justice the National Consumer Council were scathingly critical of such court proceedings which in practice, they said, became a rubber stamp. The documents the court sent out were difficult to understand and no guidance was given on completing it. The ‘defendant’ was not asked about his personal circumstances. The Civil Justice Review found that a third of banks and building societies, and a fifth of local authorities, did not enquire about the debtor's circumstances before the hearing. Three quarters of local authorities did not follow up the Department of Environment's advice and carry out checks to see if the tenant was receiving the right benefits. Sixty-seven per cent of creditors had no knowledge of the debtor's financial state at the time of the original transaction, and 77 per cent did not obtain any further information before or during the proceedings. ========== court,local,advice,appeal,mortgage,information,authority,cent,bank,authorities,husband,wife,service,house,judgment,judge,services,housing,charge,creditor,time,bureau,building,decision,security,home,law,government,plaintiff,proceedings,action,national,defendant,people,influence,council,act,application,rate,cab,loan,property,contact,notice,debtor,societies,office,rates,undue,society,legal,party,support,evidence,surety,offer,bureaux,provide,plaintiffs,defendants,documents,effect,agency,held,question,circumstances,form,social,department,free,telephone,issue,central,agent,lenders,independent,details,set,matter,transaction,county,courts,person,hearing,loans,lord,claim,justice,special,association,document,found,mortgages,workers,jurisdiction,leave,public,grant,pay,required ================================================== text_14 ------- The Dickens study tells us that not every dismissed employee eligible to claim unfair dismissal does so. Only about one in ten of those eligible to claim actually does so. Among those who apply there is a greater tendency to bring unfair dismissal proceedings where the employer is a small single establishment employer with below average unionization. Nearly half of all applications are against employers with fewer than 20 employees. The larger the employer, the less likely it is that there will be an unfair dismissal claim. There are a number of possible explanations for this pattern of application. Larger employers are likely to have internal appeals procedures and failure there, where union representation may have been provided, is the point at which the employee draws the line. Employees may feel a sense of powerlessness in taking on a large organization or it may be that advisers are more reluctant to take on large organizations. ========== employer,employment,employee,tribunal,dismissal,employees,contract,industrial,cent,tribunals,job,union,unfair,employers,redundancy,trade,dismissed,unions,transfer,appeal,rights,company,claim,time,law,terms,organization,pay,table,business,representation,decision,employed,figures,procedure,notice,reason,legal,workers,statutory,relations,average,period,management,entitled,reasonable,fair,adjudication,internal,parties,hearing,figure,total,labour,circumstances,compensation,claims,position,security,act,protection,leave,court,external,rules,nature,regulations,evidence,system,bargaining,written,reasons,appeals,found,organizations,service,officer,payment,process,represented,apply,conditions,people,held,offer,procedures,social,question,relevant,conciliation,result,provide,courts,person,required,alternative,applicants,redundant,proportion,national ================================================== text_15 ------- Our terms of reference suggested that we should consider drama in the context of the great dramatic works of literature. We believe that plays should be approached through the dramatic medium; children should often see or participate in the play being acted, and not just read the text. This approach will not only result in an appreciation of the literary merits, but also foster an understanding of stagecraft. There is still an important place within drama activity for the exploration and study of scripted plays, and we addressed this aspect in our statements of attainment and programmes of study. At primary level, the range of material for exploration needs to be more diverse: myth, legend, fairy stories, poems. At secondary level, such work can expand naturally into the exploration of dramatic texts. Children's own writing can also be explored — at both levels — through the medium of drama. ========== children,drama,teacher,level,literature,curriculum,pupils,literary,story,levels,teachers,school,play,class,experience,role,education,child,schools,time,teaching,writing,criticism,texts,study,dramatic,cultural,stories,national,ideas,language,reading,critical,text,learning,activities,skills,subject,mathematics,studies,assessment,chapter,history,activity,range,subjects,book,attainment,read,primary,people,understanding,discussion,stage,theatre,mathematical,classroom,experiences,theory,renaissance,development,culture,poetry,secondary,academic,set,pupil,develop,modern,terms,materials,key,real,opportunities,simple,content,talk,create,opportunity,form,instance,writers,playing,sense,structure,difficult,science,critics,focus,told,educational,context,questions,historical,examples,short,vocabulary,life,approach,tradition ================================================== text_16 ------- Activity 1 (15–20 mins): Identify a small group of clients, such as the first six people you saw in your last day's community care, the first six people attending your outpatients' clinic, or six individuals in a bay in your ward. For each client, list the nursing interventions either by yourself or someone else, such as ‘insulin injection’, ‘mouth care’, ‘socialisation’, ‘health promotion’, that each required in the fist hour of care, say between eight and nine, or nine and 10 in the morning. You should end up with at least six separate lists, some with perhaps only one item on it, others with several items, listed in the order that each client received, or was assisted with, that care. Are there any items common to several, or all, of the clients? Did they receive similar care at the same time or in the same order? ========== list,nursing,client,nurses,care,patient,nurse,patients,ward,clients,time,lists,staff,health,names,hospital,clinical,people,items,day,firm,practice,individual,hours,ensure,include,minutes,medical,behaviour,social,lawyer,required,information,included,listed,lawyers,professional,team,visitors,item,personal,surgery,home,involved,individuals,person,period,community,assessment,unit,check,found,district,days,wards,ten,listing,hour,identify,night,admitted,morning,role,experience,advice,short,times,practitioner,operation,allocation,instructions,support,details,require,discuss,feel,carried,goals,set,senior,sister,treatment,preparation,service,surgical,write,return,responsibility,theatre,left,relationship,chosen,type,study,date,specific,chapter,addresses,provide,half ================================================== text_17 ------- Once again that requirement to get on with people, clients, account executives and the creative teams is basic to your daily work. Just how does cooperation between a planner and the creative team work? After all, creative people are supposed to be sensitive and aware of the consumer and society and in real touch with change and mood. Let's take an example of the planner and creative team together. Trying to devise the strategy for a lager campaign, the planner found out through the research that the key benefit consumers looked for in lager was refreshment — incidentally something no other beer advertiser mentioned. The creative team took this new insight and used it as a spring-board to create a very successful campaign based on sprouting leaves and the headline: "Refreshes the parts other beers cannot reach" , thus demonstrating the imaginative leap creative people make from research findings to effect communication messages. ========== advertising,team,agency,people,campaign,creative,product,agencies,advertisements,media,teams,marketing,ad,commercial,time,ads,innovation,research,brand,advertisement,ideas,account,television,market,client,products,sales,beer,advertisers,creativity,thinking,industry,clients,commercials,successful,promotion,posters,idea,job,press,brands,director,advertise,direct,process,business,magazines,sell,campaigns,buy,technology,approach,poster,set,department,companies,effective,message,run,consumer,audience,money,success,newspapers,company,development,major,innovations,image,magazine,consumers,adverts,medium,brewery,difficult,strategy,launch,task,selling,radio,change,newspaper,public,individual,budget,spend,means,innovative,create,produce,specialist,potential,target,designed,information,advert,brewers,real,copy,brewing ================================================== text_18 ------- While many of these may be social occasions, work groups especially in large companies may often stay on late to participate in quality control circles or zero defect clubs. There are up to four million quality control circle participants in Japanese industry and in large companies two in five workers are members. Quality consciousness is said to be very high among Japanese workers who endeavour to eliminate components that are rejected as substandard. Each smaller work group attempts to perform better than their rival groups in both quality control and in the number of suggestions they offer to improve productivity. Workplace harmony is enhanced by communal sports clubs, company vacation resorts, one-class cafeterias and the absence of status barriers within the plant. There is an hierarchical structure, but managerial authority is respected as a benign guardian of company interests. Corporate identification with workers knowing their place is in short "a managers Nirvana". ========== quality,control,management,company,organisation,workers,time,club,technology,process,life,jobs,people,business,companies,improvement,service,job,experience,system,team,production,staff,customer,organisations,performance,customers,sport,employees,world,human,manager,factory,managers,means,structure,training,standards,labour,plant,systems,industry,sports,programme,development,set,union,organization,individual,social,total,spiritual,responsibility,authority,relationship,improvements,form,sense,nature,machine,level,love,power,success,ski,controls,change,machines,market,procedures,relationships,god,assurance,temporary,involved,women,manufacturing,commitment,major,improved,ensure,food,achieve,industrial,services,mind,product,football,worker,top,director,improve,benefits,action,failure,trade,workforce,approach,teams,lack ================================================== text_19 ------- While it would be unlikely for a firm contractual commitment to be made which binds a record company to produce a promotional video, it is a matter of fact that a promotional video will be produced to support an artist's first single. With limited production costs, this video would fall into the £15,000 to £30,000 range, as opposed to the six-figure costs incurred by the established major artists. The cost of the promotional video for a developing artist would be recoupable against both audio and video income received by the record company. The income to pay these video costs is usually minimal with new artists, so these expenses are often set against future video exploitation. This is income which increases as the artist gains greater success and begins to release such items as compilation videos comprising selected promotional videos, or full length videos of live concert performances. ========== record,costs,video,music,cost,recording,tape,records,company,band,artist,companies,artists,sound,time,tax,deal,tapes,money,income,recordings,recorded,manager,studio,act,songs,cassette,major,recorder,label,album,publishing,people,discs,musicians,videos,radio,business,live,bands,contract,benefit,material,play,audio,incurred,basis,acts,machine,equipment,signed,disc,industry,benefits,sales,royalty,paid,machines,cassettes,royalties,success,expenses,amount,taxation,quality,set,producer,film,television,writer,studios,talent,system,camera,successful,recorders,cent,sign,labels,release,charges,tour,public,pay,independent,copyright,career,producers,editing,result,singles,account,albums,single,microphone,original,agent,top,songwriter,stereo ================================================== text_20 ------- Despite the challenges associated with building up large-scale production, the Japanese are forging ahead in display technology — and for very good reasons. Obviously the straightforward replacement of bulky cathode ray tubes with flat panel display leads to significant power and weight reductions as exemplified in the commercialisation of laptop computers. The most strategically important reason for investing in flat panel display technology, however, is that with continued miniaturisation of the integrated circuits the display itself will become the platform on which the system is built. This raises the prospect of fully integrated systems for which the sourcing of individual components such as drivers, memory chips and processors on the world market would no longer be an issue. Countries with such a display manufacturing capability would dominate the market and effectively eliminate competition based on older technology made up from discrete components. ========== companies,disk,market,industry,business,system,machine,firms,drive,computer,company,memory,board,hard,image,technology,ram,sales,time,markets,systems,components,video,growth,data,investment,products,development,major,circuit,software,world,power,performance,future,multimedia,screen,information,card,costs,images,windows,processor,drives,floppy,machines,manufacturing,quality,competition,production,share,expansion,unit,standard,electronic,range,competitive,light,industries,size,digital,electronics,increased,international,sector,local,operating,run,product,network,management,increase,success,box,printer,businesses,countries,financial,profits,monitor,set,result,disks,industrial,display,cost,based,difficult,disc,artwork,foreign,speed,main,supply,manufacturers,significant,recession,continue,current,profit ================================================== text_21 ------- Though less visible, it was export competition in goods and services which had a more fundamental effect on UK towns and cities. The internal economic geography of the UK has been reworked over a century by fundamental change in the nature and orientation of exports, which has reflected the success of individual industries and their factories. This demonstrates the principal changes so far this century in the composition of export goods. In 1900, the country was still largely dependent on exports of textiles, metals and coal, whereas by 1987 nearly half the country's exports were accounted for by ‘machinery and transport equipment’ and chemicals. The impact of North Sea oil on the structure of the balance of payments may actually have reduced the absolute volume of manufacturing exports. This is because it raised the real sterling exchange rate, rendering ‘marginal’ manufacturing exports uncompetitive. We shall return to this issue at several points later in this volume. ========== trade,manufacturing,employment,industry,exports,imports,industrial,production,countries,industries,export,sector,world,economy,market,labour,jobs,economic,country,growth,prices,cent,products,import,exchange,decline,service,services,foreign,tonnes,markets,sectors,century,change,major,trading,workers,period,international,rate,domestic,price,tariffs,imported,currency,output,development,terms,demand,surplus,rates,million,oil,agricultural,total,national,increased,firms,unemployment,level,time,regions,grain,manufactured,increase,regional,balance,tariff,food,employed,steel,exported,deficit,shift,economies,united,producers,agriculture,share,importance,job,structure,government,dollar,rise,subsidies,transport,free,plants,main,levels,result,textiles,quotas,system,half,geography,sterling,net,raw ================================================== text_22 ------- As far as the Royal Navy were concerned the nuisance of excessive leakage was largely put a stop to when Sir Robert Seppings (1764–1840) introduced diagonal iron bracing into wooden hulls about 1830. Seppings, who used to say ‘partial strength produces general weakness’, seems to have been one of the first Naval Architects to have a clear mental picture of the stress systems in a ship's hull. In the merchant service wooden hulls were to a considerable extent replaced by composite and iron and steel construction after the middle of the century. A number of wooden ships continued to be built without adequate shear bracing, however, and such ships got more leaky as they got older, until, in an age when most of the pumping was done by hand, it became uneconomic to run them any longer. Up till 1914 Norwegian shipowners were still making money by buying up British sailing ships and running them with windmill pumps. ========== mill,ship,ships,sea,mills,strength,water,material,time,navy,fleet,stress,century,captain,naval,materials,crack,glass,surface,fracture,pipe,fibres,crew,vessels,port,vessel,built,coast,war,system,seamen,shipping,board,corn,royal,brittle,merchant,site,energy,voyage,sailors,strong,wheel,power,sailed,building,house,wood,fibre,admiral,sailing,age,iron,trade,strain,carried,weight,tensile,left,main,world,east,mechanical,company,cloth,sail,structure,cracks,times,money,home,cargo,tension,days,life,waters,length,load,machinery,cellulose,found,john,solid,steel,harbour,officers,island,local,run,buildings,people,result,tip,set,steam,ports,diamond,provided,wooden,process ================================================== text_23 ------- Clear out all your possessions and be ruthless. Now is the time to take rubbish to the dump, to give things away to charity shops and jumble sales. There is no point in taking all your useless rubbish with you. Also clear up the garden. You are not supposed to leave rubbish behind for the next occupants to cope with, although you can leave it bagged up outside the door for the dustmen to take later. If you are leaving the area do not forget to pick up any clothes that are at the cleaners, or shoes, clocks, or other items that are away being mended. You will also need to withdraw sufficient cash from the bank to pay for the removal. It is common practice to tip the people who have done the removal work so you may want to withdraw enough for this too. ========== bag,bags,time,account,plastic,paper,money,bank,people,packed,left,box,boxes,car,carrier,clothes,cash,found,home,suitcase,carrying,contents,luggage,cheque,days,set,carry,lot,pack,day,shopping,inside,pay,hand,cardboard,packing,items,pair,house,bottles,books,bought,rubbish,suitcases,door,carefully,paid,stuff,missing,wrapped,cheques,floor,contained,accounts,piece,couple,garden,picked,looked,empty,heavy,hands,payment,shop,pieces,sort,common,kit,boot,shoes,amount,packet,leave,stuffed,credit,carried,brought,hold,black,shops,rest,mind,idea,card,polythene,remember,parcel,pile,send,feel,pocket,half,arrived,bits,clothing,leather,brown,started,drawer,store ================================================== text_24 ------- Individual goals may well be in conflict with organisational goals even where there is a strong commitment to one goal by the organisation. It is worth repeating that there may also be competing goals within the organisation itself. Thus, for example, the prison service may wish to pursue the twin goals of the punishment of offenders and at the same time their rehabilitation. These two goals may prove to be incompatible and yet each will have its supporters. Within the National Health Service there may well be a commitment to provide the best possible medical care that the state of medical knowledge will allow and yet this may be tempered by the requirement to act within tight financial constraints. The two goals may be in conflict. Many organisations will face the problem of which goals to prioritise in the light of competing goals. ========== health,objectives,goals,objective,conflict,service,achieve,organisation,services,goal,set,management,people,care,sentence,achieved,time,means,aims,organisations,authority,success,aim,achieving,step,court,offenders,hospital,structure,courts,prison,criminal,specific,conflicts,achievement,terms,medical,purpose,patients,individual,setting,process,change,justice,result,provide,involved,public,offences,organisational,sentences,offence,control,responsibility,task,community,level,role,magistrates,sentencing,act,imprisonment,managers,performance,strategy,probation,successful,practice,situation,behaviour,effective,action,staff,individuals,offender,system,national,planning,concerned,home,difficult,progress,targets,circumstances,activities,treatment,decide,plan,approach,hospitals,statement,term,range,environment,crime,relationship,local,personal,future,relationships ================================================== text_25 ------- On 25 July 1985 the dock company put in a planning application for the construction of a Roll on — Roll off (‘Ro-Ro’) terminal in the River Medway. Permission was refused, there was an appeal and an inquiry by an inspector whose recommendations the Secretary of State for the Environment accepted. The appeal was dismissed. The main consideration was undoubtedly the increase in heavy goods vehicles that would be generated by the new development and the consequent increase in noise levels, in particular night-time levels in Medway Road and Bridge Road. These environmental objections were considered to be serious enough to outweigh the economic benefits of allowing the proposal. It was this development and in particular the evidence given at the Ro-Ro inquiry which in due course prompted the council to bring the present proceedings. In March 1988 the council passed the necessary resolution and the writ was issued on 20 July 1988. ========== site,court,appeal,development,planning,council,port,local,decision,plans,building,road,land,company,scheme,build,increase,permission,application,construction,public,ferry,increased,house,proposed,built,inquiry,authority,project,dock,centre,judge,park,time,judgment,residents,ground,existing,facilities,held,ports,county,town,plan,district,cost,grounds,north,traffic,lords,proposal,access,environment,rate,effect,route,due,people,sites,major,ships,considered,law,harbour,cargo,issue,east,decided,level,shipping,granted,docks,act,power,justice,question,department,industrial,result,national,housing,lord,south,community,meeting,refused,matter,main,objections,developers,hearing,ferries,completed,developer,section,evidence,complex,planned,ship,station ================================================== text_26 ------- At the start of the exercise, the actual procedure was checked against a conceptual model that included the activities deemed necessary to achieve the agreed transformation. If the changes revealed by this comparison have not been made prior to the audit commencing, this could be the reason for the failure to meet the target levels of attainment. If, however, the procedure does comply with the procedure description derived earlier, then it will be necessary to subject each element or activity of the model to further scrutiny, for example by breaking them down to lower-order activities, or by auditing each element in the same manner as the parent procedure. This process is similar to work study exercises where measurable elements of a task are identified before the actual measurement takes place, and consideration is given to the resources required at each level, including the skills and experience of the operator. ========== information,system,time,analysis,systems,date,period,activities,management,performance,required,support,model,process,resources,situation,level,organisation,functional,basis,activity,notice,study,considered,control,terms,assessment,evaluation,practice,procedure,analysts,development,staff,exercise,concerned,departments,requirements,elder,functions,fig,main,ideas,review,carried,detailed,levels,filing,relevant,finance,stage,potential,factors,form,computer,monitoring,identified,objectives,procedures,effect,determine,approach,project,task,root,examination,client,effectiveness,definition,provide,effective,database,achieved,audit,requirement,elders,analyst,providing,planning,individual,tasks,taking,months,users,proposed,based,components,stages,measures,chapter,act,criteria,days,quality,manner,existing,earlier,related,relation,actual,assessing ================================================== text_27 ------- The Knights of the Blazing Sun were created after the Battle of Magritta in 1457 during the crusades which eventually freed the land of Estalia from the Arabian invaders. The battle was a great victory for the Knights of the Old World, made all the remarkable by a strange and prophetic occurrence. During fierce street fighting around the temple of Myrmidia, the warrior goddess of Estalia, a group of knights found themselves surrounded by the dreaded Black Guard led by Emir Wasr the Cruel. Just as the Arabians closed in a sudden earth tremor shook the temple, dislodging a huge bronze statue of the goddess which plummeted to the street below crushing the Emir and many of his troops. The event was to prove the turning point of the battle. Afterwards, the surviving knights established the Order of the Blazing Sun with Myrmidia as its patron and protector. ========== temple,army,time,king,god,battle,sacred,goddess,found,ancient,gods,left,soldiers,street,temples,cult,head,dead,town,religious,ritual,enemy,horse,eyes,castle,miles,shrine,church,road,tomb,horses,day,troops,north,prince,built,south,fight,black,body,rode,sun,force,river,hundred,war,cavalry,city,sword,stone,led,killed,fighting,form,blood,thousand,night,news,events,fire,attack,centre,period,deity,house,set,camp,white,walls,main,worship,building,life,round,arms,west,reached,lord,tombs,days,figure,held,called,human,world,carried,brought,symbol,air,palace,cut,late,march,lay,earth,wall,royal,power,altar,event ================================================== text_28 ------- The answer to the first, or ‘why’, question begins with a recognition that banks are private sector, profit-making organisations with obligations to shareholders to increase profits over time. Thus they will always be looking for ways of expanding their balance sheets provided this leads to extra profit. Look again at Table 3.3 which shows the aggregate balance sheet of a large number of banks. Notice that assets are composed of various forms of lending: to the personal sector, the commercial sector, the government or the Bank of England. The liabilities side is dominated by deposits. Notice also that we can express any class of asset as a proportion of total assets or liabilities and remember too that in section 1.1.5 we said that these ratios are arrived at as a matter of deliberate choice and are assumed to represent portfolio equilibrium. ========== bank,public,private,banks,money,sector,market,deposits,assets,bills,government,financial,rates,discount,class,rate,funds,supply,time,liquidity,cash,monetary,balance,houses,lending,question,institutions,deposit,accounts,liquid,questions,company,notes,balances,credit,demand,loans,treasury,net,ratio,commercial,account,answer,markets,amount,profit,liabilities,borrowing,asset,authorities,exchange,issue,held,capital,banking,stock,form,hold,short,cost,sheet,base,system,sterling,surplus,personal,accounting,total,increase,basis,individual,operations,business,table,classes,issued,customers,loss,lend,companies,borrow,effect,bonds,bill,maturity,transactions,securities,economy,return,investment,period,means,policy,future,finance,services,building,cent,reserves,purchase ================================================== text_29 ------- Using the golfing tips he gleaned from such fine players, Andy soon had his handicap down to two. He was by then an assistant pro in its fullest sense, so he decided to try his hand at playing tournaments. Although he qualified for a few regional events, in fact he was aiming much higher: he wanted a crack at the Open Championship. So in 1973 Andy decided to try and qualify for the Open at Royal Troon — and it was here that an incident occurred that changed his career. He had played the first round, but before he had a chance even to hit a ball in the second he was out of the pre-qualifier, suffering from injuries he had received in a car accident with his caddie. Swallowing hard on the disappointment, Andy spent the next few years taking even more blows on the chin. ========== golf,round,green,hole,shot,play,tour,hit,won,tournament,par,time,car,holes,win,played,accident,day,tee,championship,players,ball,masters,player,playing,shots,game,professional,putt,club,caddie,cup,week,golfer,hospital,left,amateur,nick,yesterday,golfers,rounds,greens,driving,yards,champion,finished,world,driver,putting,clubs,practice,top,feet,crash,killed,road,short,jack,fairway,drive,putter,event,people,died,birdies,birdie,sandy,lead,golfing,happened,major,courses,home,head,injured,injuries,bunker,police,lost,missed,cut,couples,tournaments,final,royal,putts,days,winner,match,told,season,ambulance,hitting,winning,stroke,professionals,pro,record,set,tom ================================================== text_30 ------- Improve your mood and counteract stress: Ask anyone who exercises regularly and they will tell you that they always feel exhilarated at the end of a session — even if they had begun by feeling that they were not in the mood for exercise and had almost forced themselves to continue. Physical fitness also provides considerable protection against stress and the illnesses it can cause. So, however busy your life, perhaps you could try and fit some regular exercise into your day. Let it be something which is in complete contrast to the way you normally spend your time. One word of warning though: if you are someone whose daily life involves a strong competitive element, you would do well to avoid too much in the way of competitive sport (squash, tennis and so on) as your form of exercise as these will only tend to maintain an already high level of stress. ========== exercise,fitness,body,exercises,time,walking,training,muscles,physical,heart,walk,health,fit,day,aerobic,muscle,regular,life,minutes,weight,routine,strength,feel,programme,week,people,stamina,running,swimming,jogging,aerobics,rate,session,increase,activity,gym,stress,build,exercising,rest,stretching,sports,level,benefits,start,hard,healthy,times,sessions,taking,mental,improve,weights,normal,person,energy,begin,diet,active,vigorous,regularly,days,helps,pulse,shape,effort,increased,workout,gradually,mind,brisk,benefit,hour,activities,cycling,suppleness,feeling,enjoy,remember,easy,sport,strain,condition,fitter,blood,maximum,yoga,increasing,sedentary,period,athletes,form,fat,depression,pace,oxygen,amount,difficult,type,run ================================================== text_31 ------- I knew, however, that the top must remain thick. A simple 3/4in board is an anticlimax after all that architecture, and would ask ‘Why the fuss?’ A double thickness top adds the correct weight and importance. It is not, of course, 1–1/2in throughout. There is no need for that. Instead, in selecting the finest boards for the top, cut them over-length. After jointing and gluing (be careful where you stop and start your tongues), two pieces can be cut off to finish at four and a half inches each. These are mitred in to an extra front strip. A thinner strip runs between them at the back. This way, all the grain travels in the same direction and you do not store up shrinkage problems. They must all be wide enough to take the buttons which will hold down the top. Mould these pieces and glue them in place. ========== top,cut,bottom,holes,plastic,hole,piece,edge,metal,position,fit,remove,length,inside,base,left,surface,screws,wall,frame,wood,wire,cutting,tape,fitted,screw,strip,hold,glue,size,flat,time,edges,pieces,drill,plate,round,line,set,centre,joints,shape,square,mark,thin,fixing,strips,slightly,clean,steel,thick,diameter,required,panel,angle,removed,front,check,adhesive,hand,fitting,push,fixed,sharp,level,easy,material,joint,sections,simple,cover,half,method,section,smooth,larger,vertical,carefully,fix,sheet,rubber,ensure,knife,bolts,correct,horizontal,job,held,support,easier,firmly,hammer,thickness,width,board,easily,pin,bit,secure,lower ================================================== text_32 ------- The next three items cover different facets of designing for need. Martin, a student from another part of the college, a Higher Diploma course, reports back on the progress of the Garden Project (designing an accessible garden). The collaboration between the Design School and the multi-media group is, he says, working out quite well. There are some problems of communication and continuity (some multi-media students are full-time, some are part-time). However, there has been an interesting development. After initial experiments with raised beds, ramps and customised tools some lateral thinkers from both groups came up with the idea of a wheelchair with a seat which could be lowered to the plants at ground level. Models of the chair have already been built. Members of the group agree to document the project with photographs and notes and to continue it after the Design students graduate. ========== project,garden,students,university,student,gardens,projects,plants,time,model,gardening,development,college,study,library,seat,education,design,house,information,gardener,people,trees,level,staff,gardeners,team,schools,chair,provide,involved,skills,martin,science,multimedia,universities,planting,academic,school,lawn,models,major,plant,ideas,set,resources,campus,flowers,systems,degree,building,shrubs,summer,flower,designed,engineering,disabled,access,idea,system,world,courses,technology,seats,proposal,video,planning,digital,grass,space,planted,levels,grow,studies,computer,mature,equipment,research,successful,programme,nursery,scientific,success,roses,beds,potential,developed,growing,facilities,plan,disc,term,main,existing,graduates,department,fashion,including,engineer,centre ================================================== text_33 ------- Almost all accidents start with a simple error on the part of the pilot that leads to a chain of events, each of which makes the situation worse and an accident more and more difficult to avoid. The art of safe piloting is to learn to avoid the initial error whenever possible. But, if an error of judgement or a bad decision has been made, the vital thing is to recognise that, admit it and take immediate action to break the chain of events while a safe course of action is still possible. Forget the error or the cause of the problem and get on with correcting it and avoiding a worse situation. A similar situation occurs when soaring cross-country. Although you may get ridiculously low because of pressing on too hard, when, a few minutes later, you are back in the good conditions several thousand feet up, you must forget the wasted time and concentrate on flying normally. ========== events,time,error,event,errors,glider,pilot,speed,start,wind,people,ground,wing,flying,correct,landing,wrong,easy,rudder,difficult,pilots,check,aircraft,flight,launch,spin,stick,mistake,remember,gliders,occur,field,height,low,mistakes,experience,approach,nose,feet,situation,avoid,stall,stop,means,run,decide,result,extra,lift,position,job,happen,worth,feel,simply,wings,mind,normal,idea,matter,easier,makes,simple,bad,ahead,lot,close,hard,sort,quickly,correction,fly,cable,left,gliding,taking,safe,risk,change,climb,move,advice,forward,movement,hand,practice,easily,obvious,control,choose,prevent,straight,decision,link,thinking,leave,chance,recovery,money,air ================================================== text_34 ------- At death registration, registrars are instructed to make every effort to find out about the previous work experience of people, including those who might be unemployed or sick. But until changes in the registration of women's occupation were introduced in 1986 there was a major difference between men and women: ‘At the registration of the death of a child…the instructions to the registrars specify that the occupation…of a woman should not be recorded unless she has been in employment for most of her adult life.’ Bradshaw and Miller's work has shown that a substantial proportion of single mothers have never been in full time employment. A reasonable assumption to make on the basis of the instructions given to registrars before 1986, therefore, is that most of the deaths of children classified as unoccupied will have been registered by economically inactive lone mothers. ========== women,support,children,families,mothers,death,households,lone,people,household,parents,form,information,living,kin,family,details,time,parent,relatives,evidence,married,application,office,single,date,study,life,required,live,certificate,circumstances,person,copy,economic,address,age,care,employment,financial,found,patterns,send,die,studies,poverty,dependent,forms,income,dead,mother,register,copies,died,past,contact,registration,home,child,assistance,data,apply,provide,department,request,letter,couples,source,obtained,social,resources,provided,documents,including,elderly,arrangements,completed,telephone,return,days,received,period,suggests,receipt,complete,proportion,relative,applications,common,significant,personal,marriage,list,obtain,section,labour,receiving,wives,dying,money ================================================== text_35 ------- Developmental norms are an attempt to provide an indication of the ages at which one might expect ordinary children to show evidence of certain skills or abilities. Since children vary with respect to the ages at which they demonstrate any particular behaviour, norms represent an ‘average’ obtained from an examination of the developmental changes occurring in a large number of children. Data from a large sample will show the earliest age at which a child would be expected to gain control of a particular aspect of language, and the age by which 90 per cent or 95 per cent of non-handicapped children might be expected to show evidence of the same ability. If children who have already been diagnosed as suffering from some specific handicapping condition are included, the data will show the expected age delay before this group matches the performance of the normally developing children. ========== children,test,child,tests,parents,testing,cent,age,results,adult,scores,adults,tested,score,assessment,sample,performance,time,ability,items,measure,parent,validity,provide,found,childhood,school,family,intelligence,information,home,selection,study,average,measured,low,level,data,compared,basis,evidence,families,life,mother,mothers,based,response,mental,extent,positive,standard,aged,analysis,carried,reliability,development,measures,individual,difficulties,procedures,obtained,normal,depression,assessments,designed,procedure,methods,similar,result,studies,education,subject,care,disease,parental,scoring,assess,abilities,samples,research,social,shown,play,set,required,standardised,difficulty,scale,population,people,illness,pass,reliable,difficult,specific,expected,form,months,ages,babies ================================================== text_36 ------- Colborne conceded that he was fighting a losing battle; a battle against the entire social structure within the palace and the snobbery and jealousy of the Old Guard that surrounded the Prince. Colborne's departure was a shock to Charles. He was the one person within his household who had told him the truth; he had been his eyes and ears in the community, voiced the opinions of the man in the street. At times he had been his conscience too — when the Prince had lost his temper or been rude to someone, Colborne would write him a note and tell him so. He was devoted to the Prince, but he had served him for ten years and his wife had scarcely seen him. He was now fifty, and he felt she deserved more from her marriage. He left just a few days before Christmas in 1984. ========== prince,royal,princess,people,queen,time,battle,family,fight,life,palace,day,told,world,marriage,social,days,feel,public,hundred,friends,victory,wrong,win,lost,wife,won,love,fighting,bad,true,woman,night,duchess,husband,friend,fought,thousand,real,care,village,couple,mind,children,left,home,times,class,understand,words,community,private,struggle,hard,moment,mother,talk,war,ten,found,yesterday,house,live,stupid,sort,pounds,head,stand,close,book,worse,visit,rest,truth,hurt,hate,stop,person,defeat,meant,call,set,brought,angry,months,hope,duke,trouble,battles,simply,matter,twenty,eyes,happened,chance,power,women,reason,met,leave ================================================== text_37 ------- Most Third World countries are one-party states of one type or another and many are ruled through the routine exercise of physical force by the army and the police. This is not in the long term interests of global capitalism, and TNCs through their governments have been known to put pressure on dictators for the purpose of creating or restoring pluralist political systems. Capitalism depends on both the reality and the illusion of choice, but people are not fools and the global capitalist system offers many genuine choices. This creates many contradictions and paradoxes. In the previous chapter some general contradictions and paradoxes of economic, political and cultural-ideological TNPs were discussed. In this chapter the focus will be on the economic TNPs of transnational corporations, and the political TNPs of transnational capitalist classes in the Third World. The culture-ideology of consumerism in the Third World will be the subject of Chapter 5. ========== countries,world,chapter,force,development,economic,political,international,production,capitalist,global,developing,class,system,country,social,aid,power,society,capitalism,nations,capital,developed,forces,choice,labour,united,people,governments,real,government,means,section,economy,western,analysis,reality,time,discussed,book,military,control,relations,national,chapters,form,major,discussion,transnational,nature,terms,foreign,process,institutions,societies,main,poor,growth,resources,role,bureaucracy,industrial,elite,economies,army,study,life,south,politics,population,theory,concerned,aspects,forms,bank,classes,based,question,detail,rich,modern,public,human,systems,issues,west,subject,provide,account,consumption,choose,workers,attempt,trade,sense,basic,structure,level,view,attention ================================================== text_38 ------- The contexts of the other two examples is not recoverable since Kirchner does not give complete references. In both cases where the context is available however, the bare infinitive is used in reference to the undergoing of unpleasant treatment, where the speaker clearly wishes to stress the realization of a distasteful experience which was forced upon him. Substitution of the to infinitive gives a somewhat different impression: the events seem to be evoked in a much more resultative fashion — as the fact of having been made to scream, the state of Byron's feelings — that is, as an object of reflection rather than a recall of actual experience. While nothing definitive can be concluded from such meagre data, the fact that such examples do seem to suggest different impressions than the to infinitive to speakers of various dialects indicates that they deserve closer attention, especially in the light of a further examination of the passive voice. ========== infinitive,event,time,person,bare,verb,meaning,support,speaker,speech,verbs,evokes,sense,subject,fear,sentence,action,people,found,realization,form,dare,perception,relation,feelings,conceived,impression,evoke,feel,effect,express,represented,potential,voice,modal,book,means,life,occurrence,sentences,anger,experience,existence,language,result,examples,expressed,words,denoted,respect,movement,hand,potentiality,past,view,contexts,causation,type,implies,actual,emotions,construction,emotional,incidence,contrast,real,permission,simply,expresses,auxiliary,object,possibility,speak,feeling,denotes,similar,explanation,usage,prior,condition,context,relationship,direct,modals,evoked,position,beginning,mere,reaction,reference,negative,subsequent,idea,van,representation,love,dared,realized,analysis,referred ================================================== text_39 ------- ‘You're a cheerful bastard!’ I remarked, as we both ducked down into the trench. For the next few minutes I had to put up with Sid's reminiscences about how much worse it had been during the campaign in North Africa. The shelling continued until about midnight, then suddenly it stopped. The German guns then opened up but not to the same extent. They seemed further away, their shells passing over very high up and crashing into the area of the Orne canal. The German shelling lasted about twenty minutes, one gun continued to fire, starting with a clear crack, then the sound of the shell passing over, followed by the explosion as it hit the ground. I was somewhat fascinated by this German gun. I found myself listening for the distinct crack, then gazing up at the clear starry sky trying to follow the flight of the shell. ========== trench,time,piper,orchard,commando,brigade,road,village,commandos,wounded,positions,mortar,minutes,looked,front,evening,shelling,night,light,officer,trenches,direction,enemy,dead,jeep,short,left,day,close,ground,slit,hours,days,replied,mosquitoes,shells,bloody,trees,bagpipes,guns,remarked,attack,fire,distance,head,morning,gun,casualties,started,appeared,farm,entrance,lying,brigadier,entered,feet,house,shell,lot,yards,sleep,hour,officers,round,bastards,continued,passing,grass,burst,arrived,suddenly,yesterday,voice,sitting,dark,usual,past,shrapnel,team,half,darkness,pipes,couple,ten,rifle,bomb,explosions,sergeant,stopped,sound,wall,passed,doubt,sky,field,joined,moved,stood,fairly,south ================================================== text_40 ------- She'd been convinced all along that eventually she must lose him, that Marianne was right — some other attraction must inevitably draw him away. She hadn't changed her mind about that — a man such as Dane would always attract beautiful women, and Shannon could never hope to compete. But would the pain of losing him be any the less simply because she'd managed to hold him at bay? Eventually, probably sooner rather than later, he'd grow tired of waiting for Shannon, and then she'd be left with nothing, in any case. Though she could never let him know it, he already possessed her heart; if she were to give herself to him body and soul, at least the memories would be rich and ultimately fulfilling. Right now all she'd have to look back on would be frustration and longing suppressed by fear. ========== life,love,time,feel,feelings,fear,tears,loved,feeling,mother,woman,pain,anger,day,heart,told,world,mind,people,left,found,death,father,sense,child,lost,emotional,emotions,moment,home,understand,experience,grief,happy,past,eyes,hope,cry,days,friends,relationship,hurt,person,words,happened,women,bear,loss,guilt,real,sad,emotion,night,future,marriage,times,friend,true,change,wife,suffering,comfort,died,leave,brought,desire,live,angry,loving,deep,afraid,strong,hard,crying,lives,house,joy,family,body,strength,simply,despair,remember,return,suddenly,truth,memories,happiness,bed,sadness,husband,finally,terrible,thinking,knowing,difficult,believed,reason,deeply,looked ================================================== text_41 ------- There can be no doubt that for many women fear of loss is built into us by the way we've been reared. As children we may have been made to feel inadequate, silly or useless because we were never praised. In adult life, some may be submissive and ingratiating, expecting to be in the wrong, expecting to be discarded and unwanted. And surprise, surprise, they get just that sort of treatment. The only way to stop it happening, and therefore to stop the fear of it, is to develop self-esteem. Learn to be assertive, stand up for yourself and your own value. That way people will see you as even more lovable. That is what I mean by making fear your friend. If you are subject to these irrational fears, then use that fear as a trigger to change your attitude. It could revolutionise your life. ========== people,fear,feelings,feel,life,anger,emotions,emotional,feeling,person,love,time,experience,world,angry,relationship,sense,mind,emotion,learn,afraid,relationships,children,fears,understand,bad,lives,hurt,wrong,control,pain,childhood,change,past,experiences,real,true,beliefs,loss,negative,child,express,strong,ego,words,loving,personal,response,behaviour,guilt,makes,physical,women,simply,unconscious,adult,situation,hate,anxiety,reason,grow,told,process,create,form,live,parents,human,frustration,experienced,desire,difficult,conscious,talk,resentment,accept,hard,powerful,start,personality,feels,stop,reactions,partner,day,unable,choose,positive,truth,care,reality,expressed,woman,expression,hope,inside,stupid,bring,sort,rejection ================================================== text_42 ------- The prime document for EC statistics is now the VAT return. All who are engaged in intra-EC trade must now show thereon the total value of all goods dispatched to other EC customers and received from other EC suppliers in the special boxes provided on the return form. Where either category has exceeded £135,000 during 1992 further, more detailed information has to be submitted within the very strict time limit of ten working days after each month end. Known as the Intrastat system, the data can be submitted by a computerised medium but only if it meets Customs specification requirements and has prior approval. Specific details relating to each consignment are required but values and quantities may be aggregated where all other details are identical. Up to ten items of coded information are required comprising such details as the commodity reference of the goods, delivery terms, weight, method of transport and, for arrivals, the country of origin. ========== data,information,stock,form,customer,details,date,time,trade,office,application,cash,required,invoice,copy,vat,supplier,retailer,total,note,address,department,delivery,certificate,items,send,forms,discount,received,item,sales,register,statistics,section,record,registration,analysis,obtained,special,check,price,payment,days,cost,invoices,receipt,amount,copies,apply,request,contact,figures,person,ledger,system,period,letter,census,procedure,till,issued,exports,complete,requirements,documents,returned,completed,return,file,provided,telephone,registered,including,day,list,local,applications,provide,records,entry,countries,imports,means,table,month,obtain,credit,control,warehouse,products,notice,relevant,include,suppliers,profit,customs,arrangements,staff,written,product ================================================== text_43 ------- Back home, the observation would have been no less apt. In the years leading up to the First World War the Hooligan embarked on a remarkable career, appearing in name if not in person before numerous governmental and semi-official bodies of enquiry. He loomed large in the apocalyptic discourse surrounding the fears of racial decline and physical inefficiency. He figured centrally in the Edwardian era's deliberations on the ‘boy labour’ question. He would crop up repeatedly in the anxious preoccupation with the demoralising influence of popular amusements, the collapse of ‘fair play’ sportsmanship, and the allegations of excessive ‘freedom’and ‘affluence’ that were levelled against the young. The name of the Hooligan, in fact, provided a crystallising focus for any number of overlapping anxieties associated with imperial decline, military incapacity, the erosion of social discipline and moral authority, the eclipse of family life, and what was feared to be the death rattle of ‘Old England’. ========== football,fans,war,violence,boys,hooligans,hooliganism,youth,hooligan,street,social,disorder,time,gang,gangs,police,behaviour,economic,people,world,supporters,political,crowd,life,soccer,society,crime,youths,respectable,rowdies,decline,streets,period,public,violent,terraces,matches,found,moral,common,fighting,rival,fights,juvenile,times,contemporary,traditional,government,family,history,game,delinquency,fight,trouble,late,power,territory,fears,evidence,economy,national,riots,class,fan,ground,panic,forms,led,set,questions,question,crowds,culture,sense,century,peace,popular,crisis,media,local,spectator,grounds,boy,town,united,authority,home,oxford,remained,aggro,major,death,postwar,brought,nation,road,bank,excitement,change,phenomenon ================================================== text_44 ------- In fact, as I soon discovered, these ruins are inhabited. I met the old lady as I was walking down a steep path out of the village. She was struggling up, bent under a heavy sack. We greeted each other. The skin of her face hung in purple folds and the old eyes were blurred with cataract. When I offered to carry her sack she waved me aside. Who was this impertinent stranger eyeing her baggage? We moved on up to her tumbledown tower on the last crag of the village. At the base was a terrace with one stool on it. Before us stretched an enormous view of mountain, promontory and shimmering sea. From my pack I offered her an apple, the only food I had. She dismissed it with a regal gesture. Then I saw her toothless gums. I left her in peace with her bundle, her stool and her majestic view. ========== sun,sky,bag,white,looked,trees,green,blue,day,eyes,dark,light,air,black,water,sir,time,stood,grass,hair,morning,bags,left,red,grey,round,sat,house,walked,head,master,bright,village,rose,fields,found,hand,lay,wind,night,sea,brown,clouds,summer,hills,days,lady,beautiful,pale,set,warm,home,feet,stone,teeth,hot,river,hands,heat,evening,john,leaves,woman,road,golden,brought,cloud,deep,ground,past,silver,beneath,edge,cold,sunlight,tall,plastic,gold,earth,huge,slowly,yellow,afternoon,hill,people,door,tree,forest,paper,cool,birds,watched,mist,low,flowers,valley,thin,smiled,life,wall ================================================== text_45 ------- Such integration can be largely formal; in Lesotho, for instance, the evidence of real integration in between Mathematics and Science is very slight. On the other hand it may represent a genuine attempt by specialists in related subjects to sit down together and plan a programme which allows for separate activities but suggests common themes and provides examples of integrated lessons as in the Nigerian Cultural and Creative Art syllabus. Yet again it may be the product of basic rethinking and true integration founded on new objectives and a fresh approach as in the Social Studies syllabus now under development in Sierra Leone where an integrated programme with significant regional variations is being planned in a series of central and local workshops and where a special series of booklets on skills development (e.g. map making, note taking skills, creative skills) is being produced for teachers. ========== curriculum,pupils,school,teachers,education,schools,national,teaching,learning,assessment,skills,mathematics,development,children,regional,teacher,subjects,attainment,subject,primary,study,region,time,differences,secondary,range,science,pupil,content,educational,programmes,individual,regions,level,knowledge,local,art,process,activities,programme,experience,levels,information,structure,taught,courses,form,communication,innovation,common,people,ideas,classroom,opportunities,targets,thinking,key,creative,achievement,language,variety,based,media,develop,materials,terms,planning,core,set,understanding,approach,similar,aims,central,ability,report,features,technology,syllabus,pattern,emphasis,aspects,stage,elements,studies,social,plan,curricular,training,framework,statements,progress,history,age,patterns,basic,including,wide,creativity,arts ================================================== text_46 ------- Regarding access to health care, we meet the fact that women usually live longer than men. This is one area of life in which women have a definite advantage! It would appear that access to the health service is reasonably equitable between men and women, and that women's longer lives should not be attributed to prejudice against men in the health sector! However, some writers have suggested that the diseases commonly found among men are treated with greater concern and more expensive medical treatment than those more commonly found among women. For instance, attention has recently been drawn to the inadequate provision of screening for cervical cancer despite the fact that this service could provide the means of identifying early forms of the disease before it reaches its incurable and lethal stage. (More discussion of women and health can be found in chapter 9, section 9.5.) ========== health,women,care,cancer,medical,services,male,woman,people,female,chapter,public,disease,education,social,patients,service,national,stage,illness,feminist,time,life,tumour,family,role,children,medicine,private,primary,tumours,healthy,ill,promotion,poor,conditions,programmes,population,development,doctors,study,mortality,found,prevention,community,workers,research,attention,sector,section,gender,sex,term,major,issues,society,main,feminists,policy,screening,terms,book,status,living,feminism,concerned,aspects,diseases,practice,treatment,quality,authority,discussed,clinics,government,analysis,importance,world,studies,risk,cell,mothers,provide,chapters,cancers,programme,process,discussion,improve,improved,information,sexual,preventive,support,report,factors,common,access,recently,power ================================================== text_47 ------- The Dinner or Luncheon Party: Whatever time of day it is, this is most likely to mean inviting a group of people over for a ‘sit-down’ meal. The grandness of the meal, and how much of it you pay for, depends upon the expectations of yourself and your guests and perhaps their relationship to you. If, say, you are a young person — student or worker — who has invited over friends of the same age, they will probably expect to bring a bottle of wine with them. In fact, most friends, of any age, would bring a bottle of something — unless the dinner party was very grand. Relatives often seem to feel that they do not need to bring a contribution, unless, of course, you are young, living alone for the first time and being visited by your mother, in which case she will probably bring a month's supply of food and wash up for you as well! ========== people,party,dinner,evening,time,guests,friends,home,day,night,money,house,age,family,hotel,life,table,mother,invited,person,week,social,wife,lunch,met,found,arrived,parties,pay,lady,days,guest,food,friend,ladies,told,drink,talk,feel,champagne,round,occasion,meet,left,meal,late,daughter,enjoyed,wine,conversation,spent,host,company,elderly,afternoon,visit,husband,hall,invitation,morning,brought,paid,job,counselling,care,dancing,tea,drinks,glass,parents,father,children,pleasure,happy,experience,hospitality,feelings,girl,restaurant,private,staff,dance,couple,support,relationship,special,living,women,difficult,arranged,live,personal,lives,counsellor,buy,dining,cost,hour,spend,enjoy ================================================== text_48 ------- The implementation of care management in April could rapidly illustrate how the admirable intentions of the government's community care policy might founder on the unintended consequences of more powerful forces and contradictions. Firstly, although the transfer of social security funds will allow more needs driven services, it will also cash limit expenditure. Secondly, this transfer punishes local authorities with few residential care homes and cuts off money for future expansion. Thirdly, the directive that care managers should not themselves give direct care runs counter to the core of good social work practice and creates a new corps of care administrators, thereby reducing the number of staff available to give direct care. Fourthly, no central guidance has emerged on how to coordinate at the local level, care management, the care programme approach, and hospital discharge procedures, thus inviting triplication of planning effort. ========== care,social,services,community,health,service,people,local,workers,expenditure,government,spending,budget,assessment,authorities,residential,policy,public,support,worker,management,effect,practice,authority,clients,effects,resources,client,mental,staff,provision,development,department,approach,planning,agencies,individual,carers,voluntary,time,users,cuts,provide,departments,home,money,professionals,system,team,sector,set,elderly,professional,policies,key,national,teams,role,provided,act,day,level,welfare,direct,plans,training,information,managers,statutory,hospital,research,central,increase,homes,range,practitioners,billion,specialist,plan,financial,arrangements,specific,develop,implementation,programme,process,budgets,finance,assessments,doh,issues,manager,result,person,control,responsibility,joint,monitoring,change,real ================================================== text_49 ------- It was a great discovery. But it was utterly disastrous for classical physics. An electron encircling a nucleus is continuously subject to acceleration as its velocity keeps on changing direction. (Acceleration is just the rate of change of velocity.) It is an inexorable consequence of classical physics that such an accelerating electron radiates off some of its energy at a frequency corresponding to the frequency of the electron's circulation. This causes the electron to move closer to the nucleus and changes the frequency. The radiation loss continues. In other words, a classical "solar system" atom under electromagnetic forces is nothing like the actual solar system held together by gravitational forces. The atom would be unstable, as its electrons spiralled ever closer to the nucleus, and it would emit its dying radiation in a band of frequencies with no trace of discreteness. The nuclear atom dealt the coup de grâce to classical physics. ========== particles,quantum,theory,electron,particle,light,energy,physics,mechanics,electrons,waves,matter,called,time,mass,proton,electromagnetic,classical,change,wave,principle,atoms,experiment,sound,physicists,atom,experiments,position,energies,theories,quarks,nucleus,physical,decay,weak,nuclear,system,momentum,results,protons,photon,interactions,atomic,uncertainty,found,measurement,spin,equation,produce,radiation,force,result,means,forces,motion,world,velocity,bat,calculations,unified,speed,mathematical,objects,effect,fundamental,times,idea,similar,frequency,physicist,relativity,wavelength,terms,properties,bats,single,field,theoretical,produced,measure,range,beam,predicted,charged,photons,experimental,amount,direction,detect,rate,mechanical,probability,universe,slit,form,strong,polarisation,frequencies,gravity,predictions ================================================== ```python vocabulary = corpus_data['vocabulary'] #open(cache_fullpath('bnc_vocab_49328.txt')).read().split() vocab = datautils.Vocab(vocabulary) recalled_words = sorted(set( pandas.read_pickle(cache_fullpath('brisbane_06b643a_recall_results.pkl'))['word'].values)\ .intersection(vocabulary) ) ``` ```python predictive_probabilities = [] text_names = sorted(posterior_predictions.keys(), key=lambda arg: int(arg.split('_')[1])) for text_name in text_names: f = [] for word in recalled_words: f.append(posterior_predictions[text_name][vocab.word2index[word]]) predictive_probabilities.append(f) predictive_probabilities = numpy.array(predictive_probabilities) predictive_probabilities = numpy.c_[predictive_probabilities, 1-predictive_probabilities.sum(1)] header = ','.join(recalled_words + ['ALTERNATIVE_WORD']) M = [header] for i,f in enumerate(predictive_probabilities): M.append(text_names[i] + ',' + ','.join(map(str, f))) M = '\n'.join(M) posterior_predictions_of_recalled_words = 'posterior_predictions_of_recalled_words.csv' ``` ```python with open(cache_fullpath(posterior_predictions_of_recalled_words), 'w') as f: f.write(M) # Verify the integrity of the exported csv file. assert utils.checksum(cache_fullpath(posterior_predictions_of_recalled_words))\ == 'd8a4155b3e8d04331ddf6c791188653b4c9612f8d395ecca286bde6983a28743' ``` ```python V = {v:i for i, v in enumerate(corpus_data['vocabulary'])} posterior_predictions_demo_fname = 'hdptm_201117172636_2290_posterior_predictions_demo.csv' def get_posterior_predictions(K=100): pp = [] for text_id in sorted(posterior_predictions.keys(), key=lambda args: int(args.split('_')[1])): phi = posterior_predictions[text_id] words_in_text = topicmodels.text_to_words(texts[text_id], V) indices = phi.argsort()[::-1] for index in indices[:K]: pp.extend([(text_id, corpus_data['vocabulary'][index], phi[index], corpus_data['vocabulary'][index] in words_in_text)]) return pp pandas.DataFrame(get_posterior_predictions(), columns = ['text', 'item', 'probability', 'present']).to_csv( cache_fullpath(posterior_predictions_demo_fname), index=False ) assert utils.checksum(cache_fullpath(posterior_predictions_demo_fname))\ == '8cc6b290807e52fdb71b950a552955d679f0331fa45811f0f0d3dd9884d29c2f' ```
Module Playground1. Inductive nat : Type := | O : nat | S : nat -> nat. Definition pred (n : nat) : nat := match n with | O => O | S n' => n' end. End Playground1. Definition minustwo (n : nat) : nat := match n with | O => O | S O => O | S (S n') => n' end. Check (S (S (S (S O)))). Eval simpl in (minustwo 4). Check S. Check pred. Check minustwo. Fixpoint evenb (n:nat) : bool := match n with | O => true | S O => false | S (S n') => evenb n' end. Definition oddb (n:nat) : bool := negb (evenb n). Example test_oddb1: (oddb (S O)) = true. Proof. simpl. reflexivity. Qed. Example test_oddb2: (oddb (S (S (S (S O))))) = false. Proof. simpl. reflexivity. Qed. Module Playground2. Fixpoint plus (n : nat) (m : nat) : nat := match n with | O => m | S n' => S (plus n' m) end. Eval simpl in (plus (S (S (S O))) (S (S O))). Fixpoint mult (n m : nat) : nat := match n with | O => O | S n' => plus m (mult n' m) end. Eval simpl in (mult 5 6). Fixpoint minus (n m:nat) : nat := match n, m with | O , _ => O | S _ , O => n | S n', S m' => minus n' m' end. End Playground2. Fixpoint exp (base power : nat) : nat := match power with | O => S O | S p => mult base (exp base p) end. Example test_mult1: (mult 3 3) = 9. Proof. simpl. reflexivity. Qed. Fixpoint factorial (n:nat) : nat := match n with | 0 => 1 | S p => mult n (factorial p) end. Example test_factorial1: (factorial 3) = 6. Proof. simpl. reflexivity. Qed. Example test_factorial2: (factorial 5) = (mult 10 12). Proof. simpl. reflexivity. Qed. Notation "x + y" := (plus x y) (at level 50, left associativity) : nat_scope. Notation "x - y" := (minus x y) (at level 50, left associativity) : nat_scope. Notation "x * y" := (mult x y) (at level 40, left associativity) : nat_scope. Check ((0 + 1) + 1). Fixpoint beq_nat (n m : nat) : bool := match n with | O => match m with | O => true | S m' => false end | S n' => match m with | O => false | S m' => beq_nat n' m' end end. Fixpoint ble_nat (n m : nat) : bool := match n with | O => true | S n' => match m with | O => false | S m' => ble_nat n' m' end end. Example test_ble_nat1: (ble_nat 2 2) = true. Proof. simpl. reflexivity. Qed. Example test_ble_nat2: (ble_nat 2 4) = true. Proof. simpl. reflexivity. Qed. Example test_ble_nat3: (ble_nat 4 2) = false. Proof. simpl. reflexivity. Qed. Definition blt_nat (n m : nat) : bool := andb (ble_nat n m) (notb (beq_nat n m)). Example test_blt_nat1: (blt_nat 2 2) = false. Proof. simpl. reflexivity. Qed. Example test_blt_nat2: (blt_nat 2 4) = true. Proof. simpl. reflexivity. Qed. Example test_blt_nat3: (blt_nat 4 2) = false. Proof. simpl. reflexivity. Qed.
Definition inj{X Y}(f : X -> Y) := forall x x', f x = f x' -> x = x'. Definition surj{X Y}(f : X -> Y) := forall y, {x : X & f x = y}. Definition ded_fin(X : Set) := forall f : X -> X, inj f -> surj f. Section df_inh_cancel_sgroups. Variable X : Set. Variable x0 : X. Variable m : X -> X -> X. Infix "*" := m. Hypothesis X_df : ded_fin X. Hypothesis assoc : forall x y z, x * (y * z) = (x * y) * z. Hypothesis l_cancel : forall x y z, x * y = x * z -> y = z. Hypothesis r_cancel : forall x y z, y * x = z * x -> y = z. Lemma l_mult_inj : forall x, inj (m x). Proof. intros x y z H. exact (l_cancel _ _ _ H). Qed. Lemma r_mult_inj : forall x, inj (fun y => m y x). Proof. intros x y z H. exact (r_cancel _ _ _ H). Qed. Lemma r_eq_solve : forall a b, {x : X & a * x = b}. Proof. intros. destruct (X_df (m a) (l_mult_inj a) b). exists x; exact e. Qed. Lemma l_eq_solve : forall a b, {x : X & x * a = b}. Proof. intros. destruct (X_df (fun y => m y a) (r_mult_inj a) b). exists x; exact e. Qed. (* the identity *) Definition e : X := projT1 (l_eq_solve x0 x0). Lemma l_x0_id : e * x0 = x0. Proof. unfold e. destruct (l_eq_solve x0 x0). simpl. exact e0. Qed. Theorem l_id : forall x, e * x = x. Proof. intro. destruct (r_eq_solve x0 x) as [y Hy]. rewrite <- Hy. rewrite assoc. rewrite l_x0_id. reflexivity. Qed. Theorem r_id : forall x, x * e = x. Proof. intro. apply (r_cancel e). rewrite <- assoc. rewrite l_id. reflexivity. Qed. (* the inverse operations *) Definition inv : X -> X := fun x => projT1 (l_eq_solve x e). Theorem l_inv : forall x, (inv x) * x = e. Proof. intro. unfold inv. destruct (l_eq_solve x e). simpl. exact e0. Qed. Theorem r_inv : forall x, x * (inv x) = e. Proof. intro. apply (r_cancel x). rewrite <- assoc. rewrite l_inv. rewrite l_id, r_id. reflexivity. Qed. End df_inh_cancel_sgroups.
State Before: α : Type u_1 β : Type ?u.222676 ι : Type ?u.222679 G : Type ?u.222682 M : Type u_2 N : Type ?u.222688 inst✝¹ : CommMonoid M inst✝ : CommMonoid N f g : α → M a b : α s t : Set α hf : EqOn f 1 s ⊢ (∏ᶠ (i : α) (_ : i ∈ s), f i) = 1 State After: α : Type u_1 β : Type ?u.222676 ι : Type ?u.222679 G : Type ?u.222682 M : Type u_2 N : Type ?u.222688 inst✝¹ : CommMonoid M inst✝ : CommMonoid N f g : α → M a b : α s t : Set α hf : EqOn f 1 s ⊢ (∏ᶠ (i : α) (_ : i ∈ s), f i) = ∏ᶠ (i : α) (_ : i ∈ s), 1 Tactic: rw [← finprod_mem_one s] State Before: α : Type u_1 β : Type ?u.222676 ι : Type ?u.222679 G : Type ?u.222682 M : Type u_2 N : Type ?u.222688 inst✝¹ : CommMonoid M inst✝ : CommMonoid N f g : α → M a b : α s t : Set α hf : EqOn f 1 s ⊢ (∏ᶠ (i : α) (_ : i ∈ s), f i) = ∏ᶠ (i : α) (_ : i ∈ s), 1 State After: no goals Tactic: exact finprod_mem_congr rfl hf
# __ ___ # / |/ /___ _______________ # / /|_/ / __ `/ ___/ ___/ __ \ # / / / / /_/ / / / /__/ /_/ / # /_/ /_/\__,_/_/ \___/\____/ # _ ___ __ __ ___ # | | / (_)____/ /_/ /_ / (_)___ # | | /| / / / ___/ __/ __ \/ / / __ \ # | |/ |/ / / / / /_/ / / / / / / / / # |__/|__/_/_/ \__/_/ /_/_/_/_/ /_/------------------------------------------------------------------------- #S2876507 # Running instructions: Press Ctrl+A, then Ctrl+Enter. "plyr" package must be installed. # If you zoom in on the graph, drag the window a bit to the right, until the plots are roughly of quadratic shape (nicer that way). #sets working directory to source file location (RSTUDIO ONLY! comment out if not rstudio.) library("rstudioapi") library("plyr") setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) source("actr_functions.r") source("plotting_functions.r") # exp_dict according to Taatgen, van Rijn and Anderson (2004) exp_dict <- list( tick_increment = 1.1, # (default: 1.1) b = sample(0.0125:0.0126, 1, replace = TRUE), # (default 0.015) tick_base = 11, # (default: 11) decay = -1.5, #decay parameter, (default: 0.5) amount_subjects = 5, # subjects per interval amount_trials = 50, # amount of trials per subject and per interval (default: 50) amount_training = 5, subject_data = data.frame(matrix(ncol = 7, nrow = 0)), #tmp data storage parm_t = 60, # (default: 1) point_gain = 5, # (default: 5) no_penalty = 0, low_penalty = -5, # (default: -5) high_penalty = -30, # (default: -30) yellowDot_time = sample(1000:2000, 1, replace = TRUE), base_interval = 700, # (default: 750) sample(725:775, 1, replace = TRUE) leeway = 0.15, #percentage of space around base interval that counts as correct (default: 0.15) # adaption_rate = 50, condition_order = c(1, 2, 3, 1) ) experiment_setup <- function(current_subject) #I want setup the experiment parameters for each subject, once { list(real_time = 0, #this is the subjects objective time in ms. this will stay with the subject for the duration of the experiment subject_nr = current_subject, points = 0, recalled_interval = 0, trialnr = 0, DecMem = matrix(NA, 100, 500), cond = 0 ) } trial <- function(current_condition, subject_setup) { subject_setup$cond <- subject_setup$cond + 1 if(current_condition == 1){ penalty <- exp_dict$no_penalty} else if(current_condition == 2){ penalty <- exp_dict$low_penalty} else if(current_condition == 3){ penalty <- exp_dict$high_penalty} for (.. in seq(1, exp_dict$amount_trials)) #amount_trials (default: 50) { subject_setup$trialnr <- subject_setup$trialnr + 1 ts <- exp_dict$base_interval subject_setup$real_time <- subject_setup$real_time + exp_dict$yellowDot_time #time yellow dot flashes sample_int_pulse <- msecs_to_pulses(ts) # the sample interval gets converted into pulses subject_setup <- encounter_add(subject_setup, sample_int_pulse) blended_response <- blending(subject_setup) rt <- pulse_to_msces(blended_response) if (rt > (1 - exp_dict$leeway)*exp_dict$base_interval & rt < (1 + exp_dict$leeway)*exp_dict$base_interval) { correct <- 1 points_increment <- exp_dict$point_gain subject_setup <- encounter_add(subject_setup, (25)) } else { correct <- 0 points_increment <- exp_dict$point_gain + penalty subject_setup <- encounter_add(subject_setup, (13 - penalty*1.5)) } subject_setup$points <- subject_setup$points + points_increment subject_setup$subject_data <- rbind(subject_setup$subject_data, c(subject_setup$subject_nr, subject_setup$trialnr, subject_setup$cond, correct, subject_setup$points, points_increment, rt)) } subject_setup } # training <- function(subject_setup) # { # subject_setup$recalled_interval <- 750 # for (.. in seq(1, exp_dict$amount_training)) #training was 5 times exposition to 750 ms interval # { # train_pulses <- msecs_to_pulses(subject_setup$recalled_interval) # subject_setup <- encounter_add(subject_setup, train_pulses) # blended_training <- blending(subject_setup) # subject_setup$recalled_interval <- pulse_to_msces(blended_training) # } # subject_setup # } # adaption <- function(subject_setup, penalty) # { # adaption_pulses <- msecs_to_pulses(subject_setup$recalled_interval) # # subject_setup$recalled_interval <- pulse_to_msces(subject_setup$recalled_interval + adaption) # # subject_setup # } main <- function() { simulated_data <- data.frame(matrix(ncol = 7, nrow = 0)) #main data storage for (.. in seq(1, exp_dict$amount_subjects)) #loop for subjects { current_subject <- .. subject_setup <- experiment_setup(current_subject) #initializing current subject for (.. in exp_dict$condition_order) # loop containing all conditions { current_condition <- .. # subject_setup <- training(current_condition) subject_setup <- trial(current_condition, subject_setup) #here the trials happen (another loop inside) } simulated_data <- rbind(simulated_data, subject_setup$subject_data) } colnames(simulated_data) <- c("Subject_Nr ", "Trial_Nr", "Cond", "Correct", "Points", "Points_Increment", "Rt") simulated_data plotdat <- ddply(simulated_data, c("Trial_Nr", "Cond"), summarise, mRT = mean(Rt), sdRT = sd(Rt), mScore = mean(Points), mCurPoints = mean(Points_Increment), mCorrect = mean(Correct)) plotdat print("Run successfull!") # rt_plot <- plot_rt(plotdat) #sd_plot <- plot_sd(plotdat) # mScore_plot <- plot_mScore(plotdat) # mCurPoints_plot <- plot_mCurPoints(plotdat) #mCorrect_plot <- plot_mCorrect(plotdat) } main()
import data.real.basic /- Tactics you may consider -intro -rw -apply -exact -cal -dsimp: definition simplification -/ variables (f g : ℝ → ℝ) #check mul_assoc #check neg_mul_comm #check neg_mul_neg #check neg_eq_neg_one_mul -- BEGIN def fn_even (f : ℝ → ℝ) : Prop := ∀ x, f x = f (-x) def fn_odd (f : ℝ → ℝ) : Prop := ∀ x, f x = - f (-x) example (ef : fn_even f) (og : fn_odd g) : fn_odd (λ x, f x * g x) := begin intro x, dsimp, rw [ef, og], rw ← neg_mul_comm, rw neg_eq_neg_one_mul, rw mul_assoc, rw ← neg_eq_neg_one_mul, end example (ef : fn_even f) (eg : fn_even g) : fn_even (λ x, f x + g x) := begin intro x, calc (λ x, f x + g x) x = f x + g x : rfl ... = f (-x) + g (-x) : by rw [ef, eg] end example (of : fn_odd f) (og : fn_odd g) : fn_even (λ x, f x * g x) := begin intro x, calc (λ x, f x * g x) x = f x * g x : rfl ... = - f (-x) * - g(-x) : by rw [of, og] ... = f (-x) * g(-x) : by rw neg_mul_neg, end -- END
# GraphHopper Directions API # # You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various constraints like time window and capacity restrictions. Also it is possible to get all distances between all locations with our fast Matrix API. # # OpenAPI spec version: 1.0.0 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' Routing Class #' #' @field calc_points #' @field consider_traffic #' @field network_data_provider #' @field fail_fast #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export Routing <- R6::R6Class( 'Routing', public = list( `calc_points` = NULL, `consider_traffic` = NULL, `network_data_provider` = NULL, `fail_fast` = NULL, initialize = function(`calc_points`, `consider_traffic`, `network_data_provider`, `fail_fast`){ if (!missing(`calc_points`)) { self$`calc_points` <- `calc_points` } if (!missing(`consider_traffic`)) { self$`consider_traffic` <- `consider_traffic` } if (!missing(`network_data_provider`)) { stopifnot(is.character(`network_data_provider`), length(`network_data_provider`) == 1) self$`network_data_provider` <- `network_data_provider` } if (!missing(`fail_fast`)) { self$`fail_fast` <- `fail_fast` } }, toJSON = function() { RoutingObject <- list() if (!is.null(self$`calc_points`)) { RoutingObject[['calc_points']] <- self$`calc_points` } if (!is.null(self$`consider_traffic`)) { RoutingObject[['consider_traffic']] <- self$`consider_traffic` } if (!is.null(self$`network_data_provider`)) { RoutingObject[['network_data_provider']] <- self$`network_data_provider` } if (!is.null(self$`fail_fast`)) { RoutingObject[['fail_fast']] <- self$`fail_fast` } RoutingObject }, fromJSON = function(RoutingJson) { RoutingObject <- jsonlite::fromJSON(RoutingJson) if (!is.null(RoutingObject$`calc_points`)) { self$`calc_points` <- RoutingObject$`calc_points` } if (!is.null(RoutingObject$`consider_traffic`)) { self$`consider_traffic` <- RoutingObject$`consider_traffic` } if (!is.null(RoutingObject$`network_data_provider`)) { self$`network_data_provider` <- RoutingObject$`network_data_provider` } if (!is.null(RoutingObject$`fail_fast`)) { self$`fail_fast` <- RoutingObject$`fail_fast` } }, toJSONString = function() { sprintf( '{ "calc_points": %s, "consider_traffic": %s, "network_data_provider": %s, "fail_fast": %s }', self$`calc_points`, self$`consider_traffic`, self$`network_data_provider`, self$`fail_fast` ) }, fromJSONString = function(RoutingJson) { RoutingObject <- jsonlite::fromJSON(RoutingJson) self$`calc_points` <- RoutingObject$`calc_points` self$`consider_traffic` <- RoutingObject$`consider_traffic` self$`network_data_provider` <- RoutingObject$`network_data_provider` self$`fail_fast` <- RoutingObject$`fail_fast` } ) )
module Data.Collection.Inclusion where open import Data.Collection.Equivalence open import Data.Collection.Core open import Function using (id; _∘_) open import Function.Equivalence using (equivalence) open import Level using (Level; suc; zero) open import Relation.Unary hiding (_⇒_) open import Relation.Binary open import Relation.Binary.PropositionalEquality ≋⇒⊆ : _≋_ ⇒ _⊆_ ≋⇒⊆ P≋Q ∈P = nach P≋Q ∈P ⊆-Transitive : ∀ {a ℓ} {A : Set a} → Transitive {_} {_} {Pred A ℓ} _⊆_ ⊆-Transitive P⊆Q Q⊆R = Q⊆R ∘ P⊆Q ⊆-IsPreorder : IsPreorder _≋_ _⊆_ ⊆-IsPreorder = record { isEquivalence = ≋-IsEquivalence ; reflexive = ≋⇒⊆ ; trans = ⊆-Transitive } ⊆-Preorder : Preorder _ _ _ ⊆-Preorder = record { Carrier = Pred String zero ; _≈_ = _≋_ ; _∼_ = _⊆_ ; isPreorder = ⊆-IsPreorder } ⊆-Antisymmetric : Antisymmetric _≋_ _⊆_ ⊆-Antisymmetric P⊆Q Q⊆P = equivalence P⊆Q Q⊆P ⊆-IsPartialOrder : IsPartialOrder _≋_ _⊆_ ⊆-IsPartialOrder = record { isPreorder = ⊆-IsPreorder ; antisym = ⊆-Antisymmetric } ⊆-Poset : Poset _ _ _ ⊆-Poset = record { Carrier = Pred String zero ; _≈_ = _≋_ ; _≤_ = _⊆_ ; isPartialOrder = ⊆-IsPartialOrder } -------------------------------------------------------------------------------- -- Conditional Inclusion -------------------------------------------------------------------------------- _⊆[_]_ : ∀ {a ℓ₀ ℓ₁ ℓ₂} {A : Set a} → Pred A ℓ₀ → Pred A ℓ₁ → Pred A ℓ₂ → Set _ A ⊆[ P ] B = ∀ {x} → x ∈ P → x ∈ A → x ∈ B _⊈[_]_ : ∀ {a ℓ₀ ℓ₁ ℓ₂} {A : Set a} → Pred A ℓ₀ → Pred A ℓ₁ → Pred A ℓ₂ → Set _ A ⊈[ P ] B = ∀ {x} → x ∈ P → x ∉ A → x ∉ B -- prefix version of _⊆[_]_, with the predicate being the first argument [_]⊆ : ∀ {a ℓ₀ ℓ₁ ℓ₂} {A : Set a} → Pred A ℓ₁ → Pred A ℓ₀ → Pred A ℓ₂ → Set _ [ P ]⊆ A B = A ⊆[ P ] B ≋[]⇒⊆[] : ∀ {a} {P : Pred Element a} → [ P ]≋ ⇒ [ P ]⊆ ≋[]⇒⊆[] A≋B = nach ∘ A≋B ⊆[]-Transitive : ∀ {a ℓ} {P : Pred Element a} → Transitive {_} {_} {Pred String ℓ} [ P ]⊆ ⊆[]-Transitive A⊆B B⊆C ∈P = B⊆C ∈P ∘ A⊆B ∈P ⊆[]-IsPreorder : ∀ {a} {P : Pred Element a} → IsPreorder [ P ]≋ [ P ]⊆ ⊆[]-IsPreorder = record { isEquivalence = ≋[]-IsEquivalence ; reflexive = ≋[]⇒⊆[] ; trans = ⊆[]-Transitive } ⊆[]-Preorder : ∀ {a} {P : Pred Element a} → Preorder _ _ _ ⊆[]-Preorder {_} {P} = record { Carrier = Pred String zero ; _≈_ = [ P ]≋ ; _∼_ = [ P ]⊆ ; isPreorder = ⊆[]-IsPreorder } ⊆[]-Antisymmetric : ∀ {a} {P : Pred Element a} → Antisymmetric [ P ]≋ [ P ]⊆ ⊆[]-Antisymmetric P⊆Q Q⊆P ∈P = equivalence (P⊆Q ∈P) (Q⊆P ∈P) ⊆[]-IsPartialOrder : ∀ {a} {P : Pred Element a} → IsPartialOrder [ P ]≋ [ P ]⊆ ⊆[]-IsPartialOrder = record { isPreorder = ⊆[]-IsPreorder ; antisym = ⊆[]-Antisymmetric } ⊆[]-Poset : ∀ {a} {P : Pred Element a} → Poset _ _ _ ⊆[]-Poset {_} {P} = record { Carrier = Pred String zero ; _≈_ = [ P ]≋ ; _≤_ = [ P ]⊆ ; isPartialOrder = ⊆[]-IsPartialOrder }
%% isclose % Below is a demonstration of the features of the |isclose| function %% clear; close all; clc; %% Syntax % |L=isclose(A,B,toleranceLevel);| %% Description % UNDOCUMENTED %% Examples % %% % % <<gibbVerySmall.gif>> % % _*GIBBON*_ % <www.gibboncode.org> % % _Kevin Mattheus Moerman_, <[email protected]> %% % _*GIBBON footer text*_ % % License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE> % % GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for % image segmentation, image-based modeling, meshing, and finite element % analysis. % % Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <math.h> #include <gsl/gsl_linalg.h> #include "getNextIterate.h" void getNextIterate(const grid *grd, const bool eos_func, const wksp *w #if AA_M > 0 , const unsigned long itCount, const long nHist, double *residMax #endif ) { long i; #if AA_M > 0 long j, mk, colptr; gsl_matrix *resid; gsl_vector *tau, *llsresid, *aa_wgts, *constraint; gsl_vector_view constraint_view; #endif #if AA_M == 0 /* No Anderson acceleration, so just move temporaries into next guess */ for (i=0; i<grd->nr; i++) { w->colNew[i] = w->colTmp[i]; w->presNew_g[i+1] = gsl_vector_get(w->presTmp_g, i+1); if (eos_func==1) w->eIntNew[i] = w->eIntTmp[i]; } #else /* Anderson acceleration code */ /* Set up pointers */ mk = itCount < AA_M+1 ? itCount : AA_M+1; colptr = (itCount - 1) % (AA_M+1); /* Store the current guesses in the history array */ for (i=0; i<grd->nr; i++) { w->colHist[i + colptr*grd->nr] = w->colTmp[i]; w->presHist[i + colptr*grd->nr] = gsl_vector_get(w->presTmp_g, i+1); if (eos_func) w->eIntHist[i + colptr*grd->nr] = w->eIntTmp[i]; } /* Compute residuals and store them in the residual matrix */ for (i=0; i<grd->nr; i++) { w->colResid[i + colptr*grd->nr] = (w->colHist[i+colptr*grd->nr]-w->colNew[i]) / w->colHist[i+colptr*grd->nr]; if (fabs(w->colResid[i + colptr*grd->nr]) > *residMax) { *residMax = fabs(w->colResid[i + colptr*grd->nr]); } w->presResid[i + colptr*grd->nr] = (w->presHist[i+colptr*grd->nr]-w->presNew_g[i+1]) / w->presHist[i+colptr*grd->nr]; if (fabs(w->presResid[i + colptr*grd->nr]) > *residMax) { *residMax = fabs(w->presResid[i + colptr*grd->nr]); } if (eos_func) { w->eIntResid[i + colptr*grd->nr] = (w->eIntHist[i+colptr*grd->nr]-w->eIntNew[i]) / w->eIntHist[i+colptr*grd->nr]; if (fabs(w->eIntResid[i + colptr*grd->nr]) > *residMax) *residMax = fabs(w->eIntResid[i + colptr*grd->nr]); } } /* If we're in the first iteration, set move temporaries to next guess */ if (itCount == 1) { for (i=0; i<grd->nr; i++) { w->colNew[i] = w->colHist[i+colptr*grd->nr]; w->presNew_g[i+1] = w->presHist[i+colptr*grd->nr]; if (eos_func) w->eIntNew[i] = w->eIntHist[i+colptr*grd->nr]; } } else { /* On subsequent iterations, solve the linear least squares optimization problem to get a weighted sum of previous guesses for the new guess */ /* Allocate workspace for this iteration */ resid = gsl_matrix_alloc(nHist+1, mk); llsresid = gsl_vector_alloc(nHist+1); aa_wgts = gsl_vector_alloc(mk); if (nHist+1 < mk) { tau = gsl_vector_alloc(nHist+1); } else { tau = gsl_vector_alloc(mk); } /* Build matrix of residuals */ for (i=0; i<grd->nr; i++) { for (j=0; j<mk; j++) { gsl_matrix_set(resid, i, j, w->colResid[i+j*grd->nr]); gsl_matrix_set(resid, i+grd->nr, j, w->presResid[i+j*grd->nr]); if (eos_func) gsl_matrix_set(resid, i+2*grd->nr, j, w->eIntResid[i+j*grd->nr]); } } /* Set up constraints on coefficients */ for (j=0; j<mk; j++) gsl_matrix_set(resid, nHist, j, 1.0e3*(*residMax)); constraint_view = gsl_vector_subvector(w->constraint, 0, nHist+1); constraint = &(constraint_view.vector); gsl_vector_set(constraint, nHist, 1e3*(*residMax)); /* Solve linear least squares system by QR decomposition */ gsl_linalg_QR_decomp(resid, tau); gsl_linalg_QR_lssolve(resid, tau, constraint, aa_wgts, llsresid); /* Build the new guess from the computed weights */ for (i=0; i<grd->nr; i++) { w->colNew[i] = gsl_vector_get(aa_wgts, 0)*w->colHist[i]; w->presNew_g[i+1] = gsl_vector_get(aa_wgts, 0)*w->presHist[i]; if (eos_func) w->eIntNew[i] = gsl_vector_get(aa_wgts, 0)*w->eIntHist[i]; } for (j=1; j<mk; j++) { for (i=0; i<grd->nr; i++) { w->colNew[i] += gsl_vector_get(aa_wgts, j) * w->colHist[i+j*grd->nr]; w->presNew_g[i+1] += gsl_vector_get(aa_wgts, j) * w->presHist[i+j*grd->nr]; if (eos_func) w->eIntNew[i] += gsl_vector_get(aa_wgts, j) * w->eIntHist[i+j*grd->nr]; } } /* Free memory for this iteration */ gsl_vector_free(llsresid); gsl_vector_free(tau); gsl_vector_free(aa_wgts); gsl_matrix_free(resid); } #endif /* End Anderson acceleration code */ }
# ***Introduction to Radar Using Python and MATLAB*** ## Andy Harrison - Copyright (C) 2019 Artech House <br/> # Power Aperture Product *** Referring to Equation 4.54 \begin{equation}\label{eq:radar_equation_search_final} {SNR}_o = \frac{P_{av}\, A_e\, \sigma }{(4\pi)^3\, k\, T_0\, F\, L\, r^4} \, \frac{T_{scan}}{\Omega}, \end{equation} $P_{av}\, A_e$ is the power aperture product and is a useful measure of performance for search and surveillance type radar systems. *** Begin by getting the library path ```python import lib_path ``` Set the minimum and maximum target range (m) ```python target_min_range = 10e3 target_max_range = 100e3 ``` Import the `linspace` routine from `scipy` and set up the target range array ```python from numpy import linspace target_range = linspace(target_min_range, target_max_range, 2000) ``` Set the noise figure (dB), the radar losses (dB), the target RCS (dBsm), the signal to noise ration (dB), the system temperature (K), the search volume (sr), and the scan time (s) ```python from scipy.constants import pi noise_figure = 4.0 losses = 9.0 target_rcs = -5.0 signal_to_noise = 23.0 system_temperature = 305 search_volume = 2.0 * pi scan_time = 0.1 ``` Set up the keyword args ```python kwargs = {'target_range': target_range, 'system_temperature': system_temperature, 'search_volume': search_volume, 'noise_factor': 10 ** (noise_figure / 10.0), 'losses': 10 ** (losses / 10.0), 'signal_to_noise': 10 ** (signal_to_noise / 10.0), 'scan_time': scan_time, 'target_rcs': 10 ** (target_rcs / 10.0)} ``` Import the `power_aperture` routine from `search_radar_range` ```python from Libs.radar_range.search_radar_range import power_aperture ``` Calculate the power aperture product ```python power_aperture = power_aperture(**kwargs) ``` Import the `matplotlib` routines and the `log10` routine for plotting the power aperture product ```python from matplotlib import pyplot as plt from numpy import log10 ``` Display the results ```python # Set the figure size plt.rcParams["figure.figsize"] = (15, 10) # Display the results plt.plot(target_range / 1.0e3, 10.0 * log10(power_aperture), '') # Set the plot title and labels plt.title('Power Aperture Product', size=14) plt.xlabel('Target Range (km)', size=14) plt.ylabel('Power Aperture (dB)', size=14) # Set the tick label size plt.tick_params(labelsize=12) # Turn on the grid plt.grid(linestyle=':', linewidth=0.5) ```
\section{Introduction} There has been tremendous interest in resource disaggregation in recent years, with both academic and industrial researchers chasing the potential for increased scalability, power efficiency, and cost savings~\cite{fastswap,rethinking,the-machine,requirements,clio-arxiv,firebox,leap,zombieland,storm,aifm,legoos,supernic}. By physically separating compute from storage across a network, it is possible to dynamically adjust hardware resource allocations to suit changing workloads. Considerable headway has been made at higher levels of the storage hierarchy; published and even production systems now support remoting spinning disks, SSDs, and modern non-volatile memory technologies~\cite{decible}. Remote primary storage, however, remains a fundamental challenge due to the orders-of-magnitude disparity between main-board memory accesses and even rack-local network round trips. %Resource disaggregation is an architectural paradigm which separates %disk, CPU and memory over a network. The goal of this architecture is %to enable extreme flexibility in terms of machine composition. For %example a systems memory capacity can be dynamically apportioned by %reconfiguration, rather than by manually changing the physical %components of a single machine. It is now common for disks (HHD and %SSD) to be disaggregated from CPU and memory. SSDs are comparatively %easier to disaggregated than main memory as their access latencies are %on the order of 10's of microseconds which amortizes the network round %trip cost. %Local memory latency is around 50ns. The cost of accessing memory over the %network is on the order of 1us -- approximately a 20x overhead. This order of %magnitude difference in latency makes hiding remote memory accesses a hard %problem. The hardware community has made great strides in closing the latency gap via novel technologies like silicon photonics and new rack-scale interconnects, but commercially available options remain significantly slower than on-board options. Concretely, the latency of making a memory access over interconnect technologies like RDMA~\cite{infiniband-spec}, Gen-Z~\cite{genz}, and CXL~\cite{cxl} remains on the order of 20$\times$ slower than a local access (e.g., 50~ns local versus 1~$\mu$s remote). As a result, despite the fact that these memory transport technologies provide the ability to directly execute requests like read, write and compare and swap on remote host memory through the use of a RDMA capable NICs~\cite{connectx}, SoCs~\cite{cavium}, FPGA SmartNICs~\cite{corundum,kv-direct}, or DPUs~\cite{fungible}, most existing systems coordinate with a remote CPU on the socket at which the DMA is being performed to assist with serialization~\cite{cliquemap,erpc,herd,sonuma,storm}. The few published systems that provide fully passive remote memory~\cite{reigons,clover} focus on read-heavy workloads to amortize the costs of conflict detection and resolution. %% % and Omni-Path~\cite{omni-path}. // omni-path is dead now % %Each protocol, while distinct, meets approximately the same requirements, %reliable access to byte addressable remote memory with low latency and high %throughput. %% it would be nice to Cite SUPERNIC and CLIO here but I'm not sure it makes %sense untill it's published at a major venue %%Clio~\cite{clio-arxiv} %%todo ask alex about the archive reference %%todo do a quick read of how DMA is dealt with on the other interconnects In the absence of a general-purpose CPU located alongside remote memory, it falls to each individual client to ensure that its reads and writes are serialized, usually by leveraging expensive hardware-provided atomic requests like compare and swap~\cite{design-guidelines,clover}. The cost of client-side serialization is steep, and most existing systems simply partition memory completely and forgo sharing~\cite{reigons,fastswap, legoos}. On the other hand, one recent disaggregated key-value store, Clover~\cite{clover}, goes to great lengths to provide lock-less reads while supporting concurrent writes by deploying an optimistic concurrency scheme that leverages RDMA's atomic compare-and-swap request to detect and recover from write/write conflicts. While highly scalable for read-heavy workloads, Clover's client-based recovery scheme quickly becomes cost prohibitive when faced with significant levels of write contention. This shortcoming is not limited to Clover, but is fundamental to any approach based upon distributed conflict resolution. %% minimize conflicts by caching metadata about the %% location of the latest writes and reads while also make use of a %% remote data structures which allows for lock-less reads. In the case of %% highly contended resources however the performance of clover %% diminishes sharply due to an increased number of atomic locking %% operations required on writes. The traditional alternative, of course, is to deploy a centralized memory controller that can serve as a serialization point and ensure all races are resolved before accessing memory. Unfortunately, such designs are inherently unscalable as they require all accesses to be routed through the controller, rather than forwarded directly between the client and relevant server. In this work we make the observation that such a serialization point already exists in rack-scale disaggregated deployments: the top-of-rack switch. We propose to leverage the capabilities of modern programmable switches to cache sufficient information about in-flight requests to transparently detect and resolve conflicts before they occur. Unlike a traditional centralized memory controller, our serializer need only act upon actual conflicts and can avoid the unnecessary costs of enforcing ordering among unrelated requests. Moreover, the serializer serves as a performance-enhancing proxy: it can allow even conflicting requests to pass through unmodified without jeopardizing safety, as client-based conflict resolution remains. We present {\sword}, an on-path serializer %(implemented either %directly on the top-of-rack switch or an attached %middle box~\cite{disandapp}) that dramatically improves the performance of optimistic passive remote memory systems that support write sharing. Like all ToRs, {\sword} imposes a globally observable total order on memory requests within a rack. Crucially, {\sword} does not replace the underlying optimistic concurrency scheme: all remote memory operations are still suitably guarded to ensure that clients can detect and recover from conflicts. Rather, because {\sword} understands the disaggregated memory protocol, it can inspect the total ordering and detect which guards will fail. If suitably provisioned (i.e., it has the appropriate metadata cached), it can transparently modify requests in flight to account for the preceding operations and decrease the likelihood the guard will trip. Moreover, if {\sword} is configured to explicitly manage the RDMA connections themselves, it can enforce per-server ordering and remove the expensive guards entirely. We prototype {\sword} using a DPDK-based middlebox connected in-line to the ToR in the context of Clover on ConnectX-5 RoCE RDMA NICs. Our evaluation shows that {\sword} dramatically increases the performance of Clover in the presence of write contention. Under a 50:50 read-write workload, throughput rises by almost 3$\times$, tail latency drops by over 36$\times$ and bandwidth usage cuts almost in half. Further, we show that by replacing compare-and-swap requests in flight with standard RDMA verbs, we can surpass the hardware-imposed limit on atomic requests per queue pair. %% Using RDMA transport information and clover specific application %% knowledge all reads and writes to contended areas are totally ordered %% in the network. Specifically all reads and writes to the same keys are %% multiplexed to the same queue pairs, by utilizing the RDMA ordering %% requirements of QP's reads and writes require no expensive locks and %% can flow at line rate to remote memory. This ordering requires a %% number in band adjustments to the RDMA protocol in order to %% interoperable with commodity hardware. QP state must be maintained in %% network, specifically the sequence numbers of multiplexed requests, so %% that response packets can be demultiplexes back to their original %% connections. Small adjustments such as generating ACKs for collapsed %% requests is also required. We demonstrate that these algorithms are %% implementable in network at little cost with a DPDK prototype. We %% measure that ~\todo{we achieve a ?X improvement in performance using %% only XMB of in network state, and ?X performance improvement in %% highly contested settings with full use of system memory}.
# Normal and tangential coordinates In the normal and tangential coordinate system, the (vector) equation of motion $$ \sum \mathbf{F} = m \mathbf{a} $$ decomposes into the three scalar equations for the tangential ($t$), normal ($n$), and binormal ($b$) directons: $$ \begin{align} \sum F_t &= m a_t = m \dot{v} = m \ddot{s} \\ \sum F_n &= m a_n = m \frac{v^2}{\rho} \\ \sum F_b &= m a_b = 0 \;, \end{align} $$ where $F_i$ is a force in the $i$ direction, $m$ is the particle mass, $v$ is the velocity, and $\rho$ is the radius of curvature. The tangential acceleration $a_t$ is positive or negative in the direction of motion, the normal acceleration $a_n$ is **always** positive in the normal direction, and the binormal acceleration $a_b$ is **always** zero, because motion lies in the plane formed by the normal and tangential directions. ## Example: race car at banking angle (no friction) A Formula 1 race car of mass $m$ = 740 kg is traveling on a track at constant velocity $v$ = 60 m/s, where the radius of curvature is $\rho$ = 400 m. What is the banking angle $\theta$ necessary for the car to avoid sliding as it goes around this curve? First, let's draw a free-body diagram for the car: Now, write the three scalar equations of motion for the car. The equation in the tangential direction does not really tell us much, since the car is moving at a constant speed in its direction of motion: $$ \sum F_t = m a_t = m \dot{v} = 0 \;. $$ In the normal direction, the only force is the normal component of the resultant force: $$ \begin{align} \sum F_n &= m a_n \\ N_C \sin \theta &= m \frac{v^2}{\rho} \end{align} $$ and in the binormal direction, we have both the component of the resultant force and also the car's weight, but the binormal acceleration is zero: $$ \begin{align} \sum F_b &= m a_b = 0 \\ N_C \cos \theta - m g &= 0 \\ \rightarrow N_C \cos \theta &= m g \end{align} $$ If we divide the latter equation from the former, we can solve for the banking angle: $$ \begin{align} \frac{N_C \sin \theta}{N_C \cos \theta} &= \frac{m v^2 / \rho}{mg} \\ \tan \theta &= \frac{v^2}{\rho g} \\ \therefore \theta &= \tan^{-1} \left(\frac{v^2}{\rho g} \right) \end{align} $$ For the parameters given: ```python import numpy as np mass = 740 # kg velocity = 60 # m/s rho = 400 # m g = 9.81 # m/s^2 theta = np.arctan(velocity**2 / (rho * g)) print(f'theta ={theta * 180/np.pi: .2f}°') ``` theta = 42.53° ## Example: race car at banking angle (with friction) Now, consider the same situation, but account for the effect of friction, which will counter the car's motion in the outward direction. What is the new banking angle needed to avoid the car sliding in this case? Assume the coefficient of static friction is $\mu_s = 0.2$. ```python mu = 0.2 ``` In this case, we now have to account for components of the friction force in the normal and binormal directions, where the friction force is $$ f = \mu_s N_C \;. $$ In the normal direction, we have $$ \begin{align} \sum F_n &= m a_n \\ N_C \sin \theta + f \cos \theta &= m \frac{v^2}{\rho} \end{align} $$ and in the binormal direction $$ \begin{align} \sum F_b &= m a_b = 0 \\ N_C \cos \theta - f \sin \theta - m g &= 0 \\ \rightarrow N_C \cos \theta - f \sin \theta &= m g \end{align} $$ Combining the two equations (again, by dividing the first by the second) and recalling that $f = \mu_s N_c$: $$ \begin{align} \frac{N_C \sin \theta + f \cos \theta}{N_C \cos \theta - f \sin \theta} &= \frac{m v^2 / \rho}{m g} \\ \frac{\sin \theta + \mu_s \cos \theta}{\cos \theta - \mu_s \sin \theta} &= \frac{v^2}{\rho g} \;. \end{align} $$ This is our equation to find the banking angle, but unfortunately it has no closed-form solution. So, how do we find $\theta$? Using a numerical method! ### Method 1: manual iteration We could first attack this problem by manually guessing and checking different values of $\theta$, until the left-hand side of the equation equals the right-hand side. For example, trying different values from 20° to 40°: ```python # need to convert to radians vals = np.arange(20, 41, 2) * np.pi / 180 print('Theta LHS RHS') for theta in vals: lhs = (np.sin(theta) + mu*np.cos(theta)) / (np.cos(theta) - mu*np.sin(theta)) rhs = velocity**2 / (rho*g) print(f'{theta*180/np.pi: 4.1f}° {lhs: 5.3f} {rhs: 5.3f}') ``` Theta LHS RHS 20.0° 0.608 0.917 22.0° 0.657 0.917 24.0° 0.708 0.917 26.0° 0.762 0.917 28.0° 0.819 0.917 30.0° 0.879 0.917 32.0° 0.943 0.917 34.0° 1.011 0.917 36.0° 1.084 0.917 38.0° 1.163 0.917 40.0° 1.249 0.917 So, clearly the correct value is between 30° and 32°. A bit more manual iteration shows that the correct angle is just about 31.2°: ```python theta = 31.2 * np.pi / 180 lhs = (np.sin(theta) + mu*np.cos(theta)) / (np.cos(theta) - mu*np.sin(theta)) rhs = velocity**2 / (rho*g) print(lhs, rhs) ``` 0.9166501382856722 0.9174311926605505 ### Method 2: `root_scalar` Manually solving like this would be quite tedious; fortunately, there are numerical methods for solving scalar equations like this. We refer to this at **root finding**, since to solve we formulate the equation like $F(x) = 0$, and find the value of the unknown variable that makes the function zero (i.e., the root). In this case, we make the equation into the form $$ F(\theta) = \frac{\sin \theta + \mu_s \cos \theta}{\cos \theta - \mu_s \sin \theta} - \frac{v^2}{\rho g} = 0 \;, $$ Then, to solve, we can use the `root_scalar` function provided in the `scipy.optimize` module, which needs us to provide it with a function that returns $F(\theta)$ for candidate values of $\theta$ (with the goal of finding the one that makes $F(\theta)=0$), along with a few guess values: ```python from scipy.optimize import root_scalar def f(theta): '''This function evaluates the equation for finding theta. ''' return ( (np.sin(theta) + mu*np.cos(theta)) / (np.cos(theta) - mu*np.sin(theta)) - velocity**2 / (rho*g) ) sol = root_scalar(f, x0=(20*np.pi/180), x1=(40*np.pi/180)) print(f'theta ={sol.root * 180/np.pi: .2f}°') ``` theta = 31.22° ```python ```
function pdepetrans % 1D transport - modelling with extensions for decay and fast sorption % using MATLAB pdepe % % $Ekkehard Holzbecher $Date: 2006/03/16 $ %-------------------------------------------------------------------------- T = 1; % maximum time [s] L = 1; % length [m] D = 1; % diffusivity [m*m/s] v = 1; % velocity [m/s] lambda = 0.0; % decay constant [1/s] sorption = 2; % sorption-model: no sorption (0), linear (1), % Freundlich (2), Langmuir (3) k1 = 0.0004; % sorption parameter 1 (R=0 for linear isotherm with Kd, else k1=R) k2 = 0.5; % sorption parameter 2 (Kd for linear isotherm with Kd) rhob = 1300; % porous medium bulk density [kg/m*m*m] theta = 0.2; % porosity [-] c0 = 0.0; % initial concentration [kg/m*m*m] cin = 1; % boundary concentration [kg/m*m*m] M = 40; % number of timesteps N = 40; % number of nodes %-------------------------- output parameters gplot = 0; % =1: breakthrough curves; =2: profiles gsurf = 0; % surface gcont = 0; % =1: contours; =2: filled contours ganim = 2; % animation of profiles; =1: single line; =2: all lines t = linspace (T/M,T,M); % time discretization x = linspace (0,L,N); % space discretization %----------------------execution------------------------------------------- if sorption == 1 & k1 <=0 k1 = 1+k2*rhob/theta; else if sorption > 1 k1 = rhob*k1/theta; end end options = odeset; if (c0 == 0) c0 = 1.e-20; end c = pdepe(0,@transfun,@ictransfun,@bctransfun,x,[0 t],options,D,v,lambda,sorption,k1,k2,c0,cin); %---------------------- graphical output ---------------------------------- switch gplot case 1 plot ([0 t],c) % breakthrough curves xlabel ('time'); ylabel ('concentration'); case 2 plot (x,c','--') % profiles xlabel ('space'); ylabel ('concentration'); end if gsurf % surface plot figure; surf (x,[0 t],c); xlabel ('space'); ylabel ('time'); zlabel('concentration'); end if gcont figure; end switch gcont case 1 contour (x,[0 t],c) % contours grid on; xlabel ('space'); ylabel ('time'); case 2 contourf(x,[0 t],c) % filled contours colorbar; xlabel ('space'); ylabel ('time'); end if (ganim) [FileName,PathName] = uiputfile('*.mpg'); figure; if (ganim > 1) hold on; end for j = 1:size(c,1) axis manual; plot (x,c(j,:),'r','LineWidth',2); YLim = [min(c0,cin) max(c0,cin)]; legend (['t=' num2str(T*(j-1)/M)]); Anim(j) = getframe; plot (x,c(j,:),'b','LineWidth',2); end mpgwrite (Anim,colormap,[PathName '/' FileName]); % mgwrite not standard MATLAB movie (Anim,0); % play animation end %----------------------functions------------------------------ function [c,f,s] = transfun(x,t,u,DuDx,D,v,lambda,sorption,k1,k2,c0,cin) switch sorption case 0 R = 1; case 1 R = k1; case 2 R = 1+k1*k2*u^(k2-1); case 3 R = 1+k1*k2*u/(k2+u)/(k2+u); end c = R; f = D*DuDx; s = -v*DuDx -lambda*R*u; % -------------------------------------------------------------- function u0 = ictransfun(x,D,v,lambda,sorption,k1,k2,c0,cin) u0 = c0; % -------------------------------------------------------------- function [pl,ql,pr,qr] = bctransfun(xl,ul,xr,ur,t,D,v,lambda,sorption,k1,k2,c0,cin) pl = ul-cin; ql = 0; pr = 0; qr = 1;
If $f$ and $g$ are holomorphic on a set $S$, then $f \cdot g$ is holomorphic on $S$.
/* filter/gaussian.c * * Gaussian smoothing filters * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_filter.h> #include <gsl/gsl_poly.h> /* maximum derivative order allowed for Gaussian filter */ #define GSL_FILTER_GAUSSIAN_MAX_ORDER 10 typedef double gaussian_type_t; typedef double ringbuf_type_t; #include "ringbuf.c" typedef struct { size_t n; /* window size */ double * window; /* linear array with current window */ ringbuf * rbuf; /* ring buffer storing current window */ } gaussian_state_t; static size_t gaussian_size(const size_t n); static int gaussian_init(const size_t n, void * vstate); static int gaussian_insert(const gaussian_type_t x, void * vstate); static int gaussian_delete(void * vstate); static int gaussian_get(void * params, gaussian_type_t * result, const void * vstate); static const gsl_movstat_accum gaussian_accum_type; /* gsl_filter_gaussian_alloc() Allocate a workspace for Gaussian filtering. Inputs: K - number of samples in window; if even, it is rounded up to the next odd, to have a symmetric window Return: pointer to workspace */ gsl_filter_gaussian_workspace * gsl_filter_gaussian_alloc(const size_t K) { const size_t H = K / 2; gsl_filter_gaussian_workspace *w; size_t state_size; w = calloc(1, sizeof(gsl_filter_gaussian_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->K = 2 * H + 1; w->kernel = malloc(w->K * sizeof(double)); if (w->kernel == 0) { gsl_filter_gaussian_free(w); GSL_ERROR_NULL ("failed to allocate space for kernel", GSL_ENOMEM); return NULL; } state_size = gaussian_size(w->K); w->movstat_workspace_p = gsl_movstat_alloc_with_size(state_size, H, H); if (!w->movstat_workspace_p) { gsl_filter_gaussian_free(w); GSL_ERROR_NULL ("failed to allocate space for movstat workspace", GSL_ENOMEM); } return w; } void gsl_filter_gaussian_free(gsl_filter_gaussian_workspace * w) { if (w->kernel) free(w->kernel); if (w->movstat_workspace_p) gsl_movstat_free(w->movstat_workspace_p); free(w); } /* gsl_filter_gaussian() Apply a Gaussian filter to an input vector: G_{sigma}(x) = exp [ -x^2 / (2 sigma^2) ] Inputs: alpha - number of standard deviations to include in Gaussian kernel order - derivative order of Gaussian x - input vector, size n y - (output) filtered vector, size n w - workspace Notes: 1) If alpha = 3, then the Gaussian kernel will be a Gaussian of +/- 3 standard deviations */ int gsl_filter_gaussian(const gsl_filter_end_t endtype, const double alpha, const size_t order, const gsl_vector * x, gsl_vector * y, gsl_filter_gaussian_workspace * w) { if (x->size != y->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else if (alpha <= 0.0) { GSL_ERROR("alpha must be positive", GSL_EDOM); } else { int status; gsl_vector_view kernel = gsl_vector_view_array(w->kernel, w->K); /* construct Gaussian kernel of length K */ gsl_filter_gaussian_kernel(alpha, order, 1, &kernel.vector); status = gsl_movstat_apply_accum(endtype, x, &gaussian_accum_type, (void *) w->kernel, y, NULL, w->movstat_workspace_p); return status; } } /* gsl_filter_gaussian_kernel() Construct Gaussian kernel with given sigma and order Inputs: alpha - number of standard deviations to include in window order - kernel order (0 = gaussian, 1 = first derivative, ...) normalize - normalize so sum(G) = 1 kernel - (output) Gaussian kernel Return: success/error Notes: 1) If alpha = 3, then the output kernel will contain a Gaussian with +/- 3 standard deviations */ int gsl_filter_gaussian_kernel(const double alpha, const size_t order, const int normalize, gsl_vector * kernel) { const size_t N = kernel->size; if (alpha <= 0.0) { GSL_ERROR("alpha must be positive", GSL_EDOM); } else if (order > GSL_FILTER_GAUSSIAN_MAX_ORDER) { GSL_ERROR("derivative order is too large", GSL_EDOM); } else { const double half = 0.5 * (N - 1.0); /* (N - 1) / 2 */ double sum = 0.0; size_t i; /* check for quick return */ if (N == 1) { if (order == 0) gsl_vector_set(kernel, 0, 1.0); else gsl_vector_set(kernel, 0, 0.0); return GSL_SUCCESS; } for (i = 0; i < N; ++i) { double xi = ((double)i - half) / half; double yi = alpha * xi; double gi = exp(-0.5 * yi * yi); gsl_vector_set(kernel, i, gi); sum += gi; } /* normalize so sum(kernel) = 1 */ if (normalize) gsl_vector_scale(kernel, 1.0 / sum); if (order > 0) { const double beta = -0.5 * alpha * alpha; double q[GSL_FILTER_GAUSSIAN_MAX_ORDER + 1]; size_t k; /* * Need to calculate derivatives of the Gaussian window; define * * w(n) = C * exp [ p(n) ] * * p(n) = beta * n^2 * beta = -1/2 * ( alpha / ((N-1)/2) )^2 * * Then: * * d^k/dn^k w(n) = q_k(n) * w(n) * * where q_k(n) is a degree-k polynomial in n, which satisfies: * * q_k(n) = d/dn q_{k-1}(n) + q_{k-1}(n) * dp(n)/dn * q_0(n) = 1 / half^{order} */ /* initialize q_0(n) = 1 / half^{order} */ q[0] = 1.0 / gsl_pow_uint(half, order); for (i = 1; i <= GSL_FILTER_GAUSSIAN_MAX_ORDER; ++i) q[i] = 0.0; /* loop through derivative orders and calculate q_k(n) for k = 1,...,order */ for (k = 1; k <= order; ++k) { double qm1 = q[0]; q[0] = q[1]; for (i = 1; i <= k; ++i) { double tmp = q[i]; q[i] = (i + 1.0) * q[i + 1] + /* d/dn q_{k-1} */ 2.0 * beta * qm1; /* q_{k-1}(n) p'(n) */ qm1 = tmp; } } /* now set w(n) := q(n) * w(n) */ for (i = 0; i < N; ++i) { double xi = ((double)i - half) / half; double qn = gsl_poly_eval(q, order + 1, xi); double *wn = gsl_vector_ptr(kernel, i); *wn *= qn; } } return GSL_SUCCESS; } } static size_t gaussian_size(const size_t n) { size_t size = 0; size += sizeof(gaussian_state_t); size += n * sizeof(gaussian_type_t); size += ringbuf_size(n); return size; } static int gaussian_init(const size_t n, void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; state->n = n; state->window = (gaussian_type_t *) ((unsigned char *) vstate + sizeof(gaussian_state_t)); state->rbuf = (ringbuf *) ((unsigned char *) state->window + n * sizeof(gaussian_type_t)); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int gaussian_insert(const gaussian_type_t x, void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; /* add new element to ring buffer */ ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int gaussian_delete(void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) ringbuf_pop_back(state->rbuf); return GSL_SUCCESS; } static int gaussian_get(void * params, gaussian_type_t * result, const void * vstate) { const gaussian_state_t * state = (const gaussian_state_t *) vstate; const double * kernel = (const double *) params; size_t n = ringbuf_copy(state->window, state->rbuf); double sum = 0.0; size_t i; for (i = 0; i < n; ++i) sum += state->window[i] * kernel[n - i - 1]; *result = sum; return GSL_SUCCESS; } static const gsl_movstat_accum gaussian_accum_type = { gaussian_size, gaussian_init, gaussian_insert, gaussian_delete, gaussian_get };
[GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α ⊢ GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 [PROOFSTEP] intro 𝓐 𝓕 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α 𝓐 : Filter ((α →ᵤ β) × (α →ᵤ β)) 𝓕 : Filter (β × β) ⊢ (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) 𝓐 ≤ 𝓕 ↔ 𝓐 ≤ (fun 𝓕 => UniformFun.filter α β 𝓕) 𝓕 [PROOFSTEP] symm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α 𝓐 : Filter ((α →ᵤ β) × (α →ᵤ β)) 𝓕 : Filter (β × β) ⊢ 𝓐 ≤ (fun 𝓕 => UniformFun.filter α β 𝓕) 𝓕 ↔ (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) 𝓐 ≤ 𝓕 [PROOFSTEP] calc 𝓐 ≤ UniformFun.filter α β 𝓕 ↔ (UniformFun.basis α β 𝓕).sets ⊆ 𝓐.sets := by rw [UniformFun.filter, ← FilterBasis.generate, le_generate_iff] _ ↔ ∀ U ∈ 𝓕, UniformFun.gen α β U ∈ 𝓐 := image_subset_iff _ ↔ ∀ U ∈ 𝓕, {uv | ∀ x, (uv, x) ∈ {t : ((α →ᵤ β) × (α →ᵤ β)) × α | (t.1.1 t.2, t.1.2 t.2) ∈ U}} ∈ 𝓐 := Iff.rfl _ ↔ ∀ U ∈ 𝓕, {uvx : ((α →ᵤ β) × (α →ᵤ β)) × α | (uvx.1.1 uvx.2, uvx.1.2 uvx.2) ∈ U} ∈ 𝓐 ×ˢ (⊤ : Filter α) := (forall₂_congr fun U _hU => mem_prod_top.symm) _ ↔ lower_adjoint 𝓐 ≤ 𝓕 := Iff.rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α 𝓐 : Filter ((α →ᵤ β) × (α →ᵤ β)) 𝓕 : Filter (β × β) ⊢ 𝓐 ≤ UniformFun.filter α β 𝓕 ↔ (UniformFun.basis α β 𝓕).sets ⊆ 𝓐.sets [PROOFSTEP] rw [UniformFun.filter, ← FilterBasis.generate, le_generate_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β x : α ⊢ UniformContinuous (Function.eval x ∘ ↑toFun) [PROOFSTEP] change _ ≤ _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β x : α ⊢ map (fun x_1 => ((Function.eval x ∘ ↑toFun) x_1.fst, (Function.eval x ∘ ↑toFun) x_1.snd)) (𝓤 (α →ᵤ β)) ≤ 𝓤 β [PROOFSTEP] rw [map_le_iff_le_comap, (UniformFun.hasBasis_uniformity α β).le_basis_iff ((𝓤 _).basis_sets.comap _)] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β x : α ⊢ ∀ (i' : Set (β × β)), i' ∈ 𝓤 β → ∃ i, i ∈ 𝓤 β ∧ UniformFun.gen α β i ⊆ (fun x_1 => ((Function.eval x ∘ ↑toFun) x_1.fst, (Function.eval x ∘ ↑toFun) x_1.snd)) ⁻¹' id i' [PROOFSTEP] exact fun U hU => ⟨U, hU, fun uv huv => huv x⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u : ι → UniformSpace γ ⊢ uniformSpace α γ = ⨅ (i : ι), uniformSpace α γ [PROOFSTEP] ext : 1 [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u : ι → UniformSpace γ ⊢ 𝓤 (α →ᵤ γ) = 𝓤 (α →ᵤ γ) [PROOFSTEP] change UniformFun.filter α γ 𝓤[⨅ i, u i] = 𝓤[⨅ i, 𝒰(α, γ, u i)] [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u : ι → UniformSpace γ ⊢ UniformFun.filter α γ (𝓤 γ) = 𝓤 (α →ᵤ γ) [PROOFSTEP] rw [iInf_uniformity, iInf_uniformity] [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u : ι → UniformSpace γ ⊢ UniformFun.filter α γ (⨅ (i : ι), 𝓤 γ) = ⨅ (i : ι), 𝓤 (α →ᵤ γ) [PROOFSTEP] exact (UniformFun.gc α γ).u_iInf [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ = uniformSpace α γ ⊓ uniformSpace α γ [PROOFSTEP] rw [inf_eq_iInf, inf_eq_iInf, UniformFun.iInf_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u₁ u₂ : UniformSpace γ ⊢ ⨅ (i : Bool), uniformSpace α γ = ⨅ (b : Bool), bif b then uniformSpace α γ else uniformSpace α γ [PROOFSTEP] refine' iInf_congr fun i => _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u₁ u₂ : UniformSpace γ i : Bool ⊢ uniformSpace α γ = bif i then uniformSpace α γ else uniformSpace α γ [PROOFSTEP] cases i [GOAL] case false α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ = bif false then uniformSpace α γ else uniformSpace α γ [PROOFSTEP] rfl [GOAL] case true α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ = bif true then uniformSpace α γ else uniformSpace α γ [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β ⊢ uniformSpace α γ = UniformSpace.comap (fun x => f ∘ x) (uniformSpace α β) [PROOFSTEP] letI : UniformSpace γ := ‹UniformSpace β›.comap f [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ ⊢ uniformSpace α γ = UniformSpace.comap (fun x => f ∘ x) (uniformSpace α β) [PROOFSTEP] ext : 1 [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ ⊢ 𝓤 (α →ᵤ γ) = 𝓤 (α →ᵤ γ) [PROOFSTEP] change UniformFun.filter α γ ((𝓤 β).comap _) = (UniformFun.filter α β (𝓤 β)).comap _ -- We have the following four Galois connection which form a square diagram, and we want -- to show that the square of upper adjoints is commutative. The trick then is to use -- `GaloisConnection.u_comm_of_l_comm` to reduce it to commutativity of the lower adjoints, -- which is way easier to prove. [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] let fcomp := ((f ∘ ·) : ((α → γ) → (α → β))) [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] have h₁ := Filter.gc_map_comap (Prod.map fcomp fcomp) [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] have h₂ := Filter.gc_map_comap (Prod.map f f) [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] have h₃ := UniformFun.gc α β [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] have h₄ := UniformFun.gc α γ [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 ⊢ UniformFun.filter α γ (comap (fun p => (f p.fst, f p.snd)) (𝓤 β)) = comap (fun p => ((fun x => f ∘ x) p.fst, (fun x => f ∘ x) p.snd)) (UniformFun.filter α β (𝓤 β)) [PROOFSTEP] refine' GaloisConnection.u_comm_of_l_comm h₁ h₂ h₃ h₄ fun 𝓐 => _ [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) ⊢ map (Prod.map f f) (map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) = map (UniformFun.phi α β) (map (Prod.map fcomp fcomp) 𝓐 ×ˢ ⊤) [PROOFSTEP] have : Prod.map f f ∘ (UniformFun.phi α γ) = (UniformFun.phi α β) ∘ Prod.map (Prod.map fcomp fcomp) (id : α → α) := by ext <;> rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) ⊢ Prod.map f f ∘ UniformFun.phi α γ = UniformFun.phi α β ∘ Prod.map (Prod.map fcomp fcomp) id [PROOFSTEP] ext [GOAL] case h.h₁ α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) x✝ : ((α →ᵤ γ) × (α →ᵤ γ)) × α ⊢ ((Prod.map f f ∘ UniformFun.phi α γ) x✝).fst = ((UniformFun.phi α β ∘ Prod.map (Prod.map fcomp fcomp) id) x✝).fst [PROOFSTEP] rfl [GOAL] case h.h₂ α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) x✝ : ((α →ᵤ γ) × (α →ᵤ γ)) × α ⊢ ((Prod.map f f ∘ UniformFun.phi α γ) x✝).snd = ((UniformFun.phi α β ∘ Prod.map (Prod.map fcomp fcomp) id) x✝).snd [PROOFSTEP] rfl [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this✝ : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) this : Prod.map f f ∘ UniformFun.phi α γ = UniformFun.phi α β ∘ Prod.map (Prod.map fcomp fcomp) id ⊢ map (Prod.map f f) (map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) = map (UniformFun.phi α β) (map (Prod.map fcomp fcomp) 𝓐 ×ˢ ⊤) [PROOFSTEP] rw [map_comm this, ← prod_map_map_eq'] [GOAL] case a α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → β this✝ : UniformSpace γ := UniformSpace.comap f inst✝ fcomp : (α → γ) → α → β := fun x => f ∘ x h₁ : GaloisConnection (map (Prod.map fcomp fcomp)) (comap (Prod.map fcomp fcomp)) h₂ : GaloisConnection (map (Prod.map f f)) (comap (Prod.map f f)) h₃ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α β) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α β 𝓕 h₄ : GaloisConnection (fun 𝓐 => map (UniformFun.phi α γ) (𝓐 ×ˢ ⊤)) fun 𝓕 => UniformFun.filter α γ 𝓕 𝓐 : Filter ((α → γ) × (α → γ)) this : Prod.map f f ∘ UniformFun.phi α γ = UniformFun.phi α β ∘ Prod.map (Prod.map fcomp fcomp) id ⊢ map (UniformFun.phi α β) (map (Prod.map fcomp fcomp) 𝓐 ×ˢ map id ⊤) = map (UniformFun.phi α β) (map (Prod.map fcomp fcomp) 𝓐 ×ˢ ⊤) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : UniformContinuous f ⊢ UniformContinuous (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) [PROOFSTEP] refine uniformContinuous_iff.mpr ?_ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : UniformContinuous f ⊢ uniformSpace α γ ≤ UniformSpace.comap (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) (uniformSpace α β) [PROOFSTEP] exact (UniformFun.mono (uniformContinuous_iff.mp hf)).trans_eq UniformFun.comap_eq [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : UniformInducing f ⊢ UniformInducing (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) [PROOFSTEP] constructor [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : UniformInducing f ⊢ comap (fun x => ((↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) x.fst, (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) x.snd)) (𝓤 (α →ᵤ β)) = 𝓤 (α →ᵤ γ) [PROOFSTEP] replace hf : (𝓤 β).comap (Prod.map f f) = _ := hf.comap_uniformity [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : comap (Prod.map f f) (𝓤 β) = 𝓤 γ ⊢ comap (fun x => ((↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) x.fst, (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) x.snd)) (𝓤 (α →ᵤ β)) = 𝓤 (α →ᵤ γ) [PROOFSTEP] change comap (Prod.map (ofFun ∘ (f ∘ ·) ∘ toFun) (ofFun ∘ (f ∘ ·) ∘ toFun)) _ = _ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : comap (Prod.map f f) (𝓤 β) = 𝓤 γ ⊢ comap (Prod.map (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun)) (𝓤 (α →ᵤ β)) = 𝓤 (α →ᵤ γ) [PROOFSTEP] rw [← uniformity_comap] at hf ⊢ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ 𝓤 (α →ᵤ γ) = 𝓤 (α →ᵤ γ) [PROOFSTEP] congr [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ UniformSpace.comap (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) (uniformSpace α β) = uniformSpace α γ [PROOFSTEP] rw [← uniformSpace_eq hf, UniformFun.comap_eq] [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ UniformSpace.comap (↑ofFun ∘ (fun x => f ∘ x) ∘ ↑toFun) (uniformSpace α β) = UniformSpace.comap (fun x => f ∘ x) (uniformSpace α β) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → α ⊢ UniformContinuous fun g => ↑ofFun (g ∘ f) [PROOFSTEP] rw [uniformContinuous_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → α ⊢ uniformSpace α β ≤ UniformSpace.comap (fun g => ↑ofFun (g ∘ f)) (uniformSpace γ β) [PROOFSTEP] change 𝓤 (α →ᵤ β) ≤ (𝓤 (γ →ᵤ β)).comap (Prod.map (fun g : α →ᵤ β => g ∘ f) fun g : α →ᵤ β => g ∘ f) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → α ⊢ 𝓤 (α →ᵤ β) ≤ comap (Prod.map (fun g => g ∘ f) fun g => g ∘ f) (𝓤 (γ →ᵤ β)) [PROOFSTEP] rw [(UniformFun.hasBasis_uniformity α β).le_basis_iff ((UniformFun.hasBasis_uniformity γ β).comap _)] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β f : γ → α ⊢ ∀ (i' : Set (β × β)), i' ∈ 𝓤 β → ∃ i, i ∈ 𝓤 β ∧ UniformFun.gen α β i ⊆ (Prod.map (fun g => g ∘ f) fun g => g ∘ f) ⁻¹' UniformFun.gen γ β i' [PROOFSTEP] exact fun U hU => ⟨U, hU, fun uv huv x => huv (f x)⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : T2Space β ⊢ ∀ (x y : α →ᵤ β), x ≠ y → ∃ u v, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v [PROOFSTEP] intro f g h [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g✝ : ι → α inst✝¹ : UniformSpace β inst✝ : T2Space β f g : α →ᵤ β h : f ≠ g ⊢ ∃ u v, IsOpen u ∧ IsOpen v ∧ f ∈ u ∧ g ∈ v ∧ Disjoint u v [PROOFSTEP] obtain ⟨x, hx⟩ := not_forall.mp (mt funext h) [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g✝ : ι → α inst✝¹ : UniformSpace β inst✝ : T2Space β f g : α →ᵤ β h : f ≠ g x : α hx : ¬f x = g x ⊢ ∃ u v, IsOpen u ∧ IsOpen v ∧ f ∈ u ∧ g ∈ v ∧ Disjoint u v [PROOFSTEP] exact separated_by_continuous (uniformContinuous_eval β x).continuous hx [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β ⊢ UniformContinuous ↑toFun [PROOFSTEP] rw [uniformContinuous_pi] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β ⊢ ∀ (i : α), UniformContinuous fun x => ↑toFun x i [PROOFSTEP] intro x [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β x : α ⊢ UniformContinuous fun x_1 => ↑toFun x_1 x [PROOFSTEP] exact uniformContinuous_eval β x [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β F : ι → α →ᵤ β f : α →ᵤ β ⊢ Tendsto F p (𝓝 f) ↔ TendstoUniformly F f p [PROOFSTEP] rw [(UniformFun.hasBasis_nhds α β f).tendsto_right_iff, TendstoUniformly] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β F : ι → α →ᵤ β f : α →ᵤ β ⊢ (∀ (i : Set (β × β)), i ∈ 𝓤 β → ∀ᶠ (x : ι) in p, F x ∈ {g | (f, g) ∈ UniformFun.gen α β i}) ↔ ∀ (u : Set (β × β)), u ∈ 𝓤 β → ∀ᶠ (n : ι) in p, ∀ (x : α), (f x, F n x) ∈ u [PROOFSTEP] exact Iff.rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ UniformInducing ↑(Equiv.arrowProdEquivProdArrow β γ α) [PROOFSTEP] constructor [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ comap (fun x => (↑(Equiv.arrowProdEquivProdArrow β γ α) x.fst, ↑(Equiv.arrowProdEquivProdArrow β γ α) x.snd)) (𝓤 ((α →ᵤ β) × (α →ᵤ γ))) = 𝓤 (α →ᵤ β × γ) [PROOFSTEP] change comap (Prod.map (Equiv.arrowProdEquivProdArrow _ _ _) (Equiv.arrowProdEquivProdArrow _ _ _)) _ = _ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ comap (Prod.map ↑(Equiv.arrowProdEquivProdArrow β γ α) ↑(Equiv.arrowProdEquivProdArrow β γ α)) (𝓤 ((α →ᵤ β) × (α →ᵤ γ))) = 𝓤 (α →ᵤ β × γ) [PROOFSTEP] simp_rw [UniformFun] [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ comap (Prod.map ↑(Equiv.arrowProdEquivProdArrow β γ α) ↑(Equiv.arrowProdEquivProdArrow β γ α)) (𝓤 ((α → β) × (α → γ))) = 𝓤 (α → β × γ) [PROOFSTEP] rw [← uniformity_comap] [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ 𝓤 (α → β × γ) = 𝓤 (α → β × γ) [PROOFSTEP] congr [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ UniformSpace.comap (↑(Equiv.arrowProdEquivProdArrow β γ α)) instUniformSpaceProd = uniformSpace α (β × γ) [PROOFSTEP] unfold instUniformSpaceProd [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ UniformSpace.comap (↑(Equiv.arrowProdEquivProdArrow β γ α)) (UniformSpace.comap Prod.fst (uniformSpace α β) ⊓ UniformSpace.comap Prod.snd (uniformSpace α γ)) = uniformSpace α (β × γ) [PROOFSTEP] rw [UniformSpace.comap_inf, ← UniformSpace.comap_comap, ← UniformSpace.comap_comap] [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ ⊢ UniformSpace.comap (Prod.fst ∘ ↑(Equiv.arrowProdEquivProdArrow β γ α)) (uniformSpace α β) ⊓ UniformSpace.comap (Prod.snd ∘ ↑(Equiv.arrowProdEquivProdArrow β γ α)) (uniformSpace α γ) = uniformSpace α (β × γ) [PROOFSTEP] have := (@UniformFun.inf_eq α (β × γ) (UniformSpace.comap Prod.fst ‹_›) (UniformSpace.comap Prod.snd ‹_›)).symm [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β inst✝ : UniformSpace γ this : uniformSpace α (β × γ) ⊓ uniformSpace α (β × γ) = uniformSpace α (β × γ) ⊢ UniformSpace.comap (Prod.fst ∘ ↑(Equiv.arrowProdEquivProdArrow β γ α)) (uniformSpace α β) ⊓ UniformSpace.comap (Prod.snd ∘ ↑(Equiv.arrowProdEquivProdArrow β γ α)) (uniformSpace α γ) = uniformSpace α (β × γ) [PROOFSTEP] rwa [UniformFun.comap_eq, UniformFun.comap_eq] at this [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ UniformInducing ↑(Equiv.piComm fun a i => δ i) [PROOFSTEP] refine @UniformInducing.mk ?_ ?_ ?_ ?_ ?_ ?_ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ comap (fun x => (↑(Equiv.piComm fun a i => δ i) x.fst, ↑(Equiv.piComm fun a i => δ i) x.snd)) (𝓤 ((i : ι) → (fun i => α → δ i) i)) = 𝓤 (α →ᵤ (i : ι) → δ i) [PROOFSTEP] change comap (Prod.map Function.swap Function.swap) _ = _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ comap (Prod.map Function.swap Function.swap) (𝓤 ((i : ι) → (fun i => α → δ i) i)) = 𝓤 (α →ᵤ (i : ι) → δ i) [PROOFSTEP] rw [← uniformity_comap] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ 𝓤 (α → (y : ι) → δ y) = 𝓤 (α →ᵤ (i : ι) → δ i) [PROOFSTEP] congr [GOAL] case h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ UniformSpace.comap Function.swap (Pi.uniformSpace fun i => α → δ i) = uniformSpace α ((i : ι) → δ i) [PROOFSTEP] unfold Pi.uniformSpace [GOAL] case h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ UniformSpace.comap Function.swap (UniformSpace.ofCoreEq UniformSpace.toCore Pi.topologicalSpace (_ : Pi.topologicalSpace = UniformSpace.Core.toTopologicalSpace UniformSpace.toCore)) = uniformSpace α ((i : ι) → δ i) [PROOFSTEP] rw [UniformSpace.ofCoreEq_toCore, UniformSpace.ofCoreEq_toCore, UniformSpace.comap_iInf, UniformFun.iInf_eq] [GOAL] case h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ ⨅ (i : ι), UniformSpace.comap Function.swap (UniformSpace.comap (fun a => a i) ((fun i => uniformSpace α (δ i)) i)) = ⨅ (i : ι), uniformSpace α ((i : ι) → δ i) [PROOFSTEP] refine' iInf_congr fun i => _ [GOAL] case h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) i : ι ⊢ UniformSpace.comap Function.swap (UniformSpace.comap (fun a => a i) ((fun i => uniformSpace α (δ i)) i)) = uniformSpace α ((i : ι) → δ i) [PROOFSTEP] rw [← UniformSpace.comap_comap, UniformFun.comap_eq] [GOAL] case h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) i : ι ⊢ UniformSpace.comap ((fun a => a i) ∘ Function.swap) ((fun i => uniformSpace α (δ i)) i) = UniformSpace.comap (fun x => (fun a => a i) ∘ x) (uniformSpace α (δ i)) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α 𝔖 : Set (Set α) S : Set α V : Set (β × β) ⊢ UniformOnFun.gen 𝔖 S V = Prod.map (restrict S ∘ ↑UniformFun.toFun) (restrict S ∘ ↑UniformFun.toFun) ⁻¹' UniformFun.gen (↑S) β V [PROOFSTEP] ext uv [GOAL] case h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α 𝔖 : Set (Set α) S : Set α V : Set (β × β) uv : (α →ᵤ[𝔖] β) × (α →ᵤ[𝔖] β) ⊢ uv ∈ UniformOnFun.gen 𝔖 S V ↔ uv ∈ Prod.map (restrict S ∘ ↑UniformFun.toFun) (restrict S ∘ ↑UniformFun.toFun) ⁻¹' UniformFun.gen (↑S) β V [PROOFSTEP] exact ⟨fun h ⟨x, hx⟩ => h x hx, fun h x hx => h ⟨x, hx⟩⟩ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) ⊢ topologicalSpace α β 𝔖 = ⨅ (s : Set α) (_ : s ∈ 𝔖), TopologicalSpace.induced (restrict s ∘ ↑UniformFun.toFun) (UniformFun.topologicalSpace (↑s) β) [PROOFSTEP] simp only [UniformOnFun.topologicalSpace, toTopologicalSpace_iInf, toTopologicalSpace_iInf, toTopologicalSpace_comap] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) ⊢ ⨅ (i : Set α) (_ : i ∈ 𝔖), TopologicalSpace.induced (restrict i) UniformSpace.toTopologicalSpace = ⨅ (s : Set α) (_ : s ∈ 𝔖), TopologicalSpace.induced (restrict s ∘ ↑UniformFun.toFun) (UniformFun.topologicalSpace (↑s) β) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p✝ : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) p : ι → Prop s : ι → Set (β × β) hb : HasBasis (𝓤 β) p s S : Set α ⊢ HasBasis (𝓤 (α →ᵤ[𝔖] β)) p fun i => UniformOnFun.gen 𝔖 S (s i) [PROOFSTEP] simp_rw [UniformOnFun.gen_eq_preimage_restrict, uniformity_comap] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p✝ : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) p : ι → Prop s : ι → Set (β × β) hb : HasBasis (𝓤 β) p s S : Set α ⊢ HasBasis (comap (Prod.map (restrict S) (restrict S)) (𝓤 (↑S → β))) p fun i => Prod.map (restrict S ∘ ↑UniformFun.toFun) (restrict S ∘ ↑UniformFun.toFun) ⁻¹' UniformFun.gen (↑S) β (s i) [PROOFSTEP] exact (UniformFun.hasBasis_uniformity_of_basis S β hb).comap _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p✝ : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : Set.Nonempty 𝔖 h' : DirectedOn (fun x x_1 => x ⊆ x_1) 𝔖 p : ι → Prop s : ι → Set (β × β) hb : HasBasis (𝓤 β) p s ⊢ HasBasis (𝓤 (α →ᵤ[𝔖] β)) (fun Si => Si.fst ∈ 𝔖 ∧ p Si.snd) fun Si => UniformOnFun.gen 𝔖 Si.fst (s Si.snd) [PROOFSTEP] simp only [iInf_uniformity] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p✝ : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : Set.Nonempty 𝔖 h' : DirectedOn (fun x x_1 => x ⊆ x_1) 𝔖 p : ι → Prop s : ι → Set (β × β) hb : HasBasis (𝓤 β) p s ⊢ HasBasis (⨅ (i : Set α) (_ : i ∈ 𝔖), 𝓤 (α →ᵤ[𝔖] β)) (fun Si => Si.fst ∈ 𝔖 ∧ p Si.snd) fun Si => UniformOnFun.gen 𝔖 Si.fst (s Si.snd) [PROOFSTEP] exact hasBasis_biInf_of_directed h (fun S => UniformOnFun.gen 𝔖 S ∘ s) _ (fun S _hS => UniformOnFun.hasBasis_uniformity_of_basis_aux₁ α β 𝔖 hb S) (UniformOnFun.hasBasis_uniformity_of_basis_aux₂ α β 𝔖 h' hb) [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : s ∈ 𝔖 ⊢ UniformContinuous (↑UniformFun.ofFun ∘ restrict s ∘ ↑(toFun 𝔖)) [PROOFSTEP] change _ ≤ _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : s ∈ 𝔖 ⊢ map (fun x => ((↑UniformFun.ofFun ∘ restrict s ∘ ↑(toFun 𝔖)) x.fst, (↑UniformFun.ofFun ∘ restrict s ∘ ↑(toFun 𝔖)) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ≤ 𝓤 (↑s →ᵤ β) [PROOFSTEP] simp only [UniformOnFun.uniformSpace, map_le_iff_le_comap, iInf_uniformity] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : s ∈ 𝔖 ⊢ ⨅ (i : Set α) (_ : i ∈ 𝔖), 𝓤 (α →ᵤ[𝔖] β) ≤ comap (fun x => ((↑UniformFun.ofFun ∘ restrict s ∘ ↑(toFun 𝔖)) x.fst, (↑UniformFun.ofFun ∘ restrict s ∘ ↑(toFun 𝔖)) x.snd)) (𝓤 (↑s →ᵤ β)) [PROOFSTEP] exact iInf₂_le s h [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u : ι → UniformSpace γ ⊢ uniformSpace α γ 𝔖 = ⨅ (i : ι), uniformSpace α γ 𝔖 [PROOFSTEP] simp_rw [UniformOnFun.uniformSpace, UniformFun.iInf_eq, UniformSpace.comap_iInf] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u : ι → UniformSpace γ ⊢ ⨅ (s : Set α) (_ : s ∈ 𝔖) (i : ι), UniformSpace.comap (restrict s) (UniformFun.uniformSpace (↑s) γ) = ⨅ (i : ι) (s : Set α) (_ : s ∈ 𝔖), UniformSpace.comap (restrict s) (UniformFun.uniformSpace (↑s) γ) [PROOFSTEP] rw [iInf_comm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u : ι → UniformSpace γ ⊢ ⨅ (s : Set α) (_ : s ∈ 𝔖) (i : ι), UniformSpace.comap (restrict s) (UniformFun.uniformSpace (↑s) γ) = ⨅ (j : Set α) (i : ι) (_ : j ∈ 𝔖), UniformSpace.comap (restrict j) (UniformFun.uniformSpace (↑j) γ) [PROOFSTEP] exact iInf_congr fun s => iInf_comm [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ 𝔖 = uniformSpace α γ 𝔖 ⊓ uniformSpace α γ 𝔖 [PROOFSTEP] rw [inf_eq_iInf, inf_eq_iInf, UniformOnFun.iInf_eq] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u₁ u₂ : UniformSpace γ ⊢ ⨅ (i : Bool), uniformSpace α γ 𝔖 = ⨅ (b : Bool), bif b then uniformSpace α γ 𝔖 else uniformSpace α γ 𝔖 [PROOFSTEP] refine' iInf_congr fun i => _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u₁ u₂ : UniformSpace γ i : Bool ⊢ uniformSpace α γ 𝔖 = bif i then uniformSpace α γ 𝔖 else uniformSpace α γ 𝔖 [PROOFSTEP] cases i [GOAL] case false α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ 𝔖 = bif false then uniformSpace α γ 𝔖 else uniformSpace α γ 𝔖 [PROOFSTEP] rfl [GOAL] case true α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) u₁ u₂ : UniformSpace γ ⊢ uniformSpace α γ 𝔖 = bif true then uniformSpace α γ 𝔖 else uniformSpace α γ 𝔖 [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) f : γ → β ⊢ uniformSpace α γ 𝔖 = UniformSpace.comap ((fun x x_1 => x ∘ x_1) f) (uniformSpace α β 𝔖) [PROOFSTEP] simp_rw [UniformOnFun.uniformSpace, UniformSpace.comap_iInf, UniformFun.comap_eq, ← UniformSpace.comap_comap] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) f : γ → β ⊢ ⨅ (s : Set α) (_ : s ∈ 𝔖), UniformSpace.comap ((fun x => f ∘ x) ∘ restrict s) (UniformFun.uniformSpace (↑s) β) = ⨅ (i : Set α) (_ : i ∈ 𝔖), UniformSpace.comap (restrict i ∘ fun x => f ∘ x) (UniformFun.uniformSpace (↑i) β) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : UniformContinuous f ⊢ UniformContinuous (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) [PROOFSTEP] rw [uniformContinuous_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : UniformContinuous f ⊢ uniformSpace α γ 𝔖 ≤ UniformSpace.comap (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) (uniformSpace α β 𝔖) [PROOFSTEP] exact (UniformOnFun.mono (uniformContinuous_iff.mp hf) subset_rfl).trans_eq UniformOnFun.comap_eq [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : UniformInducing f ⊢ UniformInducing (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) [PROOFSTEP] constructor [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : UniformInducing f ⊢ comap (fun x => ((↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) x.fst, (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) = 𝓤 (α →ᵤ[𝔖] γ) [PROOFSTEP] replace hf : (𝓤 β).comap (Prod.map f f) = _ := hf.comap_uniformity [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : comap (Prod.map f f) (𝓤 β) = 𝓤 γ ⊢ comap (fun x => ((↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) x.fst, (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) = 𝓤 (α →ᵤ[𝔖] γ) [PROOFSTEP] change comap (Prod.map (ofFun 𝔖 ∘ (· ∘ ·) f ∘ toFun 𝔖) (ofFun 𝔖 ∘ (· ∘ ·) f ∘ toFun 𝔖)) _ = _ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : comap (Prod.map f f) (𝓤 β) = 𝓤 γ ⊢ comap (Prod.map (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖))) (𝓤 (α →ᵤ[𝔖] β)) = 𝓤 (α →ᵤ[𝔖] γ) [PROOFSTEP] rw [← uniformity_comap] at hf ⊢ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ 𝓤 (α →ᵤ[𝔖] γ) = 𝓤 (α →ᵤ[𝔖] γ) [PROOFSTEP] congr [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ UniformSpace.comap (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) (uniformSpace α β 𝔖) = uniformSpace α γ 𝔖 [PROOFSTEP] rw [← uniformSpace_eq hf, UniformOnFun.comap_eq] [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ f : γ → β hf : 𝓤 γ = 𝓤 γ ⊢ UniformSpace.comap (↑(ofFun 𝔖) ∘ (fun x x_1 => x ∘ x_1) f ∘ ↑(toFun 𝔖)) (uniformSpace α β 𝔖) = UniformSpace.comap ((fun x x_1 => x ∘ x_1) f) (uniformSpace α β 𝔖) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 ⊢ UniformContinuous fun g => ↑(ofFun 𝔗) (g ∘ f) [PROOFSTEP] simp_rw [uniformContinuous_iff, UniformOnFun.uniformSpace, UniformSpace.comap_iInf, ← UniformSpace.comap_comap] -- For any `t ∈ 𝔗`, note `s := f '' t ∈ 𝔖`. -- We will show that `comap s.restrict 𝒰(↥s, β, uβ) ≤ comap (t.restrict ∘ (— ∘ f)) 𝒰(↥t, β, uβ)`. [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 ⊢ ⨅ (s : Set α) (_ : s ∈ 𝔖), UniformSpace.comap (restrict s) (UniformFun.uniformSpace (↑s) β) ≤ ⨅ (i : Set γ) (_ : i ∈ 𝔗), UniformSpace.comap (restrict i ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) (UniformFun.uniformSpace (↑i) β) [PROOFSTEP] refine' le_iInf₂ fun t ht => iInf_le_of_le (f '' t) <| iInf_le_of_le (hf ht) _ -- Let `f'` be the map from `t` to `f '' t` induced by `f`. [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 ⊢ UniformSpace.comap (restrict (f '' t)) (UniformFun.uniformSpace (↑(f '' t)) β) ≤ UniformSpace.comap (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) (UniformFun.uniformSpace (↑t) β) [PROOFSTEP] let f' : t → f '' t := (mapsTo_image f t).restrict f t (f '' t) -- By definition `t.restrict ∘ (— ∘ f) = (— ∘ f') ∘ (f '' t).restrict`. [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 f' : ↑t → ↑(f '' t) := MapsTo.restrict f t (f '' t) (_ : MapsTo f t (f '' t)) ⊢ UniformSpace.comap (restrict (f '' t)) (UniformFun.uniformSpace (↑(f '' t)) β) ≤ UniformSpace.comap (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) (UniformFun.uniformSpace (↑t) β) [PROOFSTEP] have : (t.restrict ∘ fun g : α →ᵤ[𝔖] β => ofFun 𝔗 (g ∘ f)) = (fun g : f '' t → β => g ∘ f') ∘ (f '' t).restrict := rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 f' : ↑t → ↑(f '' t) := MapsTo.restrict f t (f '' t) (_ : MapsTo f t (f '' t)) this : (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) = (fun g => g ∘ f') ∘ restrict (f '' t) ⊢ UniformSpace.comap (restrict (f '' t)) (UniformFun.uniformSpace (↑(f '' t)) β) ≤ UniformSpace.comap (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) (UniformFun.uniformSpace (↑t) β) [PROOFSTEP] rw [this, @UniformSpace.comap_comap (α →ᵤ[𝔖] β) (f '' t →ᵤ β)] -- But this is exactly monotonicity of `comap` applied to -- `UniformFun.precomp_continuous`. [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 f' : ↑t → ↑(f '' t) := MapsTo.restrict f t (f '' t) (_ : MapsTo f t (f '' t)) this : (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) = (fun g => g ∘ f') ∘ restrict (f '' t) ⊢ UniformSpace.comap (restrict (f '' t)) (UniformFun.uniformSpace (↑(f '' t)) β) ≤ UniformSpace.comap (restrict (f '' t)) (UniformSpace.comap (fun g => g ∘ f') (UniformFun.uniformSpace (↑t) β)) [PROOFSTEP] refine' UniformSpace.comap_mono _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 f' : ↑t → ↑(f '' t) := MapsTo.restrict f t (f '' t) (_ : MapsTo f t (f '' t)) this : (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) = (fun g => g ∘ f') ∘ restrict (f '' t) ⊢ UniformFun.uniformSpace (↑(f '' t)) β ≤ UniformSpace.comap (fun g => g ∘ f') (UniformFun.uniformSpace (↑t) β) [PROOFSTEP] rw [← uniformContinuous_iff] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) f : γ → α hf : 𝔗 ⊆ image f ⁻¹' 𝔖 t : Set γ ht : t ∈ 𝔗 f' : ↑t → ↑(f '' t) := MapsTo.restrict f t (f '' t) (_ : MapsTo f t (f '' t)) this : (restrict t ∘ fun g => ↑(ofFun 𝔗) (g ∘ f)) = (fun g => g ∘ f') ∘ restrict (f '' t) ⊢ UniformContinuous fun g => g ∘ f' [PROOFSTEP] exact UniformFun.precomp_uniformContinuous [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) e : γ ≃ α he : 𝔗 ⊆ image ↑e ⁻¹' 𝔖 he' : 𝔖 ⊆ preimage ↑e ⁻¹' 𝔗 src✝ : (γ → β) ≃ (α → β) := Equiv.arrowCongr e (Equiv.refl β) ⊢ 𝔖 ⊆ (image fun x => ↑e.symm x) ⁻¹' 𝔗 [PROOFSTEP] intro s hs [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) e : γ ≃ α he : 𝔗 ⊆ image ↑e ⁻¹' 𝔖 he' : 𝔖 ⊆ preimage ↑e ⁻¹' 𝔗 src✝ : (γ → β) ≃ (α → β) := Equiv.arrowCongr e (Equiv.refl β) s : Set α hs : s ∈ 𝔖 ⊢ s ∈ (image fun x => ↑e.symm x) ⁻¹' 𝔗 [PROOFSTEP] change e.symm '' s ∈ 𝔗 [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) e : γ ≃ α he : 𝔗 ⊆ image ↑e ⁻¹' 𝔖 he' : 𝔖 ⊆ preimage ↑e ⁻¹' 𝔗 src✝ : (γ → β) ≃ (α → β) := Equiv.arrowCongr e (Equiv.refl β) s : Set α hs : s ∈ 𝔖 ⊢ ↑e.symm '' s ∈ 𝔗 [PROOFSTEP] rw [← preimage_equiv_eq_image_symm] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) 𝔗 : Set (Set γ) e : γ ≃ α he : 𝔗 ⊆ image ↑e ⁻¹' 𝔖 he' : 𝔖 ⊆ preimage ↑e ⁻¹' 𝔗 src✝ : (γ → β) ≃ (α → β) := Equiv.arrowCongr e (Equiv.refl β) s : Set α hs : s ∈ 𝔖 ⊢ ↑e ⁻¹' s ∈ 𝔗 [PROOFSTEP] exact he' hs [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : T2Space β h : ⋃₀ 𝔖 = univ ⊢ ∀ (x y : α →ᵤ[𝔖] β), x ≠ y → ∃ u v, IsOpen u ∧ IsOpen v ∧ x ∈ u ∧ y ∈ v ∧ Disjoint u v [PROOFSTEP] intro f g hfg [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g✝ : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : T2Space β h : ⋃₀ 𝔖 = univ f g : α →ᵤ[𝔖] β hfg : f ≠ g ⊢ ∃ u v, IsOpen u ∧ IsOpen v ∧ f ∈ u ∧ g ∈ v ∧ Disjoint u v [PROOFSTEP] obtain ⟨x, hx⟩ := not_forall.mp (mt funext hfg) [GOAL] case intro α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g✝ : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : T2Space β h : ⋃₀ 𝔖 = univ f g : α →ᵤ[𝔖] β hfg : f ≠ g x : α hx : ¬f x = g x ⊢ ∃ u v, IsOpen u ∧ IsOpen v ∧ f ∈ u ∧ g ∈ v ∧ Disjoint u v [PROOFSTEP] obtain ⟨s, hs, hxs⟩ : ∃ s ∈ 𝔖, x ∈ s := mem_sUnion.mp (h.symm ▸ True.intro) [GOAL] case intro.intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x✝ : α p : Filter ι g✝ : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : T2Space β h : ⋃₀ 𝔖 = univ f g : α →ᵤ[𝔖] β hfg : f ≠ g x : α hx : ¬f x = g x s : Set α hs : s ∈ 𝔖 hxs : x ∈ s ⊢ ∃ u v, IsOpen u ∧ IsOpen v ∧ f ∈ u ∧ g ∈ v ∧ Disjoint u v [PROOFSTEP] exact separated_by_continuous (uniformContinuous_eval_of_mem β 𝔖 hxs hs).continuous hx [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : ⋃₀ 𝔖 = univ ⊢ UniformContinuous ↑(toFun 𝔖) [PROOFSTEP] rw [uniformContinuous_pi] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : ⋃₀ 𝔖 = univ ⊢ ∀ (i : α), UniformContinuous fun x => ↑(toFun 𝔖) x i [PROOFSTEP] intro x [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : ⋃₀ 𝔖 = univ x : α ⊢ UniformContinuous fun x_1 => ↑(toFun 𝔖) x_1 x [PROOFSTEP] obtain ⟨s : Set α, hs : s ∈ 𝔖, hxs : x ∈ s⟩ := sUnion_eq_univ_iff.mp h x [GOAL] case intro.intro α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x✝ : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) h : ⋃₀ 𝔖 = univ x : α s : Set α hs : s ∈ 𝔖 hxs : x ∈ s ⊢ UniformContinuous fun x_1 => ↑(toFun 𝔖) x_1 x [PROOFSTEP] exact uniformContinuous_eval_of_mem β 𝔖 hxs hs [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β ⊢ Tendsto F p (𝓝 f) ↔ ∀ (s : Set α), s ∈ 𝔖 → TendstoUniformlyOn F f p s [PROOFSTEP] rw [UniformOnFun.topologicalSpace_eq, nhds_iInf, tendsto_iInf] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β ⊢ (∀ (i : Set α), Tendsto F p (𝓝 f)) ↔ ∀ (s : Set α), s ∈ 𝔖 → TendstoUniformlyOn F f p s [PROOFSTEP] refine' forall_congr' fun s => _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β s : Set α ⊢ Tendsto F p (𝓝 f) ↔ s ∈ 𝔖 → TendstoUniformlyOn F f p s [PROOFSTEP] rw [nhds_iInf, tendsto_iInf] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β s : Set α ⊢ s ∈ 𝔖 → Tendsto F p (𝓝 f) ↔ s ∈ 𝔖 → TendstoUniformlyOn F f p s [PROOFSTEP] refine' forall_congr' fun hs => _ [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β s : Set α hs : s ∈ 𝔖 ⊢ Tendsto F p (𝓝 f) ↔ TendstoUniformlyOn F f p s [PROOFSTEP] rw [nhds_induced (T := _), tendsto_comap_iff, tendstoUniformlyOn_iff_tendstoUniformly_comp_coe, UniformFun.tendsto_iff_tendstoUniformly] [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s✝ s' : Set α x : α p : Filter ι g : ι → α inst✝ : UniformSpace β 𝔖 : Set (Set α) F : ι → α →ᵤ[𝔖] β f : α →ᵤ[𝔖] β s : Set α hs : s ∈ 𝔖 ⊢ TendstoUniformly ((restrict s ∘ ↑UniformFun.toFun) ∘ F) ((restrict s ∘ ↑UniformFun.toFun) f) p ↔ TendstoUniformly (fun i x => F i ↑x) (f ∘ Subtype.val) p [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ ⊢ UniformInducing ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) [PROOFSTEP] constructor [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ ⊢ comap (fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 ((α →ᵤ[𝔖] β) × (α →ᵤ[𝔖] γ))) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] rw [uniformity_prod, comap_inf, comap_comap, comap_comap] [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] have H := @UniformOnFun.inf_eq α (β × γ) 𝔖 (UniformSpace.comap Prod.fst ‹_›) (UniformSpace.comap Prod.snd ‹_›) [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : uniformSpace α (β × γ) 𝔖 = uniformSpace α (β × γ) 𝔖 ⊓ uniformSpace α (β × γ) 𝔖 ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] apply_fun (fun u ↦ @uniformity (α →ᵤ[𝔖] β × γ) u) at H [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : 𝓤 (α →ᵤ[𝔖] β × γ) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] convert H.symm using 1 [GOAL] case h.e'_2 α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : 𝓤 (α →ᵤ[𝔖] β × γ) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] rw [UniformOnFun.comap_eq, UniformOnFun.comap_eq] [GOAL] case h.e'_2 α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : 𝓤 (α →ᵤ[𝔖] β × γ) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] erw [inf_uniformity] [GOAL] case h.e'_2 α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : 𝓤 (α →ᵤ[𝔖] β × γ) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊓ 𝓤 (α →ᵤ[𝔖] β × γ) [PROOFSTEP] rw [uniformity_comap, uniformity_comap] [GOAL] case h.e'_2 α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) inst✝ : UniformSpace γ H : 𝓤 (α →ᵤ[𝔖] β × γ) = 𝓤 (α →ᵤ[𝔖] β × γ) ⊢ comap ((fun p => (p.fst.fst, p.snd.fst)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] β)) ⊓ comap ((fun p => (p.fst.snd, p.snd.snd)) ∘ fun x => (↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.fst, ↑((ofFun 𝔖).symm.trans ((Equiv.arrowProdEquivProdArrow β γ α).trans (Equiv.prodCongr (ofFun 𝔖) (ofFun 𝔖)))) x.snd)) (𝓤 (α →ᵤ[𝔖] γ)) = comap (Prod.map ((fun x x_1 => x ∘ x_1) Prod.fst) ((fun x x_1 => x ∘ x_1) Prod.fst)) (𝓤 (α → β)) ⊓ comap (Prod.map ((fun x x_1 => x ∘ x_1) Prod.snd) ((fun x x_1 => x ∘ x_1) Prod.snd)) (𝓤 (α → γ)) [PROOFSTEP] rfl [GOAL] α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ UniformInducing ↑(Equiv.piComm fun a i => δ i) [PROOFSTEP] constructor [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ comap (fun x => (↑(Equiv.piComm fun a i => δ i) x.fst, ↑(Equiv.piComm fun a i => δ i) x.snd)) (𝓤 ((i : ι) → α →ᵤ[𝔖] δ i)) = 𝓤 (α →ᵤ[𝔖] (i : ι) → δ i) [PROOFSTEP] change comap (Prod.map Function.swap Function.swap) _ = _ [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ comap (Prod.map Function.swap Function.swap) (𝓤 ((i : ι) → α →ᵤ[𝔖] δ i)) = 𝓤 (α →ᵤ[𝔖] (i : ι) → δ i) [PROOFSTEP] erw [← uniformity_comap] [GOAL] case comap_uniformity α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ 𝓤 (α → (y : ι) → δ y) = 𝓤 (α →ᵤ[𝔖] (i : ι) → δ i) [PROOFSTEP] congr [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ UniformSpace.comap Function.swap (Pi.uniformSpace fun i => α →ᵤ[𝔖] δ i) = uniformSpace α ((i : ι) → δ i) 𝔖 [PROOFSTEP] rw [Pi.uniformSpace, UniformSpace.ofCoreEq_toCore, Pi.uniformSpace, UniformSpace.ofCoreEq_toCore, UniformSpace.comap_iInf, UniformOnFun.iInf_eq] [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) ⊢ ⨅ (i : ι), UniformSpace.comap Function.swap (UniformSpace.comap (fun a => a i) (uniformSpace α (δ i) 𝔖)) = ⨅ (i : ι), uniformSpace α ((i : ι) → δ i) 𝔖 [PROOFSTEP] refine' iInf_congr fun i => _ [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) i : ι ⊢ UniformSpace.comap Function.swap (UniformSpace.comap (fun a => a i) (uniformSpace α (δ i) 𝔖)) = uniformSpace α ((i : ι) → δ i) 𝔖 [PROOFSTEP] rw [← UniformSpace.comap_comap, UniformOnFun.comap_eq] [GOAL] case comap_uniformity.h.e_2.h α : Type u_1 β : Type u_2 γ : Type u_3 ι : Type u_4 s s' : Set α x : α p : Filter ι g : ι → α inst✝¹ : UniformSpace β 𝔖 : Set (Set α) δ : ι → Type u_5 inst✝ : (i : ι) → UniformSpace (δ i) i : ι ⊢ UniformSpace.comap ((fun a => a i) ∘ Function.swap) (uniformSpace α (δ i) 𝔖) = UniformSpace.comap ((fun x x_1 => x ∘ x_1) fun a => a i) (uniformSpace α (δ i) 𝔖) [PROOFSTEP] rfl
\section{Block Diagrams} % overview + VRAM \begin{figure}[ht!] \centering \includegraphics[width=6in]{block_diagrams/full.png} \caption{Full block diagram} \end{figure} The hardware consists of four main modules: the FPGA (and supporting hardware), the analog input, the memory devices and display, and the switches. On the block diagram above, the FPGA components are in the bottom left with the FPGA itself represented by the large light blue rectangle, the analog is in the bottom right, the memory is in the top left, and the switches are in the top right. The FPGA itself consists of several separable components, although these will be covered more in the Firmware section (Chapter \ref{firmware}). As a broad overview, the FPGA features a soft-core CPU, a controller for the VRAM and display, logic for handling switch and rotary encoder input, and the entire ADC input and triggering section. As seen in the block diagram, all of these major components have inputs and outputs to the other major hardware components of the board; they are also all buffered to protect the FPGA. The analog section consists of two analog channels (A and B) and an 8-bit logic analyzer. While the logic analyzer feeds directly to the FPGA buffer inputs, the two analog channels are fed through an analog front-end before being converted by the ADC. The analog front-end supports a large range of input voltages due to the input protection and voltage scaling op amp circuits. The front-end also contains a few user-controls: the voltage can be shifted using the voltage shift potentiometers; the input mode can be selected between DC, AC, and GND. While the gain is also variable as a function of the vertical sensitivity rotary encoders, the control is indirect (through the FPGA/CPU) as opposed to being a direct part of the analog circuitry. The memory consists of three separate components: the flash, the SRAM, and the VRAM (plus display). These are connected to the FPGA's soft core CPU as you might expect: address and data buses, as well as chip select and read/write lines. One thing to note is that the VRAM has a separate address bus (9 bits), whereas the flash and SRAM share a 16-bit address bus. The flash memory serves as a non-volatile memory for storing the soft core CPU's operating system. The SRAM serves as external storage for the CPU. The VRAM is memory for the display, discussed in more detail below. Finally, the user interface is controlled by a number of switches and rotary encoders / potentiometers. Some of these directly control the analog circuitry (potentiometers and mode select slide switches), while others indirectly control the board through FPGA logic (pushbutton switches and rotary encoders). Input from these switches is debounced or interpreted (for rotary encoders), then that simplified information is used to generate an interrupt for the CPU. All debouncing and rotary encoder decoding is done in the FPGA logic (not in the CPU's program). \begin{figure}[ht!] \centering \includegraphics[width=3in]{block_diagrams/video.png} \caption{Display block diagram} \end{figure} This is a closer look at the VRAM / Display section of the hardware. The large containing blue block represents components internal to the FPGA, and the other blocks represent external components. As usual, there's a buffer to protect the FPGA from damage. To read/write data to the VRAM (for eventual display by the display), first the CPU tries to write to the VRAM address of interest (18 bits), offset by the VRAM's location in the address map. This actually sends a signal to the VRAM controller (in FPGA logic) that splits the address into the row and column (9 bits each). The VRAM controller sends out the proper signals to the external VRAM chip, allowing the CPU to read or write data. Thus, the VRAM controller and VRAM together form, what looks like to the CPU, a single standard memory component. With the VRAM loaded with display data, the display should be updated to show what's in VRAM. This operation is done completely separate from the CPU (all in FPGA logic) with the display controller. The display is a parallel input device which takes three clocks (VSYNC, HSYNC, DCLK), which will be discussed in more detail later. At each of the dot clocks, the parallel input takes a color for what to display at the current dot. Thus, the VRAM must output (SDQ0-15) to the display each pixel as requested - the VRAM is clocked by (SC). The combination of CPU reads/writes to VRAM and VRAM serial transfers to display completes the operation of the display subcomponent of the hardware. \section{FPGA} \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/main_fpga.png} \caption{FPGA and supporing components schematic diagram} \end{figure} The FPGA is a Quartus EP3C25Q240 Cyclone III FPGA (240-pin quad flat pack) [U4]. Besides various configuration pins, it contains a large number of general purpose I/O. These are connected through buffers [U2,3,5,6,7,8,10,11] to external circuit components. Power for the entire board is provided by [J2] and contains dual $\pm 12V$ power, as well as a higher current $5V$ line. The FPGA operates on three voltages. The core is powered at $1.2V$ with [U13], the internal analog circuitry is powered at $2.5V$ with [U14], and the I/O banks are powered at $3.3V$ with [U9]. \section{FPGA Support} There are a few other supporting components specifically for the FPGA. [J1] is a JTAG header that allows configuring the FPGA logic, as well as downloading code for the soft core CPU. [U1] is a serial configuration chip (EPCS16 with 16MB of space) which allows the FPGA to be re-configured after power is lost, without reprogramming the device through JTAG. [JP1-3] provide mode select capabilities. The board is typically kept in Fast Standard Mode with $3.3V$. [X1] provides a $36MHz$ clock signal. [U12] is a watchdog reset chip that can be used to automatically reset the FPGA (or just the CPU) in the case that the CPU stops operating or reaches an infinite loop. \section{Analog Frontend} \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/analog.png} \caption{Analog section schematic diagram} \end{figure} The analog section contains two channels (A and B) for dual analog input capabilities. Starting from the BNC connector inputs, we can see the full path the signal takes before reaching the ADC to be collected digitally by the FPGA. BNC connectors [J5-6] take analog input from a standard oscilloscope probe (or a 10x probe). Diode packages [D4-5] provide protection from excessive voltages. [SW2-3] allows for selection of the input mode (between DC/AC/GND). From there, the signals are buffered with [U22], then fed into a programmable gain amplifier (selectable -20dB to 20dB gain) [U23]. [U21] is an extended i2c controllable I/O port which allows for selecting the desired gain on the PGA. From the PGA, the signal passes through another high-Z buffer [U19], which also provides level shifting (the shift level is provided by potentiometers [POT1-2], which are analog buffered by unused preamplifiers in the PGA [U23]). Finally, the output is again protected by safety diodes before reaching the ADC. Because the ADC has a voltage input swing of $\pm 0.512V$, the $0.7V_F$ diodes [D2-3] can be connected as shown to provide decent protection. They essentially limit the ADC input to within $0.7V$ of the reference voltage. [U20] is the ADC, which provides 8 bits of data for each of the A and B channels. [P5] is a header for providing 8 bits of logic-analyzer input. \section{Analog Frontend Transfer Properties} Effort was put forth to make sure the analog front-end (at least at near-unity gain) had decent transfer function characteristics. Ideally, at least a $5MHz$ bandwidth and no ringing. There were issues, initially, with ringing, as seen in the left of the image below. However, fine-tuning [C56] and [C57] turns out to allow for the results seen in the middle and right. \begin{figure}[ht!] \centering \includegraphics[width=6in]{specs/tuning.png} \caption{Analog frontend step response (input top; output bottom). The left is an underdamped response [C56] $= 0pF$, the middle is well-damped [C56] $= 2pF$, and the right is overdamped [C56] $= 5pF$.} \end{figure} With the $2pF$ values chosen, measurements of the gain and phase were made at a wide range of frequencies. From the step response, we can tell that the circuit has a nice transfer function, but this allows for a more quantitative characterization. Here are the results (DC input mode, -$6dB$ low/mid-band gain): \begin{table}[ht!] \begin{center} \caption{Transfer gain and phase at various frequencies} \begin{tabular}{|c|c|c|} \hline Frequency & Gain & Phase \\ \hline $0.1Hz$ & $-5.7 dB$ & $0^o$ \\ \hline $0.2Hz$ & $-5.7 dB$ & $0^o$ \\ \hline $0.5Hz$ & $-5.7 dB$ & $0^o$ \\ \hline $1.0Hz$ & $-5.7 dB$ & $0^o$ \\ \hline $\vdots$ & $\vdots$ & $\vdots$ \\ \hline $5kHz$ & $-5.7 dB$ & $0^o$ \\ \hline $10kHz$ & $-5.7 dB$ & $0^o$ \\ \hline $20kHz$ & $-5.7 dB$ & $0^o$ \\ \hline $50kHz$ & $-5.4 dB$ & $0^o$ \\ \hline $100kHz$ & $-5.4 dB$ & $0^o$ \\ \hline $200kHz$ & $-5.4 dB$ & $-7^o$ \\ \hline $500kHz$ & $-5.4 dB$ & $-14^o$ \\ \hline $1MHz$ & $-5.2 dB$ & $-29^o$ \\ \hline $2MHz$ & $-5.4 dB$ & $-54^o$ \\ \hline $3MHz$ & $-6.0 dB$ & $-84^o$ \\ \hline $4MHz$ & $-6.7 dB$ & $-112^o$ \\ \hline $5MHz$ & $-8.0 dB$ & $-140^o$ \\ \hline $6MHz$ & $-9.4 dB$ & $-167^o$ \\ \hline $7MHz$ & $-11 dB$ & $-189^o$ \\ \hline $8MHz$ & $-13 dB$ & $-216^o$ \\ \hline $9MHz$ & $-15 dB$ & $-235^o$ \\ \hline $10MHz$ & $-18 dB$ & $-252^o$ \\ \hline \end{tabular} \end{center} \end{table} \newpage This gives the following Bode plot: \begin{figure}[ht!] \centering \includegraphics[width=4.5in]{specs/bode_raw.png} \caption{Analog input raw Bode plot} \end{figure} This gain and phase function is pretty good. Here's some additional analysis: \begin{figure}[ht!] \centering \includegraphics[width=4.5in]{specs/bode_total.png} \caption{Analog input Bode plot with annotations} \end{figure} As we can see, we achieve the desired $5MHz$ bandwidth with a corner frequency at $5.8MHz$. \newpage \section{ADC and Timing} \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-ANALOG.png} \caption{ADC timing} \end{figure} ADC timing is fairly straightforward. The FPGA provides a steady ADC clock (limited to a max of $80MHz$), which the ADC then uses to synchronously sample analog input and output the digital value. In the configuration shown, ADC channel A output is synchronized with the clock and channel B output is $180^o$ offset from that. Because of the simplicity of timing and the fact that we don't care about small amounts of sample propagation delay, we can simply clock the FPGA sample collection synchronized with the ADC clock to get good data. \section{Memory and Display} \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/memory.png} \caption{Memory schematic diagram} \end{figure} As discussed earlier, flash [U15] and SRAM [U16] are connected in fairly standard configurations. They share a data bus, address bus, and read/write line. Each has a separate chip select input. Both always have outputs enabled since we don't care about saving power. While VRAM [U18] shares the same data bus and read/write line as flash and SRAM, it has its own 9-bit address line and two separate row/column chip selects. It also has a serial clock pin which outputs the next half-word of data to the SDQ line for the display (it should be clocked whenever we want to send a new pixel to the display). The VRAM operates at $5V$ while the display operates at $3.3V$, so [U17] provides necessary voltage level translation. The display itself is a $480 \times 272$ 24-bit RGB display (connector [J3]) with a capacitive touch screen (and a controller that can be communicated with via i2c (connector [J4])). Because VRAM is only 16-bits, the system is only set up to control 5 bits of each color component (15-bit color control). The display is LED backlit (takes $19.2V$), so power is provided from the dual $\pm 12V$ line. \section{SRAM and Timing} \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-RAM-READ.png} \caption{SRAM read timing} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-RAM-WRITE.png} \caption{SRAM write timing} \end{figure} SRAM timing is shown above. Since the FPGA is clocked with a $36MHz$ source ($27ns$ period), we can see that we can satisfy timing requirements if we have one clock cycle latencies for reading and writing, a one clock setup time, and a zero clock hold time. \section{Flash and Timing} \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-ROM-READ.png} \caption{Flash read timing} \end{figure} Flash timing is shown above. Since the FPGA is clocked with a $36MHz$ source ($27ns$ period), we can see that we can satisfy timing requirements if we have three clock cycle latencies for reading and no latencies for setup and hold times. \section{VRAM and Timing} Since VRAM is controlled by the VRAM controller, timing is important to understand what the VRAM controller must be capable of providing. The CPU, on the other hand, should interact with the VRAM controller using a busy signal. That is, after requesting a read or write, it will wait until the busy signal indicates the data can be read (if reading) or de-asserted (if writing). The VRAM has four important operational modes. The first two, read and write, provide their obvious functionality. However, because VRAM is a DRAM, it requires period refreshes (refresh cycle). Finally, because it's a video RAM with one port for the CPU to read/write data and one port for the display to receive data, it also requires a serial row transfer cycle. During this cycle, data from a selected row is transferred to a special part of memory so that on serial clocks, the SDQ line fills with data from sequential memory cells in the selected row of memory. \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-VRAM-READ.png} \caption{VRAM read timing} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-VRAM-WRITE-EARLY.png} \caption{VRAM early write timing} \end{figure} There are a fair number of signals at play, but the important ones for reading and writing are the address and data buses, the RAS/CAS signals, and obviously the read/write (WE) line. \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-VRAM-REFRESH.png} \caption{VRAM refresh timing} \end{figure} A refresh cycle is typically very simple. The timing shown above is for a refresh cycle specific to a particular row. There's also a global refresh that refreshes the entire chip very quickly. \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/FPGA-Oscilloscope-VRAM-SERIAL-READ.png} \caption{VRAM serial row transfer timing} \end{figure} The serial row transfer is also fairly simple. Simply provide the row of interest (the row that you want the display to update), and then provide the serial clocks to sequentially output data from that row. With all of these timings, a state machine can be produced in FPGA logic that provides the necessary signals and delays to trigger the various VRAM modes. See the VRAM state machine VHDL code for more details on specific cycle delays for each of the modes. \section{Display and Timing} The display timing is shown below. The most basic timing is a steady dot clock (DCLK) that is the base pulse of all of the other pulses. During certain portions of the dot clock, each pulse sequences through a row of the display's pixels and any data on the parallel input is read as an RGB value for the display. For each row to be displayed, there are front and back porches of a few dot clocks, during which nothing is changed on the display (this is shown on the bottom timing diagram). Each row is clocked by the HSYNC pulse. Many of these pulses allow for writing multiple rows of the display (as seen in the middle timing diagram). Finally, when a screen's worth of rows are covered, the VSYNC pulses (as seen in the top timing diagram). Just as there were front and back porches for the dot clock with respect to a single HSYNC pulse, likewise there are front and back porches for the HSYNC with respect to a single VSYNC pulse. All of these front and back porches together forms an invisible frame around the true image during which the dot clock is active, but no new pixels are drawn to the screen. \begin{figure}[ht!] \centering \includegraphics[width=6in]{Timing/disp_timing.png} \caption{Display timing} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=3in]{Timing/disp_timing_chart.png} \caption{Display timing values} \end{figure} \section{User Input / Switches} There are three different types of switches used on the board. Five momentary pushbutton switches are used as the screen menu select buttons. Two latching pushbutton switches are used for triggering controls (slope and trigger mode). Finally, five rotary encoders are used - two for the channel A/B vertical sensitivities, one for the time sensitivity, and two for trigger delay and level. \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/switches.png} \caption{Switches schematic diagram} \end{figure} All of the switches are held high by $1k\Omega$ resistors (resistors in the range of $1k\Omega$ are required due to the low input impedance of the buffers). When the switch closes (or during certain phases of the rotary encoder), the switch terminal is brought from $V_{CC}$ to $GND$. From there, the signals are debounced or decoded in FPGA logic to the soft core CPU. \begin{figure}[ht!] \centering \includegraphics[width=3in]{Timing/encoder.jpg} \caption{Rotary encoder timing} \end{figure} Rotary encoder timing is shown above. It uses a gray code between two outputs (A/B). Thus, the rotation direction can be detected from the pattern seen. \section{Board Layout} Refer to the following diagrams to understand the relationship between the raw board layout, the overarching large-scale hardware modules, and the physical part layout. The first diagram is just the raw board layout. Areas in red are top layer copper and areas in blue are bottom layer copper. The next diagram highlights the major hardware modules and buses. Finally, the third diagram overlays components on top, so the overall design can be intuited. \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/board.png} \caption{Board layout (raw)} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/board_annotated.png} \caption{Board layout with annotations} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=6in]{circuit/board_part_overlay.png} \caption{Board layout with top part overlay} \end{figure}
CHAPTER 16 The LISP Editor 16.1. The Editors It is quite possible to use VI, Emacs or other stan- dard editors to edit your lisp programs, and many peo- ple do just that. However there is a lisp structure editor which is particularly good for the editing of lisp programs, and operates in a rather different fashion, namely within a lisp environment. applica- tion. It is handy to know how to use it for fixing problems without exiting from the lisp system (e.g. from the debugger so you can continue to execute rather than having to start over.) The editor is not quite like the top-level and debugger, in that it expects you to type editor commands to it. It will not evaluate whatever you happen to type. (There is an editor command to evaluate things, though.) The editor is available (assuming your system is set up correctly with a lisp library) by typing (load 'cmufncs) and (load 'cmuedit). The most frequent use of the editor is to change function definitions by starting the editor with one of the commands described in section 16.14. (see _e_d_i_t_f), values (_e_d_i_t_v), properties (_e_d_i_t_p), and expressions (_e_d_i_t_e). The beginner is advised to start with the following (very basic) commands: _o_k, _u_n_d_o, _p, #, under which are explained two different basic commands which start with numbers, and f. This documentation, and the editor, were imported from PDP-10 CMULisp by Don Cohen. PDP-10 CMULisp is based on UCILisp, and the editor itself was derived from an early version of Interlisp. Lars Ericson, the author of this section, has provided this very concise sum- mary. Tutorial examples and implementation details may be found in the Interlisp Reference Manual, where a similar editor is described. 9 9The LISP Editor 16-1 The LISP Editor 16-2 16.2. Scope of Attention Attention-changing commands allow you to look at a different part of a Lisp expression you are editing. The sub-structure upon which the editor's attention is centered is called "the current expression". Chang- ing the current expression means shifting attention and not actually modifying any structure. ____________________________________________________________ _S_C_O_P_E _O_F _A_T_T_E_N_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _n (_n>_0) . Makes the nth element of the current expression be the new current expression. -_n (_n>_0). Makes the nth element from the end of the current expression be the new current expression. _0. Makes the next higher expression be the new correct expression. If the intention is to go back to the next higher left parenthesis, use the command !0. _u_p . If a p command would cause the editor to type ... before typing the current expression, (the current expres- sion is a tail of the next higher expression) then has no effect; else, up makes the old current expression the first element in the new current expression. !_0 . Goes back to the next higher left parenthesis. ^ . Makes the top level expression be the current expres- sion. _n_x . Makes the current expression be the next expression. (_n_x _n) equivalent to n nx commands. !_n_x . Makes current expression be the next expression at a higher level. Goes through any number of right parentheses to get to the next expression. _b_k . Makes the current expression be the previous expres- sion in the next higher expression. (_n_t_h _n) _n>_0 . Makes the list starting with the nth element of the current expression be the current expression. (_n_t_h $) - _g_e_n_e_r_a_l_i_z_e_d _n_t_h _c_o_m_m_a_n_d. nth locates $, and then backs up to the current level, where the new current expres- sion is the tail whose first element contains, however dee- ply, the expression that was the terminus of the location operation. Printed: July 21, 1983 The LISP Editor 16-3 :: . (pattern :: . $) e.g., (cond :: return). finds a cond that contains a return, at any depth. (_b_e_l_o_w _c_o_m _x) . The below command is useful for locating a substructure by specifying something it contains. (below cond) will cause the cond clause containing the current expression to become the new current expression. Suppose you are editing a list of lists, and want to find a sublist that contains a foo (at any depth). Then simply executes f foo (below ). (_n_e_x _x) . same as (_b_e_l_o_w _x) followed by nx. For example, if you are deep inside of a selectq clause, you can advance to the next clause with (_n_e_x _s_e_l_e_c_t_q). _n_e_x. The atomic form of _n_e_x is useful if you will be performing repeated executions of (_n_e_x _x). By simply marking the chain corresponding to x, you can use _n_e_x to step through the sublists. ____________________________________________________________ 16.3. Pattern Matching Commands Many editor commands that search take patterns. A pattern _p_a_t matches with x if: ____________________________________________________________ _P_A_T_T_E_R_N _S_P_E_C_I_F_I_C_A_T_I_O_N _S_U_M_M_A_R_Y - _p_a_t is _e_q to x. - _p_a_t is &. - _p_a_t is a number and equal to x. - if (car _p_a_t) is the atom *any*, (cdr _p_a_t) is a list of patterns, and _p_a_t matches x if and only if one of the pat- terns on (cdr _p_a_t) matches x. - if _p_a_t is a literal atom or string, and (nthchar _p_a_t -1) is @, then _p_a_t matches with any literal atom or string which has the same initial characters as _p_a_t, e.g. ver@ matches with verylongatom, as well as "verylongstring". - if (car _p_a_t) is the atom --, _p_a_t matches x if (a) (cdr _p_a_t)=nil, i.e. _p_a_t=(--), e.g., (a --) matches (a) (a b c) and (a . b) in other words, -- can match any tail of a list. (b) (cdr _p_a_t) matches with some tail of x, e.g. (a Printed: July 21, 1983 The LISP Editor 16-4 -- (&)) will match with (a b c (d)), but not (a b c d), or (a b c (d) e). however, note that (a -- (&) --) will match with (a b c (d) e). in other words, -- will match any inte- rior segment of a list. - if (car _p_a_t) is the atom ==, _p_a_t matches x if and only if (cdr _p_a_t) is _e_q to x. (this pattern is for use by programs that call the editor as a subroutine, since any non-atomic expression in a command typed in by the user obviously can- not be _e_q to existing structure.) - otherwise if x is a list, _p_a_t matches x if (car _p_a_t) matches (car x), and (cdr _p_a_t) matches (cdr x). - when searching, the pattern matching routine is called only to match with elements in the structure, unless the pattern begins with :::, in which case cdr of the pattern is matched against tails in the structure. (in this case, the tail does not have to be a proper tail, e.g. (::: a --) will match with the element (a b c) as well as with cdr of (x a b c), since (a b c) is a tail of (a b c).) ____________________________________________________________ 16.3.1. Commands That Search ____________________________________________________________ _S_E_A_R_C_H _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _f _p_a_t_t_e_r_n . f informs the editor that the next command is to be interpreted as a pattern. If no pattern is given on the same line as the f then the last pattern is used. f pattern means find the next instance of pattern. (_f _p_a_t_t_e_r_n _n). Finds the next instance of pattern. (_f _p_a_t_t_e_r_n _t). similar to f pattern, except, for example, if the current expression is (cond ..), f cond will look for the next cond, but (f cond t) will 'stay here'. (_f _p_a_t_t_e_r_n _n) _n>_0. Finds the nth place that pattern matches. If the current expression is (foo1 foo2 foo3), (f f00@ 3) will find foo3. (_f _p_a_t_t_e_r_n) _o_r (_f _p_a_t_t_e_r_n _n_i_l). only matches with elements at the top level of the current expression. If the current expression is (_p_r_o_g _n_i_l (_s_e_t_q _x (_c_o_n_d & &)) (_c_o_n_d &) ...) f (cond --) will find the cond inside the setq, whereas (f (cond --)) will find the top level cond, i.e., the second one. Printed: July 21, 1983 The LISP Editor 16-5 (_s_e_c_o_n_d . $) . same as (lc . $) followed by another (lc . $) except that if the first succeeds and second fails, no change is made to the edit chain. (_t_h_i_r_d . $) . Similar to second. (_f_s _p_a_t_t_e_r_n_1 ... _p_a_t_t_e_r_n_n) . equivalent to f pattern1 fol- lowed by f pattern2 ... followed by f pattern n, so that if f pattern m fails, edit chain is left at place pattern m-1 matched. (_f= _e_x_p_r_e_s_s_i_o_n _x) . Searches for a structure eq to expres- sion. (_o_r_f _p_a_t_t_e_r_n_1 ... _p_a_t_t_e_r_n_n) . Searches for an expression that is matched by either pattern1 or ... patternn. _b_f _p_a_t_t_e_r_n . backwards find. If the current expression is (_p_r_o_g _n_i_l (_s_e_t_q _x (_s_e_t_q _y (_l_i_s_t _z))) (_c_o_n_d ((_s_e_t_q _w --) --)) --) f list followed by bf setq will leave the current expression as (setq y (list z)), as will f cond followed by bf setq (_b_f _p_a_t_t_e_r_n _t). backwards find. Search always includes current expression, i.e., starts at end of current expres- sion and works backward, then ascends and backs up, etc. ____________________________________________________________ 16.3.1.1. Location Specifications Many editor commands use a method of specifying position called a location specification. The meta- symbol $ is used to denote a location specifica- tion. $ is a list of commands interpreted as described above. $ can also be atomic, in which case it is interpreted as (list $). a location specification is a list of edit commands that are executed in the normal fashion with two exceptions. first, all commands not recognized by the editor are interpreted as though they had been preceded by f. The location specification (cond 2 3) specifies the 3rd element in the first clause of the next cond. the if command and the ## function provide a way of using in location specifications arbitrary predicates applied to elements in the current expression. In insert, delete, replace and change, if $ is Printed: July 21, 1983 The LISP Editor 16-6 nil (empty), the corresponding operation is per- formed on the current edit chain, i.e. (replace with (car x)) is equivalent to (:(car x)). for added readability, here is also permitted, e.g., (insert (print x) before here) will insert (print x) before the current expression (but not change the edit chain). It is perfectly legal to ascend to insert, replace, or delete. for example (insert (_r_e_t_u_r_n) after ^ prog -1) will go to the top, find the first prog, and insert a (_r_e_t_u_r_n) at its end, and not change the current edit chain. The a, b, and : commands all make special checks in e1 thru em for expressions of the form (## . coms). In this case, the expression used for inserting or replacing is a copy of the current expression after executing coms, a list of edit commands. (insert (## f cond -1 -1) after3) will make a copy of the last form in the last clause of the next cond, and insert it after the third element of the current expres- sion. $. In descriptions of the editor, the meta- symbol $ is used to denote a location specifica- tion. $ is a list of commands interpreted as described above. $ can also be atomic. ____________________________________________________________ _L_O_C_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y (_l_c . $) . Provides a way of explicitly invoking the loca- tion operation. (lc cond 2 3) will perform search. (_l_c_l . $) . Same as lc except search is confined to current expression. To find a cond containing a _r_e_t_u_r_n, one might use the location specification (cond (lcl _r_e_t_u_r_n) ) where the would reverse the effects of the lcl command, and make the final current expression be the cond. ____________________________________________________________ 16.3.2. The Edit Chain The edit-chain is a list of which the first element is the the one you are now editing ("current expression"), the next element is what would become the current expression if you were to do a 0, etc., until the last element which is the expression that was passed to the editor. Printed: July 21, 1983 The LISP Editor 16-7 ____________________________________________________________ _E_D_I_T _C_H_A_I_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _m_a_r_k . Adds the current edit chain to the front of the list marklst. _ . Makes the new edit chain be (car marklst). (_ _p_a_t_t_e_r_n) . Ascends the edit chain looking for a link which matches pattern. for example: __ . Similar to _ but also erases the mark. \ . Makes the edit chain be the value of unfind. unfind is set to the current edit chain by each command that makes a "big jump", i.e., a command that usually performs more than a single ascent or descent, namely ^, _, __, !nx, all com- mands that involve a search, e.g., f, lc, ::, below, et al and and themselves. if the user types f cond, and then f car, would take him back to the cond. another would take him back to the car, etc. \_p . Restores the edit chain to its state as of the last print operation. If the edit chain has not changed since the last printing, \p restores it to its state as of the printing before that one. If the user types p followed by 3 2 1 p, \p will return to the first p, i.e., would be equivalent to 0 0 0. Another \p would then take him back to the second p. ____________________________________________________________ 16.4. Printing Commands ____________________________________________________________ _P_R_I_N_T_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _p Prints current expression in abbreviated form. (p m) prints mth element of current expression in abbreviated form. (p m n) prints mth element of current expression as though printlev were given a depth of n. (p 0 n) prints current expression as though printlev were given a depth of n. (p cond 3) will work. ? . prints the current expression as though printlev were given a depth of 100. 9 9 Printed: July 21, 1983 The LISP Editor 16-8 _p_p . pretty-prints the current expression. _p_p*. is like pp, but forces comments to be shown. ____________________________________________________________ 16.5. Structure Modification Commands All structure modification commands are undoable. See _u_n_d_o. ____________________________________________________________ _S_T_R_U_C_T_U_R_E _M_O_D_I_F_I_C_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y # [_e_d_i_t_o_r _c_o_m_m_a_n_d_s] (n) n>1 deletes the corresponding ele- ment from the current expression. (_n _e_1 ... _e_m) _n,_m>_1 replaces the nth element in the current expression with e1 ... em. (-_n _e_1 ... _e_m) _n,_m>_1 inserts e1 ... em before the n ele- ment in the current expression. (_n _e_1 ... _e_m) (the letter "n" for "next" or "nconc", not a number) m>1 attaches e1 ... em at the end of the current expression. (_a _e_1 ... _e_m) . inserts e1 ... em after the current expression (or after its first element if it is a tail). (_b _e_1 ... _e_m) . inserts e1 ... em before the current expression. to insert foo before the last element in the current expression, perform -1 and then (b foo). (: _e_1 ... _e_m) . replaces the current expression by e1 ... em. If the current expression is a tail then replace its first element. _d_e_l_e_t_e _o_r (:) . deletes the current expression, or if the current expression is a tail, deletes its first element. (_d_e_l_e_t_e . $). does a (lc . $) followed by delete. current edit chain is not changed. (_i_n_s_e_r_t _e_1 ... _e_m _b_e_f_o_r_e . $) . similar to (lc. $) fol- lowed by (b e1 ... em). (_i_n_s_e_r_t _e_1 ... _e_m _a_f_t_e_r . $). similar to insert before Printed: July 21, 1983 The LISP Editor 16-9 except uses a instead of b. (_i_n_s_e_r_t _e_1 ... _e_m _f_o_r . $). similar to insert before except uses : for b. (_r_e_p_l_a_c_e $ _w_i_t_h _e_1 ... _e_m) . here $ is the segment of the command between replace and with. (_c_h_a_n_g_e $ _t_o _e_1 ... _e_m) . same as replace with. ____________________________________________________________ 16.6. Extraction and Embedding Commands ____________________________________________________________ _E_X_T_R_A_C_T_I_O_N _A_N_D _E_M_B_E_D_D_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y (_x_t_r . $) . replaces the original current expression with the expression that is current after performing (lcl . $). (_m_b_d _x) . x is a list, substitutes the current expression for all instances of the atom * in x, and replaces the current expression with the result of that substitution. (mbd x) : x atomic, same as (mbd (x *)). (_e_x_t_r_a_c_t $_1 _f_r_o_m $_2) . extract is an editor command which replaces the current expression with one of its subexpres- sions (from any depth). ($1 is the segment between extract and from.) example: if the current expression is (print (cond ((null x) y) (t z))) then following (extract y from cond), the current expression will be (print y). (extract 2 -1 from cond), (extract y from 2), (extract 2 -1 from 2) will all produce the same result. (_e_m_b_e_d $ _i_n . _x) . embed replaces the current expression with a new expression which contains it as a subexpression. ($ is the segment between embed and in.) example: (embed print in setq x), (embed 3 2 in _r_e_t_u_r_n), (embed cond 3 1 in (or * (null x))). ____________________________________________________________ 16.7. Move and Copy Commands 9 9 Printed: July 21, 1983 The LISP Editor 16-10 ____________________________________________________________ _M_O_V_E _A_N_D _C_O_P_Y _C_O_M_M_A_N_D _S_U_M_M_A_R_Y (_m_o_v_e $_1 _t_o _c_o_m . $_2) . ($1 is the segment between move and to.) where com is before, after, or the name of a list com- mand, e.g., :, n, etc. If $2 is nil, or (here), the current position specifies where the operation is to take place. If $1 is nil, the move command allows the user to specify some place the current expression is to be moved to. if the current expression is (a b d c), (move 2 to after 4) will make the new current expression be (a c d b). (_m_v _c_o_m . $) . is the same as (move here to com . $). (_c_o_p_y $_1 _t_o _c_o_m . $_2) is like move except that the source expression is not deleted. (_c_p _c_o_m . $). is like mv except that the source expression is not deleted. ____________________________________________________________ 16.8. Parentheses Moving Commands The commands presented in this section permit modification of the list structure itself, as opposed to modifying com- ponents thereof. their effect can be described as inserting or removing a single left or right parenthesis, or pair of left and right parentheses. ____________________________________________________________ _P_A_R_E_N_T_H_E_S_E_S _M_O_V_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y (_b_i _n _m) . both in. inserts parentheses before the nth element and after the mth element in the current expression. example: if the current expression is (a b (c d e) f g), then (bi 2 4) will modify it to be (a (b (c d e) f) g). (bi n) : same as (bi n n). example: if the current expression is (a b (c d e) f g), then (bi -2) will modify it to be (a b (c d e) (f) g). (_b_o _n) . both out. removes both parentheses from the nth element. example: if the current expression is (a b (c d e) f g), then (bo d) will modify it to be (a b c d e f g). (_l_i _n) . left in. inserts a left parenthesis before the nth element (and a matching right parenthesis at the end of the current expression). example: if the current expres- sion is (a b (c d e) f g), then (li 2) will modify it to be Printed: July 21, 1983 The LISP Editor 16-11 (a (b (c d e) f g)). (_l_o _n) . left out. removes a left parenthesis from the nth element. all elements following the nth element are deleted. example: if the current expression is (a b (c d e) f g), then (lo 3) will modify it to be (a b c d e). (_r_i _n _m) . right in. move the right parenthesis at the end of the nth element in to after the mth element. inserts a right parenthesis after the mth element of the nth ele- ment. The rest of the nth element is brought up to the level of the current expression. example: if the current expression is (a (b c d e) f g), (ri 2 2) will modify it to be (a (b c) d e f g). (_r_o _n) . right out. move the right parenthesis at the end of the nth element out to the end of the current expres- sion. removes the right parenthesis from the nth element, moving it to the end of the current expression. all elements following the nth element are moved inside of the nth element. example: if the current expression is (a b (c d e) f g), (ro 3) will modify it to be (a b (c d e f g)). (_r _x _y) replaces all instances of x by y in the current expression, e.g., (r caadr cadar). x can be the s- expression (or atom) to be substituted for, or can be a pat- tern which specifies that s-expression (or atom). (_s_w _n _m) switches the nth and mth elements of the current expression. for example, if the current expression is (list (cons (car x) (car y)) (cons (cdr y))), (sw 2 3) will modify it to be (list (cons (cdr x) (cdr y)) (cons (car x) (car y))). (sw car cdr) would produce the same result. ____________________________________________________________ 16.8.1. Using to and thru to, thru, extract, embed, delete, replace, and move can be made to operate on several contiguous ele- ments, i.e., a segment of a list, by using the to or thru command in their respective location specifications. thru and to are intended to be used in conjunction with extract, embed, delete, replace, and move. to and thru can also be used directly with xtr (which takes after a location specification), as in (xtr (2 thru 4)) (from the current expression). 9 9 Printed: July 21, 1983 The LISP Editor 16-12 ____________________________________________________________ _T_O _A_N_D _T_H_R_U _C_O_M_M_A_N_D _S_U_M_M_A_R_Y ($_1 _t_o $_2) . same as thru except last element not included. ($_1 _t_o). same as ($1 thru -1) ($_1 _t_h_r_u $_2) . If the current expression is (a (b (c d) (e) (f g h) i) j k), following (c thru g), the current expression will be ((c d) (e) (f g h)). If both $1 and $2 are numbers, and $2 is greater than $1, then $2 counts from the beginning of the current expression, the same as $1. in other words, if the current expression is (a b c d e f g), (3 thru 4) means (c thru d), not (c thru f). in this case, the corresponding bi command is (bi 1 $2-$1+1). ($_1 _t_h_r_u). same as ($_1 _t_h_r_u -_1). ____________________________________________________________ 16.9. Undoing Commands each command that causes struc- ture modification automatically adds an entry to the front of undolst containing the information required to restore all pointers that were changed by the com- mand. The undo command undoes the last, i.e., most recent such command. ____________________________________________________________ _U_N_D_O _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _u_n_d_o . the undo command undoes most recent, structure modification command that has not yet been undone, and prints the name of that command, e.g., mbd undone. The edit chain is then exactly what it was before the 'undone' com- mand had been performed. !_u_n_d_o . undoes all modifications performed during this editing session, i.e., this call to the editor. _u_n_b_l_o_c_k . removes an undo-block. If executed at a non- blocked state, i.e., if undo or !undo could operate, types not blocked. _t_e_s_t . adds an undo-block at the front of undolst. note that test together with !undo provide a 'tentative' mode for editing, i.e., the user can perform a number of changes, and then undo all of them with a single !undo Printed: July 21, 1983 The LISP Editor 16-13 command. _u_n_d_o_l_s_t [_v_a_l_u_e]. each editor command that causes structure modification automatically adds an entry to the front of undolst containing the information required to restore all pointers that were changed by the command. ?? prints the entries on undolst. The entries are listed most recent entry first. ____________________________________________________________ 16.10. Commands that Evaluate ____________________________________________________________ _E_V_A_L_U_A_T_I_O_N _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _e . only when typed in, (i.e., (insert d before e) will treat e as a pattern) causes the editor to call the lisp interpreter giving it the next input as argument. (_e _x) evaluates x, and prints the result. (e x t) same as (e x) but does not print. (_i _c _x_1 ... _x_n) same as (c y1 ... yn) where yi=(eval xi). example: (i 3 (cdr foo)) will replace the 3rd element of the current expression with the cdr of the value of foo. (i n foo (car fie)) will attach the value of foo and car of the value of fie to the end of the current expression. (i f= foo t) will search for an expression eq to the value of foo. If c is not an atom, it is evaluated as well. (_c_o_m_s _x_1 ... _x_n) . each xi is evaluated and its value executed as a command. The i command is not very convenient for computing an entire edit command for execution, since it computes the command name and its arguments separately. also, the i command cannot be used to compute an atomic command. The coms and comsq commands provide more gen- eral ways of computing commands. (coms (cond (x (list 1 x)))) will replace the first element of the current expres- sion with the value of x if non-nil, otherwise do nothing. (nil as a command is a nop.) (_c_o_m_s_q _c_o_m_1 ... _c_o_m_n) . executes com1 ... comn. comsq is mainly useful in conjunction with the coms command. for example, suppose the user wishes to compute an entire list of commands for evaluation, as opposed to computing each command one at a time as does the coms command. he would then write (coms (cons (quote comsq) x)) where x computed Printed: July 21, 1983 The LISP Editor 16-14 the list of commands, e.g., (coms (cons (quote comsq) (get foo (quote commands)))) ____________________________________________________________ 16.11. Commands that Test ____________________________________________________________ _T_E_S_T_I_N_G _C_O_M_M_A_N_D _S_U_M_M_A_R_Y (_i_f _x) generates an error unless the value of (eval x) is non-nil, i.e., if (eval x) causes an error or (eval x)=nil, if will cause an error. (if x coms1 coms2) if (eval x) is non-nil, execute coms1; if (eval x) causes an error or is equal to nil, execute coms2. (if x coms1) if (eval x) is non-nil, execute coms1; otherwise generate an error. (_l_p . _c_o_m_s) . repeatedly executes coms, a list of commands, until an error occurs. (lp f print (n t)) will attach a t at the end of every print expression. (lp f print (if (## 3) nil ((n t)))) will attach a t at the end of each print expression which does not already have a second argument. (i.e. the form (## 3) will cause an error if the edit command 3 causes an error, thereby select- ing ((n t)) as the list of commands to be executed. The if could also be written as (if (cddr (##)) nil ((n t))).). (_l_p_q . _c_o_m_s) same as lp but does not print n occurrences. (_o_r_r _c_o_m_s_1 ... _c_o_m_s_n) . orr begins by executing coms1, a list of commands. If no error occurs, orr is finished. otherwise, orr restores the edit chain to its original value, and continues by executing coms2, etc. If none of the command lists execute without errors, i.e., the orr "drops off the end", orr generates an error. otherwise, the edit chain is left as of the completion of the first command list which executes without error. ____________________________________________________________ 16.12. Editor Macros Many of the more sophisticated branching commands in the editor, such as orr, if, etc., are most often used in conjunction with edit macros. The macro feature permits the user to define new commands and Printed: July 21, 1983 The LISP Editor 16-15 thereby expand the editor's repertoire. (however, built in commands always take precedence over mac- ros, i.e., the editor's repertoire can be expanded, but not modified.) macros are defined by using the m command. (_m _c . _c_o_m_s) for c an atom, m defines c as an atomic command. (if a macro is redefined, its new defini- tion replaces its old.) executing c is then the same as executing the list of commands coms. macros can also define list commands, i.e., commands that take arguments. (m (c) (arg[1] ... arg[n]) . coms) c an atom. m defines c as a list command. executing (c e1 ... en) is then performed by substituting e1 for arg[1], ... en for arg[n] throughout coms, and then executing coms. a list command can be defined via a macro so as to take a fixed or indefinite number of 'arguments'. The form given above specified a macro with a fixed number of argu- ments, as indicated by its argument list. if the of arguments. (m (c) args . coms) c, args both atoms, defines c as a list command. executing (c e1 ... en) is performed by substituting (e1 ... en), i.e., cdr of the command, for args throughout coms, and then executing coms. (m bp bk up p) will define bp as an atomic command which does three things, a bk, an up, and a p. note that macros can use commands defined by macros as well as built in commands in their definitions. for example, suppose z is defined by (m z -1 (if (null (##)) nil (p))), i.e. z does a -1, and then if the current expression is not nil, a p. now we can define zz by (m zz -1 z), and zzz by (m zzz -1 -1 z) or (m zzz -1 zz). we could define a more general bp by (m (bp) (n) (bk n) up p). (bp 3) would perform (bk 3), followed by an up, followed by a p. The com- mand second can be defined as a macro by (m (2nd) x (orr ((lc . x) (lc . x)))). Note that for all editor commands, 'built in' com- mands as well as commands defined by macros, atomic definitions and list definitions are completely independent. in other words, the existence of an atomic definition for c in no way affects the treat- ment of c when it appears as car of a list command, and the existence of a list definition for c in no way affects the treatment of c when it appears as an atom. in particular, c can be used as the name of either an atomic command, or a list command, or both. in the latter case, two entirely different defini- tions can be used. note also that once c is defined as an atomic command via a macro definition, Printed: July 21, 1983 The LISP Editor 16-16 it will not be searched for when used in a location specification, unless c is preceded by an f. (insert -- before bp) would not search for bp, but instead perform a bk, an up, and a p, and then do the inser- tion. The corresponding also holds true for list com- mands. (_b_i_n_d . _c_o_m_s) bind is an edit command which is useful mainly in macros. it binds three dummy vari- ables #1, #2, #3, (initialized to nil), and then exe- cutes the edit commands coms. note that these bindings are only in effect while the commands are being executed, and that bind can be used recursively; it will rebind #1, #2, and #3 each time it is invoked. _u_s_e_r_m_a_c_r_o_s [_v_a_l_u_e]. this variable contains the users editing macros . if you want to save your mac- ros then you should save usermacros. you should probably also save editcomsl. _e_d_i_t_c_o_m_s_l [_v_a_l_u_e]. editcomsl is the list of "list commands" recognized by the editor. (these are the ones of the form (command arg1 arg2 ...).) 16.13. Miscellaneous Editor Commands ____________________________________________________________ _M_I_S_C_E_L_L_A_N_E_O_U_S _E_D_I_T_O_R _C_O_M_M_A_N_D _S_U_M_M_A_R_Y _o_k . Exits from the editor. _n_i_l . Unless preceded by f or bf, is always a null opera- tion. _t_t_y: . Calls the editor recursively. The user can then type in commands, and have them executed. The tty: command is completed when the user exits from the lower editor (with ok or stop). the tty: command is extremely use- ful. it enables the user to set up a complex operation, and perform interactive attention-changing commands part way through it. for example the command (move 3 to after cond 3 p tty:) allows the user to interact, in effect, within the move command. he can verify for himself that the correct location has been found, or complete the specification "by hand". in effect, tty: says "I'll tell you what you should do when you get there." _s_t_o_p . exits from the editor with an error. mainly for use Printed: July 21, 1983 The LISP Editor 16-17 in conjunction with tty: commands that the user wants to abort. since all of the commands in the editor are errset protected, the user must exit from the editor via a command. stop provides a way of distinguishing between a successful and unsuccessful (from the user's standpoint) editing ses- sion. _t_l . tl calls (top-level). to return to the editor just use the _r_e_t_u_r_n top-level command. _r_e_p_a_c_k . permits the 'editing' of an atom or string. (_r_e_p_a_c_k $) does (lc . $) followed by repack, e.g. (repack this@). (_m_a_k_e_f_n _f_o_r_m _a_r_g_s _n _m) . makes (car form) an expr with the nth through mth elements of the current expression with each occurrence of an element of (cdr form) replaced by the corresponding element of args. The nth through mth elements are replaced by form. (_m_a_k_e_f_n _f_o_r_m _a_r_g_s _n). same as (makefn form args n n). (_s _v_a_r . $) . sets var (using setq) to the current expres- sion after performing (lc . $). (s foo) will set foo to the current expression, (s foo -1 1) will set foo to the first element in the last element of the current expres- sion. ____________________________________________________________ 16.14. Editor Functions (editf s_x1 ...) SIDE EFFECT: edits a function. s_x1 is the name of the function, any additional arguments are an optional list of commands. RETURNS: s_x1. NOTE: if s_x1 is not an editable function, editf gen- erates an fn not editable error. 9 9 Printed: July 21, 1983 The LISP Editor 16-18 (edite l_expr l_coms s_atm)) edits an expression. its value is the last element of (editl (list l_expr) l_coms s_atm nil nil). (editracefn s_com) is available to help the user debug complex edit macros, or subroutine calls to the editor. editracefn is to be defined by the user. whenever the value of editracefn is non-nil, the editor calls the function editracefn before executing each command (at any level), giving it that command as its argument. editracefn is initially equal to nil, and undefined. (editv s_var [ g_com1 ... ]) SIDE EFFECT: similar to editf, for editing values. editv sets the variable to the value returned. RETURNS: the name of the variable whose value was edited. (editp s_x) SIDE EFFECT: similar to editf for editing property lists. used if x is nil. RETURNS: the atom whose property list was edited. (editl coms atm marklst mess) SIDE EFFECT: editl is the editor. its first argument is the edit chain, and its value is an edit chain, namely the value of l at the time editl is exited. (l is a special variable, and so can be examined or set by edit commands. ^ is equivalent to (e (setq l(last l)) t).) coms is an optional list of commands. for interactive edit- ing, coms is nil. in this case, editl types edit and then waits for input from the teletype. (if mess is not nil editl types it instead of edit. for example, the tty: command is essentially (setq l (editl l nil nil nil (quote tty:))).) exit occurs only via an ok, stop, or save command. If coms is not nil, no message is typed, and each member of coms is treated as a command and executed. If an Printed: July 21, 1983 The LISP Editor 16-19 error occurs in the execution of one of the commands, no error message is printed , the rest of the commands are ignored, and editl exits with an error, i.e., the effect is the same as though a stop com- mand had been executed. If all commands execute successfully, editl returns the current value of l. marklst is the list of marks. on calls from editf, atm is the name of the function being edited; on calls from editv, the name of the vari- able, and calls from editp, the atom of which some property of its property list is being edited. The property list of atm is used by the save command for saving the state of the edit. save will not save anything if atm=nil i.e., when editing arbitrary expressions via edite or editl directly. (editfns s_x [ g_coms1 ... ]) fsubr function, used to perform the same editing operations on several functions. editfns maps down the list of func- tions, prints the name of each function, and calls the edi- tor (via editf) on that function. EXAMPLE: editfns foofns (r fie fum)) will change every fie to fum in each of the functions on foofns. NOTE: the call to the editor is errset protected, so that if the editing of one function causes an error, editfns will proceed to the next func- tion. in the above example, if one of the functions did not contain a fie, the r command would cause an error, but editing would con- tinue with the next function. The value of editfns is nil. (edit4e pat y) SIDE EFFECT: is the pattern match routine. RETURNS: t if pat matches y. see edit-match for defini- tion of 'match'. NOTE: before each search operation in the editor begins, the entire pattern is scanned for atoms or strings that end in at-signs. These are replaced by patterns of the form (cons (quote /@) (explodec atom)). from the Printed: July 21, 1983 The LISP Editor 16-20 standpoint of edit4e, pattern type 5, atoms or strings ending in at-signs, is really "if car[pat] is the atom @ (at-sign), pat will match with any literal atom or string whose ini- tial character codes (up to the @) are the same as those in cdr[pat]." if the user wishes to call edit4e directly, he must therefore convert any patterns which contain atoms or strings ending in at-signs to the form recognized by edit4e. this can be done via the function editfpat. (editfpat pat flg) makes a copy of pat with all patterns of type 5 (see edit- match) converted to the form expected by edit4e. flg should be passed as nil (flg=t is for internal use by the editor). (editfindp x pat flg) NOTE: Allows a program to use the edit find command as a pure predicate from outside the editor. x is an expression, pat a pattern. The value of edit- findp is t if the command f pat would succeed, nil otherwise. editfindp calls editfpat to con- vert pat to the form expected by edit4e, unless flg=t. if the program is applying editfindp to several different expressions using the same pat- tern, it will be more efficient to call editfpat once, and then call editfindp with the converted pattern and flg=t. (## g_com1 ...) RETURNS: what the current expression would be after executing the edit commands com1 ... starting from the present edit chain. generates an error if any of comi cause errors. The current edit chain is never changed. example: (i r (quote x) (## (cons ..z))) replaces all x's in the current expression by the first cons containing a z. 9 9 Printed: July 21, 1983
SUBROUTINE GDXINP ( gdfile, gdatim, gvcord, cxstns, gfunc, + cint, scale, line, + ptype, yaxis, border, gvect, + wind, refvec, skip, title, clear, + device, text, panel, contur, fint, fline, + ctype, clrbar, ijskip, iret ) C************************************************************************ C* GDXINP * C* * C* This subroutine gets the input parameters for GDCROSS. * C* * C* GDXINP ( GDFILE, GDATIM, GVCORD, CXSTNS, GFUNC, CINT, SCALE, LINE, * C* PTYPE, YAXIS, BORDER, GVECT, WIND, REFVEC, SKIP, TITLE, * C* CLEAR, DEVICE, TEXT, PANEL, CONTUR, FINT, FLINE, * C* CTYPE, CLRBAR, IJSKIP, IRET ) * C* * C** * C* Log: * C* K. F. BRill/GSC 5/89 Created from GDPINP * C* S. Schotz/GSC 7/90 Update for IN_LINE * C* K. Brill/NMC 01/92 Added CONTUR, FINT, FLINE, CTYPE * C* L. Sager/NMC 7/93 Added REFVEC * C* S. Jacobs/EAI 9/93 Added CLRBAR * C* T. Lee/SAIC 3/02 Returned SKIP with ' ' * C* K. Brill/HPC 12/02 Added IJSKIP * C************************************************************************ CHARACTER*(*) gdfile, gdatim, gvcord, cxstns, gfunc, gvect, + cint, scale, line, + ptype, yaxis, border, wind, refvec, + skip, title, device, text, panel, contur, + fint, fline, ctype, clrbar, ijskip LOGICAL clear INTEGER ier(25) C------------------------------------------------------------------------ skip = ' ' CALL IP_STR ( 'GDFILE', gdfile, ier(1) ) CALL IP_STR ( 'GDATTIM', gdatim, ier(2) ) CALL IP_STR ( 'GVCORD', gvcord, ier(3) ) CALL IP_STR ( 'CXSTNS', cxstns, ier(4) ) CALL IP_STR ( 'GFUNC', gfunc, ier(5) ) CALL IP_STR ( 'CINT', cint, ier(6) ) CALL IP_STR ( 'SCALE', scale, ier(7) ) CALL IP_STR ( 'LINE', line, ier(8) ) CALL IP_STR ( 'PTYPE', ptype, ier(9) ) CALL IP_STR ( 'YAXIS', yaxis, ier(10) ) CALL IP_STR ( 'BORDER', border, ier(11) ) CALL IP_STR ( 'GVECT' , gvect, ier(12) ) CALL IP_STR ( 'WIND', wind, ier(13) ) CALL IP_STR ( 'REFVEC', refvec, ier(14) ) CALL IP_STR ( 'TITLE', title, ier(15) ) CALL IP_LOG ( 'CLEAR', clear, ier(16) ) CALL IP_STR ( 'DEVICE', device, ier(17) ) CALL IP_STR ( 'TEXT', text, ier(18) ) CALL IP_STR ( 'PANEL', panel, ier(19) ) CALL IP_STR ( 'CONTUR', contur, ier(20) ) CALL IP_STR ( 'FINT', fint, ier(21) ) CALL IP_STR ( 'FLINE', fline, ier(22) ) CALL IP_STR ( 'CTYPE', ctype, ier(23) ) CALL IP_STR ( 'CLRBAR', clrbar, ier(24) ) CALL IP_STR ( 'IJSKIP', ijskip, ier(25) ) C* iret = 0 DO i = 1, 25 iret = iret + ier (i) END DO C* IF ( iret .ne. 0 ) iret = -2 C* RETURN END
include("abstract.jl") """ Analysis data of determinant quantum Monte Carlo (DQMC) simulation """ @with_kw mutable struct DQMCAnalysis acc_rate::Float64 = 0. prop_local::Int = 0 acc_local::Int = 0 acc_rate_global::Float64 = 0. prop_global::Int = 0 acc_global::Int = 0 end """ Parameters of determinant quantum Monte Carlo (DQMC) """ @with_kw struct DQMCParameters global_moves::Bool = false global_rate::Int = 5 thermalization::Int = 100 # number of thermalization sweeps sweeps::Int = 100 # number of sweeps (after thermalization) all_checks::Bool = true # e.g. check if propagation is stable/instable safe_mult::Int = 10 delta_tau::Float64 = 0.1 beta::Float64 slices::Int = beta / delta_tau @assert isinteger(beta / delta_tau) string("beta/delta_tau", " (= number of imaginary time slices) must be an integer but is", beta / delta_tau, ".") measure_rate::Int = 10 end """ Determinant quantum Monte Carlo (DQMC) simulation """ mutable struct DQMC{M<:Model, CB<:Checkerboard, ConfType<:Any, Stack<:AbstractDQMCStack} <: MonteCarloFlavor model::M conf::ConfType s::Stack p::DQMCParameters a::DQMCAnalysis thermalization_measurements::Dict{Symbol, AbstractMeasurement} measurements::Dict{Symbol, AbstractMeasurement} DQMC{M, CB, ConfType, Stack}() where {M<:Model, CB<:Checkerboard, ConfType<:Any, Stack<:AbstractDQMCStack} = new() end include("stack.jl") include("slice_matrices.jl") """ DQMC(m::M; kwargs...) where M<:Model Create a determinant quantum Monte Carlo simulation for model `m` with keyword parameters `kwargs`. """ function DQMC(m::M; seed::Int=-1, checkerboard::Bool=false, thermalization_measurements = Dict{Symbol, AbstractMeasurement}(), measurements = :default, kwargs... ) where M<:Model # default params # paramskwargs = filter(kw->kw[1] in fieldnames(DQMCParameters), kwargs) p = DQMCParameters(; kwargs...) geltype = greenseltype(DQMC, m) heltype = hoppingeltype(DQMC, m) conf = rand(DQMC, m, p.slices) mc = DQMC{M, checkerboard ? CheckerboardTrue : CheckerboardFalse, typeof(conf), DQMCStack{geltype, heltype}}() mc.model = m mc.p = p mc.s = DQMCStack{geltype, heltype}() init!( mc, seed = seed, conf = conf, thermalization_measurements = thermalization_measurements, measurements = measurements ) return mc end """ DQMC(m::M, params::Dict) DQMC(m::M, params::NamedTuple) Create a determinant quantum Monte Carlo simulation for model `m` with (keyword) parameters as specified in the dictionary/named tuple `params`. """ DQMC(m::Model, params::Dict{Symbol, T}) where T = DQMC(m; params...) DQMC(m::Model, params::NamedTuple) = DQMC(m; params...) # convenience @inline beta(mc::DQMC) = mc.p.beta @inline nslices(mc::DQMC) = mc.p.slices @inline model(mc::DQMC) = mc.model @inline conf(mc::DQMC) = mc.conf @inline current_slice(mc::DQMC) = mc.s.current_slice # cosmetics import Base.summary import Base.show Base.summary(mc::DQMC) = "DQMC simulation of $(summary(mc.model))" function Base.show(io::IO, mc::DQMC) print(io, "Determinant quantum Monte Carlo simulation\n") print(io, "Model: ", mc.model, "\n") print(io, "Beta: ", mc.p.beta, " (T ≈ $(round(1/mc.p.beta, sigdigits=3)))\n") N_th_meas = length(mc.thermalization_measurements) N_me_meas = length(mc.measurements) print(io, "Measurements: ", N_th_meas + N_me_meas, " ($N_th_meas + $N_me_meas)") end Base.show(io::IO, m::MIME"text/plain", mc::DQMC) = print(io, mc) """ init!(mc::DQMC[; seed::Real=-1]) Initialize the determinant quantum Monte Carlo simulation `mc`. If `seed !=- 1` the random generator will be initialized with `Random.seed!(seed)`. """ function init!(mc::DQMC; seed::Real = -1, conf = rand(DQMC,model(mc),nslices(mc)), thermalization_measurements = Dict{Symbol, AbstractMeasurement}(), measurements = :default ) seed == -1 || Random.seed!(seed) mc.conf = conf init_hopping_matrices(mc, mc.model) initialize_stack(mc) mc.a = DQMCAnalysis() mc.thermalization_measurements = thermalization_measurements if measurements isa Dict{Symbol, AbstractMeasurement} mc.measurements = measurements elseif measurements == :default mc.measurements = default_measurements(mc, mc.model) else @warn( "`measurements` should be of type Dict{Symbol, AbstractMeasurement}, but is " * "$(typeof(measurements)). No measurements have been set." ) mc.measurements = Dict{Symbol, AbstractMeasurement}() end nothing end """ run!(mc::DQMC[; verbose::Bool=true, sweeps::Int, thermalization::Int]) Runs the given Monte Carlo simulation `mc`. Progress will be printed to `stdout` if `verbose=true` (default). """ function run!(mc::DQMC; verbose::Bool=true, sweeps::Int=mc.p.sweeps, thermalization=mc.p.thermalization) do_th_measurements = !isempty(mc.thermalization_measurements) do_me_measurements = !isempty(mc.measurements) !do_me_measurements && @warn( "There are no measurements set up for this simulation!" ) total_sweeps = sweeps + thermalization start_time = now() verbose && println("Started: ", Dates.format(start_time, "d.u yyyy HH:MM")) # fresh stack verbose && println("Preparing Green's function stack") initialize_stack(mc) # redundant ?! build_stack(mc) propagate(mc) _time = time() verbose && println("\n\nThermalization stage - ", thermalization) do_th_measurements && prepare!(mc.thermalization_measurements, mc, mc.model) for i in 1:total_sweeps verbose && (i == thermalization + 1) &&println("\n\nMeasurement stage - ", sweeps) for u in 1:2 * nslices(mc) update(mc, i) # For optimal performance whatever is most likely to fail should be # checked first. if current_slice(mc) == nslices(mc) && i <= thermalization && mc.s.direction == -1 && iszero(mod(i, mc.p.measure_rate)) && do_th_measurements measure!(mc.thermalization_measurements, mc, mc.model, i) end if (i == thermalization+1) do_th_measurements && finish!(mc.thermalization_measurements, mc, mc.model) do_me_measurements && prepare!(mc.measurements, mc, mc.model) end if current_slice(mc) == nslices(mc) && mc.s.direction == -1 && i > thermalization && iszero(mod(i, mc.p.measure_rate)) && do_me_measurements measure!(mc.measurements, mc, mc.model, i) end end if mod(i, 10) == 0 mc.a.acc_rate = mc.a.acc_rate / (10 * 2 * nslices(mc)) mc.a.acc_rate_global = mc.a.acc_rate_global / (10 / mc.p.global_rate) sweep_dur = (time() - _time)/10 if verbose println("\t", i) @printf("\t\tsweep dur: %.3fs\n", sweep_dur) @printf("\t\tacc rate (local) : %.1f%%\n", mc.a.acc_rate*100) if mc.p.global_moves @printf("\t\tacc rate (global): %.1f%%\n", mc.a.acc_rate_global*100) @printf("\t\tacc rate (global, overall): %.1f%%\n", mc.a.acc_global/mc.a.prop_global*100) end end mc.a.acc_rate = 0.0 mc.a.acc_rate_global = 0.0 flush(stdout) _time = time() end end do_me_measurements && finish!(mc.measurements, mc, mc.model) mc.a.acc_rate = mc.a.acc_local / mc.a.prop_local mc.a.acc_rate_global = mc.a.acc_global / mc.a.prop_global end_time = now() verbose && println("Ended: ", Dates.format(end_time, "d.u yyyy HH:MM")) verbose && @printf("Duration: %.2f minutes", (end_time - start_time).value/1000. /60.) nothing end """ update(mc::DQMC, i::Int) Propagates the Green's function and performs local and global updates at current imaginary time slice. """ function update(mc::DQMC, i::Int) propagate(mc) # global move # if mc.p.global_moves && (current_slice(mc) == mc.p.slices && # mc.s.direction == -1 && iszero(mod(i, mc.p.global_rate))) # mc.a.prop_global += 1 # b = global_move(mc, mc.model, mc.conf) # not yet in DQMC_optional, i.e. unsupported # mc.a.acc_global += b # end # local moves sweep_spatial(mc) nothing end """ sweep_spatial(mc::DQMC) Performs a sweep of local moves along spatial dimension at current imaginary time slice. """ function sweep_spatial(mc::DQMC) m = model(mc) N = nsites(m) @inbounds for i in 1:N detratio, ΔE_boson, Δ = propose_local(mc, m, i, current_slice(mc), conf(mc)) mc.a.prop_local += 1 if abs(imag(detratio)) > 1e-6 println("Did you expect a sign problem? imag. detratio: ", abs(imag(detratio))) @printf "%.10e" abs(imag(detratio)) end p = real(exp(- ΔE_boson) * detratio) # Metropolis if p > 1 || rand() < p accept_local!(mc, m, i, current_slice(mc), conf(mc), Δ, detratio, ΔE_boson) mc.a.acc_rate += 1/N mc.a.acc_local += 1 end end nothing end """ greens(mc::DQMC) Obtain the current equal-time Green's function. Internally, `mc.s.greens` is an effective Green's function. This method transforms this effective one to the actual Green's function by multiplying hopping matrix exponentials from left and right. """ function greens(mc::DQMC_CBFalse) eThalfminus = mc.s.hopping_matrix_exp eThalfplus = mc.s.hopping_matrix_exp_inv greens = copy(mc.s.greens) greens .= greens * eThalfminus greens .= eThalfplus * greens return greens end function greens(mc::DQMC_CBTrue) chkr_hop_half_minus = mc.s.chkr_hop_half chkr_hop_half_plus = mc.s.chkr_hop_half_inv greens = copy(mc.s.greens) @inbounds @views begin for i in reverse(1:mc.s.n_groups) greens .= greens * chkr_hop_half_minus[i] end for i in reverse(1:mc.s.n_groups) greens .= chkr_hop_half_plus[i] * greens end end return greens end include("DQMC_mandatory.jl") include("DQMC_optional.jl") include("measurements.jl")
def entry_point(): import os import time from optparse import OptionParser import numpy as np import pandas as pd import scipy as sp from ..data import BedReader from ..iSet.iset import fit_iSet from ..util import unique_variants as f_uni_variants parser = OptionParser() parser.add_option("--bfile", dest='bfile', type=str, default=None) # parser.add_option("--cfile", dest='cfile', type=str, default=None) parser.add_option("--pfile", dest='pfile', type=str, default=None) parser.add_option("--wfile", dest='wfile', type=str, default=None) parser.add_option("--ffile", dest='ffile', type=str, default=None) parser.add_option("--ifile", dest='ifile', type=str, default=None) parser.add_option("--resdir", dest='resdir', type=str, default='./') # start window, end window and permutations parser.add_option("--n_perms", type=int, default=10) parser.add_option("--start_wnd", dest='i0', type=int, default=None) parser.add_option("--end_wnd", dest='i1', type=int, default=None) parser.add_option("--factr", dest='factr', type=float, default=1e7) parser.add_option( "--unique_variants", action="store_true", dest='unique_variants', default=False) parser.add_option( "--standardize", action="store_true", dest='standardize', default=False) (options, args) = parser.parse_args() print('importing data') F = sp.loadtxt(options.ffile + '.fe') Y = sp.loadtxt(options.pfile + '.phe') if len(Y.shape) == 1: Y = Y[:, sp.newaxis] sets = pd.DataFrame.from_csv( options.wfile + '.wnd', sep='\t', index_col=None) reader = BedReader(options.bfile) i0 = 1 if options.i0 is None else options.i0 i1 = sets.shape[0] if options.i1 is None else options.i1 df = pd.DataFrame() df0 = pd.DataFrame() if options.ifile is None: Ie = None else: Ie = sp.loadtxt(options.ifile + '.ind').flatten() == 1 res_dir = options.resdir if not os.path.exists(res_dir): os.makedirs(res_dir) n_digits = len(str(sets.shape[0])) fname = str(i0).zfill(n_digits) fname += '_' + str(i1).zfill(n_digits) resfile = os.path.join(res_dir, fname) for wnd_i in range(i0, i1): t0 = time.time() _set = sets.ix[wnd_i] print('.. set %d: %s' % (wnd_i, _set['setid'])) Xr = reader.getGenotypes( pos_start=_set['start'], pos_end=_set['end'], chrom=_set['chrom'], impute=True) if options.unique_variants: Xr = f_uni_variants(Xr) if options.standardize: Xr -= Xr.mean(0) Xr /= Xr.std(0) else: # encoding minor as 0 p = 0.5 * Xr.mean(0) Xr[:, p > 0.5] = 2 - Xr[:, p > 0.5] Xr /= np.sqrt(Xr.shape[1]) _df, _df0 = fit_iSet(Y, F=F, Xr=Xr, Ie=Ie, n_nulls=10) df = df.append(_df) df0 = df0.append(_df0) print('Elapsed:', time.time() - t0) df.to_csv(resfile + '.iSet.real') df0.to_csv(resfile + '.iSet.perm')
#pragma once #include <boost/multiprecision/cpp_int.hpp> #include <istream> #include <ostream> namespace base { template<typename T> class BigInteger { public: BigInteger() = default; template<typename N> BigInteger(const N& big_int); BigInteger(const BigInteger&) = default; BigInteger& operator=(const BigInteger&) = default; BigInteger(BigInteger&&) = default; BigInteger& operator=(BigInteger&&) = default; ~BigInteger() = default; //---------------------------------- BigInteger<T> operator+(const BigInteger<T>& other) const; BigInteger<T> operator-(const BigInteger<T>& other) const; BigInteger<T> operator*(const BigInteger<T>& other) const; BigInteger<T> operator/(const BigInteger<T>& other) const; BigInteger<T>& operator+=(const BigInteger<T>& other); BigInteger<T>& operator-=(const BigInteger<T>& other); BigInteger<T>& operator*=(const BigInteger<T>& other); BigInteger<T>& operator/=(const BigInteger<T>& other); //---------------------------------- bool operator!=(const BigInteger<T>& other) const; bool operator==(const BigInteger<T>& other) const; bool operator>(const BigInteger<T>& other) const; bool operator<(const BigInteger<T>& other) const; bool operator>=(const BigInteger<T>& other) const; bool operator<=(const BigInteger<T>& other) const; //---------------------------------- BigInteger<T>& operator++(); BigInteger<T> operator++(int); BigInteger<T>& operator--(); BigInteger<T> operator--(int); //---------------------------------- std::string toString() const noexcept; private: boost::multiprecision::number<T> _number; }; template<typename T> std::ostream& operator<<(std::ostream& output, const BigInteger<T>& big_int); template<typename T> std::istream& operator>>(std::istream& input, BigInteger<T>& big_int); using Uint256 = BigInteger< boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::cpp_integer_type::unsigned_magnitude, boost::multiprecision::cpp_int_check_type::checked, void>>; using Uint512 = BigInteger< boost::multiprecision::backends::cpp_int_backend<512, 512, boost::multiprecision::cpp_integer_type::unsigned_magnitude, boost::multiprecision::cpp_int_check_type::checked, void>>; } // namespace base #include "big_integer.tpp"
Formal statement is: lemma tendsto_add_smallo_iff: assumes "f2 \<in> o[F](f1)" shows "(f1 \<longlongrightarrow> a) F \<longleftrightarrow> ((\<lambda>x. f1 x + f2 x) \<longlongrightarrow> a) F" Informal statement is: If $f_2$ is $o(f_1)$, then $f_1$ tends to $a$ if and only if $f_1 + f_2$ tends to $a$.
[STATEMENT] lemma (in category) cat_ntcf_Hom_snd_is_ntcf: assumes "f : s \<mapsto>\<^bsub>\<CC>\<^esub> r" shows "Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> [PROOF STEP] note f = cat_is_arrD[OF assms] [PROOF STATE] proof (state) this: f \<in>\<^sub>\<circ> \<CC>\<lparr>Arr\<rparr> s \<in>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr> r \<in>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr> \<CC>\<lparr>Dom\<rparr>\<lparr>f\<rparr> = s \<CC>\<lparr>Cod\<rparr>\<lparr>f\<rparr> = r goal (1 subgoal): 1. Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> [PROOF STEP] unfolding ntcf_Hom_snd_def f [PROOF STATE] proof (prove) goal (1 subgoal): 1. Yoneda_arrow \<alpha> Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) r f : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> [PROOF STEP] proof(rule category.cat_Yoneda_arrow_is_ntcf) [PROOF STATE] proof (state) goal (4 subgoals): 1. category \<alpha> \<CC> 2. Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> 3. r \<in>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr> 4. f \<in>\<^sub>\<circ> Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-)\<lparr>ObjMap\<rparr>\<lparr>r\<rparr> [PROOF STEP] from assms category_axioms [PROOF STATE] proof (chain) picking this: f : s \<mapsto>\<^bsub>\<CC>\<^esub> r category \<alpha> \<CC> [PROOF STEP] show "f \<in>\<^sub>\<circ> Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-)\<lparr>ObjMap\<rparr>\<lparr>r\<rparr>" [PROOF STATE] proof (prove) using this: f : s \<mapsto>\<^bsub>\<CC>\<^esub> r category \<alpha> \<CC> goal (1 subgoal): 1. f \<in>\<^sub>\<circ> Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-)\<lparr>ObjMap\<rparr>\<lparr>r\<rparr> [PROOF STEP] by (cs_concl cs_simp: cat_cs_simps cat_op_simps cs_intro: cat_cs_intros) [PROOF STATE] proof (state) this: f \<in>\<^sub>\<circ> Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-)\<lparr>ObjMap\<rparr>\<lparr>r\<rparr> goal (3 subgoals): 1. category \<alpha> \<CC> 2. Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> 3. r \<in>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr> [PROOF STEP] qed (intro category_axioms cat_cf_Hom_snd_is_functor f)+ [PROOF STATE] proof (state) this: Hom\<^sub>A\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(f,-) : Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(r,-) \<mapsto>\<^sub>C\<^sub>F Hom\<^sub>O\<^sub>.\<^sub>C\<^bsub>\<alpha>\<^esub>\<CC>(s,-) : \<CC> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> cat_Set \<alpha> goal: No subgoals! [PROOF STEP] qed
import Data.So data Tree : (a: Type) -> Type where Leaf : Tree a Node : (key: a) -> (left: Tree a) -> (right: Tree a) -> Tree a minVal : Ord a => Tree a -> Maybe a minVal Leaf = Nothing minVal (Node key Leaf _) = Just key minVal (Node key left right) = minVal left maxVal : Ord a => Tree a -> Maybe a maxVal Leaf = Nothing maxVal (Node key _ Leaf) = Just key maxVal (Node left key right) = maxVal right data Comp = LT | EQ | GT lessTree : Ord a => a -> Tree a -> Bool lessTree x node = case minVal node of Nothing => True Just key => x < key moreTree : Ord a => a -> Tree a -> Bool moreTree x node = case maxVal node of Nothing => True Just key => x >= key comp : Ord a => a -> a -> Comp comp x y = if x > y then GT else if x < y then LT else EQ IsLft : Ord a => (x: a) -> (left: Tree a) -> Type IsLft x left = So (moreTree x left) IsRgt : Ord a => (x: a) -> (right: Tree a) -> Type IsRgt x right = So (lessTree x right) mkIsLft : Ord a => (x: a) -> (l: Tree a) -> (IsLft x l) mkIsLft x l = case (choose (moreTree x l)) of Left proofYes => proofYes mkIsRgt : Ord a => (x: a) -> (r: Tree a) -> (IsRgt x r) mkIsRgt x r = case (choose (lessTree x r)) of Left proofYes => proofYes data IsBST : (t : Tree a) -> Type where IsBSTLeaf : IsBST Leaf IsBSTNode : Ord a => (x: a) -> (IsBST left) -> (IsLft x left) -> (IsBST right) -> (IsRgt x right) -> (IsBST (Node x left right)) BSTree : Type -> Type BSTree a = (t' : (Tree a) ** (IsBST t')) insert : Ord a => (x : a) -> BSTree a -> BSTree a insert x (Leaf ** IsBSTLeaf) = let isLftPrf = mkIsLft x Leaf isRgtPrf = mkIsRgt x Leaf in ((Node x Leaf Leaf) ** (IsBSTNode x IsBSTLeaf isLftPrf IsBSTLeaf isRgtPrf)) insert x ((Node y left right) ** (IsBSTNode y lPrf isLftPrf rPrf isRgtPrf)) = case comp y x of GT => let (lTree ** pl) = insert x (left ** lPrf) isLft = mkIsLft y lTree in ((Node y lTree right) ** (IsBSTNode y pl isLft rPrf isRgtPrf)) LT => let (rTree ** pr) = insert x (right ** rPrf) isRgt = mkIsRgt y rTree in ((Node y left rTree) ** (IsBSTNode y lPrf isLftPrf pr isRgt)) EQ => ((Node y left right) ** (IsBSTNode y lPrf isLftPrf rPrf isRgtPrf)) -- wrongInsert : Ord a => (x : a) -> BSTree a -> BSTree a -- wrongInsert x (Leaf ** IsBSTLeaf) = -- let isLftPrf = mkIsLft x Leaf -- isRgtPrf = mkIsRgt x Leaf -- in ((Node x Leaf Leaf) ** (IsBSTNode x IsBSTLeaf isLftPrf IsBSTLeaf isRgtPrf)) -- wrongInsert x ((Node y left right) ** (IsBSTNode y lPrf isLftPrf rPrf isRgtPrf)) = -- case comp y x of -- GT => -- let (lTree ** pl) = insert x (left ** lPrf) -- isLft = mkIsLft y lTree -- in ((Node y right lTree) ** (IsBSTNode y rPrf isRgtPrf pl isLft)) -- LT => -- let (rTree ** pr) = insert x (right ** rPrf) -- isRgt = mkIsRgt y rTree -- in ((Node y left rTree) ** (IsBSTNode y lPrf isLftPrf pr isRgt)) -- EQ => ((Node y left right) ** (IsBSTNode y lPrf isLftPrf rPrf isRgtPrf))
!-----------------------------------------------------------------------------! !-----------------------------------------------------------------------------! ! MAE 6263 Computational Fluid Dynamics - Project 1 ! ! Sk. Mashfiqur Rahman ! ! CWID: A20102717 ! !-----------------------------------------------------------------------------! !-----------------------------------------------------------------------------! program heatdiff implicit none integer::i,j,k,nx,ny,nt,nitr,N,ischeme,c,pr real*8 ::dx,dt,dy,xi,xf,yi,t,yf,alpha,Tmax,gamma real*8 ::tol,omega,w,t1,t2,probe real*8,allocatable ::Te(:,:),Ti(:,:),x(:),y(:),b(:,:) !Domain xi = 0.0d0 !left xf = 1.0d0 !right yi = 0.0d0 !bottom yf = 1.0d0 !up open(9,file='project1input.txt') read(9,*)nx !resolution in x direction read(9,*)ny !resolution in y direction read(9,*)gamma !value of gamma to measure time-step size read(9,*)Tmax !final time read(9,*)alpha !diffusion coefficient read(9,*)tol !tolerance for iterative solvers read(9,*)omega !relaxation parameter for SOR iterative solver (optimized value = 1.08-1.28) read(9,*)probe !value to calculate data on a point in space read(9,*)ischeme ![0]Explicit, [1]Implicit-Gauss-Seidel(GS) solver, [2]Implicit-SOR, [3]Both explicit and implicit (GS) (for analysis), [4]Both explicit and implicit (SOR)(for analysis), [5]Approximate factorization close(9) !Calculating grid spacing (spatial) dx = (xf-xi)/dfloat(nx) dy = (yf-yi)/dfloat(ny) pr = dint(((probe - yi)*dfloat(ny))/(yf-yi)) !Time step dt = ((dx*dx)*gamma) /alpha !calculating number of snapshots (ns) nt = nint(Tmax/dt) !spatial coordinate points allocate(x(0:nx)) do i=0,nx x(i) = xi + dfloat(i)*dx end do allocate(y(0:ny)) do j=0,ny y(j) = yi + dfloat(j)*dy end do !T: temperature variable !b: solution vector for Ax=b allocate(Te(0:nx,0:ny)) allocate(Ti(0:nx,0:ny)) allocate(b(0:nx,0:ny)) !initial and boundary condition !N: iteration counter !c: time step counter t = 0.0d0 c = 0 N = 0 do j=0,ny do i=0,nx Te(i,j) = 0.0d0 end do end do do j=0,ny Te(0,j) = 0.0d0 +y(j) Te(nx,j) = 1.0d0 +y(j) end do do i=0,nx Te(i,0) = x(i)+ 0.0d0 Te(i,ny) = x(i)+ 1.0d0 end do do j=0,ny do i=0,nx Ti(i,j) = Te(i,j) end do end do !Plot initial condition open(18,file='Tin.plt') write(18,*) 'variables ="x","y","T"' write(18,100)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(18,*) x(i),y(j),Te(i,j) end do end do close(18) !$$$$$$ open(20,file='nitr.plt') !$$$$$$ write(20,*) 'variables ="w","N-ITR"' if(ischeme.eq.1 .or. ischeme.eq.3) then w = 1.0d0 else w = omega end if call cpu_time(t1) !-----------------------------------------------------------------------------! !Time integration (for both explicit and implicit solvers) !-----------------------------------------------------------------------------! if (ischeme.eq.0) then !explicit solver do k=1,nt c = c+1 !time step counter call FTCS(nx,ny,Te,gamma) t = t + dt !time update end do else if(ischeme.eq.3 .or. ischeme.eq.4) then do k=1,nt c = c+1 !time step counter call FTCS(nx,ny,Te,gamma) t = t + dt !time update end do do k=1,nt c = c+1 !time step counter !solution vector update do j=0,ny do i=0,nx b(i,j) = Ti(i,j) end do end do call BTCS(nx,ny,Ti,b,w,gamma,tol,nitr) t = t + dt !time update for plotting N = N + nitr end do else if(ischeme.eq.5) then !Approximate factorization do k=1,nt c = c+1 !time step counter !solution vector update do j=0,ny do i=0,nx b(i,j) = Ti(i,j) end do end do call BTCSAF(nx,ny,gamma,Ti,b) t = t + dt !time update end do else !implicit solver do k=1,nt c = c+1 !time step counter !solution vector update do j=0,ny do i=0,nx b(i,j) = Ti(i,j) end do end do call BTCS(nx,ny,Ti,b,w,gamma,tol,nitr) t = t + dt !time update N = N + nitr end do end if !call OptOm(nx,ny,Th,b,gamma,tol,omega) !-----------------------------------------------------------------------------! !output to .plt file for Tecplot !-----------------------------------------------------------------------------! call cpu_time(t2) open(4,file='cpu.txt') write(4,*)"cpu time (sec)=",(t2-t1) close(4) print*,"------------------------" print*,"Total CPU time (seconds) = ", (t2-t1) print*,"------------------------" if (ischeme.eq.0) then !FTCS open(12, file="explicit.plt") write(12,*)'variables ="x","y","T"' write(12,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(12,*) x(i),y(j),Te(i,j) end do end do close(12) open(22, file="explicit.txt") do j=0,ny do i=0,nx write(22,*) x(i),y(j),Te(i,j) end do end do close(22) print*,"-------------------------------" print*,"Total number of time iterations = ", c print*,"-------------------------------" else if(ischeme.eq.3 .or. ischeme.eq.4) then !GS + SOR open(19, file="explicit.plt") write(19,*)'variables ="x","y","T"' write(19,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(19,*) x(i),y(j),Te(i,j) end do end do close(19) open(29, file="explicit.txt") do j=0,ny do i=0,nx write(29,*) x(i),y(j),Te(i,j) end do end do close(29) open(14, file="implicit.plt") write(14,*)'variables ="x","y","T"' write(14,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(14,*) x(i),y(j),Ti(i,j) end do end do close(14) open(24, file="implicit.txt") do j=0,ny do i=0,nx write(24,*) x(i),y(j),Ti(i,j) end do end do close(24) open(12, file="error_iso.plt") write(12,*)'variables ="x","y","error"' write(12,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(12,*) x(i),y(j),dabs(Te(i,j)-Ti(i,j)) end do end do close(12) open(22, file="error_iso.txt") do j=0,ny do i=0,nx write(22,*) x(i),y(j),dabs(Te(i,j)-Ti(i,j)) end do end do close(22) open(3, file="impact_analysis_ex.plt") write(3,*)'variables ="x","T"' do i=0,nx write(3,*) x(i),Te(i,pr) end do close(3) open(23, file="impact_analysis_ex.txt") write(23,*)'variables ="x","T"' do i=0,nx write(23,*) x(i),Te(i,pr) end do close(23) open(4, file="impact_analysis_im.plt") write(4,*)'variables ="x","T"' do i=0,nx write(4,*) x(i),Ti(i,pr) end do close(4) open(34, file="impact_analysis_im.txt") write(34,*)'variables ="x","T"' do i=0,nx write(34,*) x(i),Ti(i,pr) end do close(34) else if(ischeme.eq.5) then !Approximate Factorization !$$$$$$ print*,"------------------------" !$$$$$$ print*,"Total CPU time (seconds) = ", (t2-t1) !$$$$$$ print*,"------------------------" open(12, file="implicit.plt") write(12,*)'variables ="x","y","T"' write(12,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(12,*) x(i),y(j),Ti(i,j) end do end do close(12) open(22, file="implicit.txt") do j=0,ny do i=0,nx write(22,*) x(i),y(j),Ti(i,j) end do end do close(22) open(4, file="impact_analysis_im.plt") write(4,*)'variables ="x","T"' do i=0,nx write(4,*) x(i),Ti(i,10) end do close(4) open(34, file="impact_analysis_im.txt") write(34,*)'variables ="x","T"' do i=0,nx write(34,*) x(i),Ti(i,pr) end do close(34) print*,"-------------------------------" print*,"Total number of time iterations = ", c print*,"-------------------------------" else !implicits open(12, file="implicit.plt") write(12,*)'variables ="x","y","T"' write(12,*)'zone f=point i=',nx+1,',j=',ny+1,',t="time',t,'"' do j=0,ny do i=0,nx write(12,*) x(i),y(j),Ti(i,j) end do end do close(12) open(22, file="implicit.txt") do j=0,ny do i=0,nx write(22,*) x(i),y(j),Ti(i,j) end do end do close(22) open(4, file="impact_analysis_im.plt") write(4,*)'variables ="x","T"' do i=0,nx write(4,*) x(i),Ti(i,pr) end do close(4) open(34, file="impact_analysis_im.txt") write(34,*)'variables ="x","T"' do i=0,nx write(34,*) x(i),Ti(i,pr) end do close(34) print*,"----------------------------------------------" print*,"Total number of iterations in iterative solver = ", N print*,"----------------------------------------------" print*,"-------------------------------" print*,"Total number of time iterations = ", c print*,"-------------------------------" !$$$$$$ !$$$$$$ print*,"------------------------" !$$$$$$ print*,"Total CPU time (seconds) = ", (t2-t1) !$$$$$$ print*,"------------------------" end if 100 format(a16,i8,a4,i8,a10,f10.4,a3) end !-----------------------------------------------------------------------------! !Explicit Solver (spatial treatment) !-----------------------------------------------------------------------------! subroutine FTCS(nx,ny,Te,gamma) implicit none integer::nx,ny,i,j real*8 ::gamma real*8 ::u(0:nx,0:ny),Te(0:nx,0:ny) !previous step (t=n) do j=0,ny do i=0,nx u(i,j) = Te(i,j) end do end do !update (t=n+1) do j=1,ny-1 do i=1,nx-1 Te(i,j) = u(i,j) + gamma*(u(i+1,j)+u(i-1,j)+u(i,j+1)+u(i,j-1)-4.0d0*u(i,j)) end do end do end !-----------------------------------------------------------------------------! !Iterative solver (for implicit scheme) (spatial treatment) !-----------------------------------------------------------------------------! subroutine BTCS(nx,ny,Ti,b,w,gamma,tol,nitr) implicit none integer::nx,ny,i,j,nitr real*8 ::tol,err,w,gamma real*8 ::Ti(0:nx,0:ny),e(0:nx,0:ny),v(0:nx,0:ny),b(0:nx,0:ny) err=1.0d0 nitr = 0 do while(err.gt.tol) nitr = nitr + 1 err=0.0d0 do j=0,ny do i=0,nx v(i,j) = Ti(i,j) end do end do !update do j=1,ny-1 do i=1,nx-1 Ti(i,j) = v(i,j) + ((w*gamma)/(1 + (4.0d0*gamma)))*(v(i+1,j)+Ti(i-1,j)+v(i,j+1)+Ti(i,j-1)+ & (b(i,j)/gamma)-((1 + (4.0d0*gamma))*v(i,j)/gamma)) end do end do !compute L1 norm do j=0,ny do i=0,nx e(i,j) = dabs(Ti(i,j)-v(i,j)) err = e(i,j) + err end do end do end do end !-----------------------------------------------------------------------------! !Optimized Omega calculation !-----------------------------------------------------------------------------! subroutine OptOm(nx,ny,Ti,b,gamma,tol,omega) implicit none integer::i,j,nx,ny,nitr,p real*8::dom,om1,nom,gamma,tol,omega real*8 ::b(0:nx,0:ny),Ti(0:nx,0:ny) om1=0.5d0 dom = 0.05d0 nom = 20 do p=0,nom do j=0,ny do i=0,nx b(i,j) = Ti(i,j) end do end do omega = om1 + dfloat(p)*dom call SOR(nx,ny,Ti,b,omega,gamma,tol,nitr) !write error write(*,*)'omega and total interval:' write(20,*) omega, nitr write(*,*) omega, nitr end do close(20) end !-----------------------------------------------------------------------------! !Approximate Factorization !-----------------------------------------------------------------------------! subroutine BTCSAF(nx,ny,gamma,Ti,b) implicit none integer::nx,ny,i,j real*8 ::gamma,bx,by,Tia,Tib real*8 ::Ti(0:nx,0:ny) real*8,allocatable ::t(:),d(:),m(:),r(:),q(:) real*8 ::b(0:nx,0:ny),z(0:nx,0:ny) do j=0,ny do i=0,nx z(i,j) = 0.0d0 end do end do bx = gamma by = gamma !x-sweep to compute intermediate values: do j=1,ny-1 !Build coefficient matrix: allocate(t(1:nx-1),d(1:nx-1),m(1:nx-1),r(1:nx-1),q(1:nx-1)) do i=1,nx-1 t(i) = -bx d(i) = (1.0d0+2.0d0*bx) m(i) = -bx r(i) = b(i,j) end do !apply boundary conditions Tia = Ti(0,j) - by*(Ti(0,j+1)-2.0d0*Ti(0,j)+Ti(0,j-1)) Tib = Ti(nx,j) - by*(Ti(nx,j+1)-2.0d0*Ti(nx,j)+Ti(nx,j-1)) r(1) = r(1) - t(1)*Tia !b.c. r(nx-1) = r(nx-1) - m(nx-1)*Tib !b.c. call tdma(t,d,m,r,q,1,nx-1) !assign solutions for as z do i=1,nx-1 z(i,j)=q(i) end do z(0,j) =Tia z(nx,j)=Tib deallocate(t,d,m,r,q) end do !y-sweep to compute final solution: do i=1,nx-1 !Build coefficient matrix: allocate(t(1:ny-1),d(1:ny-1),m(1:ny-1),r(1:ny-1),q(1:ny-1)) do j=1,ny-1 t(j) = -by d(j) = (1.0d0+2.0d0*by) m(j) = -by r(j) = z(i,j) end do !apply boundary conditions Tia = Ti(i,0) Tib = Ti(i,ny) r(1) = r(1) - t(1)*Tia !b.c. r(ny-1) = r(ny-1) - m(ny-1)*Tib !b.c. call tdma(t,d,m,r,q,1,ny-1) !assign solutions for as z do j=1,ny-1 Ti(i,j)=q(j) end do deallocate(t,d,m,r,q) end do end !------------------------------------------------------------------! !TDMA !------------------------------------------------------------------! subroutine tdma(t,d,m,r,x,k,l) implicit none integer k,l,i real*8, dimension(k:l) ::t,d,m,r,x ! forward elimination phase do i=k+1,l d(i) = d(i) -t(i)/d(i-1)*m(i-1) r(i) = r(i) - t(i)/d(i-1)*r(i-1) end do ! backward substitution phase x(l) = r(l)/d(l) do i=l-1,k,-1 x(i) = (r(i)-m(i)*x(i+1))/d(i) end do return end
from itertools import combinations import copy import numpy as np import pandas as pd from PyPCAlg.utilities.logs import create_logger from PyPCAlg.utilities.pc_algorithm import find_adjacent_vertices, \ find_adjacent_vertices_to, find_unshielded_triples from PyPCAlg.meeks_rules import apply_Meeks_rules field_pc_cpdag = 'CPDAG' field_separation_sets = 'SeparationSets' def run_pc_adjacency_phase(data: pd.DataFrame, indep_test_func: callable, cond_indep_test_func: callable, level: float, log_file: str = '') -> tuple[np.ndarray, dict]: """ Runs the adjacency phase of the PC algorithm, producing the causal skeleton and the separation sets. Parameters ---------- data : pandas.DataFrame The observations. indep_test_func : callable A function to perform unconditional independence testing. cond_indep_test_func : callable A function to perform conditional independence testing. level : float The level for the tests. log_file : str, optional The path to a file in which to store the log. No log will be generated if the empty string is provided. Returns ------- tuple A tuple containing the causal skeleton as first element, and a dictionary of the separation sets as second element. """ # To deal with matters of logging logging_active = False if log_file != '': logging_active = True logger = create_logger( logger_name='pc_alg_adjacency_phase', log_file=log_file ) nb_obs, nb_var = data.shape causal_skeleton = np.ones((nb_var, nb_var)) - np.identity(nb_var) separation_sets = dict() for x in range(nb_var): for y in range(x + 1, nb_var): separation_sets[(x, y)] = set() separation_sets[(y, x)] = set() depth = 0 while True: adjacent_vertices = find_adjacent_vertices(causal_skeleton) if logging_active: logger.info('\n\n\n\n') # just for greater readability of the log logger.info(f'Depth == {depth}') logger.info(f'Causal Skeleton :\n{causal_skeleton}') logger.info( f'Adjacent Vertices :\n{sorted(list(adjacent_vertices))}\n' ) stop_condition = True for (x, y) in adjacent_vertices: adj_to_x = find_adjacent_vertices_to(x, causal_skeleton) adj_to_x_excl_y = [elt for elt in adj_to_x if elt != y] stop_condition = stop_condition and (len(adj_to_x_excl_y) < depth) if logging_active: logger.info(f'Stop condition == {stop_condition}') for (x, y) in adjacent_vertices: if logging_active: logger.info(f'Pair considered == {(x,y)}') adj_to_x = find_adjacent_vertices_to(x, causal_skeleton) adj_to_x_excl_y = [elt for elt in adj_to_x if elt != y] if logging_active: logger.info(f'Adjacent to {x} == {adj_to_x}') logger.info(f'Adjacent to {x} except {y} == {adj_to_x_excl_y}') if len(adj_to_x_excl_y) >= depth: if depth == 0: if logging_active: logger.info('Conditioning set considered == []') x_indep_y = indep_test_func( data=data, x=x, y=y, level=level ) if x_indep_y: if logging_active: logger.info(f'INDEPENDENCE FOUND : {x} _||_ {y}') causal_skeleton[x, y] = 0 causal_skeleton[y, x] = 0 separation_sets[(x, y)].add(tuple()) separation_sets[(y, x)].add(tuple()) else: for z in combinations(adj_to_x_excl_y, depth): if logging_active: logger.info(f'Conditioning set considered == {z}') x_indep_y_given_z = cond_indep_test_func( data=data, x=x, y=y, z=list(z), level=level ) if x_indep_y_given_z: if logging_active: logger.info( f'INDEPENDENCE FOUND == {x} _||_ {y} | {z}' ) causal_skeleton[x, y] = 0 causal_skeleton[y, x] = 0 separation_sets[(x, y)].add(tuple(sorted(z))) separation_sets[(y, x)].add(tuple(sorted(z))) depth += 1 if stop_condition: break return causal_skeleton, separation_sets def run_pc_orientation_phase(causal_skeleton: np.ndarray, separation_sets: dict, log_file: str = '') -> np.ndarray: """ Runs the adjacency phase of the PC algorithm, producing the Completed Partially Directed Acyclic Graph (CPDAG) of the true causal graph (i.e. the graphical representation of the Markov equivalence class of the true graph). Parameters ---------- causal_skeleton : array_like The causal skeleton of the true causal graph. separation_sets : dict The separation sets. log_file : str, optional The path to a file in which to store the log. No log will be generated if the empty string is provided. Returns ------- array_like The CPDAG. """ # To deal with matters of logging logging_active = False if log_file != '': logging_active = True logger = create_logger( logger_name='pc_alg_orientation_phase', log_file=log_file ) cpdag = copy.deepcopy(causal_skeleton) # Orient the unshielded triples if any unshielded_triples = find_unshielded_triples( adjacency_matrix=causal_skeleton ) if logging_active: logger.info(f'The unshielded triples are : {unshielded_triples}') for (a, b, c) in unshielded_triples: not_in_sepset = all([b not in sep for sep in separation_sets[(a, c)]]) if not_in_sepset: cpdag[b, a] = 0 cpdag[b, c] = 0 if logging_active: logger.info(f'Unshielded triple {(a, b, c)}') logger.info(f'{[b]} not in SepSet[{(a, c)}] = ' f'{separation_sets[(a, c)]}') logger.info(f'Removing {b} -> {a} and {b} -> {c} from graph') # Apply Meek's rules repeatedly until the CPDAG no longer changes current_cpdag = copy.deepcopy(cpdag) while True: new_cpdag = apply_Meeks_rules( pdag=current_cpdag, apply_R4=False # Rule R4 is not necessary for the PC algorithm ) if np.array_equal(new_cpdag, current_cpdag): break current_cpdag = new_cpdag return new_cpdag def run_pc_algorithm(data: pd.DataFrame, indep_test_func: callable, cond_indep_test_func: callable, level: float, log_file: str = '') -> dict: """ Runs the original PC algorithm. Parameters ---------- data : pandas.DataFrame The observations. indep_test_func : callable A function to perform unconditional independence testing. cond_indep_test_func : callable A function to perform conditional independence testing. level : float The level for the tests. log_file : str, optional The path to a file in which to store the log. No log will be generated if the empty string is provided. Returns ------- dict A dictionary containing the CPDAG obtained by running the PC algorithm as well as the separation sets determined on the way. """ causal_skeleton, separation_sets = run_pc_adjacency_phase( data=data, indep_test_func=indep_test_func, cond_indep_test_func=cond_indep_test_func, level=level, log_file=log_file ) cpdag = run_pc_orientation_phase( causal_skeleton=causal_skeleton, separation_sets=separation_sets, log_file=log_file ) res = dict() res[field_pc_cpdag] = cpdag res[field_separation_sets] = separation_sets return res
% !TEX root = ../thesis.tex \vspace{-20pt} \section{Comparative Performance Benchmarks} \label{sec:vg:performance} \vspace{-10pt} To evaluate the performance of Reactive Vega against D3~\cite{bostock:d3} and the origin, non-reactive Vega system (v1.5.0), we use the same setup described in the previous section. \vspace{-10pt} \subsection{Streaming Visualizations} \vspace{-7pt} Figure~\ref{fig:vg:static_benchmark} shows the average performance of uninteractive streaming scatter plots, parallel coordinates plots, and trellis plots. We first measured the average time to initially parse and render the visualizations. To gauge streaming performance, we next measured the average time taken to update and re-render upon adding, modifying, or removing 1\% of tuples. We ran 10 trials per dataset, sized 100--100,000 tuples. \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{streaming-lines.pdf} \caption{Average performance of rendering (non-interactive) streaming visualizations: (top-bottom) scatterplot, parallel coordinates, and trellis plot; (left-right) initialization time, average frame time, and average frame rate. Dashed lines indicate the threshold of interactive updates~\cite{card:modelhuman}.} \label{fig:vg:static_benchmark} \end{figure} Reactive Vega has the greatest effect with the parallel coordinates plot, displaying 2x and 4x performance increases over D3 and Vega 1.5, respectively. This effect is due to each plotted line being built and encoded by its own dataflow branch. Across the other two examples, and averaging between the Canvas and \textsc{svg} renderers, we find that although Reactive Vega takes 1.7x longer to initialize the visualizations, subsequent streaming operations are 1.9x faster than D3. Against Vega 1.5, Reactive Vega is again 1.7x slower at initializing visualizations; streaming updates perform roughly op-par with the Canvas renderer, but are 2x faster with the \textsc{svg} renderer. Slower initialization times for Reactive Vega are to be expected. D3 does not have to parse and compile a \textsc{json} specification, and a streaming dataflow graph is a more complex execution model, with higher overheads, than batch processing. However, with streaming visualizations this cost amortizes and performance in response to data changes becomes more important. In this case, Reactive Vega makes up the difference in a single cycle. \vspace{-10pt} \subsection{Interactive Visualizations} \vspace{-7pt} We evaluated the performance of interactive visualizations (measured in terms of interactive frame rate) using three common examples: brushing \& linking a scatterplot matrix, a time-series overview+detail visualization, and panning \& zooming a scatterplot. We chose these examples as they all leverage interactive behaviors supported by D3, with canonical implementations available for each\footnote{Brushing \& Linking: http://bl.ocks.org/mbostock/4063663}\textsuperscript{,}\footnote{Overview + Detail: http://bl.ocks.org/mbostock/1667367}\textsuperscript{,}\footnote{Pan \& Zoom: http://bl.ocks.org/mbostock/3892919}. For Reactive Vega, we expressed these visualizations with a single declarative specification. For D3 and Vega 1.5, we use custom event handling callbacks. The Vega 1.5 callbacks mimic the behavior of the fragmented reactive approach used in prior work~\cite{reactive-vega-model}. We tested these visualizations with datasets sized between 100 and 10,000 tuples. \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{interaction-lines.pdf} \caption{Average frame rates for three interactive visualizations: (left-right) brushing and linking on a scatterplot matrix; brushing and linking on an overview+detail visualization; panning and zooming on a scatterplot. Dashed lines indicate the threshold of interactive updates~\cite{card:modelhuman}.} \label{fig:vg:interactive_benchmark} \end{figure} Reactive Vega has the greatest effect with the parallel coordinates plot, displaying 2x and 4x performance increases over D3 and Vega 1.5, respectively. This effect is due to each plotted line being built and encoded by its own dataflow branch. Across the other two examples, and averaging between the Canvas and \textsc{svg} renderers, we find that although Reactive Vega takes 1.7x longer to initialize the visualizations, subsequent streaming operations are 1.9x faster than D3. Against Vega 1.5, Reactive Vega is again 1.7x slower at initializing visualizations; streaming updates perform roughly op-par with the Canvas renderer, but are 2x faster with the \textsc{svg} renderer.
"""For GPU usage testing purposes.""" import numpy as np from h2oaicore.models import CustomModel from h2oaicore.models_utils import import_tensorflow class CustomTFGPUCheck(CustomModel): _regression = True _binary = True _multiclass = False # WIP _is_reproducible = False _can_use_gpu = True # if enabled, will use special job scheduler for GPUs _get_gpu_lock = True # whether to lock GPUs for this model before fit and predict _must_use_gpu = True # this recipe can only be used if have GPUs _predict_on_same_gpus_as_fit = True # force predict to behave like fit, regardless of config.num_gpus_for_prediction def set_default_params(self, accuracy=None, time_tolerance=None, interpretability=None, **kwargs): self.params = {} def mutate_params(self, **kwargs): self.params = {} def fit(self, X, y, sample_weight=None, eval_set=None, sample_weight_eval_set=None, **kwargs): ''' Basic Multi GPU computation example using TensorFlow library. Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' ''' This tutorial requires your machine to have 1 GPU "/cpu:0": The CPU of your machine. "/gpu:0": The first GPU of your machine ''' tf = import_tensorflow() import numpy as np import datetime # Processing Units logs log_device_placement = True # Num of multiplications to perform n = 10 ''' Example: compute A^n + B^n on 2 GPUs Results on 8 cores with 2 GTX-980: * Single GPU computation time: 0:00:11.277449 * Multi GPU computation time: 0:00:07.131701 ''' # Create random large matrix A = np.random.rand(10000, 10000).astype('float32') B = np.random.rand(10000, 10000).astype('float32') # Create a graph to store results c1 = [] c2 = [] def matpow(M, n): if n < 1: #Abstract cases where n < 1 return M else: return tf.matmul(M, matpow(M, n-1)) ''' Single GPU computing ''' with tf.device('/gpu:0'): a = tf.placeholder(tf.float32, [10000, 10000]) b = tf.placeholder(tf.float32, [10000, 10000]) # Compute A^n and B^n and store results in c1 c1.append(matpow(a, n)) c1.append(matpow(b, n)) with tf.device('/gpu:0'): sum = tf.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n t1_1 = datetime.datetime.now() with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement, allow_soft_placement=True)) as sess: # Run the op. sess.run(sum, {a:A, b:B}) t2_1 = datetime.datetime.now() print("Single GPU computation time: " + str(t2_1-t1_1)) self.set_model_properties(model=[1], features=list(X.names), importances=([1.0] * len(list(X.names))), iterations=0) def predict(self, X, **kwargs): """ Returns: dt.Frame, np.ndarray or pd.DataFrame, containing predictions (target values or class probabilities) Shape: (K, c) where c = 1 for regression or binary classification, and c>=3 for multi-class problems. """ return np.random.randint(0, 2, (X.nrows, 1))
[GOAL] R : Type u_1 inst✝⁶ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M N : Type u_3 inst✝³ : AddCommMonoid N inst✝² : Module R N ι : Type u_4 inst✝¹ : DecidableEq ι x✝ y✝ z : M inst✝ : Subsingleton M x y : M ⊢ SameRay R x y [PROOFSTEP] rw [Subsingleton.elim x 0] [GOAL] R : Type u_1 inst✝⁶ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M N : Type u_3 inst✝³ : AddCommMonoid N inst✝² : Module R N ι : Type u_4 inst✝¹ : DecidableEq ι x✝ y✝ z : M inst✝ : Subsingleton M x y : M ⊢ SameRay R 0 y [PROOFSTEP] exact zero_left _ [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x✝ y z x : M ⊢ SameRay R x x [PROOFSTEP] nontriviality R [GOAL] R : Type u_1 inst✝⁶ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M N : Type u_3 inst✝³ : AddCommMonoid N inst✝² : Module R N ι : Type u_4 inst✝¹ : DecidableEq ι x✝ y z x : M inst✝ : Nontrivial R ⊢ SameRay R x x [PROOFSTEP] exact Or.inr (Or.inr <| ⟨1, 1, zero_lt_one, zero_lt_one, rfl⟩) [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy : y = 0 → x = 0 ∨ z = 0 ⊢ SameRay R x z [PROOFSTEP] rcases eq_or_ne x 0 with (rfl | hx) [GOAL] case inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι y z : M hyz : SameRay R y z hxy : SameRay R 0 y hy : y = 0 → 0 = 0 ∨ z = 0 ⊢ SameRay R 0 z [PROOFSTEP] exact zero_left z [GOAL] case inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 ⊢ SameRay R x z [PROOFSTEP] rcases eq_or_ne z 0 with (rfl | hz) [GOAL] case inr.inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y : M hxy : SameRay R x y hx : x ≠ 0 hyz : SameRay R y 0 hy : y = 0 → x = 0 ∨ 0 = 0 ⊢ SameRay R x 0 [PROOFSTEP] exact zero_right x [GOAL] case inr.inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 hz : z ≠ 0 ⊢ SameRay R x z [PROOFSTEP] rcases eq_or_ne y 0 with (rfl | hy) [GOAL] case inr.inr.inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x z : M hx : x ≠ 0 hz : z ≠ 0 hxy : SameRay R x 0 hyz : SameRay R 0 z hy : 0 = 0 → x = 0 ∨ z = 0 ⊢ SameRay R x z [PROOFSTEP] exact (hy rfl).elim (fun h => (hx h).elim) fun h => (hz h).elim [GOAL] case inr.inr.inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy✝ : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 hz : z ≠ 0 hy : y ≠ 0 ⊢ SameRay R x z [PROOFSTEP] rcases hxy.exists_pos hx hy with ⟨r₁, r₂, hr₁, hr₂, h₁⟩ [GOAL] case inr.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy✝ : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 hz : z ≠ 0 hy : y ≠ 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h₁ : r₁ • x = r₂ • y ⊢ SameRay R x z [PROOFSTEP] rcases hyz.exists_pos hy hz with ⟨r₃, r₄, hr₃, hr₄, h₂⟩ [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy✝ : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 hz : z ≠ 0 hy : y ≠ 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h₁ : r₁ • x = r₂ • y r₃ r₄ : R hr₃ : 0 < r₃ hr₄ : 0 < r₄ h₂ : r₃ • y = r₄ • z ⊢ SameRay R x z [PROOFSTEP] refine' Or.inr (Or.inr <| ⟨r₃ * r₁, r₂ * r₄, mul_pos hr₃ hr₁, mul_pos hr₂ hr₄, _⟩) [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hxy : SameRay R x y hyz : SameRay R y z hy✝ : y = 0 → x = 0 ∨ z = 0 hx : x ≠ 0 hz : z ≠ 0 hy : y ≠ 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h₁ : r₁ • x = r₂ • y r₃ r₄ : R hr₃ : 0 < r₃ hr₄ : 0 < r₄ h₂ : r₃ • y = r₄ • z ⊢ (r₃ * r₁) • x = (r₂ * r₄) • z [PROOFSTEP] rw [mul_smul, mul_smul, h₁, ← h₂, smul_comm] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z v : M r : R h✝ : 0 ≤ r h : 0 < r ⊢ 0 < 1 [PROOFSTEP] nontriviality R [GOAL] R : Type u_1 inst✝⁶ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M N : Type u_3 inst✝³ : AddCommMonoid N inst✝² : Module R N ι : Type u_4 inst✝¹ : DecidableEq ι x y z v : M r : R h✝ : 0 ≤ r h : 0 < r inst✝ : Nontrivial R ⊢ 0 < 1 [PROOFSTEP] exact zero_lt_one [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M r : R h : SameRay R x y hr : 0 ≤ r hy : y = 0 ⊢ r • y = 0 [PROOFSTEP] rw [hy, smul_zero] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M f : M →ₗ[R] N h : SameRay R x y hx : x = 0 ⊢ ↑f x = 0 [PROOFSTEP] rw [hx, map_zero] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M f : M →ₗ[R] N h : SameRay R x y hy : y = 0 ⊢ ↑f y = 0 [PROOFSTEP] rw [hy, map_zero] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M f : M →ₗ[R] N h✝ : SameRay R x y x✝ : ∃ r₁ r₂, 0 < r₁ ∧ 0 < r₂ ∧ r₁ • x = r₂ • y r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h : r₁ • x = r₂ • y ⊢ r₁ • ↑f x = r₂ • ↑f y [PROOFSTEP] rw [← f.map_smul, ← f.map_smul, h] [GOAL] R : Type u_1 inst✝⁶ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁵ : AddCommMonoid M inst✝⁴ : Module R M N : Type u_3 inst✝³ : AddCommMonoid N inst✝² : Module R N ι : Type u_4 inst✝¹ : DecidableEq ι x y z : M F : Type u_5 inst✝ : LinearMapClass F R M N f : F hf : Function.Injective ↑f ⊢ SameRay R (↑f x) (↑f y) ↔ SameRay R x y [PROOFSTEP] simp only [SameRay, map_zero, ← hf.eq_iff, map_smul] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z ⊢ SameRay R (x + y) z [PROOFSTEP] rcases eq_or_ne x 0 with (rfl | hx₀) [GOAL] case inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι y z : M hy : SameRay R y z hx : SameRay R 0 z ⊢ SameRay R (0 + y) z [PROOFSTEP] rwa [zero_add] [GOAL] case inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 ⊢ SameRay R (x + y) z [PROOFSTEP] rcases eq_or_ne y 0 with (rfl | hy₀) [GOAL] case inr.inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x z : M hx : SameRay R x z hx₀ : x ≠ 0 hy : SameRay R 0 z ⊢ SameRay R (x + 0) z [PROOFSTEP] rwa [add_zero] [GOAL] case inr.inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 ⊢ SameRay R (x + y) z [PROOFSTEP] rcases eq_or_ne z 0 with (rfl | hz₀) [GOAL] case inr.inr.inl R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y : M hx₀ : x ≠ 0 hy₀ : y ≠ 0 hx : SameRay R x 0 hy : SameRay R y 0 ⊢ SameRay R (x + y) 0 [PROOFSTEP] apply zero_right [GOAL] case inr.inr.inr R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 ⊢ SameRay R (x + y) z [PROOFSTEP] rcases hx.exists_pos hx₀ hz₀ with ⟨rx, rz₁, hrx, hrz₁, Hx⟩ [GOAL] case inr.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 rx rz₁ : R hrx : 0 < rx hrz₁ : 0 < rz₁ Hx : rx • x = rz₁ • z ⊢ SameRay R (x + y) z [PROOFSTEP] rcases hy.exists_pos hy₀ hz₀ with ⟨ry, rz₂, hry, hrz₂, Hy⟩ [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 rx rz₁ : R hrx : 0 < rx hrz₁ : 0 < rz₁ Hx : rx • x = rz₁ • z ry rz₂ : R hry : 0 < ry hrz₂ : 0 < rz₂ Hy : ry • y = rz₂ • z ⊢ SameRay R (x + y) z [PROOFSTEP] refine' Or.inr (Or.inr ⟨rx * ry, ry * rz₁ + rx * rz₂, mul_pos hrx hry, _, _⟩) [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro.refine'_1 R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 rx rz₁ : R hrx : 0 < rx hrz₁ : 0 < rz₁ Hx : rx • x = rz₁ • z ry rz₂ : R hry : 0 < ry hrz₂ : 0 < rz₂ Hy : ry • y = rz₂ • z ⊢ 0 < ry * rz₁ + rx * rz₂ [PROOFSTEP] apply_rules [add_pos, mul_pos] [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro.refine'_2 R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 rx rz₁ : R hrx : 0 < rx hrz₁ : 0 < rz₁ Hx : rx • x = rz₁ • z ry rz₂ : R hry : 0 < ry hrz₂ : 0 < rz₂ Hy : ry • y = rz₂ • z ⊢ (rx * ry) • (x + y) = (ry * rz₁ + rx * rz₂) • z [PROOFSTEP] simp only [mul_smul, smul_add, add_smul, ← Hx, ← Hy] [GOAL] case inr.inr.inr.intro.intro.intro.intro.intro.intro.intro.intro.refine'_2 R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : M hx : SameRay R x z hy : SameRay R y z hx₀ : x ≠ 0 hy₀ : y ≠ 0 hz₀ : z ≠ 0 rx rz₁ : R hrx : 0 < rx hrz₁ : 0 < rz₁ Hx : rx • x = rz₁ • z ry rz₂ : R hry : 0 < ry hrz₂ : 0 < rz₂ Hy : ry • y = rz₂ • z ⊢ rx • ry • x + rx • ry • y = ry • rx • x + rx • ry • y [PROOFSTEP] rw [smul_comm] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι ⊢ ∀ {x y z : RayVector R M}, SameRay R ↑x ↑y → SameRay R ↑y ↑z → SameRay R ↑x ↑z [PROOFSTEP] intros x y z hxy hyz [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι x y z : RayVector R M hxy : SameRay R ↑x ↑y hyz : SameRay R ↑y ↑z ⊢ SameRay R ↑x ↑z [PROOFSTEP] exact hxy.trans hyz fun hy => (y.2 hy).elim [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι u : Rˣ hu : 0 < ↑u v : Ray R M ⊢ u • v = v [PROOFSTEP] induction v using Module.Ray.ind [GOAL] case h R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι u : Rˣ hu : 0 < ↑u v✝ : M hv✝ : v✝ ≠ 0 ⊢ u • rayOfNeZero R v✝ hv✝ = rayOfNeZero R v✝ hv✝ [PROOFSTEP] rw [smul_rayOfNeZero, ray_eq_iff] [GOAL] case h R : Type u_1 inst✝⁵ : StrictOrderedCommSemiring R M : Type u_2 inst✝⁴ : AddCommMonoid M inst✝³ : Module R M N : Type u_3 inst✝² : AddCommMonoid N inst✝¹ : Module R N ι : Type u_4 inst✝ : DecidableEq ι u : Rˣ hu : 0 < ↑u v✝ : M hv✝ : v✝ ≠ 0 ⊢ SameRay R (u • v✝) v✝ [PROOFSTEP] exact SameRay.sameRay_pos_smul_left _ hu [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M ⊢ SameRay R (-x) (-y) ↔ SameRay R x y [PROOFSTEP] simp only [SameRay, neg_eq_zero, smul_neg, neg_inj] [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M ⊢ SameRay R (-x) y ↔ SameRay R x (-y) [PROOFSTEP] rw [← sameRay_neg_iff, neg_neg] [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 h : SameRay R x (r • x) ⊢ x = 0 [PROOFSTEP] rcases h with (rfl | h₀ | ⟨r₁, r₂, hr₁, hr₂, h⟩) [GOAL] case inl R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 ⊢ 0 = 0 [PROOFSTEP] rfl [GOAL] case inr.inl R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 h₀ : r • x = 0 ⊢ x = 0 [PROOFSTEP] simpa [hr.ne] using h₀ [GOAL] case inr.inr.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h : r₁ • x = r₂ • r • x ⊢ x = 0 [PROOFSTEP] rw [← sub_eq_zero, smul_smul, ← sub_smul, smul_eq_zero] at h [GOAL] case inr.inr.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h✝ : r₁ • x = r₂ • r • x h : r₁ - r₂ * r = 0 ∨ x = 0 ⊢ x = 0 [PROOFSTEP] refine' h.resolve_left (ne_of_gt <| sub_pos.2 _) [GOAL] case inr.inr.intro.intro.intro.intro R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M r : R hr : r < 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h✝ : r₁ • x = r₂ • r • x h : r₁ - r₂ * r = 0 ∨ x = 0 ⊢ r₂ * r < r₁ [PROOFSTEP] exact (mul_neg_of_pos_of_neg hr₂ hr).trans hr₁ [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M h : SameRay R x (-x) ⊢ x = 0 [PROOFSTEP] nontriviality M [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M h : SameRay R x (-x) ✝ : Nontrivial M ⊢ x = 0 [PROOFSTEP] haveI : Nontrivial R := Module.nontrivial R M [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M h : SameRay R x (-x) ✝ : Nontrivial M this : Nontrivial R ⊢ x = 0 [PROOFSTEP] refine' eq_zero_of_sameRay_neg_smul_right (neg_lt_zero.2 (zero_lt_one' R)) _ [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x y : M inst✝ : NoZeroSMulDivisors R M h : SameRay R x (-x) ✝ : Nontrivial M this : Nontrivial R ⊢ SameRay R x (-1 • x) [PROOFSTEP] rwa [neg_one_smul] [GOAL] R✝ : Type u_1 inst✝⁴ : StrictOrderedCommRing R✝ M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R✝ M inst✝ : Module R✝ N x y : M R : Type u_4 v : RayVector R M ⊢ - -v = v [PROOFSTEP] rw [Subtype.ext_iff, coe_neg, coe_neg, neg_neg] [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x✝ y : M x : Ray R M ⊢ - -x = x [PROOFSTEP] apply ind R (by simp) x [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x✝ y : M x : Ray R M ⊢ ∀ (v : M) (hv : v ≠ 0), - -rayOfNeZero R v hv = rayOfNeZero R v hv [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x✝ y : M inst✝ : NoZeroSMulDivisors R M x : Ray R M ⊢ x ≠ -x [PROOFSTEP] induction' x using Module.Ray.ind with x hx [GOAL] case h R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x✝ y : M inst✝ : NoZeroSMulDivisors R M x : M hx : x ≠ 0 ⊢ rayOfNeZero R x hx ≠ -rayOfNeZero R x hx [PROOFSTEP] rw [neg_rayOfNeZero, Ne.def, ray_eq_iff] [GOAL] case h R : Type u_1 inst✝⁵ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝⁴ : AddCommGroup M inst✝³ : AddCommGroup N inst✝² : Module R M inst✝¹ : Module R N x✝ y : M inst✝ : NoZeroSMulDivisors R M x : M hx : x ≠ 0 ⊢ ¬SameRay R x (-x) [PROOFSTEP] exact mt eq_zero_of_sameRay_self_neg hx [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M u : Rˣ v : Ray R M ⊢ -u • v = -(u • v) [PROOFSTEP] induction v using Module.Ray.ind [GOAL] case h R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M u : Rˣ v✝ : M hv✝ : v✝ ≠ 0 ⊢ -u • rayOfNeZero R v✝ hv✝ = -(u • rayOfNeZero R v✝ hv✝) [PROOFSTEP] simp only [smul_rayOfNeZero, Units.smul_def, Units.val_neg, neg_smul, neg_rayOfNeZero] [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M u : Rˣ hu : ↑u < 0 v : Ray R M ⊢ u • v = -v [PROOFSTEP] rw [← neg_inj, neg_neg, ← neg_units_smul, units_smul_of_pos] [GOAL] case hu R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M u : Rˣ hu : ↑u < 0 v : Ray R M ⊢ 0 < ↑(-u) [PROOFSTEP] rwa [Units.val_neg, Right.neg_pos_iff] [GOAL] R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M f : M ≃ₗ[R] N v : Ray R M ⊢ ↑(map f) (-v) = -↑(map f) v [PROOFSTEP] induction' v using Module.Ray.ind with g hg [GOAL] case h R : Type u_1 inst✝⁴ : StrictOrderedCommRing R M : Type u_2 N : Type u_3 inst✝³ : AddCommGroup M inst✝² : AddCommGroup N inst✝¹ : Module R M inst✝ : Module R N x y : M f : M ≃ₗ[R] N g : M hg : g ≠ 0 ⊢ ↑(map f) (-rayOfNeZero R g hg) = -↑(map f) (rayOfNeZero R g hg) [PROOFSTEP] simp [GOAL] R : Type u_1 inst✝² : LinearOrderedCommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M v₁ v₂ : M h : v₁ ∈ MulAction.orbit { x // x ∈ Units.posSubgroup R } v₂ ⊢ SameRay R v₁ v₂ [PROOFSTEP] rcases h with ⟨⟨r, hr : 0 < r.1⟩, rfl : r • v₂ = v₁⟩ [GOAL] case intro.mk R : Type u_1 inst✝² : LinearOrderedCommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M v₂ : M r : Rˣ hr : 0 < ↑r ⊢ SameRay R (r • v₂) v₂ [PROOFSTEP] exact SameRay.sameRay_pos_smul_left _ hr [GOAL] R : Type u_1 inst✝² : LinearOrderedCommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M u : Rˣ v : Module.Ray R M this : 0 < ↑u * ↑u ⊢ 0 < ↑(u * u) [PROOFSTEP] exact this [GOAL] R : Type u_1 inst✝² : LinearOrderedCommRing R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M u : Rˣ v : Module.Ray R M this : 0 < ↑u * ↑u ⊢ (u * u) • u⁻¹ • v = u • v [PROOFSTEP] rw [mul_smul, smul_inv_smul] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M v : M hv : v ≠ 0 r : R hr : r ≠ 0 ⊢ SameRay R v (r • v) ↔ 0 < r [PROOFSTEP] simp only [sameRay_smul_right_iff, hv, or_false_iff, hr.symm.le_iff_lt] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M v : M r : R ⊢ SameRay R (-v) (r • v) ↔ r ≤ 0 ∨ v = 0 [PROOFSTEP] rw [← sameRay_neg_iff, neg_neg, ← neg_smul, sameRay_smul_right_iff, neg_nonneg] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M v : M r : R hv : v ≠ 0 hr : r ≠ 0 ⊢ SameRay R (-v) (r • v) ↔ r < 0 [PROOFSTEP] simp only [sameRay_neg_smul_right_iff, hv, or_false_iff, hr.le_iff_lt] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M u : Rˣ v : Module.Ray R M ⊢ u • v = v ↔ 0 < ↑u [PROOFSTEP] induction' v using Module.Ray.ind with v hv [GOAL] case h R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M u : Rˣ v : M hv : v ≠ 0 ⊢ u • rayOfNeZero R v hv = rayOfNeZero R v hv ↔ 0 < ↑u [PROOFSTEP] simp only [smul_rayOfNeZero, ray_eq_iff, Units.smul_def, sameRay_smul_left_iff_of_ne hv u.ne_zero] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M u : Rˣ v : Module.Ray R M ⊢ u • v = -v ↔ ↑u < 0 [PROOFSTEP] rw [← neg_inj, neg_neg, ← Module.Ray.neg_units_smul, units_smul_eq_self_iff, Units.val_neg, neg_pos] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] by_cases hx : x = 0 [GOAL] case pos R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : x = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] simpa [hx] using fun h : LinearIndependent R ![0, y] => h.ne_zero 0 rfl [GOAL] case neg R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] by_cases hy : y = 0 [GOAL] case pos R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : y = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] simpa [hy] using fun h : LinearIndependent R ![x, 0] => h.ne_zero 1 rfl [GOAL] case neg R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] simp_rw [Fintype.not_linearIndependent_iff] [GOAL] case neg R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) ↔ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] refine' ⟨fun h => _, fun h => _⟩ [GOAL] case neg.refine'_1 R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 h : SameRay R x y ∨ SameRay R x (-y) ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] rcases h with ((hx0 | hy0 | ⟨r₁, r₂, hr₁, _, h⟩) | (hx0 | hy0 | ⟨r₁, r₂, hr₁, _, h⟩)) [GOAL] case neg.refine'_1.inl.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 hx0 : x = 0 ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] exact False.elim (hx hx0) [GOAL] case neg.refine'_1.inl.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 hy0 : y = 0 ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] exact False.elim (hy hy0) [GOAL] case neg.refine'_1.inl.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • y ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] refine' ⟨![r₁, -r₂], _⟩ [GOAL] case neg.refine'_1.inl.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • y ⊢ ∑ i : Fin (Nat.succ (Nat.succ 0)), Matrix.vecCons r₁ ![-r₂] i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, Matrix.vecCons r₁ ![-r₂] i ≠ 0 [PROOFSTEP] rw [Fin.sum_univ_two, Fin.exists_fin_two] [GOAL] case neg.refine'_1.inl.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • y ⊢ Matrix.vecCons r₁ ![-r₂] 0 • Matrix.vecCons x ![y] 0 + Matrix.vecCons r₁ ![-r₂] 1 • Matrix.vecCons x ![y] 1 = 0 ∧ (Matrix.vecCons r₁ ![-r₂] 0 ≠ 0 ∨ Matrix.vecCons r₁ ![-r₂] 1 ≠ 0) [PROOFSTEP] simp [h, hr₁.ne.symm] [GOAL] case neg.refine'_1.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 hx0 : x = 0 ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] exact False.elim (hx hx0) [GOAL] case neg.refine'_1.inr.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 hy0 : -y = 0 ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] exact False.elim (hy (neg_eq_zero.1 hy0)) [GOAL] case neg.refine'_1.inr.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • -y ⊢ ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 [PROOFSTEP] refine' ⟨![r₁, r₂], _⟩ [GOAL] case neg.refine'_1.inr.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • -y ⊢ ∑ i : Fin (Nat.succ (Nat.succ 0)), Matrix.vecCons r₁ ![r₂] i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, Matrix.vecCons r₁ ![r₂] i ≠ 0 [PROOFSTEP] rw [Fin.sum_univ_two, Fin.exists_fin_two] [GOAL] case neg.refine'_1.inr.inr.inr.intro.intro.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 r₁ r₂ : R hr₁ : 0 < r₁ left✝ : 0 < r₂ h : r₁ • x = r₂ • -y ⊢ Matrix.vecCons r₁ ![r₂] 0 • Matrix.vecCons x ![y] 0 + Matrix.vecCons r₁ ![r₂] 1 • Matrix.vecCons x ![y] 1 = 0 ∧ (Matrix.vecCons r₁ ![r₂] 0 ≠ 0 ∨ Matrix.vecCons r₁ ![r₂] 1 ≠ 0) [PROOFSTEP] simp [h, hr₁.ne.symm] [GOAL] case neg.refine'_2 R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 h : ∃ g, ∑ i : Fin (Nat.succ (Nat.succ 0)), g i • Matrix.vecCons x ![y] i = 0 ∧ ∃ i, g i ≠ 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rcases h with ⟨m, hm, hmne⟩ [GOAL] case neg.refine'_2.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : ∑ i : Fin (Nat.succ (Nat.succ 0)), m i • Matrix.vecCons x ![y] i = 0 hmne : ∃ i, m i ≠ 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rw [Fin.sum_univ_two, add_eq_zero_iff_eq_neg, Matrix.cons_val_zero, Matrix.cons_val_one, Matrix.head_cons] at hm [GOAL] case neg.refine'_2.intro.intro R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rcases lt_trichotomy (m 0) 0 with (hm0 | hm0 | hm0) [GOAL] case neg.refine'_2.intro.intro.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rcases lt_trichotomy (m 1) 0 with (hm1 | hm1 | hm1) [GOAL] case neg.refine'_2.intro.intro.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rcases lt_trichotomy (m 1) 0 with (hm1 | hm1 | hm1) [GOAL] case neg.refine'_2.intro.intro.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rcases lt_trichotomy (m 1) 0 with (hm1 | hm1 | hm1) [GOAL] case neg.refine'_2.intro.intro.inl.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : m 1 < 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] refine' Or.inr (Or.inr (Or.inr ⟨-m 0, -m 1, Left.neg_pos_iff.2 hm0, Left.neg_pos_iff.2 hm1, _⟩)) [GOAL] case neg.refine'_2.intro.intro.inl.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : m 1 < 0 ⊢ -m 0 • x = -m 1 • -y [PROOFSTEP] rw [neg_smul_neg, neg_smul, hm, neg_neg] [GOAL] case neg.refine'_2.intro.intro.inl.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : m 1 = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] exfalso [GOAL] case neg.refine'_2.intro.intro.inl.inr.inl.h R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : m 1 = 0 ⊢ False [PROOFSTEP] simp [hm1, hx, hm0.ne] at hm [GOAL] case neg.refine'_2.intro.intro.inl.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : 0 < m 1 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] refine' Or.inl (Or.inr (Or.inr ⟨-m 0, m 1, Left.neg_pos_iff.2 hm0, hm1, _⟩)) [GOAL] case neg.refine'_2.intro.intro.inl.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 < 0 hm1 : 0 < m 1 ⊢ -m 0 • x = m 1 • y [PROOFSTEP] rw [neg_smul, hm, neg_neg] [GOAL] case neg.refine'_2.intro.intro.inr.inl.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 hm1 : m 1 < 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] exfalso [GOAL] case neg.refine'_2.intro.intro.inr.inl.inl.h R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 hm1 : m 1 < 0 ⊢ False [PROOFSTEP] simp [hm0, hy, hm1.ne] at hm [GOAL] case neg.refine'_2.intro.intro.inr.inl.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 hm1 : m 1 = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] rw [Fin.exists_fin_two] at hmne [GOAL] case neg.refine'_2.intro.intro.inr.inl.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : m 0 ≠ 0 ∨ m 1 ≠ 0 hm0 : m 0 = 0 hm1 : m 1 = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] exact False.elim (not_and_or.2 hmne ⟨hm0, hm1⟩) [GOAL] case neg.refine'_2.intro.intro.inr.inl.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 hm1 : 0 < m 1 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] exfalso [GOAL] case neg.refine'_2.intro.intro.inr.inl.inr.inr.h R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : m 0 = 0 hm1 : 0 < m 1 ⊢ False [PROOFSTEP] simp [hm0, hy, hm1.ne.symm] at hm [GOAL] case neg.refine'_2.intro.intro.inr.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : m 1 < 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] refine' Or.inl (Or.inr (Or.inr ⟨m 0, -m 1, hm0, Left.neg_pos_iff.2 hm1, _⟩)) [GOAL] case neg.refine'_2.intro.intro.inr.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : m 1 < 0 ⊢ m 0 • x = -m 1 • y [PROOFSTEP] rwa [neg_smul] [GOAL] case neg.refine'_2.intro.intro.inr.inr.inr.inl R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : m 1 = 0 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] exfalso [GOAL] case neg.refine'_2.intro.intro.inr.inr.inr.inl.h R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : m 1 = 0 ⊢ False [PROOFSTEP] simp [hm1, hx, hm0.ne.symm] at hm [GOAL] case neg.refine'_2.intro.intro.inr.inr.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : 0 < m 1 ⊢ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] refine' Or.inr (Or.inr (Or.inr ⟨m 0, m 1, hm0, hm1, _⟩)) [GOAL] case neg.refine'_2.intro.intro.inr.inr.inr.inr R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 m : Fin (Nat.succ (Nat.succ 0)) → R hm : m 0 • x = -(m 1 • y) hmne : ∃ i, m i ≠ 0 hm0 : 0 < m 0 hm1 : 0 < m 1 ⊢ m 0 • x = m 1 • -y [PROOFSTEP] rwa [smul_neg] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ ¬LinearIndependent R ![x, y] [PROOFSTEP] rw [← sameRay_or_sameRay_neg_iff_not_linearIndependent] [GOAL] R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] by_cases hx : x = 0 [GOAL] case pos R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : x = 0 ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] simp [hx] [GOAL] case neg R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] by_cases hy : y = 0 [GOAL] case pos R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : y = 0 ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] simp [hx, hy] [GOAL] case neg R : Type u_1 inst✝³ : LinearOrderedCommRing R M : Type u_2 inst✝² : AddCommGroup M inst✝¹ : Module R M inst✝ : NoZeroSMulDivisors R M x y : M hx : ¬x = 0 hy : ¬y = 0 ⊢ SameRay R x y ∨ x ≠ 0 ∧ y ≠ 0 ∧ SameRay R x (-y) ↔ SameRay R x y ∨ SameRay R x (-y) [PROOFSTEP] simp [hx, hy] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M h✝ : SameRay R x y hx : x ≠ 0 hy : y ≠ 0 r₁ r₂ : R hr₁ : 0 < r₁ hr₂ : 0 < r₂ h : r₁ • x = r₂ • y ⊢ (r₂⁻¹ * r₁) • x = y [PROOFSTEP] rw [mul_smul, h, inv_smul_smul₀ hr₂.ne'] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M h : SameRay R x y hx : x ≠ 0 ⊢ ∃ r, 0 ≤ r ∧ r • x = y [PROOFSTEP] obtain rfl | hy := eq_or_ne y 0 [GOAL] case inl R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x v₁ v₂ : M hx : x ≠ 0 h : SameRay R x 0 ⊢ ∃ r, 0 ≤ r ∧ r • x = 0 [PROOFSTEP] exact ⟨0, le_rfl, zero_smul _ _⟩ [GOAL] case inr R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M h : SameRay R x y hx : x ≠ 0 hy : y ≠ 0 ⊢ ∃ r, 0 ≤ r ∧ r • x = y [PROOFSTEP] exact (h.exists_pos_left hx hy).imp fun _ => And.imp_left le_of_lt [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M h : SameRay R v₁ v₂ ⊢ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) [PROOFSTEP] rcases h with (rfl | rfl | ⟨r₁, r₂, h₁, h₂, H⟩) [GOAL] case inl R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₂ : M ⊢ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ 0 = a • (0 + v₂) ∧ v₂ = b • (0 + v₂) [PROOFSTEP] use 0, 1 [GOAL] case h R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₂ : M ⊢ 0 ≤ 0 ∧ 0 ≤ 1 ∧ 0 + 1 = 1 ∧ 0 = 0 • (0 + v₂) ∧ v₂ = 1 • (0 + v₂) [PROOFSTEP] simp [GOAL] case inr.inl R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ : M ⊢ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + 0) ∧ 0 = b • (v₁ + 0) [PROOFSTEP] use 1, 0 [GOAL] case h R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ : M ⊢ 0 ≤ 1 ∧ 0 ≤ 0 ∧ 1 + 0 = 1 ∧ v₁ = 1 • (v₁ + 0) ∧ 0 = 0 • (v₁ + 0) [PROOFSTEP] simp [GOAL] case inr.inr.intro.intro.intro.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M r₁ r₂ : R h₁ : 0 < r₁ h₂ : 0 < r₂ H : r₁ • v₁ = r₂ • v₂ ⊢ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) [PROOFSTEP] have h₁₂ : 0 < r₁ + r₂ := add_pos h₁ h₂ [GOAL] case inr.inr.intro.intro.intro.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M r₁ r₂ : R h₁ : 0 < r₁ h₂ : 0 < r₂ H : r₁ • v₁ = r₂ • v₂ h₁₂ : 0 < r₁ + r₂ ⊢ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ v₁ = a • (v₁ + v₂) ∧ v₂ = b • (v₁ + v₂) [PROOFSTEP] refine' ⟨r₂ / (r₁ + r₂), r₁ / (r₁ + r₂), div_nonneg h₂.le h₁₂.le, div_nonneg h₁.le h₁₂.le, _, _, _⟩ [GOAL] case inr.inr.intro.intro.intro.intro.refine'_1 R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M r₁ r₂ : R h₁ : 0 < r₁ h₂ : 0 < r₂ H : r₁ • v₁ = r₂ • v₂ h₁₂ : 0 < r₁ + r₂ ⊢ r₂ / (r₁ + r₂) + r₁ / (r₁ + r₂) = 1 [PROOFSTEP] rw [← add_div, add_comm, div_self h₁₂.ne'] [GOAL] case inr.inr.intro.intro.intro.intro.refine'_2 R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M r₁ r₂ : R h₁ : 0 < r₁ h₂ : 0 < r₂ H : r₁ • v₁ = r₂ • v₂ h₁₂ : 0 < r₁ + r₂ ⊢ v₁ = (r₂ / (r₁ + r₂)) • (v₁ + v₂) [PROOFSTEP] rw [div_eq_inv_mul, mul_smul, smul_add, ← H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne'] [GOAL] case inr.inr.intro.intro.intro.intro.refine'_3 R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y v₁ v₂ : M r₁ r₂ : R h₁ : 0 < r₁ h₂ : 0 < r₂ H : r₁ • v₁ = r₂ • v₂ h₁₂ : 0 < r₁ + r₂ ⊢ v₂ = (r₁ / (r₁ + r₂)) • (v₁ + v₂) [PROOFSTEP] rw [div_eq_inv_mul, mul_smul, smul_add, H, ← add_smul, add_comm r₂, inv_smul_smul₀ h₁₂.ne'] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ r • x = y) ↔ SameRay R x y [PROOFSTEP] refine' ⟨fun h => _, fun h => h.exists_pos_left hx hy⟩ [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hy : y ≠ 0 h : ∃ r, 0 < r ∧ r • x = y ⊢ SameRay R x y [PROOFSTEP] rcases h with ⟨r, hr, rfl⟩ [GOAL] case intro.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x : M hx : x ≠ 0 r : R hr : 0 < r hy : r • x ≠ 0 ⊢ SameRay R x (r • x) [PROOFSTEP] exact SameRay.sameRay_pos_smul_right x hr [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 ⊢ (∃ r, 0 < r ∧ r • x = y) ↔ SameRay R x y ∧ y ≠ 0 [PROOFSTEP] constructor [GOAL] case mp R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 ⊢ (∃ r, 0 < r ∧ r • x = y) → SameRay R x y ∧ y ≠ 0 [PROOFSTEP] rintro ⟨r, hr, rfl⟩ [GOAL] case mp.intro.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x : M hx : x ≠ 0 r : R hr : 0 < r ⊢ SameRay R x (r • x) ∧ r • x ≠ 0 [PROOFSTEP] simp [hx, hr.le, hr.ne'] [GOAL] case mpr R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 ⊢ SameRay R x y ∧ y ≠ 0 → ∃ r, 0 < r ∧ r • x = y [PROOFSTEP] rintro ⟨hxy, hy⟩ [GOAL] case mpr.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hxy : SameRay R x y hy : y ≠ 0 ⊢ ∃ r, 0 < r ∧ r • x = y [PROOFSTEP] exact (exists_pos_left_iff_sameRay hx hy).2 hxy [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 ⊢ (∃ r, 0 ≤ r ∧ r • x = y) ↔ SameRay R x y [PROOFSTEP] refine' ⟨fun h => _, fun h => h.exists_nonneg_left hx⟩ [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 h : ∃ r, 0 ≤ r ∧ r • x = y ⊢ SameRay R x y [PROOFSTEP] rcases h with ⟨r, hr, rfl⟩ [GOAL] case intro.intro R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x : M hx : x ≠ 0 r : R hr : 0 ≤ r ⊢ SameRay R x (r • x) [PROOFSTEP] exact SameRay.sameRay_nonneg_smul_right x hr [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ x = r • y) ↔ SameRay R x y [PROOFSTEP] rw [SameRay.sameRay_comm] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ x = r • y) ↔ SameRay R y x [PROOFSTEP] simp_rw [eq_comm (a := x)] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hx : x ≠ 0 hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ r • y = x) ↔ SameRay R y x [PROOFSTEP] exact exists_pos_left_iff_sameRay hy hx [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ x = r • y) ↔ SameRay R x y ∧ x ≠ 0 [PROOFSTEP] rw [SameRay.sameRay_comm] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ x = r • y) ↔ SameRay R y x ∧ x ≠ 0 [PROOFSTEP] simp_rw [eq_comm (a := x)] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 < r ∧ r • y = x) ↔ SameRay R y x ∧ x ≠ 0 [PROOFSTEP] exact exists_pos_left_iff_sameRay_and_ne_zero hy [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 ≤ r ∧ x = r • y) ↔ SameRay R x y [PROOFSTEP] rw [SameRay.sameRay_comm] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 ≤ r ∧ x = r • y) ↔ SameRay R y x [PROOFSTEP] simp_rw [eq_comm (a := x)] [GOAL] R : Type u_1 inst✝² : LinearOrderedField R M : Type u_2 inst✝¹ : AddCommGroup M inst✝ : Module R M x y : M hy : y ≠ 0 ⊢ (∃ r, 0 ≤ r ∧ r • y = x) ↔ SameRay R y x [PROOFSTEP] exact exists_nonneg_left_iff_sameRay (R := R) hy
So you're a Volkswagen fan! Tell us more. Yes I am! I actually grew up around Volkswagen cars a lot! My mum had a Volkswagen Beetle Convertible, and when my sister got her driving license, my parents got her a classic Volkswagen Beetle. We had another silver Volkswagen Beetle along the way too! That's a lot of Beetles. Any other models? When I was in the UK, I got myself a Volkswagen Passat. It ran on diesel and it was a gem of a car. We went everywhere with my Volkswagen Passat and it had such a huge boot. In fact, a lot of the vintage items you see in my shop were sourced from the UK, and yes, the Passat made it really easy for us to pack them all in. So you liked the Volkswagen Passat so much you bought one when you came back? Exactly. When we got back, getting a Volkswagen Passat was the natural choice, and we've driven this Passat ever since. Ideally we'd love to get another Volkswagen when the time comes to replace it.
Require Import List. Import ListNotations. Fixpoint revapp (xs ys: list nat): list nat := match xs with | [] => ys | x::r => revapp r (x::ys) end. (* Some useful lemmas from the standard library. *) Check app_assoc: forall t (xs ys zs: list t), xs ++ ys ++ zs = (xs ++ ys) ++ zs. Check app_nil_r: forall t (xs: list t), xs ++ [] = xs. Lemma equiv: forall xs, revapp xs [] = rev xs. Proof. Qed.
/* Copyright [2017-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef _MCAS_HSTORE_POOL_MANAGER_H #define _MCAS_HSTORE_POOL_MANAGER_H #include <api/kvstore_itf.h> /* status_t */ #include "alloc_key.h" /* AK_FORMAL */ #include "pool_error.h" #include <common/logging.h> /* log_source */ #include <common/string_view.h> #include <nupm/region_descriptor.h> #include <gsl/pointers> #include <sys/uio.h> #include <cstddef> #include <functional> #include <string> #include <system_error> struct pool_path; struct dax_manager; template <typename Pool> struct pool_manager : protected common::log_source { using string_view = common::string_view; pool_manager(unsigned debug_level_) : common::log_source(debug_level_) {} virtual ~pool_manager() {} virtual void pool_create_check(const std::size_t size_) = 0; virtual void pool_close_check(const string_view) = 0; virtual nupm::region_descriptor pool_get_regions(const Pool &) const = 0; /* * throws pool_error if create_region fails */ virtual auto pool_create_1( const pool_path &path_ , std::size_t size_ ) -> nupm::region_descriptor = 0; virtual auto pool_create_2( AK_FORMAL const nupm::region_descriptor & rac , component::IKVStore::flags_t flags , std::size_t expected_obj_count ) -> std::unique_ptr<Pool> = 0; virtual auto pool_open_1( const pool_path &path_ ) -> nupm::region_descriptor = 0; virtual auto pool_open_2( AK_FORMAL const nupm::region_descriptor & access_ , component::IKVStore::flags_t flags_ ) -> std::unique_ptr<Pool> = 0; virtual void pool_delete(const pool_path &path) = 0; virtual const std::unique_ptr<dax_manager> & get_dax_manager() const = 0; }; #endif
[GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f g : ι → Ω → E ℱ✝ ℱ : Filtration ι m0 μ : Measure Ω inst✝ : IsFiniteMeasure μ x : E i j : ι x✝ : i ≤ j ⊢ μ[(fun x_1 x_2 => x) j|↑ℱ i] =ᵐ[μ] (fun x_1 x_2 => x) i [PROOFSTEP] rw [condexp_const (ℱ.le _)] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ✝ : Filtration ι m0 inst✝¹ : OrderBot ι ℱ : Filtration ι m0 μ : Measure Ω inst✝ : IsFiniteMeasure μ f : Ω → E hf : StronglyMeasurable f hfint : Integrable f ⊢ Martingale (fun x => f) ℱ μ [PROOFSTEP] refine' ⟨fun i => hf.mono <| ℱ.mono bot_le, fun i j _ => _⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ✝ : Filtration ι m0 inst✝¹ : OrderBot ι ℱ : Filtration ι m0 μ : Measure Ω inst✝ : IsFiniteMeasure μ f : Ω → E hf : StronglyMeasurable f hfint : Integrable f i j : ι x✝ : i ≤ j ⊢ μ[(fun x => f) j|↑ℱ i] =ᵐ[μ] (fun x => f) i [PROOFSTEP] rw [condexp_of_stronglyMeasurable (ℱ.le _) (hf.mono <| ℱ.mono bot_le) hfint] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ✝ ℱ : Filtration ι m0 μ : Measure Ω i j : ι x✝ : i ≤ j ⊢ μ[OfNat.ofNat 0 j|↑ℱ i] =ᵐ[μ] OfNat.ofNat 0 i [PROOFSTEP] rw [Pi.zero_apply, condexp_zero] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ✝ ℱ : Filtration ι m0 μ : Measure Ω i j : ι x✝ : i ≤ j ⊢ 0 =ᵐ[μ] OfNat.ofNat 0 i [PROOFSTEP] simp [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ✝ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ✝ ℱ : Filtration ι m0 μ : Measure Ω i j : ι x✝ : i ≤ j ⊢ 0 =ᵐ[μ] 0 [PROOFSTEP] rfl [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ hf : Martingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ = ∫ (ω : Ω) in s, f j ω ∂μ [PROOFSTEP] rw [← @set_integral_condexp _ _ _ _ _ (ℱ i) m0 _ _ _ (ℱ.le i) _ (hf.integrable j) hs] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ hf : Martingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ = ∫ (x : Ω) in s, (μ[f j|↑ℱ i]) x ∂μ [PROOFSTEP] refine' set_integral_congr_ae (ℱ.le i s hs) _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ hf : Martingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∀ᵐ (x : Ω) ∂μ, x ∈ s → f i x = (μ[f j|↑ℱ i]) x [PROOFSTEP] filter_upwards [hf.2 i j hij] with _ heq _ using heq.symm [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 hf : Martingale f ℱ μ hg : Martingale g ℱ μ ⊢ Martingale (f + g) ℱ μ [PROOFSTEP] refine' ⟨hf.adapted.add hg.adapted, fun i j hij => _⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 hf : Martingale f ℱ μ hg : Martingale g ℱ μ i j : ι hij : i ≤ j ⊢ μ[(f + g) j|↑ℱ i] =ᵐ[μ] (f + g) i [PROOFSTEP] exact (condexp_add (hf.integrable j) (hg.integrable j)).trans ((hf.2 i j hij).add (hg.2 i j hij)) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 hf : Martingale f ℱ μ hg : Martingale g ℱ μ ⊢ Martingale (f - g) ℱ μ [PROOFSTEP] rw [sub_eq_add_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 hf : Martingale f ℱ μ hg : Martingale g ℱ μ ⊢ Martingale (f + -g) ℱ μ [PROOFSTEP] exact hf.add hg.neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 c : ℝ hf : Martingale f ℱ μ ⊢ Martingale (c • f) ℱ μ [PROOFSTEP] refine' ⟨hf.adapted.smul c, fun i j hij => _⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 c : ℝ hf : Martingale f ℱ μ i j : ι hij : i ≤ j ⊢ μ[(c • f) j|↑ℱ i] =ᵐ[μ] (c • f) i [PROOFSTEP] refine' (condexp_smul c (f j)).trans ((hf.2 i j hij).mono fun x hx => _) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 c : ℝ hf : Martingale f ℱ μ i j : ι hij : i ≤ j x : Ω hx : (μ[f j|↑ℱ i]) x = f i x ⊢ (c • μ[f j|↑ℱ i]) x = (c • f) i x [PROOFSTEP] rw [Pi.smul_apply, hx, Pi.smul_apply, Pi.smul_apply] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ f : ι → Ω → ℝ hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f j ω ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ [PROOFSTEP] rw [← set_integral_condexp (ℱ.le i) (hf.integrable j) hs] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ f : ι → Ω → ℝ hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (x : Ω) in s, (μ[f j|↑ℱ i]) x ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ [PROOFSTEP] refine' set_integral_mono_ae integrable_condexp.integrableOn (hf.integrable i).integrableOn _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ f : ι → Ω → ℝ hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ (fun x => (μ[f j|↑ℱ i]) x) ≤ᵐ[μ] fun ω => f i ω [PROOFSTEP] filter_upwards [hf.2.1 i j hij] with _ heq using heq [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ ⊢ Supermartingale (f + g) ℱ μ [PROOFSTEP] refine' ⟨hf.1.add hg.1, fun i j hij => _, fun i => (hf.2.2 i).add (hg.2.2 i)⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j ⊢ μ[(f + g) j|↑ℱ i] ≤ᵐ[μ] (f + g) i [PROOFSTEP] refine' (condexp_add (hf.integrable j) (hg.integrable j)).le.trans _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j ⊢ μ[f j|↑ℱ i] + μ[g j|↑ℱ i] ≤ᵐ[μ] (f + g) i [PROOFSTEP] filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij] [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j ⊢ ∀ (a : Ω), (μ[f j|↑ℱ i]) a ≤ f i a → (μ[g j|↑ℱ i]) a ≤ g i a → (μ[f j|↑ℱ i] + μ[g j|↑ℱ i]) a ≤ (f + g) i a [PROOFSTEP] intros [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : (μ[f j|↑ℱ i]) a✝² ≤ f i a✝² a✝ : (μ[g j|↑ℱ i]) a✝² ≤ g i a✝² ⊢ (μ[f j|↑ℱ i] + μ[g j|↑ℱ i]) a✝² ≤ (f + g) i a✝² [PROOFSTEP] refine' add_le_add _ _ [GOAL] case h.refine'_1 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : (μ[f j|↑ℱ i]) a✝² ≤ f i a✝² a✝ : (μ[g j|↑ℱ i]) a✝² ≤ g i a✝² ⊢ (μ[f j|↑ℱ i]) a✝² ≤ f i a✝² [PROOFSTEP] assumption [GOAL] case h.refine'_2 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Supermartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : (μ[f j|↑ℱ i]) a✝² ≤ f i a✝² a✝ : (μ[g j|↑ℱ i]) a✝² ≤ g i a✝² ⊢ (μ[g j|↑ℱ i]) a✝² ≤ g i a✝² [PROOFSTEP] assumption [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ ⊢ Submartingale (-f) ℱ μ [PROOFSTEP] refine' ⟨hf.1.neg, fun i j hij => _, fun i => (hf.2.2 i).neg⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j ⊢ (-f) i ≤ᵐ[μ] μ[(-f) j|↑ℱ i] [PROOFSTEP] refine' EventuallyLE.trans _ (condexp_neg (f j)).symm.le [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j ⊢ (-f) i ≤ᵐ[μ] -μ[f j|↑ℱ i] [PROOFSTEP] filter_upwards [hf.2.1 i j hij] with _ _ [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j a✝¹ : Ω a✝ : (μ[f j|↑ℱ i]) a✝¹ ≤ f i a✝¹ ⊢ (-f) i a✝¹ ≤ (-μ[f j|↑ℱ i]) a✝¹ [PROOFSTEP] simpa [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ ⊢ Submartingale (f + g) ℱ μ [PROOFSTEP] refine' ⟨hf.1.add hg.1, fun i j hij => _, fun i => (hf.2.2 i).add (hg.2.2 i)⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ (f + g) i ≤ᵐ[μ] μ[(f + g) j|↑ℱ i] [PROOFSTEP] refine' EventuallyLE.trans _ (condexp_add (hf.integrable j) (hg.integrable j)).symm.le [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ (f + g) i ≤ᵐ[μ] μ[f j|↑ℱ i] + μ[g j|↑ℱ i] [PROOFSTEP] filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij] [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ ∀ (a : Ω), f i a ≤ (μ[f j|↑ℱ i]) a → g i a ≤ (μ[g j|↑ℱ i]) a → (f + g) i a ≤ (μ[f j|↑ℱ i] + μ[g j|↑ℱ i]) a [PROOFSTEP] intros [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : f i a✝² ≤ (μ[f j|↑ℱ i]) a✝² a✝ : g i a✝² ≤ (μ[g j|↑ℱ i]) a✝² ⊢ (f + g) i a✝² ≤ (μ[f j|↑ℱ i] + μ[g j|↑ℱ i]) a✝² [PROOFSTEP] refine' add_le_add _ _ [GOAL] case h.refine'_1 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : f i a✝² ≤ (μ[f j|↑ℱ i]) a✝² a✝ : g i a✝² ≤ (μ[g j|↑ℱ i]) a✝² ⊢ f i a✝² ≤ (μ[f j|↑ℱ i]) a✝² [PROOFSTEP] assumption [GOAL] case h.refine'_2 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j a✝² : Ω a✝¹ : f i a✝² ≤ (μ[f j|↑ℱ i]) a✝² a✝ : g i a✝² ≤ (μ[g j|↑ℱ i]) a✝² ⊢ g i a✝² ≤ (μ[g j|↑ℱ i]) a✝² [PROOFSTEP] assumption [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ ⊢ Supermartingale (-f) ℱ μ [PROOFSTEP] refine' ⟨hf.1.neg, fun i j hij => (condexp_neg (f j)).le.trans _, fun i => (hf.2.2 i).neg⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ i j : ι hij : i ≤ j ⊢ -μ[f j|↑ℱ i] ≤ᵐ[μ] (-f) i [PROOFSTEP] filter_upwards [hf.2.1 i j hij] with _ _ [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ i j : ι hij : i ≤ j a✝¹ : Ω a✝ : f i a✝¹ ≤ (μ[f j|↑ℱ i]) a✝¹ ⊢ (-μ[f j|↑ℱ i]) a✝¹ ≤ (-f) i a✝¹ [PROOFSTEP] simpa [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ [PROOFSTEP] rw [← neg_le_neg_iff, ← integral_neg, ← integral_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : SigmaFiniteFiltration μ ℱ f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (a : Ω) in s, -f j a ∂μ ≤ ∫ (a : Ω) in s, -f i a ∂μ [PROOFSTEP] exact Supermartingale.set_integral_le hf.neg hij hs [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Supermartingale g ℱ μ ⊢ Submartingale (f - g) ℱ μ [PROOFSTEP] rw [sub_eq_add_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Submartingale f ℱ μ hg : Supermartingale g ℱ μ ⊢ Submartingale (f + -g) ℱ μ [PROOFSTEP] exact hf.add hg.neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g✝ : ι → Ω → E ℱ : Filtration ι m0 f g : ι → Ω → ℝ hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ ⊢ Submartingale (f ⊔ g) ℱ μ [PROOFSTEP] refine' ⟨fun i => @StronglyMeasurable.sup _ _ _ _ (ℱ i) _ _ _ (hf.adapted i) (hg.adapted i), fun i j hij => _, fun i => Integrable.sup (hf.integrable _) (hg.integrable _)⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g✝ : ι → Ω → E ℱ : Filtration ι m0 f g : ι → Ω → ℝ hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ (f ⊔ g) i ≤ᵐ[μ] μ[(f ⊔ g) j|↑ℱ i] [PROOFSTEP] refine' EventuallyLE.sup_le _ _ [GOAL] case refine'_1 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g✝ : ι → Ω → E ℱ : Filtration ι m0 f g : ι → Ω → ℝ hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ (fun i_1 => f i i_1) ≤ᵐ[μ] μ[(f ⊔ g) j|↑ℱ i] [PROOFSTEP] exact EventuallyLE.trans (hf.2.1 i j hij) (condexp_mono (hf.integrable _) (Integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall fun x => le_max_left _ _)) [GOAL] case refine'_2 Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g✝ : ι → Ω → E ℱ : Filtration ι m0 f g : ι → Ω → ℝ hf : Submartingale f ℱ μ hg : Submartingale g ℱ μ i j : ι hij : i ≤ j ⊢ (fun i_1 => g i i_1) ≤ᵐ[μ] μ[(f ⊔ g) j|↑ℱ i] [PROOFSTEP] exact EventuallyLE.trans (hg.2.1 i j hij) (condexp_mono (hg.integrable _) (Integrable.sup (hf.integrable j) (hg.integrable j)) (eventually_of_forall fun x => le_max_right _ _)) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ ⊢ Submartingale f ℱ μ [PROOFSTEP] refine' ⟨hadp, fun i j hij => _, hint⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j ⊢ f i ≤ᵐ[μ] μ[f j|↑ℱ i] [PROOFSTEP] suffices f i ≤ᵐ[μ.trim (ℱ.le i)] μ[f j|ℱ i] by exact ae_le_of_ae_le_trim this [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j this : f i ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] ⊢ f i ≤ᵐ[μ] μ[f j|↑ℱ i] [PROOFSTEP] exact ae_le_of_ae_le_trim this [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j ⊢ f i ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] [PROOFSTEP] suffices 0 ≤ᵐ[μ.trim (ℱ.le i)] μ[f j|ℱ i] - f i by filter_upwards [this] with x hx rwa [← sub_nonneg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j this : 0 ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] - f i ⊢ f i ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] [PROOFSTEP] filter_upwards [this] with x hx [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j this : 0 ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] - f i x : Ω hx : OfNat.ofNat 0 x ≤ (μ[f j|↑ℱ i] - f i) x ⊢ f i x ≤ (μ[f j|↑ℱ i]) x [PROOFSTEP] rwa [← sub_nonneg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j ⊢ 0 ≤ᵐ[Measure.trim μ (_ : ↑ℱ i ≤ m0)] μ[f j|↑ℱ i] - f i [PROOFSTEP] refine' ae_nonneg_of_forall_set_integral_nonneg ((integrable_condexp.sub (hint i)).trim _ (stronglyMeasurable_condexp.sub <| hadp i)) fun s hs _ => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → ∀ (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s x✝ : ↑↑(Measure.trim μ (_ : ↑ℱ i ≤ m0)) s < ⊤ ⊢ 0 ≤ ∫ (x : Ω) in s, (μ[f j|↑ℱ i] - f i) x ∂Measure.trim μ (_ : ↑ℱ i ≤ m0) [PROOFSTEP] specialize hf i j hij s hs [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) i j : ι hij : i ≤ j s : Set Ω hs : MeasurableSet s x✝ : ↑↑(Measure.trim μ (_ : ↑ℱ i ≤ m0)) s < ⊤ hf : ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ ⊢ 0 ≤ ∫ (x : Ω) in s, (μ[f j|↑ℱ i] - f i) x ∂Measure.trim μ (_ : ↑ℱ i ≤ m0) [PROOFSTEP] rwa [← set_integral_trim _ (stronglyMeasurable_condexp.sub <| hadp i) hs, integral_sub' integrable_condexp.integrableOn (hint i).integrableOn, sub_nonneg, set_integral_condexp (ℱ.le i) (hint j) hs] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] ⊢ Submartingale f ℱ μ [PROOFSTEP] refine' ⟨hadp, fun i j hij => _, hint⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] i j : ι hij : i ≤ j ⊢ f i ≤ᵐ[μ] μ[f j|↑ℱ i] [PROOFSTEP] rw [← condexp_of_stronglyMeasurable (ℱ.le _) (hadp _) (hint _), ← eventually_sub_nonneg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 inst✝ : IsFiniteMeasure μ f : ι → Ω → ℝ hadp : Adapted ℱ f hint : ∀ (i : ι), Integrable (f i) hf : ∀ (i j : ι), i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] i j : ι hij : i ≤ j ⊢ 0 ≤ᵐ[μ] μ[f j|↑ℱ i] - μ[f i|↑ℱ i] [PROOFSTEP] exact EventuallyLE.trans (hf i j hij) (condexp_sub (hint _) (hint _)).le [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j ⊢ 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] [PROOFSTEP] by_cases h : SigmaFinite (μ.trim (ℱ.le i)) [GOAL] case pos Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] case neg Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : ¬SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] [PROOFSTEP] swap [GOAL] case neg Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : ¬SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] [PROOFSTEP] rw [condexp_of_not_sigmaFinite (ℱ.le i) h] [GOAL] case pos Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ 0 ≤ᵐ[μ] μ[f j - f i|↑ℱ i] [PROOFSTEP] refine' EventuallyLE.trans _ (condexp_sub (hf.integrable _) (hf.integrable _)).symm.le [GOAL] case pos Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ 0 ≤ᵐ[μ] μ[f j|↑ℱ i] - μ[f i|↑ℱ i] [PROOFSTEP] rw [eventually_sub_nonneg, condexp_of_stronglyMeasurable (ℱ.le _) (hf.adapted _) (hf.integrable _)] [GOAL] case pos Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝³ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝² : NormedAddCommGroup E inst✝¹ : NormedSpace ℝ E inst✝ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 f : ι → Ω → ℝ hf : Submartingale f ℱ μ i j : ι hij : i ≤ j h : SigmaFinite (Measure.trim μ (_ : ↑ℱ i ≤ m0)) ⊢ f i ≤ᵐ[μ] μ[f j|↑ℱ i] [PROOFSTEP] exact hf.2.1 i j hij [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Submartingale g ℱ μ ⊢ Supermartingale (f - g) ℱ μ [PROOFSTEP] rw [sub_eq_add_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f g : ι → Ω → E ℱ : Filtration ι m0 inst✝¹ : Preorder E inst✝ : CovariantClass E E (fun x x_1 => x + x_1) fun x x_1 => x ≤ x_1 hf : Supermartingale f ℱ μ hg : Submartingale g ℱ μ ⊢ Supermartingale (f + -g) ℱ μ [PROOFSTEP] exact hf.add hg.neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Supermartingale f ℱ μ ⊢ Supermartingale (c • f) ℱ μ [PROOFSTEP] refine' ⟨hf.1.smul c, fun i j hij => _, fun i => (hf.2.2 i).smul c⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j ⊢ μ[(c • f) j|↑ℱ i] ≤ᵐ[μ] (c • f) i [PROOFSTEP] refine' (condexp_smul c (f j)).le.trans _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j ⊢ c • μ[f j|↑ℱ i] ≤ᵐ[μ] (c • f) i [PROOFSTEP] filter_upwards [hf.2.1 i j hij] with _ hle [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j a✝ : Ω hle : (μ[f j|↑ℱ i]) a✝ ≤ f i a✝ ⊢ (c • μ[f j|↑ℱ i]) a✝ ≤ (c • f) i a✝ [PROOFSTEP] simp_rw [Pi.smul_apply] [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Supermartingale f ℱ μ i j : ι hij : i ≤ j a✝ : Ω hle : (μ[f j|↑ℱ i]) a✝ ≤ f i a✝ ⊢ c • (μ[f j|↑ℱ i]) a✝ ≤ c • f i a✝ [PROOFSTEP] exact smul_le_smul_of_nonneg hle hc [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Supermartingale f ℱ μ ⊢ Submartingale (c • f) ℱ μ [PROOFSTEP] rw [← neg_neg c, (by ext (i x); simp : - -c • f = -(-c • f))] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Supermartingale f ℱ μ ⊢ - -c • f = -(-c • f) [PROOFSTEP] ext (i x) [GOAL] case h.h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Supermartingale f ℱ μ i : ι x : Ω ⊢ (- -c • f) i x = (-(-c • f)) i x [PROOFSTEP] simp [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Supermartingale f ℱ μ ⊢ Submartingale (-(-c • f)) ℱ μ [PROOFSTEP] exact (hf.smul_nonneg <| neg_nonneg.2 hc).neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Submartingale f ℱ μ ⊢ Submartingale (c • f) ℱ μ [PROOFSTEP] rw [← neg_neg c, (by ext (i x); simp : - -c • f = -(c • -f))] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Submartingale f ℱ μ ⊢ - -c • f = -(c • -f) [PROOFSTEP] ext (i x) [GOAL] case h.h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Submartingale f ℱ μ i : ι x : Ω ⊢ (- -c • f) i x = (-(c • -f)) i x [PROOFSTEP] simp [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : 0 ≤ c hf : Submartingale f ℱ μ ⊢ Submartingale (-(c • -f)) ℱ μ [PROOFSTEP] exact Supermartingale.neg (hf.neg.smul_nonneg hc) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Submartingale f ℱ μ ⊢ Supermartingale (c • f) ℱ μ [PROOFSTEP] rw [← neg_neg c, (by ext (i x); simp : - -c • f = -(-c • f))] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Submartingale f ℱ μ ⊢ - -c • f = -(-c • f) [PROOFSTEP] ext (i x) [GOAL] case h.h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Submartingale f ℱ μ i : ι x : Ω ⊢ (- -c • f) i x = (-(-c • f)) i x [PROOFSTEP] simp [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁷ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁶ : NormedAddCommGroup E inst✝⁵ : NormedSpace ℝ E inst✝⁴ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 F : Type u_4 inst✝³ : NormedLatticeAddCommGroup F inst✝² : NormedSpace ℝ F inst✝¹ : CompleteSpace F inst✝ : OrderedSMul ℝ F f : ι → Ω → F c : ℝ hc : c ≤ 0 hf : Submartingale f ℱ μ ⊢ Supermartingale (-(-c • f)) ℱ μ [PROOFSTEP] exact (hf.smul_nonneg <| neg_nonneg.2 hc).neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ ⊢ Submartingale f 𝒢 μ [PROOFSTEP] refine' submartingale_of_set_integral_le hadp hint fun i j hij s hs => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ i j : ℕ hij : i ≤ j s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f j ω ∂μ [PROOFSTEP] induction' hij with k hk₁ hk₂ [GOAL] case refl Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ i j : ℕ s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ [PROOFSTEP] exact le_rfl [GOAL] case step Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ i j : ℕ s : Set Ω hs : MeasurableSet s k : ℕ hk₁ : Nat.le i k hk₂ : ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f k ω ∂μ ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (Nat.succ k) ω ∂μ [PROOFSTEP] exact le_trans hk₂ (hf k s (𝒢.mono hk₁ _ hs)) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f (i + 1) ω ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ ⊢ Supermartingale f 𝒢 μ [PROOFSTEP] rw [← neg_neg f] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f (i + 1) ω ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ ⊢ Supermartingale (- -f) 𝒢 μ [PROOFSTEP] refine' (submartingale_of_set_integral_le_succ hadp.neg (fun i => (hint i).neg) _).neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, f (i + 1) ω ∂μ ≤ ∫ (ω : Ω) in s, f i ω ∂μ ⊢ ∀ (i : ℕ) (s : Set Ω), MeasurableSet s → ∫ (ω : Ω) in s, (-f) i ω ∂μ ≤ ∫ (ω : Ω) in s, (-f) (i + 1) ω ∂μ [PROOFSTEP] simpa only [integral_neg, Pi.neg_apply, neg_le_neg_iff] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), f i ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] ⊢ Submartingale f 𝒢 μ [PROOFSTEP] refine' submartingale_of_set_integral_le_succ hadp hint fun i s hs => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), f i ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] i : ℕ s : Set Ω hs : MeasurableSet s ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ [PROOFSTEP] have : ∫ ω in s, f (i + 1) ω ∂μ = ∫ ω in s, (μ[f (i + 1)|𝒢 i]) ω ∂μ := (set_integral_condexp (𝒢.le i) (hint _) hs).symm [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), f i ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] i : ℕ s : Set Ω hs : MeasurableSet s this : ∫ (ω : Ω) in s, f (i + 1) ω ∂μ = ∫ (ω : Ω) in s, (μ[f (i + 1)|↑𝒢 i]) ω ∂μ ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, f (i + 1) ω ∂μ [PROOFSTEP] rw [this] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), f i ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] i : ℕ s : Set Ω hs : MeasurableSet s this : ∫ (ω : Ω) in s, f (i + 1) ω ∂μ = ∫ (ω : Ω) in s, (μ[f (i + 1)|↑𝒢 i]) ω ∂μ ⊢ ∫ (ω : Ω) in s, f i ω ∂μ ≤ ∫ (ω : Ω) in s, (μ[f (i + 1)|↑𝒢 i]) ω ∂μ [PROOFSTEP] exact set_integral_mono_ae (hint i).integrableOn integrable_condexp.integrableOn (hf i) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1)|↑𝒢 i] ≤ᵐ[μ] f i ⊢ Supermartingale f 𝒢 μ [PROOFSTEP] rw [← neg_neg f] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1)|↑𝒢 i] ≤ᵐ[μ] f i ⊢ Supermartingale (- -f) 𝒢 μ [PROOFSTEP] refine' (submartingale_nat hadp.neg (fun i => (hint i).neg) fun i => EventuallyLE.trans _ (condexp_neg _).symm.le).neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1)|↑𝒢 i] ≤ᵐ[μ] f i i : ℕ ⊢ (-f) i ≤ᵐ[μ] -μ[fun i_1 => f (i + 1) i_1|↑𝒢 i] [PROOFSTEP] filter_upwards [hf i] with x hx using neg_le_neg hx [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f (i + 1) - f i|↑𝒢 i] ⊢ Submartingale f 𝒢 μ [PROOFSTEP] refine' submartingale_nat hadp hint fun i => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f (i + 1) - f i|↑𝒢 i] i : ℕ ⊢ f i ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] [PROOFSTEP] rw [← condexp_of_stronglyMeasurable (𝒢.le _) (hadp _) (hint _), ← eventually_sub_nonneg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f (i + 1) - f i|↑𝒢 i] i : ℕ ⊢ 0 ≤ᵐ[μ] μ[f (i + 1)|↑𝒢 i] - μ[f i|↑𝒢 i] [PROOFSTEP] exact EventuallyLE.trans (hf i) (condexp_sub (hint _) (hint _)).le [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f i - f (i + 1)|↑𝒢 i] ⊢ Supermartingale f 𝒢 μ [PROOFSTEP] rw [← neg_neg f] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f i - f (i + 1)|↑𝒢 i] ⊢ Supermartingale (- -f) 𝒢 μ [PROOFSTEP] refine' (submartingale_of_condexp_sub_nonneg_nat hadp.neg (fun i => (hint i).neg) _).neg [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[f i - f (i + 1)|↑𝒢 i] ⊢ ∀ (i : ℕ), 0 ≤ᵐ[μ] μ[(-f) (i + 1) - (-f) i|↑𝒢 i] [PROOFSTEP] simpa only [Pi.zero_apply, Pi.neg_apply, neg_sub_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1) - f i|↑𝒢 i] =ᵐ[μ] 0 ⊢ Martingale f 𝒢 μ [PROOFSTEP] refine' martingale_iff.2 ⟨supermartingale_of_condexp_sub_nonneg_nat hadp hint fun i => _, submartingale_of_condexp_sub_nonneg_nat hadp hint fun i => (hf i).symm.le⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1) - f i|↑𝒢 i] =ᵐ[μ] 0 i : ℕ ⊢ 0 ≤ᵐ[μ] μ[f i - f (i + 1)|↑𝒢 i] [PROOFSTEP] rw [← neg_sub] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1) - f i|↑𝒢 i] =ᵐ[μ] 0 i : ℕ ⊢ 0 ≤ᵐ[μ] μ[-(f (i + 1) - f i)|↑𝒢 i] [PROOFSTEP] refine' (EventuallyEq.trans _ (condexp_neg _).symm).le [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1) - f i|↑𝒢 i] =ᵐ[μ] 0 i : ℕ ⊢ 0 =ᵐ[μ] -μ[f (i + 1) - f i|↑𝒢 i] [PROOFSTEP] filter_upwards [hf i] with x hx [GOAL] case h Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ f : ℕ → Ω → ℝ hadp : Adapted 𝒢 f hint : ∀ (i : ℕ), Integrable (f i) hf : ∀ (i : ℕ), μ[f (i + 1) - f i|↑𝒢 i] =ᵐ[μ] 0 i : ℕ x : Ω hx : (μ[f (i + 1) - f i|↑𝒢 i]) x = OfNat.ofNat 0 x ⊢ OfNat.ofNat 0 x = (-μ[f (i + 1) - f i|↑𝒢 i]) x [PROOFSTEP] simpa only [Pi.zero_apply, Pi.neg_apply, zero_eq_neg] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Submartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) n : ℕ ⊢ f 0 ≤ᵐ[μ] f n [PROOFSTEP] induction' n with k ih [GOAL] case zero Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Submartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) ⊢ f 0 ≤ᵐ[μ] f Nat.zero [PROOFSTEP] rfl [GOAL] case succ Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Submartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) k : ℕ ih : f 0 ≤ᵐ[μ] f k ⊢ f 0 ≤ᵐ[μ] f (Nat.succ k) [PROOFSTEP] exact ih.trans ((hfmgle.2.1 k (k + 1) k.le_succ).trans_eq <| Germ.coe_eq.mp <| congr_arg Germ.ofFun <| condexp_of_stronglyMeasurable (𝒢.le _) (hfadp _) <| hfmgle.integrable _) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Supermartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) n : ℕ ⊢ f n ≤ᵐ[μ] f 0 [PROOFSTEP] induction' n with k ih [GOAL] case zero Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Supermartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) ⊢ f Nat.zero ≤ᵐ[μ] f 0 [PROOFSTEP] rfl [GOAL] case succ Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁵ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝⁴ : NormedAddCommGroup E inst✝³ : NormedSpace ℝ E inst✝² : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝¹ : Preorder E inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Supermartingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) k : ℕ ih : f k ≤ᵐ[μ] f 0 ⊢ f (Nat.succ k) ≤ᵐ[μ] f 0 [PROOFSTEP] exact ((Germ.coe_eq.mp <| congr_arg Germ.ofFun <| condexp_of_stronglyMeasurable (𝒢.le _) (hfadp _) <| hfmgle.integrable _).symm.trans_le (hfmgle.2.1 k (k + 1) k.le_succ)).trans ih [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Martingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) n : ℕ ⊢ f n =ᵐ[μ] f 0 [PROOFSTEP] induction' n with k ih [GOAL] case zero Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Martingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) ⊢ f Nat.zero =ᵐ[μ] f 0 [PROOFSTEP] rfl [GOAL] case succ Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : SigmaFiniteFiltration μ 𝒢 f : ℕ → Ω → E hfmgle : Martingale f 𝒢 μ hfadp : Adapted 𝒢 fun n => f (n + 1) k : ℕ ih : f k =ᵐ[μ] f 0 ⊢ f (Nat.succ k) =ᵐ[μ] f 0 [PROOFSTEP] exact ((Germ.coe_eq.mp (congr_arg Germ.ofFun <| condexp_of_stronglyMeasurable (𝒢.le _) (hfadp _) (hfmgle.integrable _))).symm.trans (hfmgle.2 k (k + 1) k.le_succ)).trans ih [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω ⊢ Submartingale (fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ [PROOFSTEP] have hξbdd : ∀ i, ∃ C, ∀ ω, |ξ i ω| ≤ C := fun i => ⟨R, fun ω => (abs_of_nonneg (hnonneg i ω)).trans_le (hbdd i ω)⟩ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C ⊢ Submartingale (fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ [PROOFSTEP] have hint : ∀ m, Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) μ := fun m => integrable_finset_sum' _ fun i _ => Integrable.bdd_mul ((hf.integrable _).sub (hf.integrable _)) hξ.stronglyMeasurable.aestronglyMeasurable (hξbdd _) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) ⊢ Submartingale (fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ [PROOFSTEP] have hadp : Adapted 𝒢 fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k) := by intro m refine' Finset.stronglyMeasurable_sum' _ fun i hi => _ rw [Finset.mem_range] at hi exact (hξ.stronglyMeasurable_le hi.le).mul ((hf.adapted.stronglyMeasurable_le (Nat.succ_le_of_lt hi)).sub (hf.adapted.stronglyMeasurable_le hi.le)) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) ⊢ Adapted 𝒢 fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k) [PROOFSTEP] intro m [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) m : ℕ ⊢ StronglyMeasurable ((fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k)) m) [PROOFSTEP] refine' Finset.stronglyMeasurable_sum' _ fun i hi => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) m i : ℕ hi : i ∈ Finset.range m ⊢ StronglyMeasurable (ξ i * (f (i + 1) - f i)) [PROOFSTEP] rw [Finset.mem_range] at hi [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) m i : ℕ hi : i < m ⊢ StronglyMeasurable (ξ i * (f (i + 1) - f i)) [PROOFSTEP] exact (hξ.stronglyMeasurable_le hi.le).mul ((hf.adapted.stronglyMeasurable_le (Nat.succ_le_of_lt hi)).sub (hf.adapted.stronglyMeasurable_le hi.le)) [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) hadp : Adapted 𝒢 fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k) ⊢ Submartingale (fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k)) 𝒢 μ [PROOFSTEP] refine' submartingale_of_condexp_sub_nonneg_nat hadp hint fun i => _ [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) hadp : Adapted 𝒢 fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k) i : ℕ ⊢ 0 ≤ᵐ[μ] μ[∑ k in Finset.range (i + 1), ξ k * (f (k + 1) - f k) - ∑ k in Finset.range i, ξ k * (f (k + 1) - f k)|↑𝒢 i] [PROOFSTEP] simp only [← Finset.sum_Ico_eq_sub _ (Nat.le_succ _), Finset.sum_apply, Pi.mul_apply, Pi.sub_apply, Nat.Ico_succ_singleton, Finset.sum_singleton] [GOAL] Ω : Type u_1 E : Type u_2 ι : Type u_3 inst✝⁴ : Preorder ι m0 : MeasurableSpace Ω μ : Measure Ω inst✝³ : NormedAddCommGroup E inst✝² : NormedSpace ℝ E inst✝¹ : CompleteSpace E f✝ g : ι → Ω → E ℱ : Filtration ι m0 𝒢 : Filtration ℕ m0 inst✝ : IsFiniteMeasure μ R : ℝ ξ f : ℕ → Ω → ℝ hf : Submartingale f 𝒢 μ hξ : Adapted 𝒢 ξ hbdd : ∀ (n : ℕ) (ω : Ω), ξ n ω ≤ R hnonneg : ∀ (n : ℕ) (ω : Ω), 0 ≤ ξ n ω hξbdd : ∀ (i : ℕ), ∃ C, ∀ (ω : Ω), |ξ i ω| ≤ C hint : ∀ (m : ℕ), Integrable (∑ k in Finset.range m, ξ k * (f (k + 1) - f k)) hadp : Adapted 𝒢 fun n => ∑ k in Finset.range n, ξ k * (f (k + 1) - f k) i : ℕ ⊢ 0 ≤ᵐ[μ] μ[ξ i * (f (i + 1) - f i)|↑𝒢 i] [PROOFSTEP] exact EventuallyLE.trans (EventuallyLE.mul_nonneg (eventually_of_forall (hnonneg _)) (hf.condexp_sub_nonneg (Nat.le_succ _))) (condexp_stronglyMeasurable_mul (hξ _) (((hf.integrable _).sub (hf.integrable _)).bdd_mul hξ.stronglyMeasurable.aestronglyMeasurable (hξbdd _)) ((hf.integrable _).sub (hf.integrable _))).symm.le
State Before: ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ ⊢ length l ≤ length (insertNth n x l) State After: case inl ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : n ≤ length l ⊢ length l ≤ length (insertNth n x l) case inr ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : length l < n ⊢ length l ≤ length (insertNth n x l) Tactic: cases' le_or_lt n l.length with hn hn State Before: case inl ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : n ≤ length l ⊢ length l ≤ length (insertNth n x l) State After: case inl ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : n ≤ length l ⊢ length l ≤ length l + 1 Tactic: rw [length_insertNth _ _ hn] State Before: case inl ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : n ≤ length l ⊢ length l ≤ length l + 1 State After: no goals Tactic: exact (Nat.lt_succ_self _).le State Before: case inr ι : Type ?u.123956 α : Type u β : Type v γ : Type w δ : Type x l₁ l₂ : List α a : α l : List α x : α n : ℕ hn : length l < n ⊢ length l ≤ length (insertNth n x l) State After: no goals Tactic: rw [insertNth_of_length_lt _ _ _ hn]
import collections import matplotlib.pyplot as plt import numpy as np import util def get_words(message): """Get the normalized list of words from a message string. This function should split a message into words, normalize them, and return the resulting list. For splitting, you should split on spaces. For normalization, you should convert everything to lowercase. Args: message: A string containing an SMS message Returns: The list of normalized words from the message. """ return map(lambda w: w.lower(), message.split(" ")) def create_dictionary(messages): """Create a dictionary mapping words to integer indices. This function should create a dictionary of word to indices using the provided training messages. Use get_words to process each message. Rare words are often not useful for modeling. Please only add words to the dictionary if they occur in at least five messages. Args: messages: A list of strings containing SMS messages Returns: A python dict mapping words to integers. """ msgs = [get_words(msg) for msg in messages] counter = collections.Counter(w for msg in set(msgs) for w in msg) words = [w for w, c in counter.items() if c >= 5] return dict(zip(words, range(len(words)))) def transform_text(messages, word_dictionary): """Transform a list of text messages into a numpy array for further processing. This function should create a numpy array that contains the number of times each word appears in each message. Each row in the resulting array should correspond to each message and each column should correspond to a word. Use the provided word dictionary to map words to column indices. Ignore words that are not present in the dictionary. Use get_words to get the words for a message. Args: messages: A list of strings where each string is an SMS message. word_dictionary: A python dict mapping words to integers. Returns: A numpy array marking the words present in each message. """ x = np.zeros([len(messages), len(word_dictionary)]) msgs = [get_words(msg) for msg in messages] for i in range(len(msgs)): for w in msgs[i]: if w in word_dictionary: x[i, word_dictionary[w]] += 1 return x def main(train_path, test_path): train_messages, train_labels = util.load_spam_dataset(train_path) test_messages, test_labels = util.load_spam_dataset(test_path) dictionary = create_dictionary(train_messages) util.write_json('./output/p06_dictionary', dictionary) x_train = transform_text(train_messages, dictionary) x_test = transform_text(test_messages, dictionary) np.savetxt('./output/p06_sample_train_matrix', x_train[:100,:]) nb = NaiveBayes() nb.fit(x_train, train_labels) y_pred = nb.predict(x_test) np.savetxt('./output/p06_naive_bayes_predictions', y_pred) accuracy = np.mean(y_pred == test_labels) print('Naive Bayes had an accuracy of {} on the testing set'.format(accuracy)) top_5_words = nb.top_words(5, dictionary) print('The top 5 indicative words for Naive Bayes are: ', top_5_words) class NaiveBayes(): def fit(self, x, y): """Fit a naive bayes model. This function should fit a Naive Bayes model given a training matrix and labels. Args: x: A numpy array containing word counts for the training data y: The binary (0 or 1) labels for that training data Returns: theta: GDA model parameters. """ m, n = x.shape y1 = np.sum(y) p_y1 = 1.0/m * y1 self.p_y1 = np.log(p_y1) self.p_y0 = np.log(1-p_y1) self.p_x_y1 = np.log(1.0/(y1+n) * (np.sum(x[y == 1], axis=0)+1)) self.p_x_y0 = np.log(1.0/(m-y1+n) * (np.sum(x[y == 0], axis=0)+1)) def predict(self, x): """Use a Naive Bayes model to compute predictions for a target matrix. This function should be able to predict on the models that fit_naive_bayes_model outputs. Args: x: A numpy array containing word counts Returns: A numpy array containing the predictions from the model """ p_y1_x = x.dot(self.p_x_y1) + self.p_y1 p_y0_x = x.dot(self.p_x_y0) + self.p_y0 return (p_y1_x > p_y0_x).astype(int) def top_words(self, k, dictionary): """Compute the top k words that are most indicative of the spam (i.e positive) class. Use the metric given in 6c as a measure of how indicative a word is. Return the words in sorted form, with the most indicative word first. Args: k: An integer indicating the number of words to display dictionary: A mapping of word to integer ids Returns: The top k most indicative words in sorted order with the most indicative first """ to_word = dict((i, w) for w, i in dictionary.items()) norm_p_x_y1 = list(zip(self.p_x_y1-self.p_x_y0, range(self.p_x_y1.size))) norm_p_x_y1.sort() return [to_word[norm_p_x_y1[i][1]] for i in range(max(-len(norm_p_x_y1), -k), 0)] if __name__ == "__main__": main(train_path='../data/ds6_train.tsv', test_path='../data/ds6_test.tsv')
Whereas Hergé 's use of Chinese in The Blue Lotus was correct , the Arabic script employed in The Crab with the Golden Claws was intentionally fictitious . Many of the place names featured in the series are puns : the town of <unk> was a pun on the French Que faire ? ( " what is to be done ? " ) while the port of <unk> derives from the French <unk> ( scrape , or fight ) . The name of Omar ben Salaad is a pun meaning " Lobster Salad " in French .
zipWithS : (f : a -> b -> c) -> Stream a -> Stream b -> Stream c zipWithS f (x :: xs) (y :: ys) = f x y :: zipWithS f xs ys partial fib : Stream Nat fib = 0 :: zipWithS (+) fib (1 :: fib) partial main : IO () main = printLn (take 15 fib)
import numpy import matplotlib.pyplot as plt import seaborn as sns import sys import json sns.set_style("whitegrid") results = json.load(open(sys.argv[1])) bar_width = 0.3 n_groups = len(results["cluster_ids"]) index = numpy.arange(n_groups) + bar_width/2 legend_labels = [] colors = sns.color_palette("hls", len(results["cluster_ids"])) for j, traj in enumerate(results["id_to_path"].keys()): rects = plt.bar(index, results["populations"][traj], bar_width, color = colors[j] ) index = index + bar_width legend_labels.append(results["id_to_path"][traj]) lgd = plt.legend(legend_labels, loc='center right', bbox_to_anchor=(1, 1)) plt.legend() plt.show()
If $f$ is a linear function from $\mathbb{R}$ to $\mathbb{R}$, then there exists a real number $c$ such that $f(x) = cx$ for all $x \<in> \mathbb{R}$.
State Before: R : Type ?u.871535 inst✝¹¹ : CommRing R M : Type u_3 inst✝¹⁰ : AddCommGroup M inst✝⁹ : Module R M M' : Type ?u.872126 inst✝⁸ : AddCommGroup M' inst✝⁷ : Module R M' ι✝ : Type ?u.872668 inst✝⁶ : DecidableEq ι✝ inst✝⁵ : Fintype ι✝ e : Basis ι✝ R M A : Type u_2 inst✝⁴ : CommRing A inst✝³ : Module A M κ : Type ?u.873644 inst✝² : Fintype κ ι : Type u_1 inst✝¹ : Finite ι inst✝ : Nonempty ι b : Basis ι A M ⊢ ↑LinearMap.det 0 = 0 State After: R : Type ?u.871535 inst✝¹¹ : CommRing R M : Type u_3 inst✝¹⁰ : AddCommGroup M inst✝⁹ : Module R M M' : Type ?u.872126 inst✝⁸ : AddCommGroup M' inst✝⁷ : Module R M' ι✝ : Type ?u.872668 inst✝⁶ : DecidableEq ι✝ inst✝⁵ : Fintype ι✝ e : Basis ι✝ R M A : Type u_2 inst✝⁴ : CommRing A inst✝³ : Module A M κ : Type ?u.873644 inst✝² : Fintype κ ι : Type u_1 inst✝¹ : Finite ι inst✝ : Nonempty ι b : Basis ι A M this : DecidableEq ι ⊢ ↑LinearMap.det 0 = 0 Tactic: haveI := Classical.decEq ι State Before: R : Type ?u.871535 inst✝¹¹ : CommRing R M : Type u_3 inst✝¹⁰ : AddCommGroup M inst✝⁹ : Module R M M' : Type ?u.872126 inst✝⁸ : AddCommGroup M' inst✝⁷ : Module R M' ι✝ : Type ?u.872668 inst✝⁶ : DecidableEq ι✝ inst✝⁵ : Fintype ι✝ e : Basis ι✝ R M A : Type u_2 inst✝⁴ : CommRing A inst✝³ : Module A M κ : Type ?u.873644 inst✝² : Fintype κ ι : Type u_1 inst✝¹ : Finite ι inst✝ : Nonempty ι b : Basis ι A M this : DecidableEq ι ⊢ ↑LinearMap.det 0 = 0 State After: case intro R : Type ?u.871535 inst✝¹¹ : CommRing R M : Type u_3 inst✝¹⁰ : AddCommGroup M inst✝⁹ : Module R M M' : Type ?u.872126 inst✝⁸ : AddCommGroup M' inst✝⁷ : Module R M' ι✝ : Type ?u.872668 inst✝⁶ : DecidableEq ι✝ inst✝⁵ : Fintype ι✝ e : Basis ι✝ R M A : Type u_2 inst✝⁴ : CommRing A inst✝³ : Module A M κ : Type ?u.873644 inst✝² : Fintype κ ι : Type u_1 inst✝¹ : Finite ι inst✝ : Nonempty ι b : Basis ι A M this : DecidableEq ι val✝ : Fintype ι ⊢ ↑LinearMap.det 0 = 0 Tactic: cases nonempty_fintype ι State Before: case intro R : Type ?u.871535 inst✝¹¹ : CommRing R M : Type u_3 inst✝¹⁰ : AddCommGroup M inst✝⁹ : Module R M M' : Type ?u.872126 inst✝⁸ : AddCommGroup M' inst✝⁷ : Module R M' ι✝ : Type ?u.872668 inst✝⁶ : DecidableEq ι✝ inst✝⁵ : Fintype ι✝ e : Basis ι✝ R M A : Type u_2 inst✝⁴ : CommRing A inst✝³ : Module A M κ : Type ?u.873644 inst✝² : Fintype κ ι : Type u_1 inst✝¹ : Finite ι inst✝ : Nonempty ι b : Basis ι A M this : DecidableEq ι val✝ : Fintype ι ⊢ ↑LinearMap.det 0 = 0 State After: no goals Tactic: rwa [← det_toMatrix b, LinearEquiv.map_zero, det_zero]