Datasets:
AI4M
/

text
stringlengths
0
3.34M
C C $Id: e2fndp.f,v 1.5 2008-07-27 00:17:08 haley Exp $ C C Copyright (C) 2000 C University Corporation for Atmospheric Research C All Rights Reserved C C The use of this Software is governed by a License Agreement. C DOUBLE PRECISION FUNCTION E2FNDP (ECCNTS) C C This function computes the constant E2. C IMPLICIT DOUBLE PRECISION (A-Z) DATA CON1,CON2 /0.05859375D0,0.75D0/ DATA ONE /1.0D0/ C E2FNDP = CON1 * ECCNTS * ECCNTS * (ONE + CON2 * ECCNTS) C RETURN END
Boron nitride is a synthetic material that's available in several forms, including powder, solid, liquid, and aerosol spray. Most types of glass will not stick to boron nitride; as a result, the liquid and aerosol forms can be used in kiln-forming as a release on slumping molds. Although boron nitride is much more expensive than kiln wash, it does have several advantages. Applied correctly, it is smoother than kiln wash. It's also less dusty, and may be less likely to mark the slumped glass than kiln wash. It can be used on both stainless steel and clay molds, but most formulations of boron nitride are not suitable for use on the kiln shelf. Depending on the quality and purity, liquid boron nitride may be used as is or diluted with distilled water. It works best when diluted to the consistency of whole milk. Boron nitride aerosol sprays can be used straight out of the can, and no mixing or diluting is necessary. In general, boron nitride is rated for kiln use only to around 1550F/840C. Some varieties of the product will claim higher rated temperatures, but usually this refers to the product's use in a reducing atmosphere, rather than in the oxidizing atmosphere typical of most kilns. Tomorrow's tip will contain specific information about using boron nitride on slumping molds.
a=1:20 @test avg(a) == 10.5
### CCM analysis to determine causality # Spatial CV ~ Age diversity, Abundance, AMO, SBT/SST, CV of SBT/SST ########## Warning! # This step takes much time. # One can skip this step if the pre-run CCM results are provided. # Please see the loading code below. ########## Warning! # run CCM several times to find the best lag for each variable EDM_lib_var = lapply(EDM_lib_var, function(item, lib_var=library_var, lag=lags, t_ccm=time_ccm){ data = item[[dataset]] data = subset(data, select=names(data) %ni% c("Year", "Quarter")) data = cbind(data[lib_var], subset(data, select=names(data) %ni% lib_var)) item$ccm = data.frame(matrix(0, nrow = 0, ncol = 10)) for (i in 1:t_ccm){ seed = 1234 + i * 10 ccm_result = determineCausality(data = data, dim.list = item$E, species = item$species, lags = lag, seed = seed) item$ccm = rbind(item$ccm, ccm_result) } return(item) }) # save ccm results lapply(EDM_lib_var, function(item){ write.csv(item$ccm, file = paste0(wd, ccm_path, item$species, ".csv"), row.names = FALSE) })
INCLUDE "cortex-a7.rd"
(* ** License * ----------------------------------------------------------------------- * Copyright 2016--2017 IMDEA Software Institute * Copyright 2016--2017 Inria * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ----------------------------------------------------------------------- *) (* ** Imports and settings *) From mathcomp Require Import all_ssreflect. From Coq.Unicode Require Import Utf8. Require Import ZArith Setoid Morphisms CMorphisms CRelationClasses. Require Import xseq oseq. Require Psatz. From CoqWord Require Import ssrZ. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope Z_scope. (* -------------------------------------------------------------------- *) Module FinIsCount. Section FinIsCount. Variable (T : eqType) (enum : seq T) (A : Finite.axiom enum). Definition pickle (x : T) := seq.index x enum. Definition unpickle (n : nat) := nth None [seq some x | x <- enum] n. Definition pickleK : pcancel pickle unpickle. Proof. move=> x; have xE: x \in enum by apply/count_memPn; rewrite (A x). by rewrite /pickle /unpickle (nth_map x) ?(nth_index, index_mem). Qed. End FinIsCount. End FinIsCount. (* ** Result monad * -------------------------------------------------------------------- *) Variant result (E : Type) (A : Type) : Type := | Ok of A | Error of E. Arguments Error {E} {A} s. Definition is_ok (E A:Type) (r:result E A) := if r is Ok a then true else false. Lemma is_ok_ok (E A:Type) (a:A) : is_ok (Ok E a). Proof. done. Qed. Hint Resolve is_ok_ok. Lemma is_okP (E A:Type) (r:result E A) : reflect (exists (a:A), r = Ok E a) (is_ok r). Proof. case: r => /=; constructor; first by eauto. by move=> []. Qed. Section ResultEqType. Variable E A : eqType. Definition result_eq (r1 r2: result E A): bool := match r1, r2 with | Ok a1, Ok a2 => a1 == a2 | Error e1, Error e2 => e1 == e2 | _, _ => false end. Lemma result_eqP : Equality.axiom result_eq. Proof. case=> [a1|e1] [a2|e2] /=; try (by apply: ReflectF); by apply: (equivP eqP);split=>[|[]] ->. Qed. Canonical result_eqMixin := EqMixin result_eqP. Canonical result_eqType := Eval hnf in EqType (result E A) result_eqMixin. End ResultEqType. Module Result. Definition apply eT aT rT (f : aT -> rT) (x : rT) (u : result eT aT) := if u is Ok y then f y else x. Definition bind eT aT rT (f : aT -> result eT rT) g := match g with | Ok x => f x | Error s => Error s end. Definition map eT aT rT (f : aT -> rT) := bind (fun x => Ok eT (f x)). Definition default eT aT := @apply eT aT aT (fun x => x). End Result. Definition o2r eT aT (e : eT) (o : option aT) := match o with | None => Error e | Some x => Ok eT x end. Notation rapp := Result.apply. Notation rdflt := Result.default. Notation rbind := Result.bind. Notation rmap := Result.map. Notation ok := (@Ok _). Notation "m >>= f" := (rbind f m) (at level 25, left associativity). Notation "'Let' x ':=' m 'in' body" := (m >>= (fun x => body)) (at level 25). Lemma bindA eT aT bT cT (f : aT -> result eT bT) (g: bT -> result eT cT) m: m >>= f >>= g = m >>= (fun a => f a >>= g). Proof. case:m => //=. Qed. Lemma bind_eq eT aT rT (f1 f2 : aT -> result eT rT) m1 m2 : m1 = m2 -> f1 =1 f2 -> m1 >>= f1 = m2 >>= f2. Proof. move=> <- Hf; case m1 => //=. Qed. Definition ok_inj {E A} (a a': A) (H: Ok E a = ok a') : a = a' := let 'Logic.eq_refl := H in Logic.eq_refl. Definition Error_inj {E A} (a a': E) (H: @Error E A a = Error a') : a = a' := let 'Logic.eq_refl := H in Logic.eq_refl. Definition assert E (b: bool) (e: E) : result E unit := if b then ok tt else Error e. Lemma assertP E b e u : @assert E b e = ok u → b. Proof. by case: b. Qed. Arguments assertP {E b e u} _. Variant error := | ErrOob | ErrAddrUndef | ErrAddrInvalid | ErrStack | ErrType. Scheme Equality for error. Lemma error_beqP : Equality.axiom error_beq. Proof. move=> e1 e2;case Heq: error_beq;constructor. + by apply: internal_error_dec_bl. by move=> /internal_error_dec_lb;rewrite Heq. Qed. Canonical error_eqMixin := EqMixin error_beqP. Canonical error_eqType := Eval hnf in EqType error error_eqMixin. Definition exec t := result error t. Definition type_error {t} := @Error _ t ErrType. Definition undef_error {t} := @Error error t ErrAddrUndef. Lemma bindW {T U} (v : exec T) (f : T -> exec U) r : v >>= f = ok r -> exists2 a, v = ok a & f a = ok r. Proof. by case E: v => [a|//] /= <-; exists a. Qed. Lemma rbindP eT aT rT (e:result eT aT) (body:aT -> result eT rT) v (P:Type): (forall z, e = ok z -> body z = Ok _ v -> P) -> e >>= body = Ok _ v -> P. Proof. by case: e=> //= a H /H H';apply H'. Qed. Ltac t_rbindP := do? (apply: rbindP => ??). Ltac t_xrbindP := match goal with | [ |- Result.bind _ _ = Ok _ _ -> _ ] => let y := fresh "y" in let h := fresh "h" in apply: rbindP=> y; t_xrbindP=> h; t_xrbindP; move: y h | [ |- ok _ = ok _ -> _ ] => case; t_xrbindP | [ |- _ -> _ ] => let h := fresh "h" in move=> h; t_xrbindP; move: h | _ => idtac end. Ltac clarify := repeat match goal with | H : ?a = ?b |- _ => subst a || subst b | H : ok _ = ok _ |- _ => apply ok_inj in H | H : Some _ = Some _ |- _ => move: H => /Some_inj H | H : ?a = _, K : ?a = _ |- _ => rewrite H in K end. Lemma Let_Let {eT A B C} (a:result eT A) (b:A -> result eT B) (c: B -> result eT C) : ((a >>= b) >>= c) = a >>= (fun a => b a >>= c). Proof. by case: a. Qed. Definition mapM eT aT bT (f : aT -> result eT bT) : seq aT → result eT (seq bT) := fix mapM xs := match xs with | [::] => Ok eT [::] | [:: x & xs] => f x >>= fun y => mapM xs >>= fun ys => Ok eT [:: y & ys] end. Lemma mapM_cons aT eT bT x xs y ys (f : aT -> result eT bT): f x = ok y /\ mapM f xs = ok ys <-> mapM f (x :: xs) = ok (y :: ys). Proof. split. by move => [] /= -> ->. by simpl; t_xrbindP => y0 -> h0 -> -> ->. Qed. Lemma map_ext aT bT f g m : (forall a, List.In a m -> f a = g a) -> @map aT bT f m = map g m. Proof. elim: m => //= a m ih ext. rewrite ext; [ f_equal | ]; eauto. Qed. Instance mapM_ext eT aT bT : Proper (@eqfun (result eT bT) aT ==> eq ==> eq) (@mapM eT aT bT). Proof. move => f g ext xs xs' <-{xs'}. by elim: xs => //= a xs ->; rewrite (ext a); case: (g a). Qed. Lemma mapM_size eT aT bT f xs ys : @mapM eT aT bT f xs = ok ys -> size xs = size ys. Proof. elim: xs ys. - by move => ys [<-]. move => x xs ih ys /=; case: (f _) => //= y. by case: (mapM f xs) ih => //= ys' ih [] ?; subst; rewrite (ih _ erefl). Qed. Local Close Scope Z_scope. Lemma mapM_nth eT aT bT f xs ys d d' n : @mapM eT aT bT f xs = ok ys -> n < size xs -> f (nth d xs n) = ok (nth d' ys n). Proof. elim: xs ys n. - by move => ys n [<-]. move => x xs ih ys n /=; case h: (f _) => [ y | ] //=. case: (mapM f xs) ih => //= ys' /(_ _ _ erefl) ih [] <- {ys}. by case: n ih => // n /(_ n). Qed. Local Open Scope Z_scope. Lemma mapM_onth eT aT bT (f: aT → result eT bT) (xs: seq aT) ys n x : mapM f xs = ok ys → onth xs n = Some x → ∃ y, onth ys n = Some y ∧ f x = ok y. Proof. move => ok_ys. case: (leqP (size xs) n) => hsz; first by rewrite (onth_default hsz). elim: xs ys ok_ys n hsz. - by move => ys [<-]. move => y xs ih ys' /=; t_xrbindP => z ok_z ys ok_ys <- [| n ] hsz /= ok_y. - by exists z; case: ok_y => <-. exact: (ih _ ok_ys n hsz ok_y). Qed. Lemma mapM_onth' eT aT bT (f: aT → result eT bT) (xs: seq aT) ys n y : mapM f xs = ok ys → onth ys n = Some y → ∃ x, onth xs n = Some x ∧ f x = ok y. Proof. move => ok_ys. case: (leqP (size ys) n) => hsz; first by rewrite (onth_default hsz). elim: xs ys ok_ys n hsz. - by move => ys [<-]. move => x xs ih ys' /=; t_xrbindP => z ok_z ys ok_ys <- [| n ] hsz /= ok_y. - by exists x; case: ok_y => <-. exact: (ih _ ok_ys n hsz ok_y). Qed. Lemma mapMP {eT} {aT bT: eqType} (f: aT -> result eT bT) (s: seq aT) (s': seq bT) y: mapM f s = ok s' -> reflect (exists2 x, x \in s & f x = ok y) (y \in s'). Proof. elim: s s' => /= [s' [] <-|x s IHs s']; first by right; case. apply: rbindP=> y0 Hy0. apply: rbindP=> ys Hys []<-. have IHs' := (IHs _ Hys). rewrite /= in_cons eq_sym; case Hxy: (y0 == y). by left; exists x; [rewrite mem_head | rewrite -(eqP Hxy)]. apply: (iffP IHs')=> [[x' Hx' <-]|[x' Hx' Dy]]. by exists x'; first by apply: predU1r. rewrite -Dy. case/predU1P: Hx'=> [Hx|]. + exfalso. move: Hxy=> /negP Hxy. apply: Hxy. rewrite Hx Hy0 in Dy. by move: Dy=> [] ->. + by exists x'. Qed. Lemma mapM_In {aT bT eT} (f: aT -> result eT bT) (s: seq aT) (s': seq bT) x: mapM f s = ok s' -> List.In x s -> exists y, List.In y s' /\ f x = ok y. Proof. elim: s s'=> // a l /= IH s'. apply: rbindP=> y Hy. apply: rbindP=> ys Hys []<-. case. + by move=> <-; exists y; split=> //; left. + move=> Hl; move: (IH _ Hys Hl)=> [y0 [Hy0 Hy0']]. by exists y0; split=> //; right. Qed. Lemma mapM_In' {aT bT eT} (f: aT -> result eT bT) (s: seq aT) (s': seq bT) y: mapM f s = ok s' -> List.In y s' -> exists2 x, List.In x s & f x = ok y. Proof. elim: s s'. + by move => _ [<-]. move => a s ih s'' /=; t_xrbindP => b ok_b s' rec <- {s''} /=. case. + by move=> <-; exists a => //; left. by move => h; case: (ih _ rec h) => x hx ok_y; eauto. Qed. Lemma mapM_cat {eT aT bT} (f: aT → result eT bT) (s1 s2: seq aT) : mapM f (s1 ++ s2) = Let r1 := mapM f s1 in Let r2 := mapM f s2 in ok (r1 ++ r2). Proof. elim: s1 s2; first by move => s /=; case (mapM f s). move => a s1 ih s2 /=. case: (f _) => // b; rewrite /= ih{ih}. case: (mapM f s1) => // bs /=. by case: (mapM f s2). Qed. Corollary mapM_rcons {eT aT bT} (f: aT → result eT bT) (s: seq aT) (a: aT) : mapM f (rcons s a) = Let r1 := mapM f s in Let r2 := f a in ok (rcons r1 r2). Proof. by rewrite -cats1 mapM_cat /=; case: (f a) => // b; case: (mapM _ _) => // bs; rewrite /= cats1. Qed. Section FOLDM. Context (eT aT bT:Type) (f:aT -> bT -> result eT bT). Fixpoint foldM (acc : bT) (l : seq aT) := match l with | [::] => Ok eT acc | [:: a & la ] => f a acc >>= fun acc => foldM acc la end. Definition isOk e a (r : result e a) := if r is Ok _ then true else false. End FOLDM. Section FOLD2. Variable A B E R:Type. Variable e: E. Variable f : A -> B -> R -> result E R. Fixpoint fold2 (la:seq A) (lb: seq B) r := match la, lb with | [::] , [::] => Ok E r | a::la, b::lb => f a b r >>= (fold2 la lb) | _ , _ => Error e end. End FOLD2. Section MAP2. Variable A B E R:Type. Variable e: E. Variable f : A -> B -> result E R. Fixpoint mapM2 (la:seq A) (lb: seq B) := match la, lb with | [::] , [::] => Ok E [::] | a::la, b::lb => Let c := f a b in Let lc := mapM2 la lb in ok (c::lc) | _ , _ => Error e end. Lemma mapM2_Forall2 (P: R → B → Prop) ma mb mr : (∀ a b r, List.In (a, b) (zip ma mb) → f a b = ok r → P r b) → mapM2 ma mb = ok mr → List.Forall2 P mr mb. Proof. elim: ma mb mr. + move => [] // mr _ [<-]; constructor. move => a ma ih [] // b mb mr' h /=; t_xrbindP => r ok_r mr rec <- {mr'}. constructor. + by apply: (h _ _ _ _ ok_r); left. by apply: ih => // a' b' r' h' ok_r'; apply: (h a' b' r' _ ok_r'); right. Qed. End MAP2. (* Inversion lemmas *) (* -------------------------------------------------------------- *) Lemma seq_eq_injL A (m n: seq A) (h: m = n) : match m with | [::] => if n is [::] then True else False | a :: m' => if n is b :: n' then a = b ∧ m' = n' else False end. Proof. by subst n; case: m. Qed. Lemma List_Forall_inv A (P: A → Prop) m : List.Forall P m → match m with [::] => True | x :: m' => P x ∧ List.Forall P m' end. Proof. by case. Qed. Lemma List_Forall2_refl A (R:A->A->Prop) l : (forall a, R a a) -> List.Forall2 R l l. Proof. by move=> HR;elim: l => // a l Hrec;constructor. Qed. Lemma List_Forall2_inv_l A B (R: A → B → Prop) m n : List.Forall2 R m n → match m with | [::] => n = [::] | a :: m' => ∃ b n', n = b :: n' ∧ R a b ∧ List.Forall2 R m' n' end. Proof. case; eauto. Qed. Lemma List_Forall2_inv_r A B (R: A → B → Prop) m n : List.Forall2 R m n → match n with | [::] => m = [::] | b :: n' => ∃ a m', m = a :: m' ∧ R a b ∧ List.Forall2 R m' n' end. Proof. case; eauto. Qed. Section All2. Variable A B:Type. Variable f : A -> B -> bool. Fixpoint all2 (l1:seq A) (l2: seq B) := match l1, l2 with | [::] , [::] => true | a1::l1, a2::l2 => f a1 a2 && all2 l1 l2 | _ , _ => false end. Lemma all2P l1 l2 : reflect (List.Forall2 f l1 l2) (all2 l1 l2). Proof. elim: l1 l2 => [ | a l1 hrec] [ | b l2] /=;try constructor. + by constructor. + by move/List_Forall2_inv_l. + by move/List_Forall2_inv_r. apply: equivP;first apply /andP. split => [[]h1 /hrec h2 |];first by constructor. by case/List_Forall2_inv_l => b' [n] [] [-> ->] [->] /hrec. Qed. End All2. Section Map2. Context (A B C : Type) (f : A -> B -> C). Fixpoint map2 la lb := match la, lb with | a::la, b::lb => f a b :: map2 la lb | _, _ => [::] end. Lemma map2E ma mb : map2 ma mb = map (λ ab, f ab.1 ab.2) (zip ma mb). Proof. elim: ma mb; first by case. by move => a ma ih [] // b mb /=; f_equal. Qed. End Map2. Section Map3. Context (A B C D : Type) (f : A -> B -> C -> D). Fixpoint map3 ma mb mc := match ma, mb, mc with | a :: ma', b :: mb', c :: mc' => f a b c :: map3 ma' mb' mc' | _, _, _ => [::] end. Lemma map3E ma mb mc : map3 ma mb mc = map2 (λ ab, f ab.1 ab.2) (zip ma mb) mc. Proof. elim: ma mb mc; first by case. by move => a ma ih [] // b mb [] // c mc /=; f_equal. Qed. End Map3. (* ** Misc functions * -------------------------------------------------------------------- *) Definition isSome aT (o : option aT) := if o is Some _ then true else false. Fixpoint list_to_rev (ub : nat) := match ub with | O => [::] | x.+1 => [:: x & list_to_rev x ] end. Definition list_to ub := rev (list_to_rev ub). Definition list_from_to (lb : nat) (ub : nat) := map (fun x => x + lb)%nat (list_to (ub - lb)). Definition conc_map aT bT (f : aT -> seq bT) (l : seq aT) := flatten (map f l). Definition oeq aT (f : aT -> aT -> Prop) (o1 o2 : option aT) := match o1, o2 with | Some x1, Some x2 => f x1 x2 | None, None => true | _ , _ => false end. Definition req eT aT (f : aT -> aT -> Prop) (o1 o2 : result eT aT) := match o1, o2 with | Ok x1, Ok x2 => f x1 x2 | Error _, Error _ => true | _ , _ => false end. Lemma Forall2_trans (A B C:Type) l2 (R1:A->B->Prop) (R2:B->C->Prop) l1 l3 (R3:A->C->Prop) : (forall b a c, R1 a b -> R2 b c -> R3 a c) -> List.Forall2 R1 l1 l2 -> List.Forall2 R2 l2 l3 -> List.Forall2 R3 l1 l3. Proof. move=> H hr1;elim: hr1 l3 => {l1 l2} [ | a b l1 l2 hr1 _ hrec] l3 /List_Forall2_inv_l. + by move => ->. by case => ? [?] [->] [??]; constructor; eauto. Qed. (* -------------------------------------------------------------------------- *) (* Operators to build comparison *) (* ---------------------------------------------------------------------------*) Section CTRANS. Definition ctrans c1 c2 := nosimpl ( match c1, c2 with | Eq, _ => Some c2 | _ , Eq => Some c1 | Lt, Lt => Some Lt | Gt, Gt => Some Gt | _ , _ => None end). Lemma ctransI c : ctrans c c = Some c. Proof. by case: c. Qed. Lemma ctransC c1 c2 : ctrans c1 c2 = ctrans c2 c1. Proof. by case: c1 c2 => -[]. Qed. Lemma ctrans_Eq c1 c2 : ctrans Eq c1 = Some c2 <-> c1 = c2. Proof. by rewrite /ctrans;case:c1=> //=;split=>[[]|->]. Qed. Lemma ctrans_Lt c1 c2 : ctrans Lt c1 = Some c2 -> Lt = c2. Proof. by rewrite /ctrans;case:c1=> //= -[] <-. Qed. Lemma ctrans_Gt c1 c2 : ctrans Gt c1 = Some c2 -> Gt = c2. Proof. by rewrite /ctrans;case:c1=> //= -[] <-. Qed. End CTRANS. Notation Lex u v := match u with | Lt => Lt | Eq => v | Gt => Gt end. (* -------------------------------------------------------------------- *) Scheme Equality for comparison. Lemma comparison_beqP : Equality.axiom comparison_beq. Proof. move=> e1 e2;case Heq: comparison_beq;constructor. + by apply: internal_comparison_dec_bl. by move=> /internal_comparison_dec_lb;rewrite Heq. Qed. Canonical comparison_eqMixin := EqMixin comparison_beqP. Canonical comparison_eqType := Eval hnf in EqType comparison comparison_eqMixin. (* -------------------------------------------------------------------- *) Class Cmp {T:Type} (cmp:T -> T -> comparison) := { cmp_sym : forall x y, cmp x y = CompOpp (cmp y x); cmp_ctrans : forall y x z c, ctrans (cmp x y) (cmp y z) = Some c -> cmp x z = c; cmp_eq : forall x y, cmp x y = Eq -> x = y; }. Definition gcmp {T:Type} {cmp:T -> T -> comparison} {C:Cmp cmp} := cmp. Section CMP. Context {T:Type} {cmp:T -> T -> comparison} {C:Cmp cmp}. Lemma cmp_trans y x z c: cmp x y = c -> cmp y z = c -> cmp x z = c. Proof. by move=> H1 H2;apply (@cmp_ctrans _ _ C y);rewrite H1 H2 ctransI. Qed. Lemma cmp_refl x : cmp x x = Eq. Proof. by have := @cmp_sym _ _ C x x;case: (cmp x x). Qed. Definition cmp_lt x1 x2 := gcmp x1 x2 == Lt. Definition cmp_le x1 x2 := gcmp x2 x1 != Lt. Lemma cmp_le_refl x : cmp_le x x. Proof. by rewrite /cmp_le /gcmp cmp_refl. Qed. Lemma cmp_lt_trans y x z : cmp_lt x y -> cmp_lt y z -> cmp_lt x z. Proof. rewrite /cmp_lt /gcmp => /eqP h1 /eqP h2;apply /eqP;apply (@cmp_ctrans _ _ C y). by rewrite h1 h2. Qed. Lemma cmp_le_trans y x z : cmp_le x y -> cmp_le y z -> cmp_le x z. Proof. rewrite /cmp_le /gcmp => h1 h2;have := (@cmp_ctrans _ _ C y z x). by case: cmp h1 => // _;case: cmp h2 => //= _;rewrite /ctrans => /(_ _ erefl) ->. Qed. Lemma cmp_nle_lt x y: ~~ (cmp_le x y) = cmp_lt y x. Proof. by rewrite /cmp_le /cmp_lt /gcmp Bool.negb_involutive. Qed. Lemma cmp_nlt_le x y: ~~ (cmp_lt x y) = cmp_le y x. Proof. done. Qed. Lemma cmp_lt_le_trans y x z: cmp_lt x y -> cmp_le y z -> cmp_lt x z. Proof. rewrite /cmp_le /cmp_lt /gcmp (cmp_sym z) => h1 h2. have := (@cmp_ctrans _ _ C y x z). by case: cmp h1 => // _;case: cmp h2 => //= _;rewrite /ctrans => /(_ _ erefl) ->. Qed. Lemma cmp_le_lt_trans y x z: cmp_le x y -> cmp_lt y z -> cmp_lt x z. Proof. rewrite /cmp_le /cmp_lt /gcmp (cmp_sym y) => h1 h2. have := (@cmp_ctrans _ _ C y x z). by case: cmp h1 => // _;case: cmp h2 => //= _;rewrite /ctrans => /(_ _ erefl) ->. Qed. Lemma cmp_lt_le x y : cmp_lt x y -> cmp_le x y. Proof. rewrite /cmp_lt /cmp_le /gcmp => /eqP h. by rewrite cmp_sym h. Qed. Lemma cmp_nle_le x y : ~~ (cmp_le x y) -> cmp_le y x. Proof. by rewrite cmp_nle_lt; apply: cmp_lt_le. Qed. End CMP. Notation "m < n" := (cmp_lt m n) : cmp_scope. Notation "m <= n" := (cmp_le m n) : cmp_scope. Notation "m ≤ n" := (cmp_le m n) : cmp_scope. Delimit Scope cmp_scope with CMP. Hint Resolve cmp_le_refl. Section EqCMP. Context {T:eqType} {cmp:T -> T -> comparison} {C:Cmp cmp}. Lemma cmp_le_eq_lt (s1 s2:T): cmp_le s1 s2 = cmp_lt s1 s2 || (s1 == s2). Proof. rewrite /cmp_le /cmp_lt cmp_sym /gcmp. case heq: cmp => //=. + by rewrite (cmp_eq heq) eqxx. case: eqP => // ?;subst. by rewrite cmp_refl in heq. Qed. Lemma cmp_le_antisym x y : cmp_le x y → cmp_le y x → x = y. Proof. by rewrite -cmp_nlt_le (cmp_le_eq_lt y) => /negbTE -> /eqP. Qed. End EqCMP. Section LEX. Variables (T1 T2:Type) (cmp1:T1 -> T1 -> comparison) (cmp2:T2 -> T2 -> comparison). Definition lex x y := Lex (cmp1 x.1 y.1) (cmp2 x.2 y.2). Lemma Lex_lex x1 x2 y1 y2 : Lex (cmp1 x1 y1) (cmp2 x2 y2) = lex (x1,x2) (y1,y2). Proof. done. Qed. Lemma lex_sym x y : cmp1 x.1 y.1 = CompOpp (cmp1 y.1 x.1) -> cmp2 x.2 y.2 = CompOpp (cmp2 y.2 x.2) -> lex x y = CompOpp (lex y x). Proof. by move=> H1 H2;rewrite /lex H1;case: cmp1=> //=;apply H2. Qed. Lemma lex_trans y x z: (forall c, ctrans (cmp1 x.1 y.1) (cmp1 y.1 z.1) = Some c -> cmp1 x.1 z.1 = c) -> (forall c, ctrans (cmp2 x.2 y.2) (cmp2 y.2 z.2) = Some c -> cmp2 x.2 z.2 = c) -> forall c, ctrans (lex x y) (lex y z) = Some c -> lex x z = c. Proof. rewrite /lex=> Hr1 Hr2 c;case: cmp1 Hr1. + move=> H;rewrite (H (cmp1 y.1 z.1));last by rewrite ctrans_Eq. (case: cmp1;first by apply Hr2); rewrite ctransC; [apply ctrans_Lt | apply ctrans_Gt]. + move=> H1 H2;rewrite (H1 Lt);move:H2;first by apply: ctrans_Lt. by case: cmp1. move=> H1 H2;rewrite (H1 Gt);move:H2;first by apply: ctrans_Gt. by case: cmp1. Qed. Lemma lex_eq x y : lex x y = Eq -> cmp1 x.1 y.1 = Eq /\ cmp2 x.2 y.2 = Eq. Proof. case: x y => [x1 x2] [y1 y2] /=. by rewrite /lex;case:cmp1 => //;case:cmp2. Qed. Instance LexO (C1:Cmp cmp1) (C2:Cmp cmp2) : Cmp lex. Proof. constructor=> [x y | y x z | x y]. + by apply /lex_sym;apply /cmp_sym. + by apply /lex_trans;apply /cmp_ctrans. by case: x y => ?? [??] /lex_eq /= [] /(@cmp_eq _ _ C1) -> /(@cmp_eq _ _ C2) ->. Qed. End LEX. Section MIN. Context T (cmp: T → T → comparison) (O: Cmp cmp). Definition cmp_min (x y: T) : T := if (x ≤ y)%CMP then x else y. Lemma cmp_minP x y (P: T → Prop) : ((x ≤ y)%CMP → P x) → ((y < x)%CMP → P y) → P (cmp_min x y). Proof. rewrite /cmp_min; case: ifP. - by move => _ /(_ erefl). by rewrite -cmp_nle_lt => -> _ /(_ erefl). Qed. Lemma cmp_min_leL x y : (cmp_min x y ≤ x)%CMP. Proof. apply: (@cmp_minP x y (λ z, z ≤ x)%CMP) => //. apply: cmp_lt_le. Qed. Lemma cmp_min_leR x y : (cmp_min x y ≤ y)%CMP. Proof. exact: (@cmp_minP x y (λ z, z ≤ y)%CMP). Qed. Lemma cmp_le_min x y : (x ≤ y)%CMP → cmp_min x y = x. Proof. by rewrite /cmp_min => ->. Qed. End MIN. Arguments cmp_min {T cmp O} x y. Definition bool_cmp b1 b2 := match b1, b2 with | false, true => Lt | false, false => Eq | true , true => Eq | true , false => Gt end. Instance boolO : Cmp bool_cmp. Proof. constructor=> [[] [] | [] [] [] c | [] []] //=; apply ctrans_Eq. Qed. Polymorphic Instance equiv_iffT: Equivalence iffT. Proof. split. + by move=> x;split;apply id. + by move=> x1 x2 []??;split. move=> x1 x2 x3 [??] [??];constructor;auto. Qed. Polymorphic Instance subrelation_iff_arrow : subrelation iffT arrow. Proof. by move=> ?? []. Qed. Polymorphic Instance subrelation_iff_flip_arrow : subrelation iffT (flip arrow). Proof. by move=> ?? []. Qed. Instance reflect_m: Proper (iff ==> (@eq bool) ==> iffT) reflect. Proof. by move=> P1 P2 Hiff b1 b2 ->; split=> H; apply (equivP H);rewrite Hiff. Qed. Coercion Zpos : positive >-> Z. Lemma P_leP (x y:positive) : reflect (x <= y)%Z (x <=? y)%positive. Proof. apply: (@equivP (Pos.le x y)) => //;rewrite -Pos.leb_le;apply idP. Qed. Lemma P_ltP (x y:positive) : reflect (x < y)%Z (x <? y)%positive. Proof. apply: (@equivP (Pos.lt x y)) => //;rewrite -Pos.ltb_lt;apply idP. Qed. Lemma Pos_leb_trans y x z: (x <=? y)%positive -> (y <=? z)%positive -> (x <=? z)%positive. Proof. move=> /P_leP ? /P_leP ?;apply /P_leP;omega. Qed. Lemma Pos_lt_leb_trans y x z: (x <? y)%positive -> (y <=? z)%positive -> (x <? z)%positive. Proof. move=> /P_ltP ? /P_leP ?;apply /P_ltP;omega. Qed. Lemma Pos_le_ltb_trans y x z: (x <=? y)%positive -> (y <? z)%positive -> (x <? z)%positive. Proof. move=> /P_leP ? /P_ltP ?;apply /P_ltP;omega. Qed. Lemma pos_eqP : Equality.axiom Pos.eqb. Proof. by move=> p1 p2;apply:(iffP idP);rewrite -Pos.eqb_eq. Qed. Definition pos_eqMixin := EqMixin pos_eqP. Canonical pos_eqType := EqType positive pos_eqMixin. Instance positiveO : Cmp Pos.compare. Proof. constructor. + by move=> ??;rewrite Pos.compare_antisym. + move=> ????;case:Pos.compare_spec=> [->|H1|H1]; case:Pos.compare_spec=> H2 //= -[] <- //;subst; rewrite ?Pos.compare_lt_iff ?Pos.compare_gt_iff //. + by apply: Pos.lt_trans H1 H2. by apply: Pos.lt_trans H2 H1. apply Pos.compare_eq. Qed. Lemma Z_eqP : Equality.axiom Z.eqb. Proof. by move=> p1 p2;apply:(iffP idP);rewrite -Z.eqb_eq. Qed. (*Definition Z_eqMixin := EqMixin Z_eqP. Canonical Z_eqType := EqType Z Z_eqMixin. *) Instance ZO : Cmp Z.compare. Proof. constructor. + by move=> ??;rewrite Z.compare_antisym. + move=> ????;case:Z.compare_spec=> [->|H1|H1]; case:Z.compare_spec=> H2 //= -[] <- //;subst; rewrite ?Z.compare_lt_iff ?Z.compare_gt_iff //. + by apply: Z.lt_trans H1 H2. by apply: Z.lt_trans H2 H1. apply Z.compare_eq. Qed. Lemma Z_to_nat_subn z1 z2 : 0 <= z1 -> 0 <= z2 -> z2 <= z1 -> Z.to_nat (z1 - z2) = (Z.to_nat z1 - Z.to_nat z2)%nat. Proof. case: z1 z2 => [|n1|n1] [|n2|n2] //=; try by rewrite /Z.le. + by move=> _ _ _; rewrite subn0. move=> _ _; rewrite -[_ <= _]/(n2 <= n1)%positive => le. have := Z.pos_sub_discr n1 n2; case: Z.pos_sub => /=. + by move=> ->; rewrite subnn. + move=> p ->; rewrite Pos2Nat.inj_add. by rewrite -[plus _ _]/(addn _ _) addnC addnK. + move=> p ->; apply/esym/eqP; rewrite subn_eq0. by rewrite Pos2Nat.inj_add leq_addr. Qed. Lemma Z_to_nat_le0 z : z <= 0 -> Z.to_nat z = 0%N. Proof. by rewrite /Z.to_nat; case: z => //=; rewrite /Z.le. Qed. (* ** Some Extra tactics * -------------------------------------------------------------------- *) Ltac sinversion H := inversion H=>{H};subst. (* -------------------------------------------------------------------- *) Variant dup_spec (P : Prop) := | Dup of P & P. Lemma dup (P : Prop) : P -> dup_spec P. Proof. by move=> ?; split. Qed. (* -------------------------------------------------------------------- *) Lemma drop_add {T : Type} (s : seq T) (n m : nat) : drop n (drop m s) = drop (n+m) s. Proof. elim: s n m => // x s ih [|n] [|m] //; by rewrite !(drop0, drop_cons, addn0, addnS). Qed. (* -------------------------------------------------------------------- *) Lemma inj_drop {T : Type} (s : seq T) (n m : nat) : (n <= size s)%nat -> (m <= size s)%nat -> drop n s = drop m s -> n = m. Proof. move => /leP hn /leP hm he; have := size_drop n s. rewrite he size_drop /subn /subn_rec; Psatz.lia. Qed. Definition ZleP : ∀ x y, reflect (x <= y) (x <=? y) := Z.leb_spec0. Definition ZltP : ∀ x y, reflect (x < y) (x <? y) := Z.ltb_spec0. Lemma eq_dec_refl (T: Type) (dec: ∀ x y : T, { x = y } + { x ≠ y }) (x: T) : dec x x = left erefl. Proof. case: (dec _ _) => // e; apply: f_equal. exact: Eqdep_dec.UIP_dec. Qed. (* ------------------------------------------------------------------------- *) Lemma rwR1 (A:Type) (P:A->Prop) (f:A -> bool) : (forall a, reflect (P a) (f a)) -> forall a, (f a) <-> (P a). Proof. by move=> h a; rewrite (rwP (h _)). Qed. Lemma rwR2 (A B:Type) (P:A->B->Prop) (f:A -> B -> bool) : (forall a b, reflect (P a b) (f a b)) -> forall a b, (f a b) <-> (P a b). Proof. by move=> h a b; rewrite (rwP (h _ _)). Qed. Notation pify := (rwR2 (@andP), rwR2 (@orP), rwR2 (@implyP), rwR1 (@forallP _), rwR1 (@negP)). Notation zify := (pify, (rwR2 (@ZleP), rwR2 (@ZltP))). (* -------------------------------------------------------------------- *) Definition ziota p (z:Z) := [seq p + Z.of_nat i | i <- iota 0 (Z.to_nat z)]. Lemma ziota0 p : ziota p 0 = [::]. Proof. done. Qed. Lemma ziota_neg p z: z <= 0 -> ziota p z = [::]. Proof. by case: z. Qed. Lemma ziotaS_cons p z: 0 <= z -> ziota p (Z.succ z) = p :: ziota (p+1) z. Proof. move=> hz;rewrite /ziota Z2Nat.inj_succ //= Z.add_0_r; f_equal. rewrite -addn1 addnC iota_addl -map_comp. by apply eq_map => i /=; rewrite Zpos_P_of_succ_nat;Psatz.lia. Qed. Lemma ziotaS_cat p z: 0 <= z -> ziota p (Z.succ z) = ziota p z ++ [:: p + z]. Proof. by move=> hz;rewrite /ziota Z2Nat.inj_succ // -addn1 iota_add map_cat /= add0n Z2Nat.id. Qed. Lemma in_ziota (p z i:Z) : (i \in ziota p z) = ((p <=? i) && (i <? p + z)). Proof. case: (ZleP 0 z) => hz. + move: p; pattern z; apply natlike_ind => [ p | {z hz} z hz hrec p| //]. + by rewrite ziota0 in_nil; case: andP => // -[/ZleP ? /ZltP ?]; Psatz.lia. rewrite ziotaS_cons // in_cons; case: eqP => [-> | ?] /=. + by rewrite Z.leb_refl /=; symmetry; apply /ZltP; Psatz.lia. by rewrite hrec; apply Bool.eq_iff_eq_true;split=> /andP [/ZleP ? /ZltP ?]; (apply /andP;split;[apply /ZleP| apply /ZltP]); Psatz.lia. rewrite ziota_neg;last Psatz.lia. rewrite in_nil;symmetry;apply /negP => /andP [/ZleP ? /ZltP ?]; Psatz.lia. Qed. Lemma size_ziota p z: size (ziota p z) = Z.to_nat z. Proof. by rewrite size_map size_iota. Qed. Lemma nth_ziota p (i:nat) z : leq (S i) (Z.to_nat z) -> nth 0%Z (ziota p z) i = (p + Z.of_nat i)%Z. Proof. by move=> hi;rewrite (nth_map O) ?size_iota // nth_iota. Qed. Lemma eq_map_ziota (T:Type) p1 p2 (f1 f2: Z -> T) : (forall i, (p1 <= i < p1 + p2)%Z -> f1 i = f2 i) -> map f1 (ziota p1 p2) = map f2 (ziota p1 p2). Proof. move=> hi; have {hi}: (forall i, i \in ziota p1 p2 -> f1 i = f2 i). + move=> ?; rewrite in_ziota !zify; apply hi. elim: ziota => //= i l hrec hf; rewrite hrec;first by rewrite hf ?mem_head. by move=> ? hin; apply hf;rewrite in_cons hin orbT. Qed. Lemma all_ziota p1 p2 (f1 f2: Z -> bool) : (forall i, (p1 <= i < p1 + p2)%Z -> f1 i = f2 i) -> all f1 (ziota p1 p2) = all f2 (ziota p1 p2). Proof. move=> hi; have {hi}: (forall i, i \in ziota p1 p2 -> f1 i = f2 i). + move=> ?; rewrite in_ziota !zify; apply hi. elim: ziota => //= i l hrec hf; rewrite hrec;first by rewrite hf ?mem_head. by move=> ? hin; apply hf;rewrite in_cons hin orbT. Qed. (* ------------------------------------------------------------------------- *) Lemma sumbool_of_boolET (b: bool) (h: b) : Sumbool.sumbool_of_bool b = left h. Proof. by move: h; rewrite /is_true => ?; subst. Qed. Lemma sumbool_of_boolEF (b: bool) (h: b = false) : Sumbool.sumbool_of_bool b = right h. Proof. by move: h; rewrite /is_true => ?; subst. Qed. (* ------------------------------------------------------------------------- *) Definition funname := positive. Definition get_fundef {T} (p: seq (funname * T)) (f: funname) := assoc p f. (* ------------------------------------------------------------------------- *) Definition lprod ts tr := foldr (fun t tr => t -> tr) tr ts. Fixpoint ltuple (ts:list Type) : Type := match ts with | [::] => unit | [::t1] => t1 | t1::ts => t1 * ltuple ts end. Notation "(:: x , .. , y & z )" := (pair x .. (pair y z) ..) (only parsing). Fixpoint merge_tuple (l1 l2: list Type) : ltuple l1 -> ltuple l2 -> ltuple (l1 ++ l2) := match l1 return ltuple l1 -> ltuple l2 -> ltuple (l1 ++ l2) with | [::] => fun _ p => p | t1 :: l1 => let rec := @merge_tuple l1 l2 in match l1 return (ltuple l1 -> ltuple l2 -> ltuple (l1 ++ l2)) -> ltuple (t1::l1) -> ltuple l2 -> ltuple (t1 :: l1 ++ l2) with | [::] => fun _ (x:t1) => match l2 return ltuple l2 -> ltuple (t1::l2) with | [::] => fun _ => x | t2::l2 => fun (p:ltuple (t2::l2)) => (x, p) end | t1' :: l1' => fun rec (x:t1 * ltuple (t1'::l1')) p => (x.1, rec x.2 p) end rec end.
theory nat_acc_alt_mul_same imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Nat = Z | S "Nat" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S n) y = S (plus n y)" fun mult :: "Nat => Nat => Nat" where "mult (Z) y = Z" | "mult (S n) y = plus y (mult n y)" fun accplus :: "Nat => Nat => Nat" where "accplus (Z) y = y" | "accplus (S z) y = accplus z (S y)" fun accaltmul :: "Nat => Nat => Nat" where "accaltmul (Z) y = Z" | "accaltmul (S z) (Z) = Z" | "accaltmul (S z) (S x2) = S (accplus z (accplus x2 (accaltmul z x2)))" (*hipster plus mult accplus accaltmul *) theorem x0 : "!! (x :: Nat) . !! (y :: Nat) . (accaltmul x y) = (mult x y)" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
\documentclass[color=usenames,dvipsnames]{beamer} %\documentclass[color=usenames,dvipsnames,handout]{beamer} %\usepackage[roman]{../../../pres1} \usepackage[sans]{../../../pres1} \usepackage{graphicx} \usepackage{bm} \usepackage{soul} \usepackage{color} \usepackage{Sweave} \usepackage{pdfpages} %\setbeameroption{notes on second screen} \DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl,formatcom=\color{red}} \DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom=\color{MidnightBlue}} \DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl} \newcommand{\bxt}{${\bm x}_j$} \newcommand{\bx}{{\bm x}} \newcommand{\bxj}{{\bm x}_j} \newcommand{\bst}{${\bm s}_i$} \newcommand{\bs}{{\bm s}} \newcommand{\bsi}{{\bm s}_i} \newcommand{\ed}{\|\bx - \bs\|} \newcommand{\cs}{\mathcal{S} } \begin{document} \begin{frame}[plain] \begin{center} \LARGE {\bf \color{RoyalBlue}{Spatial Jolly-Seber Model}} \par \vspace{0.8cm} % \color{Gray}{ % \Large {Spatial Capture-Recapture Workshop} \\ % \par % \large Athens, GA -- March 2015 \\ \large WILD 8300 -- Spatial Capture-Recapture \par \vspace{0.2cm} March 30, 2016 % \includegraphics[width=0.3\textwidth]{figs/scrbook} \\ % } \end{center} \end{frame} %\section{Intro} \begin{frame}[plain] \frametitle{Topics} \Large \only<1>{\tableofcontents}%[hideallsubsections]} % \only<2 | handout:0>{\tableofcontents[currentsection]}%,hideallsubsections]} \end{frame} \section{Intro} \begin{frame} \frametitle{Overview} \large {\bf Jolly-Seber model} \begin{itemize} \item Extends CJS model to allow for recruitment \item We no longer ``condition on first capture'' \item Typically, we use the robust design \end{itemize} \end{frame} \begin{frame} \frametitle{Stochastic population dynamics without dispersal} {\bf Initial Abundance} \[ N_1 \sim \mbox{Poisson}(\lambda) \] \vfill {\bf Survival} \[ S_t \sim \mbox{Binomial}(N_{t-1}, \phi) \] \vfill {\bf Recruitment} \[ R_t \sim \mbox{Poisson}(N_{t-1} \gamma) \] \vfill {\bf Abundance} \[ N_t = S_t + R_t \] \end{frame} %% \section{Non-spatial CJS} %% \begin{frame} %% \frametitle{Non-spatial CJS model} %% {\bf State model} %% \[ %% z_{i,t} \sim \mbox{Bernoulli}(z_{i,t-1} \times \phi) %% \] %% \vfill %% {\bf Observation model} %% \[ %% y_{i,t} \sim \mbox{Bernoulli}(z_{i,t} \times p) %% \] %% \pause %% \vfill %% \small %% where \\ %% \begin{itemize} %% \item $z_{i,t}$ is ``alive state'' of individual $i$ at time $t$ %% \item $\phi$ is ``apparent survival''. Probability of being alive and not permanently emigrating. %% \item $y_{i,t}=1$ if individual was encountered. $y_{i,t}=0$ otherwise. %% \end{itemize} %% \end{frame} \section{Spatial JS} \begin{frame} \frametitle{Spatial model} \large {\bf Extensions} \begin{itemize} \item Individuals heterogeneity in vital rates \item Spatial heterogeneity in vital rates \item Density dependence \item Dispersal \end{itemize} \end{frame} \begin{frame} \frametitle{Spatial Model using Data Augmentation} {\bf Initial State} \[ z_{i,1} \sim \mbox{Bernoulli}(\psi) \] \vfill {\bf Survival and Recruitment} \[ z_{i,t} \sim \mbox{Bernoulli}(z_{i,t-1}\phi + \mbox{recruitable}_{i,t-1}\gamma') \] \vfill {\bf Abundance} \[ N_t = \sum_{i=1}^M z_{i,t} \] \pause \vfill {\centering \bf Dispersal could be added using approaches discussed last week \par} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} \scriptsize % \tiny %\small {\bf Parameters and data dimensions} \begin{Schunk} \begin{Sinput} > T <- 10 # years/primary periods > K <- 3 # 3 secondary sampling occasion > N0 <- 25 # Abundance in year 1 > M <- 500 # Easiest way to simulate data is using data augmentation > phi <- 0.7 # Apparent survival > gamma <- 0.3 # Per-capital recruitment rate > p0 <- 0.4 > sigma <- 0.1 \end{Sinput} \end{Schunk} \pause {\bf Traps, activity centers, and detection probability} \begin{Schunk} \begin{Sinput} > set.seed(340) > co <- seq(0.25, 0.75, length=5) > X <- cbind(rep(co, each=5), rep(co, times=5)) > J <- nrow(X) > xlim <- ylim <- c(0,1) > s <- cbind(runif(M, xlim[1], xlim[2]), runif(M, ylim[1], ylim[2])) > d <- p <- matrix(NA, M, J) > for(i in 1:M) { + d[i,] <- sqrt((s[i,1]-X[,1])^2 + (s[i,2]-X[,2])^2) + p[i,] <- p0*exp(-d[i,]^2/(2*sigma^2)) + } \end{Sinput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} {\bf Generate $z$} \scriptsize \begin{Schunk} \begin{Sinput} > set.seed(034) > z <- recruitable <- died <- recruited <- matrix(0, M, T) > z[1:N0,1] <- 1 # First N0 are alive > recruitable[(N0+1):M,1] <- 1 > for(t in 2:T) { + prevN <- sum(z[,t-1]) # number alive at t-1 + ER <- prevN*gamma # expected number of recruits + prevA <- sum(recruitable[,t-1]) # Number available to be recruited + gammaPrime <- ER/prevA + if(gammaPrime > 1) + stop("M isn't big enough") + for(i in 1:M) { + z[i,t] <- rbinom(1, 1, z[i,t-1]*phi + recruitable[i,t-1]*gammaPrime) + recruitable[i,t] <- 1 - max(z[i,1:(t)]) # to be recruited + died[i,t] <- z[i,t-1]==1 & z[i,t]==0 + recruited[i,t] <- z[i,t]==1 & z[i,t-1]==0 + } + } \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Populaton size, mortalities, and recruits} \begin{Schunk} \begin{Sinput} > N <- colSums(z) # Population size > Deaths <- colSums(died) > Recruits <- colSums(recruited) > everAlive <- sum(rowSums(z)>0) \end{Sinput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} {\bf Generate encounter histories for all $M$ individuals} \footnotesize \begin{Schunk} \begin{Sinput} > yall <- array(NA, c(M, J, K, T)) > for(i in 1:M) { + for(t in 1:T) { + for(j in 1:J) { + yall[i,j,1:K,t] <- rbinom(K, 1, z[i,t]*p[i,j]) + } + } + } \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Discard individuals that were never captured} \begin{Schunk} \begin{Sinput} > detected <- rowSums(yall) > 0 > y <- yall[detected,,,] > str(y) \end{Sinput} \begin{Soutput} int [1:42, 1:25, 1:3, 1:10] 0 0 1 0 0 0 0 0 0 0 ... \end{Soutput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Time series} \tiny \vspace{-3mm} \begin{center} \includegraphics[width=0.8\textwidth]{Open-JS-NDR} \end{center} \end{frame} \begin{frame}[fragile] \frametitle{Spatial CJS model in \jags} \vspace{-5mm} \tiny \fbox{\parbox{\linewidth}{\verbatiminput{JS-spatial.jag}}} \end{frame} \begin{frame}[fragile] \frametitle{\jags} % \footnotesize {\bf Data augmentation} \scriptsize \begin{Schunk} \begin{Sinput} > M <- nrow(y) + 50 > yz <- array(0, c(M, J, K, T)) > yz[1:nrow(y),,,] <- y \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Initial values for $z$ matrix} \begin{Schunk} \begin{Sinput} > zi <- matrix(0, M, T) > zi[1:nrow(y),] <- 1 > ji1 <- function() list(phi=0.01, gamma=0.01, z=zi) \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Fit the model} \begin{Schunk} \begin{Sinput} > jd1 <- list(y = yz, M = M, X = X, J = J, K = K, T = T, xlim = xlim, + ylim = ylim) > jp1 <- c("phi", "gamma", "p0", "sigma", "N", "Deaths", "Recruits", + "Ntot") > library(rjags) > jm1 <- jags.model("JS-spatial.jag", jd1, ji1, n.chains = 1, n.adapt = 500) > jc1 <- coda.samples(jm1, jp1, 1000) \end{Sinput} \end{Schunk} \end{frame} \begin{frame} \frametitle{Is $M$ big enough?} \includegraphics{Open-JS-Ntot} \end{frame} \begin{frame}[fragile] \frametitle{Posterior distributions} \begin{center} \fbox{\includegraphics[width=0.7\textwidth]{Open-JS-jc1}} \end{center} \end{frame} \begin{frame}[fragile] \frametitle{Posterior distributions} \begin{center} \fbox{\includegraphics[width=0.45\textwidth]{Open-JS-jcN1-4}} \fbox{\includegraphics[width=0.45\textwidth]{Open-JS-jcN5-8}} \end{center} \end{frame} \section{Spatial JS with density-dependence} \begin{frame} \frametitle{Density-dependent recruitment} \large {\bf Logistic} \[ \gamma_t = \gamma_{max}(1 - N_{t-1}/K) \] \vfill {\bf Log-linear} \[ \gamma_t = \nu_0\exp(-\nu_1 N_{t-1}) \] \vfill {\bf Log-linear (alt version)} \[ \log(\gamma_t) = \nu_0 + \nu_1 N_{t-1} \] %<<>>= %gompertz <- function(N, a, b, c) { % x <- numeric(length(N)) % for(i in N) { % x[i] <- a*exp(-b*exp(-c*i)) % } % return(x) %} %gompertz(1:10, a=1, b=1, c=1) %##plot(gompertz(1:10, a=2, b=1, c=.11)) %@ \end{frame} \begin{frame}[fragile] \frametitle{Density-dependent recruitment} \tiny \vspace{-4mm} \begin{center} \includegraphics[width=\textwidth]{Open-JS-dd1} \end{center} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} \scriptsize % \tiny %\small {\bf Parameters and data dimensions} \begin{Schunk} \begin{Sinput} > T <- 10 # years/primary periods > K <- 3 # 3 secondary sampling occasion > ## Is it necessary to be far from equilibrium to detect density-dependence? > ## Equilibrium here is where (1-phi) == gamma, where gamma is function of N > N0 <- 10 # Abundance in year 1 > M <- 500 # Easiest way to simulate data is using data augmentation > phi <- 0.7 # Apparent survival > ##gamma <- 0.3 # Per-capital recruitment rate > nu0 <- 2 > nu1 <- 0.05 > p0 <- 0.4 > sigma <- 0.1 \end{Sinput} \end{Schunk} \pause {\bf Traps, activity centers, and detection probability} \begin{Schunk} \begin{Sinput} > set.seed(3479) > co <- seq(0.25, 0.75, length=5) > X <- cbind(rep(co, each=5), rep(co, times=5)) > J <- nrow(X) > xlim <- ylim <- c(0,1) > s <- cbind(runif(M, xlim[1], xlim[2]), runif(M, ylim[1], ylim[2])) > d <- p <- matrix(NA, M, J) > for(i in 1:M) { + d[i,] <- sqrt((s[i,1]-X[,1])^2 + (s[i,2]-X[,2])^2) + p[i,] <- p0*exp(-d[i,]^2/(2*sigma^2)) + } \end{Sinput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} {\bf Generate $z$} \scriptsize \begin{Schunk} \begin{Sinput} > set.seed(3401) > z2 <- recruitable <- died <- recruited <- matrix(0, M, T) > z2[1:N0,1] <- 1 # First N0 are alive > recruitable[(N0+1):M,1] <- 1 > for(t in 2:T) { + prevN <- sum(z2[,t-1]) # number alive at t-1 + gamma <- nu0*exp(-nu1*prevN) ## Density dependent recruitment rate + ER <- prevN*gamma # expected number of recruits + prevA <- sum(recruitable[,t-1]) # Number available to be recruited + gammaPrime <- ER/prevA + if(gammaPrime > 1) + stop("M isn't big enough") + for(i in 1:M) { + z2[i,t] <- rbinom(1, 1, z2[i,t-1]*phi + recruitable[i,t-1]*gammaPrime) + recruitable[i,t] <- 1 - max(z2[i,1:(t)]) # to be recruited + died[i,t] <- z2[i,t-1]==1 & z2[i,t]==0 + recruited[i,t] <- z2[i,t]==1 & z2[i,t-1]==0 + } + } \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Populaton size, mortalities, and recruits} \begin{Schunk} \begin{Sinput} > N2 <- colSums(z2) # Population size > Deaths2 <- colSums(died) > Recruits2 <- colSums(recruited) > everAlive2 <- sum(rowSums(z2)>0) \end{Sinput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Simulating spatial JS data with robust design} {\bf Generate encounter histories for all $M$ individuals} \footnotesize \begin{Schunk} \begin{Sinput} > yall <- array(NA, c(M, J, K, T)) > for(i in 1:M) { + for(t in 1:T) { + for(j in 1:J) { + yall[i,j,1:K,t] <- rbinom(K, 1, z2[i,t]*p[i,j]) + } + } + } \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Discard individuals that were never captured} \begin{Schunk} \begin{Sinput} > detected <- rowSums(yall) > 0 > y2 <- yall[detected,,,] > str(y2) \end{Sinput} \begin{Soutput} int [1:85, 1:25, 1:3, 1:10] 0 0 0 0 0 0 0 0 0 0 ... \end{Soutput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Time series} \tiny \vspace{-3mm} \begin{center} \includegraphics[width=\textwidth]{Open-JS-NDR-DD} \end{center} \end{frame} \begin{frame}[fragile] \frametitle{Spatial CJS model in \jags} \vspace{-5mm} \tiny \fbox{\parbox{\linewidth}{\verbatiminput{JS-spatial-DD.jag}}} \end{frame} \begin{frame}[fragile] \frametitle{\jags} % \footnotesize {\bf Data augmentation} \scriptsize \begin{Schunk} \begin{Sinput} > M2 <- nrow(y2) + 75 > yz2 <- array(0, c(M2, J, K, T)) > yz2[1:nrow(y2),,,] <- y2 \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Initial values for $z$ matrix} \begin{Schunk} \begin{Sinput} > zi <- matrix(0, M2, T) > ##zi[1:nrow(y2),] <- 1 > zi[1:nrow(y2),] <- z2[detected,] ## cheating > ji2 <- function() list(phi=0.01, z=zi) \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Fit the model} \begin{Schunk} \begin{Sinput} > jd2 <- list(y = yz2, M = M2, X = X, J = J, K = K, T = T, xlim = xlim, + ylim = ylim) > jp2 <- c("phi", "nu0", "nu1", "p0", "sigma", "N", "Deaths", "Recruits", + "Ntot") > library(rjags) > jm2 <- jags.model("JS-spatial-DD.jag", jd2, ji2, n.chains = 1, + n.adapt = 200) > jc2 <- coda.samples(jm2, jp2, 5000) \end{Sinput} \end{Schunk} \end{frame} \begin{frame}[fragile] \frametitle{Posterior distributions} \begin{center} \fbox{\includegraphics[width=0.7\textwidth]{Open-JS-jc1}} \end{center} \end{frame} \begin{frame}[fragile] \frametitle{Actual and estimated abundance} {\bf Extract and summarize posterior samples of $N_t$} \footnotesize \begin{Schunk} \begin{Sinput} > Npost <- as.matrix(jc2[,paste("N[", 1:10, "]", sep="")]) > Nmed <- apply(Npost, 2, median) > Nupper <- apply(Npost, 2, quantile, prob=0.975) > Nlower <- apply(Npost, 2, quantile, prob=0.025) \end{Sinput} \end{Schunk} \pause \vfill {\bf \normalsize Plot} \begin{Schunk} \begin{Sinput} > plot(1:T, N2, type="o", col="blue", ylim=c(0, 100), xlab="Time", + ylab="Abundance") > points(1:T, Nmed) > arrows(1:T, Nlower, 1:T, Nupper, angle=90, code=3, length=0.05) > legend(1, 100, c("Actual abundance", "Estimated abundance"), + col=c("blue", "black"), lty=c(1,1), pch=c(1,1)) \end{Sinput} \end{Schunk} \end{frame} \begin{frame} \frametitle{Actual and estimated abundance} \vspace{-4mm} \begin{center} \includegraphics[width=0.8\textwidth]{Open-JS-Npost} \end{center} \end{frame} \begin{frame} \frametitle{Summary} \large {\bf Key points} \begin{itemize}[<+->] \item Spatial Jolly-Seber models make it possible to fit spatio-temporal models of population dynamics to standard data \item We could have movement just like we did with CJS models \end{itemize} \end{frame} \begin{frame} \frametitle{Assignment} {\bf \large For next week} \begin{enumerate}[\bf (1)] \item Work on analysis of your own data and your final paper, which should include: \begin{itemize} \item Introduction \item Methods (including model description) \item Results \item Discussion \end{itemize} \item Paper should be a minimum of 4 pages, single-spaced, 12-pt font \end{enumerate} \end{frame} \end{document}
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.int.basic import Mathlib.Lean3Lib.init.data.ordering.basic namespace Mathlib namespace int def nonneg (a : ℤ) := int.cases_on a (fun (n : ℕ) => True) fun (n : ℕ) => False protected def le (a : ℤ) (b : ℤ) := nonneg (b - a) protected instance has_le : HasLessEq ℤ := { LessEq := int.le } protected def lt (a : ℤ) (b : ℤ) := a + 1 ≤ b protected instance has_lt : HasLess ℤ := { Less := int.lt } def decidable_nonneg (a : ℤ) : Decidable (nonneg a) := int.cases_on a (fun (a : ℕ) => decidable.true) fun (a : ℕ) => decidable.false protected instance decidable_le (a : ℤ) (b : ℤ) : Decidable (a ≤ b) := decidable_nonneg (b - a) protected instance decidable_lt (a : ℤ) (b : ℤ) : Decidable (a < b) := decidable_nonneg (b - (a + 1)) theorem lt_iff_add_one_le (a : ℤ) (b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl (a < b) theorem nonneg.elim {a : ℤ} : nonneg a → ∃ (n : ℕ), a = ↑n := int.cases_on a (fun (n : ℕ) (H : nonneg (Int.ofNat n)) => exists.intro n rfl) fun (n' : ℕ) => false.elim theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (fun (n : ℕ) => Or.inl trivial) fun (n : ℕ) => Or.inr trivial theorem le.intro_sub {a : ℤ} {b : ℤ} {n : ℕ} (h : b - a = ↑n) : a ≤ b := (fun (this : nonneg (b - a)) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (nonneg (b - a))) h)) trivial) theorem le.intro {a : ℤ} {b : ℤ} {n : ℕ} (h : a + ↑n = b) : a ≤ b := sorry theorem le.dest_sub {a : ℤ} {b : ℤ} (h : a ≤ b) : ∃ (n : ℕ), b - a = ↑n := nonneg.elim h theorem le.dest {a : ℤ} {b : ℤ} (h : a ≤ b) : ∃ (n : ℕ), a + ↑n = b := sorry theorem le.elim {a : ℤ} {b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ (n : ℕ), a + ↑n = b → P) : P := exists.elim (le.dest h) h' protected theorem le_total (a : ℤ) (b : ℤ) : a ≤ b ∨ b ≤ a := sorry theorem coe_nat_le_coe_nat_of_le {m : ℕ} {n : ℕ} (h : m ≤ n) : ↑m ≤ ↑n := sorry theorem le_of_coe_nat_le_coe_nat {m : ℕ} {n : ℕ} (h : ↑m ≤ ↑n) : m ≤ n := le.elim h fun (k : ℕ) (hk : ↑m + ↑k = ↑n) => (fun (this : m + k = n) => nat.le.intro this) (int.coe_nat_inj (Eq.trans (int.coe_nat_add m k) hk)) theorem coe_nat_le_coe_nat_iff (m : ℕ) (n : ℕ) : ↑m ≤ ↑n ↔ m ≤ n := { mp := le_of_coe_nat_le_coe_nat, mpr := coe_nat_le_coe_nat_of_le } theorem coe_zero_le (n : ℕ) : 0 ≤ ↑n := coe_nat_le_coe_nat_of_le (nat.zero_le n) theorem eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ (n : ℕ), a = ↑n := sorry theorem eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ (n : ℕ), a = ↑(Nat.succ n) := sorry theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(Nat.succ n) := sorry theorem lt.intro {a : ℤ} {b : ℤ} {n : ℕ} (h : a + ↑(Nat.succ n) = b) : a < b := h ▸ lt_add_succ a n theorem lt.dest {a : ℤ} {b : ℤ} (h : a < b) : ∃ (n : ℕ), a + ↑(Nat.succ n) = b := sorry theorem lt.elim {a : ℤ} {b : ℤ} (h : a < b) {P : Prop} (h' : ∀ (n : ℕ), a + ↑(Nat.succ n) = b → P) : P := exists.elim (lt.dest h) h' theorem coe_nat_lt_coe_nat_iff (n : ℕ) (m : ℕ) : ↑n < ↑m ↔ n < m := sorry theorem lt_of_coe_nat_lt_coe_nat {m : ℕ} {n : ℕ} (h : ↑m < ↑n) : m < n := iff.mp (coe_nat_lt_coe_nat_iff m n) h theorem coe_nat_lt_coe_nat_of_lt {m : ℕ} {n : ℕ} (h : m < n) : ↑m < ↑n := iff.mpr (coe_nat_lt_coe_nat_iff m n) h /- show that the integers form an ordered additive group -/ protected theorem le_refl (a : ℤ) : a ≤ a := le.intro (int.add_zero a) protected theorem le_trans {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := sorry protected theorem le_antisymm {a : ℤ} {b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := sorry protected theorem lt_irrefl (a : ℤ) : ¬a < a := sorry protected theorem ne_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a ≠ b := fun (this : a = b) => absurd (eq.mp (Eq._oldrec (Eq.refl (a < b)) this) h) (int.lt_irrefl b) theorem le_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a ≤ b := lt.elim h fun (n : ℕ) (hn : a + ↑(Nat.succ n) = b) => le.intro hn protected theorem lt_iff_le_and_ne (a : ℤ) (b : ℤ) : a < b ↔ a ≤ b ∧ a ≠ b := sorry theorem lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected theorem add_le_add_left {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b := sorry protected theorem add_lt_add_left {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b := sorry protected theorem mul_nonneg {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := sorry protected theorem mul_pos {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := sorry protected theorem zero_lt_one : 0 < 1 := trivial protected theorem lt_iff_le_not_le {a : ℤ} {b : ℤ} : a < b ↔ a ≤ b ∧ ¬b ≤ a := sorry protected instance linear_order : linear_order ℤ := linear_order.mk int.le int.lt int.le_refl int.le_trans int.le_antisymm int.le_total int.decidable_le int.decidable_eq int.decidable_lt theorem eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = ↑(nat_abs a) := sorry theorem le_nat_abs {a : ℤ} : a ≤ ↑(nat_abs a) := sorry theorem neg_succ_lt_zero (n : ℕ) : Int.negSucc n < 0 := sorry theorem eq_neg_succ_of_lt_zero {a : ℤ} : a < 0 → ∃ (n : ℕ), a = Int.negSucc n := sorry /- int is an ordered add comm group -/ protected theorem eq_neg_of_eq_neg {a : ℤ} {b : ℤ} (h : a = -b) : b = -a := eq.mpr (id (Eq._oldrec (Eq.refl (b = -a)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (b = --b)) (int.neg_neg b))) (Eq.refl b)) protected theorem neg_add_cancel_left (a : ℤ) (b : ℤ) : -a + (a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (-a + (a + b) = b)) (Eq.symm (int.add_assoc (-a) a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (-a + a + b = b)) (int.add_left_neg a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (int.zero_add b))) (Eq.refl b))) protected theorem add_neg_cancel_left (a : ℤ) (b : ℤ) : a + (-a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a + (-a + b) = b)) (Eq.symm (int.add_assoc a (-a) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a + b = b)) (int.add_right_neg a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (int.zero_add b))) (Eq.refl b))) protected theorem add_neg_cancel_right (a : ℤ) (b : ℤ) : a + b + -b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + b + -b = a)) (int.add_assoc a b (-b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + (b + -b) = a)) (int.add_right_neg b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a))) protected theorem neg_add_cancel_right (a : ℤ) (b : ℤ) : a + -b + b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + -b + b = a)) (int.add_assoc a (-b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + (-b + b) = a)) (int.add_left_neg b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a))) protected theorem sub_self (a : ℤ) : a - a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a - a = 0)) int.sub_eq_add_neg)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (int.add_right_neg a))) (Eq.refl 0)) protected theorem sub_eq_zero_of_eq {a : ℤ} {b : ℤ} (h : a = b) : a - b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a - b = 0)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (b - b = 0)) (int.sub_self b))) (Eq.refl 0)) protected theorem eq_of_sub_eq_zero {a : ℤ} {b : ℤ} (h : a - b = 0) : a = b := sorry protected theorem sub_eq_zero_iff_eq {a : ℤ} {b : ℤ} : a - b = 0 ↔ a = b := { mp := int.eq_of_sub_eq_zero, mpr := int.sub_eq_zero_of_eq } @[simp] protected theorem neg_eq_of_add_eq_zero {a : ℤ} {b : ℤ} (h : a + b = 0) : -a = b := sorry protected theorem neg_mul_eq_neg_mul (a : ℤ) (b : ℤ) : -(a * b) = -a * b := sorry protected theorem neg_mul_eq_mul_neg (a : ℤ) (b : ℤ) : -(a * b) = a * -b := sorry @[simp] theorem neg_mul_eq_neg_mul_symm (a : ℤ) (b : ℤ) : -a * b = -(a * b) := Eq.symm (int.neg_mul_eq_neg_mul a b) @[simp] theorem mul_neg_eq_neg_mul_symm (a : ℤ) (b : ℤ) : a * -b = -(a * b) := Eq.symm (int.neg_mul_eq_mul_neg a b) protected theorem neg_mul_neg (a : ℤ) (b : ℤ) : -a * -b = a * b := sorry protected theorem neg_mul_comm (a : ℤ) (b : ℤ) : -a * b = a * -b := sorry protected theorem mul_sub (a : ℤ) (b : ℤ) (c : ℤ) : a * (b - c) = a * b - a * c := sorry protected theorem sub_mul (a : ℤ) (b : ℤ) (c : ℤ) : (a - b) * c = a * c - b * c := sorry protected theorem le_of_add_le_add_left {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ a + c) : b ≤ c := sorry protected theorem lt_of_add_lt_add_left {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < a + c) : b < c := sorry protected theorem add_le_add_right {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : a + c ≤ b + c := int.add_comm c a ▸ int.add_comm c b ▸ int.add_le_add_left h c protected theorem add_lt_add_right {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : a + c < b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a + c < b + c)) (int.add_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (c + a < b + c)) (int.add_comm b c))) (int.add_lt_add_left h c)) protected theorem add_le_add {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (int.add_le_add_right h₁ c) (int.add_le_add_left h₂ b) protected theorem le_add_of_nonneg_right {a : ℤ} {b : ℤ} (h : b ≥ 0) : a ≤ a + b := (fun (this : a + b ≥ a + 0) => eq.mp (Eq._oldrec (Eq.refl (a + b ≥ a + 0)) (int.add_zero a)) this) (int.add_le_add_left h a) protected theorem le_add_of_nonneg_left {a : ℤ} {b : ℤ} (h : b ≥ 0) : a ≤ b + a := (fun (this : 0 + a ≤ b + a) => eq.mp (Eq._oldrec (Eq.refl (0 + a ≤ b + a)) (int.zero_add a)) this) (int.add_le_add_right h a) protected theorem add_lt_add {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (int.add_lt_add_right h₁ c) (int.add_lt_add_left h₂ b) protected theorem add_lt_add_of_le_of_lt {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (int.add_le_add_right h₁ c) (int.add_lt_add_left h₂ b) protected theorem add_lt_add_of_lt_of_le {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (int.add_lt_add_right h₁ c) (int.add_le_add_left h₂ b) protected theorem lt_add_of_pos_right (a : ℤ) {b : ℤ} (h : b > 0) : a < a + b := (fun (this : a + 0 < a + b) => eq.mp (Eq._oldrec (Eq.refl (a + 0 < a + b)) (int.add_zero a)) this) (int.add_lt_add_left h a) protected theorem lt_add_of_pos_left (a : ℤ) {b : ℤ} (h : b > 0) : a < b + a := (fun (this : 0 + a < b + a) => eq.mp (Eq._oldrec (Eq.refl (0 + a < b + a)) (int.zero_add a)) this) (int.add_lt_add_right h a) protected theorem le_of_add_le_add_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c + b) : a ≤ c := sorry protected theorem lt_of_add_lt_add_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c + b) : a < c := sorry -- here we start using properties of zero. protected theorem add_nonneg {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := int.zero_add 0 ▸ int.add_le_add ha hb protected theorem add_pos {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add ha hb protected theorem add_pos_of_pos_of_nonneg {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add_of_lt_of_le ha hb protected theorem add_pos_of_nonneg_of_pos {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add_of_le_of_lt ha hb protected theorem add_nonpos {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := int.zero_add 0 ▸ int.add_le_add ha hb protected theorem add_neg {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b < 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add ha hb protected theorem add_neg_of_neg_of_nonpos {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add_of_lt_of_le ha hb protected theorem add_neg_of_nonpos_of_neg {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add_of_le_of_lt ha hb protected theorem lt_add_of_le_of_pos {a : ℤ} {b : ℤ} {c : ℤ} (hbc : b ≤ c) (ha : 0 < a) : b < c + a := int.add_zero b ▸ int.add_lt_add_of_le_of_lt hbc ha protected theorem sub_add_cancel (a : ℤ) (b : ℤ) : a - b + b = a := int.neg_add_cancel_right a b protected theorem add_sub_cancel (a : ℤ) (b : ℤ) : a + b - b = a := int.add_neg_cancel_right a b protected theorem add_sub_assoc (a : ℤ) (b : ℤ) (c : ℤ) : a + b - c = a + (b - c) := sorry protected theorem neg_le_neg {a : ℤ} {b : ℤ} (h : a ≤ b) : -b ≤ -a := sorry protected theorem le_of_neg_le_neg {a : ℤ} {b : ℤ} (h : -b ≤ -a) : a ≤ b := sorry protected theorem nonneg_of_neg_nonpos {a : ℤ} (h : -a ≤ 0) : 0 ≤ a := (fun (this : -a ≤ -0) => int.le_of_neg_le_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ -0)) int.neg_zero)) h) protected theorem neg_nonpos_of_nonneg {a : ℤ} (h : 0 ≤ a) : -a ≤ 0 := (fun (this : -a ≤ -0) => eq.mp (Eq._oldrec (Eq.refl (-a ≤ -0)) int.neg_zero) this) (int.neg_le_neg h) protected theorem nonpos_of_neg_nonneg {a : ℤ} (h : 0 ≤ -a) : a ≤ 0 := (fun (this : -0 ≤ -a) => int.le_of_neg_le_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-0 ≤ -a)) int.neg_zero)) h) protected theorem neg_nonneg_of_nonpos {a : ℤ} (h : a ≤ 0) : 0 ≤ -a := (fun (this : -0 ≤ -a) => eq.mp (Eq._oldrec (Eq.refl (-0 ≤ -a)) int.neg_zero) this) (int.neg_le_neg h) protected theorem neg_lt_neg {a : ℤ} {b : ℤ} (h : a < b) : -b < -a := sorry protected theorem lt_of_neg_lt_neg {a : ℤ} {b : ℤ} (h : -b < -a) : a < b := int.neg_neg a ▸ int.neg_neg b ▸ int.neg_lt_neg h protected theorem pos_of_neg_neg {a : ℤ} (h : -a < 0) : 0 < a := (fun (this : -a < -0) => int.lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a < -0)) int.neg_zero)) h) protected theorem neg_neg_of_pos {a : ℤ} (h : 0 < a) : -a < 0 := (fun (this : -a < -0) => eq.mp (Eq._oldrec (Eq.refl (-a < -0)) int.neg_zero) this) (int.neg_lt_neg h) protected theorem neg_of_neg_pos {a : ℤ} (h : 0 < -a) : a < 0 := (fun (this : -0 < -a) => int.lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-0 < -a)) int.neg_zero)) h) protected theorem neg_pos_of_neg {a : ℤ} (h : a < 0) : 0 < -a := (fun (this : -0 < -a) => eq.mp (Eq._oldrec (Eq.refl (-0 < -a)) int.neg_zero) this) (int.neg_lt_neg h) protected theorem le_neg_of_le_neg {a : ℤ} {b : ℤ} (h : a ≤ -b) : b ≤ -a := eq.mp (Eq._oldrec (Eq.refl ( --b ≤ -a)) (int.neg_neg b)) (int.neg_le_neg h) protected theorem neg_le_of_neg_le {a : ℤ} {b : ℤ} (h : -a ≤ b) : -b ≤ a := eq.mp (Eq._oldrec (Eq.refl (-b ≤ --a)) (int.neg_neg a)) (int.neg_le_neg h) protected theorem lt_neg_of_lt_neg {a : ℤ} {b : ℤ} (h : a < -b) : b < -a := eq.mp (Eq._oldrec (Eq.refl ( --b < -a)) (int.neg_neg b)) (int.neg_lt_neg h) protected theorem neg_lt_of_neg_lt {a : ℤ} {b : ℤ} (h : -a < b) : -b < a := eq.mp (Eq._oldrec (Eq.refl (-b < --a)) (int.neg_neg a)) (int.neg_lt_neg h) protected theorem sub_nonneg_of_le {a : ℤ} {b : ℤ} (h : b ≤ a) : 0 ≤ a - b := eq.mp (Eq._oldrec (Eq.refl (b + -b ≤ a + -b)) (int.add_right_neg b)) (int.add_le_add_right h (-b)) protected theorem le_of_sub_nonneg {a : ℤ} {b : ℤ} (h : 0 ≤ a - b) : b ≤ a := eq.mp (Eq._oldrec (Eq.refl (0 + b ≤ a)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (0 + b ≤ a - b + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_nonpos_of_le {a : ℤ} {b : ℤ} (h : a ≤ b) : a - b ≤ 0 := eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ b + -b)) (int.add_right_neg b)) (int.add_le_add_right h (-b)) protected theorem le_of_sub_nonpos {a : ℤ} {b : ℤ} (h : a - b ≤ 0) : a ≤ b := eq.mp (Eq._oldrec (Eq.refl (a ≤ 0 + b)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b ≤ 0 + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_pos_of_lt {a : ℤ} {b : ℤ} (h : b < a) : 0 < a - b := eq.mp (Eq._oldrec (Eq.refl (b + -b < a + -b)) (int.add_right_neg b)) (int.add_lt_add_right h (-b)) protected theorem lt_of_sub_pos {a : ℤ} {b : ℤ} (h : 0 < a - b) : b < a := eq.mp (Eq._oldrec (Eq.refl (0 + b < a)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (0 + b < a - b + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem sub_neg_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a - b < 0 := eq.mp (Eq._oldrec (Eq.refl (a + -b < b + -b)) (int.add_right_neg b)) (int.add_lt_add_right h (-b)) protected theorem lt_of_sub_neg {a : ℤ} {b : ℤ} (h : a - b < 0) : a < b := eq.mp (Eq._oldrec (Eq.refl (a < 0 + b)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b < 0 + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem add_le_of_le_neg_add {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ -a + c) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (-a + c))) (int.add_neg_cancel_left a c)) (int.add_le_add_left h a) protected theorem le_neg_add_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : b ≤ -a + c := eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) ≤ -a + c)) (int.neg_add_cancel_left a b)) (int.add_le_add_left h (-a)) protected theorem add_le_of_le_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ c - a) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ c + a - a)) (int.add_sub_cancel c a)) (eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + c - a)) (int.add_comm a c)) (eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (c - a))) (Eq.symm (int.add_sub_assoc a c a))) (int.add_le_add_left h a))) protected theorem le_sub_left_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : b ≤ c - a := eq.mp (Eq._oldrec (Eq.refl (b + a + -a ≤ c + -a)) (int.add_neg_cancel_right b a)) (eq.mp (Eq._oldrec (Eq.refl (a + b + -a ≤ c + -a)) (int.add_comm a b)) (int.add_le_add_right h (-a))) protected theorem add_le_of_le_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ c - b) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ c - b + b)) (int.sub_add_cancel c b)) (int.add_le_add_right h b) protected theorem le_sub_right_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : a ≤ c - b := eq.mp (Eq._oldrec (Eq.refl (a + b + -b ≤ c + -b)) (int.add_neg_cancel_right a b)) (int.add_le_add_right h (-b)) protected theorem le_add_of_neg_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a ≤ c) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (b + (-b + a) ≤ b + c)) (int.add_neg_cancel_left b a)) (int.add_le_add_left h b) protected theorem neg_add_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -b + a ≤ c := eq.mp (Eq._oldrec (Eq.refl (-b + a ≤ -b + (b + c))) (int.neg_add_cancel_left b c)) (int.add_le_add_left h (-b)) protected theorem le_add_of_sub_left_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b ≤ c) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (a ≤ c + b)) (int.add_comm c b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b ≤ c + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_left_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : a - b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ c + b + -b)) (int.add_neg_cancel_right c b)) (eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ b + c + -b)) (int.add_comm b c)) (int.add_le_add_right h (-b))) protected theorem le_add_of_sub_right_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - c ≤ b) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (a - c + c ≤ b + c)) (int.sub_add_cancel a c)) (int.add_le_add_right h c) protected theorem sub_right_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : a - c ≤ b := eq.mp (Eq._oldrec (Eq.refl (a + -c ≤ b + c + -c)) (int.add_neg_cancel_right b c)) (int.add_le_add_right h (-c)) protected theorem le_add_of_neg_add_le_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a ≤ c) : a ≤ b + c := int.le_add_of_sub_left_le (eq.mp (Eq._oldrec (Eq.refl (-b + a ≤ c)) (int.add_comm (-b) a)) h) protected theorem neg_add_le_left_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -b + a ≤ c := eq.mpr (id (Eq._oldrec (Eq.refl (-b + a ≤ c)) (int.add_comm (-b) a))) (int.sub_left_le_of_le_add h) protected theorem le_add_of_neg_add_le_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -c + a ≤ b) : a ≤ b + c := int.le_add_of_sub_right_le (eq.mp (Eq._oldrec (Eq.refl (-c + a ≤ b)) (int.add_comm (-c) a)) h) protected theorem neg_add_le_right_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -c + a ≤ b := int.neg_add_le_left_of_le_add (eq.mp (Eq._oldrec (Eq.refl (a ≤ b + c)) (int.add_comm b c)) h) protected theorem le_add_of_neg_le_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -a ≤ b - c) : c ≤ a + b := int.le_add_of_neg_add_le_left (int.add_le_of_le_sub_right h) protected theorem neg_le_sub_left_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c ≤ a + b) : -a ≤ b - c := eq.mp (Eq._oldrec (Eq.refl (-a ≤ -c + b)) (int.add_comm (-c) b)) (int.le_neg_add_of_add_le (int.sub_left_le_of_le_add h)) protected theorem le_add_of_neg_le_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -b ≤ a - c) : c ≤ a + b := int.le_add_of_sub_right_le (int.add_le_of_le_sub_left h) protected theorem neg_le_sub_right_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c ≤ a + b) : -b ≤ a - c := int.le_sub_left_of_add_le (int.sub_right_le_of_le_add h) protected theorem sub_le_of_sub_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b ≤ c) : a - c ≤ b := int.sub_left_le_of_le_add (int.le_add_of_sub_right_le h) protected theorem sub_le_sub_left {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : c - b ≤ c - a := int.add_le_add_left (int.neg_le_neg h) c protected theorem sub_le_sub_right {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : a - c ≤ b - c := int.add_le_add_right h (-c) protected theorem sub_le_sub {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := int.add_le_add hab (int.neg_le_neg hcd) protected theorem add_lt_of_lt_neg_add {a : ℤ} {b : ℤ} {c : ℤ} (h : b < -a + c) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < a + (-a + c))) (int.add_neg_cancel_left a c)) (int.add_lt_add_left h a) protected theorem lt_neg_add_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : b < -a + c := eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c)) (int.neg_add_cancel_left a b)) (int.add_lt_add_left h (-a)) protected theorem add_lt_of_lt_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b < c - a) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < c + a - a)) (int.add_sub_cancel c a)) (eq.mp (Eq._oldrec (Eq.refl (a + b < a + c - a)) (int.add_comm a c)) (eq.mp (Eq._oldrec (Eq.refl (a + b < a + (c - a))) (Eq.symm (int.add_sub_assoc a c a))) (int.add_lt_add_left h a))) protected theorem lt_sub_left_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : b < c - a := eq.mp (Eq._oldrec (Eq.refl (b + a + -a < c + -a)) (int.add_neg_cancel_right b a)) (eq.mp (Eq._oldrec (Eq.refl (a + b + -a < c + -a)) (int.add_comm a b)) (int.add_lt_add_right h (-a))) protected theorem add_lt_of_lt_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a < c - b) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < c - b + b)) (int.sub_add_cancel c b)) (int.add_lt_add_right h b) protected theorem lt_sub_right_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : a < c - b := eq.mp (Eq._oldrec (Eq.refl (a + b + -b < c + -b)) (int.add_neg_cancel_right a b)) (int.add_lt_add_right h (-b)) protected theorem lt_add_of_neg_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a < c) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (b + (-b + a) < b + c)) (int.add_neg_cancel_left b a)) (int.add_lt_add_left h b) protected theorem neg_add_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -b + a < c := eq.mp (Eq._oldrec (Eq.refl (-b + a < -b + (b + c))) (int.neg_add_cancel_left b c)) (int.add_lt_add_left h (-b)) protected theorem lt_add_of_sub_left_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b < c) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (a < c + b)) (int.add_comm c b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b < c + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem sub_left_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : a - b < c := eq.mp (Eq._oldrec (Eq.refl (a + -b < c + b + -b)) (int.add_neg_cancel_right c b)) (eq.mp (Eq._oldrec (Eq.refl (a + -b < b + c + -b)) (int.add_comm b c)) (int.add_lt_add_right h (-b))) protected theorem lt_add_of_sub_right_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - c < b) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (a - c + c < b + c)) (int.sub_add_cancel a c)) (int.add_lt_add_right h c) protected theorem sub_right_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : a - c < b := eq.mp (Eq._oldrec (Eq.refl (a + -c < b + c + -c)) (int.add_neg_cancel_right b c)) (int.add_lt_add_right h (-c)) protected theorem lt_add_of_neg_add_lt_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a < c) : a < b + c := int.lt_add_of_sub_left_lt (eq.mp (Eq._oldrec (Eq.refl (-b + a < c)) (int.add_comm (-b) a)) h) protected theorem neg_add_lt_left_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -b + a < c := eq.mpr (id (Eq._oldrec (Eq.refl (-b + a < c)) (int.add_comm (-b) a))) (int.sub_left_lt_of_lt_add h) protected theorem lt_add_of_neg_add_lt_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -c + a < b) : a < b + c := int.lt_add_of_sub_right_lt (eq.mp (Eq._oldrec (Eq.refl (-c + a < b)) (int.add_comm (-c) a)) h) protected theorem neg_add_lt_right_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -c + a < b := int.neg_add_lt_left_of_lt_add (eq.mp (Eq._oldrec (Eq.refl (a < b + c)) (int.add_comm b c)) h) protected theorem lt_add_of_neg_lt_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -a < b - c) : c < a + b := int.lt_add_of_neg_add_lt_left (int.add_lt_of_lt_sub_right h) protected theorem neg_lt_sub_left_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c < a + b) : -a < b - c := eq.mp (Eq._oldrec (Eq.refl (-a < -c + b)) (int.add_comm (-c) b)) (int.lt_neg_add_of_add_lt (int.sub_left_lt_of_lt_add h)) protected theorem lt_add_of_neg_lt_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -b < a - c) : c < a + b := int.lt_add_of_sub_right_lt (int.add_lt_of_lt_sub_left h) protected theorem neg_lt_sub_right_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c < a + b) : -b < a - c := int.lt_sub_left_of_add_lt (int.sub_right_lt_of_lt_add h) protected theorem sub_lt_of_sub_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b < c) : a - c < b := int.sub_left_lt_of_lt_add (int.lt_add_of_sub_right_lt h) protected theorem sub_lt_sub_left {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : c - b < c - a := int.add_lt_add_left (int.neg_lt_neg h) c protected theorem sub_lt_sub_right {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : a - c < b - c := int.add_lt_add_right h (-c) protected theorem sub_lt_sub {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a < b) (hcd : c < d) : a - d < b - c := int.add_lt_add hab (int.neg_lt_neg hcd) protected theorem sub_lt_sub_of_le_of_lt {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a ≤ b) (hcd : c < d) : a - d < b - c := int.add_lt_add_of_le_of_lt hab (int.neg_lt_neg hcd) protected theorem sub_lt_sub_of_lt_of_le {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a < b) (hcd : c ≤ d) : a - d < b - c := int.add_lt_add_of_lt_of_le hab (int.neg_le_neg hcd) protected theorem sub_le_self (a : ℤ) {b : ℤ} (h : b ≥ 0) : a - b ≤ a := trans_rel_left LessEq (trans_rel_right LessEq rfl (int.add_le_add_left (int.neg_nonpos_of_nonneg h) a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a)) protected theorem sub_lt_self (a : ℤ) {b : ℤ} (h : b > 0) : a - b < a := trans_rel_left Less (trans_rel_right Less rfl (int.add_lt_add_left (int.neg_neg_of_pos h) a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a)) protected theorem add_le_add_three {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} {e : ℤ} {f : ℤ} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := le_trans (int.add_le_add (int.add_le_add h₁ h₂) h₃) (le_refl (d + e + f)) /- missing facts -/ protected theorem mul_lt_mul_of_pos_left {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := sorry protected theorem mul_lt_mul_of_pos_right {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := sorry protected theorem mul_le_mul_of_nonneg_left {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := sorry protected theorem mul_le_mul_of_nonneg_right {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := sorry -- TODO: there are four variations, depending on which variables we assume to be nonneg protected theorem mul_le_mul {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := le_trans (int.mul_le_mul_of_nonneg_right hac nn_b) (int.mul_le_mul_of_nonneg_left hbd nn_c) protected theorem mul_nonpos_of_nonneg_of_nonpos {a : ℤ} {b : ℤ} (ha : a ≥ 0) (hb : b ≤ 0) : a * b ≤ 0 := (fun (h : a * b ≤ a * 0) => eq.mp (Eq._oldrec (Eq.refl (a * b ≤ a * 0)) (int.mul_zero a)) h) (int.mul_le_mul_of_nonneg_left hb ha) protected theorem mul_nonpos_of_nonpos_of_nonneg {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≥ 0) : a * b ≤ 0 := (fun (h : a * b ≤ 0 * b) => eq.mp (Eq._oldrec (Eq.refl (a * b ≤ 0 * b)) (int.zero_mul b)) h) (int.mul_le_mul_of_nonneg_right ha hb) protected theorem mul_lt_mul {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := lt_of_lt_of_le (int.mul_lt_mul_of_pos_right hac pos_b) (int.mul_le_mul_of_nonneg_left hbd nn_c) protected theorem mul_lt_mul' {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h1 : a ≤ c) (h2 : b < d) (h3 : b ≥ 0) (h4 : c > 0) : a * b < c * d := lt_of_le_of_lt (int.mul_le_mul_of_nonneg_right h1 h3) (int.mul_lt_mul_of_pos_left h2 h4) protected theorem mul_neg_of_pos_of_neg {a : ℤ} {b : ℤ} (ha : a > 0) (hb : b < 0) : a * b < 0 := (fun (h : a * b < a * 0) => eq.mp (Eq._oldrec (Eq.refl (a * b < a * 0)) (int.mul_zero a)) h) (int.mul_lt_mul_of_pos_left hb ha) protected theorem mul_neg_of_neg_of_pos {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b > 0) : a * b < 0 := (fun (h : a * b < 0 * b) => eq.mp (Eq._oldrec (Eq.refl (a * b < 0 * b)) (int.zero_mul b)) h) (int.mul_lt_mul_of_pos_right ha hb) protected theorem mul_le_mul_of_nonpos_right {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := sorry protected theorem mul_nonneg_of_nonpos_of_nonpos {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := (fun (this : 0 * b ≤ a * b) => eq.mp (Eq._oldrec (Eq.refl (0 * b ≤ a * b)) (int.zero_mul b)) this) (int.mul_le_mul_of_nonpos_right ha hb) protected theorem mul_lt_mul_of_neg_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b < a) (hc : c < 0) : c * a < c * b := sorry protected theorem mul_lt_mul_of_neg_right {a : ℤ} {b : ℤ} {c : ℤ} (h : b < a) (hc : c < 0) : a * c < b * c := sorry protected theorem mul_pos_of_neg_of_neg {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b < 0) : 0 < a * b := (fun (this : 0 * b < a * b) => eq.mp (Eq._oldrec (Eq.refl (0 * b < a * b)) (int.zero_mul b)) this) (int.mul_lt_mul_of_neg_right ha hb) protected theorem mul_self_le_mul_self {a : ℤ} {b : ℤ} (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := int.mul_le_mul h2 h2 h1 (le_trans h1 h2) protected theorem mul_self_lt_mul_self {a : ℤ} {b : ℤ} (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := int.mul_lt_mul' (le_of_lt h2) h2 h1 (lt_of_le_of_lt h1 h2) /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ Int.ofNat n := trivial theorem coe_succ_pos (n : ℕ) : ↑(Nat.succ n) > 0 := coe_nat_lt_coe_nat_of_lt (nat.succ_pos n) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃ (n : ℕ), a = -↑n := sorry theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : ↑(nat_abs a) = a := sorry theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : ↑(nat_abs a) = -a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs a) = -a)) (Eq.symm (nat_abs_neg a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs (-a)) = -a)) (nat_abs_of_nonneg (int.neg_nonneg_of_nonpos H)))) (Eq.refl (-a))) theorem lt_of_add_one_le {a : ℤ} {b : ℤ} (H : a + 1 ≤ b) : a < b := H theorem add_one_le_of_lt {a : ℤ} {b : ℤ} (H : a < b) : a + 1 ≤ b := H theorem lt_add_one_of_le {a : ℤ} {b : ℤ} (H : a ≤ b) : a < b + 1 := int.add_le_add_right H 1 theorem le_of_lt_add_one {a : ℤ} {b : ℤ} (H : a < b + 1) : a ≤ b := int.le_of_add_le_add_right H theorem sub_one_le_of_lt {a : ℤ} {b : ℤ} (H : a ≤ b) : a - 1 < b := int.sub_right_lt_of_lt_add (lt_add_one_of_le H) theorem lt_of_sub_one_le {a : ℤ} {b : ℤ} (H : a - 1 < b) : a ≤ b := le_of_lt_add_one (int.lt_add_of_sub_right_lt H) theorem le_sub_one_of_lt {a : ℤ} {b : ℤ} (H : a < b) : a ≤ b - 1 := int.le_sub_right_of_add_le H theorem lt_of_le_sub_one {a : ℤ} {b : ℤ} (H : a ≤ b - 1) : a < b := int.add_le_of_le_sub_right H theorem sign_of_succ (n : ℕ) : sign ↑(Nat.succ n) = 1 := rfl theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 := sorry theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 := sorry theorem eq_zero_of_sign_eq_zero {a : ℤ} : sign a = 0 → a = 0 := sorry theorem pos_of_sign_eq_one {a : ℤ} : sign a = 1 → 0 < a := sorry theorem neg_of_sign_eq_neg_one {a : ℤ} : sign a = -1 → a < 0 := sorry theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a := { mp := pos_of_sign_eq_one, mpr := sign_eq_one_of_pos } theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 := { mp := neg_of_sign_eq_neg_one, mpr := sign_eq_neg_one_of_neg } theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 := sorry protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a : ℤ} {b : ℤ} (h : a * b = 0) : a = 0 ∨ b = 0 := sorry protected theorem eq_of_mul_eq_mul_right {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (h : b * a = c * a) : b = c := sorry protected theorem eq_of_mul_eq_mul_left {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (h : a * b = a * c) : b = c := sorry theorem eq_one_of_mul_eq_self_left {a : ℤ} {b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := int.eq_of_mul_eq_mul_right Hpos (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = 1 * a)) (int.one_mul a))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = a)) H)) (Eq.refl a))) theorem eq_one_of_mul_eq_self_right {a : ℤ} {b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := int.eq_of_mul_eq_mul_left Hpos (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b * 1)) (int.mul_one b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b)) H)) (Eq.refl b))) end Mathlib
n := 0; repeat n := n + 1; Print(n, "\n"); until RemInt(n, 6) = 0;
theory Chisholm_SDL imports SDL (*Christoph Benzmüller & Xavier Parent, 2019*) begin (*Unimportant*) nitpick_params [user_axioms,show_all,format=2] (*** Chisholm Example ***) consts go::\<sigma> tell::\<sigma> kill::\<sigma> abbreviation "D1 \<equiv> \<^bold>\<circle><go>" (*It ought to be that Jones goes to assist his neighbors.*) abbreviation "D2w \<equiv> \<^bold>\<circle><go \<^bold>\<rightarrow> tell>" (*It ought to be that if Jones goes, then he tells them he is coming.*) abbreviation "D2n \<equiv> go \<^bold>\<rightarrow> \<^bold>\<circle><tell>" abbreviation "D3w \<equiv> \<^bold>\<circle><\<^bold>\<not>go \<^bold>\<rightarrow> \<^bold>\<not>tell>" (*If Jones doesn't go, then he ought not tell them he is coming.*) abbreviation "D3n \<equiv> \<^bold>\<not>go \<^bold>\<rightarrow> \<^bold>\<circle><\<^bold>\<not>tell>" abbreviation "D4 \<equiv> \<^bold>\<not>go" (*Jones doesn't go. (This is encoded as a locally valid statement.)*) (*** Chisholm_A: All-wide scoping is leading to an inadequate, dependent set of the axioms.***) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3w) \<^bold>\<rightarrow> D4\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D4) \<^bold>\<rightarrow> D3w\<rfloor>" sledgehammer by blast (*proof*) lemma "\<lfloor>(D1 \<^bold>\<and> D3w \<^bold>\<and> D4) \<^bold>\<rightarrow> D2w\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D2w \<^bold>\<and> D3w \<^bold>\<and> D4) \<^bold>\<rightarrow> D1\<rfloor>" nitpick oops (*countermodel*) (* Consistency *) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" nitpick [satisfy] oops (*Consistent? Yes*) (* Queries *) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><\<^bold>\<not>tell>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James not tell? No*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><tell>\<rfloor>\<^sub>c\<^sub>w" using assms by blast (*Should J. tell? Yes*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><kill>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James kill? No*) (*** Chisholm_B: All-narrow scoping is leading to a inadequate, dependent set of the axioms.*) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3n) \<^bold>\<rightarrow> D4\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D4) \<^bold>\<rightarrow> D3n\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D3n \<^bold>\<and> D4) \<^bold>\<rightarrow> D2n\<rfloor>" sledgehammer by blast (*proof*) lemma "\<lfloor>(D2n \<^bold>\<and> D3n \<^bold>\<and> D4) \<^bold>\<rightarrow> D1\<rfloor>" nitpick oops (*countermodel*) (* Consistency *) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" nitpick [satisfy] oops (*Consistent? Yes*) (* Queries *) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><\<^bold>\<not>tell>\<rfloor>\<^sub>c\<^sub>w" using assms by smt (*Should J. not tell? Yes*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><tell>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James tell? No*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><kill>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James kill? No*) (*** Chisholm_C: Wide-narrow scoping is leading to an adequate, independence of the axioms.*) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n) \<^bold>\<rightarrow> D4\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D4) \<^bold>\<rightarrow> D3n\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D3n \<^bold>\<and> D4) \<^bold>\<rightarrow> D2w\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D2w \<^bold>\<and> D3n \<^bold>\<and> D4) \<^bold>\<rightarrow> D1\<rfloor>" nitpick oops (*countermodel*) (* Consistency *) lemma "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" nitpick [satisfy,expect=none] oops (*Consistent? No*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows False using D assms by blast (* Queries *) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><\<^bold>\<not>tell>\<rfloor>\<^sub>c\<^sub>w" using D assms by smt (*Shld J. not tell? Yes*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><tell>\<rfloor>\<^sub>c\<^sub>w" using assms by blast (*Should J. tell? Yes*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2w \<^bold>\<and> D3n)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><kill>\<rfloor>\<^sub>c\<^sub>w" using D assms by blast (*Should J. kill? Yes*) (*** Chisholm_D: Narrow-wide scoping is leading to a inadequate, dependent set of the axioms.*) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3w) \<^bold>\<rightarrow> D4\<rfloor>" nitpick oops (*countermodel*) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D4) \<^bold>\<rightarrow> D3w\<rfloor>" by blast (*proof*) lemma "\<lfloor>(D1 \<^bold>\<and> D3w \<^bold>\<and> D4) \<^bold>\<rightarrow> D2n\<rfloor>" by blast (*proof*) lemma "\<lfloor>(D2n \<^bold>\<and> D3w \<^bold>\<and> D4) \<^bold>\<rightarrow> D1\<rfloor>" nitpick oops (*countermodel*) (* Consistency *) lemma "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" nitpick [satisfy] oops (*Consistent? Yes*) (* Queries *) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><\<^bold>\<not>tell>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James not tell? No*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><tell>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James tell? No*) lemma assumes "\<lfloor>(D1 \<^bold>\<and> D2n \<^bold>\<and> D3w)\<rfloor> \<and> \<lfloor>D4\<rfloor>\<^sub>c\<^sub>w" shows "\<lfloor>\<^bold>\<circle><kill>\<rfloor>\<^sub>c\<^sub>w" nitpick oops (*Should James kill? No*) end
A point $y$ is a limit point of the open ball $B(x,\epsilon)$ if and only if $0 < \epsilon$ and $y \in \overline{B(x,\epsilon)}$.
Require Import Basics.Overture Basics.Tactics. Require Import Pos.Core. Local Open Scope positive_scope. (** ** Specification of [succ] in term of [add] *) Lemma pos_add_1_r p : p + 1 = pos_succ p. Proof. by destruct p. Qed. Lemma pos_add_1_l p : 1 + p = pos_succ p. Proof. by destruct p. Qed. (** ** Specification of [add_carry] *) Theorem pos_add_carry_spec p q : pos_add_carry p q = pos_succ (p + q). Proof. revert q. induction p; destruct q; simpl; by apply ap. Qed. (** ** Commutativity of [add] *) Theorem pos_add_comm p q : p + q = q + p. Proof. revert q. induction p; destruct q; simpl; apply ap; trivial. rewrite 2 pos_add_carry_spec; by apply ap. Qed. (** ** Permutation of [add] and [succ] *) Theorem pos_add_succ_r p q : p + pos_succ q = pos_succ (p + q). Proof. revert q. induction p; destruct q; simpl; apply ap; auto using pos_add_1_r; rewrite pos_add_carry_spec; auto. Qed. Theorem pos_add_succ_l p q : pos_succ p + q = pos_succ (p + q). Proof. rewrite pos_add_comm, (pos_add_comm p). apply pos_add_succ_r. Qed. Definition pos_add_succ p q : p + pos_succ q = pos_succ p + q. Proof. by rewrite pos_add_succ_r, pos_add_succ_l. Defined. Definition pos_add_carry_spec_l q r : pos_add_carry q r = pos_succ q + r. Proof. by rewrite pos_add_carry_spec, pos_add_succ_l. Qed. Definition pos_add_carry_spec_r q r : pos_add_carry q r = q + pos_succ r. Proof. by rewrite pos_add_carry_spec, pos_add_succ_r. Defined. (** ** No neutral elements for addition *) Lemma pos_add_no_neutral p q : q + p <> p. Proof. revert q. induction p as [ |p IHp|p IHp]; intros [ |q|q]. 1,3: apply x0_neq_xH. 1: apply x1_neq_xH. 1,3: apply x1_neq_x0. 2,4: apply x0_neq_x1. 1,2: intro H; apply (IHp q). 1: apply x0_inj, H. apply x1_inj, H. Qed. (** * Injectivity of pos_succ *) Lemma pos_succ_inj n m : pos_succ n = pos_succ m -> n = m. Proof. revert m. induction n as [ | n x | n x]; induction m as [ | m y | m y]. + reflexivity. + intro p. destruct (x0_neq_x1 p). + intro p. simpl in p. apply x0_inj in p. destruct m. 1,3: destruct (xH_neq_x0 p). destruct (xH_neq_x1 p). + intro p. destruct (x1_neq_x0 p). + simpl. intro p. by apply ap, x1_inj. + intro p. destruct (x1_neq_x0 p). + intro p. cbn in p. apply x0_inj in p. destruct n. 1,3: destruct (x0_neq_xH p). destruct (x1_neq_xH p). + intro p. cbn in p. destruct (x0_neq_x1 p). + intro p. apply ap, x, x0_inj, p. Defined. (** ** Addition is associative *) Theorem pos_add_assoc p q r : p + (q + r) = p + q + r. Proof. revert q r. induction p. + intros [|q|q] [|r|r]. all: try reflexivity. all: simpl. 1,2: by destruct r. 1,2: apply ap; symmetry. 1: apply pos_add_carry_spec. 1: apply pos_add_succ_l. apply ap. rewrite pos_add_succ_l. apply pos_add_carry_spec. + intros [|q|q] [|r|r]. all: try reflexivity. all: cbn; apply ap. 3,4,6: apply IHp. 1: apply pos_add_1_r. 1: symmetry; apply pos_add_carry_spec_r. 1: apply pos_add_succ_r. rewrite 2 pos_add_carry_spec_l. rewrite <- pos_add_succ_r. apply IHp. + intros [|q|q] [|r|r]. all: cbn; apply ap. 1: apply pos_add_1_r. 1: apply pos_add_carry_spec_l. 1: apply pos_add_succ. 1: apply pos_add_carry_spec. 1: apply IHp. 2: symmetry; apply pos_add_carry_spec_r. 1,2: rewrite 2 pos_add_carry_spec, ?pos_add_succ_l. 1,2: apply ap, IHp. rewrite ?pos_add_carry_spec_r. rewrite pos_add_succ. apply IHp. Qed. (** ** One is neutral for multiplication *) Lemma pos_mul_1_l p : 1 * p = p. Proof. reflexivity. Qed. Lemma pos_mul_1_r p : p * 1 = p. Proof. induction p; cbn; trivial; by apply ap. Qed. (** pos_succ and doubling functions *) Lemma pos_pred_double_succ n : pos_pred_double (pos_succ n) = n~1. Proof. induction n as [|n|n nH]. all: trivial. cbn; apply ap, nH. Qed. Lemma pos_succ_pred_double n : pos_succ (pos_pred_double n) = n~0. Proof. induction n as [|n nH|n]. all: trivial. cbn; apply ap, nH. Qed. (** ** Iteration and pos_succ *) Lemma pos_iter_succ_l {A} (f : A -> A) p a : pos_iter f (pos_succ p) a = f (pos_iter f p a). Proof. unfold pos_iter. by rewrite pos_peano_ind_beta_pos_succ. Qed. Lemma pos_iter_succ_r {A} (f : A -> A) p a : pos_iter f (pos_succ p) a = pos_iter f p (f a). Proof. revert p f a. srapply pos_peano_ind. 1: hnf; intros; trivial. hnf; intros p q f a. refine (_ @ _ @ _^). 1,3: unfold pos_iter; by rewrite pos_peano_ind_beta_pos_succ. apply ap. apply q. Qed. (** ** Right reduction properties for multiplication *) Lemma mul_xO_r p q : p * q~0 = (p * q)~0. Proof. induction p; simpl; f_ap; f_ap; trivial. Qed. Lemma mul_xI_r p q : p * q~1 = p + (p * q)~0. Proof. induction p; simpl; trivial; f_ap. rewrite IHp. rewrite pos_add_assoc. rewrite (pos_add_comm q p). symmetry. apply pos_add_assoc. Qed. (** ** Commutativity of multiplication *) Lemma pos_mul_comm p q : p * q = q * p. Proof. induction q; simpl. 1: apply pos_mul_1_r. + rewrite mul_xO_r. f_ap. + rewrite mul_xI_r. f_ap; f_ap. Qed. (** ** Distributivity of addition over multiplication *) Theorem pos_mul_add_distr_l p q r : p * (q + r) = p * q + p * r. Proof. induction p; cbn; [reflexivity | f_ap | ]. rewrite IHp. set (m:=(p*q)~0). set (n:=(p*r)~0). change ((p*q+p*r)~0) with (m+n). rewrite 2 pos_add_assoc; f_ap. rewrite <- 2 pos_add_assoc; f_ap. apply pos_add_comm. Qed. Theorem pos_mul_add_distr_r p q r : (p + q) * r = p * r + q * r. Proof. rewrite 3 (pos_mul_comm _ r); apply pos_mul_add_distr_l. Qed. (** ** Associativity of multiplication *) Theorem pos_mul_assoc p q r : p * (q * r) = p * q * r. Proof. induction p; simpl; rewrite ?IHp; trivial. by rewrite pos_mul_add_distr_r. Qed. (** ** pos_succ and pos_mul *) Lemma pos_mul_succ_l p q : (pos_succ p) * q = p * q + q. Proof. by rewrite <- pos_add_1_r, pos_mul_add_distr_r, pos_mul_1_l. Qed. Lemma pos_mul_succ_r p q : p * (pos_succ q) = p + p * q. Proof. by rewrite <- pos_add_1_l, pos_mul_add_distr_l, pos_mul_1_r. Qed.
Holiday Tag Post – Join me and share your answers! Are any of you YouTubers? There is this entirely separate YouTube world roaming on the internet. We have a channel that is updated very sporadically but we are planning to create more videos in the upcoming year.
open import Oscar.Prelude module Oscar.Class.Pure where module _ {𝔬 𝔣} (𝔉 : Ø 𝔬 → Ø 𝔣) where 𝓹ure = ∀ {𝔒 : Ø 𝔬} → 𝔒 → 𝔉 𝔒 record 𝓟ure : Ø 𝔣 ∙̂ ↑̂ 𝔬 where field pure : 𝓹ure open 𝓟ure ⦃ … ⦄ public
import Myint.Canon namespace myint theorem ne_irrefl (a : myint) : ¬ a ≉ a := by rw [mynotequal] rw [Ne] have := refl a rw [myequal] at this rw [this] have : ¬ a.y + a.x = a.y + a.x → False := by intro h rw [← Ne] at h exact Ne.irrefl h exact this theorem ne_symm {a b : myint} (hab : mynotequal a b) : mynotequal b a := by rw [mynotequal] at hab ⊢ have hres := Ne.symm hab rw [mynat.add_comm a.y, mynat.add_comm a.x] at hres exact hres -- Warning: this is not the usual transitivity. -- this says that if a ≠ b and b = c then a ≠ c theorem ne_trans {a b c : myint} (hab : mynotequal a b) (hbc : myequal b c) : mynotequal a c := by rw [myequal] at hbc rw [mynotequal] at hab ⊢ have : a.x + b.y + (b.x + c.y) ≠ a.y + b.x + (b.y + c.x) := by rw [hbc] intro h have := mynat.add_right_cancel (a.x + b.y) (b.y + c.x) (a.y + b.x) h exact hab this repeat rw [← mynat.add_assoc] at this rw [mynat.add_assoc a.x] at this rw [mynat.add_comm b.y] at this rw [mynat.add_comm a.x] at this rw [mynat.add_assoc a.y] at this rw [mynat.add_comm a.y] at this repeat rw [mynat.add_assoc (b.x + b.y)] at this intro hfalse rw [hfalse] at this exact this (Eq.refl (b.x + b.y + (a.y + c.x))) theorem ne_implies_exists_offset (a b : myint) : a ≉ b → ∃ c : myint, c ≉ 0 ∧ a ≈ b + c := by intro h rw [mynotequal] at h cases mynat.le_total (a.x + b.y) (a.y + b.x) case inl hle => rw [mynat.le_iff_exists_add] at hle cases hle with | intro d hd => exists myint.mk 0 d apply And.intro . rw [mynotequal] rw [destruct_x, destruct_y _ d] rw [default_nat_has_no_y, default_nat_has_same_x] rw [mynat.myofnat, mynat.mynat_zero_eq_zero] repeat rw [mynat.add_zero] cases d case zero => apply False.elim _ rw [mynat.mynat_zero_eq_zero, mynat.add_zero] at hd exact h (Eq.symm hd) case succ d' => exact Ne.symm (mynat.succ_ne_zero d') . rw [equiv_is_myequal, myequal] rw [add_y, destruct_y _ d] rw [add_x, destruct_x 0 _] rw [mynat.add_zero] rw [← mynat.add_assoc] exact Eq.symm hd case inr hle => rw [mynat.le_iff_exists_add] at hle cases hle with | intro d hd => exists myint.mk d 0 apply And.intro . rw [mynotequal] rw [destruct_x, destruct_y _ 0] rw [default_nat_has_no_y, default_nat_has_same_x] rw [mynat.myofnat, mynat.mynat_zero_eq_zero] repeat rw [mynat.zero_add] cases d case zero => apply False.elim _ rw [mynat.mynat_zero_eq_zero, mynat.add_zero] at hd exact h hd case succ d' => rw [mynat.add_zero] exact mynat.succ_ne_zero d' . rw [equiv_is_myequal, myequal] rw [add_y, destruct_y _ 0] rw [add_x, destruct_x d _] rw [mynat.add_zero] rw [← mynat.add_assoc] exact hd theorem ne_iff_exists_offset (a b : myint) : a ≉ b ↔ ∃ c : myint, c ≉ 0 ∧ a ≈ b + c := by apply Iff.intro . exact ne_implies_exists_offset a b . intro h cases h with | intro d hd => have hdnz := hd.left have hab := hd.right rw [mynotequal] rw [equiv_is_myequal, myequal] at hab rw [add_y, add_x] at hab rw [mynotequal, zerox, zeroy, mynat.add_zero, mynat.add_zero] at hdnz intro hcont repeat rw [← mynat.add_assoc] at hab rw [hcont] at hab have := (mynat.add_left_cancel _ _ _) hab exact hdnz (Eq.symm this) theorem ne_mul_still_ne (a b t : myint) : a ≉ b ∧ t ≉ 0 → a * t ≉ b * t := by intro h have hab := h.left have htnz := h.right have hoffset := (ne_iff_exists_offset a b).mp hab cases hoffset with | intro c hc => have hcnz := hc.left have habc := hc.right have htimes := mul_right a (b + c) t habc have : a * t ≈ b * t + c * t := trans htimes (add_mul b c t) intro hfalse rw [← myequal, ← equiv_is_myequal] at hfalse have := trans (symm hfalse) this have := add_left_cancel (b * t) 0 (c * t) this have := eq_zero_or_eq_zero_of_mul_eq_zero c t (symm this) cases this case inl h' => exact hcnz h' case inr h' => exact htnz h' theorem mul_nonzero (a b : myint) : a ≉ 0 → b ≉ 0 → a * b ≉ 0 := by intro ha intro hb have := ne_mul_still_ne a 0 b ⟨ ha, hb ⟩ have := ne_trans this (zero_mul b) exact this def myle (a b : myint) := ∃ (c : mynat), b ≈ a + (myint.mk c 0) instance : LE myint where le := myle theorem le_iff_exists_add (a b : myint) : a ≤ b ↔ ∃ (c : mynat), b ≈ a + (myint.mk c 0) := Iff.rfl theorem le_refl (x : myint) : x ≤ x := by exists 0 exact add_zero x theorem le_refl_equiv (x y : myint) : x ≈ y → x ≤ y := by intro h exists 0 exact trans (symm h) (add_zero x) theorem le_trans (a b c : myint) (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := by cases hab with | intro d hd => cases hbc with | intro e he => have hdp := add_right b (a + myint.mk d 0) (myint.mk e 0) hd have heq : c ≈ (a + (myint.mk d 0) + (myint.mk e 0)) := trans he hdp exists d + e have heqasc : c ≈ a + ((myint.mk d 0) + (myint.mk e 0)) := trans heq (add_assoc a (myint.mk d 0) (myint.mk e 0)) conv at heqasc => rhs arg 2 rw [add_eq_myadd, myadd] rw [destruct_x, destruct_y, destruct_x, mynat.add_zero] exact heqasc theorem le_trans_equiv (a b c : myint) (hab : a ≤ b) (hbc : b ≈ c) : a ≤ c := by have := le_refl_equiv b c hbc exact le_trans a b c hab this theorem le_equiv_trans (a b c : myint) (hab : a ≈ b) (hbc : b ≤ c) : a ≤ c := by have := le_refl_equiv a b hab exact le_trans a b c this hbc theorem le_antisymm (a b : myint) (hab : a ≤ b) (hba : b ≤ a) : a ≈ b := by cases hab with | intro c hc => cases hba with | intro d hd => have hadd : b + (myint.mk d 0) ≈ a + (myint.mk c 0) + (myint.mk d 0) := add_right _ _ _ hc have hassoc : b + (myint.mk d 0) ≈ a + ((myint.mk c 0) + (myint.mk d 0)) := trans hadd (add_assoc _ _ _) have := trans hd hassoc have := add_left_cancel a 0 _ this rw [equiv_is_myequal, myequal] at this rw [add_x, destruct_x c _, destruct_x d _, zerox] at this rw [add_y, destruct_y, zeroy] at this repeat rw [mynat.zero_add] at this have hdz := mynat.add_left_eq_zero (Eq.symm this) rw [hdz] at hd have hzz : myint.mk 0 0 ≈ 0 := rfl have := trans hd (add_left b _ _ hzz) have := trans this (add_zero b) exact this theorem add_le_add_right {a b : myint} : a ≤ b → ∀ t, (a + t) ≤ (b + t) := by intro h rw [le_iff_exists_add] at h cases h with | intro c hc => intro t exists c have ht1 := add_right b (a + myint.mk c 0) t hc have ht2 : a + { x := c, y := 0 } + t ≈ a + t + { x := c, y := 0} := by have hst1 : a + (myint.mk c 0) + t ≈ a + ((myint.mk c 0) + t) := add_assoc _ _ _ have hst2 : a + ((myint.mk c 0) + t) ≈ a + (t + (myint.mk c 0)) := add_left a _ _ (add_comm _ _) have hst3 : a + (t + (myint.mk c 0)) ≈ a + t + (myint.mk c 0) := symm (add_assoc _ _ _) exact trans (trans hst1 hst2) hst3 exact trans ht1 ht2 theorem le_total (a b : myint) : a ≤ b ∨ b ≤ a := by have hlemma (n : myint) : n ≤ 0 ∨ 0 ≤ n := by let pn := n.x ≤ n.y cases Classical.em pn case inl h => have : n.x ≤ n.y := h apply Or.intro_left rw [le_iff_exists_add] have := canon_neg n this cases this with | intro c hc => exists c.y have ht1 : c + (myint.mk c.y 0) ≈ n + (myint.mk c.y 0) := add_right c n _ hc.right have : myint.mk 0 c.y ≈ c := by apply if_x_and_y_equal_then_equiv rw [destruct_x, destruct_y] exact ⟨ Eq.symm hc.left, rfl ⟩ have ht2 : (myint.mk 0 c.y) + (myint.mk c.y 0) ≈ c + (myint.mk c.y 0) := add_right (myint.mk 0 c.y) c (myint.mk c.y 0) this have ht3 : 0 ≈ (myint.mk 0 c.y) + (myint.mk c.y 0) := by rw [equiv_is_myequal, myequal] rw [add_y, destruct_y, destruct_y _ 0] rw [add_x, destruct_x 0, destruct_x c.y] rw [zerox, zeroy, mynat.zero_add, mynat.add_zero, mynat.zero_add, mynat.zero_add] exact trans (trans ht3 ht2) ht1 case inr h => have : ¬ n.x ≤ n.y := h have := mynat.le_total n.x n.y cases this case inl hh => apply False.elim exact this hh case inr hh => apply Or.intro_right rw [le_iff_exists_add] have := canon_pos n hh cases this with | intro c hc => have ⟨ cx, cy ⟩ := c exists cx have : cy = 0 := hc.left rw [← this] exact trans (symm hc.right) (symm (zero_add (myint.mk cx cy))) have : a - b ≤ 0 ∨ 0 ≤ a - b := hlemma (a - b) have hmain : a ≈ a - b + b := by have hm := add_left a 0 (-b + b) (symm (trans (add_comm (-b) b) (neg_is_inv b))) have := equal_implies_equiv _ _ (Eq.symm (sub_eq_plusneg a b)) have := add_right (a + -b) (a - b) b this have hl := symm (add_zero a) have hr : a + (-b + b) ≈ a + -b + b := symm (add_assoc a (-b) b) exact trans (trans hl hm) hr have haux : 0 + b ≈ b := zero_add b cases this case inl h => have : (a - b) + b ≤ 0 + b := add_le_add_right h b apply Or.intro_left exact le_trans_equiv _ _ _ (le_equiv_trans _ _ _ hmain this) haux case inr h => have : 0 + b ≤ (a - b) + b := add_le_add_right h b apply Or.intro_right exact le_trans_equiv _ _ _ (le_equiv_trans _ _ _ (symm haux) this) (symm hmain) -- This law is called "material implication" and I'm not sure if there is a better way to maintain this law? -- have : (¬ a ≤ b → b ≤ a) → a ≤ b ∨ b ≤ a := by -- intro h1 -- let p : Prop := a ≤ b -- cases (Classical.em p) -- case inl hp => -- apply Or.intro_left -- have h : a ≤ b := hp -- exact h -- case inr hnotp => -- apply Or.intro_right -- have h : ¬ a ≤ b := hnotp -- exact h1 h -- apply this -- intro h -- rw [LE.le, instLEMyint] at h -- simp at h -- rw [myle] at h -- -- Another logic law -- sorry theorem add_le_add_left {a b : myint} (h : a ≤ b) (t : myint) : t + a ≤ t + b := by have := add_le_add_right h t exact le_trans_equiv _ _ _ (le_equiv_trans _ _ _ (add_comm t a) this) (add_comm b t) theorem pos_iff_y_le_x (n : myint) : 0 ≤ n ↔ n.y ≤ n.x := by apply Iff.intro . intro h rw [le_iff_exists_add] at h cases h with | intro c hc => have ⟨ nx, ny ⟩ := n rw [equiv_is_myequal, myequal] at hc rw [destruct_x, destruct_y _ ny] at hc rw [add_y, add_x] at hc rw [destruct_y _ 0, destruct_x c _] at hc rw [destruct_y, destruct_x] exists c rw [zeroy, zerox, mynat.add_zero, mynat.zero_add, mynat.add_zero] at hc exact hc . intro h have := canon_pos n h cases this with | intro c hc => have ⟨ cx, cy ⟩ := c rw [destruct_y] at hc have ⟨ hc1, hc2 ⟩ := hc rw [hc1] at hc2 have : 0 ≤ myint.mk cx 0 := by exists cx exact symm (zero_add (myint.mk cx 0)) exact le_trans_equiv _ _ _ this hc2 theorem le_mul_pos (a b : myint) (h : a ≤ b) (t : myint) (ht : 0 ≤ t) : a * t ≤ b * t := by have hpos := ht rw [le_iff_exists_add] at hpos cases h with | intro c hc => have := mul_right b (a + myint.mk c 0) t hc have huse : b * t ≈ a * t + (myint.mk c 0) * t := trans this (add_mul _ _ _) have := canon_pos t ((pos_iff_y_le_x t).mp ht) cases this with | intro d hd => have ⟨ dx, dy ⟩ := d rw [destruct_y] at hd have ⟨ hd1, hd2 ⟩ := hd rw [hd1] at hd2 have hhelper : a * t + { x := c, y := 0 } * t ≈ a * t + { x := c, y := 0 } * { x := dx, y := 0} := (add_left (a * t) _ _) (mul_left (myint.mk c 0) t (myint.mk dx 0) (symm hd2)) have hthis := trans huse hhelper conv at hthis => rhs arg 2 rw [mul_eq_mymul, mymul] rw [destruct_x, destruct_x, destruct_y] rw [mynat.mul_zero, mynat.mul_zero, mynat.zero_mul, mynat.add_zero, mynat.add_zero] exists c * dx theorem le_mul_neg (a b : myint) (h : a ≤ b) (t : myint) (ht : t ≤ 0) : b * t ≤ a * t := by have : a * (-t) ≤ b * (-t) := by have : 0 ≤ -t := by have := add_le_add_right ht (-t) have := le_equiv_trans _ _ _ (symm (neg_is_inv t)) this exact le_trans_equiv _ _ _ this (zero_add _) exact le_mul_pos a b h (-t) this have hlemma (f g : myint) : f * g + f * -g ≈ 0 := by have : f * g + f * g * -1 ≈ f * g + f * -g := add_left _ _ _ (trans (mul_assoc _ _ _) (mul_left f _ _ (mul_negone g))) have hs3 : f * g * -1 ≈ - (f * g) := mul_negone (f * g) have hs : f * g + -(f * g) ≈ f * g + f * -g := trans (symm (add_left (f * g) _ _ hs3)) this have ht := trans (symm (neg_is_inv (f * g))) hs exact symm ht have : 0 ≤ a * t + b * (-t) := by have hthis := add_le_add_left this (a * t) exact le_equiv_trans _ _ _ (symm (hlemma a t)) hthis have hthis := add_le_add_right this (b * t) have := le_trans_equiv _ _ _ hthis (add_assoc _ _ _) have hadjust := add_left (a * t) _ _ (trans (add_comm _ _) (hlemma b t)) have := le_trans_equiv _ _ _ this hadjust exact le_equiv_trans _ _ _ (symm (zero_add (b * t))) this theorem sq_pos (n : myint) : 0 ≤ n * n := by let pn := 0 ≤ n cases Classical.em pn case inl h => have : 0 ≤ n := h have := le_mul_pos 0 n this n this exact le_equiv_trans _ _ _ (symm (zero_mul n)) this case inr h => have : ¬ 0 ≤ n := h have := le_total 0 n cases this case inl hh => apply False.elim exact this hh case inr hh => have := le_mul_neg n 0 hh n hh exact le_equiv_trans _ _ _ (symm (zero_mul n)) this -- actually this obviously implies the simple case of AM-GM inequality... def mylt (a b : mynat) := a ≤ b ∧ ¬ (b ≤ a) instance : LT mynat := ⟨mylt⟩ theorem lt_def (a b : mynat) : a < b ↔ a ≤ b ∧ ¬ (b ≤ a) := Iff.rfl end myint
DOUBLE PRECISION FUNCTION DDASNM (NEQ, V, WT, RWORK, IWORK) c Copyright (c) 2006, Math a la Carte, Inc. c>> 2003-03-06 ddasnm Hanson changed norm computation to use reciprocals. c>> 2001-11-23 ddasnm Krogh Changed many names per library conventions. c>> 2001-11-04 ddasnm Krogh Fixes for F77 and conversion to single c>> 2001-11-01 ddasnm Hanson Provide code to Math a la Carte. c--D replaces "?": ?DASNM, ?DASLX c IMPLICIT NONE C***BEGIN PROLOGUE DDASNM C***SUBSIDIARY C***PURPOSE Compute vector norm for DDASLX. C***LIBRARY SLATEC (DDASLX) C***TYPE DOUBLE PRECISION (SDASNM-S, DDASNM-D) C***AUTHOR Petzold, Linda R., (LLNL) C***DESCRIPTION c ---------------------------------------------------------------------- C THIS FUNCTION ROUTINE COMPUTES THE WEIGHTED C ROOT-MEAN-SQUARE NORM OF THE VECTOR OF LENGTH C NEQ CONTAINED IN THE ARRAY V,WITH WEIGHTS C CONTAINED IN THE ARRAY WT OF LENGTH NEQ. C DDASNM=SQRT((1/NEQ)*SUM(V(I)/WT(I))**2) c ---------------------------------------------------------------------- C***ROUTINES CALLED (NONE) C***REVISION HISTORY (YYMMDD) C 830315 DATE WRITTEN C 901009 Finished conversion to SLATEC 4.0 format (F.N.Fritsch) C 901019 Merged changes made by C. Ulrich with SLATEC 4.0 format. C 901026 Added explicit declarations for all variables and minor C cosmetic changes to prologue. (FNF) C***END PROLOGUE DDASNM C INTEGER NEQ, IWORK(*) DOUBLE PRECISION V(NEQ), WT(NEQ), RWORK(*) C INTEGER I DOUBLE PRECISION SUM, VMAX EXTERNAL D1MACH DOUBLE PRECISION D1MACH, G, H, T INTEGER L C***FIRST EXECUTABLE STATEMENT DDASNM H=sqrt(sqrt(d1mach(2))) G=d1mach(1)/d1mach(4) sum=0.d0 vmax=0.d0 DO 100 I=1,NEQ t=abs(v(i)*wt(i)) C If a component will have a square .gt. sqrt(huge) then C shift to a scaled version of the norm. if(t .gt. H) GO TO 110 sum=sum+t**2 vmax=max(vmax, t) 100 CONTINUE C May have a damaging underflow here. If vmax = 0 then C vector was flat zero. If sum of squares is .le. tiny/epsilon C then underflows (set to zero) may hurt accuracy. So C shift to a scaled version of the norm. I=NEQ+1 if(sum .le. G .and. vmax .gt. 0.D0) GO TO 110 ddasnm=sqrt(sum/neq) return 110 CONTINUE DDASNM = 0.0D0 C Can start loop at I since the first I-1 components have C been scanned for the max abs already. DO 10 L = I,NEQ IF(ABS(V(L)*WT(L)) .GT. VMAX) VMAX = ABS(V(L)*WT(L)) 10 CONTINUE IF(VMAX .LE. 0.0D0) GO TO 30 SUM = 0.0D0 DO 20 I = 1,NEQ 20 SUM = SUM + ((V(I)*WT(I))/VMAX)**2 DDASNM = VMAX*SQRT(SUM/NEQ) 30 CONTINUE RETURN c -----END OF FUNCTION DDASNM------ END
namespace Foo export data A = B | C namespace Bar export data A = D | E
%% IMAGE_SCRIPT is a script to call IMAGE_FUN. % % Discussion: % % The BATCH command runs scripts, not functions. So we have to write % this short script if we want to work with BATCH! % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 28 March 2010 % % Author: % % John Burkardt % fprintf ( 1, '\n' ); fprintf ( 1, 'IMAGE_SCRIPT\n' ); fprintf ( 1, ' Filter an image using 3 workers\n' ); [ x, y, z ] = image_fun ( );
[STATEMENT] theorem iu_condition_imply_secure: assumes RUC: "ref_union_closed P" and IU: "weakly_future_consistent P I D (rel_ipurge P I D)" shows "secure P I D" [PROOF STATE] proof (prove) goal (1 subgoal): 1. secure P I D [PROOF STEP] proof (simp add: secure_def futures_def, (rule allI)+, rule impI, erule conjE) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>xs y ys Y zs Z. \<lbrakk>(xs @ y # ys, Y) \<in> failures P; (xs @ zs, Z) \<in> failures P\<rbrakk> \<Longrightarrow> (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] fix xs y ys Y zs Z [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>xs y ys Y zs Z. \<lbrakk>(xs @ y # ys, Y) \<in> failures P; (xs @ zs, Z) \<in> failures P\<rbrakk> \<Longrightarrow> (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] assume A: "(xs @ y # ys, Y) \<in> failures P" and B: "(xs @ zs, Z) \<in> failures P" [PROOF STATE] proof (state) this: (xs @ y # ys, Y) \<in> failures P (xs @ zs, Z) \<in> failures P goal (1 subgoal): 1. \<And>xs y ys Y zs Z. \<lbrakk>(xs @ y # ys, Y) \<in> failures P; (xs @ zs, Z) \<in> failures P\<rbrakk> \<Longrightarrow> (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] show "(xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P" (is "?P \<and> ?Q") [PROOF STATE] proof (prove) goal (1 subgoal): 1. (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] proof [PROOF STATE] proof (state) goal (2 subgoals): 1. (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P 2. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] show ?P [PROOF STATE] proof (prove) goal (1 subgoal): 1. (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P [PROOF STEP] using RUC and IU and A [PROOF STATE] proof (prove) using this: ref_union_closed P weakly_future_consistent P I D (rel_ipurge P I D) (xs @ y # ys, Y) \<in> failures P goal (1 subgoal): 1. (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P [PROOF STEP] by (rule iu_condition_imply_secure_1) [PROOF STATE] proof (state) this: (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] have "((xs @ [y]) @ ys, Y) \<in> failures P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((xs @ [y]) @ ys, Y) \<in> failures P [PROOF STEP] using A [PROOF STATE] proof (prove) using this: (xs @ y # ys, Y) \<in> failures P goal (1 subgoal): 1. ((xs @ [y]) @ ys, Y) \<in> failures P [PROOF STEP] by simp [PROOF STATE] proof (state) this: ((xs @ [y]) @ ys, Y) \<in> failures P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] hence "(xs @ [y], {}) \<in> failures P" [PROOF STATE] proof (prove) using this: ((xs @ [y]) @ ys, Y) \<in> failures P goal (1 subgoal): 1. (xs @ [y], {}) \<in> failures P [PROOF STEP] by (rule process_rule_2_failures) [PROOF STATE] proof (state) this: (xs @ [y], {}) \<in> failures P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] hence "xs @ [y] \<in> traces P" [PROOF STATE] proof (prove) using this: (xs @ [y], {}) \<in> failures P goal (1 subgoal): 1. xs @ [y] \<in> traces P [PROOF STEP] by (rule failures_traces) [PROOF STATE] proof (state) this: xs @ [y] \<in> traces P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] with RUC and IU [PROOF STATE] proof (chain) picking this: ref_union_closed P weakly_future_consistent P I D (rel_ipurge P I D) xs @ [y] \<in> traces P [PROOF STEP] show ?Q [PROOF STATE] proof (prove) using this: ref_union_closed P weakly_future_consistent P I D (rel_ipurge P I D) xs @ [y] \<in> traces P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] using B [PROOF STATE] proof (prove) using this: ref_union_closed P weakly_future_consistent P I D (rel_ipurge P I D) xs @ [y] \<in> traces P (xs @ zs, Z) \<in> failures P goal (1 subgoal): 1. (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P [PROOF STEP] by (rule iu_condition_imply_secure_2) [PROOF STATE] proof (state) this: (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (xs @ ipurge_tr I D (D y) ys, ipurge_ref I D (D y) ys Y) \<in> failures P \<and> (xs @ y # ipurge_tr I D (D y) zs, ipurge_ref I D (D y) zs Z) \<in> failures P goal: No subgoals! [PROOF STEP] qed
Several songs from the soundtrack were included in the annual <unk> <unk> list of top filmi songs . " Mehbooba <unk> " was listed at No. 24 on the 1975 list , and at No. 6 on the 1976 list . " Koi <unk> " was listed at No. 30 in 1975 , and No. 20 in 1976 . " Yeh Dosti " was listed at No. 9 in 1976 . Despite the soundtrack 's success , at the time , the songs from Sholay attracted less attention than the film 's dialogue — a rarity for Bollywood . The producers were thus prompted to release records with only dialogue . Taken together , the album sales totalled an unprecedented 500 @,@ 000 units , and became one of the top selling Bollywood soundtracks of the 1970s .
(* correct failure of injection/discriminate on types whose inductive status derives from the substitution of an argument *) Inductive t : nat -> Type := | M : forall n: nat, nat -> t n. Lemma eq_t : forall n n' m m', existT (fun B : Type => B) (t n) (M n m) = existT (fun B : Type => B) (t n') (M n' m') -> True. Proof. intros. injection H. intro Ht. exact I. Qed. Lemma eq_t' : forall n n' : nat, existT (fun B : Type => B) (t n) (M n 0) = existT (fun B : Type => B) (t n') (M n' 1) -> True. Proof. intros. discriminate H || exact I. Qed.
%% OpenMAS Object Class Diagnotistic tool (OMAS_objectDiagnostics.m) %%%%%% % This function is designed to preform a batch analysis of the complete % class library to verify their development status for simulation. function [issueCount] = OMAS_objectDiagnostics(varargin) % Input sanity check assert(numel(varargin) <= 2,'Please provide an object to test, or nothing to test all objects in the "objects" directory.'); % Generate the path to the model directory phaseStr = 'DIAGNOSTICS'; outputFileName = 'object-diagnostics.xlsx'; repoPath = mfilename('fullpath'); % Get the system paths ind = strfind(repoPath,'env'); repoPath = repoPath(1:(ind-1)); objectsDir = [repoPath,'objects']; outputFile = [repoPath,outputFileName]; tempDir = OMAS_system.GetOSPathString([repoPath,'temp']); % DETERMINE THE INPUTS switch numel(varargin) case 1 % Assume named model targetFiles = varargin(1); case 0 % Assume all models targetFiles = dir([objectsDir,'\*.m']); targetFiles = {targetFiles.name}'; otherwise error('Please provide a model name, or no input.'); end fprintf('[%s]\t%d object behaviours found, evaluating...\n',phaseStr,numel(targetFiles)); % Handle file I/O fclose('all'); % Release any file handle if exist(outputFile,'file') delete(outputFile); % Delete output file end % Prepare the diagnostic header headerArray = {'model #','file name','class',... 'build status','build message',... 'OMAS status','OMAS message',... 'notes'}; % Check if file is active try % Try to write the header to the file xlswrite(outputFile,headerArray); catch writeError warning('Unable to write to diagnostic file, is it open?'); rethrow(writeError); end % Container for model error status statusArray = false(numel(targetFiles),1); summaryArray = cell(numel(targetFiles),numel(headerArray)); % ///////////////// MOVE THROUGH THE MODELS /////////////////// for i = 1:numel(targetFiles) % For clarity fprintf('[%s]\tEvaluating model "%s"...\n',phaseStr,targetFiles{i}); % Preform diagnostic routine on selected model [entry,statusArray(i)] = GetObjectEvaluation(phaseStr,tempDir,targetFiles{i}); % For clarity fprintf('[%s]\tEvaluation for model "%s" complete.\n\n',phaseStr,targetFiles{i}); close all; % Terminate all open figures summaryArray(i,:) = [num2str(i),entry]; % Append the test number end % ///////////////////////////////////////////////////////////// issueCount = sum(statusArray); % Simply confirm if there are any issues % Write data to the output .xlsx file xlswrite(outputFile,[headerArray;summaryArray]); fclose('all'); % Release any file handle % Delete temporary directory try rmdir(tempDir,'s'); catch warning('There was a problem deleting the temporary file.'); end % Pass statistics errorNumber = sum(statusArray == 0); successNumber = sum(statusArray == 1); % Summary string fprintf('[%s]\tDiagnostics complete, %d object errors, %d objects working correctly.\n',phaseStr,errorNumber,successNumber); end % Compute the evaluation of the provided object file function [entryArray,isSuccessful] = GetObjectEvaluation(phaseStr,tempDir,fileName) % Input sanity check assert(ischar(fileName),'The model name must be given as a string.'); % Remove the .m from the file-name for evaluation if contains(fileName,'.m') fileName = strrep(fileName,'.m',''); % Remove extension if necessary end % Containers sim_steps = 5; sim_dt = 0.25; failString = 'FAILED'; passString = 'PASSED'; importStatus = 0; simStatus = 0; isSuccessful = 0; % Create row for output .csv entryArray = repmat({'-'},1,7); entryArray{1} = fileName; entryArray{2} = 'N/a'; % //////////// ATTEMPT TO INSTANTIATE THE MODEL /////////////// % CREATE THE OBJECT SET objectNumber = 2; objectIndex = cell(objectNumber,1); try for j = 1:objectNumber objectIndex{j} = eval(fileName); % Attempt to construct the object end importStatus = 1; catch instantiationError warning(instantiationError.message); entryArray{3} = failString; entryArray{4} = instantiationError.message; end % ///////////////////////////////////////////////////////////// % Check instantiation was successful if ~importStatus fprintf('[%s]\t%s(1) - Object "%s" failed to be instantiated.\n',phaseStr,failString,fileName); return end fprintf('[%s]\t%s(1) - Object "%s" instantiated.\n',phaseStr,passString,fileName); % Lift basic model parameters entryArray{2} = class(objectIndex{1}); entryArray{3} = passString; % ////////// IF THE OBJECT CAN BE SIMULATED, ATTEMPT SIMULATION /////////// fprintf('[%s]\tSimulating object "%s"\n',phaseStr,fileName); try OMAS_initialise(... 'objects',objectIndex,... 'duration',sim_steps*sim_dt,... 'dt',sim_dt,... 'idleTimeOut',0.5,... 'figures','None',... 'verbosity',0,... 'outputPath',tempDir); simStatus = 1; catch simError warning(simError.message); entryArray{5} = failString; entryArray{6} = simError.message; notes = strcat('[function] -> ',simError.stack(1).name); entryArray{7} = strcat(notes,' [line] -> ',num2str(simError.stack(1).line)); end % ///////////////////////////////////////////////////////////////////////// % Check simulation was successful if ~simStatus fprintf('[%s]\t%s(2) - Model "%s" failed simulation test\n.',phaseStr,failString,fileName); return end fprintf('[%s]\t%s(2) - Model "%s" simulated successfully.\n',phaseStr,passString,fileName); % Indicate simulation was successful entryArray{5} = passString; % Indicate that if there where no errors isSuccessful = 1; end
subroutine a(arr) integer:: arr(10) integer::i arr(1) = 10 do i = 1, 10 arr(i) = 1 return end do arr(2) = 20 end subroutine a program vin integer::arr(10) call a(arr) print *, arr(1) end program vin
// // This file is part of the libWetCloth open source project // // The code is licensed solely for academic and non-commercial use under the // terms of the Clear BSD License. The terms of the Clear BSD License are // provided below. Other licenses may be obtained by contacting the faculty // of the Columbia Computer Graphics Group or a Columbia University licensing officer. // // We would like to hear from you if you appreciate this work. // // The Clear BSD License // // Copyright 2018 Yun (Raymond) Fei, Christopher Batty, Eitan Grinspun, and Changxi Zheng // // Redistribution and use in source and binary forms, with or without // modification, are permitted (subject to the limitations in the disclaimer // below) provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS // LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. #include <Eigen/StdVector> #include <cmath> #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <sys/stat.h> #include <tclap/CmdLine.h> #ifdef WIN32 #include <direct.h> #ifndef GL_MULTISAMPLE_ARB #define GL_MULTISAMPLE_ARB 0x809D #endif #ifndef GL_MULTISAMPLE_FILTER_HINT_NV #define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 #endif #endif #include "TwoDScene.h" #include "Force.h" #include "TwoDSceneXMLParser.h" #include "TwoDSceneSerializer.h" #include "StringUtilities.h" #include "MathDefs.h" #include "TimingUtilities.h" #include "Camera.h" #ifdef RENDER_ENABLED #include "TwoDimensionalDisplayController.h" #include "TwoDSceneRenderer.h" #include "RenderingUtilities.h" #include "YImage.h" #include <AntTweakBar.h> #endif #include "ParticleSimulation.h" /////////////////////////////////////////////////////////////////////////////// // Contains the actual simulation, renderer, parser, and serializer std::shared_ptr<ParticleSimulation> g_executable_simulation = NULL; /////////////////////////////////////////////////////////////////////////////// // Rendering State bool g_rendering_enabled = true; double g_sec_per_frame; double g_last_time = timingutils::seconds(); renderingutils::Color g_bgcolor(1.0,1.0,1.0); /////////////////////////////////////////////////////////////////////////////// // SVG Rendering State /////////////////////////////////////////////////////////////////////////////// // Parser state std::string g_xml_scene_file; std::string g_description; std::string g_scene_tag = ""; /////////////////////////////////////////////////////////////////////////////// // Scene input/output/comparison state int g_save_to_binary = 0; std::string g_binary_file_name; std::ofstream g_binary_output; std::string g_short_file_name; /////////////////////////////////////////////////////////////////////////////// // Simulation state int g_dump_png = 0; bool g_paused = true; scalar g_dt = 0.0; int g_num_steps = 0; int g_current_step = 0; /////////////////////////////////////////////////////////////////////////////// // Simulation functions void miscOutputCallback(); void dumpPNG(const std::string &filename); void stepSystem() { g_executable_simulation->stepSystem(g_dt); g_current_step++; // Execute the user-customized output callback miscOutputCallback(); // Determine if the simulation is complete if( g_current_step >= g_num_steps ) { std::cout << "Complete Simulation! Enter time to continue (exit with 0): " << std::endl; double new_time = 0.0; std::cin >> new_time; g_num_steps += ceil(new_time / g_dt); if(new_time < g_dt) g_paused = true; } } void syncScene() { } void headlessSimLoop() { while(true) { while( g_current_step <= g_num_steps ) { stepSystem(); } std::cout << "Complete Simulation! Enter time to continue (exit with 0): " << std::endl; double new_time = 0.0; std::cin >> new_time; if(new_time < g_dt) break; g_num_steps += ceil(new_time / g_dt); } } #ifdef RENDER_ENABLED void dumpPNGsubprog(YImage* image, char* fnstr) { image->flip(); image->save(fnstr); delete image; delete fnstr; } /////////////////////////////////////////////////////////////////////////////// // Rendering and UI functions void dumpPNG(const std::string &filename) { YImage* image = new YImage; char* fnstr = new char[filename.length() + 1]; strcpy(fnstr, filename.data()); image->resize(g_executable_simulation->getWindowWidth(), g_executable_simulation->getWindowHeight()); glFinish(); glPixelStorei(GL_PACK_ALIGNMENT, 4); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); glReadBuffer(GL_BACK); glFinish(); glReadPixels(0, 0, g_executable_simulation->getWindowWidth(), g_executable_simulation->getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, image->data()); std::thread t(std::bind(dumpPNGsubprog, image, fnstr)); t.detach(); } void reshape( int w, int h ) { TwWindowSize(w, h); g_executable_simulation->reshape(w, h); assert( renderingutils::checkGLErrors() ); } // TODO: Move these functions to scene renderer? void setOrthographicProjection() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, g_executable_simulation->getWindowWidth(), 0, g_executable_simulation->getWindowHeight()); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); assert( renderingutils::checkGLErrors() ); } void renderBitmapString( float x, float y, float z, void *font, std::string s ) { glRasterPos3f(x, y, z); for( std::string::iterator i = s.begin(); i != s.end(); ++i ) { char c = *i; glutBitmapCharacter(font, c); } assert( renderingutils::checkGLErrors() ); } void drawHUD() { setOrthographicProjection(); glColor3f(1.0-g_bgcolor.r,1.0-g_bgcolor.g,1.0-g_bgcolor.b); renderBitmapString( 4, g_executable_simulation->getWindowHeight()-20, 0.0, GLUT_BITMAP_HELVETICA_18, stringutils::convertToString(g_current_step*g_dt) ); renderBitmapString( 4, g_executable_simulation->getWindowHeight()-50, 0.0, GLUT_BITMAP_HELVETICA_18, std::string("Camera [") + stringutils::convertToString(g_executable_simulation->currentCameraIndex()) + std::string("]") ); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); TwDraw(); assert( renderingutils::checkGLErrors() ); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); assert( renderingutils::checkGLErrors() ); assert( g_executable_simulation != NULL ); g_executable_simulation->renderSceneOpenGL(g_dt); drawHUD(); glutSwapBuffers(); assert( renderingutils::checkGLErrors() ); } void keyboard( unsigned char key, int x, int y ) { if( TwEventKeyboardGLUT(key, x, y) ) { glutPostRedisplay(); return; } g_executable_simulation->keyboard(key,x,y); if( key == 27 || key == 'q' ) { TwTerminate(); exit(0); } else if( key == 's' || key =='S' ) { stepSystem(); glutPostRedisplay(); } else if( key == ' ' ) { g_paused = !g_paused; } else if( key == 'c' || key == 'C' ) { g_executable_simulation->centerCamera(); glutPostRedisplay(); } else if( key == 'a' || key == 'A') { g_executable_simulation->printDDA(); } assert( renderingutils::checkGLErrors() ); } // Proccess 'special' keys void special( int key, int x, int y ) { if( TwEventSpecialGLUT(key, x, y) ) { glutPostRedisplay(); return; } g_executable_simulation->special(key,x,y); assert( renderingutils::checkGLErrors() ); } void mouse( int button, int state, int x, int y ) { if( TwEventMouseButtonGLUT(button, state, x, y) ) { glutPostRedisplay(); return; } g_executable_simulation->mouse(button,state,x,y); assert( renderingutils::checkGLErrors() ); } void motion( int x, int y ) { if( TwEventMouseMotionGLUT(x, y) ) { glutPostRedisplay(); return; } g_executable_simulation->motion(x,y); assert( renderingutils::checkGLErrors() ); } void idle() { //std::cout << "g_last_time: " << g_last_time << std::endl; // Trigger the next timestep double current_time = timingutils::seconds(); //std::cout << "current_time: " << current_time << std::endl; //std::cout << "g_sec_per_frame: " << g_sec_per_frame << std::endl; if( !g_paused && current_time-g_last_time >= g_sec_per_frame ) { g_last_time = current_time; stepSystem(); glutPostRedisplay(); } assert( renderingutils::checkGLErrors() ); } void initializeOpenGLandGLUT( int argc, char** argv ) { // Initialize GLUT glutInit(&argc,argv); //glutInitDisplayString("rgba stencil=8 depth=24 samples=4 hidpi"); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE | GLUT_DEPTH); int scrwidth = glutGet(GLUT_SCREEN_WIDTH); int scrheight = glutGet(GLUT_SCREEN_HEIGHT); int factor = std::min(scrwidth / 320, scrheight / 180); scrwidth = factor * 320; scrheight = factor * 180; /*#ifdef __APPLE__ scrwidth *= 2; scrheight *= 2; #endif*/ g_executable_simulation->setWindowWidth(scrwidth); g_executable_simulation->setWindowHeight(scrheight); glutInitWindowSize(g_executable_simulation->getWindowWidth(),g_executable_simulation->getWindowHeight()); glutCreateWindow("libWetCloth: A Multi-Scale Model for Liquid-Fabric Interactions"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutSpecialFunc(special); glutMouseFunc(mouse); glutMotionFunc(motion); glutIdleFunc(idle); glEnable(GL_MULTISAMPLE_ARB); glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST); TwInit(TW_OPENGL, NULL); TwGLUTModifiersFunc(glutGetModifiers); // Initialize OpenGL reshape(scrwidth,scrheight); glClearColor(g_bgcolor.r, g_bgcolor.g, g_bgcolor.b, 1.0); glEnable(GL_BLEND); glEnable(GL_POLYGON_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); GLubyte halftone[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55}; glPolygonStipple(halftone); g_executable_simulation->initializeOpenGLRenderer(); assert( renderingutils::checkGLErrors() ); } #endif /////////////////////////////////////////////////////////////////////////////// // Parser functions void loadScene( const std::string& file_name ) { // Maximum time in the simulation to run for. This has nothing to do with run time, cpu time, etc. This is time in the 'virtual world'. scalar max_time; // Maximum frequency, in wall clock time, to execute the simulation for. This serves as a cap for simulations that run too fast to see a solution. scalar steps_per_sec_cap = 100.0; // Contains the center and 'scale factor' of the view renderingutils::Viewport view; // Load the simulation and pieces of rendring and UI state assert( g_executable_simulation == NULL ); TwoDSceneXMLParser xml_scene_parser; bool cam_init = false; Camera cam; xml_scene_parser.loadExecutableSimulation( file_name, g_rendering_enabled, g_executable_simulation, cam, g_dt, max_time, steps_per_sec_cap, g_bgcolor, g_description, g_scene_tag, cam_init, g_binary_file_name ); assert( g_executable_simulation != NULL ); // If the user did not request a custom viewport, try to compute a reasonable default. if( !cam_init ) { g_executable_simulation->centerCamera(false); } // Otherwise set the viewport per the user's request. else { g_executable_simulation->setCamera(cam); } g_executable_simulation->finalInit(); // To cap the framerate, compute the minimum time a single timestep should take g_sec_per_frame = 1.0/steps_per_sec_cap; // Integer number of timesteps to take g_num_steps = ceil(max_time/g_dt); // We begin at the 0th timestep g_current_step = 0; } void parseCommandLine( int argc, char** argv ) { try { TCLAP::CmdLine cmd("A Multi-Scale Model for Simulating Liquid-Fabric Interactions"); // XML scene file to load TCLAP::ValueArg<std::string> scene("s", "scene", "Simulation to run; an xml scene file", true, "", "string", cmd); // Begin the scene paused or running TCLAP::ValueArg<bool> paused("p", "paused", "Begin the simulation paused if 1, running if 0", false, true, "boolean", cmd); // Run the simulation with rendering enabled or disabled TCLAP::ValueArg<bool> display("d", "display", "Run the simulation with display enabled if 1, without if 0", false, true, "boolean", cmd); // Begin the scene paused or running TCLAP::ValueArg<int> dumppng("g", "generate", "Generate PNG if 1, not if 0", false, 0, "integer", cmd); // These cannot be set at the same time // File to save output to TCLAP::ValueArg<int> output("o", "outputfile", "Binary file to save simulation state to", false, 0, "integer", cmd); // File to load for comparisons TCLAP::ValueArg<std::string> input("i", "inputfile", "Binary file to load simulation pos from", false, "", "string", cmd); cmd.parse(argc, argv); assert( scene.isSet() ); g_xml_scene_file = scene.getValue(); g_paused = paused.getValue(); g_rendering_enabled = display.getValue(); g_dump_png = dumppng.getValue(); g_save_to_binary = output.getValue(); g_binary_file_name = input.getValue(); } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.what() << std::endl; exit(1); } } void cleanupAtExit() { } std::ostream& main_header( std::ostream& stream ) { stream << outputmod::startgreen << ".__ ._____. __ __ __ _________ .__ __ .__ \n" << "| | |__\\_ |__/ \\ / \\ _____/ |_\\_ ___ \\| | _____/ |_| |__ \n" << "| | | || __ \\ \\/\\/ _/ __ \\ __/ \\ \\/| | / _ \\ __| | \\ \n" << "| |_| || \\_\\ \\ /\\ ___/| | \\ \\___| |_( <_> | | | Y \\\n" << "|____|__||___ /\\__/\\ / \\___ |__| \\______ |____/\\____/|__| |___| /\n" << " \\/ \\/ \\/ \\/ \\/ " << outputmod::endgreen << std::endl; return stream; } std::ofstream g_debugoutput; void miscOutputCallback() { // If the user wants to save output to a binary if( g_save_to_binary && !(g_current_step % g_save_to_binary) && g_current_step <= g_num_steps ) { std::stringstream oss_cloth; oss_cloth << g_short_file_name << "/cloth" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; std::stringstream oss_hairs; oss_hairs << g_short_file_name << "/hair" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; std::stringstream oss_fluid; oss_fluid << g_short_file_name << "/fluid" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; std::stringstream oss_inbd; oss_inbd << g_short_file_name << "/internal" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; std::stringstream oss_exbd; oss_exbd << g_short_file_name << "/external" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; std::stringstream oss_spring; oss_spring << g_short_file_name << "/spring" << std::setw(5) << std::setfill('0') << (g_current_step / g_save_to_binary) << ".obj"; g_executable_simulation->serializeScene(oss_cloth.str(), oss_hairs.str(), oss_fluid.str(), oss_inbd.str(), oss_exbd.str(), oss_spring.str()); } // Update the state of the renderers #ifdef RENDER_ENABLED if( g_rendering_enabled ) g_executable_simulation->updateOpenGLRendererState(); // If comparing simulations, load comparison scene's equivalent step // If the user wants to generate a PNG movie if( g_dump_png && !(g_current_step % g_dump_png) ) { std::stringstream oss; oss << g_short_file_name << "/frame" << std::setw(5) << std::setfill('0') << (g_current_step / g_dump_png) << ".png"; dumpPNG(oss.str()); oss.clear(); } #endif } int main( int argc, char** argv ) { Eigen::initParallel(); Eigen::setNbThreads(std::thread::hardware_concurrency()); srand(0x0108170F); // Parse command line arguments parseCommandLine( argc, argv ); std::vector<std::string> pathes; stringutils::split(g_xml_scene_file, '/', pathes); std::vector<std::string> path_first; stringutils::split(pathes[pathes.size() - 1], '.', path_first); g_short_file_name = path_first[0]; #ifdef WIN32 _mkdir(g_short_file_name.c_str()); #else mkdir(g_short_file_name.c_str(), 0777); #endif // Function to cleanup at progarm exit atexit(cleanupAtExit); // Load the user-specified scene loadScene(g_xml_scene_file); // If requested, open the input file for the scene to benchmark #ifdef RENDER_ENABLED // Initialization for OpenGL and GLUT if( g_rendering_enabled ) initializeOpenGLandGLUT(argc,argv); #endif // Print a header std::cout << main_header << std::endl; #ifdef CMAKE_BUILD_TYPE std::cout << outputmod::startblue << "Build type: " << outputmod::endblue << CMAKE_BUILD_TYPE << std::endl; #endif #ifdef EIGEN_VECTORIZE std::cout << outputmod::startblue << "Vectorization: " << outputmod::endblue << "Enabled" << std::endl; #else std::cout << outputmod::startblue << "Vectorization: " << outputmod::endblue << "Disabled" << std::endl; #endif std::cout << outputmod::startblue << "Scene: " << outputmod::endblue << g_xml_scene_file << std::endl; std::cout << outputmod::startblue << "Integrator: " << outputmod::endblue << g_executable_simulation->getSolverName() << std::endl; std::cout << outputmod::startblue << "Global Parameters: " << outputmod::endblue << std::endl << g_executable_simulation->getLiquidInfo() << std::endl; #ifdef RENDER_ENABLED if( g_rendering_enabled ) glutMainLoop(); else headlessSimLoop(); #else headlessSimLoop(); #endif return 0; }
function test06 ( dim_num, level_max ) %*****************************************************************************80 % %% TEST06 creates a sparse Clenshaw-Curtis grid and writes it to a file. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 11 August 2009 % % Author: % % John Burkardt % % Parameters: % % Input, integer DIM_NUM, the spatial dimension. % % Input, integer LEVEL_MAX, the level. % fprintf ( 1, '\n' ); fprintf ( 1, 'TEST06:\n' ); fprintf ( 1, ' SPARSE_GRID_CC makes a sparse Clenshaw-Curtis grid.\n' ); fprintf ( 1, ' Write the data to a set of quadrature files.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' LEVEL_MAX = %d\n', level_max ); fprintf ( 1, ' Spatial dimension DIM_NUM = %d\n', dim_num ); % % Determine the number of points. % point_num = sparse_grid_cfn_size ( dim_num, level_max ); r(1:dim_num,1) = -1.0; r(1:dim_num,2) = +1.0; % % Compute the weights and points. % [ w, x ] = sparse_grid_cc ( dim_num, level_max, point_num ); % % Write the data out. % r_filename = sprintf ( 'cc_d%d_level%d_r.txt', dim_num, level_max ); w_filename = sprintf ( 'cc_d%d_level%d_w.txt', dim_num, level_max ); x_filename = sprintf ( 'cc_d%d_level%d_x.txt', dim_num, level_max ); r8mat_write ( r_filename, dim_num, 2, r ); r8mat_write ( w_filename, 1, point_num, w ); r8mat_write ( x_filename, dim_num, point_num, x ); fprintf ( 1, '\n' ); fprintf ( 1, ' R data written to "%s".\n', r_filename ); fprintf ( 1, ' W data written to "%s".\n', w_filename ); fprintf ( 1, ' X data written to "%s",\n', x_filename ); return end
module Issue470 where data Bool : Set where true false : Bool _and_ : Bool → Bool → Bool true and x = x false and x = false infixr 5 _∷_ data Foo : Bool → Set where [] : Foo true _∷_ : ∀ {b} (x : Bool) → Foo b → Foo (x and b) Baz : Bool → Set Baz true = Bool Baz false = Foo false data Bar : ∀ {b} → Foo b → Set where [] : Bar [] _∷_ : ∀ {b} {foo : Foo b} {x} (g : Baz x) → (bar : Bar foo) → Bar (x ∷ foo) foo : Foo false foo = false ∷ true ∷ [] bar : Bar foo bar = (false ∷ []) ∷ false ∷ [] -- ← is yellow {- _59 := _55 ∷ false ∷ [] [blocked by problem 75] [75] ["apply" (_53 ∷ true ∷ [])] == ["apply" (false ∷ true ∷ [])] : Foo (_53 and (true and true)) → Set [blocked by problem 76] [76] (_53 and (true and true)) = false : Bool _54 := false ∷ [] :? Baz _53 -}
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract camera serial number from Voyager flight label. subroutine vgrlab_cam(lab,cam) implicit none character*7200 lab !input Voyager flight label integer*4 cam !output camera serial number (4-7) integer*4 i integer*4 sc_id,camera_id integer*4 camera_sn(2,2)/7,6, !VGR1 NA,WA & 5,4/ !VGR2 NA,WA call vgrlab_sc_id(lab,sc_id) call vgrlab_camera_id(lab,camera_id) if (sc_id.eq.-999 .or. camera_id.eq.-999) then cam = -999 else cam = camera_sn(camera_id,sc_id) endif return end cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract spacecraft ID from Voyager flight label. subroutine vgrlab_sc_id(lab,sc_id) implicit none character*7200 lab !input Voyager flight label integer*4 sc_id ! 1=VGR-1, 2=VGR-2 integer*4 i sc_id = -999 i = index(lab(1:),'VGR-1') if (i.ne.0) then sc_id = 1 !Voyager 1 else i = index(lab(1:),'VGR-2') if (i.ne.0) sc_id=2 endif return end cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract camera id from Voyager flight label. subroutine vgrlab_camera_id(lab,camera_id) implicit none character*7200 lab !input Voyager flight label integer*4 camera_id ! 1=NA, 2=WA integer*4 i camera_id = -999 i = index(lab(1:),'NA CAMERA') if (i.ne.0) then camera_id = 1 !narrow angle else i = index(lab(1:),'WA CAMERA') if (i.ne.0) camera_id=2 endif return end cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract FDS count from Voyager flight label. c subroutine vgrlab_fds(lab,fds) implicit none character*7200 lab !Voyager flight label (input) integer*4 fds !FDS count (output) integer*4 i,mod16,mod60 c note: the FDS is returned as an integer as 100*mod16 + mod60 c Example: FDS 16368.32 is returened as 1636832 i = index(lab(1:),' FDS ') if (i.ne.0 .and. lab(i+5:i+5).ne.'*') then read(lab(i+5:),'(bn,i5)') mod16 read(lab(i+11:),'(bn,i2)') mod60 fds = 100*mod16 + mod60 else fds = -999 endif return end cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract filter, gain, scan rate, operating mode, and exposure time c from Voyager flight label. subroutine vgrlab_camparams(lab,filter,gain,scan,mode,t) implicit none c ...input argument character*7200 lab !Voyager flight label c ...output arguments integer*4 filter !filter position (0-7) integer*4 gain !0=low gain, 1=high gain integer*4 scan !scan rate: 1, 2, 3, 5, 10 integer*4 mode !operating mode real*4 t !exposure time in milliseconds integer*4 i filter = -999 gain = -999 scan = -999 mode = -999 t = -999. i = index(lab(1:),' FILT ') !example: FILT 0(CLEAR) if (i.ne.0 .and. lab(i+6:i+6).ne.'*') & read(lab(i+6:),'(bn,i1)') filter if (index(lab(1:),' LO GAIN').gt.0) then gain = 0 elseif (index(lab(1:),' HI GAIN ').gt.0) then gain = 1 endif i = index(lab(1:),' SCAN RATE') !example: SCAN RATE 10:1 if (i.ne.0 .and. lab(i+12:i+12) .ne. '*') & read(lab(i+12:),'(bn,i2)') scan i = index(lab(1:),' MODE') !example: MODE 4(BOTALT) if (i.ne.0 .and. lab(i+6:i+6).ne.'*') & read (lab(i+6:),'(bn,i1)') mode i = index(lab(1:),' EXP ') !example: EXP 00360.0 MSEC if (i.ne.0 .and. lab(i+5:i+5).ne.'*') & read(lab(i+5:),'(bn,f7.0)') t return end ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Extract PICNO from Voyager flight label. c subroutine vgrlab_picno(lab,picno,ind1) implicit none character*7200 lab !Voyager flight label (input) character*10 picno !picno='xxxxPS+DDD' (output) integer*4 ind1 integer*4 i i = index(lab(1:),' PICNO ') !Example: PICNO 0548J1-001 if (i.gt.0 .and. lab(i+7:i+7).ne.'X' + .and. lab(i+7:i+7).ne.'*') then picno = lab(i+7:i+16) else ind1 = -1 endif return end
# -*- coding: utf-8 -*- """ Created on Tue Jul 23 11:25:33 2019 @author: ntr002 """ import WaPOR import requests import os from WaPOR import GIS_functions as gis import numpy as np import datetime np.warnings.filterwarnings('ignore') def main(Dir, data='RET', Startdate='2009-01-01', Enddate='2018-12-31', latlim=[-40.05, 40.05], lonlim=[-30.5, 65.05],level=1, version = 2, Waitbar = 1,cached_catalog=True): """ This function downloads WaPOR daily data. Keyword arguments: Dir -- 'C:/file/to/path/' Startdate -- 'yyyy-mm-dd' Enddate -- 'yyyy-mm-dd' latlim -- [ymin, ymax] (values must be between -40.05 and 40.05) lonlim -- [xmin, xmax] (values must be between -30.05 and 65.05) cached_catalog -- True Use a cached catalog. False Load a new catalog from the database """ print(f'\nDownload WaPOR Level {level} daily {data} data for the period {Startdate} till {Enddate}') # Download data WaPOR.API.version=version catalog=WaPOR.API.getCatalog(cached=cached_catalog) bbox=[lonlim[0],latlim[0],lonlim[1],latlim[1]] if level==1: cube_code=f"L1_{data}_E" else: print('Invalid Level') try: cube_info=WaPOR.API.getCubeInfo(cube_code) multiplier=cube_info['measure']['multiplier'] except: print('ERROR: Cannot get cube info. Check if WaPOR version has cube %s'%(cube_code)) return None time_range='{0},{1}'.format(Startdate,Enddate) try: df_avail=WaPOR.API.getAvailData(cube_code,time_range=time_range) except: print('ERROR: cannot get list of available data') return None if Waitbar == 1: import WaPOR.WaitbarConsole as WaitbarConsole total_amount = len(df_avail) amount = 0 WaitbarConsole.printWaitBar(amount, total_amount, prefix = 'Progress:', suffix = 'Complete', length = 50) Dir=os.path.join(Dir,'WAPOR.v%s_daily_%s' %(version,cube_code)) if not os.path.exists(Dir): os.makedirs(Dir) for index,row in df_avail.iterrows(): ### get download url download_url=WaPOR.API.getCropRasterURL(bbox,cube_code, row['time_code'], row['raster_id'], WaPOR.API.Token, print_job=False) filename='{0}.tif'.format(row['raster_id']) outfilename=os.path.join(Dir,filename) download_file=os.path.join(Dir,'raw_{0}.tif'.format(row['raster_id'])) ### Download raster file resp=requests.get(download_url) open(download_file,'wb').write(resp.content) ### correct raster with multiplier driver, NDV, xsize, ysize, GeoT, Projection= gis.GetGeoInfo(download_file) Array = gis.OpenAsArray(download_file,nan_values=True) Array=np.where(Array<0,0,Array) #mask out flagged value -9998 CorrectedArray=Array*multiplier gis.CreateGeoTiff(outfilename,CorrectedArray, driver, NDV, xsize, ysize, GeoT, Projection) os.remove(download_file) if Waitbar == 1: amount += 1 WaitbarConsole.printWaitBar(amount, total_amount, prefix = 'Progress:', suffix = 'Complete', length = 50) return Dir
#include "Defines.hpp" // <!--set debug/test variables in this file #include <iostream> #if UNITTEST > 0 #define BOOST_TEST_MODULE Queued_logger_test_module #define BOOST_TEST_MODULE SimulatorTest #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> #endif #include "Logger/Queued_logger.hpp" #include "Logger/Log_to_file.hpp" #include "ProductionControl.hpp" #include "Network/machineNetworkHandler.hpp" #include "Factory.hpp" int main(int argc, char* argv[]) { #if UNITTEST > 0 return boost::unit_test::unit_test_main( &init_unit_test, argc, argv ); #endif try { std::cout << "\t\t !- productiestraat-spaanders -! " << std::endl; Queued_logger::get_instance().switch_logger_type( new Log_to_file("result.csv")); Queued_logger::get_instance().log(""); //TODO: logt af en toe naar terminal en af en toe naar file... Queued_logger::get_instance().log( "SIM_DAY,TIME_OF_DAY (H:M),MACHINE/BUFFER,ID,MACHINE_NAME,STATE,CURRENT_MACHINE_AMOUNT_OF_WORK,MILLISECONDS_FROM_SIM_START"); //Factory implementatie Factory f; f.startSimulation("../../Exe1/master.ini"); while (FactoryClock::getInstance()->isRunning()) { } std::this_thread::sleep_for (std::chrono::milliseconds(1000)); // TODO: zorgt ervoor dat statistics zijn weggeschreven Queued_logger::get_instance().stop(); std::cout << "Application End." << std::endl; return 0; } catch (std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; } catch (...) { std::cout << "Unknown exception caught." << std::endl; } return -1; }
Formal statement is: lemma complex_unimodular_polar: assumes "norm z = 1" obtains t where "0 \<le> t" "t < 2 * pi" "z = Complex (cos t) (sin t)" Informal statement is: If $z$ is a complex number with norm $1$, then there exists a real number $t$ such that $0 \leq t < 2\pi$ and $z = \cos(t) + i \sin(t)$.
(************************************************************************** * TLC: A library for Coq * * Option data-structure **************************************************************************) Set Implicit Arguments. From TLC Require Import LibTactics LibReflect. Generalizable Variables A. (* --TODO: find a more explicit name? *) (* ********************************************************************** *) (** * Option type *) (* ---------------------------------------------------------------------- *) (** ** Definition *) (** From the Prelude: Inductive option A : Type := | Some : A -> option A | None : option A. *) Arguments Some {A}. Arguments None {A}. (* ---------------------------------------------------------------------- *) (** ** Inhabited *) #[global] Instance Inhab_option : forall A, Inhab (option A). Proof using. intros. apply (Inhab_of_val None). Qed. (* ********************************************************************** *) (** * Operations *) (* ---------------------------------------------------------------------- *) (** ** [is_some] *) (** [is_some o] holds when [o] is of the form [Some x] *) Definition is_some A (o:option A) := match o with | None => false | Some _ => true end. (* ---------------------------------------------------------------------- *) (** ** [unsome_default] *) (** [unsome_default d o] returns the content of the option, and returns [d] in case the option in [None]. *) Definition unsome_default A d (o:option A) := match o with | None => d | Some x => x end. (* ---------------------------------------------------------------------- *) (** ** [unsome] *) (** [unsome o] returns the content of the option, and returns an arbitrary value in case the option in [None]. *) Definition unsome `{Inhab A} := unsome_default (arbitrary (A:=A)). (* ---------------------------------------------------------------------- *) (** ** [map] *) (** [map f o] takes an option and returns an option, and maps the function [f] to the content of the option if it has one. *) Definition map A B (f : A -> B) (o : option A) : option B := match o with | None => None | Some x => Some (f x) end. Lemma map_eq_none_inv : forall A B (f : A->B) o, map f o = None -> o = None. Proof using. introv H. destruct o; simpl; inverts* H. Qed. Lemma map_eq_some_inv : forall A B (f : A->B) o x, map f o = Some x -> exists z, o = Some z /\ x = f z. Proof using. introv H. destruct o; simpl; inverts* H. Qed. Arguments map_eq_none_inv [A] [B] [f] [o]. Arguments map_eq_some_inv [A] [B] [f] [o] [x]. (* ---------------------------------------------------------------------- *) (** ** [map_on] *) (* --TODO: is this really useful? *) (** [map_on o f] is the same as [map f o], only the arguments are swapped. *) Definition map_on A B (o : option A) (f : A -> B) : option B := map f o. Lemma map_on_eq_none_inv : forall A B (f : A -> B) o, map f o = None -> o = None. Proof using. introv H. destruct~ o; tryfalse. Qed. Lemma map_on_eq_some_inv : forall A B (f : A -> B) o x, map_on o f = Some x -> exists z, o = Some z /\ x = f z. Proof using. introv H. destruct o; simpl; inverts* H. Qed. Arguments map_eq_none_inv [A] [B] [f] [o]. Arguments map_on_eq_some_inv [A] [B] [f] [o] [x]. (* ---------------------------------------------------------------------- *) (** ** [apply] *) (** [apply f o] optionnaly applies a function of type [A -> option B] *) Definition apply A B (f : A->option B) (o : option A) : option B := match o with | None => None | Some x => f x end. (* ---------------------------------------------------------------------- *) (** ** [apply_on] *) (* --TODO: is this really useful? *) (** [apply_on o f] is the same as [apply f o] *) Definition apply_on A B (o : option A) (f : A->option B) : option B:= apply f o. Lemma apply_on_eq_none_inv : forall A B (f : A->option B) o, apply_on o f = None -> (o = None) \/ (exists x, o = Some x /\ f x = None). Proof using. introv H. destruct o; simpl; inverts* H. Qed. Lemma apply_on_eq_some_inv : forall A B (f : A->option B) o x, apply_on o f = Some x -> exists z, o = Some z /\ f z = Some x. Proof using. introv H. destruct o; simpl; inverts* H. Qed. Arguments apply_on_eq_none_inv [A] [B] [f] [o]. Arguments apply_on_eq_some_inv [A] [B] [f] [o] [x].
[STATEMENT] lemma sr_imp_eigen_vector_main: "sr *s u = A *v u" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sr *s u = A *v u [PROOF STEP] proof (rule ccontr) [PROOF STATE] proof (state) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] assume *: "sr *s u \<noteq> A *v u" [PROOF STATE] proof (state) this: sr *s u \<noteq> A *v u goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] let ?x = "A *v u - sr *s u" [PROOF STATE] proof (state) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] from * [PROOF STATE] proof (chain) picking this: sr *s u \<noteq> A *v u [PROOF STEP] have 0: "?x \<noteq> 0" [PROOF STATE] proof (prove) using this: sr *s u \<noteq> A *v u goal (1 subgoal): 1. A *v u - sr *s u \<noteq> 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: A *v u - sr *s u \<noteq> 0 goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] let ?y = "pow_A_1 u" [PROOF STATE] proof (state) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] have "le_vec (sr *s u) (A *v u)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. le_vec (sr *s u) (A *v u) [PROOF STEP] using rx_le_Ax[OF u] [PROOF STATE] proof (prove) using this: le_vec (r u *s u) (A *v u) goal (1 subgoal): 1. le_vec (sr *s u) (A *v u) [PROOF STEP] unfolding ru [PROOF STATE] proof (prove) using this: le_vec (sr *s u) (A *v u) goal (1 subgoal): 1. le_vec (sr *s u) (A *v u) [PROOF STEP] . [PROOF STATE] proof (state) this: le_vec (sr *s u) (A *v u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] hence le: "le_vec 0 ?x" [PROOF STATE] proof (prove) using this: le_vec (sr *s u) (A *v u) goal (1 subgoal): 1. le_vec 0 (A *v u - sr *s u) [PROOF STEP] by auto [PROOF STATE] proof (state) this: le_vec 0 (A *v u - sr *s u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] from 0 le [PROOF STATE] proof (chain) picking this: A *v u - sr *s u \<noteq> 0 le_vec 0 (A *v u - sr *s u) [PROOF STEP] have x: "?x \<in> X" [PROOF STATE] proof (prove) using this: A *v u - sr *s u \<noteq> 0 le_vec 0 (A *v u - sr *s u) goal (1 subgoal): 1. A *v u - sr *s u \<in> X [PROOF STEP] unfolding X_def [PROOF STATE] proof (prove) using this: A *v u - sr *s u \<noteq> 0 le_vec 0 (A *v u - sr *s u) goal (1 subgoal): 1. A *v u - sr *s u \<in> {x. le_vec 0 x \<and> x \<noteq> 0} [PROOF STEP] by auto [PROOF STATE] proof (state) this: A *v u - sr *s u \<in> X goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] have y_pos: "lt_vec 0 ?y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. lt_vec 0 (pow_A_1 u) [PROOF STEP] using Y_pos_main[of ?y] u [PROOF STATE] proof (prove) using this: pow_A_1 u \<in> pow_A_1 ` X \<Longrightarrow> 0 < pow_A_1 u $h ?i u \<in> X goal (1 subgoal): 1. lt_vec 0 (pow_A_1 u) [PROOF STEP] by auto [PROOF STATE] proof (state) this: lt_vec 0 (pow_A_1 u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] hence y: "?y \<in> X" [PROOF STATE] proof (prove) using this: lt_vec 0 (pow_A_1 u) goal (1 subgoal): 1. pow_A_1 u \<in> X [PROOF STEP] unfolding X_def [PROOF STATE] proof (prove) using this: lt_vec 0 (pow_A_1 u) goal (1 subgoal): 1. pow_A_1 u \<in> {x. le_vec 0 x \<and> x \<noteq> 0} [PROOF STEP] by (auto simp: order.strict_iff_order) [PROOF STATE] proof (state) this: pow_A_1 u \<in> X goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] from Y_pos_main[of "pow_A_1 ?x"] x [PROOF STATE] proof (chain) picking this: pow_A_1 (A *v u - sr *s u) \<in> pow_A_1 ` X \<Longrightarrow> 0 < pow_A_1 (A *v u - sr *s u) $h ?i A *v u - sr *s u \<in> X [PROOF STEP] have "lt_vec 0 (pow_A_1 ?x)" [PROOF STATE] proof (prove) using this: pow_A_1 (A *v u - sr *s u) \<in> pow_A_1 ` X \<Longrightarrow> 0 < pow_A_1 (A *v u - sr *s u) $h ?i A *v u - sr *s u \<in> X goal (1 subgoal): 1. lt_vec 0 (pow_A_1 (A *v u - sr *s u)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: lt_vec 0 (pow_A_1 (A *v u - sr *s u)) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] hence lt: "lt_vec (sr *s ?y) (A *v ?y)" [PROOF STATE] proof (prove) using this: lt_vec 0 (pow_A_1 (A *v u - sr *s u)) goal (1 subgoal): 1. lt_vec (sr *s pow_A_1 u) (A *v pow_A_1 u) [PROOF STEP] unfolding pow_A_1_def matrix_vector_right_distrib_diff matrix_vector_mul_assoc A1n_commute vector_smult_distrib [PROOF STATE] proof (prove) using this: lt_vec 0 (A ** A1n *v u - sr *s (A1n *v u)) goal (1 subgoal): 1. lt_vec (sr *s (A1n *v u)) (A ** A1n *v u) [PROOF STEP] by simp [PROOF STATE] proof (state) this: lt_vec (sr *s pow_A_1 u) (A *v pow_A_1 u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] let ?f = "(\<lambda> i. (A *v ?y - sr *s ?y) $ i / ?y $ i)" [PROOF STATE] proof (state) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] let ?U = "UNIV :: 'n set" [PROOF STATE] proof (state) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] define eps where "eps = Min (?f ` ?U)" [PROOF STATE] proof (state) this: eps = (MIN i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] have U: "finite (?f ` ?U)" "?f ` ?U \<noteq> {}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite (range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i)) &&& range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i) \<noteq> {} [PROOF STEP] by auto [PROOF STATE] proof (state) this: finite (range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i)) range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i) \<noteq> {} goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] have eps: "eps > 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < eps [PROOF STEP] unfolding eps_def Min_gr_iff[OF U] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Ball (range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i)) ((<) 0) [PROOF STEP] using lt sr_pos y_pos [PROOF STATE] proof (prove) using this: lt_vec (sr *s pow_A_1 u) (A *v pow_A_1 u) 0 < sr lt_vec 0 (pow_A_1 u) goal (1 subgoal): 1. Ball (range (\<lambda>i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i)) ((<) 0) [PROOF STEP] by auto [PROOF STATE] proof (state) this: 0 < eps goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] have le: "le_vec ((sr + eps) *s ?y) (A *v ?y)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. le_vec ((sr + eps) *s pow_A_1 u) (A *v pow_A_1 u) [PROOF STEP] proof [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] fix i [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] have "((sr + eps) *s ?y) $ i = sr * ?y $ i + eps * ?y $ i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((sr + eps) *s pow_A_1 u) $h i = sr * pow_A_1 u $h i + eps * pow_A_1 u $h i [PROOF STEP] by (simp add: comm_semiring_class.distrib) [PROOF STATE] proof (state) this: ((sr + eps) *s pow_A_1 u) $h i = sr * pow_A_1 u $h i + eps * pow_A_1 u $h i goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] also [PROOF STATE] proof (state) this: ((sr + eps) *s pow_A_1 u) $h i = sr * pow_A_1 u $h i + eps * pow_A_1 u $h i goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] have "\<dots> \<le> sr * ?y $ i + ?f i * ?y $ i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sr * pow_A_1 u $h i + eps * pow_A_1 u $h i \<le> sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i [PROOF STEP] proof (rule add_left_mono[OF mult_right_mono]) [PROOF STATE] proof (state) goal (2 subgoals): 1. eps \<le> (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i 2. 0 \<le> pow_A_1 u $h i [PROOF STEP] show "0 \<le> ?y $ i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 \<le> pow_A_1 u $h i [PROOF STEP] using y_pos[rule_format, of i] [PROOF STATE] proof (prove) using this: 0 $h i < pow_A_1 u $h i goal (1 subgoal): 1. 0 \<le> pow_A_1 u $h i [PROOF STEP] by auto [PROOF STATE] proof (state) this: 0 \<le> pow_A_1 u $h i goal (1 subgoal): 1. eps \<le> (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i [PROOF STEP] show "eps \<le> ?f i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eps \<le> (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i [PROOF STEP] unfolding eps_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (MIN i. (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i) \<le> (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i [PROOF STEP] by (rule Min_le, auto) [PROOF STATE] proof (state) this: eps \<le> (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: sr * pow_A_1 u $h i + eps * pow_A_1 u $h i \<le> sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] also [PROOF STATE] proof (state) this: sr * pow_A_1 u $h i + eps * pow_A_1 u $h i \<le> sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] have "\<dots> = (A *v ?y) $ i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i = (A *v pow_A_1 u) $h i [PROOF STEP] using sr_pos y_pos[rule_format, of i] [PROOF STATE] proof (prove) using this: 0 < sr 0 $h i < pow_A_1 u $h i goal (1 subgoal): 1. sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i = (A *v pow_A_1 u) $h i [PROOF STEP] by simp [PROOF STATE] proof (state) this: sr * pow_A_1 u $h i + (A *v pow_A_1 u - sr *s pow_A_1 u) $h i / pow_A_1 u $h i * pow_A_1 u $h i = (A *v pow_A_1 u) $h i goal (1 subgoal): 1. \<And>i. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] show "((sr + eps) *s ?y) $ i \<le> (A *v ?y) $ i" [PROOF STATE] proof (prove) using this: ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i goal (1 subgoal): 1. ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i [PROOF STEP] . [PROOF STATE] proof (state) this: ((sr + eps) *s pow_A_1 u) $h i \<le> (A *v pow_A_1 u) $h i goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: le_vec ((sr + eps) *s pow_A_1 u) (A *v pow_A_1 u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] from rho_le_x_Ax_imp_rho_le_rx[OF y le] [PROOF STATE] proof (chain) picking this: sr + eps \<le> r (pow_A_1 u) [PROOF STEP] have "r ?y \<ge> sr + eps" [PROOF STATE] proof (prove) using this: sr + eps \<le> r (pow_A_1 u) goal (1 subgoal): 1. sr + eps \<le> r (pow_A_1 u) [PROOF STEP] . [PROOF STATE] proof (state) this: sr + eps \<le> r (pow_A_1 u) goal (1 subgoal): 1. sr *s u \<noteq> A *v u \<Longrightarrow> False [PROOF STEP] with sr_max[OF y] eps [PROOF STATE] proof (chain) picking this: r (pow_A_1 u) \<le> sr 0 < eps sr + eps \<le> r (pow_A_1 u) [PROOF STEP] show False [PROOF STATE] proof (prove) using this: r (pow_A_1 u) \<le> sr 0 < eps sr + eps \<le> r (pow_A_1 u) goal (1 subgoal): 1. False [PROOF STEP] by auto [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed
From Hammer Require Import Hammer. Require Import Setoid. Require Import RelationClasses. Require Import Morphisms. Set Implicit Arguments. Set Strict Implicit. Theorem Proper_red : forall T U (rT : relation T) (rU : relation U) (f : T -> U), (forall x x', rT x x' -> rU (f x) (f x')) -> Proper (rT ==> rU) f. intuition. Qed. Theorem respectful_red : forall T U (rT : relation T) (rU : relation U) (f g : T -> U), (forall x x', rT x x' -> rU (f x) (g x')) -> respectful rT rU f g. intuition. Qed. Theorem respectful_if_bool T : forall (x x' : bool) (t t' f f' : T) eqT, x = x' -> eqT t t' -> eqT f f' -> eqT (if x then t else f) (if x' then t' else f') . intros; subst; auto; destruct x'; auto. Qed. Ltac derive_morph := repeat first [ lazymatch goal with | |- Proper _ _ => red; intros | |- (_ ==> _)%signature _ _ => red; intros end | apply respectful_red; intros | apply respectful_if_bool; intros | match goal with | [ H : (_ ==> ?EQ)%signature ?F ?F' |- ?EQ (?F _) (?F' _) ] => apply H | [ |- ?EQ (?F _) (?F _) ] => let inst := constr:(_ : Proper (_ ==> EQ) F) in apply inst | [ H : (_ ==> _ ==> ?EQ)%signature ?F ?F' |- ?EQ (?F _ _) (?F' _ _) ] => apply H | [ |- ?EQ (?F _ _) (?F' _ _) ] => let inst := constr:(_ : Proper (_ ==> _ ==> EQ) F) in apply inst | [ |- ?EQ (?F _ _ _) (?F _ _ _) ] => let inst := constr:(_ : Proper (_ ==> _ ==> _ ==> EQ) F) in apply inst | [ |- ?EQ (?F _) (?F _) ] => unfold F | [ |- ?EQ (?F _ _) (?F _ _) ] => unfold F | [ |- ?EQ (?F _ _ _) (?F _ _ _) ] => unfold F end ]. Global Instance Proper_andb : Proper (@eq bool ==> @eq bool ==> @eq bool) andb. derive_morph; auto. Qed. Section K. Variable F : bool -> bool -> bool. Hypothesis Fproper : Proper (@eq bool ==> @eq bool ==> @eq bool) F. Existing Instance Fproper. Definition food (x y z : bool) : bool := F x (F y z). Global Instance Proper_food : Proper (@eq bool ==> @eq bool ==> @eq bool ==> @eq bool) food. Proof. hammer_hook "Parametric" "Parametric.Proper_food". derive_morph; auto. Qed. Global Instance Proper_S : Proper (@eq nat ==> @eq nat) S. Proof. hammer_hook "Parametric" "Parametric.Proper_S". derive_morph; auto. Qed. End K. Require Import List. Section Map. Variable T : Type. Variable eqT : relation T. Inductive listEq {T} (eqT : relation T) : relation (list T) := | listEq_nil : listEq eqT nil nil | listEq_cons : forall x x' y y', eqT x x' -> listEq eqT y y' ->listEq eqT (x :: y) (x' :: y'). Theorem listEq_match V U (eqV : relation V) (eqU : relation U) : forall x x' : list V, forall X X' Y Y', eqU X X' -> (eqV ==> listEq eqV ==> eqU)%signature Y Y' -> listEq eqV x x' -> eqU (match x with | nil => X | x :: xs => Y x xs end) (match x' with | nil => X' | x :: xs => Y' x xs end). Proof. hammer_hook "Parametric" "Parametric.listEq_match". intros. induction H1; auto. derive_morph; auto. Qed. Variable U : Type. Variable eqU : relation U. Variable f : T -> U. Variable fproper : Proper (eqT ==> eqU) f. Definition hd (l : list T) : option T := match l with | nil => None | l :: _ => Some l end. Fixpoint map' (l : list T) : list U := match l with | nil => nil | l :: ls => f l :: map' ls end. Global Instance Proper_map' : Proper (listEq eqT ==> listEq eqU) map'. Proof. hammer_hook "Parametric" "Parametric.Proper_map'". derive_morph. induction H; econstructor; derive_morph; auto. Qed. End Map.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This is a modified ONE COLUMN version of % the following template: % % Deedy - One Page Two Column Resume % LaTeX Template % Version 1.1 (30/4/2014) % % Original author: % Debarghya Das (http://debarghyadas.com) % % Original repository: % https://github.com/deedydas/Deedy-Resume % % IMPORTANT: THIS TEMPLATE NEEDS TO BE COMPILED WITH XeLaTeX % % This template uses several fonts not included with Windows/Linux by % default. If you get compilation errors saying a font is missing, find the line % on which the font is used and either change it to a font included with your % operating system or comment the line out to use the default font. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TODO: % 1. Integrate biber/bibtex for article citation under publications. % 2. Figure out a smoother way for the document to flow onto the next page. % 3. Add styling information for a "Projects/Hacks" section. % 4. Add location/address information % 5. Merge OpenFont and MacFonts as a single sty with options. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CHANGELOG: % v1.1: % 1. Fixed several compilation bugs with \renewcommand % 2. Got Open-source fonts (Windows/Linux support) % 3. Added Last Updated % 4. Move Title styling into .sty % 5. Commented .sty file. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Known Issues: % 1. Overflows onto second page if any column's contents are more than the % vertical limit % 2. Hacky space on the first bullet point on the second column. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \documentclass[]{deedy-resume-openfont} \begin{document} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LAST UPDATED DATE % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \lastupdated %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TITLE NAME % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \namesection{Hardik}{Goel}{ \urlstyle{same}\url{} \href{mailto:[email protected]}{[email protected]} | 612.532.4261\\ } \vspace{\topsep} {\fontspec[Path = fonts/lato/]{Lato-Bol}\selectfont\bfseries\href{https://www.linkedin.com/in/hardikgoel}{https://www.linkedin.com/in/hardikgoel}}\\ \vspace{\topsep} {\fontspec[Path = fonts/lato/]{Lato-Bol}\selectfont\href{https://github.com/goelhardik/}{https://github.com/goelhardik/}}\\ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EXPERIENCE % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Experience} \runsubsection{Cisco Systems} \descript{| Software Engineer } \location{July 2011 – August 2015 | Bangalore, India} \vspace{\topsep} % Hacky fix for awkward extra vertical space \begin{tightemize} \item Worked as a firmware engineer on an I/O Virtualized, Converged Network Adapter, which is part of a Data Center solution - UCS (Unified Compute Servers). \item Worked on iSCSI boot, allowing servers to remotely boot from a central NetApp/EMC storage array. Resolved timing issues to fix Linux crashes and added support for booting multiple hosts. \item Worked on board bring-up for new network adapters, programming new chips and adding new network speeds. \item Created a tool in python for debugging of adapter issues. The tool accepted XML file with commands and generated results using expect scripts. \item Worked on the re-factoring of CLI based tool for configuration of the adapter from the UCS Manager over the network. This also enabled multi-host configuration on the adapter. \end{tightemize} \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EDUCATION % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Education} \runsubsection{University of Minnesota} \descript{| MS in Computer Science} \location{Expected May 2017 | Twin-Cities, MN } GPA: 4.0 / 4.0\\ \textbullet{} Advanced Algorithms and Data Structures \textbullet{} Matrix Theory \textbullet{} Artificial Intelligence I \textbullet{} \\ \textbullet{} Teaching Assistant for undergrad Operating Systems. \sectionsep \runsubsection{Indian Institute of Technology, Roorkee} \descript{| BTech in Electronics \& Communication Engg.} \location{May 2011 | Roorkee, India} GPA: 7.6 / 10.0\\ \textbullet{} Digital Signal Processing \textbullet{} Digital Communication \textbullet{} Data Structures and Algorithms \textbullet{} Mathematics \textbullet{} Computer Networks \textbullet{} Computer Architecture \textbullet{} Database Management \textbullet{} \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PROJECTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Projects} \runsubsection{Optical Character Recognition for handwritten Hindi script} \location{ | \space\space Jan 2011 – May 2011} Worked in a team of three to develop a complete Optical Character Recognition system for handwritten Hindi script.This involved the use of techniques of image enhancement, segmentation and feature extraction (adapted to work best for Hindi text). Used Zernike Moments and Center of Mass as features for a static database.\\ \textbullet{} MATLAB \textbullet{} \sectionsep \runsubsection{Othello Bot} \location{ | \space\space December 2015} Developed an AI to play the game of Othello. Implemented adversary search algorithms such as Minimax and Alpha-Beta Pruning, along with a lot of heuristic based scoring, spcific to Othello.\\ Also made a simple {\fontspec[Path = fonts/lato/]{Lato-Bol}\selectfont\bfseries{\href{http://tictactoeapp.herokuapp.com/}{Tic Tac Toe}}} game for humans to play against an unbeatable bot.\\ \textbullet{} Python \textbullet{} HTML \textbullet{} CSS \textbullet{} Javascript \textbullet{} Flask \textbullet{} \sectionsep %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SKILLS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Skills} \begin{minipage}[t]{.9\textwidth} \subsection{Programming} \begin{minipage}[t]{.2\textwidth} \location{Comfortable:} \textbullet{} Python \textbullet{} Matlab \textbullet{} \end{minipage} \hfill \begin{minipage}[t]{.7\textwidth} \location{Rusty/Familiar:} \textbullet{} C \textbullet{} Shell \textbullet{} Javascript \textbullet{} CSS \textbullet{} HTML \textbullet{} Lisp \textbullet{} \LaTeX\ \textbullet{} \end{minipage} \sectionsep \end{minipage} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % AWARDS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \section{Awards} \vspace{\topsep} % Hacky fix for awkward extra vertical space \begin{tightemize} \item Cisco Achievement Program (CAP) award (2x) for identifying and handling release-critical issues. \item All India Rank 997 in IIT-JEE 2007 (Joint Entrance Examination) among ~300,000 candidates. \end{tightemize} \sectionsep \end{document} \documentclass[]{article}
import Lean.Elab.Tactic open Lean Elab Tactic in elab "print!" : tactic => do logInfo "foo" throwError "error" example : True := by print! admit
import ..lovelib /-! # Project : Eudoxus Reals Reference: https://arxiv.org/pdf/math/0405454.pdf -/ /- This project formalizes a construction of the real numbers called the Eudoxus reals. To do so we first introduce almost homomorphisms which are functions ℤ → ℤ for which the set {f(m+n) - f(m) - f(n), n m : ℤ} is finite. Eudoxus Reals are then defined as equivalence classes of almost homomorphisms. With f ~ g ↔ {f(n) - g(n), n : ℤ} is finite. Therefore these are fonctions that grow almost linearily and the growth rate represents a given real. For intuition, the Eudoxus real that represents the real number α will be the equivalence class of (λ n : ℤ, ⌊α * n⌋). Currently we show that the Eudoxus real form a commutative ring. Left to do: - Invertibility of non zero elements for * - Ordering - Completeness -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- We start with some general results about sets of integers. -/ lemma int_interval_is_finite (M : ℤ): M ≥ 0 → set.finite ({x | x < M ∧ - M < x}):= begin --apply set.finite_Ioo (-M) M, sorry, end lemma bounded_intset_is_finite (s : set ℤ) : (∃ M : ℤ, ∀ x ∈ s, abs(x) < M) → s.finite := begin intro hbounded, cases' hbounded with M1, let M := abs M1, have haux1 : M1 ≤ M := by exact le_abs_self M1, have haux2 : ∀ (x : ℤ), x ∈ s → abs x < M := begin intros x hx, exact gt_of_ge_of_gt haux1 (h x hx), end, have haux3 : s ⊆ {x | x < M ∧ -M < x} := begin simp [set.subset_def], intros x hx, specialize haux2 x hx, have haux_aux_1 : x < M := begin exact lt_of_abs_lt haux2, end, have haux_aux_2 : x > -M := begin exact neg_lt_of_abs_lt haux2, end, exact ⟨haux_aux_1, haux_aux_2⟩, end, have haux4 : M ≥ 0 := by exact abs_nonneg M1, apply (set.finite.subset (int_interval_is_finite M haux4) haux3), end lemma finset_exists_max {α : Type} (s : set α) [linear_order α] (hnonempty : set.nonempty s) : s.finite → ∃ m ∈ s, ∀ x ∈ s, x ≤ m := begin intro hfin, exact set.exists_max_image s (λ (b : α), b) hfin hnonempty, end lemma finset_exists_bound (s : set ℤ ) (hnonempty : set.nonempty s) : s.finite → ∃ m ∈ s, ∀ x ∈ s, abs(x) ≤ abs(m) := begin intro hfin, exact set.exists_max_image s (λ (b : ℤ), abs(b)) hfin hnonempty, end lemma finset_exists_strict_bound (s : set ℤ ) (hnonempty : set.nonempty s) : s.finite → ∃ C : ℤ, ∀ x ∈ s, abs(x) < C := begin intro hfin, cases' (finset_exists_bound s hnonempty hfin), cases' h with hw, apply exists.intro (abs w + 1), have haux1 : abs w < abs w + 1 := lt_add_one (abs w), intros x hx, specialize h x hx, exact lt_of_le_of_lt h haux1, end /- # Almost homomorphisms -/ def almost_hom (f : ℤ → ℤ) : Prop := {x | ∃ m n : ℤ, x = f(n + m) - f(n) - f(m)}.finite structure almost_homs := (func : ℤ → ℤ) (almost_hom : almost_hom func) namespace almost_homomorphisms @[instance] def setoid : setoid almost_homs := { r := λf g : almost_homs, {x | ∃ n : ℤ, x = f.func(n) - g.func(n)}.finite, iseqv := begin apply and.intro, { simp [reflexive] }, apply and.intro, { simp [symmetric], intros f g, intro hfg, let sfg := {x | ∃ n : ℤ, x = f.func(n) - g.func(n)}, let sgf := {x | ∃ n : ℤ, x = g.func(n) - f.func(n)}, have hneg : sgf = (λn, -n) '' sfg := begin apply eq.symm, apply set.surj_on.image_eq_of_maps_to _ _, { simp [set.surj_on, set.subset_def], intro a, apply exists.intro a, simp,}, { simp [set.maps_to], intro a, apply exists.intro a, simp,}, end, have sgf_def : {x | ∃ n : ℤ, x = g.func(n) - f.func(n)} = sgf := by simp, have sfg_def : {x | ∃ n : ℤ, x = f.func(n) - g.func(n)} = sfg := by simp, rw sgf_def at ⊢, rw sfg_def at hfg, rw hneg at ⊢, apply set.finite.image (λ n, -n) hfg, }, { simp [transitive], intros f g h hfg hgh, let sfg := {x : ℤ | ∃ (n : ℤ), x = f.func n - g.func n}, have sfg_def : {x : ℤ | ∃ (n : ℤ), x = f.func n - g.func n} = sfg := by refl, let sgh := {x : ℤ | ∃ (n : ℤ), x = g.func n - h.func n}, have sgh_def : {x : ℤ | ∃ (n : ℤ), x = g.func n - h.func n} = sgh := by refl, let sfh := {x : ℤ | ∃ (n : ℤ), x = f.func n - h.func n}, have sfh_def : {x : ℤ | ∃ (n : ℤ), x = f.func n - h.func n} = sfh := by refl, rw sfg_def at hfg, rw sgh_def at hgh, have hsub : sfh ⊆ set.image2 (λa b, a+b) sfg sgh := begin rw set.image2, simp [set.subset_def], intro n, apply exists.intro (f.func n - g.func n), apply and.intro, {apply exists.intro n, refl,}, apply exists.intro (g.func n - h.func n), apply and.intro, {apply exists.intro n, refl}, linarith, end, simp [sfh_def], have himfin : set.finite(set.image2 (λ a b, a + b) sfg sgh) := by apply set.finite.image2 (λ a b, a+b) hfg hgh, apply set.finite.subset himfin hsub, }, end } lemma setoid_iff (f g : almost_homs) : f ≈ g ↔ {x | ∃ n : ℤ, x = f.func(n) - g.func(n) }.finite := by refl @[instance] def has_zero : has_zero almost_homs := { zero := { func:= λ n, 0, almost_hom := by simp [almost_hom], } } @[simp] lemma zero_func : (0 : almost_homs).func = λn, 0 := by refl @[instance] def has_neg : has_neg almost_homs := { neg := λ f : almost_homs, { func := - f.func, almost_hom := begin simp [almost_hom], let s := {x | ∃ m n : ℤ, x = f.func(n + m) - f.func(n) - f.func(m)}, have hsfin : s.finite := f.almost_hom, have him : {x | ∃ m n : ℤ, x = f.func(n) - f.func(n + m) + f.func(m)} = (λn, -n) '' s := begin apply eq.symm, refine set.surj_on.image_eq_of_maps_to _ _, { simp [set.surj_on, set.subset_def], intros x m n h, apply exists.intro m, apply exists.intro n, linarith, }, { simp [set.maps_to], intros x m n h, apply exists.intro m, apply exists.intro n, linarith,}, end, rw him at ⊢, refine set.finite.image (λ n, -n) hsfin, end, } } @[simp] lemma neg_func (f : almost_homs) : (-f).func = - f.func := by refl @[instance] def has_one : has_one almost_homs := { one := { func:= λ n, n, almost_hom := by simp [almost_hom], } } @[simp] lemma one_func : (1 : almost_homs).func = λn, n := by refl -- # Addition @[instance] def has_add : has_add almost_homs := { add := λf g : almost_homs, { func:= f.func + g.func, almost_hom := begin simp [almost_hom], let sf := {x | ∃ m n : ℤ, x = f.func(n + m) - f.func(n) - f.func(m)}, have hf : sf.finite := f.almost_hom, let sg := {x | ∃ m n : ℤ, x = g.func(n + m) - g.func(n) - g.func(m)}, have hg : sg.finite := g.almost_hom, let sfg := {x : ℤ | ∃ (m n : ℤ), x = f.func (n + m) + g.func (n + m) - (f.func n + g.func n) - (f.func m + g.func m)}, have sfg_def : {x : ℤ | ∃ (m n : ℤ), x = f.func (n + m) + g.func (n + m) - (f.func n + g.func n) - (f.func m + g.func m)} = sfg := by refl, have hsub : sfg ⊆ set.image2 (λ a b, a + b) sf sg := begin rw set.image2, simp [set.subset_def], intros x m n hmn, apply exists.intro (f.func (n + m) - f.func n - f.func m), apply and.intro, { apply exists.intro m, apply exists.intro n, refl, }, apply exists.intro (g.func (n + m) - g.func n - g.func m), apply and.intro, { apply exists.intro m, apply exists.intro n, refl, }, simp [hmn], linarith, end, simp [sfg_def], have himfin : set.finite(set.image2 (λ a b, a + b) sf sg) := by apply set.finite.image2 (λ a b, a+b) hf hg, apply set.finite.subset himfin hsub, end, } } @[simp] lemma add_func (f g : almost_homs): (f + g).func = f.func + g.func := by refl lemma add_equiv_add {f f' g g' : almost_homs} (hf : f ≈ f') (hg : g ≈ g') : f + g ≈ f' + g' := begin simp [setoid_iff] at *, let sff' := {x | ∃ n : ℤ, x = f.func n - f'.func n}, have sff'_def : {x | ∃ n : ℤ, x = f.func n - f'.func n} = sff' := by refl, let sgg' := {x | ∃ n : ℤ, x = g.func n - g'.func n}, have sgg'_def : {x | ∃ n : ℤ, x = g.func n - g'.func n} = sgg' := by refl, let s := {x | ∃ n : ℤ, x = f.func n + g.func n - (f'.func n + g'.func n)}, have s_def : {x | ∃ n : ℤ, x = f.func n + g.func n - (f'.func n + g'.func n)} = s := by refl, simp [sff'_def, sgg'_def, s_def] at *, have hsub : s ⊆ set.image2 (λ a b, a + b) sff' sgg' := begin rw set.image2, simp [set.subset_def], intro n, apply exists.intro (f.func n - f'.func n), apply and.intro, {apply exists.intro n, refl}, { apply exists.intro (g.func n - g'.func n), apply and.intro, {apply exists.intro n, refl}, linarith, } end, have himfin : set.finite(set.image2 (λ a b, a + b) sff' sgg') := by apply set.finite.image2 (λ a b, a+b) hf hg, apply set.finite.subset himfin hsub, end lemma zero_add {f : almost_homs} : 0 + f ≈ f := by simp [setoid_iff] lemma add_zero {f : almost_homs} : f + 0 ≈ f := by simp [setoid_iff] -- # Order def is_positive (f : almost_homs) : Prop := {x | ∃ n : ℕ, x = f.func(n)}.infinite /- lemma lemma5 (f : almost_homs) : xor (∃ M, ∀ n, f.func n < M) (xor (∀ C > 0, ∃ N, ∀ p > N, f.func(p) > C) (∀ C > 0, ∃ N, ∀ p > N, f.func(p) < -C) ) := sorry -/ -- # Multiplication -- We now define the error of an almost homomorphism. -- d_f(m, n) = f(m + n) - f(m) - f(n) -- This value represents by how much f is not actually a homomorphism. def hom_error (f : ℤ → ℤ) (m n : ℤ) := f(m + n) - f(m) - f(n) lemma hbounded_error (f : almost_homs) : ∃ C : ℤ, ∀ m n : ℤ, abs (f.func(n + m) - f.func(n) - f.func(m)) < C := begin let s_hom_err := {x | ∃ m n : ℤ, x = f.func(n + m) - f.func(n) - f.func(m)}, have hfin : set.finite s_hom_err := f.almost_hom, have hnonempty : set.nonempty s_hom_err := begin simp [set.nonempty_def], apply exists.intro (- f.func 0), apply exists.intro (int.of_nat 0), apply exists.intro (int.of_nat 0), simp, end, cases' (finset_exists_bound s_hom_err hnonempty hfin), let C := abs(w) + 1, have hC_def : C = abs(w) + 1 := by refl, apply exists.intro C, intros m n, cases' h with hw, have hin : f.func (n + m) - f.func n - f.func m ∈ s_hom_err := begin simp, apply exists.intro m, apply exists.intro n, simp, end, rw hC_def, have haux : abs (f.func (n + m) - f.func n - f.func m) ≤ abs w := by apply (h (f.func (n + m) - f.func n - f.func m) hin), have hsimp : abs w < abs w + 1 := by linarith, apply lt_of_le_of_lt haux hsimp, end lemma lemma7 (f : almost_homs) : ∃ C : ℤ, ∀ m n : ℤ, abs (m * (f.func n) - n * (f.func m)) < (abs m + abs n + 2) * C := begin let s_hom_err := {x | ∃ m n : ℤ, x = f.func(n + m) - f.func(n) - f.func(m)}, have hbounded_homerror : ∃ C : ℤ, ∀ x ∈ s_hom_err, abs(x) < C := begin simp, cases' (hbounded_error f) with C, apply exists.intro C, intros x m n hx, rw hx, apply (h m n), end, cases' hbounded_homerror with C, -- m ≥ 0 have haux_m_nat : ∀ m : ℕ, ∀ n : ℤ, abs(f.func (m*n) - m * f.func n) < (abs (m) + 1) * C := begin intros m n, induction m, { -- m = 0 simp, have hf_mzero_in : (- f.func 0) ∈ s_hom_err := begin simp, apply exists.intro (int.of_nat 0), apply exists.intro (int.of_nat 0), simp, end, have habsneg : abs (f.func 0) = abs (- f.func 0) := by simp [abs_neg], rw habsneg at ⊢, refine h (- f.func 0) hf_mzero_in, }, -- p m → p m+1 { simp, rename m_n m, rename m_ih ih, have hin : f.func (m*n + n) - f.func (m*n) - f.func n ∈ s_hom_err := begin simp, apply exists.intro n, apply exists.intro (int.of_nat m*n), simp, end, have haux : abs (f.func (m*n + n) - f.func (m*n) - f.func n) < C := by exact h (f.func (↑m * n + n) - f.func (↑m * n) - f.func n) hin, calc abs (f.func ((↑m + 1) * n) - (↑m + 1) * f.func n) = abs (f.func (↑m * n + n) - f.func (↑m * n) - f.func n + f.func (int.of_nat m * n) - int.of_nat m * f.func n) : _ ... ≤ abs (f.func (↑m * n + n) - f.func (↑m * n) - f.func n) + abs (f.func (int.of_nat m * n) - int.of_nat m * f.func n) : _ ... < (abs(↑m + 1) + 1) * C : _, { simp, have hsimp1 : (↑m + 1) * n = ↑m * n + n := begin linarith, end, rw hsimp1 at ⊢, have hsimp2 : f.func (↑m * n + n) - f.func (↑m * n) - f.func n + f.func (↑m * n) - ↑m * f.func n = f.func (↑m * n + n) - f.func n - ↑m * f.func n := by linarith, rw hsimp2 at ⊢, have hsimp3 : (↑m + 1) * f.func n = f.func n + ↑m * f.func n := by linarith, rw hsimp3 at ⊢, have hsimp4 : f.func (↑m * n + n) - (f.func n + ↑m * f.func n) = f.func (↑m * n + n) - f.func n - ↑m * f.func n := by linarith, rw hsimp4 at ⊢, }, { let a := f.func (↑m * n + n) - f.func (↑m * n) - f.func n, have a_def : f.func (↑m * n + n) - f.func (↑m * n) - f.func n = a := by refl, have hsimp1 : a + f.func (↑m * n) - ↑m * f.func n = a + (f.func (↑m * n) - ↑m * f.func n) := by linarith, let b := f.func (↑m * n) - ↑m * f.func n, have b_def : f.func (↑m * n) - ↑m * f.func n = b := by refl, rw a_def, simp, rw hsimp1 at ⊢, rw b_def, exact abs_add a b, }, { have haux2 : abs (f.func (int.of_nat m * n) - int.of_nat m * f.func n) + abs (f.func (↑m * n + n) - f.func (↑m * n) - f.func n) < (abs (int.of_nat m) + 1) * C + C := by exact add_lt_add ih haux, have hsimp1 : (abs (int.of_nat m) + 1) = int.of_nat m + 1 := begin have haux1_1 : abs (int.of_nat m) = int.of_nat m := begin simp, end, rw haux1_1 at ⊢, end, have hsimp2 : (abs (int.of_nat m + 1) + 1) = int.of_nat m + 1 + 1 := begin exact rfl, end, have hsimp3 : (abs (↑m + 1) + 1) * C = (abs (int.of_nat m + 1) + 1) * C := by refl, rw hsimp3, rw hsimp2, rw hsimp1 at haux2, linarith, } }, end, -- m ≤ 0 have haux_m_neg : ∀ m : ℕ, ∀ n : ℤ, abs (f.func (-[1+ m] * n) - -[1+ m] * f.func n) < (abs -[1+ m] + 1) * C := begin intro m, induction m, { intro n, have hsimp0 : -[1+0] = -1 := by exact rfl, simp [hsimp0], have hsimp1 : f.func (-n) + f.func n = (f.func (-n) + f.func n - f.func(n - n)) + f.func 0 := by simp, calc abs (f.func (-n) + f.func n) = abs(f.func (-n) + f.func n - f.func(n - n) + f.func 0) : by simp ... ≤ abs (f.func (-n) + f.func n - f.func(n - n)) + abs (f.func 0) : _ ... < C + C : _ ... = (1 + 1) * C : by linarith, { exact abs_add (f.func (-n) + f.func n - f.func (n - n)) (f.func 0), }, { have haux1 : abs (f.func (-n) + f.func n - f.func (n - n)) < C := begin have hmember : (f.func (n-n) - f.func(-n) - f.func n) ∈ s_hom_err := begin simp, apply exists.intro n, apply exists.intro (-n), simp, end, have haux1_1 : abs((f.func (n-n) - f.func(-n) - f.func n)) < C := by exact h (f.func (n - n) - f.func (-n) - f.func n) hmember, have hsimp: abs (f.func (n-n) - f.func (-n) - f.func n) = abs (f.func (-n) + f.func n - f.func (n - n)) := begin have hsimp_simp : (f.func (n-n) - f.func (-n) - f.func n) = - (f.func (-n) + f.func n - f.func (n - n)) := by linarith, rw hsimp_simp, exact abs_neg (f.func (-n) + f.func n - f.func (n - n)), end, rw hsimp at haux1_1, exact haux1_1, end, have haux2 : abs(f.func 0) < C := begin have hmem : f.func 0 - f.func 0 - f.func 0 ∈ s_hom_err := begin simp, apply exists.intro (int.of_nat 0), apply exists.intro (int.of_nat 0), simp, end, have hsimp1 : abs(f.func 0) = abs (- f.func 0) := by simp [abs_neg (f.func 0)], have hsimp2 : -f.func 0 = f.func 0 - f.func 0 - f.func 0 := by linarith, rw hsimp1, rw hsimp2, exact h (f.func 0 - f.func 0 - f.func 0) hmem, end, exact add_lt_add haux1 haux2, }, }, { intro n, rename m_ih ih, rename m_n m, have hsimp0 : -[1+ nat.succ m] = - (m + 2) := by exact rfl, simp [hsimp0], have hsimp1 : -[1+ m] = -(m + 1) := by exact rfl, simp [hsimp1] at ih, have hsimp2 : f.func ((-2 + -↑m) * n) - (-2 + -↑m) * f.func n = f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n) + (f.func ((-1 + -↑m) * n) - (-1 + -↑m) * f.func n) := begin linarith, end, have haux1 : abs (f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n)) < C := begin have hmem : f.func ((-1 + -↑m) * n) - f.func ((-2 + -↑m) * n) - f.func n ∈ s_hom_err := begin simp, apply exists.intro n, apply exists.intro ((-2 + -↑m) * n), simp, have hsimp : (-1 + -↑m) * n = (-2 + -↑m) * n + n := by linarith, simp [hsimp], end, have haux_aux : abs(f.func ((-1 + -↑m) * n) - f.func ((-2 + -↑m) * n) - f.func n) < C := begin apply (h (f.func ((-1 + -↑m) * n) - f.func ((-2 + -↑m) * n) - f.func n) hmem), end, have hsimp_simp : f.func ((-1 + -↑m) * n) - f.func ((-2 + -↑m) * n) - f.func n = - (f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n)) := by linarith, rw hsimp_simp at haux_aux, rw abs_neg at haux_aux, exact haux_aux, end, have haux2 : abs (f.func ((-1 + -↑m) * n) - (-1 + -↑m) * f.func n) < (abs -[1+ m] + 1) * C := by simp [hsimp1]; exact (ih n), calc abs (f.func ((-2 + -↑m) * n) - (-2 + -↑m) * f.func n) = abs(f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n) + (f.func ((-1 + -↑m) * n) - (-1 + -↑m) * f.func n)) : by rw hsimp2 ... ≤ abs(f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n)) + abs ((f.func ((-1 + -↑m) * n) - (-1 + -↑m) * f.func n)) : _ ... < C + (abs -[1+ m] + 1) * C : by apply (add_lt_add haux1 haux2) ... = (abs (-2 + -↑m) + 1) * C : _, { exact abs_add (f.func ((-2 + -↑m) * n) + f.func n - f.func ((-1 + -↑m) * n)) (f.func ((-1 + -↑m) * n) - (-1 + -↑m) * f.func n), }, { rw hsimp1 at ⊢, have habsneg : abs (-1 + -(int.of_nat m)) = m + 1 := begin exact abs_sub (-1) (int.of_nat m), end, have habsneg2 : abs(-2 + -int.of_nat m) = m + 2 := begin exact abs_sub (-2) (int.of_nat m), end, simp at *, rw habsneg, rw habsneg2, linarith, } }, end, -- m : ℤ have haux : ∀ m n : ℤ, abs(f.func (m*n) - m * f.func n) < (abs (m) + 1) * C := begin intros m n, cases' m, -- m is positive or negative simp, simp at haux_m_nat, exact haux_m_nat m n, exact haux_m_neg m n, end, apply exists.intro C, intros m n, have h1 : abs (f.func(m*n) - m*f.func(n)) < (abs(m) + 1) * C := haux m n, have h2 : abs (n*f.func(m) - f.func(m*n)) < (abs(n) + 1) * C := begin have hsimp : abs (n*f.func(m) - f.func(m*n)) = abs (f.func(m*n) - n*f.func(m)) := by exact abs_sub (n * f.func m) (f.func (m * n)), rw hsimp, have hsimp2 : m*n = n*m := by linarith, rw hsimp2, exact haux n m, end, calc abs (m * f.func n - n * f.func m) = abs (f.func (m * n) - m * f.func n + n * f.func m - f.func (m * n)) : _ ... ≤ abs (f.func (m * n) - m * f.func n) + abs (n * f.func m - f.func (m * n)) : _ ... < (abs m + 1) * C + (abs n + 1) * C : by exact add_lt_add h1 h2 ... = (abs m + abs n + 2) * C : by linarith, { have hsimp : m * f.func n - n * f.func m = - (f.func (m * n) - m * f.func n + n * f.func m - f.func (m * n)) := begin linarith, end, rw hsimp, exact abs_neg (f.func (m * n) - m * f.func n + n * f.func m - f.func (m * n)), }, { let a := f.func (m * n) - m * f.func n, have a_def : f.func (m * n) - m * f.func n = a := by refl, let b := n * f.func m - f.func (m * n), have b_def : n * f.func m - f.func (m * n) = b := by refl, rw a_def, have hsimp : a + n * f.func m - f.func (m * n) = a + (n * f.func m - f.func (m * n)) := by linarith, rw hsimp, rw b_def, exact abs_add a b, }, end lemma lemma8 (f : almost_homs) : ∃ A B : ℤ, ∀ m : ℤ, abs (f.func m) < A * abs(m) + B := begin cases' (lemma7 f) with C, apply exists.intro (C + abs (f.func 1)), apply exists.intro (3*C), intro m, have haux1 : abs (m * f.func 1 - 1 * f.func m) < (abs m + abs 1 + 2) * C := by exact (h m 1), simp at haux1, have haux2 : abs (f.func m) - abs (m * f.func 1) ≤ abs (f.func m - m * f.func 1) := by apply abs_sub_abs_le_abs_sub, have hsimp1 : abs (m * f.func 1 - f.func m) = abs (f.func m - m * f.func 1) := by exact abs_sub (m * f.func 1) (f.func m), rw hsimp1 at haux1, have haux3 : abs (f.func m) - abs (m * f.func 1) < (abs m + 1 + 2) * C := by apply lt_of_le_of_lt haux2 haux1, have haux4 : abs (f.func m) < (abs m + 1 + 2) * C + abs (m * f.func 1) := by exact sub_lt_iff_lt_add.mp haux3, have hsimp2 : abs (m * f.func 1) = abs (m) * abs(f.func 1) := by exact abs_mul m (f.func 1), have hsimp3 : (abs m + 1 + 2) * C + abs (m) * abs(f.func 1) = (C + abs (f.func 1)) * abs m + 3 * C := by linarith, simp [hsimp2, hsimp3] at haux4, exact haux4, end @[instance] def has_mul : has_mul almost_homs := { mul := λf g : almost_homs, { func:= f.func ∘ g.func, almost_hom := begin simp [almost_hom], apply bounded_intset_is_finite, cases' (hbounded_error f) with Cf hCf, cases' (hbounded_error g) with Cg hCg, have haux1 : ∀ m n : ℤ, abs(f.func(g.func m + g.func n) - f.func (g.func m) - f.func (g.func n)) < Cf := begin intros m n, apply (hCf (g.func n) (g.func m)), end, have haux2 : ∀ m n : ℤ, abs(f.func(g.func (m + n)) - f.func (g.func (m + n) - g.func m - g.func n) - f.func (g.func m + g.func n)) < Cf := begin intros m n, let h := (hCf (g.func m + g.func n) (g.func(m + n) - g.func m - g.func n)), simp at *, apply h, end, have haux3 : ∃ C, ∀ m n : ℤ, abs(f.func(g.func (m + n) - g.func m - g.func n)) < C := begin let sg := {x | ∃ m n : ℤ, x = g.func(n + m) - g.func(n) - g.func(m)}, have hsg_fin : sg.finite := g.almost_hom, let sfg := {x | ∃ y ∈ sg, x = (f.func y)}, have hfabs_fin : set.finite sfg := by exact set.finite.dependent_image hsg_fin (λ (x : ℤ) (hx : x ∈ sg), (f.func x)), cases' (finset_exists_bound sfg _ hfabs_fin), { apply exists.intro ((abs w) + 1), intros m n, have haux1 : (g.func (m + n) - g.func m - g.func n) ∈ sg := begin simp, apply exists.intro n, apply exists.intro m, refl, end, have haux2 : (f.func(g.func (m + n) - g.func m - g.func n)) ∈ sfg := begin simp, apply exists.intro (g.func (m + n) - g.func m - g.func n), apply and.intro, apply exists.intro n, apply exists.intro m, refl, refl, end, cases' h with w hw, have haux3 : abs w < abs w + 1 := by exact lt_add_one (abs w), exact lt_of_le_of_lt (hw (f.func (g.func (m + n) - g.func m - g.func n)) haux2) haux3, }, { simp [set.nonempty_def], apply exists.intro (f.func(- g.func 0)), apply exists.intro (- g.func 0), apply and.intro, apply exists.intro (int.of_nat 0), apply exists.intro (int.of_nat 0), simp, }, end, have haux4 : ∀ m n : ℤ, f.func(g.func (m + n)) - f.func (g.func m) - f.func (g.func n) = f.func(g.func m + g.func n) - f.func (g.func m) - f.func (g.func n) + (f.func(g.func (m + n)) - f.func (g.func (m + n) - g.func m - g.func n) - f.func (g.func m + g.func n)) + (f.func(g.func (m + n) - g.func m - g.func n)) := by intros m n; linarith, cases' haux3 with C, have haux5 : ∀ m n : ℤ, abs (f.func(g.func (m + n)) - f.func (g.func m) - f.func (g.func n)) < 2*Cf + C := begin intros m n, calc abs (f.func(g.func (m + n)) - f.func (g.func m) - f.func (g.func n)) = abs (f.func(g.func m + g.func n) - f.func (g.func m) - f.func (g.func n) + (f.func(g.func (m + n)) - f.func (g.func (m + n) - g.func m - g.func n) - f.func (g.func m + g.func n)) + (f.func(g.func (m + n) - g.func m - g.func n))) : by simp [haux4] ... ≤ abs (f.func(g.func m + g.func n) - f.func (g.func m) - f.func (g.func n)) + abs(f.func(g.func (m + n)) - f.func (g.func (m + n) - g.func m - g.func n) - f.func (g.func m + g.func n)) + abs(f.func(g.func (m + n) - g.func m - g.func n)) : _ ... < Cf + Cf + C : by exact add_lt_add (add_lt_add (haux1 m n) (haux2 m n)) (h m n) ... = 2 * Cf + C : by linarith, { exact abs_add_three (f.func (g.func m + g.func n) - f.func (g.func m) - f.func (g.func n)) (f.func (g.func (m + n)) - f.func (g.func (m + n) - g.func m - g.func n) - f.func (g.func m + g.func n)) (f.func (g.func (m + n) - g.func m - g.func n)), }, end, apply exists.intro (2*Cf + C), intro x, simp, intros m n hx, rw hx, apply (haux5 n m), end, } } @[simp] lemma mul_func (f g : almost_homs): (f * g).func = f.func ∘ g.func := by refl lemma one_mul {f : almost_homs} : 1 * f ≈ f := by simp [setoid_iff] lemma mul_equiv_mul {f f' g g' : almost_homs} (hff' : f ≈ f') (hgg' : g ≈ g') : f * g ≈ f' * g' := begin simp [setoid_iff] at *, apply bounded_intset_is_finite, set sff' := {x : ℤ | ∃ (n : ℤ), x = f.func n - f'.func n} with sff'_def, set sgg' := {x : ℤ | ∃ (n : ℤ), x = g.func n - g'.func n} with sgg'_def, have hnonemptyf : set.nonempty sff' := begin simp [set.nonempty_def], apply exists.intro (f.func 0 - f'.func 0), apply exists.intro (int.of_nat 0), simp, end, have hnonemptyg : set.nonempty sgg' := begin simp [set.nonempty_def], apply exists.intro (g.func 0 - g'.func 0), apply exists.intro (int.of_nat 0), simp, end, cases' (finset_exists_strict_bound sff' hnonemptyf hff') with Cff' hCff', cases' (finset_exists_strict_bound sgg' hnonemptyg hgg') with Cgg' hCgg', have haux1 : ∀ n : ℤ, abs (f.func (g.func n) - f'.func (g.func n)) < Cff' := begin intro n, have hmember : f.func (g.func n) - f'.func (g.func n) ∈ sff' := begin simp, apply exists.intro (g.func n), refl, end, apply (hCff' (f.func (g.func n) - f'.func (g.func n)) hmember), end, let sf' := {x | ∃ m n : ℤ, x = f'.func(n + m) - f'.func(n) - f'.func(m)}, have hsg_fin : sf'.finite := f'.almost_hom, cases' (hbounded_error f') with Cf' hCf', have haux2 : ∀ n : ℤ, abs (f'.func(g.func n) - f'.func(g.func n - g'.func n) - f'.func (g'.func n)) < Cf' := begin intro n, have hsimp : f'.func (g.func n) = f'.func(g.func n - g'.func n + g'.func n) := by simp, rw hsimp, apply (hCf' (g'.func n) (g.func n - g'.func n)), end, have haux3 : ∃ C : ℤ, ∀ n : ℤ, abs (f'.func (g.func n - g'.func n)) < C := begin set sf'g := {x | ∃ y ∈ sgg', x = f'.func y} with sf'g_def, have hfin : set.finite sf'g := by exact set.finite.dependent_image hgg' (λ (x : ℤ) (hx : x ∈ sgg'), f'.func x), have hnonempty : set.nonempty sf'g := begin simp [set.nonempty_def], apply exists.intro (f'.func (g.func 0 - g'.func 0)), apply exists.intro ((g.func 0 - g'.func 0)), apply and.intro, apply exists.intro (int.of_nat 0), refl, refl, end, cases' (finset_exists_strict_bound sf'g hnonempty hfin) with C hC, apply exists.intro C, simp [sf'g_def] at hC, exact hC, end, cases' haux3 with C, have hrw : ∀ n : ℤ, f.func (g.func n) - f'.func (g'.func n) = (f.func (g.func n) - f'.func (g.func n)) + (f'.func(g.func n) - f'.func(g.func n - g'.func n) - f'.func (g'.func n)) + (f'.func (g.func n - g'.func n)) := by intro n; linarith, apply exists.intro (Cff' + Cf' + C), have haux4 : ∀ n : ℤ, abs (f.func (g.func n) - f'.func (g'.func n)) < Cff' + Cf' + C := begin intro n, calc abs (f.func (g.func n) - f'.func (g'.func n)) = abs((f.func (g.func n) - f'.func (g.func n)) + (f'.func(g.func n) - f'.func(g.func n - g'.func n) - f'.func (g'.func n)) + (f'.func (g.func n - g'.func n))) : by rw hrw ... ≤ abs (f.func (g.func n) - f'.func (g.func n)) + abs (f'.func(g.func n) - f'.func(g.func n - g'.func n) - f'.func (g'.func n)) + abs (f'.func (g.func n - g'.func n)) : _ ... < Cff' + Cf' + C : _, { exact abs_add_three (f.func (g.func n) - f'.func (g.func n)) (f'.func (g.func n) - f'.func (g.func n - g'.func n) - f'.func (g'.func n)) (f'.func (g.func n - g'.func n)), }, { apply add_lt_add (add_lt_add (haux1 n) (haux2 n)) (h n), } end, simp, exact haux4, end lemma mul_monotone (a b c :ℤ): a ≥ 0 → b ≥ c → a * b ≥ a * c := begin intros ha hbc, exact mul_le_mul_of_nonneg_left hbc ha, end lemma mul_monotone_right (a b c :ℤ): a ≥ 0 → b ≥ c → b * a ≥ c * a := begin intros ha hbc, have hsimp1 : b * a = a * b := by linarith, have hsimp2 : c * a = a * c := by linarith, rw hsimp1 at ⊢, rw hsimp2 at ⊢, exact mul_monotone a b c ha hbc, end lemma mul_comm_aux (f g : almost_homs) : ∃ A B C : ℤ, (A ≥ 0 ∧ B ≥ 0 ∧ C ≥ 0) ∧ ∀ (p : ℤ), abs (p) * abs(f.func (g.func p) - g.func (f.func p)) < 2 * (abs p + (A * abs p + B) + 2) * C := begin cases' (almost_homomorphisms.lemma7 f) with Cf hCf, cases' (almost_homomorphisms.lemma7 g) with Cg hCg, set absCf := abs Cf with absCf_def, set absCg := abs Cg with absCg_def, have haux1 : ∀ p, abs (p * f.func (g.func p) - g.func p * f.func p) < (abs p + abs (g.func p ) + 2) * Cf := by intro p; exact hCf p (g.func p), have haux2 : ∀ p, abs (g.func p * f.func p - p * (g.func (f.func p))) < (abs p + abs (f.func p) + 2) * Cg := begin intro p, have hsimp : abs (g.func p * f.func p - p * g.func (f.func p)) = abs (- (g.func p * f.func p - p * g.func (f.func p))):= by exact eq.symm (abs_neg (g.func p * f.func p - p * g.func (f.func p))), simp [hsimp], rw (mul_comm (g.func p) (f.func p)), apply hCg p (f.func p), end, have haux3 : ∀ p, abs (p * (f.func (g.func p)) - p * (g.func (f.func p))) < (abs p + abs (g.func p ) + 2) * Cf + (abs p + abs (f.func p) + 2) * Cg := begin intro p, calc abs (p * (f.func (g.func p)) - p * (g.func (f.func p))) = abs ((p * f.func (g.func p) - g.func p * f.func p) + (g.func p * f.func p - p * g.func (f.func p))) : _ ... ≤ abs (p * f.func (g.func p) - g.func p * f.func p) + abs (g.func p * f.func p - p * g.func (f.func p)) : _ ... < (abs p + abs (g.func p ) + 2) * Cf + (abs p + abs (f.func p) + 2) * Cg : _, { have hlinarith : p * (f.func (g.func p)) - p * (g.func (f.func p)) = p * (f.func (g.func p)) - g.func p * (f.func p) + (g.func p * (f.func p) - p * (g.func (f.func p))) := by linarith, rw hlinarith, }, {exact abs_add (p * f.func (g.func p) - g.func p * f.func p) (g.func p * f.func p - p * g.func (f.func p)),}, {exact add_lt_add (hCf p (g.func p)) (haux2 p),} end, cases' (almost_homomorphisms.lemma8 f) with Af hAf, cases' hAf with Bf hABf, cases' (almost_homomorphisms.lemma8 g) with Ag hAg, cases' hAg with Bg hABg, have haux1'_aux : ∀ p, (abs p + abs (g.func p) + 2) * Cf ≤ (abs p + abs (g.func p) + 2) * absCf := begin intro p, have h1 : (abs p + abs (g.func p) + 2) ≥ 0 := begin have h1_1 : abs p ≥ 0 := abs_nonneg p, have h1_2 : abs (g.func p) ≥ 0 := abs_nonneg (g.func p), linarith, end, apply (mul_monotone (abs p + abs (g.func p) + 2) absCf Cf h1 _), exact le_abs_self Cf, end, have haux1' : ∀ p, abs (p * f.func (g.func p) - g.func p * f.func p) < (abs p + abs (g.func p) + 2) * absCf := begin intro p, have haux1'_aux : (abs p + abs (g.func p) + 2) * Cf ≤ (abs p + abs (g.func p) + 2) * absCf := begin have h1 : (abs p + abs (g.func p) + 2) ≥ 0 := begin have h1_1 : abs p ≥ 0 := abs_nonneg p, have h1_2 : abs (g.func p) ≥ 0 := abs_nonneg (g.func p), linarith, end, apply (mul_monotone (abs p + abs (g.func p) + 2) absCf Cf h1 _), exact le_abs_self Cf, end, apply lt_of_lt_of_le (haux1 p) haux1'_aux, end, have haux2' : ∀ (p : ℤ), abs (g.func p * f.func p - p * g.func (f.func p)) < (abs p + abs (f.func p) + 2) * absCg := begin intro p, have haux2'_aux : (abs p + abs (f.func p) + 2) * Cg ≤ (abs p + abs (f.func p) + 2) * absCg := begin have h1 : (abs p + abs (f.func p) + 2) ≥ 0 := begin have h1_1 : abs p ≥ 0 := abs_nonneg p, have h1_2 : abs (f.func p) ≥ 0 := abs_nonneg (f.func p), linarith, end, apply (mul_monotone (abs p + abs (f.func p) + 2) absCg Cg h1 _), exact le_abs_self Cg, end, apply lt_of_lt_of_le (haux2 p) haux2'_aux, end, have haux4 : ∀ p, (abs p + abs (g.func p) + 2) * absCf ≤ (abs p + (Ag * abs p + Bg) + 2) * absCf := begin intro p, have h1 : (abs p + abs(g.func p) + 2) < (abs p + (Ag * abs p + Bg) + 2) := begin have h1_1 : abs p + abs (g.func p) < abs p + (Ag * abs p + Bg) := by exact add_lt_add_left (hABg p) (abs p), exact add_lt_add_right h1_1 2, end, have h : absCf * (abs p + (Ag * abs p + Bg) + 2) ≥ absCf * (abs p + abs (g.func p) + 2) := begin apply mul_monotone absCf (abs p + (Ag * abs p + Bg) + 2) (abs p + abs(g.func p) + 2), exact abs_nonneg Cf, exact le_of_lt h1, end, linarith, end, have haux5 : ∀ p, (abs p + abs (f.func p) + 2) * absCg ≤ (abs p + (Af * abs p + Bf) + 2) * absCg := begin intro p, have h1 : (abs p + abs(f.func p) + 2) < (abs p + (Af * abs p + Bf) + 2) := begin have h1_1 : abs p + abs (f.func p) < abs p + (Af * abs p + Bf) := by exact add_lt_add_left (hABf p) (abs p), exact add_lt_add_right h1_1 2, end, have h : absCg * (abs p + (Af * abs p + Bf) + 2) ≥ absCg * (abs p + abs (f.func p) + 2) := begin apply mul_monotone absCg (abs p + (Af * abs p + Bf) + 2) (abs p + abs(f.func p) + 2), exact abs_nonneg Cg, exact le_of_lt h1, end, linarith, end, have haux6 : ∀ (p : ℤ), (abs p + abs (g.func p) + 2) * absCf + (abs p + abs (f.func p) + 2) * absCg ≤ (abs p + (Ag * abs p + Bg) + 2) * absCf + (abs p + (Af * abs p + Bf) + 2) * absCg := begin intro p, apply add_le_add (haux4 p) (haux5 p), end, have haux3' : ∀ (p : ℤ), abs (p * f.func (g.func p) - p * g.func (f.func p)) < (abs p + abs (g.func p) + 2) * absCf + (abs p + abs (f.func p) + 2) * absCg := begin intro p, calc abs (p * (f.func (g.func p)) - p * (g.func (f.func p))) = abs ((p * f.func (g.func p) - g.func p * f.func p) + (g.func p * f.func p - p * g.func (f.func p))) : _ ... ≤ abs (p * f.func (g.func p) - g.func p * f.func p) + abs (g.func p * f.func p - p * g.func (f.func p)) : _ ... < (abs p + abs (g.func p ) + 2) * absCf + (abs p + abs (f.func p) + 2) * absCg : _, { have hlinarith : p * (f.func (g.func p)) - p * (g.func (f.func p)) = p * (f.func (g.func p)) - g.func p * (f.func p) + (g.func p * (f.func p) - p * (g.func (f.func p))) := by linarith, rw hlinarith, }, {exact abs_add (p * f.func (g.func p) - g.func p * f.func p) (g.func p * f.func p - p * g.func (f.func p)),}, {exact add_lt_add (lt_of_lt_of_le (hCf p (g.func p)) (haux1'_aux p)) (haux2' p),}, end, have haux4' : ∀ (p : ℤ), abs (p * f.func (g.func p) - p * g.func (f.func p)) < (abs p + (Ag * abs p + Bg) + 2) * absCf + (abs p + (Af * abs p + Bf) + 2) * absCg := begin intro p, apply lt_of_lt_of_le (haux3' p) (haux6 p), end, have haux5' : ∀ p, abs (p * f.func (g.func p) - p * g.func (f.func p)) = abs p * abs (f.func (g.func p) - g.func (f.func p)) := begin intro p, have h : (p * f.func (g.func p) - p * g.func (f.func p)) = p * (f.func (g.func p) - g.func (f.func p)) := by linarith, rw h, exact abs_mul p (f.func (g.func p) - g.func (f.func p)), end, set A := max Af Ag with Adef, set B := max Bf Bg with Bdef, have hsimp1 : ∀ p, Af * abs p + Bf ≤ A * abs p + B := begin intro p, have h1 : abs p * A ≥ abs p * Af := begin apply mul_monotone (abs p) A Af, exact abs_nonneg p, exact le_max_left Af Ag, end, have h1' : abs p * Af ≤ abs p * A := by apply ge.le h1, have h2 : Bf ≤ B := by exact le_max_left Bf Bg, have h3 : abs p * Af + Bf ≤ abs p * A + B := by apply add_le_add h1 h2, have hsimp1 : abs p * Af = Af * abs p := by linarith, have hsimp2 : abs p * A = A * abs p := by linarith, rw hsimp1 at h3, rw hsimp2 at h3, exact h3, end, have hsimp2 : ∀ p, Ag * abs p + Bg ≤ A * abs p + B := begin intro p, have h1 : abs p * A ≥ abs p * Ag := begin apply mul_monotone (abs p) A Ag, exact abs_nonneg p, exact le_max_right Af Ag, end, have h1' : abs p * Ag ≤ abs p * A := by apply ge.le h1, have h2 : Bg ≤ B := by exact le_max_right Bf Bg, have h3 : abs p * Ag + Bg ≤ abs p * A + B := by apply add_le_add h1 h2, have hsimp1 : abs p * Ag = Ag * abs p := by linarith, have hsimp2 : abs p * A = A * abs p := by linarith, rw hsimp1 at h3, rw hsimp2 at h3, exact h3, end, set C := max absCf absCg with Cdef, have hCpos : C ≥ 0 := begin have haux : C ≥ absCf := by apply le_max_left absCf absCg, have habsCfpos : absCf ≥ 0 := abs_nonneg Cf, exact le_trans habsCfpos haux, end, set absA := abs A with absAdef, set absB := abs B with absBdef, have haux6': ∀ (p : ℤ), abs (p * f.func (g.func p) - p * g.func (f.func p)) < 2 * (abs p + (absA * abs p + absB) + 2) * C := begin intro p, calc abs (p * f.func (g.func p) - p * g.func (f.func p)) < (abs p + (Ag * abs p + Bg) + 2) * absCf + (abs p + (Af * abs p + Bf) + 2) * absCg : by exact (haux4' p) ... ≤ (abs p + (A * abs p + B) + 2) * absCf + (abs p + (A * abs p + B) + 2) * absCg : _ ... ≤ (abs p + (absA * abs p + absB) + 2) * absCf + (abs p + (absA * abs p + absB) + 2) * absCg : _ ... ≤ (abs p + (absA * abs p + absB) + 2) * C + (abs p + (absA * abs p + absB) + 2) * C : _ ... = 2 * (abs p + (absA * abs p + absB) + 2) * C : by linarith, { have h1 : absCf * (abs p + (A * abs p + B) + 2) ≥ absCf * (abs p + (Ag * abs p + Bg) + 2) := begin apply mul_monotone absCf (abs p + (A * abs p + B) + 2) (abs p + (Ag * abs p + Bg) + 2), exact abs_nonneg Cf, simp, exact hsimp2 p, end, have h2 : absCg * (abs p + (A * abs p + B) + 2) ≥ absCg * (abs p + (Af * abs p + Bf) + 2) := begin apply mul_monotone absCg (abs p + (A * abs p + B) + 2) (abs p + (Af * abs p + Bf) + 2), exact abs_nonneg Cg, simp, exact hsimp1 p, end, rw ge_iff_le at h1, rw ge_iff_le at h2, have h3 : absCf * (abs p + (Ag * abs p + Bg) + 2) + absCg * (abs p + (Af * abs p + Bf) + 2) ≤ absCf * (abs p + (A * abs p + B) + 2) + absCg * (abs p + (A * abs p + B) + 2) := by apply add_le_add h1 h2, have hs1 : absCf * (abs p + (Ag * abs p + Bg) + 2) = (abs p + (Ag * abs p + Bg) + 2) * absCf := by linarith, have hs2 : absCg * (abs p + (Af * abs p + Bf) + 2) = (abs p + (Af * abs p + Bf) + 2) * absCg := by linarith, have hs3 : absCf * (abs p + (A * abs p + B) + 2) = (abs p + (A * abs p + B) + 2) * absCf := by linarith, have hs4 : absCg * (abs p + (A * abs p + B) + 2) = (abs p + (A * abs p + B) + 2) * absCg := by linarith, rw hs1 at h3, rw hs2 at h3, rw hs3 at h3, rw hs4 at h3, exact h3, }, { have h1 : (abs p + (absA * abs p + absB) + 2) * absCf ≥ (abs p + (A * abs p + B) + 2) * absCf := begin have h1_1 : absA * abs p ≥ A * abs p := by apply mul_monotone_right (abs p) (absA) A (abs_nonneg p) (le_abs_self A), have h1_2 : absB ≥ B := by exact le_abs_self B, have h1_3 : absA * abs p + absB ≥ A * abs p + B := by exact add_le_add h1_1 h1_2, apply mul_monotone_right absCf (abs p + (absA * abs p + absB) + 2) (abs p + (A * abs p + B) + 2), exact abs_nonneg Cf, simp, apply h1_3, end, have h2 : (abs p + (absA * abs p + absB) + 2) * absCg ≥ (abs p + (A * abs p + B) + 2) * absCg := begin have h1_1 : absA * abs p ≥ A * abs p := by apply mul_monotone_right (abs p) (absA) A (abs_nonneg p) (le_abs_self A), have h1_2 : absB ≥ B := by exact le_abs_self B, have h1_3 : absA * abs p + absB ≥ A * abs p + B := by exact add_le_add h1_1 h1_2, apply mul_monotone_right absCg (abs p + (absA * abs p + absB) + 2) (abs p + (A * abs p + B) + 2), exact abs_nonneg Cg, simp, apply h1_3, end, apply add_le_add h1 h2, }, { have hpos : abs p + (absA * abs p + absB) + 2 ≥ 0 := begin have hpos1 : absA ≥ 0 := abs_nonneg A, have hpos2 : absB ≥ 0 := abs_nonneg B, have hpos3 : abs p ≥ 0 := abs_nonneg p, have hpos4 : absA * abs p ≥ 0 := mul_nonneg hpos1 hpos3, have hpos5 : absA * abs p + absB ≥ 0 := add_nonneg hpos4 hpos2, have hpos6 : abs p + (absA * abs p + absB) ≥ 0 := add_nonneg hpos3 hpos5, refine add_nonneg hpos6 _, linarith, end, have h1 : (abs p + (absA * abs p + absB) + 2) * C ≥ (abs p + (absA * abs p + absB) + 2) * absCf := begin apply mul_monotone (abs p + (absA * abs p + absB) + 2) C absCf, apply hpos, apply le_max_left absCf absCg, end, have h2 : (abs p + (absA * abs p + absB) + 2) * C ≥ (abs p + (absA * abs p + absB) + 2) * absCg := begin apply mul_monotone (abs p + (absA * abs p + absB) + 2) C absCg, apply hpos, apply le_max_right absCf absCg, end, apply add_le_add h1 h2, }, end, have haux7': ∀ (p : ℤ), abs (p) * abs(f.func (g.func p) - g.func (f.func p)) < 2 * (abs p + (absA * abs p + absB) + 2) * C := begin intro p, have h := (eq.symm (haux5' p)), rw h at ⊢, exact (haux6' p), end, apply exists.intro absA, apply exists.intro absB, apply exists.intro C, apply and.intro, apply and.intro, apply abs_nonneg A, apply and.intro, apply abs_nonneg B, apply hCpos, exact haux7', end lemma abs_nonnul_ge_1 (x : ℤ) : x ≠ 0 → abs x ≥ 1 := begin intro hx, have hpos : 0 < abs x := begin exact abs_pos.mpr hx, end, exact hpos, end lemma mul_comm (f g : almost_homs) : f * g ≈ g * f := begin simp [almost_homomorphisms.setoid_iff], apply bounded_intset_is_finite, cases' mul_comm_aux f g with A hrest, cases' hrest with B hrest, cases' hrest with C hrest, have hABCpos : (A ≥ 0 ∧ B ≥ 0 ∧ C ≥ 0) := by apply and.elim_left hrest, have hApos : A ≥ 0 := and.elim_left hABCpos, have hBpos : B ≥ 0 := and.elim_left (and.elim_right hABCpos), have hCpos : C ≥ 0 := and.elim_right (and.elim_right hABCpos), have hbound : ∀ (p : ℤ), abs (p) * abs(f.func (g.func p) - g.func (f.func p)) < 2 * (abs p + (A * abs p + B) + 2) * C := by apply and.elim_right hrest, clear hrest, have hbound_1 : ∀ (p : ℤ), p ≠ 0 → abs(f.func (g.func p) - g.func (f.func p)) < 2 * (1 + (A + B) + 2) * C := begin intros p hp, have haux1 : abs (p) * abs(f.func (g.func p) - g.func (f.func p)) < 2 * (abs p + (A * abs p + B) + 2) * C := hbound p, have haux2 : abs p * abs(f.func (g.func p) - g.func (f.func p)) < abs p * (2 * (1 + (A + B) + 2) * C) ↔ abs(f.func (g.func p) - g.func (f.func p)) < 2 * (1 + (A + B) + 2) * C := begin apply (@mul_lt_mul_left _ _ (abs(f.func (g.func p) - g.func (f.func p))) (2 * (1 + (A + B) + 2) * C) (abs p) _), apply (iff.elim_right abs_pos), apply hp, end, apply (iff.elim_left haux2), have habsp_one : abs p ≥ 1 := by apply abs_nonnul_ge_1 p hp, have haux4 : 2 * (abs p + (A * abs p + B) + 2) * C ≤ abs p * (2 * (1 + (A + B) + 2) * C) := begin have hsimp : abs p * (2 * (1 + (A + B) + 2) * C) = 2 * (abs p * 1 + (A * abs p + abs p * B) + abs p *2) * C := by linarith, rw hsimp, have h1 := mul_monotone_right B (abs p) 1 hBpos habsp_one, simp at h1, have h2 := mul_monotone_right 2 (abs p) 1 zero_le_two habsp_one, simp at h2, have h3 : A * abs p + B ≤ A * abs p + abs p * B := begin refine add_le_add _ h1, linarith, end, have h4 : (A * abs p + B) + 2 ≤ (A * abs p + abs p * B) + abs p * 2 := by exact add_le_add h3 h2, have h5 : abs p + (A * abs p + B) + 2 ≤ abs p + (A * abs p + abs p * B) + abs p * 2 := by linarith, have h6 : 2 * (abs p + (A * abs p + B) + 2) ≤ 2 * (abs p + (A * abs p + abs p * B) + abs p * 2) := by linarith, have h7 := mul_monotone_right C (2 * (abs p + (A * abs p + abs p * B) + abs p * 2)) (2 * (abs p + (A * abs p + B) + 2)) hCpos h6, simp at h7, simp, exact h7, end, calc abs p * abs (f.func (g.func p) - g.func (f.func p)) < 2 * (abs p + (A * abs p + B) + 2) * C : hbound p ... ≤ abs p * (2 * (1 + (A + B) + 2) * C) : haux4, end, set M0 := abs (f.func (g.func 0) - g.func (f.func 0)) with M0_def, set Mp := 2 * (1 + (A + B) + 2) * C with Mp_def, set M := max (M0+1) Mp, apply exists.intro M, intros x, simp, intros n hx, have cases_n : n = 0 ∨ n ≠ 0 := dec_em (n = 0), cases cases_n, { simp [cases_n] at hx, have hxM0 : abs x ≤ M0 := by simp [hx], refine or.inl _, calc abs x ≤ M0 : hxM0 ... < M0 + 1 : lt_add_one M0, }, { refine or.inr _, simp [hx], apply (hbound_1 n cases_n), }, end end almost_homomorphisms /- # Eudoxus Reals -/ namespace Eudoxus_Reals def Eudoxus_Reals : Type := quotient almost_homomorphisms.setoid @[instance] def has_add : has_add Eudoxus_Reals := { add := quotient.lift₂ (λf g : almost_homs, ⟦f + g⟧) begin intros f g f' g' hf hg, apply quotient.sound, exact almost_homomorphisms.add_equiv_add hf hg, end } @[instance] def has_zero : has_zero Eudoxus_Reals := { zero := ⟦0⟧ } lemma zero_add (x : Eudoxus_Reals) : 0 + x = x := begin apply quotient.induction_on x, intro x', apply quotient.sound, apply almost_homomorphisms.zero_add, end lemma add_zero (x : Eudoxus_Reals) : x + 0 = x := begin apply quotient.induction_on x, intro x', apply quotient.sound, apply almost_homomorphisms.add_zero, end @[instance] def has_one : has_one Eudoxus_Reals := { one := ⟦1⟧ } lemma add_comm (a b : Eudoxus_Reals) : a+b=b+a := begin apply quotient.induction_on₂ a b, intros a' b', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], have haux : a'.func + b'.func - (b'.func + a'.func) = 0 := begin have hauxaux: a'.func + b'.func = b'.func + a'.func := by exact add_comm a'.func b'.func, exact sub_eq_zero.mpr hauxaux, end, have haux2 : ∀ n, a'.func n + b'.func n - (b'.func n + a'.func n) = 0 := by exact congr_fun haux, simp [haux2], end lemma add_assoc (a b c : Eudoxus_Reals) : a + b + c = a + (b + c) := begin apply quotient.induction_on₃ a b c, intros a' b' c', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], have haux : ∀ n, a'.func n + b'.func n + c'.func n - (a'.func n + (b'.func n + c'.func n)) = 0 := by intro n; linarith, simp [haux], end @[instance] def has_neg : has_neg Eudoxus_Reals := { neg := quotient.lift (λf : almost_homs, ⟦- f⟧) begin intros f g hfg, apply quotient.sound, simp [almost_homomorphisms.setoid_iff] at *, exact (almost_homomorphisms.setoid_iff g f).mp (setoid.symm hfg), end } lemma add_left_neg (a : Eudoxus_Reals) : -a + a = 0 := begin apply quotient.induction_on a, intro a', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], end /- # Eudoxus Reals form an abelian group -/ @[instance] def Eudoxus_Reals.add_group : add_comm_group Eudoxus_Reals := { add := Eudoxus_Reals.has_add.add, add_assoc := add_assoc, zero := Eudoxus_Reals.has_zero.zero, zero_add := zero_add, add_zero := add_zero, neg := Eudoxus_Reals.has_neg.neg, add_left_neg := add_left_neg, add_comm := add_comm, } @[instance] def has_mul : has_mul Eudoxus_Reals := { mul := quotient.lift₂ (λf g : almost_homs, ⟦f * g⟧) begin intros f g f' g' hf hg, apply quotient.sound, exact almost_homomorphisms.mul_equiv_mul hf hg, end } lemma mul_assoc (a b c : Eudoxus_Reals) : a * b * c = a * (b * c) := begin apply quotient.induction_on₃ a b c, intros a' b' c', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], end lemma mul_comm (a b : Eudoxus_Reals) : a * b = b * a := begin apply quotient.induction_on₂ a b, intros f g, apply quotient.sound, apply almost_homomorphisms.mul_comm f g, end lemma one_mul (x : Eudoxus_Reals) : 1 * x = x := begin apply quotient.induction_on x, intro x', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], end lemma mul_one (x : Eudoxus_Reals) : x * 1 = x := begin apply quotient.induction_on x, intro x', apply quotient.sound, simp [almost_homomorphisms.setoid_iff], end lemma left_distrib (a b c : Eudoxus_Reals): a * (b + c) = a * b + a * c := begin apply quotient.induction_on₃ a b c, intros f g h, apply quotient.sound, simp [almost_homomorphisms.setoid_iff], set s_hom_err := {x | ∃ m n : ℤ, x = f.func(n + m) - f.func(n) - f.func(m)} with s_hom_err_def, set s := {x : ℤ | ∃ (n : ℤ), x = f.func (g.func n + h.func n) - (f.func (g.func n) + f.func (h.func n))} with s_def, have hfin : set.finite s_hom_err := f.almost_hom, have hsub : s ⊆ s_hom_err := begin simp [set.subset_def], intro n, apply exists.intro (h.func n), apply exists.intro (g.func n), linarith, end, exact set.finite.subset hfin hsub, end lemma right_distrib (a b c : Eudoxus_Reals): (a + b) * c = a * c + b * c := begin apply quotient.induction_on₃ a b c, intros f g h, apply quotient.sound, simp [almost_homomorphisms.setoid_iff], end /- # Eudoxus Reals form a ring -/ @[instance] def Eudoxus_Reals.ring: comm_ring Eudoxus_Reals := { add := Eudoxus_Reals.has_add.add, add_assoc := add_assoc, zero := Eudoxus_Reals.has_zero.zero, zero_add := zero_add, add_zero := add_zero, neg := Eudoxus_Reals.has_neg.neg, add_left_neg := add_left_neg, add_comm := add_comm, mul := Eudoxus_Reals.has_mul.mul, mul_assoc := mul_assoc, one := Eudoxus_Reals.has_one.one, one_mul := one_mul, mul_one := mul_one, left_distrib := left_distrib, right_distrib := right_distrib, mul_comm := mul_comm, } end Eudoxus_Reals end LoVe
State Before: α : Type u_5 β : Type ?u.94563 β₂ : Type ?u.94566 γ : Type ?u.94569 ι : Sort ?u.94572 ι' : Sort ?u.94575 κ : ι → Sort ?u.94580 κ' : ι' → Sort ?u.94585 inst✝ : CompleteLattice α f✝ g s t : ι → α a b : α ι₁ : Sort u_1 ι₂ : Sort u_2 κ₁ : ι₁ → Sort u_3 κ₂ : ι₂ → Sort u_4 f : (i₁ : ι₁) → κ₁ i₁ → (i₂ : ι₂) → κ₂ i₂ → α ⊢ (⨆ (i₁ : ι₁) (j₁ : κ₁ i₁) (i₂ : ι₂) (j₂ : κ₂ i₂), f i₁ j₁ i₂ j₂) = ⨆ (i₂ : ι₂) (j₂ : κ₂ i₂) (i₁ : ι₁) (j₁ : κ₁ i₁), f i₁ j₁ i₂ j₂ State After: no goals Tactic: simp only [@iSup_comm _ (κ₁ _), @iSup_comm _ ι₁]
{-# OPTIONS --safe --warning=error --without-K #-} open import Numbers.ClassicalReals.RealField open import LogicalFormulae open import Setoids.Subset open import Setoids.Setoids open import Setoids.Orders.Partial.Definition open import Sets.EquivalenceRelations open import Rings.Orders.Partial.Definition open import Rings.Definition open import Fields.Fields open import Groups.Definition open import Numbers.Naturals.Semiring open import Numbers.Naturals.Order open import Functions.Definition module Numbers.Intervals.Definition {a b c : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} {_<_ : Rel {_} {c} A} {R : Ring S _+_ _*_} {pOrder : SetoidPartialOrder S _<_} (pRing : PartiallyOrderedRing R pOrder) where record OpenInterval : Set a where field minBound : A maxBound : A isInInterval : A → OpenInterval → Set c isInInterval a record { minBound = min ; maxBound = max } = (min < a) && (a < max)
lemma minus_pCons [simp]: "- pCons a p = pCons (- a) (- p)"
import data.real.irrational import topology.basic import algebra.order.floor --OUTPUT 1 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) : α ∉ ℚ → ∃ S : set ℝ, (∀ x ∈ S, x ∈ Icc 0 1) ∧ (∀ x y ∈ S, x ≠ y) ∧ (∀ x y ∈ S, ∃ z ∈ S, |x - y| = z) := begin -- Let $\alpha$ be an irrational number. assume h1 : α ∉ ℚ, -- Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. have h2 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ≠ (j : ℝ) * α - ⌊(j : ℝ) * α⌋, from by auto [sub_floor, sub_floor], -- If this were not true, then -- $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. have h3 : ∀ i j : ℤ, i ≠ j → α ≠ ((⌊(i : ℝ) * α⌋ - ⌊(j : ℝ) * α⌋)/(i - j)), from by auto [sub_floor, sub_floor, sub_div], -- Hence, -- $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$ let S := {(i : ℝ) * α - ⌊(i : ℝ) * α⌋ | i : ℤ}, -- is an infinite subset of $\left[0,1\right]$. have h4 : ∀ i : ℤ, (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ∈ Icc 0 1, from by auto [sub_floor, sub_floor, sub_nonneg], have h5 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ≠ (j : ℝ) * α - ⌊(j : ℝ) * α⌋, from by auto [sub_floor, sub_floor], have h6 : ∀ i : ℤ, ∃ j : ℤ, i ≠ j, from by auto [int.exists_ne], have h7 : ∀ i : ℤ, ∃ j : ℤ, (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ≠ (j : ℝ) * α - ⌊(j : ℝ) * α⌋, from by auto [h6, h5], have h8 : ∃ (i : ℤ), (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ≠ (i : ℝ) * α - ⌊(i : ℝ) * α⌋, from by auto [h7], have h9 : ∃ (i : ℤ), (i : ℝ) * α - ⌊(i : ℝ) * α⌋ ∈ S, from by auto [h8, set.mem_def], -- By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. have h10 : ∃ x : ℝ, x ∈ Icc 0 1 ∧ ∀ ε > 0, ∃ y ∈ S, y ≠ x ∧ |y - x| < ε, from by auto [h9, set.bounded_iff, set.bounded_iff, set.compact_iff, set.compact_iff, set.compact_iff] using [compact_Icc], -- One can thus find pairs of elements of $S$ that are arbitrarily close. have h11 : ∀ ε > 0, ∃ x y ∈ S, x ≠ y ∧ |x - y| < ε, from by auto [h10, set.mem_def, set.mem_def, set.mem_def], -- Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$. have h12 : ∀ x y ∈ S, ∃ z ∈ S, |x - y| = z, from by auto [h11], -- To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. have h13 : ∀ y ε > 0, ∃ x ∈ S, |y - x| < ε, from by auto [h11], -- Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$. have h14 : ∀ y ε > 0, ∃ N x ∈ S, N * x ≤ y ∧ y < (N + 1) * x ∧ |y - (N * x)| < ε, from by auto [h13, set.mem_def, set.mem_def, set.mem_def, set.mem_def, set.mem_def, set.mem_def, set.mem_def, set.mem_def, set.mem_def], -- QED show ∃ (S : set ℝ), (∀ (x : ℝ), x ∈ S → x ∈ Icc 0 1) ∧ (∀ (x y : ℝ), x ∈ S → y ∈ S → x ≠ y) ∧ (∀ (x y : ℝ), x ∈ S → y ∈ S → ∃ (z : ℝ), z ∈ S ∧ |x - y| = z), from by auto [h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, h14, set.mem_def], end --OUTPUT 2 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) (hα : ¬ is_rat α) : ∀ (ε : ℝ) (hε : ε > 0), ∃ (n : ℤ) (h1 : 0 ≤ n) (h2 : n ≤ 1/ε), ∃ (m : ℤ), (n : ℝ) ≤ m * α ∧ m * α < (n + 1) := begin assume (ε : ℝ) (hε : ε > 0), let S := {n : ℤ | 0 ≤ n ∧ n ≤ 1/ε}, have h1 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h2 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h3 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h4 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h5 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h6 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h7 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h8 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h9 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h10 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h11 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h12 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h13 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h14 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h15 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h16 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h17 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h18 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h19 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h20 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h21 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h22 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h23 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h24 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h25 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h26 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h27 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h28 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h29 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h30 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h31 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq], have h32 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ 1 / ε, from by auto [set.mem_set_of_eq], have h33 : ∀ (n : ℤ), n ∈ S ↔ (0 : ℝ) ≤ n ∧ n ≤ (1 : ℝ) / ε, from by auto [set.mem_set_of_eq end --Needs more than 2000 tokens! --OUTPUT 3 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) (h1 : α ∉ ℚ) : ∀ y ∈ (Icc 0 1), ∃ x ∈ (Icc 0 1), y ≠ x ∧ |y - x| < 1 := begin assume (y : ℝ) (h2 : y ∈ Icc 0 1), let S := (set.range (λ (i : ℤ), (i : ℝ) * α)) ∩ Icc 0 1, have h3 : S ⊆ Icc 0 1, from by auto [set.mem_inter_iff, set.mem_range, set.mem_Icc], have h4 : ∀ i : ℤ, (i : ℝ) * α ∉ ℚ, from by auto [h1, mul_ne_zero], have h5 : ∀ i : ℤ, (i : ℝ) * α ∉ ℚ, from by auto [h1, mul_ne_zero], have h6 : ∀ i j : ℤ, i ≠ j → ((i : ℝ) * α) - (j : ℝ) * α ≠ 0, from by auto [h4, mul_ne_zero], have h7 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h8 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h9 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h10 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h11 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h12 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h13 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h14 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h15 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h16 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h17 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h18 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h19 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h20 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h21 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h22 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h23 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h24 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h25 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h26 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h27 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h28 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h29 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h30 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h31 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h32 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h33 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h34 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h35 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h36 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h37 : ∀ i j : ℤ, i ≠ j → (i : ℝ) * α ≠ (j : ℝ) * α, from by auto [h5, mul_ne_zero], have h38 : ∀ i j : ℤ, i ≠ j → (i : end --Needs more than 2000 tokens! --OUTPUT 4 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) (hα : α ≠ 0) (hα2 : ¬ is_rat α) : ∀ y ∈ Icc 0 1, ∃ x ∈ set.range (λ n : ℤ, n • α % 1), |y - x| < 1 := begin assume y h1, have h2 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h3 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h4 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h5 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h6 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h7 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h8 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h9 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h10 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h11 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h12 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h13 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h14 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h15 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h16 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h17 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h18 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h19 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h20 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h21 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h22 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h23 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h24 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_of_mul_eq_mul_left, eq_of_mul_eq_mul_right, is_rat.def], have h25 : ∀ i j : ℤ, i ≠ j → (i • α % 1) ≠ (j • α % 1), from by auto [hα, hα2, eq_ end --Needs more than 2000 tokens! --OUTPUT 5 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=density_of_irrational_orbit (α : ℝ) (h1 : ¬ ∃ q : ℚ, α = q) : ∀ y : ℝ, ∃ x : ℝ, x ∈ {i * α | i : ℤ} ∧ |y - x| < 1 := begin -- Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then assume (y : ℝ), have h2 : ∀ (i j : ℤ), (i ≠ j) → ((i * α) - (floor (i * α)) ≠ (j * α) - (floor (j * α))), from by auto [h1, floor_eq_iff], -- Hence, $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$ is an infinite subset of $\left[0,1\right]$. let S : set ℝ := {i * α - floor (i * α) | i : ℤ}, have h3 : (∀ (i : ℤ), i * α - floor (i * α) ∈ S) ∧ (∀ (x : ℝ), x ∈ S → ∃ (i : ℤ), x = i * α - floor (i * α)), from by auto, have h4 : ∀ (x : ℝ), x ∈ S → x ∈ Icc 0 1, from by auto [floor_nonneg, floor_le], have h5 : ∀ (x : ℝ), x ∈ S → 0 ≤ x ∧ x < 1, from by auto [h4], have h6 : ∀ (x : ℝ), x ∈ S → x < 1, from by auto [h5], have h7 : ∀ (x : ℝ), x ∈ S → 0 ≤ x, from by auto [h5], have h8 : ∀ (x : ℝ), x ∈ S → x ≠ 0, from by auto [h7], have h9 : ∀ (x : ℝ), x ∈ S → x ≠ 1, from by auto [h6], have h10 : ∀ (x : ℝ), x ∈ S → x ∈ Ico 0 1, from by auto [h5, h8, h9], have h11 : S ⊆ Ico 0 1, from by auto [h10], have h12 : ∀ (x : ℝ), x ∈ S → x ∈ Icc 0 1, from by auto [h4], have h13 : S ⊆ Icc 0 1, from by auto [h12], have h14 : ∀ (x : ℝ), x ∈ S → x ∈ Ici 0 1, from by auto [h7, h6], have h15 : S ⊆ Ici 0 1, from by auto [h14], have h16 : S ⊆ {x : ℝ | 0 ≤ x ∧ x ≤ 1}, from by auto [h15], have h17 : S ⊆ {x : ℝ | 0 < x ∧ x < 1}, from by auto [h11], have h18 : S ⊆ {x : ℝ | 0 ≤ x ∧ x < 1}, from by auto [h16], have h19 : S ⊆ {x : ℝ | 0 < x ∧ x ≤ 1}, from by auto [h16], have h20 : S ⊆ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1}, from by auto [h17, h18, h19], have h21 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1}, from by auto [h20, h8, h9], have h22 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1}, from by auto [h20], have h23 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1}, from by auto [h18, h21], have h24 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1}, from by auto [h19, h21], have h25 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 ≤ x ∧ x ≤ 1}, from by auto [h16, h21], have h26 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1}, from by auto [h23, h22], have h27 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1}, from by auto [h24, h22], have h28 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x ≤ 1}, from by auto [h25, h22], have h29 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1}, from by auto [h26, h27, h28], have h30 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1} ∪ {x : ℝ | 0 ≤ x ∧ x ≤ 1}, from by auto [h29, h28], have h31 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1} ∪ {x : ℝ | 0 ≤ x ∧ x ≤ 1} ∪ {x : ℝ | 0 < x ∧ x < 1}, from by auto [h29, h30], have h32 : S ⊆ {x : ℝ | x = 0} ∪ {x : ℝ | x = 1} ∪ {x : ℝ | 0 < x ∧ x < 1} ∪ {x : ℝ | 0 ≤ x ∧ x < 1} ∪ {x : ℝ | 0 < x ∧ x ≤ 1} ∪ {x : end --Needs more than 2000 tokens! --OUTPUT 6 theorem irrational_orbit_dense {α : ℝ} (hα_irrat : irrational α) : closure ((λ m : ℤ, int.fract (α * ↑m)) '' (@set.univ ℤ)) = set.Icc 0 1 :=irrational_orbit_dense (α : ℝ) (hα : ¬ is_rat α) : ∃ (S : set ℝ), ∀ (x : ℝ), x ∈ S → x ∈ Icc 0 1 ∧ ∀ (y : ℝ), y ∈ Icc 0 1 → ∃ (z : ℝ), z ∈ S ∧ abs (z - y) < abs (x - y) := begin --Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then have h1 : ∀ (i j : ℤ), i ≠ j → (int.fract (i * α)) ≠ (int.fract (j * α)), from by auto [int.fract_mul, int.fract_eq_iff, hα, int.fract_eq_iff], --Hence, $S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\}$ is an infinite subset of $\left[0,1\right]$. have h2 : ∀ (i : ℤ), (int.fract (i * α)) ∈ Icc 0 1, from by auto [int.fract_nonneg, int.fract_lt_one], have h3 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)), from by auto [int.fract_mul], have h4 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h5 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h6 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h7 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h8 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h9 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h10 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h11 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h12 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h13 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h14 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h15 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h16 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h17 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h18 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h19 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h20 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h21 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h22 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h23 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h24 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h25 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h26 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h27 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int.fract (i * α)) ∩ Icc 0 1, from by auto [h2, h3], have h28 : ∀ (i : ℤ), (int.fract (i * α)) ∈ set.range (λ (i : ℤ), int. end --Needs more than 2000 tokens! /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S), -- Then $A ⊆ S$ and $B ⊆ S$, by power set definition have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset], -- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left], -- Then $(A ∩ B) ⊆ S$, by subset relation is transitive have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans], -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset], end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by auto [sq] -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by auto [add_mul] -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring] -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring] end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)], have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹], -- Setting $b = a$, this becomes: have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1], have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2], -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one], have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul], show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)], end /--`theorem` Squeeze Theorem for Real Numbers Let $\sequence {x_n}$, $\sequence {y_n}$ and $\sequence {z_n}$ be sequences in $\R$. Let $\sequence {y_n}$ and $\sequence {z_n}$ both be convergent to the following limit: :$\ds \lim_{n \mathop \to \infty} y_n = l, \lim_{n \mathop \to \infty} z_n = l$ Suppose that: :$\forall n \in \N: y_n \le x_n \le z_n$ Then: :$x_n \to l$ as $n \to \infty$ that is: :$\ds \lim_{n \mathop \to \infty} x_n = l$ `proof` From Negative of Absolute Value: :$\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$ Let $\epsilon > 0$. We need to prove that: :$\exists N: \forall n > N: \size {x_n - l} < \epsilon$ As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that: :$\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$ As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that: :$\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$ Let $N = \max \set {N_1, N_2}$. Then if $n > N$, it follows that $n > N_1$ and $n > N_2$. So: :$\forall n > N: l - \epsilon < y_n < l + \epsilon$ :$\forall n > N: l - \epsilon < z_n < l + \epsilon$ But: :$\forall n \in \N: y_n \le x_n \le z_n$ So: :$\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$ and so: :$\forall n > N: l - \epsilon < x_n < l + \epsilon$ So: :$\forall n > N: \size {x_n - l} < \epsilon$ Hence the result. {{qed}} -/ theorem squeeze_theorem_real_numbers (x y z : ℕ → ℝ) (l : ℝ) : let seq_limit : (ℕ → ℝ) → ℝ → Prop := λ (u : ℕ → ℝ) (l : ℝ), ∀ ε > 0, ∃ N, ∀ n > N, |u n - l| < ε in seq_limit y l → seq_limit z l → (∀ n : ℕ, (y n) ≤ (x n) ∧ (x n) ≤ (z n)) → seq_limit x l := begin assume seq_limit (h2 : seq_limit y l) (h3 : seq_limit z l) (h4 : ∀ (n : ℕ), y n ≤ x n ∧ x n ≤ z n) (ε), --From Negative of Absolute Value: $\size {x - l} < \epsilon \iff l - \epsilon < x < l + \epsilon$ have h5 : ∀ x, |x - l| < ε ↔ (((l - ε) < x) ∧ (x < (l + ε))), from by auto [abs_sub_lt_iff] using [linarith], --Let $\epsilon > 0$. assume (h7 : ε > 0), --As $\ds \lim_{n \mathop \to \infty} y_n = l$ we know that $\exists N_1: \forall n > N_1: \size {y_n - l} < \epsilon$ cases h2 ε h7 with N1 h8, --As $\ds \lim_{n \mathop \to \infty} z_n = l$ we know that $\exists N_2: \forall n > N_2: \size {z_n - l} < \epsilon$ cases h3 ε h7 with N2 h9, --Let $N = \max \set {N_1, N_2}$. let N := max N1 N2, use N, --Then if $n > N$, it follows that $n > N_1$ and $n > N_2$. have h10 : ∀ n > N, n > N1 ∧ n > N2 := by auto [lt_of_le_of_lt, le_max_left, le_max_right], --$\forall n > N: l - \epsilon < y_n < l + \epsilon$ --$\forall n > N: l - \epsilon < z_n < l + \epsilon$ --$\forall n \in \N: y_n \le x_n \le z_n$ --So $\forall n > N: l - \epsilon < y_n \le x_n \le z_n < l + \epsilon$ have h11 : ∀ n > N, (((l - ε) < (y n)) ∧ ((y n) ≤ (x n))) ∧ (((x n) ≤ (z n)) ∧ ((z n) < l+ε)), from by auto [h8, h10, h5, h9], --$\forall n > N: l - \epsilon < x_n < l + \epsilon$ have h15 : ∀ n > N, ((l - ε) < (x n)) ∧ ((x n) < (l+ε)), from by auto [h11] using [linarith], --So $\forall n > N: \size {x_n - l} < \epsilon$ --Hence the result show ∀ (n : ℕ), n > N → |x n - l| < ε, from by auto [h5, h15], end /--`theorem` Density of irrational orbit The fractional parts of the integer multiples of an irrational number form a dense subset of the unit interval `proof` Let $\alpha$ be an irrational number. Then for distinct $i, j \in \mathbb{Z}$, we must have $\{i \alpha\} \neq\{j \alpha\}$. If this were not true, then $$ i \alpha-\lfloor i \alpha\rfloor=\{i \alpha\}=\{j \alpha\}=j \alpha-\lfloor j \alpha\rfloor, $$ which yields the false statement $\alpha=\frac{\lfloor i \alpha\rfloor-\lfloor j \alpha\rfloor}{i-j} \in \mathbb{Q}$. Hence, $$ S:=\{\{i \alpha\} \mid i \in \mathbb{Z}\} $$ is an infinite subset of $\left[0,1\right]$. By the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$. To show that $S$ is dense in $[0, 1]$, consider $y \in[0,1]$, and $\epsilon>0$. Then by selecting $x \in S$ such that $\{x\}<\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \cdot\{x\} \leq y<(N+1) \cdot\{x\}$, we get: $|y-\{N x\}|<\epsilon$. QED -/ theorem FEW SHOT PROMPTS TO CODEX(END)-/
text_raw \<open>\subsection[Identifiability, Isomorphical Uniqueness and Permutability]{Identifiability, Isomorphical Uniqueness and Permutability\isalabel{identifiability-iso-uniqueness}}\<close> theory IdentifiabilityAndIsomorphicalUniqueness imports Identifiability "../ParticularStructures/StructuralPropertiesTheorems" begin text \<^marker>\<open>tag bodyonly\<close> \<open> While we introduced, in the previous section, a definition for what consists the ``identity'' of a particular in terms of the existence of a suitable \emph{identifying predicate}, in this section we show that it is not necessary to refer to the existence of an element that is ontologically extraneous to the UFO particular structure (the identifying predicate), to characterize the concept of the ``identity'' of a particular. We achive this by proving the logical equivalence between the notion of identifiability, as described in the previous section, and the notions of isomorphical uniqueness and non-permutability, that were introduced in \autoref{subsec:isomorphical-uniqueness} and \autoref{subsec:permutability}. \<close> context ufo_particular_theory begin lemma \<^marker>\<open>tag (proof) aponly\<close> ex1_intro_1: fixes A and P assumes \<open>f \<in> A\<close> \<open>\<And>g. g \<in> A \<Longrightarrow> g a = f a\<close> shows \<open>\<exists>!z. \<forall>g \<in> A. g a = z\<close> apply (intro ex1I[of _ \<open>f a\<close>] ballI) subgoal using assms by blast subgoal premises P for z using P[rule_format,OF assms(1)] by simp done text \<^marker>\<open>tag bodyonly\<close> \<open> The equivalence of the set of isomorphically-unique particulars and the set of identifiable particulars is shown by the following lemmas and theorem: \<close> lemma im_uniques_are_identifiables: \<open>\<P>\<^sub>\<simeq>\<^sub>! \<subseteq> \<P>\<^sub>=\<close> proof (intro subsetI) fix x assume as: \<open>x \<in> \<P>\<^sub>\<simeq>\<^sub>!\<close> obtain \<open>x \<in> \<E>\<close> using as by blast have A: \<open>\<sigma> x = \<phi> x\<close> if \<open>inj_on \<phi> \<E>\<close> \<open>particular_struct_morphism \<Gamma> (MorphImg \<phi> \<Gamma>) \<sigma>\<close> for \<phi> \<sigma> :: \<open>'p \<Rightarrow> ZF\<close> apply (rule as[THEN isomorphically_unique_particulars_E]) subgoal premises P apply (rule P(2)[simplified,OF conjI ,OF that(1)[simplified] _ that(2) \<open>x \<in> \<E>\<close>, THEN iffD2]) using inj_on_id by blast+ done have pick_ex: \<open>\<exists>!y. \<forall>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>. \<phi>' x = y\<close> if as1: \<open>\<Gamma>' \<in> IsoModels\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> for \<Gamma>' proof - obtain \<phi>\<^sub>1 where phi1: \<open>\<phi>\<^sub>1 \<in> BijMorphs1\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> \<open>\<Gamma>' = MorphImg \<phi>\<^sub>1 \<Gamma>\<close> using as1 by blast interpret phi1: particular_struct_bijection_1 \<open>\<Gamma>\<close> \<open>\<phi>\<^sub>1\<close> using phi1 by simp interpret phi1_inv: particular_struct_bijection_1 \<open>MorphImg \<phi>\<^sub>1 \<Gamma>\<close> \<open>phi1.inv_morph\<close> using particular_struct_bijection_iff_particular_struct_bijection_1 by blast have AA: \<open>\<phi>\<^sub>1 \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>\<close> apply (auto) using phi1(2) phi1.particular_struct_morphism_axioms by blast have BB: \<open>\<phi>' x = \<phi>\<^sub>1 x\<close> if as2: \<open>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>\<close> for \<phi>' apply (rule A) subgoal using phi1.morph_is_injective[simplified] . using phi1(2) as2 morphs_D by metis show \<open>?thesis\<close> apply (rule ex1_intro_1[of \<open>\<phi>\<^sub>1\<close>]) subgoal using AA . subgoal premises P for \<phi>' using BB[OF P] . done qed show \<open>x \<in> \<P>\<^sub>=\<close> proof (clarsimp simp: identifiables_def \<open>x \<in> \<E>\<close>) define P where \<open>P \<Gamma>' z \<longleftrightarrow> z = (THE y. \<forall>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>. \<phi>' x = y)\<close> for \<Gamma>' and z :: \<open>ZF\<close> have P1: \<open>P \<Gamma>' (\<phi>' x)\<close> if \<open>\<exists>\<phi>\<in>BijMorphs1\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>. \<Gamma>' = MorphImg \<phi> \<Gamma>\<close> \<open>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>\<close> for \<Gamma>' \<phi>' using pick_ex[THEN the1I2,of \<open>\<Gamma>'\<close> \<open>\<lambda>y. \<forall>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub>. \<phi>' x = y\<close>, simplified P_def[symmetric],simplified] that by metis have P2: \<open>P (MorphImg \<phi> \<Gamma>) (\<phi>' x)\<close> if \<open>\<phi> \<in> BijMorphs1\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> \<open>\<phi>' \<in> Morphs\<^bsub>\<Gamma>, MorphImg \<phi> \<Gamma>\<^esub>\<close> for \<phi> \<phi>' using P1 that by metis have P3: \<open>y = \<phi> x\<close> if as3: \<open>\<sigma> \<in> BijMorphs1\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> \<open>\<phi> \<in> Morphs\<^bsub>\<Gamma>,MorphImg \<sigma> \<Gamma>\<^esub>\<close> \<open>P (MorphImg \<sigma> \<Gamma>) y\<close> for \<sigma> \<phi> y apply (rule the1_equality[of \<open>\<lambda>y. \<forall>\<phi>' \<in> Morphs\<^bsub>\<Gamma>,MorphImg \<sigma> \<Gamma>\<^esub>. \<phi>' x = y\<close>,of \<open>\<phi> x\<close>, simplified as3(3)[simplified P_def,symmetric],OF pick_ex] ; (intro ballI)?) subgoal G1 using that(1) by blast subgoal for \<phi>\<^sub>3 apply auto by (metis G1 morphs_iff pick_ex that(2)) done show \<open>\<exists>P. identity_pred \<Gamma> P x\<close> apply (intro exI[of _ \<open>P\<close>] identity_pred_I1 iffI ) subgoal by (simp add: \<open>x \<in> \<E>\<close>) subgoal by (metis (full_types) P3 as isomorphic_models_E ufo_particular_theory_sig.isomorphically_unique_particulars_E) using P2 \<open>x \<in> \<E>\<close> by auto qed qed lemma identifiables_are_im_uniques: \<open>\<P>\<^sub>= \<subseteq> \<P>\<^sub>\<simeq>\<^sub>!\<close> proof (intro subsetI) fix x assume \<open>x \<in> \<P>\<^sub>=\<close> then obtain P where P: \<open>x \<in> \<E>\<close> \<open>identity_pred \<Gamma> P x\<close> by blast show \<open>x \<in> \<P>\<^sub>\<simeq>\<^sub>!\<close> proof (rule) show \<open>x \<in> \<E>\<close> using P(1) . fix \<phi> \<sigma> y assume as: \<open>\<phi> \<in> BijMorphs1\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> \<open>\<sigma> \<in> Morphs\<^bsub>\<Gamma>,MorphImg \<phi> \<Gamma>\<^esub>\<close> \<open>y \<in> \<E>\<close> have P1: \<open>identity_pred (MorphImg \<phi> \<Gamma>) P (\<phi> x)\<close> using identity_respects_isomorphisms[OF P(2) as(1)] . interpret phi: particular_struct_bijection_1 \<open>\<Gamma>\<close> \<open>\<phi>\<close> using as(1) by blast have A: \<open>phi.tgt.\<Gamma> = MorphImg \<phi> \<Gamma>\<close> using phi.tgt_Gamma_eq_Morph_img by auto have B: \<open>\<phi> \<in> Morphs\<^bsub>\<Gamma>,MorphImg \<phi> \<Gamma>\<^esub>\<close> using as(1) by (meson bijections1_are_morphisms) note C = identity_pred_eqI[ where \<phi> = \<open>\<phi>\<close> and x = \<open>x\<close> and P = \<open>P\<close> and \<sigma> = \<open>\<phi>\<close>, OF P(2) as(1) B] identity_pred_eqI[ where \<phi> = \<open>\<sigma>\<close> and x = \<open>x\<close> and P = \<open>P\<close> and \<sigma> = \<open>\<phi>\<close>, OF P(2) as(1,2)] have D: \<open>P (MorphImg \<phi> \<Gamma>) (\<sigma> x) \<longleftrightarrow> P (MorphImg \<phi> \<Gamma>) (\<phi> x)\<close> by (metis C(1) C(2) P(1)) have E: \<open>\<phi> x = \<sigma> x \<longleftrightarrow> P (MorphImg \<phi> \<Gamma>) (\<phi> x)\<close> using C(2)[of \<open>\<phi> x\<close>] using P(1) P(2) identity_pred phi.morph_is_injective by auto have E1: \<open>MorphImg \<phi> \<Gamma> \<in> IsoModels\<^bsub>\<Gamma>,TYPE(ZF)\<^esub>\<close> using as(1) by blast obtain F: \<open>\<And>\<Gamma>' \<phi> y. \<Gamma>' \<in> IsoModels\<^bsub>\<Gamma>,TYPE(ZF)\<^esub> \<Longrightarrow> \<phi> \<in> Morphs\<^bsub>\<Gamma>,\<Gamma>'\<^esub> \<Longrightarrow> P \<Gamma>' y = (\<forall>z\<in>phi.src.endurants. (y = \<phi> z) = (z = x))\<close> using P(2)[THEN identity_pred_E] by metis note G = F[OF E1 as(2)] note H = C(1)[simplified C(2)] note J = H[THEN iffD1,simplified Ball_def,simplified,rule_format] H[THEN iffD2,simplified Ball_def,simplified,rule_format] show \<open>\<sigma> y = \<phi> x \<longleftrightarrow> y = x\<close> apply (intro iffI) subgoal using G P(2) as(3) identity_pred phi.particular_struct_bijection_1_axioms by auto subgoal using J by (metis E P(2) identity_pred phi.morph_is_injective ufo_particular_theory_sig.\<Gamma>_simps(2)) done qed qed theorem identifiables_are_the_im_uniques: \<open>\<P>\<^sub>= = \<P>\<^sub>\<simeq>\<^sub>!\<close> using im_uniques_are_identifiables identifiables_are_im_uniques by blast text \<^marker>\<open>tag bodyonly\<close> \<open> Since the set of isomorphically unique particulars is equivalent to the set of non-permutable particulars, then we can also say that the identifiable particulars are exactly those that are non-permutable:\<close> theorem identifiables_are_the_non_permutables: \<open>\<P>\<^sub>= = \<P>\<^sub>1\<^sub>!\<close> using identifiables_are_the_im_uniques by (simp add: non_permutable_particulars_are_the_unique_particulars) end end
C*********************************************************************** C Copyright (C) 1994-2016 Lawrence Livermore National Security, LLC. C LLNL-CODE-425250. C All rights reserved. C C This file is part of Silo. For details, see silo.llnl.gov. C C Redistribution and use in source and binary forms, with or without C modification, are permitted provided that the following conditions C are met: C C * Redistributions of source code must retain the above copyright C notice, this list of conditions and the disclaimer below. C * Redistributions in binary form must reproduce the above copyright C notice, this list of conditions and the disclaimer (as noted C below) in the documentation and/or other materials provided with C the distribution. C * Neither the name of the LLNS/LLNL nor the names of its C contributors may be used to endorse or promote products derived C from this software without specific prior written permission. C C THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS C "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT C LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR C A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE C LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR C CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, C EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, C PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR C PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF C LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING C NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS C SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. C C This work was produced at Lawrence Livermore National Laboratory under C Contract No. DE-AC52-07NA27344 with the DOE. C C Neither the United States Government nor Lawrence Livermore National C Security, LLC nor any of their employees, makes any warranty, express C or implied, or assumes any liability or responsibility for the C accuracy, completeness, or usefulness of any information, apparatus, C product, or process disclosed, or represents that its use would not C infringe privately-owned rights. C C Any reference herein to any specific commercial products, process, or C services by trade name, trademark, manufacturer or otherwise does not C necessarily constitute or imply its endorsement, recommendation, or C favoring by the United States Government or Lawrence Livermore C National Security, LLC. The views and opinions of authors expressed C herein do not necessarily state or reflect those of the United States C Government or Lawrence Livermore National Security, LLC, and shall not C be used for advertising or product endorsement purposes. C*********************************************************************** C C Program C C testpoint C C Purpose C C Test program illustrating use of SILO from Fortran C for writing point data. C This particular program also uses SILO's "EZ" interface to C write simple scalars and arrays with. C C Programmer C C Jeff Long, NSSD/B, 11/02/92 C C Notes C C For more info on calling sequences, see the "SILO User's C Manual". C C ierr = dbcreate (filename, len_filename, filemode, target, C file_info_string, len_file_info_string, C filetype, DBID) C C ierr = dbputpm (dbid, meshname, len_meshname, num_dims, C xcoords, ycoords, zcoords, npts, datatype, C option_list, MESHID) C C ierr = dbputpv1 (dbid, varname, len_varname, meshname, C len_meshname, C var, npts, datatype, option_list, VARID) C C ierr = ezwrite (silo_id, name, lname, data, len_data, C datatype, ierr) C C program main C ..Don't forget to include this file! include "silo.inc" integer dirid, dbid, meshid, varid, silo_id, optlistid integer varid1, driver, nargs real x(5), y(5), z(5), foo(5) real d(5), ttime integer itype(5), tcycle real ftype(5) double precision dttime character*256 cloption driver = DB_PDB nargs = iargc() call getarg(1, cloption) if (cloption .eq. "DB_HDF5") then driver = DB_HDF5 end if C...Generate some data to write out. do i = 1 , 5 x(i) = i y(i) = i z(i) = i d(i) = 10 * i itype(i) = i ftype(i) = i foo(i) = i enddo npts = 5 lfoo = 5 ttime = 0.123 tcycle = 123 dttime = 0.123 C...Create the file (using the SILO interface) ierr = dbcreate ("pointf77.silo", 13, DB_CLOBBER, DB_LOCAL, . "file info goes here", 19, driver, dbid) if (ierr .ne. 0) then print *, 'dbcreate had error' else print *, 'created file pointf77.silo' endif C...Create an option list containing time and cyle info. ierr = dbmkoptlist(3, optlistid) ! Create the option list ierr = dbaddiopt (optlistid, DBOPT_CYCLE, tcycle) ! Add integer opt ierr = dbaddropt (optlistid, DBOPT_TIME, ttime) ! Add real opt ierr = dbadddopt (optlistid, DBOPT_DTIME, dttime) ! Add double opt C...Write out the point mesh. ierr = dbputpm (dbid, 'pmesh', 5, 2, x, y, z, npts, DB_FLOAT, . optlistid, meshid) C...Write out the point variables ierr = dbputpv1 (dbid, 'd', 1, 'pmesh', 5, d, npts, DB_FLOAT, . optlistid, varid) C ierr = dbputpv1 (dbid, 'ftype', 5, 'pmesh', 5, ftype, npts, DB_FLOAT, C . optlistid, varid1) ierr = dbclose (dbid) if (ierr .ne. 0) print *, 'dbclose had error' stop end
% LaTeX resume using res.cls \documentclass[margin,10pt]{res} %\usepackage{helvetica} % uses helvetica postscript font (download helvetica.sty) %\usepackage{newcent} % uses new century schoolbook postscript font \setlength{\textwidth}{6in} % set width of text portion \newcommand{\code}[1]{\texttt{#1}} \usepackage{hyperref} \usepackage[usenames,dvipsnames]{color} %\usepackage[dvipsnames]{xcolor} \definecolor{MidnightBlue}{RGB}{10,82,131} % This replaces the need for xcolor package \hypersetup{ colorlinks=true, % false: boxed links; true: colored links linkcolor=red, % color of internal links (change box color with linkbordercolor) citecolor=green, % color of links to bibliography filecolor=magenta, % color of file links urlcolor=MidnightBlue % color of external links } \usepackage{enumitem} \setlist[itemize,1]{leftmargin=\dimexpr 26pt-3mm} \newenvironment{benumerate}[1]{ \let\oldItem\item \def\item{\addtocounter{enumi}{-2}\oldItem} \begin{enumerate} \setcounter{enumi}{#1} \addtocounter{enumi}{1} }{ \end{enumerate} } \begin{document} %% Center the name over the entire width of resume: \moveleft.5\hoffset\centerline{\textsc{\Large Jacob Lustig-Yaeger}} \moveleft.5\hoffset\centerline{Astronomy \& Astrobiology, PhD} % %% Draw a horizontal line the whole width of resume: \moveleft\hoffset\vbox{\hrule width 0.93\resumewidth height 1pt} \vspace{-12pt} \hspace{-1in} \begin{minipage}[t]{0.93\resumewidth} Email: \href{mailto:[email protected]}{[email protected]} \hfill GitHub: \href{https://github.com/jlustigy}{jlustigy}\\ Web: \url{https://jlustigy.github.io/} \hfill ORCID: \href{https://orcid.org/0000-0002-0746-1980}{0000-0002-0746-1980} \end{minipage} %% Select character to use as the bullet marker. %% Comment out to get normal dark filled circle bullets \def\labelitemi{---} \begin{resume} %\section{Current \\Position} %Exoplanet Post Doctoral Fellow \hfill (2020 -- present)\\ %Johns Hopkins Applied Physics Laboratory \\ \section{Office \\Address} 11100 Johns Hopkins Rd \\ Laurel, MD 20723 \\ United States \\ \section{Education} PhD in Astronomy \& Astrobiology (dual-titled PhD) \hfill (2014 -- 2020) \\ MS in Astronomy (2016) \\ University of Washington, Seattle, WA \\ \textit{Thesis:} \href{https://digital.lib.washington.edu/researchworks/handle/1773/46370}{``The Detection, Characterization, and Retrieval of Terrestrial Exoplanet Atmospheres''} \\ \textit{Advisor:} Victoria Meadows BS in Physics (Honors), Minor in Mathematics \hfill (2009 -- 2013) \\ University of California, Santa Cruz, CA \\ \textit{Advisor:} Jonathan Fortney \\ %\section{Research \\Interests} % \begin{itemize} \itemsep -1pt %reduce space between items % \item Characterizing terrestrial exoplanets for habitability and signs of life % \item Retrieving terrestrial planet atmospheres using Bayesian inference % \item Modeling telescope sensitivity to motivate future exoplanet science cases % \item Developing novel methods to detect exoplanet habitability and biosignatures \\ % \end{itemize} \section{Research \\Experience} {\sl Post Doctoral Fellow}: The Johns Hopkins Applied Physics Laboratory \hfill (2020 -- present)\\ Terrestrial exoplanet atmospheres, theory \& observation, mission concepts {\sl Graduate Research Assistant}: Virtual Planetary Laboratory \hfill (2014 -- 2020)\\ Terrestrial exoplanets, their atmospheres, habitability \& biosignatures %\begin{itemize} \itemsep -1pt %reduce space between items % \item Developed, tested, and applied a physically rigorous terrestrial exoplanet retrieval model % \item Simulated and analyzed radiative transfer, photochemical, climate, telescope, surface mapping, and machine learning models %\end{itemize} {\sl Undergraduate \& Postbaccalaureate Researcher}: University of California, Santa Cruz \hfill (2012 -- 2014)\\ Hot Jupiter \& brown dwarf atmospheres, opacity sources, and atmospheric retrieval \\ %\begin{itemize} \itemsep -1pt %reduce space between items % \item Retrieved exoplanet atmospheric compositions using emission spectra % \item Applied Bayesian methods for parameter estimation % \item Calculated and published weighted mean opacities for substellar and planetary atmospheres\\ %\end{itemize} \section{Honors, Awards, \& Funded Proposals} \begin{itemize} \itemsep -1pt %reduce space between items %\item Astrobiology Fellow at University of Washington Astrobiology Program (2014) \item \textbf{JWST Cycle 1 Co-PI:} \href{https://www.stsci.edu/jwst/science-execution/program-information?id=1981}{``Tell Me How I’m Supposed To Breathe With No Air: Measuring the Prevalence and Diversity of M-Dwarf Planet Atmospheres''} (2021) \item \textbf{NASA Group Achievement Award:} LUVOIR Mission Concept Study Team (2019) \item Honors undergraduate thesis in physics (2013) \item University Honor, \textit{cum laude} at University of California, Santa Cruz (2013)\\ \end{itemize} \section{Selected Publications} %{\sl First Authored} \begin{itemize} \item Mansfield, M., Schlawin, E., \textbf{Lustig-Yaeger, J.}, et al. (2020). \href{https://ui.adsabs.harvard.edu/abs/2020MNRAS.499.5151M/abstract}{``Eigenspectra: A Framework for Identifying Spectra from 3D Eclipse Mapping''}. \textit{Monthly Notices of the Royal Astronomical Society}. \item \textbf{Lustig-Yaeger, J.}, Meadows, V. S., \& Lincowski, A. P. (2019). \href{https://doi.org/10.3847/2041-8213/ab5965}{``A Mirage of the Cosmic Shoreline: Venus-like Clouds as a Statistical False Positive for Exoplanet Atmospheric Erosion''}. \textit{The Astrophysical Journal Letters}, 887(1), L11. \item \textbf{Lustig-Yaeger, J.}, Robinson, T. D., \& Arney, G. (2019). \href{https://doi.org/10.21105/joss.01387}{``\texttt{coronagraph}: Telescope Noise Modeling for Exoplanets in Python''}. \textit{Journal of Open Source Software}, 4(40), 1387. \item \textbf{Lustig-Yaeger, J.}, Meadows, V. S., \& Lincowski, A. P. (2019). \href{https://doi.org/10.3847/1538-3881/ab21e0}{``The Detectability and Characterization of the TRAPPIST-1 Exoplanet Atmospheres with JWST''}. \textit{The Astronomical Journal}, 158(1), 27. \item \textbf{Lustig-Yaeger, J.}, Meadows, V. S., Tovar Mendoza, G., Schwieterman, E. W., Fujii, Y., Luger, R., \& Robinson, T. D. (2018). \href{https://doi.org/10.3847/1538-3881/aaed3a}{``Detecting Ocean Glint on Exoplanets Using Multiphase Mapping''}. \textit{The Astronomical Journal}, 156(6), 301. \item Luger, R., \textbf{Lustig-Yaeger, J.}, \& Agol, E. (2017). \href{http://adsabs.harvard.edu/abs/2017ApJ...851...94L}{``Planet-Planet Occultations in TRAPPIST-1 and Other Exoplanet Systems''}. \textit{The Astrophysical Journal}, 851(2), 94. \item Fujii, Y., \textbf{Lustig-Yaeger, J.}, \& Cowan, N. B. (2017). \href{http://adsabs.harvard.edu/abs/2017arXiv170804886F}{``Rotational Spectral Unmixing of Exoplanets: Degeneracies between Surface Colors and Geography''}. \textit{The Astronomical Journal}, 154(5), 189. \end{itemize} \end{resume} \end{document}
section \<open>Derived facts about quantum registers\<close> theory Quantum_Extra imports Laws_Quantum Quantum begin no_notation meet (infixl "\<sqinter>\<index>" 70) no_notation Group.mult (infixl "\<otimes>\<index>" 70) no_notation Order.top ("\<top>\<index>") unbundle register_notation unbundle cblinfun_notation lemma zero_not_register[simp]: \<open>~ register (\<lambda>_. 0)\<close> unfolding register_def by simp lemma register_pair_is_register_converse: \<open>register (F;G) \<Longrightarrow> register F\<close> \<open>register (F;G) \<Longrightarrow> register G\<close> using [[simproc del: Laws_Quantum.compatibility_warn]] apply (cases \<open>register F\<close>) apply (auto simp: register_pair_def)[2] apply (cases \<open>register G\<close>) by (auto simp: register_pair_def)[2] lemma register_id'[simp]: \<open>register (\<lambda>x. x)\<close> using register_id by (simp add: id_def) lemma register_projector: assumes "register F" assumes "is_Proj a" shows "is_Proj (F a)" using assms unfolding register_def is_Proj_algebraic by metis lemma register_unitary: assumes "register F" assumes "unitary a" shows "unitary (F a)" using assms by (smt (verit, best) register_def unitary_def) lemma compatible_proj_intersect: (* I think this also holds without is_Proj premises, but my proof ideas use the Penrose-Moore pseudoinverse or simultaneous diagonalization and we do not have an existence theorem for either. *) assumes "compatible R S" and "is_Proj a" and "is_Proj b" shows "(R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>) = ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)" proof (rule antisym) have "((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (S b *\<^sub>S \<top>)" apply (subst swap_registers[OF assms(1)]) by (simp add: cblinfun_compose_image cblinfun_image_mono) moreover have "((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (R a *\<^sub>S \<top>)" by (simp add: cblinfun_compose_image cblinfun_image_mono) ultimately show \<open>((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>)\<close> by auto have "is_Proj (R a)" using assms(1) assms(2) compatible_register1 register_projector by blast have "is_Proj (S b)" using assms(1) assms(3) compatible_register2 register_projector by blast show \<open>(R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>) \<le> (R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>\<close> proof (unfold less_eq_ccsubspace.rep_eq, rule) fix \<psi> assume asm: \<open>\<psi> \<in> space_as_set ((R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>))\<close> then have \<open>\<psi> \<in> space_as_set (R a *\<^sub>S \<top>)\<close> by auto then have R: \<open>R a *\<^sub>V \<psi> = \<psi>\<close> using \<open>is_Proj (R a)\<close> cblinfun_fixes_range is_Proj_algebraic by blast from asm have \<open>\<psi> \<in> space_as_set (S b *\<^sub>S \<top>)\<close> by auto then have S: \<open>S b *\<^sub>V \<psi> = \<psi>\<close> using \<open>is_Proj (S b)\<close> cblinfun_fixes_range is_Proj_algebraic by blast from R S have \<open>\<psi> = (R a o\<^sub>C\<^sub>L S b) *\<^sub>V \<psi>\<close> by (simp add: cblinfun_apply_cblinfun_compose) also have \<open>\<dots> \<in> space_as_set ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)\<close> apply simp by (metis R S calculation cblinfun_apply_in_image) finally show \<open>\<psi> \<in> space_as_set ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)\<close> by - qed qed lemma compatible_proj_mult: assumes "compatible R S" and "is_Proj a" and "is_Proj b" shows "is_Proj (R a o\<^sub>C\<^sub>L S b)" using [[simproc del: Laws_Quantum.compatibility_warn]] using assms unfolding is_Proj_algebraic compatible_def apply auto apply (metis (no_types, lifting) cblinfun_compose_assoc register_mult) by (simp add: assms(2) assms(3) is_proj_selfadj register_projector) lemma unitary_sandwich_register: \<open>unitary a \<Longrightarrow> register (sandwich a)\<close> unfolding register_def apply (auto simp: sandwich_def) apply (metis (no_types, lifting) cblinfun_assoc_left(1) cblinfun_compose_id_right unitaryD1) by (simp add: lift_cblinfun_comp(2)) lemma sandwich_tensor: fixes a :: \<open>'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'a ell2\<close> and b :: \<open>'b::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'b ell2\<close> assumes \<open>unitary a\<close> \<open>unitary b\<close> shows "sandwich (a \<otimes>\<^sub>o b) = sandwich a \<otimes>\<^sub>r sandwich b" apply (rule tensor_extensionality) by (auto simp: unitary_sandwich_register assms sandwich_def register_tensor_is_register comp_tensor_op tensor_op_adjoint) lemma sandwich_grow_left: fixes a :: \<open>'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'a ell2\<close> assumes "unitary a" shows "sandwich a \<otimes>\<^sub>r id = sandwich (a \<otimes>\<^sub>o id_cblinfun)" by (simp add: unitary_sandwich_register assms sandwich_tensor sandwich_id) lemma register_sandwich: \<open>register F \<Longrightarrow> F (sandwich a b) = sandwich (F a) (F b)\<close> by (smt (verit, del_insts) register_def sandwich_def) lemma assoc_ell2_sandwich: \<open>assoc = sandwich assoc_ell2\<close> apply (rule tensor_extensionality3') apply (simp_all add: unitary_sandwich_register)[2] apply (rule equal_ket) apply (case_tac x) by (simp add: sandwich_def assoc_apply cblinfun_apply_cblinfun_compose tensor_op_ell2 assoc_ell2_tensor assoc_ell2'_tensor flip: tensor_ell2_ket) lemma assoc_ell2'_sandwich: \<open>assoc' = sandwich assoc_ell2'\<close> apply (rule tensor_extensionality3) apply (simp_all add: unitary_sandwich_register)[2] apply (rule equal_ket) apply (case_tac x) by (simp add: sandwich_def assoc'_apply cblinfun_apply_cblinfun_compose tensor_op_ell2 assoc_ell2_tensor assoc_ell2'_tensor flip: tensor_ell2_ket) lemma swap_sandwich: "swap = sandwich Uswap" apply (rule tensor_extensionality) apply (auto simp: sandwich_def)[2] apply (rule tensor_ell2_extensionality) by (simp add: sandwich_def cblinfun_apply_cblinfun_compose tensor_op_ell2) lemma id_tensor_sandwich: fixes a :: "'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'b::finite ell2" assumes "unitary a" shows "id \<otimes>\<^sub>r sandwich a = sandwich (id_cblinfun \<otimes>\<^sub>o a)" apply (rule tensor_extensionality) using assms by (auto simp: register_tensor_is_register comp_tensor_op sandwich_def tensor_op_adjoint unitary_sandwich_register) lemma compatible_selfbutter_join: assumes [register]: "compatible R S" shows "R (selfbutter \<psi>) o\<^sub>C\<^sub>L S (selfbutter \<phi>) = (R; S) (selfbutter (\<psi> \<otimes>\<^sub>s \<phi>))" apply (subst register_pair_apply[symmetric, where F=R and G=S]) using assms by auto lemma register_mult': assumes \<open>register F\<close> shows \<open>F a *\<^sub>V F b *\<^sub>V c = F (a o\<^sub>C\<^sub>L b) *\<^sub>V c\<close> by (simp add: assms lift_cblinfun_comp(4) register_mult) lemma register_scaleC: assumes \<open>register F\<close> shows \<open>F (c *\<^sub>C a) = c *\<^sub>C F a\<close> by (simp add: assms complex_vector.linear_scale) lemma register_bounded_clinear: \<open>register F \<Longrightarrow> bounded_clinear F\<close> using bounded_clinear_finite_dim register_def by blast lemma register_adjoint: "F (a*) = (F a)*" if \<open>register F\<close> using register_def that by blast end
= = Parks and recreation = =
You are currently viewing a selection of Cotton Shirt products filtered by your selection of 'materials: 'lace''. You can use the page links below to continue to view this selection. You have selected 'Cotton Shirt materials: 'lace'', Click on the links below to view more results from the 'Cotton Shirt materials: 'lace'' search.
lemma of_real_inverse [simp]: "of_real (inverse x) = inverse (of_real x :: 'a::{real_div_algebra,division_ring})"
National languages not covered by an authoritative language academy typically have multiple style guides — only some of which may discuss sentence spacing . This is the case in the United Kingdom . The Oxford Style Manual ( 2003 ) and the Modern Humanities Research Association 's MHRA Style Guide ( 2002 ) state that only single spacing should be used . In Canada , both the English and French language sections of the Canadian Style , A Guide to Writing and Editing ( 1997 ) , prescribe single sentence spacing . In the United States , many style guides — such as the Chicago Manual of Style ( 2003 ) — allow only single sentence spacing . The most important style guide in Italy , Il Nuovo <unk> di Stile ( 2009 ) , does not address sentence spacing , but the Guida di Stile Italiano ( 2010 ) , the official guide for Microsoft translation , tells users to use single sentence spacing " instead of the double spacing used in the United States " .
/-! # Monad Transformers In the previous sections you learned about some handy monads [Option](monads.lean.md), [IO](monads.lean.md), [Reader](readers.lean.md), [State](states.lean.md) and [Except](except.lean.md), and you now know how to make your function use one of these, but what you do not yet know is how to make your function use multiple monads at once. For example, suppose you need a function that wants to access some Reader context and optionally throw an exception? This would require composition of two monads `ReaderM` and `Except` and this is what monad transformers are for. A monad transformer is fundamentally a wrapper type. It is generally parameterized by another monadic type. You can then run actions from the inner monad, while adding your own customized behavior for combining actions in this new monad. The common transformers add `T` to the end of an existing monad name. You will find `OptionT`, `ExceptT`, `ReaderT`, `StateT` but there is no transformer for `IO`. So generally if you need `IO` it becomes the innermost wrapped monad. In the following example we use `ReaderT` to provide some read only context to a function and this `ReaderT` transformer will wrap an `Except` monad. If all goes well the `requiredArgument` returns the value of a required argument and `optionalSwitch` returns true if the optional argument is present. -/ abbrev Arguments := List String def indexOf? [BEq α] (xs : List α) (s : α) (start := 0): Option Nat := match xs with | [] => none | a :: tail => if a == s then some start else indexOf? tail s (start+1) def requiredArgument (name : String) : ReaderT Arguments (Except String) String := do let args ← read let value := match indexOf? args name with | some i => if i + 1 < args.length then args[i+1]! else "" | none => "" if value == "" then throw s!"Command line argument {name} missing" return value def optionalSwitch (name : String) : ReaderT Arguments (Except String) Bool := do let args ← read return match (indexOf? args name) with | some _ => true | none => false #eval requiredArgument "--input" |>.run ["--input", "foo"] -- Except.ok "foo" #eval requiredArgument "--input" |>.run ["foo", "bar"] -- Except.error "Command line argument --input missing" #eval optionalSwitch "--help" |>.run ["--help"] -- Except.ok true #eval optionalSwitch "--help" |>.run [] -- Except.ok false /-! Notice that `throw` was available from the inner `Except` monad. The cool thing is you can switch this around and get the exact same result using `ExceptT` as the outer monad transformer and `ReaderM` as the wrapped monad. Try changing requiredArgument to `ExceptT String (ReaderM Arguments) Bool`. Note: the `|>.` notation is described in [Readers](readers.lean.md#the-reader-solution). ## Adding more layers Here's the best part about monad transformers. Since the result of a monad transformer is itself a monad, you can wrap it inside another transformer! Suppose you need to pass in some read only context like the command line arguments, update some read-write state (like program Config) and optionally throw an exception, then you could write this: -/ structure Config where help : Bool := false verbose : Bool := false input : String := "" deriving Repr abbrev CliConfigM := StateT Config (ReaderT Arguments (Except String)) def parseArguments : CliConfigM Bool := do let mut config ← get if (← optionalSwitch "--help") then throw "Usage: example [--help] [--verbose] [--input <input file>]" config := { config with verbose := (← optionalSwitch "--verbose"), input := (← requiredArgument "--input") } set config return true def main (args : List String) : IO Unit := do let config : Config := { input := "default"} match parseArguments |>.run config |>.run args with | Except.ok (_, c) => do IO.println s!"Processing input '{c.input}' with verbose={c.verbose}" | Except.error s => IO.println s #eval main ["--help"] -- Usage: example [--help] [--verbose] [--input <input file>] #eval main ["--input", "foo"] -- Processing input file 'foo' with verbose=false #eval main ["--verbose", "--input", "bar"] -- Processing input 'bar' with verbose=true /-! In this example `parseArguments` is actually three stacked monads, `StateM`, `ReaderM`, `Except`. Notice the convention of abbreviating long monadic types with an alias like `CliConfigM`. ## Monad Lifting Lean makes it easy to compose functions that use different monads using a concept of automatic monad lifting. You already used lifting in the above code, because you were able to compose `optionalSwitch` which has type `ReaderT Arguments (Except String) Bool` and call it from `parseArguments` which has a bigger type `StateT Config (ReaderT Arguments (Except String))`. This "just worked" because Lean did some magic with monad lifting. To give you a simpler example of this, suppose you have the following function: -/ def divide (x : Float ) (y : Float): ExceptT String Id Float := if y == 0 then throw "can't divide by zero" else pure (x / y) #eval divide 6 3 -- Except.ok 2.000000 #eval divide 1 0 -- Except.error "can't divide by zero" /-! Notice here we used the `ExceptT` transformer, but we composed it with the `Id` identity monad. This is then the same as writing `Except String Float` since the identity monad does nothing. Now suppose you want to count the number of times divide is called and store the result in some global state: -/ def divideCounter (x : Float) (y : Float) : StateT Nat (ExceptT String Id) Float := do modify fun s => s + 1 divide x y #eval divideCounter 6 3 |>.run 0 -- Except.ok (2.000000, 1) #eval divideCounter 1 0 |>.run 0 -- Except.error "can't divide by zero" /-! The `modify` function is a helper which makes it easier to use `modifyGet` from the `StateM` monad. But something interesting is happening here, `divideCounter` is returning the value of `divide`, but the types don't match, yet it works? This is monad lifting in action. You can see this more clearly with the following test: -/ def liftTest (x : Except String Float) : StateT Nat (Except String) Float := x #eval liftTest (divide 5 1) |>.run 3 -- Except.ok (5.000000, 3) /-! Notice that `liftTest` returned `x` without doing anything to it, yet that matched the return type `StateT Nat (Except String) Float`. Monad lifting is provided by monad transformers. if you `#print liftTest` you will see that Lean is implementing this using a call to a function named `monadLift` from the `MonadLift` type class: ```lean,ignore class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α ``` So `monadLift` is a function for lifting a computation from an inner `Monad m α ` to an outer `Monad n α`. You could replace `x` in `liftTest` with `monadLift x` if you want to be explicit about it. The StateT monad transformer defines an instance of `MonadLift` like this: ```lean @[inline] protected def lift {α : Type u} (t : m α) : StateT σ m α := fun s => do let a ← t; pure (a, s) instance : MonadLift m (StateT σ m) := ⟨StateT.lift⟩ ``` This means that any monad `m` can be wrapped in a `StateT` monad by using the function `fun s => do let a ← t; pure (a, s)` that takes state `s`, runs the inner monad action `t`, and returns the result and the new state in a pair `(a, s)` without making any changes to `s`. Because `MonadLift` is a type class, Lean can automatically find the required `monadLift` instances in order to make your code compile and in this way it was able to find the `StateT.lift` function and use it to wrap the result of `divide` so that the correct type is returned from `divideCounter`. If you have an instance `MonadLift m n` that means there is a way to turn a computation that happens inside of `m` into one that happens inside of `n` and (this is the key part) usually *without* the instance itself creating any additional data that feeds into the computation. This means you can in principle declare lifting instances from any monad to any other monad, it does not, however, mean that you should do this in all cases. You can get a very nice report on how all this was done by adding the line `set_option trace.Meta.synthInstance true in` before `divideCounter` and moving you cursor to the end of the first line after `do`. This was a lot of detail, but it is very important to understand how monad lifting works because it is used heavily in Lean programs. ## Transitive lifting There is also a transitive version of `MonadLift` called `MonadLiftT` which can lift multiple monad layers at once. In the following example we added another monad layer with `ReaderT String ...` and notice that `x` is also automatically lifted to match. -/ def liftTest2 (x : Except String Float) : ReaderT String (StateT Nat (Except String)) Float := x #eval liftTest2 (divide 5 1) |>.run "" |>.run 3 -- Except.ok (5.000000, 3) /-! The ReaderT monadLift is even simpler than the one for StateT: ```lean,ignore instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x ``` This lift operation creates a function that defines the required `ReaderT` input argument, but the inner monad doesn't know or care about `ReaderT` so the monadLift function throws it away with the `_` then calls the inner monad action `x`. This is a perfectly legal implementation of the `ReaderM` monad. ## Add your own Custom MonadLift This does not compile: -/ def main2 : IO Unit := do try let ret ← divideCounter 5 2 |>.run 0 IO.println (toString ret) catch e => IO.println e /-! saying: ``` typeclass instance problem is stuck, it is often due to metavariables ToString ?m.4786 ``` The reason is `divideCounter` returns the big `StateT Nat (ExceptT String Id) Float` and that type cannot be automatically lifted into the `main` return type of `IO Unit` unless you give it some help. The following custom `MonadLift` solves this problem: -/ def liftIO (t : ExceptT String Id α) : IO α := do match t with | .ok r => EStateM.Result.ok r | .error s => EStateM.Result.error s instance : MonadLift (ExceptT String Id) IO where monadLift := liftIO def main3 : IO Unit := do try let ret ← divideCounter 5 2 |>.run 0 IO.println (toString ret) catch e => IO.println e #eval main3 -- (2.500000, 1) /-! It turns out that the `IO` monad you see in your `main` function is based on the `EStateM.Result` type which is similar to the `Except` type but it has an additional return value. The `liftIO` function converts any `Except String α` into `IO α` by simply mapping the ok case of the `Except` to the `Result.ok` and the error case to the `Result.error`. ## Lifting ExceptT In the previous [Except](except.lean.md) section you saw functions that `throw` Except values. When you get all the way back up to your `main` function which has type `IO Unit` you have the same problem you had above, because `Except String Float` doesn't match even if you use a `try/catch`. -/ def main4 : IO Unit := do try let ret ← divide 5 0 IO.println (toString ret) -- lifting happens here. catch e => IO.println s!"Unhandled exception: {e}" #eval main4 -- Unhandled exception: can't divide by zero /-! Without the `liftIO` the `(toString ret)` expression would not compile with a similar error: ``` typeclass instance problem is stuck, it is often due to metavariables ToString ?m.6007 ``` So the general lesson is that if you see an error like this when using monads, check for a missing `MonadLift`. ## Summary Now that you know how to combine your monads together, you're almost done with understanding the key concepts of monads! You could probably go out now and start writing some pretty nice code! But to truly master monads, you should know how to make your own, and there's one final concept that you should understand for that. This is the idea of type "laws". Each of the structures you've learned so far has a series of laws associated with it. And for your instances of these classes to make sense, they should follow the laws! Check out [Monad Laws](laws.lean.md). -/
(** * A constructor for polymorphic types *) Require Import Omega. Require Import Coq.Logic.Decidable. Require Import Coq.Program.Basics. Require Import Coq.Program.Equality. Require Import Coq.Setoids.Setoid. Require Import Coq.Classes.RelationClasses. Require Import Coq.Classes.Morphisms. Require Import Coq.Arith.Compare_dec. Require Import Coq.Arith.Plus. Require Export InformationOrdering. Require Import Nontermination. Require Import LeastFixedPoint. Require Import BohmTrees. Open Scope code_scope. (* ------------------------------------------------------------------------ *) (** ** Components for Bohm-out moves *) Section pair. Context {Var : Set}. Let x := make_var Var 0. Let y := make_var Var 1. Let f := make_var Var 2. Definition pair := Eval compute in close_var (\x,\y,\f, f * x * y). End pair. Notation "[ x , y ]" := (pair * x * y)%code : code_scope. Notation "[ x ]" := (C * I * x)%code : code_scope. Lemma pair_extensionality (Var : Set) (x y x' y' : Code Var) : [x, y] [= [x', y'] <-> x [= x' /\ y [= y'. Proof. unfold pair; beta_simpl; split. intro H; split. apply (code_le_ap_left _ _ _ K) in H; beta_simpl in H; auto. apply (code_le_ap_left _ _ _ (K*I)) in H; beta_simpl in H; auto. intros [Hx Hy]; auto. Qed. Section raise. Context {Var : Set}. Definition raise : Code Var := K. Definition lower : Code Var := [TOP]. Definition pull : Code Var := K || K * div. Definition push : Code Var := [BOT]. End raise. Lemma lower_raise (Var : Set) (x : Code Var) : lower * (raise * x) == x. Proof. unfold lower, raise; beta_simpl; reflexivity. Qed. Lemma push_pull (Var : Set) (x : Code Var) : push * (pull * x) == x. Proof. unfold push, pull; code_simpl; reflexivity. Qed. Lemma lower_pull (Var : Set) (x : Code Var) : lower * (pull * x) == TOP. Proof. unfold lower, pull; code_simpl; rewrite code_eq_div; code_simpl; reflexivity. Qed. Section exp. Context {Var : Set}. Let a := make_var Var 0. Let b := make_var Var 1. Let f := make_var Var 2. Definition exp := Eval compute in close_var (\a, \b, \f, b o f o a). End exp. Notation "x --> y" := (exp * x * y)%code : code_scope. Lemma exp_i_i (Var : Set) : I --> I == (I : Code Var). Proof. unfold exp; beta_eta. Qed. Section compose. Context {Var : Set}. Let s := make_var Var 0. Let a := make_var Var 1. Let a' := make_var Var 2. Let b := make_var Var 3. Let b' := make_var Var 4. Definition compose := Eval compute in close_var (\s, s*\a,\a', s*\b,\b', [a o b, b' o a']). Definition conjugate := Eval compute in close_var (\s, s*\a,\a', s*\b,\b', [a' --> b, a --> b']). End compose. Lemma compose_pair_le (Var : Set) (s1 r1 s2 r2 : Code Var) : [s1 o s2, r2 o r1] [= compose * ([s1, r1] || [s2, r2]). Proof. unfold compose, pair; beta_reduce. rewrite pi_j_left, pi_j_right; reflexivity. Qed. Lemma conjugate_pair_le (Var : Set) (s1 r1 s2 r2 : Code Var) : [r1 --> s2, s1 --> r2] [= conjugate * ([s1, r1] || [s2, r2]). Proof. unfold conjugate, pair; beta_reduce. rewrite pi_j_left, pi_j_right. unfold exp; code_simpl; reflexivity. Qed. (* ------------------------------------------------------------------------ *) (** ** A constructive definition of [A] *) Definition A_step {Var : Set} : Code Var := K * ([I, I] || [raise, lower] || [pull, push]) || (compose || conjugate). Definition A {Var : Set} : Code Var := Eval compute in Y * A_step. Lemma A_simpl (Var : Set) : (A : Code Var) == Y * A_step. Proof. (freeze code_eq in compute); auto. Qed. Ltac A_simpl := rewrite A_simpl; unfold A_step. (** We will make much use of the following theorems *) Theorem A_fixes (Var : Set) (f x : Code Var) : (forall s r : Code Var, r o s [= I -> f * s * r * x [= x) -> A * f * x [= x. Proof. intro H. (* TODO use a join argument: A = Join ys and forall y in ys, y f x [= x *) Admitted. Lemma A_exp_top (Var : Set) : A * exp * TOP == (TOP : Code Var). Proof. split; auto. A_simpl; unfold exp, pair; rewrite code_eq_y; do 3 rewrite pi_j_left. eta_expand as x; beta_simpl; auto. Qed. (* ------------------------------------------------------------------------ *) (** ** Using the Bohm-out method through [A] *) Lemma A_move_i_i (Var : Set) : [I, I] [= (A : Code Var). Proof. A_simpl; rewrite code_eq_y, pi_j_left, beta_k, pi_j_left, pi_j_left; reflexivity. Qed. Lemma A_move_raise_lower (Var : Set) : [raise, lower] [= (A : Code Var). Proof. A_simpl; rewrite code_eq_y, pi_j_left, beta_k, pi_j_left, pi_j_right; reflexivity. Qed. Lemma A_move_pull_push (Var : Set) : [pull, push] [= (A : Code Var). Proof. A_simpl; rewrite code_eq_y, pi_j_left, beta_k, pi_j_right; reflexivity. Qed. Lemma A_move_compose (Var : Set) (s1 r1 s2 r2 : Code Var) : [s1, r1] [= A -> [s2, r2] [= A -> [s1 o s2, r2 o r1] [= A. Proof. rewrite A_simpl at 3; rewrite code_eq_y; rewrite <- A_simpl. unfold A_step; rewrite pi_j_right, pi_j_left. intros H1 H2. assert ([s1, r1] || [s2, r2] [= A) as H; auto; rewrite <- H. apply compose_pair_le. Qed. Lemma A_move_conjugate (Var : Set) (s1 r1 s2 r2 : Code Var) : [s1, r1] [= A -> [s2, r2] [= A -> [r1 --> s2, s1 --> r2] [= A. Proof. rewrite A_simpl at 3; rewrite code_eq_y; rewrite <- A_simpl. unfold A_step; rewrite pi_j_right, pi_j_right. intros H1 H2. assert ([s1, r1] || [s2, r2] [= A) as H; auto; rewrite <- H. apply conjugate_pair_le. Qed. Lemma A_move_raise_lower_n (Var : Set) (n : nat) : [raise^n, lower^n] [= (A : Code Var). Proof. induction n; simpl. - apply A_move_i_i. - rewrite power_commute_1'; apply A_move_compose; auto. apply A_move_raise_lower. Qed. Lemma A_move_pull_push_n (Var : Set) (n : nat) : [pull^n, push^n] [= (A : Code Var). Proof. induction n; simpl. - apply A_move_i_i. - rewrite power_commute_1'; apply A_move_compose; auto. apply A_move_pull_push. Qed. Hint Resolve A_move_i_i A_move_raise_lower A_move_pull_push A_move_compose A_move_conjugate A_move_raise_lower_n A_move_pull_push_n : A_moves. Lemma lower_top (n : nat) : lower^n * TOP == (TOP : ClosedCode). Proof. induction n; simpl; code_simpl; auto. rewrite IHn; unfold lower; code_simpl; auto. Qed. Lemma push_top (n : nat) : push^n * TOP == (TOP : ClosedCode). Proof. induction n; simpl; code_simpl; auto. rewrite IHn; unfold push; code_simpl; auto. Qed. Lemma lower_k (n : nat) (x : ClosedCode) : lower^n * (K^n * x) == x. Proof. revert x; induction n; intro x; simpl; code_simpl; auto. setoid_rewrite power_commute_1 at 2. rewrite IHn; unfold lower; beta_simpl; reflexivity. Qed. Lemma push_k (n : nat) (x : ClosedCode) : push^n * (K^n * x) == x. Proof. revert x; induction n; intro x; simpl; code_simpl; auto. setoid_rewrite power_commute_1 at 2. rewrite IHn; unfold push; beta_simpl; reflexivity. Qed. Lemma raise_c_i_bot (n : nat) (x : ClosedCode) : [BOT]^n * (raise^n * x) == x. Proof. revert x; induction n; intro x; simpl; code_simpl; auto. rewrite power_commute_1, IHn; unfold raise; beta_simpl; reflexivity. Qed. Lemma pull_c_i_bot (n : nat) (x : ClosedCode) : [BOT]^n * (pull^n * x) == x. Proof. revert x; induction n; intro x; simpl; code_simpl; auto. rewrite power_commute_1, IHn; unfold pull; code_simpl; reflexivity. Qed. Ltac bohm_out := split; code_simpl; auto with A_moves; eta_expand; code_simpl. Lemma bohm_out_repair (b : nat) : exists s r : ClosedCode, [s, r] [= A /\ I [= r o K ^ b o [BOT] ^ b o s. Proof. exists (raise^b), (lower^b); bohm_out. rewrite raise_c_i_bot, lower_k; reflexivity. Qed. Lemma bohm_out_too_many_args (k d : nat) : exists s r : ClosedCode, [s, r] [= A /\ TOP [= r o K ^ k o [BOT] ^ (1 + k + d) o s. Proof. exists (raise^(1+d+k) o pull), (push o lower^(1+d+k)); bohm_out. replace (1 + k + d) with (1 + d + k) by omega. rewrite power_add, raise_c_i_bot, lower_k. replace (1 + d) with (d + 1) by omega. rewrite power_add; code_simpl. rewrite lower_pull, lower_top. unfold push; code_simpl; auto. Qed. Lemma bohm_out_too_few_args (b d : nat) : exists s r : ClosedCode, [s, r] [= A /\ TOP [= r o K ^ (1 + d + b) o [BOT] ^ b o s. Proof. exists (pull^(1+d+b) o raise), (lower o push^(1+d+b)); bohm_out. rewrite push_k; code_simpl. replace (1 + d + b) with (b + (1 + d)) by omega. rewrite power_add; code_simpl. rewrite pull_c_i_bot, power_add; simpl; beta_simpl. rewrite lower_pull; reflexivity. Qed. Lemma bohm_out_wrong_head (h k b : nat) : exists s r : ClosedCode, [s, r] [= A /\ TOP [= r o (K ^ (1 + h) * K ^ k o [BOT] ^ b) o s. Proof. exists (raise^(k+1+h)), (lower^(k+1+h)); bohm_out. setoid_rewrite power_add at 1; simpl; code_simpl. rewrite lower_k. setoid_rewrite power_add; simpl; code_simpl. unfold lower at 2; code_simpl. rewrite lower_k. apply push_top. Qed. (* ------------------------------------------------------------------------ *) (** ** Construction of Bohm tree witnesses *) Lemma lt_add (p q : nat) : p <= q -> exists r, q = p + r. Proof. intro H; induction H; eauto. destruct IHle as [r IH]. exists (Succ r); rewrite IH; auto. Qed. Lemma nle_bot_witness (x : ClosedCode) : ~x [= BOT -> exists h k b, K ^ h * K ^ k o [BOT] ^ b [= x. Proof. intro H; apply conv_nle_bot in H. rewrite conv_closed in H; destruct H as [y [xy yt]]. apply weaken_probe in xy; apply weaken_pi in yt. dependent induction yt; eauto. - admit. - admit. Qed. (** This follows %\cite{obermeyer2009equational}% pp. 48 Lemma 3.6.11. *) Theorem A_repairs_pair (i : ClosedCode) : ~ i [= BOT -> exists s r, [s, r] [= A /\ I [= r o i o s. Proof. intro H; apply nle_bot_witness in H; destruct H as [h [k [b H]]]. setoid_rewrite <- H; clear H i. destruct h. - (* case: correct head variable *) simpl; setoid_rewrite beta_i; setoid_rewrite code_eq_b_assoc. set (kb := lt_eq_lt_dec k b); destruct kb as [[Hlt | Heq] | Hgt]. + (* case: too many arguments *) apply lt_add in Hlt; destruct Hlt as [d Ed]; subst. replace (Datatypes.S k) with (1 + k) by omega. setoid_rewrite (@code_le_top _ I) at 1. apply bohm_out_too_many_args. + (* case: correct number of arguments *) subst. apply bohm_out_repair. + (* case: too few arguments *) apply lt_add in Hgt; destruct Hgt as [d Ed]; subst. replace (Datatypes.S b + d) with (1 + d + b) by omega. setoid_rewrite (@code_le_top _ I) at 1. eapply bohm_out_too_few_args. - (* case: incorrect head variable *) replace (Datatypes.S h) with (1 + h) by omega. setoid_rewrite (@code_le_top _ I) at 1. apply bohm_out_wrong_head. Qed. Corollary A_repairs (i : ClosedCode) : ~ i [= BOT -> I [= A * exp * i. Proof. intro H; apply A_repairs_pair in H; destruct H as [s [r [Ha Hi]]]. rewrite <- Ha; unfold pair, exp; code_simpl. assumption. Qed. (* TODO state and prove a [nle_i_witness] lemma Inductive Increasing : ClosedCode -> Prop := | Increasing_head (h k b : nat) : Increasing (K ^ (1 + h) * K ^ k o [BOT] ^ b) | Increasing_arg : ??? . Lemma nle_i_witness (x : ClosedCode) : ~x [= I -> ???. *) Theorem A_raises_pair (i : ClosedCode) : ~ i [= I -> exists s r, [s, r] [= A /\ TOP [= r o i o s. Proof. admit. Qed. Corollary A_raises (i : ClosedCode) : ~ i [= I -> TOP [= A * exp * i. Proof. intro H; apply A_raises_pair in H; destruct H as [s [r [Ha Hi]]]. rewrite <- Ha; unfold pair, exp; code_simpl. assumption. Qed. (* TODO the following two theorems need stronger induction hypotheses, of higher type *) Theorem A_repairs' (i : ClosedCode) : ~ i [= BOT -> I [= A * exp * i. Proof. repeat rewrite <- decompile_le. do 2 rewrite decompile_app; freeze A in freeze exp in simpl. set (i' := decompile i); subst. intro H; apply nle_normal_witness in H; destruct H as [n [Hn [ni nb]]]. rewrite <- ni; clear i i' ni; revert nb. induction Hn; intro Hnle. - admit. (* TODO deal with TOP *) - assert ((BOT [= (BOT : Term Var))%term); [reflexivity | contradiction]. - rewrite term_le_join in Hnle. apply not_and in Hnle; auto. destruct Hnle as [Hx | Hy]; [rewrite <- term_le_join_left | rewrite <- term_le_join_right]; auto. - admit. (* TODO use [pconv] instead of [conv] *) (* the last three cases require shifting down and up type. *) - admit. (* TODO prove a lemma about [inert] terms *) - admit. Qed. Theorem A_raises' (i : ClosedCode) : ~ i [= I -> TOP [= A * exp * i. Proof. repeat rewrite <- decompile_le. do 2 rewrite decompile_app; freeze A in freeze exp in simpl. set (i' := decompile i); subst. intro H; apply nle_normal_witness in H; destruct H as [n [Hn [ni nb]]]. rewrite <- ni; clear i i' ni; revert nb. induction Hn; intro Hnle. - admit. (* TODO deal with TOP *) - assert ((BOT [= (DeBruijn.I : Term Var))%term); [term_to_code | contradiction]. - rewrite term_le_join in Hnle. apply not_and in Hnle; auto. destruct Hnle as [Hx | Hy]; [rewrite <- term_le_join_left | rewrite <- term_le_join_right]; auto. - admit. (* TODO use [pconv] instead of [conv] *) (* the last three cases require shifting down and up type. *) - admit. (* TODO prove a lemma about [inert] terms *) - admit. Qed. (** To generalize to probability, we need two parametrized relations [code_ple] and [code_pnle] meaning that at least [p] of the time, [code_le] or [~ code_le] holds. Note that [code_pnle] is stronger than "it is false that [code_le] holds at least p of the time". *) Definition code_ple (p : dyadic) {Var : Set} (x y : Code Var) := x [= dyadic_sub x y p. (* FIXME Is this right? *) Definition code_pnle (p : dyadic) {Var : Set} (x y : Code Var) := ~ x || y [= dyadic_sub x y p. Theorem A_repairs_prob (i : ClosedCode) (p : dyadic) : code_pnle p i BOT -> code_ple p I (A * exp * i). Proof. admit. Qed. Theorem A_raises_prob (i : ClosedCode) (p : dyadic) : ~ i [= (dyadic_sub BOT I p) -> dyadic_sub BOT TOP p [= A * exp * i. Proof. admit. Qed. Notation "\\ x , y ; z" := (A * \x, \y, z)%code : code_scope. Section A_example. Variable Var : Set. Let a := make_var Var 0. Let a' := make_var Var 1. Let A_example : Code Var := close_var (\\a,a'; a --> a'). End A_example.
State Before: α : Type u_1 β : Type u_2 inst✝² : LinearOrderedField α inst✝¹ : Ring β abv : β → α inst✝ : IsAbsoluteValue abv g f : CauSeq β abv hf : f ≈ 0 this : LimZero (f - 0) ⊢ LimZero f State After: no goals Tactic: simpa State Before: α : Type u_1 β : Type u_2 inst✝² : LinearOrderedField α inst✝¹ : Ring β abv : β → α inst✝ : IsAbsoluteValue abv g f : CauSeq β abv hf : f ≈ 0 this✝ : LimZero (f - 0) this : LimZero (g * f) ⊢ LimZero (g * f - 0) State After: no goals Tactic: simpa
{-# LANGUAGE FlexibleContexts #-} module Image.Transform where import Data.Array.Repa as R import Data.Array.Repa.Stencil as R import Data.Array.Repa.Stencil.Dim2 as R import Data.DList as DL import Data.List as L import Data.Vector.Unboxed as VU import Numeric.LinearAlgebra as NL -- factor = 2^n, n = 0,1,.. -- the first factor in the list corresponds to the inner-most (right-most) dimension. {-# INLINE downsample #-} downsample :: (Source s e, Shape sh) => [Int] -> R.Array s sh e -> R.Array D sh e downsample factorList arr | L.all (== 1) factorList = delay arr | L.any (< 1) newDList = error "Downsample factors are too large." | otherwise = R.backpermute (shapeOfList newDList) (shapeOfList . L.zipWith (*) factorList . listOfShape) arr where dList = listOfShape . extent $ arr newDList = L.zipWith div dList factorList {-# INLINE downsampleUnsafe #-} downsampleUnsafe :: (Source s e, Shape sh) => [Int] -> R.Array s sh e -> R.Array D sh e downsampleUnsafe factorList arr = R.backpermute newSh (shapeOfList . L.zipWith (*) factorList . listOfShape) arr where dList = listOfShape $ extent arr newSh = shapeOfList $ L.zipWith div dList factorList {-# INLINE upsample #-} upsample :: (Source s e, Shape sh, Num e) => [Int] -> R.Array s sh e -> R.Array D sh e upsample factorList arr | L.all (== 1) factorList = delay arr | L.any (< 1) factorList = error $ "upsample: factor must be >= 1.\n" L.++ show factorList | otherwise = R.backpermuteDft (fromFunction (shapeOfList $ L.zipWith (*) (listOfShape . extent $ arr) factorList) (const 0)) (\shape -> if L.all (== 0) . L.zipWith (flip mod) factorList . listOfShape $ shape then Just . shapeOfList . L.zipWith (flip div) factorList . listOfShape $ shape else Nothing) arr {-# INLINE crop #-} crop :: (Source s e, Shape sh) => [Int] -> [Int] -> R.Array s sh e -> R.Array D sh e crop start len arr | L.any (< 0) start || L.or (L.zipWith3 (\x y z -> x > (z - y)) start len dList) = error $ "Crop out of boundary!\n" L.++ show start L.++ "\n" L.++ show len L.++ "\n" L.++ show dList | L.length start /= L.length len || L.length start /= L.length dList = error $ "crop: dimension error. \n start: " L.++ show (L.length start) L.++ " len:" L.++ show (L.length len) L.++ " arr:" L.++ show (L.length dList) | otherwise = R.backpermute (shapeOfList len) (shapeOfList . L.zipWith (+) start . listOfShape) arr where dList = listOfShape $ extent arr {-# INLINE cropUnsafe #-} cropUnsafe :: (Source s e, Shape sh) => [Int] -> [Int] -> R.Array s sh e -> R.Array D sh e cropUnsafe start len = R.backpermute (shapeOfList len) (shapeOfList . L.zipWith (+) start . listOfShape) {-# INLINE pad #-} pad :: (Source s e, Shape sh) => [Int] -> e -> R.Array s sh e -> R.Array D sh e pad newDims padVal arr | L.all (== 0) diff = delay arr | otherwise = backpermuteDft (fromFunction (shapeOfList dimList) (const padVal)) (\sh' -> let idx = L.zipWith (-) (listOfShape sh') diff in if L.or (L.zipWith (\i j -> i < 0 || (i >= j)) idx oldDimList) then Nothing else Just $ shapeOfList idx) arr where oldDimList = listOfShape . extent $ arr dimList = L.zipWith max newDims oldDimList diff = L.zipWith (\a b -> if a - b <= 0 then 0 else if a - b == 1 then 1 else div (a - b) 2) newDims oldDimList {-# INLINE normalizeValueRange #-} normalizeValueRange :: (Source r e, Shape sh, Num e, Fractional e, Ord e, Unbox e) => (e, e) -> R.Array r sh e -> R.Array D sh e normalizeValueRange (minVal, maxVal) arr | maxV == minV = delay arr | otherwise = R.map (\x -> (x - minV) / (maxV - minV) * (maxVal - minVal) + minVal) $ arr where vec = computeUnboxedS . delay $ arr minV = VU.minimum . toUnboxed $ vec maxV = VU.maximum . toUnboxed $ vec {-# INLINE computeDerivativeS #-} computeDerivativeS :: (R.Source r e, Num e, Fractional e) => R.Array r DIM2 e -> R.Array D DIM3 e computeDerivativeS arr = L.foldl' R.append (R.extend (Z :. R.All :. R.All :. (1 :: Int)) arr) ds where xStencil = makeStencil2 3 3 $ \ix -> case ix of Z :. 0 :. (-1) -> Just (-1) Z :. 0 :. 1 -> Just 1 _ -> Nothing yStencil = makeStencil2 3 3 $ \ix -> case ix of Z :. -1 :. 0 -> Just (-1) Z :. 1 :. 0 -> Just 1 _ -> Nothing xyStencil = makeStencil2 3 3 $ \ix -> case ix of Z :. -1 :. -1 -> Just 1 Z :. -1 :. 1 -> Just (-1) Z :. 1 :. -1 -> Just (-1) Z :. 1 :. 1 -> Just 1 _ -> Nothing ds = L.map (\s -> extend (Z :. R.All :. R.All :. (1 :: Int)) . R.map (/ 2) $ mapStencil2 BoundClamp s arr) [xStencil, yStencil, xyStencil] {-# INLINE bicubicInterpolation #-} bicubicInterpolation :: (R.Source r Double) => ((Int, Int) -> (Double, Double)) -> (Int, Int) -> R.Array r DIM2 Double -> R.Array U DIM2 Double bicubicInterpolation idxFunc (newCols, newRows) arr = let (Z :. cols :. rows) = extent arr derivative = computeDerivativeS arr derivative16 = R.traverse derivative (const (Z :. newCols :. newRows :. 4 :. (4 :: Int))) (\f (Z :. a :. b :. derivativeIdx :. pairIdx) -> let (x, y) = idxFunc (a, b) (x', y') = case pairIdx of 0 -> (floor x, floor y) 1 -> (floor x, ceiling y) 2 -> (ceiling x, floor y) 3 -> (ceiling x, ceiling y) in if (x' < 0) || (x' > (fromIntegral cols - 1)) || (y' < 0) || (y' > (fromIntegral rows - 1)) then 0 else f (Z :. x' :. y' :. derivativeIdx)) mat = ((newRows * newCols) >< 16) . R.toList $ derivative16 multiplicationResultArray = fromListUnboxed (Z :. newCols :. newRows :. 4 :. 4) . NL.toList . flatten $ mat NL.<> maxtrixA in R.sumS . R.sumS $ R.traverse multiplicationResultArray id (\f idx@(Z :. a :. b :. i :. j) -> let (x, y) = idxFunc (a, b) x' = x - fromIntegral (floor x :: Int) y' = y - fromIntegral (floor y :: Int) in f idx * (x' ^ i) * (y' ^ j)) where maxtrixA = NL.fromColumns . L.map NL.fromList $ [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , [-3, 3, 0, 0, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , [2, -2, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] , [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] , [0, 0, 0, 0, 0, 0, 0, 0, -3, 3, 0, 0, -2, -1, 0, 0] , [0, 0, 0, 0, 0, 0, 0, 0, 2, -2, 0, 0, 1, 1, 0, 0] , [-3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0, 0, 0, 0, 0] , [0, 0, 0, 0, -3, 0, 3, 0, 0, 0, 0, 0, -2, 0, -1, 0] , [9, -9, -9, 9, 6, 3, -6, -3, 6, -6, 3, -3, 4, 2, 2, 1] , [-6, 6, 6, -6, -3, -3, 3, 3, -4, 4, -2, 2, -2, -2, -1, -1] , [2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0] , [0, 0, 0, 0, 2, 0, -2, 0, 0, 0, 0, 0, 1, 0, 1, 0] , [-6, 6, 6, -6, -4, -2, 4, 2, -3, 3, -3, 3, -2, -1, -2, -1] , [4, -4, -4, 4, 2, 2, -2, -2, 2, -2, 2, -2, 1, 1, 1, 1] ] {-# INLINE bilinearInterpolation #-} bilinearInterpolation :: (R.Source r Double) => ((Int, Int) -> (Double, Double)) -> (Int, Int) -> R.Array r DIM2 Double -> R.Array U DIM2 Double bilinearInterpolation idxFunc (newCols, newRows) arr = let (Z :. cols :. rows) = extent arr in computeS . R.traverse arr id $ \f (Z :. a :. b) -> let (x, y) = idxFunc (a, b) x1 = floor x x2 = ceiling x y1 = floor y y2 = ceiling y q11 = f (Z :. x1 :. y1) q12 = f (Z :. x1 :. y2) q21 = f (Z :. x2 :. y1) q22 = f (Z :. x2 :. y2) r1 = ((fromIntegral x2 - x) / fromIntegral (x2 - x1)) * q11 + ((x - fromIntegral x1) / fromIntegral (x2 - x1)) * q21 r2 = ((fromIntegral x2 - x) / fromIntegral (x2 - x1)) * q12 + ((x - fromIntegral x1) / fromIntegral (x2 - x1)) * q22 p = ((fromIntegral y2 - y) / fromIntegral (y2 - y1)) * r1 + ((y - fromIntegral y1) / fromIntegral (y2 - y1)) * r2 in if (x < 0) || (x > (fromIntegral cols - 1)) || (y < 0) || (y > (fromIntegral rows - 1)) then 0 else if x1 == x2 then if y1 == y2 then q11 else ((fromIntegral y2 - y) / fromIntegral (y2 - y1)) * q11 + ((y - fromIntegral y1) / fromIntegral (y2 - y1)) * q12 else if y1 == y2 then r1 else p {-# INLINE resize2D #-} resize2D :: (Source s Double) => (Int, Int) -> (Double, Double) -> R.Array s DIM2 Double -> R.Array D DIM2 Double resize2D newSize@(newNx, newNy) bound arr = normalizeValueRange bound $ bicubicInterpolation (\(i, j) -> (ratioX * fromIntegral i, ratioY * fromIntegral j)) newSize arr where (Z :. nx' :. ny') = extent arr ratioX = fromIntegral nx' / fromIntegral newNx ratioY = fromIntegral ny' / fromIntegral newNy {-# INLINE resize25D #-} resize25D :: (Source s Double) => (Int, Int) -> (Double, Double) -> R.Array s DIM3 Double -> R.Array D DIM3 Double resize25D newSize@(newNx, newNy) bound arr = normalizeValueRange bound . fromUnboxed (Z :. nf' :. newNx :. newNy) . VU.concat . L.map (\i -> toUnboxed . bicubicInterpolation (\(i, j) -> (ratioX * fromIntegral i, ratioY * fromIntegral j)) newSize . R.slice arr $ (Z :. i :. R.All :. R.All)) $ [0 .. nf' - 1] where (Z :. nf' :. nx' :. ny') = extent arr ratioX = fromIntegral nx' / fromIntegral newNx ratioY = fromIntegral ny' / fromIntegral newNy {-# INLINE resize2DFixedRatio #-} resize2DFixedRatio :: (Source s Double) => Int -> (Double, Double) -> R.Array s DIM2 Double -> R.Array D DIM2 Double resize2DFixedRatio n bound arr = normalizeValueRange bound $ bicubicInterpolation (\(i, j) -> (ratio * fromIntegral i, ratio * fromIntegral j)) newSize arr where (Z :. nx' :. ny') = extent arr newSize = if nx' > ny' then (n, round $ fromIntegral ny' * ratio) else (round $ fromIntegral nx' * ratio, n) ratio = fromIntegral (max nx' ny') / fromIntegral n {-# INLINE resize25DFixedRatio #-} resize25DFixedRatio :: (Source s Double) => Int -> (Double, Double) -> R.Array s DIM3 Double -> R.Array D DIM3 Double resize25DFixedRatio n bound arr = normalizeValueRange bound . fromUnboxed (Z :. nf' :. newNx :. newNy) . VU.concat . L.map (\i -> toUnboxed . bicubicInterpolation (\(i, j) -> (ratio * fromIntegral i, ratio * fromIntegral j)) newSize . R.slice arr $ (Z :. i :. R.All :. R.All)) $ [0 .. nf' - 1] where (Z :. nf' :. nx' :. ny') = extent arr newSize@(newNx, newNy) = if nx' > ny' then (n, round $ fromIntegral ny' * ratio) else (round $ fromIntegral nx' * ratio, n) ratio = fromIntegral (max nx' ny') / fromIntegral n {-# INLINE rescale2D #-} rescale2D :: (Source s Double) => Double -> (Double, Double) -> R.Array s DIM2 Double -> R.Array D DIM2 Double rescale2D scale bound arr = normalizeValueRange bound $ bicubicInterpolation (\(i, j) -> (fromIntegral i / scale, fromIntegral j / scale)) (round $ scale * fromIntegral nx', round $ scale * fromIntegral ny') arr where (Z :. nx' :. ny') = extent arr {-# INLINE rescale25D #-} rescale25D :: (Source s Double) => Double -> (Double, Double) -> R.Array s DIM3 Double -> R.Array D DIM3 Double rescale25D scale bound arr = normalizeValueRange bound . fromUnboxed (Z :. nf' :. newNx :. newNy) . VU.concat . L.map (\i -> toUnboxed . bicubicInterpolation (\(i, j) -> (fromIntegral i / scale, fromIntegral j / scale)) (newNx, newNy) . R.slice arr $ (Z :. i :. R.All :. R.All)) $ [0 .. nf' - 1] where (Z :. nf' :. nx' :. ny') = extent arr newNx = round $ scale * fromIntegral nx' newNy = round $ scale * fromIntegral ny' {-# INLINE rotate2D #-} rotate2D :: (Source s Double) => Double -> (Double, Double) -> R.Array s DIM2 Double -> R.Array U DIM2 Double rotate2D theta (centerX, centerY) arr = bicubicInterpolation (\(i, j) -> let i' = fromIntegral i - centerX j' = fromIntegral j - centerY in ( i' * cos theta - j' * sin theta + centerX , i' * sin theta + j' * cos theta + centerY)) (nx', ny') arr where (Z :. nx' :. ny') = extent arr {-# INLINE rotate25D #-} rotate25D :: (Source s Double) => Double -> (Double, Double) -> R.Array s DIM3 Double -> R.Array U DIM3 Double rotate25D theta (centerX, centerY) arr = fromUnboxed (Z :. nf' :. nx' :. ny') . VU.concat . L.map (\i -> toUnboxed . -- bicubicInterpolation bilinearInterpolation (\(i, j) -> let i' = fromIntegral i - centerX j' = fromIntegral j - centerY in ( i' * cos theta - j' * sin theta + centerX , i' * sin theta + j' * cos theta + centerY)) (nx', ny') . R.slice arr $ (Z :. i :. R.All :. R.All)) $ [0 .. nf' - 1] where (Z :. nf' :. nx' :. ny') = extent arr
{-# language InstanceSigs, DerivingStrategies #-} {-# language PartialTypeSignatures #-} {-# OPTIONS_GHC -fno-warn-partial-type-signatures #-} {-| This module defines the 'Shaped' typeclass, which is used to generically manipulate values as fixed-points of higher-order functors in order to analyze their structure, e.g. while observing evaluation. If you just care about testing the strictness of functions over datatypes which are already instances of @Shaped@, you don't need to use this module. __Important note:__ To define new instances of 'Shaped' for types which implement 'GHC.Generic', __an empty instance will suffice__, as all the methods of 'Shaped' can be filled in by generic implementations. For example: > import GHC.Generics as GHC > import Generics.SOP as SOP > > data D = C deriving (GHC.Generic) > > instance SOP.Generic D > instance SOP.HasDatatypeInfo D > > instance Shaped D Using the @DeriveAnyClass@ extension, this can be shortened to one line: > data D = C deriving (GHC.Generic, SOP.Generic, SOP.HasDatatypeInfo, Shaped) Manual instances of 'Shaped' are necessary for types which do not or cannot implement GHC's @Generic@ typeclass, such as existential types, abstract types, and GADTs. This module is heavily based upon the approach in "Data.Functor.Foldable", which in turn is modeled after the paper "Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire" (1991) by Erik Meijer, Maarten Fokkinga and Ross Paterson. If you don't yet understand recursion schemes and want to understand this module, it's probably a good idea to familiarize yourself with "Data.Functor.Foldable" before diving into this higher-order generalization. -} module Test.StrictCheck.Shaped ( Shaped(..) , module Test.StrictCheck.Shaped.Flattened -- * Fixed-points of 'Shape's , type (%)(..) -- * Folds and unfolds over fixed-points of @Shape@s , unwrap , interleave , (%) , fuse , translate , fold , unfold , unzipWith -- , reshape -- * Rendering 'Shaped' things as structured text , QName , Rendered(..) , RenderLevel(..) , renderfold -- * Tools for manually writing instances of 'Shaped' -- ** Implementing 'Shaped' for primitive types , Prim(..), unPrim , projectPrim , embedPrim , matchPrim , flatPrim , renderPrim , renderConstant -- ** Implementing 'Shaped' for container types , Containing(..) , projectContainer , embedContainer -- * Generic implementation of the methods of 'Shaped' , GShaped , GShape(..) , gProject , gEmbed , gMatch , gRender ) where import Type.Reflection import Data.Functor.Product import Data.Bifunctor import Data.Bifunctor.Flip import Data.Coerce import Generics.SOP hiding ( Shape ) import Data.Complex -- import Data.List.NonEmpty (NonEmpty(..)) import Test.StrictCheck.Shaped.Flattened -- TODO: provide instances for all of Base -- | When a type @a@ is @Shaped@, we know how to convert it into a -- representation parameterized by an arbitrary functor @f@, so that @Shape a f@ -- (the "shape of @a@ parameterized by @f@") is structurally identical to the -- topmost structure of @a@, but with @f@ wrapped around any subfields of @a@. -- -- Note that this is /not/ a recursive representation! The functor @f@ in -- question wraps the original type of the field and /not/ a @Shape@ of that -- field. -- -- For instance, the @Shape@ of @Either a b@ might be: -- -- > data EitherShape a b f -- > = LeftShape (f a) -- > | RightShape (f b) -- > -- > instance Shaped (Either a b) where -- > type Shape (Either a b) = EitherShape a b -- > ... -- -- The shape of a primitive type should be isomorphic to the primitive type, -- with the functor parameter left unused. class Typeable a => Shaped (a :: *) where -- | The @Shape@ of an @a@ is a type isomorphic to the outermost level of -- structure in an @a@, parameterized by the functor @f@, which is wrapped -- around any fields (of any type) in the original @a@. type Shape a :: (* -> *) -> * type Shape a = GShape a -- | Given a function to expand any @Shaped@ @x@ into an @f x@, expand an @a@ -- into a @Shape a f@ -- -- That is: convert the top-most level of structure in the given @a@ into a -- @Shape@, calling the provided function on each field in the @a@ to produce -- the @f x@ necessary to fill that hole in the produced @Shape a f@. -- -- Inverse to 'embed'. project :: (forall x. Shaped x => x -> f x) -> a -> Shape a f default project :: GShaped a => (forall x. Shaped x => x -> f x) -> a -> Shape a f project = gProject -- | Given a function to collapse any @f x@ into a @Shaped@ @x@, collapse a -- @Shape a f@ into merely an @a@ -- -- That is: eliminate the top-most @Shape@ by calling the provided function on -- each field in that @Shape a f@, and using the results to fill in the pieces -- necessary to build an @a@. -- -- Inverse to 'project'. embed :: (forall x. Shaped x => f x -> x) -> Shape a f -> a default embed :: GShaped a => (forall x. Shaped x => f x -> x) -> Shape a f -> a embed = gEmbed -- | Given two @Shape@s of the same type @a@ but parameterized by potentially -- different functors @f@ and @g@, pattern-match on them to expose a uniform -- view on their fields (a 'Flattened' @(Shape a)@) to a continuation which -- may operate on those fields to produce some result -- -- If the two supplied @Shape@s do not structurally match, only the fields of -- the first are given to the continuation. If they do match, the fields of -- the second are also given, along with type-level proof that the types of -- the two sets of fields align. -- -- This very general operation subsumes equality testing, mapping, zipping, -- shrinking, and many other structural operations over @Shaped@ things. -- -- It is somewhat difficult to manually write instances for this method, but -- consulting its generic implementation 'gMatch' may prove helpful. -- -- See "Test.StrictCheck.Shaped.Flattened" for more information. match :: Shape a f -> Shape a g -> (forall xs. All Shaped xs => Flattened (Shape a) f xs -> Maybe (Flattened (Shape a) g xs) -> result) -> result default match :: GShaped a => Shape a f -> Shape a g -> (forall xs. All Shaped xs => Flattened (Shape a) f xs -> Maybe (Flattened (Shape a) g xs) -> result) -> result match = gMatch -- | Convert a @Shape a@ whose fields are some unknown constant type into a -- 'RenderLevel' filled with that type -- -- This is a specialized pretty-printing mechanism which allows for displaying -- counterexamples in a structured format. See the documentation for -- 'RenderLevel'. render :: Shape a (K x) -> RenderLevel x default render :: (GShaped a, HasDatatypeInfo a) => Shape a (K x) -> RenderLevel x render = gRender -- * Fixed-points of 'Shape's -- | A value of type @f % a@ has the same structure as an @a@, but with the -- structure of the functor @f@ interleaved at every field (including ones of -- types other than @a@). Read this type aloud as "a interleaved with f's". newtype (f :: * -> *) % (a :: *) :: * where Wrap :: f (Shape a ((%) f)) -> f % a -- | Look inside a single level of an interleaved @f % a@. Inverse to the 'Wrap' -- constructor. unwrap :: f % a -> f (Shape a ((%) f)) unwrap (Wrap fs) = fs -- * Folds and unfolds over fixed-points of @Shape@s -- | Map a function across all the fields in a 'Shape' -- -- This function may change the functor over which the @Shape@ is parameterized. -- It can assume recursively that all the fields in the @Shape@ are themselves -- instances of @Shaped@ (which they should be!). This means that you can nest -- calls to @translate@ recursively. translate :: forall a f g. Shaped a => (forall x. Shaped x => f x -> g x) -> Shape a f -> Shape a g translate t d = match @a d d $ \flat _ -> unflatten $ mapFlattened @Shaped t flat -- | The equivalent of a fold (catamorphism) over recursively 'Shaped' values -- -- Given a function which folds an @f@ containing some @Shape x g@ into a @g x@, -- recursively fold any interleaved @f % a@ into a @g a@. fold :: forall a f g. (Functor f, Shaped a) => (forall x. Shaped x => f (Shape x g) -> g x) -> f % a -> g a fold alg = alg . fmap (translate @a (fold alg)) . unwrap -- | The equivalent of an unfold (anamorphism) over recursively 'Shaped' values -- -- Given a function which unfolds an @f x@ into a @g@ containing some @Shape x -- f@, corecursively unfold any @f a@ into an interleaved @g % a@. unfold :: forall a f g. (Functor g, Shaped a) => (forall x. Shaped x => f x -> g (Shape x f)) -> f a -> g % a unfold coalg = Wrap . fmap (translate @a (unfold coalg)) . coalg -- TODO: mapM, foldM, unfoldM, ... -- | Fuse the interleaved @f@-structure out of a recursively interleaved @f % -- a@, given some way of fusing a single level @f x -> x@. -- -- This is a special case of 'fold'. fuse :: (Functor f, Shaped a) => (forall x. f x -> x) -> (f % a -> a) fuse e = e . fold (fmap (embed e)) -- | Interleave an @f@-structure at every recursive level of some @a@, given -- some way of generating a single level of structure @x -> f x@. -- -- This is a special case of 'unfold'. interleave :: (Functor f, Shaped a) => (forall x. x -> f x) -> (a -> f % a) interleave p = unfold (fmap (project p)) . p -- | An infix synonym for 'interleave' (%) :: forall a f. (Functor f, Shaped a) => (forall x. x -> f x) -> a -> f % a (%) = interleave -- | A higher-kinded @unzipWith@, operating over interleaved structures -- -- Given a function splitting some @f x@ into a functor-product @Product g h x@, -- recursively split an interleaved @f % a@ into two interleaved structures: -- one built of @g@-shapes and one of @h@-shapes. -- -- Note that @Product ((%) g) ((%) h) a@ is isomorphic to @(g % a, h % a)@; to -- get the latter, pattern-match on the 'Pair' constructor of 'Product'. unzipWith :: (All Functor [f, g, h], Shaped a) => (forall x. f x -> (g x, h x)) -> (f % a -> (g % a, h % a)) unzipWith split = unPair . fold (crunch . pair . split) where crunch :: forall x g h. (Shaped x, Functor g, Functor h) => Product g h (Shape x (Product ((%) g) ((%) h))) -> Product ((%) g) ((%) h) x crunch = pair . bimap (Wrap . fmap (translate @x (fst . unPair))) (Wrap . fmap (translate @x (snd . unPair))) . unPair pair :: (l x, r x) -> Product l r x pair = uncurry Pair unPair :: Product l r x -> (l x, r x) unPair (Pair lx rx) = (lx, rx) -- | TODO: document this strange function {- reshape :: forall b a f g. (Shaped a, Shaped b, Functor f) => (f (Shape b ((%) g)) -> g (Shape b ((%) g))) -> (forall x. Shaped x => f % x -> g % x) -> f % a -> g % a reshape homo hetero d = case eqTypeRep (typeRep @a) (typeRep @b) of Nothing -> hetero d Just HRefl -> Wrap $ homo . fmap (translate @a (reshape @b homo hetero)) $ unwrap d -} ---------------------------------- -- Rendering shapes for display -- ---------------------------------- -- | Convert an @f % a@ into a structured pretty-printing representation, -- suitable for further display/processing renderfold :: forall a f. (Shaped a, Functor f) => f % a -> Rendered f renderfold = unK . fold oneLevel where oneLevel :: forall x. Shaped x => f (Shape x (K (Rendered f))) -> K (Rendered f) x oneLevel = K . RWrap . fmap (render @x) -- | A @QName@ is a qualified name -- -- Note: -- > type ModuleName = String -- > type DatatypeName = String type QName = (ModuleName, DatatypeName, String) -- | @RenderLevel@ is a functor whose outer shape contains all the information -- about how to pretty-format the outermost @Shape@ of some value. We use -- parametricity to make it difficult to construct incorrect 'render' methods, -- by asking the user merely to produce a single @RenderLevel@ and stitching -- nested @RenderLevel@s into complete 'Rendered' trees. data RenderLevel x = ConstructorD QName [x] -- ^ A prefix constructor, and a list of its fields | InfixD QName Associativity Fixity x x -- ^ An infix constructor, its associativity and fixity, and its two fields | RecordD QName [(QName, x)] -- ^ A record constructor, and a list of its field names paired with fields | CustomD Fixity [Either (Either String (ModuleName, String)) (Fixity, x)] -- ^ A custom pretty-printing representation (i.e. for abstract types), which -- records a fixity and a list of tokens of three varieties: 1) raw strings, -- 2) qualified strings (from some module), or 3) actual fields, annotated -- with their fixity deriving (Eq, Ord, Show, Functor) -- | @Rendered f@ is the fixed-point of @f@ composed with 'RenderLevel': it -- alternates between @f@ shapes and @RenderLevel@s. Usually, @f@ will be the -- identity functor 'I', but not always. data Rendered f = RWrap (f (RenderLevel (Rendered f))) ---------------------------------------------------- -- Tools for manually writing instances of Shaped -- ---------------------------------------------------- -- | The @Shape@ of a spine-strict container (i.e. a @Map@ or @Set@) is the same -- as a container of demands on its elements. However, this does not have the -- right /kind/ to be used as a @Shape@. -- -- The @Containing@ newtype solves this problem. By defining the @Shape@ of some -- container @(C a)@ to be @(C `Containing` a)@, you can use the methods -- @projectContainer@ and @embedContainer@ to implement @project@ and @embed@ -- for your container type (although you will still need to manually define -- @match@ and @render@). newtype Containing h a f = Container (h (f a)) deriving (Eq, Ord, Show) -- | Generic implementation of @project@ for any container type whose @Shape@ -- is represented as a @Containing@ newtype projectContainer :: (Functor c, Shaped a) => (forall x. Shaped x => x -> f x) -> c a -> Containing c a f projectContainer p x = Container (fmap p x) -- | Generic implementation of @embed@ for any container type whose @Shape@ -- is represented as a @Containing@ newtype embedContainer :: (Functor c, Shaped a) => (forall x. Shaped x => f x -> x) -> Containing c a f -> c a embedContainer e (Container x) = fmap e x -- TODO: helper functions for matching and prettying containers -- | The @Shape@ of a primitive type should be equivalent to the type itself. -- However, this does not have the right /kind/ to be used as a @Shape@. -- -- The @Prim@ newtype solves this problem. By defining the @Shape@ of some -- primitive type @p@ to be @Prim p@, you can use the methods @projectPrim@, -- @embedPrim@, @matchPrim@, and @prettyPrim@ to completely fill in the -- definition of the @Shaped@ class for a primitive type. -- -- __Note:__ It is only appropriate to use this @Shape@ representation when a -- type really is primitive, in that it contains no interesting substructure. -- If you use the @Prim@ representation inappropriately, StrictCheck will not be -- able to inspect the richer structure of the type in question. newtype Prim (x :: *) (f :: * -> *) = Prim x deriving (Eq, Ord, Show) deriving newtype (Num) -- | Get the wrapped @x@ out of a @Prim x f@ (inverse to the @Prim@ constructor) unPrim :: Prim x f -> x unPrim (Prim x) = x -- | Generic implementation of @project@ for any primitive type whose @Shape@ is -- is represented as a @Prim@ newtype projectPrim :: (forall x. Shaped x => x -> f x) -> a -> Prim a f projectPrim _ = Prim -- | Generic implementation of @embed@ for any primitive type whose @Shape@ is -- is represented as a @Prim@ newtype embedPrim :: (forall x. Shaped x => f x -> x) -> Prim a f -> a embedPrim _ = unPrim -- | Generic implementation of @match@ for any primitive type whose @Shape@ is -- is represented as a @Prim@ newtype with an underlying @Eq@ instance matchPrim :: Eq a => Prim a f -> Prim a g -> (forall xs. All Shaped xs => Flattened (Prim a) f xs -> Maybe (Flattened (Prim a) g xs) -> result) -> result matchPrim (Prim a) (Prim b) k = k (flatPrim a) (if a == b then (Just (flatPrim b)) else Nothing) -- | Helper for writing @match@ instances for primitive types which don't have -- @Eq@ instance -- -- This generates a @Flattened@ appropriate for using in the implementation of -- @match@. For more documentation on how to use this, see the documentation of -- 'match'. flatPrim :: a -> Flattened (Prim a) g '[] flatPrim x = Flattened (const (Prim x)) Nil -- | Generic implementation of @render@ for any primitive type whose @Shape@ is -- is represented as a @Prim@ newtype renderPrim :: Show a => Prim a (K x) -> RenderLevel x renderPrim (Prim a) = renderConstant (show a) -- | Given some @string@, generate a custom pretty-printing representation which -- just shows the string renderConstant :: String -> RenderLevel x renderConstant s = CustomD 11 [Left (Left s)] -- TODO: What about demands for abstract types with > 1 type of unbounded-count field? {- withFieldsContainer :: forall c a f result. (forall r h. c (h a) -> (forall x. Shaped x => [h x] -> (forall g. [g x] -> c (g a)) -> r) -> r) -> Containing c a f -> (forall xs. All Shaped xs => NP f xs -> (forall g. NP g xs -> Containing c a g) -> result) -> result withFieldsContainer viaContaining (Container c) cont = viaContaining c $ \list un -> withNP @Shaped list (Container . un) cont -- TODO: Make this work for any number of lists of fields, by carefully using -- unsafeCoerce to deal with unknown list lengths withFieldsViaList :: forall demand f result. (forall r h. demand h -> (forall x. Shaped x => [h x] -> (forall g. [g x] -> demand g) -> r) -> r) -> demand f -> (forall xs. All Shaped xs => NP f xs -> (forall g. NP g xs -> demand g) -> result) -> result withFieldsViaList viaList demand cont = viaList demand $ \list un -> withNP @Shaped list un cont withNP :: forall c demand result f x. c x => [f x] -> (forall g. [g x] -> demand g) -> (forall xs. All c xs => NP f xs -> (forall g. NP g xs -> demand g) -> result) -> result withNP list unList cont = withUnhomogenized @c list $ \np -> cont np (unList . homogenize) withConcatenated :: NP (NP f) xss -> (forall xs. NP f xs -> r) -> r withConcatenated pop cont = case pop of Nil -> cont Nil (xs :* xss) -> withConcatenated xss (withPrepended xs cont) where withPrepended :: NP f ys -> (forall zs. NP f zs -> r) -> (forall zs. NP f zs -> r) withPrepended pre k rest = case pre of Nil -> k rest (x :* xs) -> withPrepended xs (k . (x :*)) rest homogenize :: All ((~) a) as => NP f as -> [f a] homogenize Nil = [] homogenize (a :* as) = a : homogenize as withUnhomogenized :: forall c a f r. c a => [f a] -> (forall as. (All c as, All ((~) a) as) => NP f as -> r) -> r withUnhomogenized [] k = k Nil withUnhomogenized (a : as) k = withUnhomogenized @c as $ \np -> k (a :* np) -} --------------------------------------------------- -- Generic implementation of the Shaped methods -- --------------------------------------------------- -- | The 'Shape' used for generic implementations of 'Shaped' -- -- This wraps a sum-of-products representation from "Generics.SOP". newtype GShape a f = GS (NS (NP f) (Code a)) -- | The collection of constraints necessary for a type to be given a generic -- implementation of the 'Shaped' methods type GShaped a = ( Generic a , Shape a ~ GShape a , All2 Shaped (Code a) , SListI (Code a) , All SListI (Code a) ) -- | Generic 'project' gProject :: GShaped a => (forall x. Shaped x => x -> f x) -> a -> Shape a f gProject p !(from -> sop) = GS (unSOP (hcliftA (Proxy @Shaped) (p . unI) sop)) -- | Generic 'embed' gEmbed :: GShaped a => (forall x. Shaped x => f x -> x) -> Shape a f -> a gEmbed e !(GS d) = to (hcliftA (Proxy @Shaped) (I . e) (SOP d)) -- | Generic 'match' gMatch :: forall a f g result. GShaped a => Shape a f -> Shape a g -> (forall xs. All Shaped xs => Flattened (Shape a) f xs -> Maybe (Flattened (Shape a) g xs) -> result) -> result gMatch !(GS df) !(GS dg) cont = go @(Code a) df (Just dg) $ \flatF mflatG -> cont (flatGD flatF) (flatGD <$> mflatG) where go :: forall xss r. (All SListI xss, All2 Shaped xss) => NS (NP f) xss -> Maybe (NS (NP g) xss) -> (forall xs. All Shaped xs => Flattened (Flip SOP xss) f xs -> Maybe (Flattened (Flip SOP xss) g xs) -> r) -> r go (Z (fieldsF :: _ xs)) (Just (Z fieldsG)) k = k @xs (flatZ fieldsF) (Just (flatZ fieldsG)) go (Z (fieldsF :: _ xs)) _ k = -- Nothing | Just (S _) k @xs (flatZ fieldsF) Nothing go (S moreF) Nothing k = go moreF Nothing $ \(flatF :: _ xs) _ -> k @xs (flatS flatF) Nothing go (S moreF) (Just (Z _)) k = go moreF Nothing $ \(flatF :: _ xs) _ -> k @xs (flatS flatF) Nothing go (S moreF) (Just (S moreG)) k = go moreF (Just moreG) $ \(flatF :: _ xs) mflatG -> k @xs (flatS flatF) (flatS <$> mflatG) flatZ :: forall h xs xss. NP h xs -> Flattened (Flip SOP (xs : xss)) h xs flatZ = Flattened (Flip . SOP . Z) flatS :: forall h xs xs' xss. Flattened (Flip SOP xss) h xs -> Flattened (Flip SOP (xs' : xss)) h xs flatS (Flattened un fields) = Flattened (Flip . SOP . S . coerce . un) fields flatGD :: forall t h xs. Flattened (Flip SOP (Code t)) h xs -> Flattened (GShape t) h xs flatGD (Flattened un fields) = Flattened (GS . coerce . un) fields -- | Generic 'render' gRender :: forall a x. (HasDatatypeInfo a, GShaped a) => Shape a (K x) -> RenderLevel x gRender (GS demand) = case info of ADT m d cs -> renderC m d demand cs Newtype m d c -> renderC m d demand (c :* Nil) where info = datatypeInfo (Proxy @a) renderC :: forall as. ModuleName -> DatatypeName -> NS (NP (K x)) as -> NP ConstructorInfo as -> RenderLevel x renderC m d subShape constructors = case (subShape, constructors) of (Z demandFields, c :* _) -> case c of Constructor name -> ConstructorD (m, d, name) $ hcollapse demandFields Infix name associativity fixity -> case demandFields of (K a :* K b :* Nil) -> InfixD (m, d, name) associativity fixity a b Record name fieldsInfo -> RecordD (m, d, name) $ zip ( hcollapse . hliftA (\(FieldInfo f) -> K (m, d, f)) $ fieldsInfo ) (hcollapse demandFields) (S another, _ :* different) -> renderC m d another different --------------- -- Instances -- --------------- instance Shaped () instance Shaped Bool instance Shaped Ordering instance Shaped a => Shaped (Maybe a) instance (Shaped a, Shaped b) => Shaped (Either a b) instance Shaped a => Shaped [a] instance (Typeable a, Typeable b) => Shaped (a -> b) where type Shape (a -> b) = Prim (a -> b) project = projectPrim embed = embedPrim match (Prim f) (Prim g) k = k (flatPrim f) (Just $ flatPrim g) render _ = renderConstant ("<function> :: " ++ show (typeRep @(a -> b))) instance Shaped Char where type Shape Char = Prim Char project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Word where type Shape Word = Prim Word project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Int where type Shape Int = Prim Int project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Double where type Shape Double = Prim Double project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Float where type Shape Float = Prim Float project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Rational where type Shape Rational = Prim Rational project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance Shaped Integer where type Shape Integer = Prim Integer project = projectPrim embed = embedPrim match = matchPrim render = renderPrim instance (Typeable a, Eq a, Show a) => Shaped (Complex a) where type Shape (Complex a) = Prim (Complex a) project = projectPrim embed = embedPrim match = matchPrim render = renderPrim -- instance Generic (NonEmpty a) -- instance HasDatatypeInfo (NonEmpty a) -- instance Shaped a => Shaped (NonEmpty a) where -- Tree -- Map k -- Seq -- Set -- IntMap -- IntSet instance (Shaped a, Shaped b) => Shaped (a, b) instance (Shaped a, Shaped b, Shaped c) => Shaped (a, b, c) instance (Shaped a, Shaped b, Shaped c, Shaped d) => Shaped (a, b, c, d) instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e ) => Shaped (a, b, c, d, e) instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f ) => Shaped (a, b, c, d, e, f) instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f , Shaped g ) => Shaped (a, b, c, d, e, f, g) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h -- ) => Shaped -- (a, b, c, d, e, f, g, h) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i -- ) => Shaped -- (a, b, c, d, e, f, g, h, i) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u, Shaped v -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u, Shaped v, Shaped w -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u, Shaped v, Shaped w, Shaped x -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u, Shaped v, Shaped w, Shaped x -- , Shaped y -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y) -- instance ( Shaped a, Shaped b, Shaped c, Shaped d, Shaped e, Shaped f -- , Shaped g, Shaped h, Shaped i, Shaped j, Shaped k, Shaped l -- , Shaped m, Shaped n, Shaped o, Shaped p, Shaped q, Shaped r -- , Shaped s, Shaped t, Shaped u, Shaped v, Shaped w, Shaped x -- , Shaped y, Shaped z -- ) => Shaped -- (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
library(MASS) library(dplyr) library(tidyr) library(ggplot2) library(ascii) library(lubridate) library(splines) library(mgcv) ## Import datasets needed for chapter 4 PSDS_PATH <- file.path('~', 'statistics-for-data-scientists') lung <- read.csv(file.path(PSDS_PATH, 'data', 'LungDisease.csv')) zhvi <- read.csv(file.path(PSDS_PATH, 'data', 'County_Zhvi_AllHomes.csv')) zhvi <- unlist(zhvi[13,-(1:5)]) dates <- parse_date_time(paste(substr(names(zhvi), start=2, stop=8), "01", sep="."), "Ymd") zhvi <- data.frame(ym=dates, zhvi_px=zhvi, row.names = NULL) %>% mutate(zhvi_idx=zhvi/last(zhvi)) house <- read.csv(file.path(PSDS_PATH, 'data', 'house_sales.csv'), sep='\t') # house <- house[house$ZipCode > 0, ] # write.table(house, file.path(PSDS_PATH, 'data', 'house_sales.csv'), sep='\t') ## Code for Figure 1 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0401.png'), width = 4, height=4, units='in', res=300) par(mar=c(4,4,0,0)+.1) plot(lung$Exposure, lung$PEFR, xlab="Exposure", ylab="PEFR") dev.off() ## Code snippet 4.1 model <- lm(PEFR ~ Exposure, data=lung) model ## Code for figure 2 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0402.png'), width = 350, height = 350) par(mar=c(4,4,0,0)+.1) plot(lung$Exposure, lung$PEFR, xlab="Exposure", ylab="PEFR", ylim=c(300,450), type="n", xaxs="i") abline(a=model$coefficients[1], b=model$coefficients[2], col="blue", lwd=2) text(x=.3, y=model$coefficients[1], labels=expression("b"[0]), adj=0, cex=1.5) x <- c(7.5, 17.5) y <- predict(model, newdata=data.frame(Exposure=x)) segments(x[1], y[2], x[2], y[2] , col="red", lwd=2, lty=2) segments(x[1], y[1], x[1], y[2] , col="red", lwd=2, lty=2) text(x[1], mean(y), labels=expression(Delta~Y), pos=2, cex=1.5) text(mean(x), y[2], labels=expression(Delta~X), pos=1, cex=1.5) text(mean(x), 400, labels=expression(b[1] == frac(Delta ~ Y, Delta ~ X)), cex=1.5) dev.off() ## Code snippet 4.2 fitted <- predict(model) resid <- residuals(model) ## Code for figure 3 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0403.png'), width = 4, height=4, units='in', res=300) par(mar=c(4,4,0,0)+.1) lung1 <- lung %>% mutate(Fitted=fitted, positive = PEFR>Fitted) %>% group_by(Exposure, positive) %>% summarize(PEFR_max = max(PEFR), PEFR_min = min(PEFR), Fitted = first(Fitted)) %>% ungroup() %>% mutate(PEFR = ifelse(positive, PEFR_max, PEFR_min)) %>% arrange(Exposure) plot(lung$Exposure, lung$PEFR, xlab="Exposure", ylab="PEFR") abline(a=model$coefficients[1], b=model$coefficients[2], col="blue", lwd=2) segments(lung1$Exposure, lung1$PEFR, lung1$Exposure, lung1$Fitted, col="red", lty=3) dev.off() ## Code snippet 4.3 head(house[, c("AdjSalePrice", "SqFtTotLiving", "SqFtLot", "Bathrooms", "Bedrooms", "BldgGrade")]) ## Code snippet 4.4 house_lm <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data=house, na.action=na.omit) ## Code snippet 4.5 house_lm ## Code snippet 4.6 summary(house_lm) ## Code snippet 4.7 house_full <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade + PropertyType + NbrLivingUnits + SqFtFinBasement + YrBuilt + YrRenovated + NewConstruction, data=house, na.action=na.omit) ## Code snippet 4.8 step_lm <- stepAIC(house_full, direction="both") step_lm lm(AdjSalePrice ~ Bedrooms, data=house) # WeightedRegression ## Code snippet 4.9 house$Year = year(house$DocumentDate) house$Weight = house$Year - 2005 ## Code snippet 4.10 house_wt <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data=house, weight=Weight, na.action=na.omit) round(cbind(house_lm=house_lm$coefficients, house_wt=house_wt$coefficients), digits=3) # Factor Variables ## Code snippet 4.11 head(house[, 'PropertyType']) ## Code snippet 4.12 prop_type_dummies <- model.matrix(~PropertyType -1, data=house) head(prop_type_dummies) ## Code snippet 4.13 lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade + PropertyType, data=house) ## Code snippet 4.14 table(house$ZipCode) ## Code snippet 4.15 zip_groups <- house %>% mutate(resid = residuals(house_lm)) %>% group_by(ZipCode) %>% summarize(med_resid = median(resid), cnt = n()) %>% # sort the zip codes by the median residual arrange(med_resid) %>% mutate(cum_cnt = cumsum(cnt), ZipGroup = factor(ntile(cum_cnt, 5))) house <- house %>% left_join(select(zip_groups, ZipCode, ZipGroup), by='ZipCode') # correlated variables # Code snippet 4.15 step_lm$coefficients # Code snippet 4.16 update(step_lm, . ~ . -SqFtTotLiving - SqFtFinBasement - Bathrooms) # ConfoundingVariables ## Code snippet 4.17 lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade + PropertyType + ZipGroup, data=house, na.action=na.omit) # Interactions ## Code snippet 4.18 lm(AdjSalePrice ~ SqFtTotLiving*ZipGroup + SqFtLot + Bathrooms + Bedrooms + BldgGrade + PropertyType, data=house, na.action=na.omit) head(model.matrix(~C(PropertyType, sum) , data=house)) # outlier anaysis ## Code snippet 4.19 house_98105 <- house[house$ZipCode == 98105,] lm_98105 <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data=house_98105) ## Code snippet 4.20 sresid <- rstandard(lm_98105) idx <- order(sresid, decreasing=FALSE) sresid[idx[1]] resid(lm_98105)[idx[1]] ## Code snippet 4.21 house_98105[idx[1], c('AdjSalePrice', 'SqFtTotLiving', 'SqFtLot', 'Bathrooms', 'Bedrooms', 'BldgGrade')] # Figure 4-5: Influential data point in regression seed <- 11 set.seed(seed) x <- rnorm(25) y <- -x/5 + rnorm(25) x[1] <- 8 y[1] <- 8 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0405.png'), width = 4, height=4, units='in', res=300) par(mar=c(3,3,0,0)+.1) plot(x, y, xlab='', ylab='', pch=16) model <- lm(y~x) abline(a=model$coefficients[1], b=model$coefficients[2], col="blue", lwd=3) model <- lm(y[-1]~x[-1]) abline(a=model$coefficients[1], b=model$coefficients[2], col="red", lwd=3, lty=2) dev.off() # influential observations ## Code snippet 4.22 std_resid <- rstandard(lm_98105) cooks_D <- cooks.distance(lm_98105) hat_values <- hatvalues(lm_98105) plot(hat_values, std_resid, cex=10*sqrt(cooks_D)) abline(h=c(-2.5, 2.5), lty=2) ## Code for Figure 4-6 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0406.png'), width = 4, height=4, units='in', res=300) par(mar=c(4,4,0,0)+.1) plot(hat_values, std_resid, cex=10*sqrt(cooks_D)) abline(h=c(-2.5, 2.5), lty=2) dev.off() ## Table 4-2 lm_98105_inf <- lm(AdjSalePrice ~ SqFtTotLiving + SqFtLot + Bathrooms + Bedrooms + BldgGrade, subset=cooks_D<.08, data=house_98105) df <- data.frame(lm_98105$coefficients, lm_98105_inf$coefficients) names(df) <- c('Original', 'Influential Removed') ascii((df), include.rownames=TRUE, include.colnames=TRUE, header=TRUE, digits=rep(0, 3), align=c("l", "r", "r") , caption="Comparison of regression coefficients with the full data and with influential data removed") ## heteroskedasticity ## Code snippet 4.23 df <- data.frame( resid = residuals(lm_98105), pred = predict(lm_98105)) ggplot(df, aes(pred, abs(resid))) + geom_point() + geom_smooth() ## Code for figure 4-7 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0407.png'), width = 4, height=4, units='in', res=300) ggplot(df, aes(pred, abs(resid))) + geom_point() + geom_smooth() + theme_bw() dev.off() ## Code for figure 4-8 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0408.png'), width = 4, height=4, units='in', res=300) par(mar=c(4,4,0,0)+.1) hist(std_resid, main='') dev.off() ## partial residuals plot ## Code snippet 4.24 terms <- predict(lm_98105, type='terms') partial_resid <- resid(lm_98105) + terms ## Code snippet 4.25 df <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'], Terms = terms[, 'SqFtTotLiving'], PartialResid = partial_resid[, 'SqFtTotLiving']) ggplot(df, aes(SqFtTotLiving, PartialResid)) + geom_point(shape=1) + scale_shape(solid = FALSE) + geom_smooth(linetype=2) + geom_line(aes(SqFtTotLiving, Terms)) ## Code for figure 4-9 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0409.png'), width = 4, height=4, units='in', res=300) df <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'], Terms = terms[, 'SqFtTotLiving'], PartialResid = partial_resid[, 'SqFtTotLiving']) ggplot(df, aes(SqFtTotLiving, PartialResid)) + geom_point(shape=1) + scale_shape(solid = FALSE) + geom_smooth(linetype=2) + theme_bw() + geom_line(aes(SqFtTotLiving, Terms)) dev.off() ## Code snippet 4.26 lm(AdjSalePrice ~ poly(SqFtTotLiving, 2) + SqFtLot + BldgGrade + Bathrooms + Bedrooms, data=house_98105) lm_poly <- lm(AdjSalePrice ~ poly(SqFtTotLiving, 2) + SqFtLot + BldgGrade + Bathrooms + Bedrooms, data=house_98105) terms <- predict(lm_poly, type='terms') partial_resid <- resid(lm_poly) + terms ## Code for Figure 4-10 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0410.png'), width = 4, height=4, units='in', res=300) df <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'], Terms = terms[, 1], PartialResid = partial_resid[, 1]) ggplot(df, aes(SqFtTotLiving, PartialResid)) + geom_point(shape=1) + scale_shape(solid = FALSE) + geom_smooth(linetype=2) + geom_line(aes(SqFtTotLiving, Terms))+ theme_bw() dev.off() ## Code snippet 4.27 knots <- quantile(house_98105$SqFtTotLiving, p=c(.25, .5, .75)) lm_spline <- lm(AdjSalePrice ~ bs(SqFtTotLiving, knots=knots, degree=3) + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data=house_98105) terms1 <- predict(lm_spline, type='terms') partial_resid1 <- resid(lm_spline) + terms ## Code for Figure 4-12 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0412.png'), width = 4, height=4, units='in', res=300) df1 <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'], Terms = terms1[, 1], PartialResid = partial_resid1[, 1]) ggplot(df1, aes(SqFtTotLiving, PartialResid)) + geom_point(shape=1) + scale_shape(solid = FALSE) + geom_smooth(linetype=2) + geom_line(aes(SqFtTotLiving, Terms))+ theme_bw() dev.off() ## Code snippet 4.27 lm_gam <- gam(AdjSalePrice ~ s(SqFtTotLiving) + SqFtLot + Bathrooms + Bedrooms + BldgGrade, data=house_98105) terms <- predict.gam(lm_gam, type='terms') partial_resid <- resid(lm_gam) + terms ## Code for Figure 4-13 png(filename=file.path(PSDS_PATH, 'figures', 'psds_0413.png'), width = 4, height=4, units='in', res=300) df <- data.frame(SqFtTotLiving = house_98105[, 'SqFtTotLiving'], Terms = terms[, 5], PartialResid = partial_resid[, 5]) ggplot(df, aes(SqFtTotLiving, PartialResid)) + geom_point(shape=1) + scale_shape(solid = FALSE) + geom_smooth(linetype=2) + geom_line(aes(SqFtTotLiving, Terms)) + theme_bw() dev.off()
-- | Type classes for random generation of values. -- -- __Note__: the contents of this module are re-exported by -- "Test.QuickCheck". You do not need to import it directly. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} #ifndef NO_GENERICS {-# LANGUAGE DefaultSignatures, FlexibleContexts, TypeOperators #-} {-# LANGUAGE FlexibleInstances, KindSignatures, ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 710 #define OVERLAPPING_ {-# OVERLAPPING #-} #else {-# LANGUAGE OverlappingInstances #-} #define OVERLAPPING_ #endif #endif #ifndef NO_POLYKINDS {-# LANGUAGE PolyKinds #-} #endif #ifndef NO_SAFE_HASKELL {-# LANGUAGE Trustworthy #-} #endif #ifndef NO_NEWTYPE_DERIVING {-# LANGUAGE GeneralizedNewtypeDeriving #-} #endif module Test.QuickCheck.Arbitrary ( -- * Arbitrary and CoArbitrary classes Arbitrary(..) , CoArbitrary(..) -- ** Unary and Binary classes , Arbitrary1(..) , arbitrary1 , shrink1 , Arbitrary2(..) , arbitrary2 , shrink2 -- ** Helper functions for implementing arbitrary , applyArbitrary2 , applyArbitrary3 , applyArbitrary4 , arbitrarySizedIntegral -- :: Integral a => Gen a , arbitrarySizedNatural -- :: Integral a => Gen a , arbitraryBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedFractional -- :: Fractional a => Gen a , arbitraryBoundedRandom -- :: (Bounded a, Random a) => Gen a , arbitraryBoundedEnum -- :: (Bounded a, Enum a) => Gen a -- ** Generators for various kinds of character , arbitraryUnicodeChar -- :: Gen Char , arbitraryASCIIChar -- :: Gen Char , arbitraryPrintableChar -- :: Gen Char -- ** Helper functions for implementing shrink #ifndef NO_GENERICS , RecursivelyShrink , GSubterms , genericShrink -- :: (Generic a, Arbitrary a, RecursivelyShrink (Rep a), GSubterms (Rep a) a) => a -> [a] , subterms -- :: (Generic a, Arbitrary a, GSubterms (Rep a) a) => a -> [a] , recursivelyShrink -- :: (Generic a, RecursivelyShrink (Rep a)) => a -> [a] , genericCoarbitrary -- :: (Generic a, GCoArbitrary (Rep a)) => a -> Gen b -> Gen b #endif , shrinkNothing -- :: a -> [a] , shrinkList -- :: (a -> [a]) -> [a] -> [[a]] , shrinkMap -- :: Arbitrary a -> (a -> b) -> (b -> a) -> b -> [b] , shrinkMapBy -- :: (a -> b) -> (b -> a) -> (a -> [a]) -> b -> [b] , shrinkIntegral -- :: Integral a => a -> [a] , shrinkRealFrac -- :: RealFrac a => a -> [a] , shrinkDecimal -- :: RealFrac a => a -> [a] -- ** Helper functions for implementing coarbitrary , coarbitraryIntegral -- :: Integral a => a -> Gen b -> Gen b , coarbitraryReal -- :: Real a => a -> Gen b -> Gen b , coarbitraryShow -- :: Show a => a -> Gen b -> Gen b , coarbitraryEnum -- :: Enum a => a -> Gen b -> Gen b , (><) -- ** Generators which use arbitrary , vector -- :: Arbitrary a => Int -> Gen [a] , orderedList -- :: (Ord a, Arbitrary a) => Gen [a] , infiniteList -- :: Arbitrary a => Gen [a] ) where -------------------------------------------------------------------------- -- imports import Control.Applicative import Data.Foldable(toList) import System.Random(Random) import Test.QuickCheck.Gen import Test.QuickCheck.Random import Test.QuickCheck.Gen.Unsafe {- import Data.Generics ( (:*:)(..) , (:+:)(..) , Unit(..) ) -} import Data.Char ( ord , isLower , isUpper , toLower , isDigit , isSpace , isPrint , generalCategory , GeneralCategory(..) ) #ifndef NO_FIXED import Data.Fixed ( Fixed , HasResolution ) #endif import Data.Ratio ( Ratio , (%) , numerator , denominator ) import Data.Complex ( Complex((:+)) ) import Data.List ( sort , nub ) import Data.Version (Version (..)) #if defined(MIN_VERSION_base) #if MIN_VERSION_base(4,2,0) import System.IO ( Newline(..) , NewlineMode(..) ) #endif #endif import Control.Monad ( liftM , liftM2 , liftM3 , liftM4 , liftM5 ) import Data.Int(Int8, Int16, Int32, Int64) import Data.Word(Word, Word8, Word16, Word32, Word64) import System.Exit (ExitCode(..)) import Foreign.C.Types #ifndef NO_GENERICS import GHC.Generics #endif import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.IntSet as IntSet import qualified Data.IntMap as IntMap import qualified Data.Sequence as Sequence import qualified Data.Tree as Tree import Data.Bits import qualified Data.Monoid as Monoid #ifndef NO_TRANSFORMERS import Data.Functor.Identity import Data.Functor.Constant import Data.Functor.Compose import Data.Functor.Product #endif -------------------------------------------------------------------------- -- ** class Arbitrary -- | Random generation and shrinking of values. -- -- QuickCheck provides @Arbitrary@ instances for most types in @base@, -- except those which incur extra dependencies. -- For a wider range of @Arbitrary@ instances see the -- <http://hackage.haskell.org/package/quickcheck-instances quickcheck-instances> -- package. class Arbitrary a where -- | A generator for values of the given type. -- -- It is worth spending time thinking about what sort of test data -- you want - good generators are often the difference between -- finding bugs and not finding them. You can use 'sample', -- 'label' and 'classify' to check the quality of your test data. -- -- There is no generic @arbitrary@ implementation included because we don't -- know how to make a high-quality one. If you want one, consider using the -- <http://hackage.haskell.org/package/testing-feat testing-feat> or -- <http://hackage.haskell.org/package/generic-random generic-random> packages. -- -- The <http://www.cse.chalmers.se/~rjmh/QuickCheck/manual.html QuickCheck manual> -- goes into detail on how to write good generators. Make sure to look at it, -- especially if your type is recursive! arbitrary :: Gen a -- | Produces a (possibly) empty list of all the possible -- immediate shrinks of the given value. -- -- The default implementation returns the empty list, so will not try to -- shrink the value. If your data type has no special invariants, you can -- enable shrinking by defining @shrink = 'genericShrink'@, but by customising -- the behaviour of @shrink@ you can often get simpler counterexamples. -- -- Most implementations of 'shrink' should try at least three things: -- -- 1. Shrink a term to any of its immediate subterms. -- You can use 'subterms' to do this. -- -- 2. Recursively apply 'shrink' to all immediate subterms. -- You can use 'recursivelyShrink' to do this. -- -- 3. Type-specific shrinkings such as replacing a constructor by a -- simpler constructor. -- -- For example, suppose we have the following implementation of binary trees: -- -- > data Tree a = Nil | Branch a (Tree a) (Tree a) -- -- We can then define 'shrink' as follows: -- -- > shrink Nil = [] -- > shrink (Branch x l r) = -- > -- shrink Branch to Nil -- > [Nil] ++ -- > -- shrink to subterms -- > [l, r] ++ -- > -- recursively shrink subterms -- > [Branch x' l' r' | (x', l', r') <- shrink (x, l, r)] -- -- There are a couple of subtleties here: -- -- * QuickCheck tries the shrinking candidates in the order they -- appear in the list, so we put more aggressive shrinking steps -- (such as replacing the whole tree by @Nil@) before smaller -- ones (such as recursively shrinking the subtrees). -- -- * It is tempting to write the last line as -- @[Branch x' l' r' | x' <- shrink x, l' <- shrink l, r' <- shrink r]@ -- but this is the /wrong thing/! It will force QuickCheck to shrink -- @x@, @l@ and @r@ in tandem, and shrinking will stop once /one/ of -- the three is fully shrunk. -- -- There is a fair bit of boilerplate in the code above. -- We can avoid it with the help of some generic functions. -- The function 'genericShrink' tries shrinking a term to all of its -- subterms and, failing that, recursively shrinks the subterms. -- Using it, we can define 'shrink' as: -- -- > shrink x = shrinkToNil x ++ genericShrink x -- > where -- > shrinkToNil Nil = [] -- > shrinkToNil (Branch _ l r) = [Nil] -- -- 'genericShrink' is a combination of 'subterms', which shrinks -- a term to any of its subterms, and 'recursivelyShrink', which shrinks -- all subterms of a term. These may be useful if you need a bit more -- control over shrinking than 'genericShrink' gives you. -- -- A final gotcha: we cannot define 'shrink' as simply @'shrink' x = Nil:'genericShrink' x@ -- as this shrinks @Nil@ to @Nil@, and shrinking will go into an -- infinite loop. -- -- If all this leaves you bewildered, you might try @'shrink' = 'genericShrink'@ to begin with, -- after deriving @Generic@ for your type. However, if your data type has any -- special invariants, you will need to check that 'genericShrink' can't break those invariants. shrink :: a -> [a] shrink _ = [] -- | Lifting of the 'Arbitrary' class to unary type constructors. class Arbitrary1 f where liftArbitrary :: Gen a -> Gen (f a) liftShrink :: (a -> [a]) -> f a -> [f a] liftShrink _ _ = [] arbitrary1 :: (Arbitrary1 f, Arbitrary a) => Gen (f a) arbitrary1 = liftArbitrary arbitrary shrink1 :: (Arbitrary1 f, Arbitrary a) => f a -> [f a] shrink1 = liftShrink shrink -- | Lifting of the 'Arbitrary' class to binary type constructors. class Arbitrary2 f where liftArbitrary2 :: Gen a -> Gen b -> Gen (f a b) liftShrink2 :: (a -> [a]) -> (b -> [b]) -> f a b -> [f a b] liftShrink2 _ _ _ = [] arbitrary2 :: (Arbitrary2 f, Arbitrary a, Arbitrary b) => Gen (f a b) arbitrary2 = liftArbitrary2 arbitrary arbitrary shrink2 :: (Arbitrary2 f, Arbitrary a, Arbitrary b) => f a b -> [f a b] shrink2 = liftShrink2 shrink shrink #ifndef NO_GENERICS -- | Shrink a term to any of its immediate subterms, -- and also recursively shrink all subterms. genericShrink :: (Generic a, RecursivelyShrink (Rep a), GSubterms (Rep a) a) => a -> [a] genericShrink x = subterms x ++ recursivelyShrink x -- | Recursively shrink all immediate subterms. recursivelyShrink :: (Generic a, RecursivelyShrink (Rep a)) => a -> [a] recursivelyShrink = map to . grecursivelyShrink . from class RecursivelyShrink f where grecursivelyShrink :: f a -> [f a] instance (RecursivelyShrink f, RecursivelyShrink g) => RecursivelyShrink (f :*: g) where grecursivelyShrink (x :*: y) = [x' :*: y | x' <- grecursivelyShrink x] ++ [x :*: y' | y' <- grecursivelyShrink y] instance (RecursivelyShrink f, RecursivelyShrink g) => RecursivelyShrink (f :+: g) where grecursivelyShrink (L1 x) = map L1 (grecursivelyShrink x) grecursivelyShrink (R1 x) = map R1 (grecursivelyShrink x) instance RecursivelyShrink f => RecursivelyShrink (M1 i c f) where grecursivelyShrink (M1 x) = map M1 (grecursivelyShrink x) instance Arbitrary a => RecursivelyShrink (K1 i a) where grecursivelyShrink (K1 x) = map K1 (shrink x) instance RecursivelyShrink U1 where grecursivelyShrink U1 = [] instance RecursivelyShrink V1 where -- The empty type can't be shrunk to anything. grecursivelyShrink _ = [] -- | All immediate subterms of a term. subterms :: (Generic a, GSubterms (Rep a) a) => a -> [a] subterms = gSubterms . from class GSubterms f a where -- | Provides the immediate subterms of a term that are of the same type -- as the term itself. -- -- Requires a constructor to be stripped off; this means it skips through -- @M1@ wrappers and returns @[]@ on everything that's not `(:*:)` or `(:+:)`. -- -- Once a `(:*:)` or `(:+:)` constructor has been reached, this function -- delegates to `gSubtermsIncl` to return the immediately next constructor -- available. gSubterms :: f a -> [a] instance GSubterms V1 a where -- The empty type can't be shrunk to anything. gSubterms _ = [] instance GSubterms U1 a where gSubterms U1 = [] instance (GSubtermsIncl f a, GSubtermsIncl g a) => GSubterms (f :*: g) a where gSubterms (l :*: r) = gSubtermsIncl l ++ gSubtermsIncl r instance (GSubtermsIncl f a, GSubtermsIncl g a) => GSubterms (f :+: g) a where gSubterms (L1 x) = gSubtermsIncl x gSubterms (R1 x) = gSubtermsIncl x instance GSubterms f a => GSubterms (M1 i c f) a where gSubterms (M1 x) = gSubterms x instance GSubterms (K1 i a) b where gSubterms (K1 _) = [] class GSubtermsIncl f a where -- | Provides the immediate subterms of a term that are of the same type -- as the term itself. -- -- In contrast to `gSubterms`, this returns the immediate next constructor -- available. gSubtermsIncl :: f a -> [a] instance GSubtermsIncl V1 a where -- The empty type can't be shrunk to anything. gSubtermsIncl _ = [] instance GSubtermsIncl U1 a where gSubtermsIncl U1 = [] instance (GSubtermsIncl f a, GSubtermsIncl g a) => GSubtermsIncl (f :*: g) a where gSubtermsIncl (l :*: r) = gSubtermsIncl l ++ gSubtermsIncl r instance (GSubtermsIncl f a, GSubtermsIncl g a) => GSubtermsIncl (f :+: g) a where gSubtermsIncl (L1 x) = gSubtermsIncl x gSubtermsIncl (R1 x) = gSubtermsIncl x instance GSubtermsIncl f a => GSubtermsIncl (M1 i c f) a where gSubtermsIncl (M1 x) = gSubtermsIncl x -- This is the important case: We've found a term of the same type. instance OVERLAPPING_ GSubtermsIncl (K1 i a) a where gSubtermsIncl (K1 x) = [x] instance OVERLAPPING_ GSubtermsIncl (K1 i a) b where gSubtermsIncl (K1 _) = [] #endif -- instances instance (CoArbitrary a) => Arbitrary1 ((->) a) where liftArbitrary arbB = promote (`coarbitrary` arbB) instance (CoArbitrary a, Arbitrary b) => Arbitrary (a -> b) where arbitrary = arbitrary1 instance Arbitrary () where arbitrary = return () instance Arbitrary Bool where arbitrary = chooseEnum (False,True) shrink True = [False] shrink False = [] instance Arbitrary Ordering where arbitrary = elements [LT, EQ, GT] shrink GT = [EQ, LT] shrink LT = [EQ] shrink EQ = [] instance Arbitrary1 Maybe where liftArbitrary arb = frequency [(1, return Nothing), (3, liftM Just arb)] liftShrink shr (Just x) = Nothing : [ Just x' | x' <- shr x ] liftShrink _ Nothing = [] instance Arbitrary a => Arbitrary (Maybe a) where arbitrary = arbitrary1 shrink = shrink1 instance Arbitrary2 Either where liftArbitrary2 arbA arbB = oneof [liftM Left arbA, liftM Right arbB] liftShrink2 shrA _ (Left x) = [ Left x' | x' <- shrA x ] liftShrink2 _ shrB (Right y) = [ Right y' | y' <- shrB y ] instance Arbitrary a => Arbitrary1 (Either a) where liftArbitrary = liftArbitrary2 arbitrary liftShrink = liftShrink2 shrink instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b) where arbitrary = arbitrary2 shrink = shrink2 instance Arbitrary1 [] where liftArbitrary = listOf liftShrink = shrinkList instance Arbitrary a => Arbitrary [a] where arbitrary = arbitrary1 shrink = shrink1 -- | Shrink a list of values given a shrinking function for individual values. shrinkList :: (a -> [a]) -> [a] -> [[a]] shrinkList shr xs = concat [ removes k n xs | k <- takeWhile (>0) (iterate (`div`2) n) ] ++ shrinkOne xs where n = length xs shrinkOne [] = [] shrinkOne (x:xs) = [ x':xs | x' <- shr x ] ++ [ x:xs' | xs' <- shrinkOne xs ] removes k n xs | k > n = [] | null xs2 = [[]] | otherwise = xs2 : map (xs1 ++) (removes k (n-k) xs2) where xs1 = take k xs xs2 = drop k xs {- -- "standard" definition for lists: shrink [] = [] shrink (x:xs) = [ xs ] ++ [ x:xs' | xs' <- shrink xs ] ++ [ x':xs | x' <- shrink x ] -} instance Integral a => Arbitrary (Ratio a) where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac #if defined(MIN_VERSION_base) && MIN_VERSION_base(4,4,0) instance Arbitrary a => Arbitrary (Complex a) where #else instance (RealFloat a, Arbitrary a) => Arbitrary (Complex a) where #endif arbitrary = liftM2 (:+) arbitrary arbitrary shrink (x :+ y) = [ x' :+ y | x' <- shrink x ] ++ [ x :+ y' | y' <- shrink y ] #ifndef NO_FIXED instance HasResolution a => Arbitrary (Fixed a) where arbitrary = arbitrarySizedFractional shrink = shrinkDecimal #endif instance Arbitrary2 (,) where liftArbitrary2 = liftM2 (,) liftShrink2 shrA shrB (x, y) = [ (x', y) | x' <- shrA x ] ++ [ (x, y') | y' <- shrB y ] instance (Arbitrary a) => Arbitrary1 ((,) a) where liftArbitrary = liftArbitrary2 arbitrary liftShrink = liftShrink2 shrink instance (Arbitrary a, Arbitrary b) => Arbitrary (a,b) where arbitrary = arbitrary2 shrink = shrink2 instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (a,b,c) where arbitrary = liftM3 (,,) arbitrary arbitrary arbitrary shrink (x, y, z) = [ (x', y', z') | (x', (y', z')) <- shrink (x, (y, z)) ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (a,b,c,d) where arbitrary = liftM4 (,,,) arbitrary arbitrary arbitrary arbitrary shrink (w, x, y, z) = [ (w', x', y', z') | (w', (x', (y', z'))) <- shrink (w, (x, (y, z))) ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e) => Arbitrary (a,b,c,d,e) where arbitrary = liftM5 (,,,,) arbitrary arbitrary arbitrary arbitrary arbitrary shrink (v, w, x, y, z) = [ (v', w', x', y', z') | (v', (w', (x', (y', z')))) <- shrink (v, (w, (x, (y, z)))) ] instance ( Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e , Arbitrary f ) => Arbitrary (a,b,c,d,e,f) where arbitrary = return (,,,,,) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary shrink (u, v, w, x, y, z) = [ (u', v', w', x', y', z') | (u', (v', (w', (x', (y', z'))))) <- shrink (u, (v, (w, (x, (y, z))))) ] instance ( Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e , Arbitrary f, Arbitrary g ) => Arbitrary (a,b,c,d,e,f,g) where arbitrary = return (,,,,,,) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary shrink (t, u, v, w, x, y, z) = [ (t', u', v', w', x', y', z') | (t', (u', (v', (w', (x', (y', z')))))) <- shrink (t, (u, (v, (w, (x, (y, z)))))) ] instance ( Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e , Arbitrary f, Arbitrary g, Arbitrary h ) => Arbitrary (a,b,c,d,e,f,g,h) where arbitrary = return (,,,,,,,) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary shrink (s, t, u, v, w, x, y, z) = [ (s', t', u', v', w', x', y', z') | (s', (t', (u', (v', (w', (x', (y', z'))))))) <- shrink (s, (t, (u, (v, (w, (x, (y, z))))))) ] instance ( Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e , Arbitrary f, Arbitrary g, Arbitrary h, Arbitrary i ) => Arbitrary (a,b,c,d,e,f,g,h,i) where arbitrary = return (,,,,,,,,) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary shrink (r, s, t, u, v, w, x, y, z) = [ (r', s', t', u', v', w', x', y', z') | (r', (s', (t', (u', (v', (w', (x', (y', z')))))))) <- shrink (r, (s, (t, (u, (v, (w, (x, (y, z)))))))) ] instance ( Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e , Arbitrary f, Arbitrary g, Arbitrary h, Arbitrary i, Arbitrary j ) => Arbitrary (a,b,c,d,e,f,g,h,i,j) where arbitrary = return (,,,,,,,,,) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary shrink (q, r, s, t, u, v, w, x, y, z) = [ (q', r', s', t', u', v', w', x', y', z') | (q', (r', (s', (t', (u', (v', (w', (x', (y', z'))))))))) <- shrink (q, (r, (s, (t, (u, (v, (w, (x, (y, z))))))))) ] -- typical instance for primitive (numerical) types instance Arbitrary Integer where arbitrary = arbitrarySizedIntegral shrink = shrinkIntegral instance Arbitrary Int where arbitrary = arbitrarySizedIntegral shrink = shrinkIntegral instance Arbitrary Int8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word where arbitrary = arbitrarySizedNatural shrink = shrinkIntegral instance Arbitrary Word8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Char where arbitrary = frequency [(3, arbitraryASCIIChar), (1, arbitraryUnicodeChar)] shrink c = filter (<. c) $ nub $ ['a','b','c'] ++ [ toLower c | isUpper c ] ++ ['A','B','C'] ++ ['1','2','3'] ++ [' ','\n'] where a <. b = stamp a < stamp b stamp a = ( (not (isLower a) , not (isUpper a) , not (isDigit a)) , (not (a==' ') , not (isSpace a) , a) ) instance Arbitrary Float where arbitrary = oneof -- generate 0..1 numbers with full precision [ genFloat -- generate integral numbers , fromIntegral <$> (arbitrary :: Gen Int) -- generate fractions with small denominators , smallDenominators -- uniform -size..size with with denominators ~ size , uniform -- and uniform -size..size with higher precision , arbitrarySizedFractional ] where smallDenominators = sized $ \n -> do i <- chooseInt (0, n) pure (fromRational (streamNth i rationalUniverse)) uniform = sized $ \n -> do let n' = toInteger n b <- chooseInteger (1, max 1 n') a <- chooseInteger ((-n') * b, n' * b) return (fromRational (a % b)) shrink = shrinkDecimal instance Arbitrary Double where arbitrary = oneof -- generate 0..1 numbers with full precision [ genDouble -- generate integral numbers , fromIntegral <$> (arbitrary :: Gen Int) -- generate fractions with small denominators , smallDenominators -- uniform -size..size with with denominators ~ size , uniform -- and uniform -size..size with higher precision , arbitrarySizedFractional ] where smallDenominators = sized $ \n -> do i <- chooseInt (0, n) pure (fromRational (streamNth i rationalUniverse)) uniform = sized $ \n -> do let n' = toInteger n b <- chooseInteger (1, max 1 n') a <- chooseInteger ((-n') * b, n' * b) return (fromRational (a % b)) shrink = shrinkDecimal instance Arbitrary CChar where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CSChar where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CUChar where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CShort where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CUShort where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CInt where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CUInt where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CLong where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CULong where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CPtrdiff where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CSize where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CWchar where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CSigAtomic where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CLLong where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CULLong where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CIntPtr where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CUIntPtr where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CIntMax where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary CUIntMax where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral #ifndef NO_CTYPES_CONSTRUCTORS -- The following four types have no Bounded instance, -- so we fake it by discovering the bounds at runtime. instance Arbitrary CClock where arbitrary = fmap CClock arbitrary shrink (CClock x) = map CClock (shrink x) instance Arbitrary CTime where arbitrary = fmap CTime arbitrary shrink (CTime x) = map CTime (shrink x) #ifndef NO_FOREIGN_C_USECONDS instance Arbitrary CUSeconds where arbitrary = fmap CUSeconds arbitrary shrink (CUSeconds x) = map CUSeconds (shrink x) instance Arbitrary CSUSeconds where arbitrary = fmap CSUSeconds arbitrary shrink (CSUSeconds x) = map CSUSeconds (shrink x) #endif #endif instance Arbitrary CFloat where arbitrary = arbitrarySizedFractional shrink = shrinkDecimal instance Arbitrary CDouble where arbitrary = arbitrarySizedFractional shrink = shrinkDecimal -- Arbitrary instances for container types instance (Ord a, Arbitrary a) => Arbitrary (Set.Set a) where arbitrary = fmap Set.fromList arbitrary shrink = map Set.fromList . shrink . Set.toList instance (Ord k, Arbitrary k) => Arbitrary1 (Map.Map k) where liftArbitrary = fmap Map.fromList . liftArbitrary . liftArbitrary liftShrink shr = map Map.fromList . liftShrink (liftShrink shr) . Map.toList instance (Ord k, Arbitrary k, Arbitrary v) => Arbitrary (Map.Map k v) where arbitrary = arbitrary1 shrink = shrink1 instance Arbitrary IntSet.IntSet where arbitrary = fmap IntSet.fromList arbitrary shrink = map IntSet.fromList . shrink . IntSet.toList instance Arbitrary1 IntMap.IntMap where liftArbitrary = fmap IntMap.fromList . liftArbitrary . liftArbitrary liftShrink shr = map IntMap.fromList . liftShrink (liftShrink shr) . IntMap.toList instance Arbitrary a => Arbitrary (IntMap.IntMap a) where arbitrary = arbitrary1 shrink = shrink1 instance Arbitrary1 Sequence.Seq where liftArbitrary = fmap Sequence.fromList . liftArbitrary liftShrink shr = map Sequence.fromList . liftShrink shr . toList instance Arbitrary a => Arbitrary (Sequence.Seq a) where arbitrary = arbitrary1 shrink = shrink1 instance Arbitrary1 Tree.Tree where liftArbitrary arb = sized $ \n -> do k <- chooseInt (0, n) go k where go n = do -- n is the size of the trees. value <- arb pars <- arbPartition (n - 1) -- can go negative! forest <- mapM go pars return $ Tree.Node value forest arbPartition :: Int -> Gen [Int] arbPartition k = case compare k 1 of LT -> pure [] EQ -> pure [1] GT -> do first <- chooseInt (1, k) rest <- arbPartition $ k - first shuffle (first : rest) liftShrink shr = go where go (Tree.Node val forest) = forest ++ [ Tree.Node e fs | (e, fs) <- liftShrink2 shr (liftShrink go) (val, forest) ] instance Arbitrary a => Arbitrary (Tree.Tree a) where arbitrary = arbitrary1 shrink = shrink1 -- Arbitrary instance for Ziplist instance Arbitrary1 ZipList where liftArbitrary = fmap ZipList . liftArbitrary liftShrink shr = map ZipList . liftShrink shr . getZipList instance Arbitrary a => Arbitrary (ZipList a) where arbitrary = arbitrary1 shrink = shrink1 #ifndef NO_TRANSFORMERS -- Arbitrary instance for transformers' Functors instance Arbitrary1 Identity where liftArbitrary = fmap Identity liftShrink shr = map Identity . shr . runIdentity instance Arbitrary a => Arbitrary (Identity a) where arbitrary = arbitrary1 shrink = shrink1 instance Arbitrary2 Constant where liftArbitrary2 arbA _ = fmap Constant arbA liftShrink2 shrA _ = fmap Constant . shrA . getConstant instance Arbitrary a => Arbitrary1 (Constant a) where liftArbitrary = liftArbitrary2 arbitrary liftShrink = liftShrink2 shrink -- Have to be defined explicitly, as Constant is kind polymorphic instance Arbitrary a => Arbitrary (Constant a b) where arbitrary = fmap Constant arbitrary shrink = map Constant . shrink . getConstant instance (Arbitrary1 f, Arbitrary1 g) => Arbitrary1 (Product f g) where liftArbitrary arb = liftM2 Pair (liftArbitrary arb) (liftArbitrary arb) liftShrink shr (Pair f g) = [ Pair f' g | f' <- liftShrink shr f ] ++ [ Pair f g' | g' <- liftShrink shr g ] instance (Arbitrary1 f, Arbitrary1 g, Arbitrary a) => Arbitrary (Product f g a) where arbitrary = arbitrary1 shrink = shrink1 instance (Arbitrary1 f, Arbitrary1 g) => Arbitrary1 (Compose f g) where liftArbitrary = fmap Compose . liftArbitrary . liftArbitrary liftShrink shr = map Compose . liftShrink (liftShrink shr) . getCompose instance (Arbitrary1 f, Arbitrary1 g, Arbitrary a) => Arbitrary (Compose f g a) where arbitrary = arbitrary1 shrink = shrink1 #endif -- Arbitrary instance for Const instance Arbitrary2 Const where liftArbitrary2 arbA _ = fmap Const arbA liftShrink2 shrA _ = fmap Const . shrA . getConst instance Arbitrary a => Arbitrary1 (Const a) where liftArbitrary = liftArbitrary2 arbitrary liftShrink = liftShrink2 shrink -- Have to be defined explicitly, as Const is kind polymorphic instance Arbitrary a => Arbitrary (Const a b) where arbitrary = fmap Const arbitrary shrink = map Const . shrink . getConst instance Arbitrary (m a) => Arbitrary (WrappedMonad m a) where arbitrary = WrapMonad <$> arbitrary shrink (WrapMonad a) = map WrapMonad (shrink a) instance Arbitrary (a b c) => Arbitrary (WrappedArrow a b c) where arbitrary = WrapArrow <$> arbitrary shrink (WrapArrow a) = map WrapArrow (shrink a) -- Arbitrary instances for Monoid instance Arbitrary a => Arbitrary (Monoid.Dual a) where arbitrary = fmap Monoid.Dual arbitrary shrink = map Monoid.Dual . shrink . Monoid.getDual instance (Arbitrary a, CoArbitrary a) => Arbitrary (Monoid.Endo a) where arbitrary = fmap Monoid.Endo arbitrary shrink = map Monoid.Endo . shrink . Monoid.appEndo instance Arbitrary Monoid.All where arbitrary = fmap Monoid.All arbitrary shrink = map Monoid.All . shrink . Monoid.getAll instance Arbitrary Monoid.Any where arbitrary = fmap Monoid.Any arbitrary shrink = map Monoid.Any . shrink . Monoid.getAny instance Arbitrary a => Arbitrary (Monoid.Sum a) where arbitrary = fmap Monoid.Sum arbitrary shrink = map Monoid.Sum . shrink . Monoid.getSum instance Arbitrary a => Arbitrary (Monoid.Product a) where arbitrary = fmap Monoid.Product arbitrary shrink = map Monoid.Product . shrink . Monoid.getProduct #if defined(MIN_VERSION_base) #if MIN_VERSION_base(3,0,0) instance Arbitrary a => Arbitrary (Monoid.First a) where arbitrary = fmap Monoid.First arbitrary shrink = map Monoid.First . shrink . Monoid.getFirst instance Arbitrary a => Arbitrary (Monoid.Last a) where arbitrary = fmap Monoid.Last arbitrary shrink = map Monoid.Last . shrink . Monoid.getLast #endif #if MIN_VERSION_base(4,8,0) instance Arbitrary (f a) => Arbitrary (Monoid.Alt f a) where arbitrary = fmap Monoid.Alt arbitrary shrink = map Monoid.Alt . shrink . Monoid.getAlt #endif #endif -- | Generates 'Version' with non-empty non-negative @versionBranch@, and empty @versionTags@ instance Arbitrary Version where arbitrary = sized $ \n -> do k <- chooseInt (0, log2 n) xs <- vectorOf (k+1) arbitrarySizedNatural return (Version xs []) where log2 :: Int -> Int log2 n | n <= 1 = 0 | otherwise = 1 + log2 (n `div` 2) shrink (Version xs _) = [ Version xs' [] | xs' <- shrink xs , length xs' > 0 , all (>=0) xs' ] instance Arbitrary QCGen where arbitrary = MkGen (\g _ -> g) instance Arbitrary ExitCode where arbitrary = frequency [(1, return ExitSuccess), (3, liftM ExitFailure arbitrary)] shrink (ExitFailure x) = ExitSuccess : [ ExitFailure x' | x' <- shrink x ] shrink _ = [] #if defined(MIN_VERSION_base) #if MIN_VERSION_base(4,2,0) instance Arbitrary Newline where arbitrary = elements [LF, CRLF] -- The behavior of code for LF is generally simpler than for CRLF -- See the documentation for this type, which states that Haskell -- Internally always assumes newlines are \n and this type represents -- how to translate that to and from the outside world, where LF means -- no translation. shrink LF = [] shrink CRLF = [LF] instance Arbitrary NewlineMode where arbitrary = NewlineMode <$> arbitrary <*> arbitrary shrink (NewlineMode inNL outNL) = [NewlineMode inNL' outNL' | (inNL', outNL') <- shrink (inNL, outNL)] #endif #endif -- ** Helper functions for implementing arbitrary -- | Apply a binary function to random arguments. applyArbitrary2 :: (Arbitrary a, Arbitrary b) => (a -> b -> r) -> Gen r applyArbitrary2 f = liftA2 f arbitrary arbitrary -- | Apply a ternary function to random arguments. applyArbitrary3 :: (Arbitrary a, Arbitrary b, Arbitrary c) => (a -> b -> c -> r) -> Gen r applyArbitrary3 f = liftA3 f arbitrary arbitrary arbitrary -- | Apply a function of arity 4 to random arguments. applyArbitrary4 :: (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => (a -> b -> c -> d -> r) -> Gen r applyArbitrary4 f = applyArbitrary3 (uncurry f) -- | Generates an integral number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedIntegral :: Integral a => Gen a arbitrarySizedIntegral = sized $ \n -> inBounds fromIntegral (chooseInt (-n, n)) -- | Generates a natural number. The number's maximum value depends on -- the size parameter. arbitrarySizedNatural :: Integral a => Gen a arbitrarySizedNatural = sized $ \n -> inBounds fromIntegral (chooseInt (0, n)) inBounds :: Integral a => (Int -> a) -> Gen Int -> Gen a inBounds fi g = fmap fi (g `suchThat` (\x -> toInteger x == toInteger (fi x))) -- | Uniformly generates a fractional number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedFractional :: Fractional a => Gen a arbitrarySizedFractional = sized $ \n -> do denom <- chooseInt (1, max 1 n) numer <- chooseInt (-n*denom, n*denom) pure $ fromIntegral numer / fromIntegral denom -- Useful for getting at minBound and maxBound without having to -- fiddle around with asTypeOf. {-# INLINE withBounds #-} withBounds :: Bounded a => (a -> a -> Gen a) -> Gen a withBounds k = k minBound maxBound -- | Generates an integral number. The number is chosen uniformly from -- the entire range of the type. You may want to use -- 'arbitrarySizedBoundedIntegral' instead. arbitraryBoundedIntegral :: (Bounded a, Integral a) => Gen a arbitraryBoundedIntegral = chooseBoundedIntegral (minBound, maxBound) -- | Generates an element of a bounded type. The element is -- chosen from the entire range of the type. arbitraryBoundedRandom :: (Bounded a, Random a) => Gen a arbitraryBoundedRandom = choose (minBound,maxBound) -- | Generates an element of a bounded enumeration. arbitraryBoundedEnum :: (Bounded a, Enum a) => Gen a arbitraryBoundedEnum = chooseEnum (minBound, maxBound) -- | Generates an integral number from a bounded domain. The number is -- chosen from the entire range of the type, but small numbers are -- generated more often than big numbers. Inspired by demands from -- Phil Wadler. arbitrarySizedBoundedIntegral :: (Bounded a, Integral a) => Gen a -- INLINEABLE so that this combinator gets specialised at each type, -- which means that the constant 'bits' in the let-block below will -- only be computed once. {-# INLINEABLE arbitrarySizedBoundedIntegral #-} arbitrarySizedBoundedIntegral = withBounds $ \mn mx -> let ilog2 1 = 0 ilog2 n | n > 0 = 1 + ilog2 (n `div` 2) -- How many bits are needed to represent this type? -- (This number is an upper bound, not exact.) bits = ilog2 (toInteger mx - toInteger mn + 1) in sized $ \k -> let -- Reach maximum size by k=80, or quicker for small integer types power = ((bits `max` 40) * k) `div` 80 -- Bounds should be 2^power, but: -- * clamp the result to minBound/maxBound -- * clamp power to 'bits', in case k is a huge number lo = toInteger mn `max` (-1 `shiftL` (power `min` bits)) hi = toInteger mx `min` (1 `shiftL` (power `min` bits)) in fmap fromInteger (chooseInteger (lo, hi)) -- ** Generators for various kinds of character -- | Generates any Unicode character (but not a surrogate) arbitraryUnicodeChar :: Gen Char arbitraryUnicodeChar = arbitraryBoundedEnum `suchThat` isValidUnicode where isValidUnicode c = case generalCategory c of Surrogate -> False NotAssigned -> False _ -> True -- | Generates a random ASCII character (0-127). arbitraryASCIIChar :: Gen Char arbitraryASCIIChar = chooseEnum ('\0', '\127') -- | Generates a printable Unicode character. arbitraryPrintableChar :: Gen Char arbitraryPrintableChar = arbitrary `suchThat` isPrint -- ** Helper functions for implementing shrink -- | Returns no shrinking alternatives. shrinkNothing :: a -> [a] shrinkNothing _ = [] -- | Map a shrink function to another domain. This is handy if your data type -- has special invariants, but is /almost/ isomorphic to some other type. -- -- @ -- shrinkOrderedList :: (Ord a, Arbitrary a) => [a] -> [[a]] -- shrinkOrderedList = shrinkMap sort id -- -- shrinkSet :: (Ord a, Arbitrary a) => Set a -> [Set a] -- shrinkSet = shrinkMap fromList toList -- @ shrinkMap :: Arbitrary a => (a -> b) -> (b -> a) -> b -> [b] shrinkMap f g = shrinkMapBy f g shrink -- | Non-overloaded version of `shrinkMap`. shrinkMapBy :: (a -> b) -> (b -> a) -> (a -> [a]) -> b -> [b] shrinkMapBy f g shr = map f . shr . g -- | Shrink an integral number. shrinkIntegral :: Integral a => a -> [a] shrinkIntegral x = nub $ [ -x | x < 0, -x > x ] ++ [ x' | x' <- takeWhile (<< x) (0:[ x - i | i <- tail (iterate (`quot` 2) x) ]) ] where -- a << b is "morally" abs a < abs b, but taking care of overflow. a << b = case (a >= 0, b >= 0) of (True, True) -> a < b (False, False) -> a > b (True, False) -> a + b < 0 (False, True) -> a + b > 0 -- | Shrink a fraction, preferring numbers with smaller -- numerators or denominators. See also 'shrinkDecimal'. shrinkRealFrac :: RealFrac a => a -> [a] shrinkRealFrac x | not (x == x) = 0 : take 10 (iterate (*2) 0) -- NaN | not (2*x+1>x) = 0 : takeWhile (<x) (iterate (*2) 0) -- infinity | x < 0 = negate x:map negate (shrinkRealFrac (negate x)) | otherwise = -- To ensure termination filter (\y -> abs y < abs x) $ -- Try shrinking to an integer first map fromInteger (shrink (truncate x) ++ [truncate x]) ++ -- Shrink the numerator [fromRational (num' % denom) | num' <- shrink num] ++ -- Shrink the denominator, and keep the fraction as close -- to the original as possible, rounding towards zero [fromRational (truncate (num * denom' % denom) % denom') | denom' <- shrink denom, denom' /= 0 ] where num = numerator (toRational x) denom = denominator (toRational x) -- | Shrink a real number, preferring numbers with shorter -- decimal representations. See also 'shrinkRealFrac'. shrinkDecimal :: RealFrac a => a -> [a] shrinkDecimal x | not (x == x) = 0 : take 10 (iterate (*2) 0) -- NaN | not (2*abs x+1>abs x) = 0 : takeWhile (<x) (iterate (*2) 0) -- infinity | otherwise = -- e.g. shrink pi = -- shrink 3 ++ map (/ 10) (shrink 31) ++ -- map (/ 100) (shrink 314) + ..., -- where the inner calls to shrink use integer shrinking. [ y | precision <- take 6 (iterate (*10) 1), let m = round (toRational x * precision), precision == 1 || m `mod` 10 /= 0, -- don't allow shrinking to increase digits n <- m:shrink m, let y = fromRational (fromInteger n / precision), abs y < abs x ] -------------------------------------------------------------------------- -- ** CoArbitrary #ifndef NO_GENERICS -- | Used for random generation of functions. -- You should consider using 'Test.QuickCheck.Fun' instead, which -- can show the generated functions as strings. -- -- If you are using a recent GHC, there is a default definition of -- 'coarbitrary' using 'genericCoarbitrary', so if your type has a -- 'Generic' instance it's enough to say -- -- > instance CoArbitrary MyType -- -- You should only use 'genericCoarbitrary' for data types where -- equality is structural, i.e. if you can't have two different -- representations of the same value. An example where it's not -- safe is sets implemented using binary search trees: the same -- set can be represented as several different trees. -- Here you would have to explicitly define -- @coarbitrary s = coarbitrary (toList s)@. #else -- | Used for random generation of functions. #endif class CoArbitrary a where -- | Used to generate a function of type @a -> b@. -- The first argument is a value, the second a generator. -- You should use 'variant' to perturb the random generator; -- the goal is that different values for the first argument will -- lead to different calls to 'variant'. An example will help: -- -- @ -- instance CoArbitrary a => CoArbitrary [a] where -- coarbitrary [] = 'variant' 0 -- coarbitrary (x:xs) = 'variant' 1 . coarbitrary (x,xs) -- @ coarbitrary :: a -> Gen b -> Gen b #ifndef NO_GENERICS default coarbitrary :: (Generic a, GCoArbitrary (Rep a)) => a -> Gen b -> Gen b coarbitrary = genericCoarbitrary -- | Generic CoArbitrary implementation. genericCoarbitrary :: (Generic a, GCoArbitrary (Rep a)) => a -> Gen b -> Gen b genericCoarbitrary = gCoarbitrary . from class GCoArbitrary f where gCoarbitrary :: f a -> Gen b -> Gen b instance GCoArbitrary U1 where gCoarbitrary U1 = id instance (GCoArbitrary f, GCoArbitrary g) => GCoArbitrary (f :*: g) where -- Like the instance for tuples. gCoarbitrary (l :*: r) = gCoarbitrary l . gCoarbitrary r instance (GCoArbitrary f, GCoArbitrary g) => GCoArbitrary (f :+: g) where -- Like the instance for Either. gCoarbitrary (L1 x) = variant 0 . gCoarbitrary x gCoarbitrary (R1 x) = variant 1 . gCoarbitrary x instance GCoArbitrary f => GCoArbitrary (M1 i c f) where gCoarbitrary (M1 x) = gCoarbitrary x instance CoArbitrary a => GCoArbitrary (K1 i a) where gCoarbitrary (K1 x) = coarbitrary x #endif {-# DEPRECATED (><) "Use ordinary function composition instead" #-} -- | Combine two generator perturbing functions, for example the -- results of calls to 'variant' or 'coarbitrary'. (><) :: (Gen a -> Gen a) -> (Gen a -> Gen a) -> (Gen a -> Gen a) (><) = (.) instance (Arbitrary a, CoArbitrary b) => CoArbitrary (a -> b) where coarbitrary f gen = do xs <- arbitrary coarbitrary (map f xs) gen instance CoArbitrary () where coarbitrary _ = id instance CoArbitrary Bool where coarbitrary False = variant 0 coarbitrary True = variant 1 instance CoArbitrary Ordering where coarbitrary GT = variant 0 coarbitrary EQ = variant 1 coarbitrary LT = variant 2 instance CoArbitrary a => CoArbitrary (Maybe a) where coarbitrary Nothing = variant 0 coarbitrary (Just x) = variant 1 . coarbitrary x instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (Either a b) where coarbitrary (Left x) = variant 0 . coarbitrary x coarbitrary (Right y) = variant 1 . coarbitrary y instance CoArbitrary a => CoArbitrary [a] where coarbitrary [] = variant 0 coarbitrary (x:xs) = variant 1 . coarbitrary (x,xs) instance (Integral a, CoArbitrary a) => CoArbitrary (Ratio a) where coarbitrary r = coarbitrary (numerator r,denominator r) #ifndef NO_FIXED instance HasResolution a => CoArbitrary (Fixed a) where coarbitrary = coarbitraryReal #endif #if defined(MIN_VERSION_base) && MIN_VERSION_base(4,4,0) instance CoArbitrary a => CoArbitrary (Complex a) where #else instance (RealFloat a, CoArbitrary a) => CoArbitrary (Complex a) where #endif coarbitrary (x :+ y) = coarbitrary x . coarbitrary y instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (a,b) where coarbitrary (x,y) = coarbitrary x . coarbitrary y instance (CoArbitrary a, CoArbitrary b, CoArbitrary c) => CoArbitrary (a,b,c) where coarbitrary (x,y,z) = coarbitrary x . coarbitrary y . coarbitrary z instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d) => CoArbitrary (a,b,c,d) where coarbitrary (x,y,z,v) = coarbitrary x . coarbitrary y . coarbitrary z . coarbitrary v instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d, CoArbitrary e) => CoArbitrary (a,b,c,d,e) where coarbitrary (x,y,z,v,w) = coarbitrary x . coarbitrary y . coarbitrary z . coarbitrary v . coarbitrary w -- typical instance for primitive (numerical) types instance CoArbitrary Integer where coarbitrary = coarbitraryIntegral instance CoArbitrary Int where coarbitrary = coarbitraryIntegral instance CoArbitrary Int8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word where coarbitrary = coarbitraryIntegral instance CoArbitrary Word8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Char where coarbitrary = coarbitrary . ord instance CoArbitrary Float where coarbitrary = coarbitraryReal instance CoArbitrary Double where coarbitrary = coarbitraryReal -- Coarbitrary instances for container types instance CoArbitrary a => CoArbitrary (Set.Set a) where coarbitrary = coarbitrary. Set.toList instance (CoArbitrary k, CoArbitrary v) => CoArbitrary (Map.Map k v) where coarbitrary = coarbitrary . Map.toList instance CoArbitrary IntSet.IntSet where coarbitrary = coarbitrary . IntSet.toList instance CoArbitrary a => CoArbitrary (IntMap.IntMap a) where coarbitrary = coarbitrary . IntMap.toList instance CoArbitrary a => CoArbitrary (Sequence.Seq a) where coarbitrary = coarbitrary . toList instance CoArbitrary a => CoArbitrary (Tree.Tree a) where coarbitrary (Tree.Node val forest) = coarbitrary val . coarbitrary forest -- CoArbitrary instance for Ziplist instance CoArbitrary a => CoArbitrary (ZipList a) where coarbitrary = coarbitrary . getZipList #ifndef NO_TRANSFORMERS -- CoArbitrary instance for transformers' Functors instance CoArbitrary a => CoArbitrary (Identity a) where coarbitrary = coarbitrary . runIdentity instance CoArbitrary a => CoArbitrary (Constant a b) where coarbitrary = coarbitrary . getConstant #endif -- CoArbitrary instance for Const instance CoArbitrary a => CoArbitrary (Const a b) where coarbitrary = coarbitrary . getConst -- CoArbitrary instances for Monoid instance CoArbitrary a => CoArbitrary (Monoid.Dual a) where coarbitrary = coarbitrary . Monoid.getDual instance (Arbitrary a, CoArbitrary a) => CoArbitrary (Monoid.Endo a) where coarbitrary = coarbitrary . Monoid.appEndo instance CoArbitrary Monoid.All where coarbitrary = coarbitrary . Monoid.getAll instance CoArbitrary Monoid.Any where coarbitrary = coarbitrary . Monoid.getAny instance CoArbitrary a => CoArbitrary (Monoid.Sum a) where coarbitrary = coarbitrary . Monoid.getSum instance CoArbitrary a => CoArbitrary (Monoid.Product a) where coarbitrary = coarbitrary . Monoid.getProduct #if defined(MIN_VERSION_base) #if MIN_VERSION_base(3,0,0) instance CoArbitrary a => CoArbitrary (Monoid.First a) where coarbitrary = coarbitrary . Monoid.getFirst instance CoArbitrary a => CoArbitrary (Monoid.Last a) where coarbitrary = coarbitrary . Monoid.getLast #endif #if MIN_VERSION_base(4,8,0) instance CoArbitrary (f a) => CoArbitrary (Monoid.Alt f a) where coarbitrary = coarbitrary . Monoid.getAlt #endif #endif instance CoArbitrary Version where coarbitrary (Version a b) = coarbitrary (a, b) #if defined(MIN_VERSION_base) #if MIN_VERSION_base(4,2,0) instance CoArbitrary Newline where coarbitrary LF = variant 0 coarbitrary CRLF = variant 1 instance CoArbitrary NewlineMode where coarbitrary (NewlineMode inNL outNL) = coarbitrary inNL . coarbitrary outNL #endif #endif -- ** Helpers for implementing coarbitrary -- | A 'coarbitrary' implementation for integral numbers. coarbitraryIntegral :: Integral a => a -> Gen b -> Gen b coarbitraryIntegral = variant -- | A 'coarbitrary' implementation for real numbers. coarbitraryReal :: Real a => a -> Gen b -> Gen b coarbitraryReal x = coarbitrary (toRational x) -- | 'coarbitrary' helper for lazy people :-). coarbitraryShow :: Show a => a -> Gen b -> Gen b coarbitraryShow x = coarbitrary (show x) -- | A 'coarbitrary' implementation for enums. coarbitraryEnum :: Enum a => a -> Gen b -> Gen b coarbitraryEnum = variant . fromEnum -------------------------------------------------------------------------- -- ** arbitrary generators -- these are here and not in Gen because of the Arbitrary class constraint -- | Generates a list of a given length. vector :: Arbitrary a => Int -> Gen [a] vector k = vectorOf k arbitrary -- | Generates an ordered list. orderedList :: (Ord a, Arbitrary a) => Gen [a] orderedList = sort `fmap` arbitrary -- | Generates an infinite list. infiniteList :: Arbitrary a => Gen [a] infiniteList = infiniteListOf arbitrary -------------------------------------------------------------------------- -- ** Rational helper infixr 5 :< data Stream a = !a :< Stream a streamNth :: Int -> Stream a -> a streamNth n (x :< xs) | n <= 0 = x | otherwise = streamNth (n - 1) xs -- We read into this stream only with ~size argument, -- so it's ok to have it as CAF. -- rationalUniverse :: Stream Rational rationalUniverse = 0 :< 1 :< (-1) :< go leftSideStream where go (x :< xs) = let nx = -x rx = recip x nrx = -rx in nx `seq` rx `seq` nrx `seq` (x :< rx :< nx :< nrx :< go xs) -- All the rational numbers on the left side of the Calkin-Wilf tree, -- in breadth-first order. leftSideStream :: Stream Rational leftSideStream = (1 % 2) :< go leftSideStream where go (x :< xs) = lChild `seq` rChild `seq` (lChild :< rChild :< go xs) where nd = numerator x + denominator x lChild = numerator x % nd rChild = nd % denominator x -------------------------------------------------------------------------- -- the end.
import data.matrix.basic data.array.lemmas data.rat.basic def fmatrix (m : ℕ) (n : ℕ) := array (m * n) ℚ namespace fmatrix variables {l m n : ℕ} instance : has_add (fmatrix m n) := ⟨array.map₂ (+)⟩ instance : has_zero (fmatrix m n) := ⟨mk_array _ 0⟩ instance : has_neg (fmatrix m n) := ⟨array.map has_neg.neg⟩ lemma add_def (a b : fmatrix m n) : a + b = a.map₂ (+) b := rfl def fin.pair (i : fin m) (j : fin n) : fin (m * n) := ⟨j + n * i, calc ((j : ℕ) + n * i) + 1 = i * n + (j + 1) : by simp [mul_comm, add_comm] ... ≤ i * n + n : add_le_add (le_refl _) j.2 ... = (i + 1) * n : by simp [add_mul] ... ≤ m * n : mul_le_mul i.2 (le_refl _) (nat.zero_le _) (nat.zero_le _)⟩ def fin.unpair₁ (x : fin (m * n)) : fin m := ⟨x / n, nat.div_lt_of_lt_mul (mul_comm m n ▸ x.2)⟩ def fin.unpair₂ (x : fin (m * n)) : fin n := ⟨x % n, nat.mod_lt _ (nat.pos_of_ne_zero (λ hn0, by rw [hn0, mul_zero] at x; exact x.elim0))⟩ @[simp] lemma fin.pair_unpair (x : fin (m * n)) : fin.pair (fin.unpair₁ x) (fin.unpair₂ x) = x := fin.eq_of_veq (nat.mod_add_div _ _) @[simp] lemma fin.unpair₁_pair (i : fin m) (j : fin n) : fin.unpair₁ (fin.pair i j) = i := fin.eq_of_veq $ show ((j : ℕ) + n * i) / n = i, by erw [nat.add_mul_div_left _ _ (lt_of_le_of_lt (nat.zero_le _) j.2), nat.div_eq_of_lt j.2, zero_add] @[simp] lemma fin.unpair₂_pair (i : fin m) (j : fin n) : fin.unpair₂ (fin.pair i j) = j := fin.eq_of_veq $ show ((j : ℕ) + n * i) % n = j, by erw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt j.2]; refl lemma fin.pair_eq_pair {i i' : fin m} {j j' : fin n} : fin.pair i j = fin.pair i' j' ↔ i' = i ∧ j' = j := ⟨λ h, ⟨by rw [← fin.unpair₁_pair i j, h, fin.unpair₁_pair], by rw [← fin.unpair₂_pair i j, h, fin.unpair₂_pair]⟩, λ ⟨hi, hj⟩, by rw [hi, hj]⟩ def read (A : fmatrix m n) (i : fin m) (j : fin n) : ℚ := array.read A (fin.pair i j) def write (A : fmatrix m n) (i : fin m) (j : fin n) : ℚ → fmatrix m n := array.write A (fin.pair i j) @[extensionality] lemma ext {A B : fmatrix m n} (h : ∀ i j, A.read i j = B.read i j) : A = B := array.ext $ λ x, by simpa [fmatrix.read] using h (fin.unpair₁ x) (fin.unpair₂ x) @[simp] lemma read_write (A : fmatrix m n) (i : fin m) (j : fin n) (x : ℚ) : (A.write i j x).read i j = x := array.read_write _ _ _ lemma read_write_of_ne (A : fmatrix m n) {i i' : fin m} {j j': fin n} (x : ℚ) (h : i' ≠ i ∨ j' ≠ j) : (A.write i j x).read i' j' = A.read i' j' := array.read_write_of_ne _ _ (by rwa [ne.def, fin.pair_eq_pair, not_and_distrib]) def foreach_aux (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : Π (i : ℕ) (j : ℕ) (hi : i ≤ m) (hj : j ≤ n), fmatrix m n | 0 j := λ hi hj, A | (i+1) 0 := λ hi hj, foreach_aux i n (nat.le_of_succ_le hi) (le_refl _) | (i+1) (j+1) := λ hi hj, (foreach_aux (i+1) j hi (nat.le_of_succ_le hj)).write ⟨i, hi⟩ ⟨j, hj⟩ (f ⟨i, hi⟩ ⟨j, hj⟩ (A.read ⟨i, hi⟩ ⟨j, hj⟩)) def foreach (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : fmatrix m n := foreach_aux A f m n (le_refl _) (le_refl _) lemma read_foreach_aux (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) : Π (i : ℕ) (j : ℕ) (hi : i ≤ m) (hj : j ≤ n) (i' : fin m) (j' : fin n) (hij' : i'.1 + 1 < i ∨ (i'.1 + 1 = i ∧ j'.1 < j)), (A.foreach_aux f i j hi hj).read i' j' = f i' j' (A.read i' j') | 0 j := λ hi hj i' j' hij', hij'.elim (λ hi', (nat.not_lt_zero _ hi').elim) (λ hij', (nat.succ_ne_zero _ hij'.1).elim) | (i+1) 0 := λ hi hj i' j' hij', hij'.elim (λ hi', begin rw [foreach_aux, read_foreach_aux], cases lt_or_eq_of_le (nat.le_of_lt_succ hi') with hi' hi', { exact or.inl hi' }, { exact or.inr ⟨hi', j'.2⟩ } end) (λ hij', (nat.not_lt_zero _ hij'.2).elim) | (i+1) (j+1) := λ hi hj i' j' hij', begin rw [foreach_aux], dsimp only, by_cases hij : i' = ⟨i, hi⟩ ∧ j' = ⟨j, hj⟩, { rw [hij.1, hij.2, read_write] }, { rw not_and_distrib at hij, rw [read_write_of_ne _ _ hij, read_foreach_aux], cases hij' with hi' hij', { exact or.inl hi' }, { exact or.inr ⟨hij'.1, lt_of_le_of_ne (nat.le_of_lt_succ hij'.2) (fin.vne_of_ne (hij.resolve_left (not_not_intro (fin.eq_of_veq (nat.succ_inj hij'.1)))))⟩ } } end @[simp] lemma read_foreach (A : fmatrix m n) (f : fin m → fin n → ℚ → ℚ) (i : fin m) (j : fin n) : (A.foreach f).read i j = f i j (A.read i j) := read_foreach_aux _ _ _ _ _ _ _ _ ((lt_or_eq_of_le (nat.succ_le_of_lt i.2)).elim or.inl (λ hi, or.inr ⟨hi, j.2⟩)) def write_column (A : fmatrix m n) (i : fin m) (f : fin n → ℚ) : fmatrix m n := (list.fin_range n).foldl (λ A j, A.write i j (f j)) A def to_matrix (A : fmatrix m n) : matrix (fin m) (fin n) ℚ | i j := A.read i j def of_matrix (A : matrix (fin m) (fin n) ℚ) : fmatrix m n := (0 : fmatrix m n).foreach (λ i j _, A i j) @[simp] lemma to_matrix_of_matrix (A : matrix (fin m) (fin n) ℚ) : (of_matrix A).to_matrix = A := by ext; simp [to_matrix, of_matrix] @[simp] lemma of_matrix_to_matrix (A : fmatrix m n) : of_matrix A.to_matrix = A := by ext; simp [of_matrix, to_matrix] def mul (B : fmatrix l m) (C : fmatrix m n) : fmatrix l n := let s : finset (fin m) := finset.univ in (0 : fmatrix l n).foreach (λ i j _, s.sum (λ k : fin m, B.read i k * C.read k j)) instance : has_mul (fmatrix n n) := ⟨mul⟩ instance : has_one (fmatrix n n) := ⟨(0 : fmatrix n n).foreach (λ i j _, if i = j then 1 else 0)⟩ instance : has_le (fmatrix m n) := ⟨λ A B, ∀ i, array.read A i ≤ array.read B i⟩ instance : decidable_rel ((≤) : fmatrix m n → fmatrix m n → Prop) := λ A B, show decidable (∀ i, array.read A i ≤ array.read B i), by apply_instance def mul₂ (M : fmatrix l m) (N : fmatrix m n) : fmatrix l n := array.foreach (0 : fmatrix l n) (λ x _, let i := fin.unpair₁ x in let k := fin.unpair₂ x in finset.univ.sum (λ j : fin m, M.read i j * N.read j k)) def equiv_matrix : fmatrix m n ≃ matrix (fin m) (fin n) ℚ := { to_fun := to_matrix, inv_fun := of_matrix, left_inv := of_matrix_to_matrix, right_inv := to_matrix_of_matrix } lemma to_matrix_add (A B : fmatrix m n) : (A + B).to_matrix = A.to_matrix + B.to_matrix := by ext; simp [to_matrix, fmatrix.read, add_def, array.read_map₂] lemma to_matrix_mul (A : fmatrix l m) (B : fmatrix m n) : (A.mul B).to_matrix = A.to_matrix.mul B.to_matrix := by ext; simp [to_matrix, matrix.mul, fmatrix.mul] end fmatrix -- #eval (fmatrix.mul (show fmatrix 50 50 ℚ, from ((list.range 2500).map nat.cast).to_array)) -- (show fmatrix 50 50 ℚ, from ((list.range 2500).map nat.cast).to_array)) -- #eval let m := 213 in let n := 100 in -- let l : array (m * n) ℚ := unchecked_cast (list.to_array (((list.range (m * n)).map -- (rat.of_int ∘ int.of_nat: ℕ → ℚ)))) in -- array.to_list -- (fmatrix.mul(show fmatrix m n, from unchecked_cast l) -- (show fmatrix n m , from unchecked_cast l))
theorem ex : ∀ x : Unit, x = () := by intro (); rfl
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) *) theory initialised_decls imports "CParser.CTranslation" begin external_file "initialised_decls.c" install_C_file "initialised_decls.c" context initialised_decls_global_addresses begin thm f_body_def thm g_body_def end text \<open> Following proof confirms that we can prove stuff about g without needing to prove that f is side-effect free; which ain't true. The translation doesn't incorrectly reckon that the initialisation of local variable i is an "embedded" function call. This proof still works, but there aren't side-effect-free guards inserted at any point in the current translation so the point is a bit moot. \<close> lemma (in initialised_decls_global_addresses) foo: shows "\<Gamma> \<turnstile> \<lbrace> True \<rbrace> \<acute>ret__int :== PROC g() \<lbrace> \<acute>ret__int = 3 \<rbrace>" apply vcg done end
module Main import IdrisUnit import Control.App import Control.App.Console hanoi : Int -> a -> a -> a -> List (a, a) hanoi 0 a b c = [] hanoi 1 a b c = [(a, c)] hanoi n a b c = hanoi (n-1) a c b ++ [(a, c)] ++ hanoi (n-1) b a c spec : Spec es => App es () spec = do describe "example" $ do context "arith" $ do it "1+1 = 2" $ do 1+1 `shouldBe` 2 it "1*1 = 1" $ do 1*1 `shouldBe` 1 describe "hanoi" $ do it "3 level" $ do hanoi 3 'A' 'B' 'C' `shouldBe` [('A', 'C'), ('A', 'B'), ('C', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('A', 'C')] it "4 level" $ do hanoi 4 'A' 'B' 'C' `shouldBe` [('A', 'B'), ('A', 'C'), ('B', 'C'), ('A', 'B'), ('C', 'A'), ('C', 'B'), ('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'A'), ('C', 'A'), ('B', 'C'), ('A', 'B'), ('A', 'C'), ('B', 'C')] main : IO () main = run spec
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl ! This file was ported from Lean 3 source module data.set.pairwise.basic ! leanprover-community/mathlib commit c227d107bbada5d0d9d20287e3282c0a7f1651a0 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Set.Function import Mathlib.Logic.Relation import Mathlib.Logic.Pairwise /-! # Relations holding pairwise This file develops pairwise relations and defines pairwise disjoint indexed sets. We also prove many basic facts about `Pairwise`. It is possible that an intermediate file, with more imports than `Logic.Pairwise` but not importing `Data.Set.Function` would be appropriate to hold many of these basic facts. ## Main declarations * `Set.PairwiseDisjoint`: `s.PairwiseDisjoint f` states that images under `f` of distinct elements of `s` are either equal or `Disjoint`. ## Notes The spelling `s.PairwiseDisjoint id` is preferred over `s.Pairwise Disjoint` to permit dot notation on `Set.PairwiseDisjoint`, even though the latter unfolds to something nicer. -/ open Set Function variable {α β γ ι ι' : Type _} {r p q : α → α → Prop} section Pairwise variable {f g : ι → α} {s t u : Set α} {a b : α} theorem pairwise_on_bool (hr : Symmetric r) {a b : α} : Pairwise (r on fun c => cond c a b) ↔ r a b := by simpa [Pairwise, Function.onFun] using @hr a b #align pairwise_on_bool pairwise_on_bool theorem pairwise_disjoint_on_bool [SemilatticeInf α] [OrderBot α] {a b : α} : Pairwise (Disjoint on fun c => cond c a b) ↔ Disjoint a b := pairwise_on_bool Disjoint.symm #align pairwise_disjoint_on_bool pairwise_disjoint_on_bool theorem Symmetric.pairwise_on [LinearOrder ι] (hr : Symmetric r) (f : ι → α) : Pairwise (r on f) ↔ ∀ ⦃m n⦄, m < n → r (f m) (f n) := ⟨fun h _m _n hmn => h hmn.ne, fun h _m _n hmn => hmn.lt_or_lt.elim (@h _ _) fun h' => hr (h h')⟩ #align symmetric.pairwise_on Symmetric.pairwise_on theorem pairwise_disjoint_on [SemilatticeInf α] [OrderBot α] [LinearOrder ι] (f : ι → α) : Pairwise (Disjoint on f) ↔ ∀ ⦃m n⦄, m < n → Disjoint (f m) (f n) := Symmetric.pairwise_on Disjoint.symm f #align pairwise_disjoint_on pairwise_disjoint_on theorem pairwise_disjoint_mono [SemilatticeInf α] [OrderBot α] (hs : Pairwise (Disjoint on f)) (h : g ≤ f) : Pairwise (Disjoint on g) := hs.mono fun i j hij => Disjoint.mono (h i) (h j) hij #align pairwise_disjoint.mono pairwise_disjoint_mono namespace Set theorem Pairwise.mono (h : t ⊆ s) (hs : s.Pairwise r) : t.Pairwise r := fun _x xt _y yt => hs (h xt) (h yt) #align set.pairwise.mono Set.Pairwise.mono theorem Pairwise.mono' (H : r ≤ p) (hr : s.Pairwise r) : s.Pairwise p := hr.imp H #align set.pairwise.mono' Set.Pairwise.mono' theorem pairwise_top (s : Set α) : s.Pairwise ⊤ := pairwise_of_forall s _ fun _ _ => trivial #align set.pairwise_top Set.pairwise_top protected theorem Subsingleton.pairwise (h : s.Subsingleton) (r : α → α → Prop) : s.Pairwise r := fun _x hx _y hy hne => (hne (h hx hy)).elim #align set.subsingleton.pairwise Set.Subsingleton.pairwise @[simp] theorem pairwise_empty (r : α → α → Prop) : (∅ : Set α).Pairwise r := subsingleton_empty.pairwise r #align set.pairwise_empty Set.pairwise_empty @[simp] theorem pairwise_singleton (a : α) (r : α → α → Prop) : Set.Pairwise {a} r := subsingleton_singleton.pairwise r #align set.pairwise_singleton Set.pairwise_singleton theorem pairwise_iff_of_refl [IsRefl α r] : s.Pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr fun _ _ _ _ => or_iff_not_imp_left.symm.trans <| or_iff_right_of_imp of_eq #align set.pairwise_iff_of_refl Set.pairwise_iff_of_refl alias pairwise_iff_of_refl ↔ Pairwise.of_refl _ #align set.pairwise.of_refl Set.Pairwise.of_refl theorem Nonempty.pairwise_iff_exists_forall [IsEquiv α r] {s : Set ι} (hs : s.Nonempty) : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by constructor · rcases hs with ⟨y, hy⟩ refine' fun H => ⟨f y, fun x hx => _⟩ rcases eq_or_ne x y with (rfl | hne) · apply IsRefl.refl · exact H hx hy hne · rintro ⟨z, hz⟩ x hx y hy _ exact @IsTrans.trans α r _ (f x) z (f y) (hz _ hx) (IsSymm.symm _ _ <| hz _ hy) #align set.nonempty.pairwise_iff_exists_forall Set.Nonempty.pairwise_iff_exists_forall /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.pairwise_eq_iff_exists_eq` for a version that assumes `[Nonempty ι]` instead of `Set.Nonempty s`. -/ theorem Nonempty.pairwise_eq_iff_exists_eq {s : Set α} (hs : s.Nonempty) {f : α → ι} : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_iff_exists_forall #align set.nonempty.pairwise_eq_iff_exists_eq Set.Nonempty.pairwise_eq_iff_exists_eq theorem pairwise_iff_exists_forall [Nonempty ι] (s : Set α) (f : α → ι) {r : ι → ι → Prop} [IsEquiv ι r] : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by rcases s.eq_empty_or_nonempty with (rfl | hne) · simp · exact hne.pairwise_iff_exists_forall #align set.pairwise_iff_exists_forall Set.pairwise_iff_exists_forall /-- A function `f : α → ι` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.Nonempty.pairwise_eq_iff_exists_eq` for a version that assumes `Set.Nonempty s` instead of `[Nonempty ι]`. -/ theorem pairwise_eq_iff_exists_eq [Nonempty ι] (s : Set α) (f : α → ι) : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_iff_exists_forall s f #align set.pairwise_eq_iff_exists_eq Set.pairwise_eq_iff_exists_eq theorem pairwise_union : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b ∧ r b a := by simp only [Set.Pairwise, mem_union, or_imp, forall_and] exact ⟨fun H => ⟨H.1.1, H.2.2, H.2.1, fun x hx y hy hne => H.1.2 y hy x hx hne.symm⟩, fun H => ⟨⟨H.1, fun x hx y hy hne => H.2.2.2 y hy x hx hne.symm⟩, H.2.2.1, H.2.1⟩⟩ #align set.pairwise_union Set.pairwise_union theorem pairwise_union_of_symmetric (hr : Symmetric r) : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b := pairwise_union.trans <| by simp only [hr.iff, and_self_iff] #align set.pairwise_union_of_symmetric Set.pairwise_union_of_symmetric theorem pairwise_insert : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_union, pairwise_singleton, true_and_iff, mem_singleton_iff, forall_eq] #align set.pairwise_insert Set.pairwise_insert theorem pairwise_insert_of_not_mem (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_insert.trans <| and_congr_right' <| forall₂_congr fun b hb => by simp [(ne_of_mem_of_not_mem hb ha).symm] #align set.pairwise_insert_of_not_mem Set.pairwise_insert_of_not_mem protected theorem Pairwise.insert (hs : s.Pairwise r) (h : ∀ b ∈ s, a ≠ b → r a b ∧ r b a) : (insert a s).Pairwise r := pairwise_insert.2 ⟨hs, h⟩ #align set.pairwise.insert Set.Pairwise.insert theorem Pairwise.insert_of_not_mem (ha : a ∉ s) (hs : s.Pairwise r) (h : ∀ b ∈ s, r a b ∧ r b a) : (insert a s).Pairwise r := (pairwise_insert_of_not_mem ha).2 ⟨hs, h⟩ #align set.pairwise.insert_of_not_mem Set.Pairwise.insert_of_not_mem theorem pairwise_insert_of_symmetric (hr : Symmetric r) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_insert, hr.iff a, and_self_iff] #align set.pairwise_insert_of_symmetric Set.pairwise_insert_of_symmetric theorem pairwise_insert_of_symmetric_of_not_mem (hr : Symmetric r) (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b := by simp only [pairwise_insert_of_not_mem ha, hr.iff a, and_self_iff] #align set.pairwise_insert_of_symmetric_of_not_mem Set.pairwise_insert_of_symmetric_of_not_mem theorem Pairwise.insert_of_symmetric (hs : s.Pairwise r) (hr : Symmetric r) (h : ∀ b ∈ s, a ≠ b → r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric hr).2 ⟨hs, h⟩ #align set.pairwise.insert_of_symmetric Set.Pairwise.insert_of_symmetric theorem Pairwise.insert_of_symmetric_of_not_mem (hs : s.Pairwise r) (hr : Symmetric r) (ha : a ∉ s) (h : ∀ b ∈ s, r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric_of_not_mem hr ha).2 ⟨hs, h⟩ #align set.pairwise.insert_of_symmetric_of_not_mem Set.Pairwise.insert_of_symmetric_of_not_mem theorem pairwise_pair : Set.Pairwise {a, b} r ↔ a ≠ b → r a b ∧ r b a := by simp [pairwise_insert] #align set.pairwise_pair Set.pairwise_pair theorem pairwise_pair_of_symmetric (hr : Symmetric r) : Set.Pairwise {a, b} r ↔ a ≠ b → r a b := by simp [pairwise_insert_of_symmetric hr] #align set.pairwise_pair_of_symmetric Set.pairwise_pair_of_symmetric theorem pairwise_univ : (univ : Set α).Pairwise r ↔ Pairwise r := by simp only [Set.Pairwise, Pairwise, mem_univ, forall_const] #align set.pairwise_univ Set.pairwise_univ @[simp] theorem pairwise_bot_iff : s.Pairwise (⊥ : α → α → Prop) ↔ (s : Set α).Subsingleton := ⟨fun h _a ha _b hb => h.eq ha hb id, fun h => h.pairwise _⟩ #align set.pairwise_bot_iff Set.pairwise_bot_iff alias pairwise_bot_iff ↔ Pairwise.subsingleton _ #align set.pairwise.subsingleton Set.Pairwise.subsingleton theorem InjOn.pairwise_image {s : Set ι} (h : s.InjOn f) : (f '' s).Pairwise r ↔ s.Pairwise (r on f) := by simp (config := { contextual := true }) [h.eq_iff, Set.Pairwise] #align set.inj_on.pairwise_image Set.InjOn.pairwise_image end Set end Pairwise theorem pairwise_subtype_iff_pairwise_set (s : Set α) (r : α → α → Prop) : (Pairwise fun (x : s) (y : s) => r x y) ↔ s.Pairwise r := by simp only [Pairwise, Set.Pairwise, SetCoe.forall, Ne.def, Subtype.ext_iff, Subtype.coe_mk] #align pairwise_subtype_iff_pairwise_set pairwise_subtype_iff_pairwise_set alias pairwise_subtype_iff_pairwise_set ↔ Pairwise.set_of_subtype Set.Pairwise.subtype #align pairwise.set_of_subtype Pairwise.set_of_subtype #align set.pairwise.subtype Set.Pairwise.subtype namespace Set section PartialOrderBot variable [PartialOrder α] [OrderBot α] {s t : Set ι} {f g : ι → α} /-- A set is `PairwiseDisjoint` under `f`, if the images of any distinct two elements under `f` are disjoint. `s.Pairwise Disjoint` is (definitionally) the same as `s.PairwiseDisjoint id`. We prefer the latter in order to allow dot notation on `Set.PairwiseDisjoint`, even though the former unfolds more nicely. -/ def PairwiseDisjoint (s : Set ι) (f : ι → α) : Prop := s.Pairwise (Disjoint on f) #align set.pairwise_disjoint Set.PairwiseDisjoint theorem PairwiseDisjoint.subset (ht : t.PairwiseDisjoint f) (h : s ⊆ t) : s.PairwiseDisjoint f := Pairwise.mono h ht #align set.pairwise_disjoint.subset Set.PairwiseDisjoint.subset theorem PairwiseDisjoint.mono_on (hs : s.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → g i ≤ f i) : s.PairwiseDisjoint g := fun _a ha _b hb hab => (hs ha hb hab).mono (h ha) (h hb) #align set.pairwise_disjoint.mono_on Set.PairwiseDisjoint.mono_on theorem PairwiseDisjoint.mono (hs : s.PairwiseDisjoint f) (h : g ≤ f) : s.PairwiseDisjoint g := hs.mono_on fun i _ => h i #align set.pairwise_disjoint.mono Set.PairwiseDisjoint.mono @[simp] theorem pairwiseDisjoint_empty : (∅ : Set ι).PairwiseDisjoint f := pairwise_empty _ #align set.pairwise_disjoint_empty Set.pairwiseDisjoint_empty @[simp] theorem pairwiseDisjoint_singleton (i : ι) (f : ι → α) : PairwiseDisjoint {i} f := pairwise_singleton i _ #align set.pairwise_disjoint_singleton Set.pairwiseDisjoint_singleton theorem pairwiseDisjoint_insert {i : ι} : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j) := pairwise_insert_of_symmetric <| symmetric_disjoint.comap f #align set.pairwise_disjoint_insert Set.pairwiseDisjoint_insert theorem pairwiseDisjoint_insert_of_not_mem {i : ι} (hi : i ∉ s) : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, Disjoint (f i) (f j) := pairwise_insert_of_symmetric_of_not_mem (symmetric_disjoint.comap f) hi #align set.pairwise_disjoint_insert_of_not_mem Set.pairwiseDisjoint_insert_of_not_mem protected theorem PairwiseDisjoint.insert (hs : s.PairwiseDisjoint f) {i : ι} (h : ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := pairwiseDisjoint_insert.2 ⟨hs, h⟩ #align set.pairwise_disjoint.insert Set.PairwiseDisjoint.insert theorem PairwiseDisjoint.insert_of_not_mem (hs : s.PairwiseDisjoint f) {i : ι} (hi : i ∉ s) (h : ∀ j ∈ s, Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := (pairwiseDisjoint_insert_of_not_mem hi).2 ⟨hs, h⟩ #align set.pairwise_disjoint.insert_of_not_mem Set.PairwiseDisjoint.insert_of_not_mem theorem PairwiseDisjoint.image_of_le (hs : s.PairwiseDisjoint f) {g : ι → ι} (hg : f ∘ g ≤ f) : (g '' s).PairwiseDisjoint f := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h exact (hs ha hb <| ne_of_apply_ne _ h).mono (hg a) (hg b) #align set.pairwise_disjoint.image_of_le Set.PairwiseDisjoint.image_of_le theorem InjOn.pairwiseDisjoint_image {g : ι' → ι} {s : Set ι'} (h : s.InjOn g) : (g '' s).PairwiseDisjoint f ↔ s.PairwiseDisjoint (f ∘ g) := h.pairwise_image #align set.inj_on.pairwise_disjoint_image Set.InjOn.pairwiseDisjoint_image theorem PairwiseDisjoint.range (g : s → ι) (hg : ∀ i : s, f (g i) ≤ f i) (ht : s.PairwiseDisjoint f) : (range g).PairwiseDisjoint f := by rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy exact ((ht x.2 y.2) fun h => hxy <| congr_arg g <| Subtype.ext h).mono (hg x) (hg y) #align set.pairwise_disjoint.range Set.PairwiseDisjoint.range theorem pairwiseDisjoint_union : (s ∪ t).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ t.PairwiseDisjoint f ∧ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j) := pairwise_union_of_symmetric <| symmetric_disjoint.comap f #align set.pairwise_disjoint_union Set.pairwiseDisjoint_union theorem PairwiseDisjoint.union (hs : s.PairwiseDisjoint f) (ht : t.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j)) : (s ∪ t).PairwiseDisjoint f := pairwiseDisjoint_union.2 ⟨hs, ht, h⟩ #align set.pairwise_disjoint.union Set.PairwiseDisjoint.union -- classical theorem PairwiseDisjoint.elim (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : ¬Disjoint (f i) (f j)) : i = j := hs.eq hi hj h #align set.pairwise_disjoint.elim Set.PairwiseDisjoint.elim end PartialOrderBot section SemilatticeInfBot variable [SemilatticeInf α] [OrderBot α] {s t : Set ι} {f g : ι → α} -- classical theorem PairwiseDisjoint.elim' (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : f i ⊓ f j ≠ ⊥) : i = j := (hs.elim hi hj) fun hij => h hij.eq_bot #align set.pairwise_disjoint.elim' Set.PairwiseDisjoint.elim' theorem PairwiseDisjoint.eq_of_le (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (hf : f i ≠ ⊥) (hij : f i ≤ f j) : i = j := (hs.elim' hi hj) fun h => hf <| (inf_of_le_left hij).symm.trans h #align set.pairwise_disjoint.eq_of_le Set.PairwiseDisjoint.eq_of_le end SemilatticeInfBot /-! ### Pairwise disjoint set of sets -/ theorem pairwiseDisjoint_range_singleton : (range (singleton : ι → Set ι)).PairwiseDisjoint id := by rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h exact disjoint_singleton.2 (ne_of_apply_ne _ h) #align set.pairwise_disjoint_range_singleton Set.pairwiseDisjoint_range_singleton theorem pairwiseDisjoint_fiber (f : ι → α) (s : Set α) : s.PairwiseDisjoint fun a => f ⁻¹' {a} := fun _a _ _b _ h => disjoint_iff_inf_le.mpr fun _i ⟨hia, hib⟩ => h <| (Eq.symm hia).trans hib #align set.pairwise_disjoint_fiber Set.pairwiseDisjoint_fiber -- classical theorem PairwiseDisjoint.elim_set {s : Set ι} {f : ι → Set α} (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj <| not_disjoint_iff.2 ⟨a, hai, haj⟩ #align set.pairwise_disjoint.elim_set Set.PairwiseDisjoint.elim_set /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_right_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ a ∈ s, Injective (f a)) : (s.PairwiseDisjoint fun a => f a '' t) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine' ⟨fun hs x hx y hy (h : f _ _ = _) => _, fun hs x hx y hy h => _⟩ · suffices x.1 = y.1 by exact Prod.ext this (hf _ hx.1 <| h.trans <| by rw [this]) refine' hs.elim hx.1 hy.1 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.2, _⟩) rw [h] exact mem_image_of_mem _ hy.2 · refine' disjoint_iff_inf_le.mpr _ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.fst <| hs (mk_mem_prod hx ha) (mk_mem_prod hy hb) hab) #align set.pairwise_disjoint_image_right_iff Set.pairwiseDisjoint_image_right_iff /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_left_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ b ∈ t, Injective fun a => f a b) : (t.PairwiseDisjoint fun b => (fun a => f a b) '' s) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine' ⟨fun ht x hx y hy (h : f _ _ = _) => _, fun ht x hx y hy h => _⟩ · suffices x.2 = y.2 by exact Prod.ext (hf _ hx.2 <| h.trans <| by rw [this]) this refine' ht.elim hx.2 hy.2 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.1, _⟩) rw [h] exact mem_image_of_mem _ hy.1 · refine' disjoint_iff_inf_le.mpr _ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.snd <| ht (mk_mem_prod ha hx) (mk_mem_prod hb hy) hab) #align set.pairwise_disjoint_image_left_iff Set.pairwiseDisjoint_image_left_iff end Set theorem pairwise_disjoint_fiber (f : ι → α) : Pairwise (Disjoint on fun a : α => f ⁻¹' {a}) := pairwise_univ.1 <| Set.pairwiseDisjoint_fiber f univ #align pairwise_disjoint_fiber pairwise_disjoint_fiber
From stdpp Require Import tactics sets. Require Import Reals Psatz Omega Fourier. From discprob.measure Require Export measurable_space. From mathcomp Require Import choice. Require ClassicalEpsilon. Export Hierarchy. Open Scope R_scope. (* Usually the Borel sigma algebra is defined for more general topological spaces, but the Coquelicot hierarchy is oriented around uniform spaces, and in any case that will be good enough *) Definition borel_sigma (A: UniformSpace) : sigma_algebra A := minimal_sigma (@open A). (* Todo: should we make it global? or only if second countable *) Instance borel (A: UniformSpace) : measurable_space A := {| measurable_space_sigma := borel_sigma A |}. Lemma continuous_inverse_open (A B: UniformSpace) (f: A → B) : (∀ x, continuous f x) → ∀ U, open U → open (fun_inv f U). Proof. rewrite /open. intros Hcont U Hopen x Hf. rewrite /continuous_on in Hcont. rewrite /fun_inv. specialize (Hcont x). edestruct Hcont as [eps ?]; first eauto. exists eps. auto. Qed. Lemma continuous_borel_measurable (A B: UniformSpace) (f: A → B) : (∀ x, continuous f x) → measurable f. Proof. intros Hcont. apply sigma_measurable_generating_sets => U Hopen. apply minimal_sigma_ub. by apply continuous_inverse_open. Qed. Lemma closed_compl {A: UniformSpace} (U: A → Prop) : open U → closed (compl U). Proof. by apply closed_not. Qed. Lemma closed_compl' {A: UniformSpace} (U: A → Prop) : open (compl U) → closed U. Proof. intros. eapply closed_ext; last eapply closed_compl; eauto. apply compl_involutive. Qed. Lemma open_compl {A: UniformSpace} (U: A → Prop) : closed U → open (compl U). Proof. by apply open_not. Qed. Lemma open_compl' {A: UniformSpace} (U: A → Prop) : closed (compl U) → open U. Proof. intros. eapply open_ext; last eapply open_compl; eauto. apply compl_involutive. Qed. Hint Resolve closed_compl open_compl closed_compl' open_compl'. Lemma borel_gen_closed (A: UniformSpace) : eq_sigma (borel A) (minimal_sigma (@closed A)). Proof. rewrite /eq_sigma/eq_prop/borel => U; split; apply minimal_sigma_lub => U' ?; rewrite -(compl_involutive U'); apply sigma_closed_complements; apply minimal_sigma_ub; auto. Qed. Lemma borel_closed (A: UniformSpace) U : closed U → (borel A) U. Proof. intros Hclosed. rewrite borel_gen_closed. by apply minimal_sigma_ub. Qed. (* Technically this would be the Borel sigma algebra on the extended reals, but we do not have the UniformSpace structure on Rbar *) Definition Rbar_sigma : sigma_algebra Rbar := minimal_sigma (λ U, ∃ x, U = (λ z, Rbar_le z x)). Instance Rbar_measurable_space : measurable_space Rbar := {| measurable_space_sigma := Rbar_sigma |}. Section borel_R. Lemma Rbar_sigma_p_infty: Rbar_sigma {[p_infty]}. Proof. assert (Hequiv: eq_prop ({[p_infty]}) (intersectF (λ n, compl (λ x, Rbar_le x (INR n : Rbar))))). { split. - inversion 1; subst. intros n. rewrite /compl//=. - intros Hall. destruct x as [r | |]. * exfalso. destruct (Rle_dec 0 r). ** destruct (archimed_pos r) as (n&Hrange); auto. rewrite S_INR in Hrange. eapply (Hall (S n)). rewrite S_INR //=. nra. ** apply (Hall O) => //=. nra. * rewrite //=. * exfalso. apply (Hall O) => //=. } rewrite Hequiv. apply sigma_closed_intersections => n. apply sigma_closed_complements. apply minimal_sigma_ub. exists (INR n). auto. Qed. Lemma Rbar_sigma_m_infty: Rbar_sigma {[m_infty]}. Proof. assert (Hequiv: eq_prop ({[m_infty]}) (intersectF (λ n, (λ x, Rbar_le x (-INR n))))). { split. - inversion 1; subst. intros n. rewrite /compl//=. - intros Hall. destruct x as [r | |]. * exfalso. destruct (Rle_dec 0 r). ** exfalso. feed pose proof (Hall (S O)) as H. rewrite //= in H. nra. ** destruct (archimed_pos (-r)) as (n'&?); first nra. feed pose proof (Hall (S n')) as H'. rewrite S_INR //= in H' H. apply Ropp_le_ge_contravar in H'. rewrite Ropp_involutive in H'. nra. * exfalso. destruct (Hall O). * done. } rewrite Hequiv. apply sigma_closed_intersections => n. apply minimal_sigma_ub. exists (-INR n). auto. Qed. Lemma borel_gen_closed_ray1 : le_prop (minimal_sigma (λ (U: R → Prop), ∃ x y, U = (λ z, x < z <= y))) (minimal_sigma (λ (U : R → Prop), ∃ x, U = (λ z, z <= x))). Proof. apply minimal_sigma_lub. intros ? (x&y&?); subst. assert ((λ z : R, x < z ∧ z <= y) ≡ (λ z : R, z <= y) ∩ compl (λ z : R, z <= x)) as Heq. { intros z; split => //=. * intros (?&?). split => //=; intros Hneg. nra. * intros (?&Hcomp). split => //=. apply Rnot_ge_lt. intros Hge. apply Hcomp. nra. } rewrite Heq. apply sigma_closed_pair_intersect. * apply minimal_sigma_ub. eexists; eauto. * apply sigma_closed_complements, minimal_sigma_ub. eexists; eauto. Qed. Lemma borel_gen_closed_ray2 : le_prop (borel (R_UniformSpace)) (minimal_sigma (λ (U : R → Prop), ∃ x, U = (λ z, z <= x))). Proof. etransitivity; last eapply borel_gen_closed_ray1. apply minimal_sigma_lub => U HopenU. unshelve (eapply sigma_proper; last eapply sigma_closed_unions). { intros n. destruct (@pickle_inv [countType of (bool * (nat * nat * nat))] n) as [(b&(x&y)&N)|]; last exact ∅. set (V := (λ z, match b with | true => (INR x / INR y) - (1/(INR N)) < z ∧ z <= (INR x / INR y) | false => - ((INR x / INR y)) - (1/(INR N)) < z ∧ z <= - (INR x / INR y) end)). destruct (ClassicalEpsilon.excluded_middle_informative (V ⊆ U)). * exact V. * exact ∅. } { split. * intros HUz. specialize (HopenU _ HUz). destruct HopenU as ((δ&Hpos)&Hdelta). destruct (Rle_dec 0 x) as [Hle|Hnle]. ** edestruct (archimed_cor1 δ) as (K&?&?); first by nra. assert (0 < / INR K). { apply Rinv_0_lt_compat, pos_INR'; done. } edestruct (archimed_rat_dense1 (/INR K) x) as (n&m&(?&?)&?); auto; try nra. exists (pickle (true, (n, m, K))). rewrite pickleK_inv => //=. destruct ClassicalEpsilon.excluded_middle_informative as [Hsub|Hnsub]; last first. { exfalso. destruct Hnsub. intros z. rewrite //=. intros [? ?]. apply Hdelta => //=. rewrite /ball//=/ball//=/AbsRing_ball//=/abs//=. rewrite /minus/opp/plus//=. assert (z >= z - x) by nra. apply Rabs_case => Hcase; try nra. } rewrite //=. nra. ** edestruct (archimed_cor1 δ) as (K&?&?); first by nra. assert (0 < / INR K). { apply Rinv_0_lt_compat, pos_INR'; done. } edestruct (archimed_rat_dense2 (/INR K) x) as (n&m&(?&?)&?); auto; try nra. exists (pickle (false, (n, m, K))). rewrite pickleK_inv => //=. destruct ClassicalEpsilon.excluded_middle_informative as [Hsub|Hnsub]; last first. { exfalso. destruct Hnsub. intros z. rewrite //=. intros [? ?]. apply Hdelta => //=. rewrite /ball//=/ball//=/AbsRing_ball//=/abs//=. rewrite /minus/opp/plus//=. assert (z >= z + x) by nra. apply Rabs_case => Hcase; try nra. } rewrite //=. nra. * intros (n&HUn). destruct pickle_inv as [(b&(n'&m')&K)|]; rewrite //= in HUn. destruct ClassicalEpsilon.excluded_middle_informative as [Hsub|Hnsub]; rewrite //= in HUn. by apply Hsub. } intros i. destruct (@pickle_inv [countType of bool * (nat * nat * nat)] i) as [(b&(n&m)&K)|] eqn:Heq; rewrite Heq; last by apply sigma_empty_set. destruct b. * set (V := λ z, INR n / INR m - 1 / INR K < z ∧ z <= INR n / INR m). destruct (Classical_Prop.classic (V ⊆ U)) as [Hsub|Hnsub]. ** apply minimal_sigma_ub. do 2 eexists. rewrite /V. destruct ClassicalEpsilon.excluded_middle_informative as [|Hnsub]; first reflexivity. exfalso; apply Hnsub. eauto. ** eapply sigma_proper; last eapply sigma_empty_set; rewrite //=. destruct ClassicalEpsilon.excluded_middle_informative as [Hsub'|]; last reflexivity. exfalso; apply Hnsub; eauto. * set (V := λ z, - (INR n / INR m) - 1 / INR K < z ∧ z <= - (INR n / INR m)). destruct (Classical_Prop.classic (V ⊆ U)) as [Hsub|Hnsub]. ** apply minimal_sigma_ub. do 2 eexists. rewrite /V. destruct ClassicalEpsilon.excluded_middle_informative as [|Hnsub]; first reflexivity. exfalso; apply Hnsub. eauto. ** eapply sigma_proper; last eapply sigma_empty_set; rewrite //=. destruct ClassicalEpsilon.excluded_middle_informative as [Hsub'|]; last reflexivity. exfalso; apply Hnsub; eauto. Qed. Lemma borel_gen_open_ray_gt: le_prop (borel (R_UniformSpace)) (minimal_sigma (λ (U : R → Prop), ∃ x, U = (λ z, x < z))). Proof. etransitivity; first apply borel_gen_closed_ray2. apply minimal_sigma_lub => U. intros (x&Heq). subst. eapply (sigma_proper _ _ (compl (λ z, x < z))). * rewrite /compl//=. split; nra. * apply sigma_closed_complements. apply minimal_sigma_ub. eexists; eauto. Qed. Lemma open_ray_borel_gt z: borel _ (λ x, z < x). Proof. apply minimal_sigma_ub. apply open_gt. Qed. Lemma open_ray_borel_lt z: borel _ (λ x, x < z). Proof. apply minimal_sigma_ub. apply open_lt. Qed. Lemma closed_ray_borel_ge z: borel _ (λ x, z <= x). Proof. apply borel_closed. apply closed_compl'. eapply open_ext; last eapply (open_lt z). intros x => //=. rewrite /compl. nra. Qed. Lemma closed_ray_borel_le z: borel _ (λ x, x <= z). Proof. apply borel_closed. apply closed_compl'. eapply open_ext; last eapply (open_gt z). intros x => //=. rewrite /compl. nra. Qed. Lemma closed_interval_borel a b: borel _ (λ x, a <= x <= b). Proof. assert ((λ x, a <= x <= b) ≡ (λ x, a <= x) ∩ (λ x, x <= b)) as ->. { split; intros; rewrite //=; nra. } eapply sigma_closed_pair_intersect; auto using closed_ray_borel_le, closed_ray_borel_ge. Qed. Lemma borel_equiv_closed_ray : eq_sigma (borel (R_UniformSpace)) (minimal_sigma (λ (U : R → Prop), ∃ x, U = (λ z, z <= x))). Proof. intros z; split. * apply borel_gen_closed_ray2. * apply minimal_sigma_lub. intros U (?&Heq). subst. apply (closed_ray_borel_le x). Qed. Lemma measurable_plus {A: Type} {F: measurable_space A} (f1 f2: A → R) : measurable f1 → measurable f2 → measurable (λ x, f1 x + f2 x). Proof. intros Hmeas1 Hmeas2. eapply sigma_measurable_mono. { rewrite /le_sigma; reflexivity. } { rewrite /le_sigma/flip. apply borel_gen_open_ray_gt. } eapply sigma_measurable_generating_sets. intros ? (t&->). rewrite /fun_inv. cut (eq_prop (λ a, t < f1 a + f2 a) (unionF (λ n, match @pickle_inv [countType of (bool * (nat * nat))] n with | None => empty_set | Some (b, (n, m)) => let r := if b then INR n / INR m else - (INR n / INR m) in (fun_inv f1 (λ x, Rlt r x)) ∩ (fun_inv f2 (λ x, Rlt (t - r) x)) end))). { intros ->. apply sigma_closed_unions => i. destruct (pickle_inv) as [(b&(n&m))|]; last apply sigma_empty_set. destruct b => //=; apply sigma_closed_pair_intersect; first [ apply Hmeas1 | apply Hmeas2 ]; apply open_ray_borel_gt. } intros a; split. - intros Hlt. destruct (Rtotal_order 0 (f1 a)) as [Hgt0|[Heq|Hlt0]]. * set (δ := Rmin ((f1 a + f2 a) - t) (f1 a / 2)). edestruct (archimed_rat_dense1 (δ/2) (f1 a - δ/2)) as (n&m&Hnm&?); rewrite /δ; auto; try nra. { apply Rmin_case_strong; intros; try nra. } { apply Rmin_case_strong; intros; try nra. } exists (pickle (true, (n, m))). rewrite pickleK_inv //=; split; rewrite /fun_inv. ** nra. ** rewrite /δ in Hnm. move: Hnm. apply Rmin_case_strong; nra. * set (δ := ((f1 a + f2 a) - t) / 2). edestruct (archimed_rat_dense2 (δ/2) (-δ/2)) as (n&m&Hnm&?); rewrite /δ; auto; try nra. exists (pickle (false, (n, m))). rewrite pickleK_inv //=; split; rewrite /fun_inv. ** nra. ** rewrite /δ in Hnm. move: Hnm. rewrite -?Heq //=. nra. * set (δ := ((f1 a + f2 a) - t) / 2). edestruct (archimed_rat_dense2 (δ/2) (f1 a - δ/2)) as (n&m&Hnm&?); rewrite /δ; auto; try nra. exists (pickle (false, (n, m))). rewrite pickleK_inv //=; split; rewrite /fun_inv. ** nra. ** rewrite /δ in Hnm. move: Hnm. rewrite -?Heq //=. nra. - intros (bnm&Hspec). destruct (pickle_inv) as [(b&(n&m))|]. * destruct b; rewrite /fun_inv//= in Hspec; destruct Hspec as [H1 H2]; nra. * destruct Hspec. Qed. Lemma measurable_scal {A: Type} {F: measurable_space A} (f: A → R) (c: R): measurable f → measurable (λ x, c * f x). Proof. intros Hmeas. destruct (Rtotal_order 0 c) as [Hgt0|[Heq|Hlt0]]. - eapply sigma_measurable_mono. { rewrite /le_sigma; reflexivity. } { rewrite /le_sigma/flip. apply borel_gen_open_ray_gt. } eapply sigma_measurable_generating_sets. intros ? (x&->). rewrite /fun_inv. eapply (sigma_proper _ _ (λ a, x /c < f a)). { intros z; split. * intros. eapply (Rmult_lt_reg_r (1/c)). move: Hgt0. clear. rewrite /Rinv. apply Rlt_mult_inv_pos; nra. field_simplify; nra. * intros. eapply (Rmult_lt_reg_r c); first nra. field_simplify; nra. } apply Hmeas, open_ray_borel_gt. - subst. intros U HU. rewrite /fun_inv. destruct (Classical_Prop.classic (U 0)). * eapply sigma_proper; last apply sigma_full. intros x; rewrite Rmult_0_l; split; auto. * eapply sigma_proper; last apply sigma_empty_set. intros x; rewrite Rmult_0_l; split; auto. inversion 1. - eapply sigma_measurable_mono. { rewrite /le_sigma; reflexivity. } { rewrite /le_sigma/flip. apply borel_gen_open_ray_gt. } eapply sigma_measurable_generating_sets. intros ? (x&->). rewrite /fun_inv. eapply (sigma_proper _ _ (λ a, x /c > f a)). { intros z; split. * intros Hineq%(Rmult_lt_gt_compat_neg_l c); last nra. field_simplify in Hineq; nra. * intros Hineq%(Rmult_lt_gt_compat_neg_l (1/c)); last first. { rewrite /Rdiv Rmult_1_l. apply Rinv_lt_0_compat. nra. } field_simplify in Hineq; nra. } apply: Hmeas. apply open_ray_borel_lt. Qed. Lemma measurable_square {A: Type} {F: measurable_space A} (f: A → R) : measurable f → measurable (λ x, f x * f x). Proof. intros Hmeas. eapply sigma_measurable_mono. { rewrite /le_sigma; reflexivity. } { rewrite /le_sigma/flip. apply borel_gen_closed_ray2. } eapply sigma_measurable_generating_sets. intros ? (t&->). rewrite /fun_inv//=. destruct (Rlt_dec t 0) as [Hlt|Hnlt]. - eapply sigma_proper; last eapply sigma_empty_set. intros x; split. * intros Hle. assert (f x * f x >= 0). { apply Rle_ge. apply Rle_0_sqr. } nra. * inversion 1. - apply Rnot_lt_ge, Rge_le in Hnlt. assert (eq_prop (λ a, f a * f a <= t) (fun_inv f (λ a, - sqrt t <= a <= sqrt t))) as ->. { rewrite /fun_inv//=. intros a; split. * intros Hsqr. apply sqrt_le_1_alt in Hsqr. rewrite sqrt_Rsqr_abs in Hsqr. move: Hsqr. apply Rabs_case; nra. * intros Hrange. replace (f a * f a) with (Rsqr (f a)) by auto. rewrite (Rsqr_abs (f a)). apply sqrt_le_0; try nra. ** apply Rle_0_sqr. ** rewrite sqrt_Rsqr; last by auto. move: Hrange. apply Rabs_case; nra. } apply Hmeas, closed_interval_borel. Qed. Lemma measurable_opp {A: Type} {F: measurable_space A} (f: A → R) : measurable f → measurable (λ x, - f x). Proof. intros. eapply measurable_comp. * eauto. * apply continuous_borel_measurable. rewrite //=. intros x. apply: continuous_opp. apply: continuous_id. Qed. Lemma measurable_minus {A: Type} {F: measurable_space A} (f1 f2: A → R) : measurable f1 → measurable f2 → measurable (λ x, f1 x - f2 x). Proof. intros Hmeas1 Hmeas2. rewrite /Rminus. apply measurable_plus; auto. eapply measurable_comp; eauto. apply measurable_opp, measurable_id. Qed. Lemma measurable_mult {A: Type} {F: measurable_space A} (f1 f2: A → R) : measurable f1 → measurable f2 → measurable (λ x, f1 x * f2 x). Proof. intros Hmeas1 Hmeas2. assert (∀ x, f1 x * f2 x = /2 * ((f1 x + f2 x) * (f1 x + f2 x)) - /2 * (f1 x * f1 x) - /2 * (f2 x * f2 x)) as Heq. { intros x. field. } setoid_rewrite Heq. repeat (apply measurable_plus || apply measurable_minus || apply measurable_scal || apply measurable_opp || apply measurable_square || auto). Qed. Ltac measurable := repeat (apply measurable_plus || apply measurable_minus || apply measurable_scal || apply measurable_opp || apply measurable_square || apply measurable_mult || apply measurable_const || auto). Lemma measurable_Rabs {A: Type} {F: measurable_space A} f1: measurable f1 → measurable (λ x, Rabs (f1 x)). Proof. intros Hmeas. eapply measurable_comp; eauto. apply continuous_borel_measurable => x. apply: continuous_abs. Qed. Lemma measurable_Rmax {A: Type} {F: measurable_space A} (f1 f2: A → R) : measurable f1 → measurable f2 → measurable (λ x, Rmax (f1 x) (f2 x)). Proof. intros. assert (Heq: ∀ x, Rmax (f1 x) (f2 x) = /2 * ((f1 x + f2 x) + Rabs (f1 x - f2 x))). { intros. apply Rmax_case_strong; apply Rabs_case; nra. } setoid_rewrite Heq. measurable. apply measurable_Rabs. apply measurable_minus; auto. Qed. Lemma measurable_Rmin {A: Type} {F: measurable_space A} (f1 f2: A → R) : measurable f1 → measurable f2 → measurable (λ x, Rmin (f1 x) (f2 x)). Proof. intros. assert (Heq: ∀ x, Rmin (f1 x) (f2 x) = /2 * ((f1 x + f2 x) - Rabs (f1 x - f2 x))). { intros. apply Rmin_case_strong; apply Rabs_case; nra. } setoid_rewrite Heq. measurable. apply measurable_Rabs. apply measurable_minus; auto. Qed. Lemma measurable_real: measurable real. Proof. eapply sigma_measurable_mono. { rewrite /le_sigma; reflexivity. } { rewrite /le_sigma/flip. apply borel_gen_closed_ray2. } eapply sigma_measurable_generating_sets. intros ? (t&->). destruct (Rlt_dec t 0). - eapply (sigma_proper _ _ ((λ x, Rbar_le x t) ∩ compl ({[m_infty]}))). * intros x; split. ** intros (Hle&Hm); destruct x => //=. exfalso. apply Hm. done. ** destruct x; rewrite /fun_inv//=; nra. * apply sigma_closed_pair_intersect. ** eapply minimal_sigma_ub. exists t => //=. ** apply sigma_closed_complements, Rbar_sigma_m_infty. - eapply (sigma_proper _ _ ((λ x, Rbar_le x t) ∪ ({[m_infty]} ∪ {[p_infty]}))). * intros x; split. ** intros [Hle|[Hm|Hp]]; destruct x => //=; rewrite /fun_inv/real; nra. ** rewrite /fun_inv/real//=. destruct x => //=; try firstorder. * apply sigma_closed_pair_union. ** eapply minimal_sigma_ub. exists t => //=. ** apply sigma_closed_pair_union. *** apply Rbar_sigma_m_infty. *** apply Rbar_sigma_p_infty. Qed. Lemma measurable_Finite: measurable Finite. Proof. intros. eapply sigma_measurable_generating_sets. intros ? (t&->). destruct t as [r | | ]. - assert (eq_prop (fun_inv Finite ((λ x, Rbar_le x r))) (λ x, Rle x r)) as ->. { intros x. split => //=. } apply closed_ray_borel_le. - eapply sigma_proper; last eapply sigma_full. split; auto. - eapply sigma_proper; last eapply sigma_empty_set. split; auto. Qed. Lemma Rbar_sigma_real_pt r: Rbar_sigma {[Finite r]}. Proof. assert (eq_prop {[Finite r]} (fun_inv real {[r]} ∩ compl {[p_infty]} ∩ compl {[m_infty]})) as ->. { split. * inversion 1; subst. rewrite /compl/fun_inv//=. * rewrite /compl/fun_inv//=. intros ((Heq&?)&?); destruct x; try firstorder. ** inversion Heq as [Heq']. rewrite //= in Heq'. subst. done. } apply sigma_closed_pair_intersect; first apply sigma_closed_pair_intersect. * apply measurable_real. apply borel_closed. apply closed_eq. * apply sigma_closed_complements, Rbar_sigma_p_infty. * apply sigma_closed_complements, Rbar_sigma_m_infty. Qed. Lemma Rbar_sigma_pt r: Rbar_sigma {[r]}. Proof. destruct r; auto using Rbar_sigma_real_pt, Rbar_sigma_p_infty, Rbar_sigma_m_infty. Qed. Lemma Rbar_sigma_gen_ge_ray: le_prop (minimal_sigma (λ U, ∃ x, U = (λ z, Rbar_le x z))) Rbar_sigma. Proof. apply minimal_sigma_lub. intros ? (x&->). assert (eq_prop (λ z, Rbar_le x z) (compl (λ z, Rbar_le z x) ∪ {[x]})) as Heq. { intros z; split. * intros [Hlt|Heq]%Rbar_le_lt_or_eq_dec. ** left. by apply Rbar_lt_not_le. ** right; subst; done. * intros [Hnle|Heq]. ** apply Rbar_not_le_lt in Hnle. by apply Rbar_lt_le. ** inversion Heq; subst; apply Rbar_le_refl. } rewrite Heq. apply sigma_closed_pair_union. - apply sigma_closed_complements. apply minimal_sigma_ub; eexists. reflexivity. - apply Rbar_sigma_pt. Qed. Lemma measurable_Rbar_opp {A: Type} {F: measurable_space A} (f: A → Rbar) : measurable f → measurable (λ x, Rbar_opp (f x)). Proof. intros Hmeas. apply sigma_measurable_generating_sets. intros ? (t&->). assert (fun_inv (λ x, Rbar_opp (f x)) (λ x, Rbar_le x t) ≡ fun_inv f (Rbar_le (Rbar_opp t))) as ->. { rewrite /fun_inv//= => x. rewrite -{1}(Rbar_opp_involutive t). apply Rbar_opp_le. } apply Hmeas. apply Rbar_sigma_gen_ge_ray. apply minimal_sigma_ub. eauto. Qed. Lemma Sup_seq_minor_Rbar_le (u : nat → Rbar) (M : Rbar) (n : nat): Rbar_le M (u n) → Rbar_le M (Sup_seq u). Proof. intros Hle. rewrite Rbar_sup_eq_lub. rewrite /Lub.Rbar_lub. destruct (Lub.Rbar_ex_lub) as (?&r). rewrite /=. eapply Rbar_le_trans; eauto. apply r. eauto. Qed. Lemma measurable_Sup {A: Type} {F: measurable_space A} (fn : nat → A → Rbar): (∀ n, measurable (fn n)) → measurable (λ x, Sup_seq (λ n, fn n x)). Proof. intros Hmeas. eapply sigma_measurable_generating_sets. intros ? (t&->). assert (eq_prop (λ x, Rbar_le (Sup_seq (λ n, fn n x)) t) (intersectF (λ n, fun_inv (fn n) (λ x, Rbar_le x t)))) as ->. { split. - intros Hsup n. rewrite /fun_inv. eapply Rbar_le_trans; eauto. eapply Sup_seq_minor_Rbar_le; eauto. apply Rbar_le_refl. - intros Hle. rewrite Rbar_sup_eq_lub. rewrite /Lub.Rbar_lub. destruct (Lub.Rbar_ex_lub) as (?&(Hub&Hlub)). apply Hlub => //=. intros r (?&->); eapply Hle. } apply sigma_closed_intersections. intros. apply Hmeas. apply minimal_sigma_ub. eauto. Qed. Lemma measurable_Inf {A: Type} {F: measurable_space A} (fn : nat → A → Rbar): (∀ n, measurable (fn n)) → measurable (λ x, Inf_seq (λ n, fn n x)). Proof. intros. setoid_rewrite Inf_opp_sup. apply measurable_Rbar_opp. apply measurable_Sup. intros n. apply measurable_Rbar_opp. done. Qed. Lemma measurable_LimSup {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, LimSup_seq (λ n, fn n x)). Proof. intros Hmeas. setoid_rewrite LimSup_InfSup_seq. apply measurable_Inf => n. apply measurable_Sup => m. eapply measurable_comp; last apply measurable_Finite. eauto. Qed. Lemma measurable_LimInf {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, LimInf_seq (λ n, fn n x)). Proof. intros Hmeas. setoid_rewrite LimInf_SupInf_seq. apply measurable_Sup => m. apply measurable_Inf => n. eapply measurable_comp; last apply measurable_Finite. eauto. Qed. Lemma measurable_Sup_seq {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, Sup_seq (λ n, fn n x) : R). Proof. intros Hmeas. eapply measurable_comp. apply measurable_Sup. { intros n. eapply measurable_comp; last apply measurable_Finite. eauto. } apply measurable_real. Qed. Lemma measurable_Inf_seq {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, Inf_seq (λ n, fn n x) : R). Proof. intros Hmeas. eapply measurable_comp. apply measurable_Inf. { intros n. eapply measurable_comp; last apply measurable_Finite. eauto. } apply measurable_real. Qed. Lemma measurable_Rbar_div_pos y: measurable (λ x, Rbar_div_pos x y). Proof. apply sigma_measurable_generating_sets. intros ? (t&->). destruct t as [r | | ]. - assert (fun_inv (λ x, Rbar_div_pos x y) (λ x, Rbar_le x r) ≡ λ x, Rbar_le x (r * y)) as ->. { rewrite /fun_inv//=; intros [ r' | |] => //=; apply Rle_div_l; destruct y; done. } apply minimal_sigma_ub; eauto. - eapply sigma_proper; last apply sigma_full. intros [ | |] => //=. - eapply sigma_proper; last apply Rbar_sigma_m_infty. intros [ | |] => //=. Qed. Lemma measurable_Rbar_plus {A: Type} {F: measurable_space A} (f1 f2: A → Rbar) : measurable f1 → measurable f2 → measurable (λ x, Rbar_plus (f1 x) (f2 x)). Proof. intros Hmeas1 Hmeas2. apply sigma_measurable_generating_sets. intros ? (t&->). destruct t as [r | | ]. - destruct (Rle_dec 0 r) as [Hle0|Hnle0]. { assert (fun_inv (λ x, Rbar_plus (f1 x) (f2 x)) (λ x, Rbar_le x r) ≡ (fun_inv (λ x, Rplus (f1 x) (f2 x)) (λ x, Rle x r) ∩ compl (fun_inv f1 ({[p_infty]} ∪ {[m_infty]})) ∩ compl (fun_inv f2 ({[p_infty]} ∪ {[m_infty]}))) ∪ fun_inv f1 {[m_infty]} ∪ fun_inv f2 {[m_infty]}) as ->. { intros a; split; rewrite /fun_inv. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. destruct (f1 a), (f2 a); rewrite //=; try (left; right; firstorder; done); try (right; firstorder; done). intros Hle. do 2 left. split_and!; auto; intros [Hin|Hin]; inversion Hin. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. intros [[((Hplus&Hnot1)&Hnot2)|Hinf1]|Hinf2]. * destruct (f1 a), (f2 a) => //=; try nra; try (exfalso; apply Hnot1; firstorder; done); try (exfalso; apply Hnot2; firstorder; done). * inversion Hinf1 as [Heq]. rewrite Heq => //=. destruct (f2 a) => //=. * inversion Hinf2 as [Heq]. rewrite Heq => //=. destruct (f1 a) => //=. } apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty. apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty. repeat apply sigma_closed_pair_intersect. * apply measurable_plus; try eapply measurable_comp; eauto using measurable_real. apply closed_ray_borel_le. * apply sigma_closed_complements; eapply Hmeas1. apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty, Rbar_sigma_p_infty. * apply sigma_closed_complements; eapply Hmeas2. apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty, Rbar_sigma_p_infty. } { assert (fun_inv (λ x, Rbar_plus (f1 x) (f2 x)) (λ x, Rbar_le x r) ≡ (fun_inv (λ x, Rplus (f1 x) (f2 x)) (λ x, Rle x r) ∩ compl (fun_inv f1 ({[p_infty]} ∪ {[m_infty]})) ∩ compl (fun_inv f2 ({[p_infty]} ∪ {[m_infty]}))) ∪ (compl (fun_inv f2 {[p_infty]}) ∩ fun_inv f1 {[m_infty]}) ∪ (compl (fun_inv f1 {[p_infty]}) ∩ fun_inv f2 {[m_infty]})) as ->. { intros a; split; rewrite /fun_inv. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. destruct (f1 a), (f2 a); rewrite //=; try (left; right; firstorder; done); try (right; firstorder; done). intros Hle. do 2 left. split_and!; auto; intros [Hin|Hin]; inversion Hin. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. intros [[((Hplus&Hnot1)&Hnot2)|(Hn1&Hinf1)]|(Hn2&Hinf2)]. * destruct (f1 a), (f2 a) => //=; try nra; try (exfalso; apply Hnot1; firstorder; done); try (exfalso; apply Hnot2; firstorder; done). * inversion Hinf1 as [Heq]. rewrite Heq => //=. destruct (f2 a) => //=. firstorder. * inversion Hinf2 as [Heq]. rewrite Heq => //=. destruct (f1 a) => //=. firstorder. } apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty; first apply sigma_closed_pair_union; eauto using Rbar_sigma_m_infty; first repeat apply sigma_closed_pair_intersect. * apply measurable_plus; try eapply measurable_comp; eauto using measurable_comp, measurable_real. apply closed_ray_borel_le. * apply sigma_closed_complements; eapply Hmeas1. apply sigma_closed_pair_union; eauto using Rbar_sigma_pt. * apply sigma_closed_complements; eapply Hmeas2. apply sigma_closed_pair_union; eauto using Rbar_sigma_pt. * apply sigma_closed_pair_intersect. ** apply sigma_closed_complements. apply Hmeas2; eauto using Rbar_sigma_pt. ** apply Hmeas1; eauto using Rbar_sigma_pt. * apply sigma_closed_pair_intersect. ** apply sigma_closed_complements. apply Hmeas1; eauto using Rbar_sigma_pt. ** apply Hmeas2; eauto using Rbar_sigma_pt. } - eapply sigma_proper; last eapply sigma_full. intros x; split; auto. rewrite /fun_inv//=. by destruct (Rbar_plus). - assert (fun_inv (λ x, Rbar_plus (f1 x) (f2 x)) (λ x, Rbar_le x m_infty) ≡ (fun_inv f1 (compl {[p_infty]}) ∩ fun_inv f2 {[m_infty]}) ∪ (fun_inv f2 (compl {[p_infty]}) ∩ fun_inv f1 {[m_infty]})) as ->. { intros a; split; rewrite /fun_inv. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. destruct (f1 a), (f2 a); firstorder set_unfold; done. - rewrite /base.union/union_Union/union/intersection/intersect_Intersection/intersect/compl. destruct (f1 a), (f2 a); firstorder set_unfold; done. } apply sigma_closed_pair_union; apply sigma_closed_pair_intersect. * eapply Hmeas1. apply sigma_closed_complements; eauto using Rbar_sigma_pt. * eapply Hmeas2. eauto using Rbar_sigma_pt. * eapply Hmeas2. apply sigma_closed_complements; eauto using Rbar_sigma_pt. * eapply Hmeas1. eauto using Rbar_sigma_pt. Qed. Lemma measurable_Lim {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, Lim_seq (λ n, fn n x)). Proof. intros Hmeas. rewrite /Lim_seq//=. eapply (measurable_comp _ (λ x, Rbar_div_pos x {| pos := 2 ; cond_pos := Rlt_R0_R2|})); eauto using measurable_Rbar_div_pos. apply measurable_Rbar_plus. * apply measurable_LimSup. done. * apply measurable_LimInf. done. Qed. Lemma measurable_Lim' {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, real (Lim_seq (λ n, fn n x))). Proof. intros. eapply measurable_comp; eauto using measurable_real. apply measurable_Lim. done. Qed. Lemma measurable_sum_n {A: Type} {F: measurable_space A} (fn : nat → A → R) m: (∀ n, measurable (fn n)) → measurable (λ x : A, sum_n (λ n : nat, fn n x) m). Proof. intros Hmeas. induction m => //=. - setoid_rewrite sum_O. eauto. - setoid_rewrite sum_Sn. apply measurable_plus; eauto. Qed. Lemma measurable_Series {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → measurable (λ x, Series (λ n, fn n x)). Proof. intros. apply measurable_Lim'; eauto. intros; eapply measurable_sum_n; eauto. Qed. Lemma measurable_fun_eq_0 {A: Type} {F: measurable_space A} f: measurable f → is_measurable (λ x, f x = 0). Proof. intros Hmeas. eapply (Hmeas (λ x, x = 0)). apply borel_closed, closed_eq. Qed. Lemma measurable_fun_eq_0_Rbar {A: Type} {F: measurable_space A} (f: A → Rbar): measurable f → is_measurable (λ x, f x = 0). Proof. intros Hmeas. eapply (Hmeas (λ x, x = 0)). apply Rbar_sigma_pt. Qed. Lemma measurable_fun_ge {A: Type} {F: measurable_space A} f k: measurable f → is_measurable (λ x, k <= f x). Proof. intros Hmeas. eapply (Hmeas (λ x, k <= x)). apply closed_ray_borel_ge. Qed. Lemma measurable_fun_le_const {A: Type} {F: measurable_space A} f k: measurable f → is_measurable (λ x, f x <= k). Proof. intros Hmeas. eapply (Hmeas (λ x, x <= k)). apply closed_ray_borel_le. Qed. Lemma measurable_fun_lt_p_infty {A: Type} {F: measurable_space A} f: measurable f → is_measurable (λ x, Rbar_lt (f x) p_infty). Proof. intros Hmeas. rewrite /is_measurable. assert ((λ x, Rbar_lt (f x) p_infty) ≡ compl (fun_inv f {[p_infty]})) as ->. { intros x. rewrite /fun_inv/compl//=. split. - intros Hlt Heq. inversion Heq as [Heq']. rewrite Heq' in Hlt. rewrite //= in Hlt. - intros Heq. destruct (f x) => //=. apply Heq. done. } apply sigma_closed_complements. eapply Hmeas. apply Rbar_sigma_pt. Qed. Lemma measurable_fun_eq_inv {A: Type} {F: measurable_space A} (f g: A → R): measurable f → measurable g → is_measurable (λ x, f x = g x). Proof. intros Hmeas1 Hmeas2. apply (sigma_proper _ _ (λ x, f x - g x = 0)). { intros x; split; nra. } apply measurable_fun_eq_0. measurable. Qed. Lemma measurable_fun_le_inv {A: Type} {F: measurable_space A} f g: measurable f → measurable g → is_measurable (λ x, f x <= g x). Proof. intros Hmeas1 Hmeas2. apply (sigma_proper _ _ (λ x, f x - g x <= 0)). { intros x; split; nra. } apply measurable_fun_le_const. measurable. Qed. Lemma measurable_fun_eq_inv_Rbar {A: Type} {F: measurable_space A} (f g: A → Rbar): measurable f → measurable g → is_measurable (λ x, f x = g x). Proof. intros Hmeas1 Hmeas2. apply (sigma_proper _ _ (λ x, Rbar_minus (f x) (g x) = 0)). { intros x; split. - destruct (f x), (g x) => //=. inversion 1; subst; f_equal; nra. - destruct (f x), (g x) => //=. intros Heq. inversion Heq; subst. f_equal. nra. } apply measurable_fun_eq_0_Rbar. rewrite /Rbar_minus. apply measurable_Rbar_plus, measurable_Rbar_opp; auto. Qed. Lemma measure_ex_lim_seq {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → is_measurable (λ x, ex_lim_seq (λ n, fn n x)). Proof. intros Hmeas. eapply sigma_proper. { intros x. apply ex_lim_LimSup_LimInf_seq. } apply measurable_fun_eq_inv_Rbar; auto using measurable_LimSup, measurable_LimInf. Qed. Lemma measure_ex_finite_lim_seq {A: Type} {F: measurable_space A} (fn : nat → A → R): (∀ n, measurable (fn n)) → is_measurable (λ x, ex_finite_lim_seq (λ n, fn n x)). Proof. intros Hmeas. eapply (sigma_proper _ _ ((λ x, ex_lim_seq (λ n, fn n x)) ∩ (fun_inv (λ x, Lim_seq (λ n, fn n x)) (compl {[p_infty]})) ∩ (fun_inv (λ x, Lim_seq (λ n, fn n x)) (compl {[m_infty]})))). { intros x. rewrite /fun_inv. split. - intros ((Hex&Hlim1)&Hlim2). destruct Hex as (v&His). destruct v as [r | |]. * exists r; eauto. * rewrite (is_lim_seq_unique _ _ His) //= in Hlim1. exfalso; apply Hlim1; done. * rewrite (is_lim_seq_unique _ _ His) //= in Hlim2. exfalso; apply Hlim2; done. - intros (v&His). split; first split. * eexists; eauto. * rewrite //= (is_lim_seq_unique _ _ His) //=. * rewrite //= (is_lim_seq_unique _ _ His) //=. } apply sigma_closed_pair_intersect; first apply sigma_closed_pair_intersect. - apply measure_ex_lim_seq; auto. - apply measurable_Lim; eauto. apply sigma_closed_complements, Rbar_sigma_pt. - apply measurable_Lim; eauto. apply sigma_closed_complements, Rbar_sigma_pt. Qed. Lemma measure_is_lim_seq {A: Type} {F: measurable_space A} (fn : nat → A → R) (f: A → Rbar): (∀ n, measurable (fn n)) → measurable f → is_measurable (λ x, is_lim_seq (λ n, fn n x) (f x)). Proof. intros. assert (Hequiv: (λ x, is_lim_seq (λ n, fn n x) (f x)) ≡ (λ x, ex_lim_seq (λ n, fn n x)) ∩ (λ x, Lim_seq (λ n, fn n x) = f x)). { intros x. split. - intros His; split; first by (eexists; eauto). by apply is_lim_seq_unique. - intros (Hex&Heq). rewrite -Heq. apply Lim_seq_correct; eauto. } rewrite /is_measurable. rewrite Hequiv. apply sigma_closed_pair_intersect. - apply measure_ex_lim_seq; eauto. - apply measurable_fun_eq_inv_Rbar; eauto using measurable_Lim. Qed. End borel_R. Ltac measurable := repeat (apply measurable_plus || apply measurable_minus || apply measurable_scal || apply measurable_opp || apply measurable_square || apply measurable_mult || apply measurable_const || apply measurable_real || apply measurable_Rabs || apply measurable_Rmax || apply measurable_Rmin || apply measure_is_lim_seq || apply measure_ex_lim_seq || apply measure_ex_finite_lim_seq || apply measurable_fun_le_inv || apply measurable_fun_eq_inv || auto).
------------------------------------------------------------------------------ -- Testing a type synonymous for Set ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOT.FOTC.Data.Nat.SetType where open import FOTC.Base open import FOTC.Data.Nat -- Type synonymous for Set. Type = Set data N' : D → Type where nzero' : N' zero nsucc' : ∀ {n} → N' n → N' (succ₁ n) {-# ATP axioms nzero' nsucc' #-} pred-N' : ∀ {n} → N' n → N' (pred₁ n) pred-N' nzero' = prf where postulate prf : N' (pred₁ zero) {-# ATP prove prf #-} pred-N' (nsucc' {n} N'n) = prf where postulate prf : N' (pred₁ (succ₁ n)) {-# ATP prove prf #-}
clear all; close all; I=imread('cameraman.tif'); I=im2double(I); J=fftshift(fft2(I)); [x, y]=meshgrid(-128:127, -128:127); [M, N]=size(I); n1=floor(M/2); n2=floor(N/2); z=sqrt((x-n1).^2+(y-n2).^2); D1=10; D2=30; n=6; H1=1./(1+(z/D1).^(2*n)); H2=1./(1+(z/D2).^(2*n)); K1=J.*H1; K2=J.*H2; L1=ifft2(ifftshift(K1)); L2=ifft2(ifftshift(K2)); figure; subplot(131); imshow(I); subplot(132); imshow(real(L1)); subplot(133); imshow(real(L2))
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details # ========================================================================== # RowDirectSum # ========================================================================== Class(RowDirectSum, BaseOverlap, rec( #----------------------------------------------------------------------- abbrevs := [ function(arg) arg:=Flat(arg); return [arg[1], arg{[2..Length(arg)]}]; end ], #----------------------------------------------------------------------- new := meth(self, overlap, spls) return self._new(0, overlap, spls); end, #----------------------------------------------------------------------- _dims := meth(self) local ovdim; ovdim := self.ovDim(self.overlap, List(self._children, t -> t.dimensions[2])); return [ Sum(self._children, t -> t.dimensions[1]), ovdim[3] - ovdim[2] + 1 # max - min + 1 ]; end, dims := self >> When(IsBound(self._setDims), self._setDims, let(d := Try(self._dims()), When(d[1], d[2], [errExp(TInt), errExp(TInt)]))), #----------------------------------------------------------------------- toAMat := meth(self) return DirectSumAMat(List(self._children, AMatSPL)) * AMatSPL( Sparse( self._rowoverlap( List(self._children, t -> t.dimensions[2]), self.overlap ) ) ); end, #----------------------------------------------------------------------- arithmeticCost := meth(self, costMul, costAddMul) return Sum(List(self.children(), x -> x.arithmeticCost(costMul, costAddMul))); end ));
```python from sympy import * ``` ```python x = Symbol('x') ``` ```python init_printing(use_unicode=True) ``` ```python expr = exp(-x) * cos(x) expr ``` ```python integrate(expr, x) ``` ```python Integral(expr, x) ``` ```python simplify(gamma(x)*gamma(1-x)) ``` ```python ```
Formal statement is: lemma continuous_on_setdist [continuous_intros]: "continuous_on T (\<lambda>y. (setdist {y} S))" Informal statement is: The function $y \mapsto \text{dist}(\{y\}, S)$ is continuous on $T$.
State Before: l : Type ?u.86247 m : Type u n : Type u' α : Type v inst✝² : Fintype n inst✝¹ : DecidableEq n inst✝ : CommRing α A B : Matrix n n α ⊢ IsUnit A ↔ IsUnit (det A) State After: no goals Tactic: simp only [← nonempty_invertible_iff_isUnit, (invertibleEquivDetInvertible A).nonempty_congr]
module PatternMatchingLambda where data Bool : Set where true false : Bool data Void : Set where data _≡_ {A : Set}(x : A) : A -> Set where refl : x ≡ x and : Bool -> Bool -> Bool and = λ { true x → x ; false _ → false } or : Bool -> Bool -> Bool or x y = not (and (not x) (not y)) where not : Bool -> Bool not = \ { true -> false ; false -> true } iff : Bool -> Bool -> Bool -> Bool iff = λ { true x -> λ { true → true ; false → false } ; false x -> λ { true -> false ; false -> true } } pattern-matching-lambdas-compute : (x : Bool) -> or true x ≡ true pattern-matching-lambdas-compute x = refl isTrue : Bool -> Set isTrue = \ { true -> Bool ; false -> Void } absurd : (x : Bool) -> isTrue x -> Bool absurd = \ { true x -> x ; false () } --carefully chosen without eta, so that pattern matching is needed data Unit : Set where unit : Unit isNotUnit : Unit -> Set isNotUnit = \ { tt -> Void } absurd-one-clause : (x : Unit) -> isNotUnit x -> Bool absurd-one-clause = λ { tt ()} data indexed-by-xor : (Bool -> Bool -> Bool) -> Set where c : (b : Bool) -> indexed-by-xor \ { true true -> false ; false false -> false ; _ _ -> true } -- won't work if the underscore is replaced with the actual value at the moment f : (r : Bool -> Bool -> Bool) -> indexed-by-xor r -> Bool f ._ (c b) = b record Σ (A : Set)(B : A -> Set) : Set where constructor _,_ field proj₁ : A proj₂ : B proj₁ fst : {A : Set}{B : A -> Set} -> (x : Σ A B) -> A fst = \ { (a , b) -> a } snd : {A : Set}{B : A -> Set} -> (x : Σ A B) -> B (fst x) snd = \ { (a , b) -> b } record FamSet : Set1 where constructor _,_ field A : Set B : A -> Set ΣFAM : (A : Set)(B : A -> Set)(P : A -> Set)(Q : (x : A) -> B x -> P x -> Set) -> FamSet ΣFAM A B P Q = (Σ A P , \ { (a , p) -> Σ (B a) (λ b → Q a b p) } ) --The syntax doesn't interfere with hidden lambdas etc: postulate P : ({x : Bool} -> Bool) -> Set p : P (λ {x} → x) --Issue 446: Absurd clauses can appear inside more complex expressions data Box (A : Set) : Set where box : A → Box A foo : {A : Set} → Box Void → A foo = λ { (box ()) }
lemma coeff_1 [simp]: "coeff 1 n = of_bool (n = 0)"
[STATEMENT] lemma rreq_rrep_fresh [simp]: "\<And>hops rreqid dip dsn dsk oip osn sip. rreq_rrep_fresh crt (Rreq hops rreqid dip dsn dsk oip osn sip) = (sip \<noteq> oip \<longrightarrow> oip\<in>kD(crt) \<and> (sqn crt oip > osn \<or> (sqn crt oip = osn \<and> the (dhops crt oip) \<le> hops \<and> the (flag crt oip) = val)))" "\<And>hops dip dsn oip sip. rreq_rrep_fresh crt (Rrep hops dip dsn oip sip) = (sip \<noteq> dip \<longrightarrow> dip\<in>kD(crt) \<and> sqn crt dip = dsn \<and> the (dhops crt dip) = hops \<and> the (flag crt dip) = val)" "\<And>dests sip. rreq_rrep_fresh crt (Rerr dests sip) = True" "\<And>d dip. rreq_rrep_fresh crt (Newpkt d dip) = True" "\<And>d dip sip. rreq_rrep_fresh crt (Pkt d dip sip) = True" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<And>hops rreqid dip dsn dsk oip osn sip. rreq_rrep_fresh crt (Rreq hops rreqid dip dsn dsk oip osn sip) = (sip \<noteq> oip \<longrightarrow> oip \<in> kD crt \<and> (osn < sqn crt oip \<or> sqn crt oip = osn \<and> the (dhops crt oip) \<le> hops \<and> the (flag crt oip) = val))) &&& (\<And>hops dip dsn oip sip. rreq_rrep_fresh crt (Rrep hops dip dsn oip sip) = (sip \<noteq> dip \<longrightarrow> dip \<in> kD crt \<and> sqn crt dip = dsn \<and> the (dhops crt dip) = hops \<and> the (flag crt dip) = val))) &&& (\<And>dests sip. rreq_rrep_fresh crt (Rerr dests sip) = True) &&& (\<And>d dip. rreq_rrep_fresh crt (Newpkt d dip) = True) &&& (\<And>d dip sip. rreq_rrep_fresh crt (Pkt d dip sip) = True) [PROOF STEP] unfolding rreq_rrep_fresh_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((\<And>hops rreqid dip dsn dsk oip osn sip. (case Rreq hops rreqid dip dsn dsk oip osn sip of Rreq hopsc x xa xb xc oipc osnc ipcc \<Rightarrow> ipcc \<noteq> oipc \<longrightarrow> oipc \<in> kD crt \<and> (osnc < sqn crt oipc \<or> sqn crt oipc = osnc \<and> the (dhops crt oipc) \<le> hopsc \<and> the (flag crt oipc) = val) | Rrep hopsc dipc dsnc x ipcc \<Rightarrow> ipcc \<noteq> dipc \<longrightarrow> dipc \<in> kD crt \<and> sqn crt dipc = dsnc \<and> the (dhops crt dipc) = hopsc \<and> the (flag crt dipc) = val | _ \<Rightarrow> True) = (sip \<noteq> oip \<longrightarrow> oip \<in> kD crt \<and> (osn < sqn crt oip \<or> sqn crt oip = osn \<and> the (dhops crt oip) \<le> hops \<and> the (flag crt oip) = val))) &&& (\<And>hops dip dsn oip sip. (case Rrep hops dip dsn oip sip of Rreq hopsc x xa xb xc oipc osnc ipcc \<Rightarrow> ipcc \<noteq> oipc \<longrightarrow> oipc \<in> kD crt \<and> (osnc < sqn crt oipc \<or> sqn crt oipc = osnc \<and> the (dhops crt oipc) \<le> hopsc \<and> the (flag crt oipc) = val) | Rrep hopsc dipc dsnc x ipcc \<Rightarrow> ipcc \<noteq> dipc \<longrightarrow> dipc \<in> kD crt \<and> sqn crt dipc = dsnc \<and> the (dhops crt dipc) = hopsc \<and> the (flag crt dipc) = val | _ \<Rightarrow> True) = (sip \<noteq> dip \<longrightarrow> dip \<in> kD crt \<and> sqn crt dip = dsn \<and> the (dhops crt dip) = hops \<and> the (flag crt dip) = val))) &&& (\<And>dests sip. (case Rerr dests sip of Rreq hopsc x xa xb xc oipc osnc ipcc \<Rightarrow> ipcc \<noteq> oipc \<longrightarrow> oipc \<in> kD crt \<and> (osnc < sqn crt oipc \<or> sqn crt oipc = osnc \<and> the (dhops crt oipc) \<le> hopsc \<and> the (flag crt oipc) = val) | Rrep hopsc dipc dsnc x ipcc \<Rightarrow> ipcc \<noteq> dipc \<longrightarrow> dipc \<in> kD crt \<and> sqn crt dipc = dsnc \<and> the (dhops crt dipc) = hopsc \<and> the (flag crt dipc) = val | _ \<Rightarrow> True) = True) &&& (\<And>d dip. (case Newpkt d dip of Rreq hopsc x xa xb xc oipc osnc ipcc \<Rightarrow> ipcc \<noteq> oipc \<longrightarrow> oipc \<in> kD crt \<and> (osnc < sqn crt oipc \<or> sqn crt oipc = osnc \<and> the (dhops crt oipc) \<le> hopsc \<and> the (flag crt oipc) = val) | Rrep hopsc dipc dsnc x ipcc \<Rightarrow> ipcc \<noteq> dipc \<longrightarrow> dipc \<in> kD crt \<and> sqn crt dipc = dsnc \<and> the (dhops crt dipc) = hopsc \<and> the (flag crt dipc) = val | _ \<Rightarrow> True) = True) &&& (\<And>d dip sip. (case Pkt d dip sip of Rreq hopsc x xa xb xc oipc osnc ipcc \<Rightarrow> ipcc \<noteq> oipc \<longrightarrow> oipc \<in> kD crt \<and> (osnc < sqn crt oipc \<or> sqn crt oipc = osnc \<and> the (dhops crt oipc) \<le> hopsc \<and> the (flag crt oipc) = val) | Rrep hopsc dipc dsnc x ipcc \<Rightarrow> ipcc \<noteq> dipc \<longrightarrow> dipc \<in> kD crt \<and> sqn crt dipc = dsnc \<and> the (dhops crt dipc) = hopsc \<and> the (flag crt dipc) = val | _ \<Rightarrow> True) = True) [PROOF STEP] by simp_all
(*<*) (* * Knowledge-based programs. * (C)opyright 2011, Peter Gammie, peteg42 at gmail.com. * License: BSD *) theory SPRViewDet imports SPRView KBPsAlg Eval List_local ODList Trie2 "Transitive-Closure.Transitive_Closure_List_Impl" "HOL-Library.Mapping" begin (*>*) subsection\<open>Perfect Recall in Deterministic Broadcast Environments\<close> text\<open> \label{sec:kbps-theory-spr-deterministic-protocols} It is well known that simultaneous broadcast has the effect of making information \emph{common knowledge}; roughly put, the agents all learn the same things at the same time as the system evolves, so the relation amongst the agents' states of knowledge never becomes more complex than it is in the initial state \citep[Chapter~6]{FHMV:1995}. For this reason we might hope to find finite-state implementations of JKBPs in broadcast environments. The broadcast assumption by itself is insufficient in general, however \citep[\S7]{Ron:1996}, and so we need to further constrain the scenario. Here we require that for each canonical trace the JKBP prescribes at most one action. In practice this constraint is easier to verify than the circularity would suggest; we return to this point at the end of this section. \<close> text_raw\<open> \begin{figure}[tb] \begin{isabellebody}% \<close> record (overloaded) ('a, 'es, 'ps) BEState = es :: "'es" ps :: "('a \<times> 'ps) odlist" locale FiniteDetBroadcastEnvironment = Environment jkbp envInit envAction envTrans envVal envObs for jkbp :: "'a \<Rightarrow> ('a :: {finite,linorder}, 'p, 'aAct) KBP" and envInit :: "('a, 'es :: {finite,linorder}, 'as :: {finite,linorder}) BEState list" and envAction :: "('a, 'es, 'as) BEState \<Rightarrow> 'eAct list" and envTrans :: "'eAct \<Rightarrow> ('a \<Rightarrow> 'aAct) \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> ('a, 'es, 'as) BEState" and envVal :: "('a, 'es, 'as) BEState \<Rightarrow> 'p \<Rightarrow> bool" and envObs :: "'a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> ('cobs \<times> 'as option)" + fixes agents :: "'a odlist" fixes envObsC :: "'es \<Rightarrow> 'cobs" defines "envObs a s \<equiv> (envObsC (es s), ODList.lookup (ps s) a)" assumes agents: "ODList.toSet agents = UNIV" assumes envTrans: "\<forall>s s' a eact eact' aact aact'. ODList.lookup (ps s) a = ODList.lookup (ps s') a \<and> aact a = aact' a \<longrightarrow> ODList.lookup (ps (envTrans eact aact s)) a = ODList.lookup (ps (envTrans eact' aact' s')) a" assumes jkbpDet: "\<forall>a. \<forall>t \<in> SPR.jkbpC. length (jAction SPR.MC t a) \<le> 1" text_raw\<open> \end{isabellebody}% \caption{Finite broadcast environments with a deterministic JKBP.} \label{fig:kbps-theory-det-broadcast-envs} \end{figure} \<close>(*<*) instantiation BEState_ext :: (linorder, linorder, linorder, linorder) linorder begin definition less_eq_BEState_ext where "x \<le> y \<equiv> es x < es y \<or> (es x = es y \<and> (ps x < ps y \<or> (ps x = ps y \<and> more x \<le> more y)))" definition less_BEState_ext where "x < y \<equiv> es x < es y \<or> (es x = es y \<and> (ps x < ps y \<or> (ps x = ps y \<and> more x < more y)))" instance apply intro_classes apply (unfold less_eq_BEState_ext_def less_BEState_ext_def) apply auto done end instance BEState_ext :: ("{finite, linorder}", finite, "{finite, linorder}", finite) finite proof let ?U = "UNIV :: ('a, 'b, 'c, 'd) BEState_ext set" { fix x :: "('a, 'b, 'c, 'd) BEState_scheme" have "\<exists>a b c. x = BEState_ext a b c" by (cases x) simp } then have U: "?U = (\<lambda>((a, b), c). BEState_ext a b c) ` ((UNIV \<times> UNIV) \<times> UNIV)" by (auto simp add: Set.image_def) show "finite ?U" by (simp add: U) qed (*>*) text\<open> We encode our expectations of the scenario in the @{term "FiniteBroadcastEnvironment"} locale of Figure~\ref{fig:kbps-theory-det-broadcast-envs}. The broadcast is modelled by having all agents make the same common observation of the shared state of type @{typ "'es"}. We also allow each agent to maintain a private state of type @{typ "'ps"}; that other agents cannot influence it or directly observe it is enforced by the constraint \<open>envTrans\<close> and the definition of @{term "envObs"}. We do however allow the environment's protocol to be non-deterministic and a function of the entire system state, including private states. \<close> context FiniteDetBroadcastEnvironment begin (*<*) (* ouch *) lemma envObs_def_raw: "envObs a = (\<lambda>s. (envObsC (es s), ODList.lookup (ps s) a))" apply (rule ext)+ apply (simp add: envObs_def) done (*>*) text\<open> We seek a suitable simulation space by considering what determines an agent's knowledge. Intuitively any set of traces that is relevant to the agents' states of knowledge with respect to @{term "t \<in> jkbpC"} need include only those with the same common observation as @{term "t"}: \<close> definition tObsC :: "('a, 'es, 'as) BEState Trace \<Rightarrow> 'cobs Trace" where "tObsC \<equiv> tMap (envObsC \<circ> es)" text\<open> Clearly this is an abstraction of the SPR jview of the given trace. \<close> lemma spr_jview_tObsC: assumes "spr_jview a t = spr_jview a t'" shows "tObsC t = tObsC t'" (*<*) using SPR.sync[rule_format, OF assms] assms by (induct rule: trace_induct2) (auto simp: envObs_def tObsC_def) lemma tObsC_tLength: "tObsC t = tObsC t' \<Longrightarrow> tLength t = tLength t'" unfolding tObsC_def by (rule tMap_eq_imp_tLength_eq) lemma tObsC_tStep_eq_inv: "tObsC t' = tObsC (t \<leadsto> s) \<Longrightarrow> \<exists>t'' s'. t' = t'' \<leadsto> s'" unfolding tObsC_def by auto lemma tObsC_prefix_closed[dest]: "tObsC (t \<leadsto> s) = tObsC (t' \<leadsto> s') \<Longrightarrow> tObsC t = tObsC t'" unfolding tObsC_def by simp lemma tObsC_tLast[iff]: "tLast (tObsC t) = envObsC (es (tLast t))" unfolding tObsC_def by simp lemma tObsC_initial[iff]: "tFirst (tObsC t) = envObsC (es (tFirst t))" "tObsC (tInit s) = tInit (envObsC (es s))" "tObsC t = tInit cobs \<longleftrightarrow> (\<exists>s. t = tInit s \<and> envObsC (es s) = cobs)" unfolding tObsC_def by simp_all lemma spr_tObsC_trc_aux: assumes "(t, t') \<in> (\<Union>a. relations SPR.MC a)\<^sup>*" shows "tObsC t = tObsC t'" using assms apply (induct) apply simp apply clarsimp apply (rule_tac a=x in spr_jview_tObsC) apply simp done lemma spr_jview_tObsC_trans: "\<lbrakk>spr_jview a t = spr_jview a t'; spr_jview a' t' = spr_jview a' t''\<rbrakk> \<Longrightarrow> tObsC t = tObsC t''" by (fastforce dest: spr_jview_tObsC) (*>*) text\<open> Unlike the single-agent case of \S\ref{sec:kbps-spr-single-agent}, it is not sufficient for a simulation to record only the final states; we need to relate the initial private states of the agents with the final states they consider possible, as the initial states may contain information that is not common knowledge. This motivates the following abstraction: \<close> definition tObsC_abs :: "('a, 'es, 'as) BEState Trace \<Rightarrow> ('a, 'es, 'as) BEState Relation" where "tObsC_abs t \<equiv> { (tFirst t', tLast t') |t'. t' \<in> SPR.jkbpC \<and> tObsC t' = tObsC t}" (*<*) lemma tObsC_abs_jview_eq[dest]: "spr_jview a t' = spr_jview a t \<Longrightarrow> tObsC_abs t = tObsC_abs t'" unfolding tObsC_abs_def by (fastforce dest: spr_jview_tObsC) lemma tObsC_abs_tObsC_eq[dest]: "tObsC t' = tObsC t \<Longrightarrow> tObsC_abs t = tObsC_abs t'" unfolding tObsC_abs_def by (fastforce dest: spr_jview_tObsC) lemma spr_jview_tObsCI: assumes tt': "tObsC t = tObsC t'" and first: "envObs a (tFirst t) = envObs a (tFirst t')" and "tMap (\<lambda>s. ODList.lookup (ps s) a) t = tMap (\<lambda>s. ODList.lookup (ps s) a) t'" shows "spr_jview a t = spr_jview a t'" using tObsC_tLength[OF tt'] assms by (induct rule: trace_induct2, auto iff: tObsC_def envObs_def spr_jview_def) lemma tObsC_absI[intro]: "\<lbrakk> t' \<in> SPR.jkbpC; tObsC t' = tObsC t; u = tFirst t'; v = tLast t' \<rbrakk> \<Longrightarrow> (u, v) \<in> tObsC_abs t" unfolding tObsC_abs_def by blast lemma tObsC_abs_conv: "(u, v) \<in> tObsC_abs t \<longleftrightarrow> (\<exists>t'. t' \<in> SPR.jkbpC \<and> tObsC t' = tObsC t \<and> u = tFirst t' \<and> v = tLast t')" unfolding tObsC_abs_def by blast lemma tObsC_abs_tLast[simp]: "(u, v) \<in> tObsC_abs t \<Longrightarrow> envObsC (es v) = envObsC (es (tLast t))" unfolding tObsC_abs_def tObsC_def by (auto iff: o_def elim: tMap_tLast_inv) lemma tObsC_abs_tInit[iff]: "tObsC_abs (tInit s) = { (s', s') |s'. s' \<in> set envInit \<and> envObsC (es s') = envObsC (es s) }" unfolding tObsC_abs_def apply auto apply (rule_tac x="tInit s'" in exI) apply simp done (*>*) text\<open>\<close> end (* context FiniteDetBroadcastEnvironment *) text\<open> We use the following record to represent the worlds of the simulated Kripke structure: \<close> record (overloaded) ('a, 'es, 'as) spr_simWorld = sprFst :: "('a, 'es, 'as) BEState" sprLst :: "('a, 'es, 'as) BEState" sprCRel :: "('a, 'es, 'as) BEState Relation" (*<*) instance spr_simWorld_ext :: ("{finite, linorder}", finite, "{finite, linorder}", finite) finite proof let ?U = "UNIV :: ('a, 'b, 'c, 'd) spr_simWorld_ext set" { fix x :: "('a, 'b, 'c, 'd) spr_simWorld_scheme" have "\<exists>a b c d. x = spr_simWorld_ext a b c d" by (cases x) simp } then have U: "?U = (\<lambda>(a, (b, (c, d))). spr_simWorld_ext a b c d) ` (UNIV \<times> (UNIV \<times> (UNIV \<times> UNIV)))" by (auto simp add: Set.image_def) show "finite ?U" by (simp add: U) qed (*>*) context FiniteDetBroadcastEnvironment begin text\<open> The simulation of a trace @{term "t \<in> jkbpC"} records its initial and final states, and the relation between initial and final states of all commonly-plausible traces: \<close> definition spr_sim :: "('a, 'es, 'as) BEState Trace \<Rightarrow> ('a, 'es, 'as) spr_simWorld" where "spr_sim \<equiv> \<lambda>t. \<lparr> sprFst = tFirst t, sprLst = tLast t, sprCRel = tObsC_abs t \<rparr>" text\<open> The associated Kripke structure relates two worlds for an agent if the agent's observation on the the first and last states corresponds, and the worlds have the same common observation relation. As always, we evaluate propositions on the final state of the trace. \<close> definition spr_simRels :: "'a \<Rightarrow> ('a, 'es, 'as) spr_simWorld Relation" where "spr_simRels \<equiv> \<lambda>a. { (s, s') |s s'. envObs a (sprFst s) = envObs a (sprFst s') \<and> envObs a (sprLst s) = envObs a (sprLst s') \<and> sprCRel s = sprCRel s' }" definition spr_simVal :: "('a, 'es, 'as) spr_simWorld \<Rightarrow> 'p \<Rightarrow> bool" where "spr_simVal \<equiv> envVal \<circ> sprLst" abbreviation "spr_simMC \<equiv> mkKripke (spr_sim ` SPR.jkbpC) spr_simRels spr_simVal" (*<*) lemma spr_sim_tFirst_tLast: "\<lbrakk> spr_sim t = s; t \<in> SPR.jkbpC \<rbrakk> \<Longrightarrow> (sprFst s, sprLst s) \<in> sprCRel s" unfolding spr_sim_def by auto lemma spr_sim_tObsC_abs: shows "tObsC_abs t = sprCRel (spr_sim t)" unfolding tObsC_abs_def spr_sim_def by simp lemma spr_simVal_eq[iff]: "spr_simVal (spr_sim t) = envVal (tLast t)" unfolding spr_sim_def spr_simVal_def by simp lemma spr_sim_range: "sim_range SPR.MC spr_simMC spr_sim" by (rule sim_rangeI) (simp_all add: spr_sim_def) lemma spr_simVal: "sim_val SPR.MC spr_simMC spr_sim" by (rule sim_valI) simp lemma spr_sim_f: "sim_f SPR.MC spr_simMC spr_sim" unfolding spr_simRels_def spr_sim_def mkKripke_def SPR.mkM_def by (rule sim_fI, auto) lemma envDetJKBP': assumes tCn: "t \<in> SPR.jkbpCn n" and aact: "act \<in> set (jAction (SPR.MCn n) t a)" shows "jAction (SPR.MCn n) t a = [act]" using jkbpDet[rule_format, where t=t and a=a] assms apply - apply (cases "jAction SPR.MC t a") apply (auto iff: SPR.jkbpC_jkbpCn_jAction_eq[OF tCn] dest: SPR.jkbpCn_jkbpC_inc) done (*>*) text\<open> All the properties of a simulation are easy to show for @{term "spr_sim"} except for reverse simulation. The critical lemma states that if we have two traces that yield the same common observations, and an agent makes the same observation on their initial states, then that agent's private states at each point on the two traces are identical. \<close> lemma spr_jview_det_ps: assumes tt'C: "{t, t'} \<subseteq> SPR.jkbpC" assumes obsCtt': "tObsC t = tObsC t'" assumes first: "envObs a (tFirst t) = envObs a (tFirst t')" shows "tMap (\<lambda>s. ODList.lookup (ps s) a) t = tMap (\<lambda>s. ODList.lookup (ps s) a) t'" (*<*) using tObsC_tLength[OF obsCtt'] first tt'C obsCtt' proof(induct rule: trace_induct2) case (tInit s s') thus ?case by (simp add: envObs_def) next case (tStep s s' t t') from tStep have ts: "t \<leadsto> s \<in> SPR.jkbpCn (tLength (t \<leadsto> s))" and t's': "t' \<leadsto> s' \<in> SPR.jkbpCn (tLength (t' \<leadsto> s'))" by blast+ from tStep have jvtt': "spr_jview a t = spr_jview a t'" by - (rule spr_jview_tObsCI, auto) with tStep have jatt': "jAction (SPR.MCn (tLength t)) t a = jAction (SPR.MCn (tLength t')) t' a" apply - apply simp apply (rule S5n_jAction_eq) apply blast unfolding SPR.mkM_def apply auto done from jvtt' have tt'Last: "ODList.lookup (ps (tLast t)) a = ODList.lookup (ps (tLast t')) a" by (auto simp: envObs_def) from ts obtain eact aact where aact: "\<forall>a. aact a \<in> set (jAction (SPR.MCn (tLength t)) t a)" and s: "s = envTrans eact aact (tLast t)" by (auto iff: Let_def) from t's' obtain eact' aact' where aact': "\<forall>a. aact' a \<in> set (jAction (SPR.MCn (tLength t')) t' a)" and s': "s' = envTrans eact' aact' (tLast t')" by (auto iff: Let_def) from tStep have tCn: "t \<in> SPR.jkbpCn (tLength t)" by auto from aact obtain act where act: "jAction (SPR.MCn (tLength t)) t a = [act]" using envDetJKBP'[OF tCn, where a=a and act="aact a"] by auto hence "jAction (SPR.MCn (tLength t')) t' a = [act]" by (simp only: jatt') with act aact aact' have "aact a = aact' a" by (auto elim!: allE[where x=a]) with agents tt'Last s s' have "ODList.lookup (ps s) a = ODList.lookup (ps s') a" by (simp add: envTrans) moreover from tStep have "tMap (\<lambda>s. ODList.lookup (ps s) a) t = tMap (\<lambda>s. ODList.lookup (ps s) a) t'" by auto moreover from tStep have "envObsC (es s) = envObsC (es s')" unfolding tObsC_def by simp ultimately show ?case by simp qed lemma spr_sim_r: "sim_r SPR.MC spr_simMC spr_sim" proof(rule sim_rI) fix a p q' assume pT: "p \<in> worlds SPR.MC" and fpq': "(spr_sim p, q') \<in> relations spr_simMC a" from fpq' obtain uq fq vq where q': "q' = \<lparr> sprFst = uq, sprLst = vq, sprCRel = tObsC_abs p \<rparr>" and uq: "envObs a (tFirst p) = envObs a uq" and vq: "envObs a (tLast p) = envObs a vq" unfolding mkKripke_def spr_sim_def spr_simRels_def by fastforce from fpq' have "q' \<in> worlds spr_simMC" by simp with q' have "(uq, vq) \<in> tObsC_abs p" using spr_sim_tFirst_tLast[where s=q'] apply auto done then obtain t where tT: "t \<in> SPR.jkbpC" and tp: "tObsC t = tObsC p" and tuq: "tFirst t = uq" and tvq: "tLast t = vq" by (auto iff: tObsC_abs_conv) from pT tT tp tuq uq have "tMap (\<lambda>s. ODList.lookup (ps s) a) p = tMap (\<lambda>s. ODList.lookup (ps s) a) t" by (auto intro: spr_jview_det_ps) with tp tuq uq have "spr_jview a p = spr_jview a t" by (auto intro: spr_jview_tObsCI) with pT tT have pt: "(p, t) \<in> relations SPR.MC a" unfolding SPR.mkM_def by simp from q' uq vq tp tuq tvq have ftq': "spr_sim t = q'" unfolding spr_sim_def by auto from pt ftq' show "\<exists>q. (p, q) \<in> relations SPR.MC a \<and> spr_sim q = q'" by blast qed (*>*) text\<open> The proof proceeds by lock-step induction over @{term "t"} and @{term "t'"}, appealing to the @{term "jkbpDet"} assumption, the definition of @{term "envObs"} and the constraint @{term "envTrans"}. It is then a short step to showing reverse simulation, and hence simulation: \<close> lemma spr_sim: "sim SPR.MC spr_simMC spr_sim" (*<*) using spr_sim_range spr_simVal spr_sim_f spr_sim_r unfolding sim_def by blast (*>*) end (* context FiniteDetBroadcastEnvironment *) sublocale FiniteDetBroadcastEnvironment < SPRdet: SimIncrEnvironment jkbp envInit envAction envTrans envVal spr_jview envObs spr_jviewInit spr_jviewIncr spr_sim spr_simRels spr_simVal (*<*) by standard (rule spr_sim) (*>*) (* **************************************** *) subsubsection\<open>Representations\<close> text\<open> As before we canonically represent the quotient of the simulated worlds @{typ "('a, 'es, 'as) spr_simWorld"} under @{term "spr_simRels"} using ordered, distinct lists. In particular, we use the type @{typ "('a \<times> 'a) odlist"} (abbreviated @{typ "'a odrelation"}) to canonically represent relations. \<close> context FiniteDetBroadcastEnvironment begin type_synonym (in -) ('a, 'es, 'as) spr_simWorldsECRep = "('a, 'es, 'as) BEState odrelation" type_synonym (in -) ('a, 'es, 'as) spr_simWorldsRep = "('a, 'es, 'as) spr_simWorldsECRep \<times> ('a, 'es, 'as) spr_simWorldsECRep" text\<open> We can abstract such a representation into a set of simulated equivalence classes: \<close> definition spr_simAbs :: "('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> ('a, 'es, 'as) spr_simWorld set" where "spr_simAbs \<equiv> \<lambda>(cec, aec). { \<lparr> sprFst = s, sprLst = s', sprCRel = toSet cec \<rparr> |s s'. (s, s') \<in> toSet aec }" text\<open> Assuming @{term "X"} represents a simulated equivalence class for @{term "t \<in> jkbpC"}, we can decompose @{term "spr_simAbs X"} in terms of @{term "tObsC_abs t"} and @{term "agent_abs t"}: \<close> definition agent_abs :: "'a \<Rightarrow> ('a, 'es, 'as) BEState Trace \<Rightarrow> ('a, 'es, 'as) BEState Relation" where "agent_abs a t \<equiv> { (tFirst t', tLast t') |t'. t' \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t }" (*<*) lemma agent_absI[intro]: "\<lbrakk> spr_jview a t' = spr_jview a t; t' \<in> SPR.jkbpC; t \<in> SPR.jkbpC \<rbrakk> \<Longrightarrow> (tFirst t', tLast t') \<in> agent_abs a t" unfolding agent_abs_def by auto lemma spr_simAbs_refl: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "spr_sim t \<in> spr_simAbs ec" using assms by simp lemma spr_simAbs_tObsC_abs[simp]: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "toSet (fst ec) = tObsC_abs t" using tC spr_simAbs_refl[OF tC ec] unfolding spr_sim_def spr_simAbs_def by auto lemma spr_simAbs_agent_abs[simp]: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "toSet (snd ec) = agent_abs a t" using tC ec unfolding spr_sim_def spr_simAbs_def agent_abs_def apply (cases ec) apply auto apply (subgoal_tac "\<lparr>sprFst = aaa, sprLst = ba, sprCRel = toSet aa\<rparr> \<in> {\<lparr>sprFst = s, sprLst = s', sprCRel = toSet aa\<rparr> |s s'. (s, s') \<in> toSet b}") apply auto done (*>*) text\<open> This representation is canonical on the domain of interest (though not in general): \<close> lemma spr_simAbs_inj_on: "inj_on spr_simAbs { x . spr_simAbs x \<in> SPRdet.jkbpSEC }" (*<*) proof(rule inj_onI) fix x y assume x: "x \<in> { x . spr_simAbs x \<in> SPRdet.jkbpSEC }" and y: "y \<in> { x . spr_simAbs x \<in> SPRdet.jkbpSEC }" and xy: "spr_simAbs x = spr_simAbs y" from x obtain a t where tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs x = SPRdet.sim_equiv_class a t" by auto from spr_simAbs_tObsC_abs[OF tC ec] spr_simAbs_tObsC_abs[OF tC trans[OF xy[symmetric] ec], symmetric] have "fst x = fst y" by (blast intro: injD[OF toSet_inj]) moreover from spr_simAbs_agent_abs[OF tC ec] spr_simAbs_agent_abs[OF tC trans[OF xy[symmetric] ec], symmetric] have "snd x = snd y" by (blast intro: injD[OF toSet_inj]) ultimately show "x = y" by (simp add: prod_eqI) qed (*>*) text\<open> The following sections make use of a Kripke structure constructed over @{term "tObsC_abs t"} for some canonical trace @{term "t"}. Note that we use the relation in the generated code. \<close> type_synonym (in -) ('a, 'es, 'as) spr_simWorlds = "('a, 'es, 'as) BEState \<times> ('a, 'es, 'as) BEState" definition (in -) spr_repRels :: "('a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> 'a \<Rightarrow> ('a, 'es, 'as) spr_simWorlds Relation" where "spr_repRels envObs \<equiv> \<lambda>a. { ((u, v), (u', v')). envObs a u = envObs a u' \<and> envObs a v = envObs a v' }" definition spr_repVal :: "('a, 'es, 'as) spr_simWorlds \<Rightarrow> 'p \<Rightarrow> bool" where "spr_repVal \<equiv> envVal \<circ> snd" abbreviation spr_repMC :: "('a, 'es, 'as) BEState Relation \<Rightarrow> ('a, 'p, ('a, 'es, 'as) spr_simWorlds) KripkeStructure" where "spr_repMC \<equiv> \<lambda>tcobsR. mkKripke tcobsR (spr_repRels envObs) spr_repVal" (*<*) abbreviation spr_repRels :: "'a \<Rightarrow> ('a, 'es, 'as) spr_simWorlds Relation" where "spr_repRels \<equiv> SPRViewDet.spr_repRels envObs" lemma spr_repMC_kripke[intro, simp]: "kripke (spr_repMC X)" by (rule kripkeI) simp lemma spr_repMC_S5n[intro, simp]: "S5n (spr_repMC X)" unfolding spr_repRels_def by (intro S5nI equivI refl_onI symI transI) auto (*>*) text\<open> As before we can show that this Kripke structure is adequate for a particular canonical trace @{term "t"} by showing that it simulates @{term "spr_repMC"} We introduce an intermediate structure: \<close> abbreviation spr_jkbpCSt :: "('a, 'es, 'as) BEState Trace \<Rightarrow> ('a, 'es, 'as) spr_simWorld set" where "spr_jkbpCSt t \<equiv> spr_sim ` { t' . t' \<in> SPR.jkbpC \<and> tObsC t = tObsC t' }" abbreviation spr_simMCt :: "('a, 'es, 'as) BEState Trace \<Rightarrow> ('a, 'p, ('a, 'es, 'as) spr_simWorld) KripkeStructure" where "spr_simMCt t \<equiv> mkKripke (spr_jkbpCSt t) spr_simRels spr_simVal" definition spr_repSim :: "('a, 'es, 'as) spr_simWorld \<Rightarrow> ('a, 'es, 'as) spr_simWorlds" where "spr_repSim \<equiv> \<lambda>s. (sprFst s, sprLst s)" (*<*) lemma spr_repSim_simps[simp]: "spr_repSim ` spr_sim ` T = (\<lambda>t. (tFirst t, tLast t)) ` T" "spr_repSim (spr_sim t) = (tFirst t, tLast t)" unfolding spr_repSim_def spr_sim_def apply auto apply (rule_tac x="\<lparr> sprFst = tFirst t, sprLst = tLast t, sprCRel = tObsC_abs t \<rparr>" in image_eqI) apply auto done lemma jkbpCSt_jkbpCS_subset: "spr_jkbpCSt t \<subseteq> spr_sim ` SPR.jkbpC" by auto (*>*) text\<open>\<close> lemma spr_repSim: assumes tC: "t \<in> SPR.jkbpC" shows "sim (spr_simMCt t) ((spr_repMC \<circ> sprCRel) (spr_sim t)) spr_repSim" (*<*) (is "sim ?M ?M' ?f") proof show "sim_range ?M ?M' ?f" proof show "worlds ?M' = ?f ` worlds ?M" apply (simp add: spr_sim_def spr_repSim_def) apply (auto iff: tObsC_abs_def) apply (rule_tac x="\<lparr> sprFst = tFirst t', sprLst = tLast t', sprCRel = tObsC_abs t \<rparr>" in image_eqI) apply simp apply (rule_tac x=t' in image_eqI) apply (simp add: tObsC_abs_def) apply auto[1] done next fix a show "relations ?M' a \<subseteq> worlds ?M' \<times> worlds ?M'" by (simp add: spr_sim_def spr_repSim_def) qed next show "sim_val ?M ?M' ?f" by rule (simp add: spr_sim_def spr_simVal_def spr_repSim_def spr_repVal_def split: prod.split) next show "sim_f ?M ?M' ?f" by rule (auto iff: spr_sim_def simp: spr_simRels_def spr_repRels_def spr_repSim_def) next show "sim_r ?M ?M' ?f" apply rule unfolding spr_repRels_def spr_repSim_def spr_simRels_def spr_sim_def apply clarsimp apply (rule_tac x="\<lparr> sprFst = aa, sprLst = b, sprCRel = tObsC_abs ta \<rparr>" in exI) apply (auto iff: tObsC_abs_def) apply (rule_tac x=t'a in image_eqI) apply auto done qed (*>*) text\<open> As before we define a set of constants that satisfy the \<open>Algorithm\<close> locale given the assumptions of the @{term "FiniteDetBroadcastEnvironment"} locale. \<close> (* **************************************** *) subsubsection\<open>Initial states\<close> text\<open> The initial states for agent @{term "a"} given an initial observation @{term "iobs"} consist of the set of states that yield a common observation consonant with @{term "iobs"} paired with the set of states where @{term "a"} observes @{term "iobs"}: \<close> definition (in -) spr_simInit :: "('a, 'es, 'as) BEState list \<Rightarrow> ('es \<Rightarrow> 'cobs) \<Rightarrow> ('a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'obs) \<Rightarrow> 'a \<Rightarrow> ('cobs \<times> 'obs) \<Rightarrow> ('a :: linorder, 'es :: linorder, 'as :: linorder) spr_simWorldsRep" where "spr_simInit envInit envObsC envObs \<equiv> \<lambda>a iobs. (ODList.fromList [ (s, s). s \<leftarrow> envInit, envObsC (es s) = fst iobs ], ODList.fromList [ (s, s). s \<leftarrow> envInit, envObs a s = iobs ])" (*<*) abbreviation spr_simInit :: "'a \<Rightarrow> ('cobs \<times> 'as option) \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep" where "spr_simInit \<equiv> SPRViewDet.spr_simInit envInit envObsC envObs" (*>*) text\<open>\<close> lemma spr_simInit: assumes "iobs \<in> envObs a ` set envInit" shows "spr_simAbs (spr_simInit a iobs) = spr_sim ` { t' \<in> SPR.jkbpC. spr_jview a t' = spr_jviewInit a iobs }" (*<*) using assms unfolding spr_simInit_def spr_simAbs_def spr_sim_def [abs_def] apply (clarsimp simp: Let_def SPR.jviewInit split: prod.split) apply rule apply clarsimp apply (rule_tac x="tInit s" in image_eqI) apply (auto iff: spr_jview_def envObs_def) done (*>*) (* **************************************** *) subsubsection\<open>Simulated observations\<close> text\<open> An observation can be made at any element of the representation of a simulated equivalence class of a canonical trace: \<close> definition (in -) spr_simObs :: "('es \<Rightarrow> 'cobs) \<Rightarrow> 'a \<Rightarrow> ('a :: linorder, 'es :: linorder, 'as :: linorder) spr_simWorldsRep \<Rightarrow> 'cobs \<times> 'as option" where "spr_simObs envObsC \<equiv> \<lambda>a. (\<lambda>s. (envObsC (es s), ODList.lookup (ps s) a)) \<circ> snd \<circ> ODList.hd \<circ> snd" (*<*) abbreviation spr_simObs :: "'a \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> 'cobs \<times> 'as option" where "spr_simObs \<equiv> SPRViewDet.spr_simObs envObsC" (*>*) text\<open>\<close> lemma spr_simObs: assumes tC: "t \<in> SPR.jkbpC" assumes ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "spr_simObs a ec = envObs a (tLast t)" (*<*) proof - have A: "\<forall>s \<in> set (toList (snd ec)). envObs a (snd s) = envObs a (tLast t)" using spr_simAbs_agent_abs[OF tC ec] apply (clarsimp simp: toSet_def) apply (auto simp: agent_abs_def) done from tC ec have B: "(tFirst t, tLast t) \<in> set (toList (snd ec))" by (auto iff: spr_simAbs_def spr_sim_def toSet_def split_def) show ?thesis unfolding spr_simObs_def using list_choose_hd[OF A B] by (simp add: ODList.hd_def envObs_def) qed (*>*) (* **************************************** *) subsubsection\<open>Evaluation\<close> text\<open> As for the clock semantics (\S\ref{sec:kbps-theory-clock-view-eval}), we use the general evalation function @{term "evalS"}. Once again we propositions are used to filter the set of possible worlds @{term "X"}: \<close> abbreviation (in -) spr_evalProp :: "(('a::linorder, 'es::linorder, 'as::linorder) BEState \<Rightarrow> 'p \<Rightarrow> bool) \<Rightarrow> ('a, 'es, 'as) BEState odrelation \<Rightarrow> 'p \<Rightarrow> ('a, 'es, 'as) BEState odrelation" where "spr_evalProp envVal \<equiv> \<lambda>X p. ODList.filter (\<lambda>s. envVal (snd s) p) X" text\<open> The knowledge operation computes the subset of possible worlds @{term "cec"} that yield the same observation as @{term "s"} for agent @{term "a"}: \<close> definition (in -) spr_knowledge :: "('a \<Rightarrow> ('a::linorder, 'es::linorder, 'as::linorder) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> ('a, 'es, 'as) BEState odrelation \<Rightarrow> 'a \<Rightarrow> ('a, 'es, 'as) spr_simWorlds \<Rightarrow> ('a, 'es, 'as) spr_simWorldsECRep" where "spr_knowledge envObs cec \<equiv> \<lambda>a s. ODList.fromList [ s' . s' \<leftarrow> toList cec, (s, s') \<in> spr_repRels envObs a ]" (*<*) (* We need to avoid the explicit enumeration of the set in spr_repRels. *) declare (in -) spr_knowledge_def[code del] lemma (in -) [code]: "spr_knowledge envObs cec = (\<lambda>a s. ODList.fromList [ s' . s' \<leftarrow> toList cec, envObs a (fst s) = envObs a (fst s') \<and> envObs a (snd s) = envObs a (snd s') ])" unfolding spr_knowledge_def spr_repRels_def by (simp add: split_def) (*>*) text\<open> Similarly the common knowledge operation computes the transitive closure \citep{AFP:TRANCL} of the union of the knowledge relations for the agents \<open>as\<close>: \<close> definition (in -) spr_commonKnowledge :: "('a \<Rightarrow> ('a::linorder, 'es::linorder, 'as::linorder) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> ('a, 'es, 'as) BEState odrelation \<Rightarrow> 'a list \<Rightarrow> ('a, 'es, 'as) spr_simWorlds \<Rightarrow> ('a, 'es, 'as) spr_simWorldsECRep" where "spr_commonKnowledge envObs cec \<equiv> \<lambda>as s. let r = \<lambda>a. ODList.fromList [ (s', s'') . s' \<leftarrow> toList cec, s'' \<leftarrow> toList cec, (s', s'') \<in> spr_repRels envObs a ]; R = toList (ODList.big_union r as) in ODList.fromList (memo_list_trancl R s)" (*<*) (* We need to avoid the explicit enumeration of the set in spr_repRels. *) declare (in -) spr_commonKnowledge_def[code del] lemma (in -) [code]: "spr_commonKnowledge envObs cec = (\<lambda>as s. let r = \<lambda>a. ODList.fromList [ (s', s'') . s' \<leftarrow> toList cec, s'' \<leftarrow> toList cec, envObs a (fst s') = envObs a (fst s'') \<and> envObs a (snd s') = envObs a (snd s'') ]; R = toList (ODList.big_union r as) in ODList.fromList (memo_list_trancl R s))" unfolding spr_commonKnowledge_def spr_repRels_def by (simp add: split_def) (*>*) text\<open> The evaluation function evaluates a subjective knowledge formula on the representation of an equivalence class: \<close> definition (in -) "eval envVal envObs \<equiv> \<lambda>(cec, X). evalS (spr_evalProp envVal) (spr_knowledge envObs cec) (spr_commonKnowledge envObs cec) X" (*<*) lemma spr_knowledge: "s \<in> toSet cec \<Longrightarrow> toSet (spr_knowledge envObs cec a s) = relations (spr_repMC (toSet cec)) a `` {s}" unfolding spr_knowledge_def spr_repRels_def by (auto simp: toSet_def[symmetric]) lemma spr_commonKnowledge_relation_image: "s \<in> toSet cec \<Longrightarrow> toSet (spr_commonKnowledge envObs cec as s) = (\<Union>a \<in> set as. relations (spr_repMC (toSet cec)) a)\<^sup>+ `` {s}" unfolding spr_commonKnowledge_def Let_def apply (simp add: memo_list_trancl toSet_def[symmetric] Image_def split_def) apply (rule Collect_cong) apply (rule_tac f="\<lambda>x. (s, b) \<in> x" in arg_cong) apply (rule arg_cong[where f=trancl]) apply fastforce done lemma eval_rec_models: assumes XY: "toSet X \<subseteq> toSet Y" and s: "s \<in> toSet X" shows "s \<in> toSet (eval_rec (spr_evalProp envVal) (spr_knowledge envObs Y) (spr_commonKnowledge envObs Y) X \<phi>) \<longleftrightarrow> spr_repMC (toSet Y), s \<Turnstile> \<phi>" using XY s proof(induct \<phi> arbitrary: X s) case (Kknows a' \<phi> X s) from \<open>s \<in> toSet X\<close> spr_knowledge[OF subsetD[OF Kknows(2) Kknows(3)], where a=a'] show ?case apply simp apply rule apply (drule arg_cong[where f="toSet"]) apply (clarsimp simp: odlist_all_iff) apply (cut_tac s1="(a, b)" and X1="spr_knowledge envObs Y a' (aa, ba)" in Kknows.hyps) using Kknows(2) Kknows(3) apply (auto simp add: S5n_rels_closed[OF spr_repMC_S5n])[3] apply (clarsimp simp: toSet_eq_iff odlist_all_iff) apply (subst Kknows.hyps) using Kknows(2) Kknows(3) apply (auto simp add: S5n_rels_closed[OF spr_repMC_S5n] o_def) done next case (Kcknows as \<phi> X s) show ?case proof(cases "as = Nil") case True with \<open>s \<in> toSet X\<close> show ?thesis by clarsimp next case False with \<open>s \<in> toSet X\<close> spr_commonKnowledge_relation_image[OF subsetD[OF Kcknows(2) Kcknows(3)], where as=as] show ?thesis apply simp apply rule apply (drule arg_cong[where f="toSet"]) apply (clarsimp simp: odlist_all_iff) apply (cut_tac s1="(a, b)" and X1="spr_commonKnowledge envObs Y as (aa, ba)" in Kcknows.hyps) using Kcknows(2) Kcknows(3) apply (auto simp add: S5n_rels_closed[OF spr_repMC_S5n])[2] apply (subst (asm) trancl_unfold) back back back (* FIXME clunky, why did this break? *) apply (auto simp add: S5n_rels_closed[OF spr_repMC_S5n])[2] apply (clarsimp simp: toSet_eq_iff odlist_all_iff) apply (subst Kcknows.hyps) using Kcknows(2) Kcknows(3) apply (auto simp add: S5n_rels_closed[OF spr_repMC_S5n] o_def) apply (subst (asm) trancl_unfold) back back back (* FIXME clunky, why did this break? *) apply blast done qed qed (simp_all add: spr_repVal_def) lemma agent_abs_tObsC_abs_subset: "tObsC t' = tObsC t \<Longrightarrow> agent_abs a t \<subseteq> tObsC_abs t'" unfolding agent_abs_def tObsC_abs_def by (auto intro: spr_jview_tObsC) lemma spr_simAbs_fst_snd: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "toSet (snd ec) \<subseteq> toSet (fst ec)" using assms by (simp add: agent_abs_tObsC_abs_subset) lemma tObsC_abs_rel: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" and r: "(x, y) \<in> (\<Union> (relations (spr_repMC (tObsC_abs t)) ` set as))\<^sup>+" shows "x \<in> tObsC_abs t \<longleftrightarrow>y \<in> tObsC_abs t" using assms apply - apply rule apply (erule trancl_induct, auto)+ done lemma spr_simAbs_fst_snd_trc: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "toSet (big_union (spr_commonKnowledge envObs (fst ec) as) (toList (snd ec))) \<subseteq> toSet (fst ec)" using assms apply clarsimp apply (simp only: toSet_def[symmetric]) apply (subgoal_tac "(ab,ba) \<in> toSet (fst ec)") apply (simp add: spr_commonKnowledge_relation_image tObsC_abs_rel[OF tC ec]) apply (simp add: subsetD[OF agent_abs_tObsC_abs_subset[OF refl]]) done lemma agent_abs_rel_inv: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" and x: "x \<in> agent_abs a t" and xy: "(x, y) \<in> relations (spr_repMC (toSet (fst ec))) a" shows "y \<in> agent_abs a t" using assms apply simp unfolding agent_abs_def tObsC_abs_def spr_repRels_def apply auto apply (rule_tac x=t'b in exI) apply clarsimp apply (rule spr_jview_tObsCI) apply simp apply auto[1] apply (rule spr_jview_det_ps) using tC apply auto done lemma agent_abs_tObsC_abs: assumes tC: "t \<in> SPR.jkbpC" and x: "x \<in> agent_abs a t" and y: "y \<in> agent_abs a t" shows "(x, y) \<in> relations (spr_repMC (tObsC_abs t)) a" using assms unfolding agent_abs_def spr_repRels_def apply clarsimp apply safe prefer 3 apply (erule tObsC_absI) back apply simp_all apply (erule spr_jview_tObsC) prefer 3 apply (erule tObsC_absI) back back apply simp_all apply (erule spr_jview_tObsC) apply (rule spr_tFirst) apply simp apply (rule spr_tLast) apply simp done lemma agent_abs_spr_repRels: assumes tC: "t \<in> SPR.jkbpC" and x: "x \<in> agent_abs a t" and y: "y \<in> agent_abs a t" shows "(x, y) \<in> spr_repRels a" using assms unfolding agent_abs_def spr_repRels_def by (auto elim!: spr_tFirst spr_tLast) lemma evalS_models: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" and subj_phi: "subjective a \<phi>" and s: "s \<in> toSet (snd ec)" shows "evalS (spr_evalProp envVal) (spr_knowledge envObs (fst ec)) (spr_commonKnowledge envObs (fst ec)) (snd ec) \<phi> \<longleftrightarrow> spr_repMC (toSet (fst ec)), s \<Turnstile> \<phi>" (is "?lhs \<phi> = ?rhs \<phi>") using subj_phi s ec proof(induct \<phi> rule: subjective.induct[case_names Kprop Knot Kand Kknows Kcknows]) case (Kknows a a' \<psi>) thus ?case apply (clarsimp simp: toSet_eq_iff) apply rule apply clarsimp apply (subgoal_tac "(a, b) \<in> toSet (snd ec)") apply (drule (1) subsetD) back apply (simp only: eval_rec_models[OF spr_simAbs_fst_snd[OF tC ec]]) using tC Kknows apply simp using tC ec apply - apply (erule (1) agent_abs_rel_inv[OF tC]) apply simp apply clarsimp apply (subst eval_rec_models[OF spr_simAbs_fst_snd[OF tC ec]]) apply simp using agent_abs_tObsC_abs[OF tC] apply auto done next case (Kcknows a as \<psi>) have "?lhs (Kcknows as \<psi>) = (\<forall>y\<in>agent_abs a t. \<forall>x\<in>((\<Union>a\<in>set as. relations (spr_repMC (toSet (fst ec))) a)\<^sup>+ `` {y}). x \<in> toSet (eval_rec (spr_evalProp envVal) (spr_knowledge envObs (fst ec)) (spr_commonKnowledge envObs (fst ec)) (big_union (spr_commonKnowledge envObs (fst ec) as) (toList (snd ec))) \<psi>))" (* FIXME dreaming of a cong rule here. *) using toSet_def[symmetric] spr_simAbs_agent_abs[OF tC Kcknows(3)] spr_simAbs_tObsC_abs[OF tC Kcknows(3)] apply (clarsimp simp: toSet_eq_iff toSet_def[symmetric] subset_eq) apply (rule ball_cong[OF refl]) apply (rule ball_cong) apply (subst spr_commonKnowledge_relation_image) apply (simp_all add: subsetD[OF agent_abs_tObsC_abs_subset[OF refl]]) done also have "... = (\<forall>s\<in>agent_abs a t. spr_repMC (toSet (fst ec)), s \<Turnstile> Kcknows as \<psi>)" apply (rule ball_cong[OF refl]) apply simp apply (rule ball_cong[OF refl]) apply (subst eval_rec_models[OF spr_simAbs_fst_snd_trc[OF tC Kcknows(3), where as=as], symmetric]) using spr_simAbs_agent_abs[OF tC Kcknows(3)] spr_simAbs_tObsC_abs[OF tC Kcknows(3)] apply (simp add: toSet_def[symmetric]) apply (rule_tac x=y in bexI) apply (subst spr_commonKnowledge_relation_image) apply (auto elim: subsetD[OF agent_abs_tObsC_abs_subset[OF refl]])[1] apply simp apply assumption apply (rule refl) done also have "... = spr_repMC (toSet (fst ec)), s \<Turnstile> Kknows a (Kcknows as \<psi>)" using spr_simAbs_agent_abs[OF tC Kcknows(3)] spr_simAbs_tObsC_abs[OF tC Kcknows(3)] Kcknows(2) tC apply simp apply (rule ball_cong[OF _ refl]) apply rule apply (clarsimp simp: subsetD[OF agent_abs_tObsC_abs_subset] agent_abs_spr_repRels[OF tC]) apply (clarsimp elim!: agent_abs_rel_inv[OF tC Kcknows(3)]) done also have "... = spr_repMC (toSet (fst ec)), s \<Turnstile> Kcknows as \<psi>" apply (rule S5n_common_knowledge_fixed_point_simpler[symmetric]) using spr_simAbs_agent_abs[OF tC Kcknows(3)] spr_simAbs_tObsC_abs[OF tC Kcknows(3)] Kcknows(1) Kcknows(2) apply (auto elim: subsetD[OF agent_abs_tObsC_abs_subset[OF refl]]) done finally show ?case . qed simp_all (*>*) text\<open> This function corresponds with the standard semantics: \<close> lemma eval_models: assumes tC: "t \<in> SPR.jkbpC" assumes ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" assumes subj_phi: "subjective a \<phi>" assumes s: "s \<in> toSet (snd ec)" shows "eval envVal envObs ec \<phi> \<longleftrightarrow> spr_repMC (toSet (fst ec)), s \<Turnstile> \<phi>" (*<*) unfolding eval_def using evalS_models[OF tC ec subj_phi s] apply auto done (*>*) (* **************************************** *) subsubsection\<open>Simulated actions\<close> text\<open> From a common equivalence class and a subjective equivalence class for agent @{term "a"}, we can compute the actions enabled for @{term "a"}: \<close> definition (in -) spr_simAction :: "('a, 'p, 'aAct) JKBP \<Rightarrow> (('a, 'es, 'as) BEState \<Rightarrow> 'p \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> 'a \<Rightarrow> ('a::linorder, 'es::linorder, 'as::linorder) spr_simWorldsRep \<Rightarrow> 'aAct list" where "spr_simAction jkbp envVal envObs \<equiv> \<lambda>a ec. [ action gc. gc \<leftarrow> jkbp a, eval envVal envObs ec (guard gc) ]" (*<*) abbreviation spr_simAction :: "'a \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> 'aAct list" where "spr_simAction \<equiv> SPRViewDet.spr_simAction jkbp envVal envObs" (*>*) text\<open> Using the above result about evaluation, we can relate \<open>spr_simAction\<close> to @{term "jAction"}. Firstly, \<open>spr_simAction\<close> behaves the same as @{term "jAction"} using the @{term "spr_repMC"} structure: \<close> lemma spr_action_jaction: assumes tC: "t \<in> SPR.jkbpC" assumes ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "set (spr_simAction a ec) = set (jAction (spr_repMC (toSet (fst ec))) (tFirst t, tLast t) a)" (*<*) unfolding spr_simAction_def jAction_def apply clarsimp apply rule apply clarsimp apply (rule_tac x=xa in bexI) apply simp apply clarsimp apply (subst eval_models[OF tC ec, symmetric]) using tC ec subj apply simp_all apply (rule agent_absI) apply simp_all apply clarsimp apply (rule_tac x=xa in bexI) apply simp apply clarsimp apply (subst eval_models[OF tC ec]) using tC ec subj apply simp_all apply (rule agent_absI) apply simp_all done lemma spr_submodel_aux: assumes tC: "t \<in> SPR.jkbpC" and s: "s \<in> worlds (spr_simMCt t)" shows "gen_model SPRdet.MCS s = gen_model (spr_simMCt t) s" proof(rule gen_model_subset[where T="spr_jkbpCSt t"]) fix a let ?X = "spr_sim ` { t' . t' \<in> SPR.jkbpC \<and> tObsC t = tObsC t' }" show "relations SPRdet.MCS a \<inter> ?X \<times> ?X = relations (spr_simMCt t) a \<inter> ?X \<times> ?X" by (simp add: Int_ac Int_absorb1 relation_mono[OF jkbpCSt_jkbpCS_subset jkbpCSt_jkbpCS_subset]) next let ?X = "spr_sim ` { t' . t' \<in> SPR.jkbpC \<and> tObsC t = tObsC t' }" from s show "(\<Union>a. relations (spr_simMCt t) a)\<^sup>* `` {s} \<subseteq> ?X" apply (clarsimp simp del: mkKripke_simps) apply (erule (1) kripke_rels_trc_worlds) apply auto done next let ?Y = "{ t' . t' \<in> SPR.jkbpC \<and> tObsC t = tObsC t' }" let ?X = "spr_sim ` ?Y" from s obtain t' where st': "s = spr_sim t'" and t'C: "t' \<in> SPR.jkbpC" and t'O: "tObsC t = tObsC t'" by fastforce { fix t'' assume tt': "(t', t'') \<in> (\<Union>a. relations SPR.MC a)\<^sup>*" from t'C tt' have t''C: "t'' \<in> SPR.jkbpC" by - (erule kripke_rels_trc_worlds, simp_all) from t'O tt' have t''O: "tObsC t = tObsC t''" by (simp add: spr_tObsC_trc_aux) from t''C t''O have "t'' \<in> ?Y" by simp } hence "(\<Union>a. relations SPR.MC a)\<^sup>* `` {t'} \<subseteq> ?Y" by clarsimp hence "spr_sim ` ((\<Union>a. relations SPR.MC a)\<^sup>* `` {t'}) \<subseteq> ?X" by (rule image_mono) with st' t'C show "(\<Union>a. relations SPRdet.MCS a)\<^sup>* `` {s} \<subseteq> ?X" using sim_trc_commute[OF SPR.mkM_kripke spr_sim, where t=t'] by simp qed (insert s, auto) (*>*) text\<open> We can connect the agent's choice of actions on the \<open>spr_repMC\<close> structure to those on the \<open>SPR.MC\<close> structure using our earlier results about actions being preserved by generated models and simulations. \<close> lemma spr_simAction: assumes tC: "t \<in> SPR.jkbpC" assumes ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "set (spr_simAction a ec) = set (jAction SPR.MC t a)" (*<*) (is "?lhs = ?rhs") proof - from tC ec have "?lhs = set (jAction (spr_repMC (toSet (fst ec))) (tFirst t, tLast t) a)" by (rule spr_action_jaction) also from tC ec have "... = set (jAction (spr_simMCt t) (spr_sim t) a)" by (simp add: simulation_jAction_eq[OF _ spr_repSim] spr_sim_tObsC_abs) also from tC have "... = set (jAction SPRdet.MCS (spr_sim t) a)" using gen_model_jAction_eq[OF spr_submodel_aux[OF tC, where s="spr_sim t"], where w'="spr_sim t"] gen_model_world_refl[where w="spr_sim t" and M="spr_simMCt t"] by simp also from tC have "... = set (jAction SPR.MC t a)" by (simp add: simulation_jAction_eq[OF _ spr_sim]) finally show ?thesis . qed (*>*) (* **************************************** *) subsubsection\<open>Simulated transitions\<close> text\<open> The story of simulated transitions takes some doing. We begin by computing the successor relation of a given equivalence class @{term "X"} with respect to the common equivalence class @{term "cec"}: \<close> abbreviation (in -) "spr_jAction jkbp envVal envObs cec s \<equiv> \<lambda>a. spr_simAction jkbp envVal envObs a (cec, spr_knowledge envObs cec a s)" definition (in -) spr_trans :: "'a odlist \<Rightarrow> ('a, 'p, 'aAct) JKBP \<Rightarrow> (('a::linorder, 'es::linorder, 'as::linorder) BEState \<Rightarrow> 'eAct list) \<Rightarrow> ('eAct \<Rightarrow> ('a \<Rightarrow> 'aAct) \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> ('a, 'es, 'as) BEState) \<Rightarrow> (('a, 'es, 'as) BEState \<Rightarrow> 'p \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> ('a, 'es, 'as) spr_simWorldsECRep \<Rightarrow> ('a, 'es, 'as) spr_simWorldsECRep \<Rightarrow> (('a, 'es, 'as) BEState \<times> ('a, 'es, 'as) BEState) list" where "spr_trans agents jkbp envAction envTrans envVal envObs \<equiv> \<lambda>cec X. [ (initialS, succS) . (initialS, finalS) \<leftarrow> toList X, eact \<leftarrow> envAction finalS, succS \<leftarrow> [ envTrans eact aact finalS . aact \<leftarrow> listToFuns (spr_jAction jkbp envVal envObs cec (initialS, finalS)) (toList agents) ] ]" text\<open> We will split the result of this function according to the common observation and also agent @{term "a"}'s observation, where @{term "a"} is the agent we are constructing the automaton for. \<close> definition (in -) spr_simObsC :: "('es \<Rightarrow> 'cobs) \<Rightarrow> (('a::linorder, 'es::linorder, 'as::linorder) BEState \<times> ('a, 'es, 'as) BEState) odlist \<Rightarrow> 'cobs" where "spr_simObsC envObsC \<equiv> envObsC \<circ> es \<circ> snd \<circ> ODList.hd" abbreviation (in -) envObs_rel :: "(('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> ('a, 'es, 'as) spr_simWorlds \<times> ('a, 'es, 'as) spr_simWorlds \<Rightarrow> bool" where "envObs_rel envObs \<equiv> \<lambda>(s, s'). envObs (snd s') = envObs (snd s)" text\<open> The above combine to yield the successor equivalence classes like so: \<close> definition (in -) spr_simTrans :: "'a odlist \<Rightarrow> ('a, 'p, 'aAct) JKBP \<Rightarrow> (('a::linorder, 'es::linorder, 'as::linorder) BEState \<Rightarrow> 'eAct list) \<Rightarrow> ('eAct \<Rightarrow> ('a \<Rightarrow> 'aAct) \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> ('a, 'es, 'as) BEState) \<Rightarrow> (('a, 'es, 'as) BEState \<Rightarrow> 'p \<Rightarrow> bool) \<Rightarrow> ('es \<Rightarrow> 'cobs) \<Rightarrow> ('a \<Rightarrow> ('a, 'es, 'as) BEState \<Rightarrow> 'cobs \<times> 'as option) \<Rightarrow> 'a \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep list" where "spr_simTrans agents jkbp envAction envTrans envVal envObsC envObs \<equiv> \<lambda>a ec. let aSuccs = spr_trans agents jkbp envAction envTrans envVal envObs (fst ec) (snd ec); cec' = ODList.fromList (spr_trans agents jkbp envAction envTrans envVal envObs (fst ec) (fst ec)) in [ (ODList.filter (\<lambda>s. envObsC (es (snd s)) = spr_simObsC envObsC aec') cec', aec') . aec' \<leftarrow> map ODList.fromList (partition (envObs_rel (envObs a)) aSuccs) ]" (*<*) abbreviation spr_trans :: "('a, 'es, 'as) spr_simWorldsECRep \<Rightarrow> ('a, 'es, 'as) spr_simWorldsECRep \<Rightarrow> (('a, 'es, 'as) spr_simWorlds) list" where "spr_trans \<equiv> SPRViewDet.spr_trans agents jkbp envAction envTrans envVal envObs" abbreviation spr_simTrans :: "'a \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep list" where "spr_simTrans \<equiv> SPRViewDet.spr_simTrans agents jkbp envAction envTrans envVal envObsC envObs" lemma spr_trans_aec: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "set (spr_trans (fst ec) (snd ec)) = { (tFirst t', s) |t' s. t' \<leadsto> s \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t }" (is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" proof fix x assume x: "x \<in> ?lhs" with assms show "x \<in> ?rhs" unfolding spr_trans_def apply (clarsimp simp del: split_paired_Ex split_paired_All simp add: toSet_def[symmetric] agent_abs_def) apply (rule_tac x=t' in exI) apply simp apply (rule_tac n="Suc (tLength t')" in SPR.jkbpCn_jkbpC_inc) apply (auto iff: Let_def simp del: split_paired_Ex split_paired_All) apply (simp add: listToFuns_ext[OF agents[unfolded toSet_def]]) apply (rule_tac x=xa in exI) apply simp apply (subst (asm) spr_simAction) apply assumption apply rule apply clarsimp apply (clarsimp simp: spr_simAbs_def) apply (subst (asm) spr_knowledge) apply (simp add: ec) apply (erule tObsC_absI) apply simp_all apply (erule spr_jview_tObsC) using ec apply clarsimp (* FIXME *) apply (clarsimp simp: spr_repRels_def tObsC_abs_conv) apply (rule_tac x=t'b in image_eqI) apply (auto iff: spr_sim_def)[1] apply clarsimp apply (rule spr_jview_tObsCI[OF _ _ spr_jview_det_ps]) apply simp_all apply (erule spr_jview_tObsC[symmetric]) apply (erule spr_jview_tObsC[symmetric]) apply clarsimp apply (clarsimp simp: spr_simAbs_def) apply (subst spr_knowledge) apply (simp_all add: ec) apply (erule tObsC_absI) apply (erule spr_jview_tObsC) apply simp_all apply (rule_tac x="tFirst xc" in exI) apply (rule_tac x="tLast xc" in exI) apply (simp add: spr_sim_def) apply rule apply (drule tObsC_abs_jview_eq) apply simp apply (erule tObsC_abs_jview_eq[symmetric]) apply (clarsimp simp: spr_repRels_def tObsC_abs_conv) apply rule apply (rule spr_tFirst) apply simp apply rule apply (rule spr_tLast) apply simp apply rule apply (rule_tac x=t' in exI) apply simp apply (erule spr_jview_tObsC) apply (rule_tac x=xc in exI) apply simp apply (drule spr_jview_tObsC) apply (drule spr_jview_tObsC) apply simp apply (subst SPR.jkbpC_jkbpCn_jAction_eq[symmetric]) apply auto done qed show "?rhs \<subseteq> ?lhs" proof fix x assume x: "x \<in> ?rhs" then obtain t' s where x': "x = (tFirst t', s)" and t'sC: "t' \<leadsto> s \<in> SPR.jkbpC" and F: "spr_jview a t' = spr_jview a t" by blast from t'sC have t'Cn: "t' \<in> SPR.jkbpCn (tLength t')" by blast from t'sC obtain eact aact where eact: "eact \<in> set (envAction (tLast t'))" and aact: "\<forall>a. aact a \<in> set (jAction (SPR.mkM (SPR.jkbpCn (tLength t'))) t' a)" and s: "s = envTrans eact aact (tLast t')" using SPR.jkbpC_tLength_inv[where t="t' \<leadsto> s" and n="Suc (tLength t')"] by (auto iff: Let_def) from tC t'sC ec F x' s eact aact show "x \<in> ?lhs" unfolding spr_trans_def apply (clarsimp simp del: split_paired_Ex split_paired_All simp: toSet_def[symmetric]) apply (rule bexI[where x="(tFirst t', tLast t')"]) apply simp apply (rule bexI[where x="eact"]) apply (rule_tac x="aact" in image_eqI) apply simp_all apply (simp add: listToFuns_ext[OF agents[unfolded toSet_def]]) defer apply blast apply (subst spr_simAction[where t=t']) apply blast defer apply (auto iff: SPR.jkbpC_jkbpCn_jAction_eq[OF t'Cn])[1] apply (clarsimp simp: spr_simAbs_def) apply (subst spr_knowledge) apply (simp_all add: ec) apply (rule tObsC_absI[where t=t and t'=t']) apply simp_all apply blast apply (blast intro: spr_jview_tObsC) apply (clarsimp simp: spr_repRels_def tObsC_abs_conv) apply rule apply clarsimp apply (rule_tac x=t'aa in image_eqI) apply (auto iff: spr_sim_def)[1] apply simp apply (rule spr_jview_tObsCI[OF _ _ spr_jview_det_ps]) apply simp_all apply (erule spr_jview_tObsC[symmetric]) apply blast apply (erule spr_jview_tObsC[symmetric]) apply (clarsimp simp: spr_sim_def) apply rule apply (drule tObsC_abs_jview_eq) apply (drule tObsC_abs_jview_eq) apply simp apply rule apply (rule spr_tFirst) apply simp apply rule apply (rule spr_tLast) apply simp apply rule apply (rule_tac x=t' in exI) apply (auto dest: spr_jview_tObsC intro: spr_jview_tObsC_trans) done qed qed lemma spr_trans_cec: assumes tC: "t \<in> SPR.jkbpC" and ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "set (spr_trans (fst ec) (fst ec)) = { (tFirst t', s) |t' s. t' \<leadsto> s \<in> SPR.jkbpC \<and> tObsC t' = tObsC t }" (is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" proof fix x assume x: "x \<in> ?lhs" with assms show "x \<in> ?rhs" unfolding spr_trans_def apply (clarsimp simp del: split_paired_Ex split_paired_All simp add: toSet_def[symmetric] tObsC_abs_def) apply (rule_tac x=t' in exI) apply simp apply (rule_tac n="Suc (tLength t')" in SPR.jkbpCn_jkbpC_inc) apply (auto iff: Let_def simp del: split_paired_Ex split_paired_All) apply (simp add: listToFuns_ext[OF agents[unfolded toSet_def]]) apply (rule_tac x=xa in exI) apply simp apply (subst (asm) spr_simAction) apply assumption apply rule apply clarsimp apply (clarsimp simp: spr_simAbs_def) apply (subst (asm) spr_knowledge) apply (simp add: ec) apply (erule tObsC_absI) apply simp_all apply (clarsimp simp: spr_repRels_def tObsC_abs_conv ec) apply (rule_tac x=t'b in image_eqI) apply (auto iff: spr_sim_def ec)[1] apply clarsimp apply (rule spr_jview_tObsCI[OF _ _ spr_jview_det_ps]) apply simp_all apply (clarsimp simp: spr_simAbs_def) apply (subst spr_knowledge) apply (simp_all add: ec) apply (erule tObsC_absI) apply simp_all apply (rule_tac x="tFirst xc" in exI) apply (rule_tac x="tLast xc" in exI) apply (simp add: spr_sim_def) apply rule apply (drule tObsC_abs_jview_eq) apply auto[1] apply (clarsimp simp: spr_repRels_def tObsC_abs_conv) apply rule apply (rule spr_tFirst) apply simp apply rule apply (rule spr_tLast) apply simp apply rule apply (rule_tac x=t' in exI) apply simp apply (rule_tac x=xc in exI) apply simp apply (drule spr_jview_tObsC) apply simp apply (subst SPR.jkbpC_jkbpCn_jAction_eq[symmetric]) apply auto done qed show "?rhs \<subseteq> ?lhs" proof fix x assume x: "x \<in> ?rhs" then obtain t' s where x': "x = (tFirst t', s)" and t'sC: "t' \<leadsto> s \<in> SPR.jkbpC" and F: "tObsC t' = tObsC t" by blast from t'sC have t'Cn: "t' \<in> SPR.jkbpCn (tLength t')" by blast from t'sC obtain eact aact where eact: "eact \<in> set (envAction (tLast t'))" and aact: "\<forall>a. aact a \<in> set (jAction (SPR.mkM (SPR.jkbpCn (tLength t'))) t' a)" and s: "s = envTrans eact aact (tLast t')" using SPR.jkbpC_tLength_inv[where t="t' \<leadsto> s" and n="Suc (tLength t')"] by (auto iff: Let_def) from tC t'sC ec F x' s eact aact show "x \<in> ?lhs" unfolding spr_trans_def apply (clarsimp simp del: split_paired_Ex split_paired_All simp: toSet_def[symmetric]) apply (rule bexI[where x="(tFirst t', tLast t')"]) apply simp apply (rule bexI[where x="eact"]) apply (rule_tac x="aact" in image_eqI) apply simp_all apply (simp add: listToFuns_ext[OF agents[unfolded toSet_def]]) defer apply blast apply (subst spr_simAction[where t=t']) apply blast defer apply (auto iff: SPR.jkbpC_jkbpCn_jAction_eq[OF t'Cn])[1] apply (clarsimp simp: spr_simAbs_def) apply (subst spr_knowledge) apply (simp_all add: ec) apply (rule tObsC_absI[where t=t and t'=t']) apply simp_all apply blast apply (clarsimp simp: spr_repRels_def tObsC_abs_conv) apply rule apply clarsimp apply (rule_tac x=t'aa in image_eqI) apply (auto iff: spr_sim_def [abs_def])[1] apply simp apply (rule spr_jview_tObsCI[OF _ _ spr_jview_det_ps]) apply simp_all apply blast apply (clarsimp simp: spr_sim_def [abs_def]) apply (rule conjI) apply (auto dest!: tObsC_abs_jview_eq intro: spr_tFirst spr_tLast)[1] apply (rule conjI) apply (auto intro: spr_tFirst)[1] apply (rule conjI) apply (auto intro: spr_tLast)[1] apply (rule conjI) apply (auto intro: spr_tLast)[1] apply (rule_tac x=xb in exI) apply (auto dest: spr_jview_tObsC intro: spr_jview_tObsC_trans)[1] done qed qed lemma spr_simObsC: assumes t'sC: "t \<leadsto> s \<in> SPR.jkbpC" and aec': "toSet aec = (rel_ext (envObs_rel (envObs a)) \<inter> X \<times> X) `` {(tFirst t, s)}" and X: "X = {(tFirst t', s) |t' s. t' \<leadsto> s \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t}" shows "spr_simObsC envObsC aec = envObsC (es s)" unfolding spr_simObsC_def apply (cases aec) using assms apply auto[1] using assms apply (simp add: ODList.hd_def toList_fromList) apply (subgoal_tac "x \<in> insert x (set xs)") apply (auto iff: envObs_def)[1] apply blast done lemma envObs_rel_equiv: "equiv UNIV (rel_ext (envObs_rel (envObs a)))" by (intro equivI refl_onI symI transI) auto (*>*) text\<open> Showing that \<open>spr_simTrans\<close> works requires a series of auxiliary lemmas that show we do in fact compute the correct successor equivalence classes. We elide the unedifying details, skipping straight to the lemma that the @{term "Algorithm"} locale expects: \<close> lemma spr_simTrans: assumes tC: "t \<in> SPR.jkbpC" assumes ec: "spr_simAbs ec = SPRdet.sim_equiv_class a t" shows "spr_simAbs ` set (spr_simTrans a ec) = { SPRdet.sim_equiv_class a (t' \<leadsto> s) |t' s. t' \<leadsto> s \<in> SPR.jkbpC \<and> spr_jview a t' = spr_jview a t}" (*<*)(is "?lhs = ?rhs") proof show "?lhs \<subseteq> ?rhs" proof fix x assume x: "x \<in> ?lhs" then obtain rx where xrx: "x = spr_simAbs rx" and rx: "rx \<in> set (spr_simTrans a ec)" by blast with tC ec obtain cec' aec' UV' t' s where rxp: "rx = (cec', aec')" and t'sC: "t' \<leadsto> s \<in> SPR.jkbpC" and tt': "spr_jview a t' = spr_jview a t" and aec': "toSet aec' = (rel_ext (envObs_rel (envObs a)) \<inter> set (spr_trans (fst ec) (snd ec)) \<times> set (spr_trans (fst ec) (snd ec))) `` {(tFirst t', s)}" and cec': "cec' = ODList.filter (\<lambda>s. envObsC (es (snd s)) = spr_simObsC envObsC aec') (fromList (spr_trans (fst ec) (fst ec)))" unfolding spr_simTrans_def using spr_trans_aec[OF assms] apply (auto split: prod.split_asm) apply (drule imageI[where f=set]) apply (simp add: partition[OF envObs_rel_equiv subset_UNIV]) apply (erule quotientE) apply fastforce done from t'sC tt' aec' cec' have "spr_simAbs (cec', aec') = SPRdet.sim_equiv_class a (t' \<leadsto> s)" unfolding spr_simAbs_def apply clarsimp apply rule using spr_trans_aec[OF assms] spr_trans_cec[OF assms] apply clarsimp apply (rule_tac x="t'aa \<leadsto> s'" in image_eqI) apply (simp add: spr_sim_def) apply (cut_tac aec=aec' and t=t' and s=s in spr_simObsC[where a=a]) apply simp_all apply rule apply clarsimp apply (erule_tac t'="t'b \<leadsto> sa" in tObsC_absI) apply simp_all apply (auto dest: spr_jview_tObsC iff: tObsC_def envObs_def_raw)[1] apply (clarsimp simp: envObs_def_raw tObsC_abs_conv) apply (case_tac t'b) apply (simp add: tObsC_def) apply clarsimp apply (rename_tac Trace State) apply (rule_tac x=Trace in exI) apply (auto dest: spr_jview_tObsC simp: tObsC_def)[1] apply (simp add: spr_jview_def) using spr_trans_aec[OF assms] spr_trans_cec[OF assms] apply (clarsimp simp: spr_sim_def) apply (cut_tac aec=aec' and t=t' and s=s in spr_simObsC[where a=a]) apply simp_all apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply safe apply (clarsimp simp: tObsC_abs_conv) apply (case_tac t'a) apply (simp add: tObsC_def) apply clarsimp apply (rename_tac Trace State) apply (rule_tac x="Trace" in exI) apply (drule spr_jview_prefix_closed) apply (auto dest: spr_jview_tObsC simp: tObsC_def)[1] apply (auto simp: spr_jview_def Let_def envObs_def_raw)[1] apply (erule_tac t'="t'a \<leadsto> sa" in tObsC_absI) apply simp_all apply (drule spr_jview_tObsC[symmetric]) apply (frule spr_jview_prefix_closed) apply (auto dest: spr_jview_tObsC simp: tObsC_def)[1] apply (simp add: spr_jview_def) apply auto[1] apply (rule_tac x="t''" in exI) apply (drule spr_jview_prefix_closed) apply simp done with xrx rxp t'sC tt' show "x \<in> ?rhs" apply simp apply (rule_tac x=t' in exI) apply (rule_tac x=s in exI) apply simp done qed next note image_cong_simp [cong del] show "?rhs \<subseteq> ?lhs" proof fix x assume x: "x \<in> ?rhs" then obtain t' s where t'sC: "t' \<leadsto> s \<in> SPR.jkbpC" and tt': "spr_jview a t' = spr_jview a t" and xt's: "x = SPRdet.sim_equiv_class a (t' \<leadsto> s)" by auto then have "(\<lambda>s. (sprFst s, sprLst s)) ` x \<in> set ` set (partition (envObs_rel (envObs a)) (spr_trans (fst ec) (snd ec)))" apply (simp add: partition[OF envObs_rel_equiv] spr_trans_aec[OF assms] spr_sim_def [abs_def]) apply (rule_tac x="(tFirst t', s)" in quotientI2) apply auto[1] apply (auto dest: spr_jview_tStep_eq_inv) apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (drule spr_jview_prefix_closed) apply auto[1] apply (rule_tac x="\<lparr>sprFst = tFirst t'aa, sprLst = sa, sprCRel = tObsC_abs (t'aa \<leadsto> sa)\<rparr>" in image_eqI) apply simp apply (rule_tac x="t'aa \<leadsto> sa" in image_eqI) apply simp apply (simp add: spr_jview_def) done then obtain rx where "rx \<in> set (partition (envObs_rel (envObs a)) (spr_trans (fst ec) (snd ec)))" and "set rx = (\<lambda>s. (sprFst s, sprLst s)) ` x" by auto with t'sC tt' xt's show "x \<in> ?lhs" unfolding spr_simTrans_def apply clarsimp apply (rule_tac x="(ODList.filter (\<lambda>s. envObsC (es (snd s)) = spr_simObsC envObsC (fromList rx)) (fromList (spr_trans (fst ec) (fst ec))), fromList rx)" in image_eqI) prefer 2 apply (rule_tac x="rx" in image_eqI) apply simp apply simp apply (subst spr_simObsC[where a=a and t=t' and s=s, OF _ _ refl]) apply simp_all apply rule apply clarsimp apply (frule spr_jview_tStep_eq_inv) apply (auto simp: spr_jview_def spr_sim_def [abs_def])[1] apply clarsimp apply (rule_tac x="spr_sim (t'aa \<leadsto> sa)" in image_eqI) apply (simp add: spr_sim_def [abs_def]) apply (rule_tac x="t'aa \<leadsto> sa" in image_eqI) apply simp apply (simp add: spr_jview_def) apply (clarsimp simp: spr_trans_cec[OF assms] spr_sim_def [abs_def] spr_simAbs_def) apply rule apply (auto iff: tObsC_abs_conv)[1] apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (frule tObsC_tStep_eq_inv) apply clarsimp apply (drule spr_jview_prefix_closed) apply (drule spr_jview_tObsC) apply (drule spr_jview_tObsC) apply (drule tObsC_prefix_closed) apply (rule_tac x=t''a in exI) apply simp apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (frule tObsC_tStep_eq_inv) apply clarsimp apply (drule spr_jview_tObsC) back apply (simp add: tObsC_def) apply (rule_tac x="t'a \<leadsto> sa" in exI) apply simp apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (drule spr_jview_tObsC) apply (frule spr_jview_tObsC) apply (simp add: tObsC_def) apply (rule_tac x="spr_sim ta" in image_eqI) apply (simp add: spr_sim_def [abs_def]) apply (rule_tac x=ta in image_eqI) apply (simp add: spr_sim_def [abs_def]) apply simp apply clarsimp apply (rule_tac x=ta in image_eqI) prefer 2 apply simp apply (clarsimp simp: tObsC_abs_def) apply auto[1] apply (rule_tac x="t'a \<leadsto> sa" in exI) apply simp apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (drule spr_jview_tObsC) apply (frule spr_jview_tObsC) apply (simp add: tObsC_def) apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (frule tObsC_tStep_eq_inv) apply clarsimp apply (rule_tac x="t''a" in exI) apply (drule spr_jview_tObsC) apply (frule spr_jview_tObsC) apply (simp add: tObsC_def) apply (frule spr_jview_tStep_eq_inv) apply clarsimp apply (frule tObsC_tStep_eq_inv) apply clarsimp apply (drule spr_jview_tObsC) back apply (simp add: tObsC_def) done qed qed (*>*) text\<open> The explicit-state approach sketched above is quite inefficient, and also some distance from the symbolic techniques we use in \S\ref{sec:kbps-prag-algorithmics}. However it does suffice to demonstrate the theory on the muddy children example in \S\ref{sec:kbps-theory-mc}. \<close> end (* context FiniteDetBroadcastEnvironment *) subsubsection\<open>Maps\<close> text\<open> As always we use a pair of tries. The domain of these maps is the pair of relations. \<close> type_synonym ('a, 'es, 'obs, 'as) trans_trie = "(('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, ('obs, ('a, 'es, 'as) spr_simWorldsRep) mapping) trie) trie) trie) trie" type_synonym ('a, 'es, 'aAct, 'as) acts_trie = "(('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, (('a, 'es, 'as) BEState, 'aAct) trie) trie) trie) trie" (*<*) definition trans_MapOps_lookup :: "('a :: linorder, 'es :: linorder, 'obs, 'as :: linorder) trans_trie \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<times> 'obs \<rightharpoonup> ('a, 'es, 'as) spr_simWorldsRep" where "trans_MapOps_lookup \<equiv> \<lambda>m ((cec, aec), obs). Option.bind (lookup_trie m (map fst (toList cec))) (\<lambda>m. Option.bind (lookup_trie m (map snd (toList cec))) (\<lambda>m. Option.bind (lookup_trie m (map fst (toList aec))) (\<lambda>m. Option.bind (lookup_trie m (map snd (toList aec))) (\<lambda>m. Mapping.lookup m obs))))" definition trans_MapOps_update :: "('a, 'es, 'as) spr_simWorldsRep \<times> 'obs \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> ('a :: linorder, 'es :: linorder, 'obs, 'as :: linorder) trans_trie \<Rightarrow> ('a, 'es, 'obs, 'as) trans_trie" where "trans_MapOps_update \<equiv> \<lambda>((cec, aec), obs) v m. trie_update_with' (map fst (toList cec)) m empty_trie (\<lambda>m. trie_update_with' (map snd (toList cec)) m empty_trie (\<lambda>m. trie_update_with' (map fst (toList aec)) m empty_trie (\<lambda>m. trie_update_with' (map snd (toList aec)) m Mapping.empty (\<lambda>m. Mapping.update obs v m))))" definition trans_MapOps :: "(('a :: linorder, 'es :: linorder, 'obs, 'as :: linorder) trans_trie, ('a, 'es, 'as) spr_simWorldsRep \<times> 'obs, ('a, 'es, 'as) spr_simWorldsRep) MapOps" where "trans_MapOps \<equiv> \<lparr> MapOps.empty = empty_trie, lookup = trans_MapOps_lookup, update = trans_MapOps_update \<rparr>" lemma (in FiniteDetBroadcastEnvironment) trans_MapOps[intro, simp]: "MapOps (\<lambda>k. (spr_simAbs (fst k), snd k)) (SPRdet.jkbpSEC \<times> UNIV) trans_MapOps" proof fix k show "MapOps.lookup trans_MapOps (MapOps.empty trans_MapOps) k = None" unfolding trans_MapOps_def trans_MapOps_lookup_def by (auto split: prod.split) next fix e k k' M assume k: "(spr_simAbs (fst k), snd k) \<in> SPRdet.jkbpSEC \<times> (UNIV :: 'z set)" and k': "(spr_simAbs (fst k'), snd k') \<in> SPRdet.jkbpSEC \<times> (UNIV :: 'z set)" show "MapOps.lookup trans_MapOps (MapOps.update trans_MapOps k e M) k' = (if (spr_simAbs (fst k'), snd k') = (spr_simAbs (fst k), snd k) then Some e else MapOps.lookup trans_MapOps M k')" proof(cases "(spr_simAbs (fst k'), snd k') = (spr_simAbs (fst k), snd k)") case True hence "k = k'" using inj_onD[OF spr_simAbs_inj_on] k k' by (auto iff: prod_eqI) thus ?thesis unfolding trans_MapOps_def trans_MapOps_lookup_def trans_MapOps_update_def by (auto simp: lookup_update lookup_trie_update_with split: option.split prod.split) next have *: "\<And> y ya. y \<noteq> ya \<Longrightarrow> Mapping.lookup (Mapping.update y e Mapping.empty) ya = None" by transfer simp case False thus ?thesis unfolding trans_MapOps_def trans_MapOps_lookup_def trans_MapOps_update_def by (auto dest: map_prod_eq simp: lookup_trie_update_with split: option.split prod.split intro!: lookup_update_neq *) qed qed (* A map for the agent actions. *) definition acts_MapOps_lookup :: "('a :: linorder, 'es :: linorder, 'aAct, 'as :: linorder) acts_trie \<Rightarrow> ('a, 'es, 'as) spr_simWorldsRep \<rightharpoonup> 'aAct" where "acts_MapOps_lookup \<equiv> \<lambda>m (cec, aec). Option.bind (lookup_trie m (map fst (toList cec))) (\<lambda>m. Option.bind (lookup_trie m (map snd (toList cec))) (\<lambda>m. Option.bind (lookup_trie m (map fst (toList aec))) (\<lambda>m. lookup_trie m (map snd (toList aec)))))" definition acts_MapOps_update :: "('a, 'es, 'as) spr_simWorldsRep \<Rightarrow> 'aAct \<Rightarrow> ('a :: linorder, 'es :: linorder, 'aAct, 'as :: linorder) acts_trie \<Rightarrow> ('a, 'es, 'aAct, 'as) acts_trie" where "acts_MapOps_update \<equiv> \<lambda>(cec, aec) pAct m. trie_update_with' (map fst (toList cec)) m empty_trie (\<lambda>m. trie_update_with' (map snd (toList cec)) m empty_trie (\<lambda>m. trie_update_with' (map fst (toList aec)) m empty_trie (\<lambda>m. trie_update (map snd (toList aec)) pAct m)))" definition acts_MapOps :: "(('a :: linorder, 'es :: linorder, 'aAct, 'as :: linorder) acts_trie, ('a, 'es, 'as) spr_simWorldsRep, 'aAct) MapOps" where "acts_MapOps \<equiv> \<lparr> MapOps.empty = empty_trie, lookup = acts_MapOps_lookup, update = acts_MapOps_update \<rparr>" lemma (in FiniteDetBroadcastEnvironment) acts_MapOps[intro, simp]: "MapOps spr_simAbs SPRdet.jkbpSEC acts_MapOps" proof fix k show "MapOps.lookup acts_MapOps (MapOps.empty acts_MapOps) k = None" unfolding acts_MapOps_def acts_MapOps_lookup_def by auto next fix e k k' M assume k: "spr_simAbs k \<in> SPRdet.jkbpSEC" and k': "spr_simAbs k' \<in> SPRdet.jkbpSEC" show "MapOps.lookup acts_MapOps (MapOps.update acts_MapOps k e M) k' = (if spr_simAbs k' = spr_simAbs k then Some e else MapOps.lookup acts_MapOps M k')" proof(cases "spr_simAbs k' = spr_simAbs k") case True hence "k = k'" using inj_onD[OF spr_simAbs_inj_on] k k' by (auto iff: prod_eqI) thus ?thesis unfolding acts_MapOps_def acts_MapOps_lookup_def acts_MapOps_update_def by (auto simp: lookup_trie_update_with lookup_trie_update split: option.split prod.split) next case False thus ?thesis unfolding acts_MapOps_def acts_MapOps_lookup_def acts_MapOps_update_def by (auto dest: map_prod_eq simp: lookup_trie_update_with lookup_trie_update split: option.split prod.split) qed qed (*>*) text\<open> This suffices to placate the @{term "Algorithm"} locale. \<close> sublocale FiniteDetBroadcastEnvironment < SPRdet: Algorithm jkbp envInit envAction envTrans envVal spr_jview envObs spr_jviewInit spr_jviewIncr spr_sim spr_simRels spr_simVal spr_simAbs spr_simObs spr_simInit spr_simTrans spr_simAction acts_MapOps trans_MapOps (*<*) apply (unfold_locales) using spr_simInit apply auto[1] using spr_simObs apply auto[1] using spr_simAction apply auto[1] using spr_simTrans apply auto[1] apply (rule acts_MapOps) apply (rule trans_MapOps) done definition "mkSPRDetAuto \<equiv> \<lambda>agents jkbp envInit envAction envTrans envVal envObsC envObs. mkAlgAuto acts_MapOps trans_MapOps (spr_simObs envObsC) (spr_simInit envInit envObsC envObs) (spr_simTrans agents jkbp envAction envTrans envVal envObsC envObs) (spr_simAction jkbp envVal envObs) (\<lambda>a. map (spr_simInit envInit envObsC envObs a \<circ> envObs a) envInit)" lemma (in FiniteDetBroadcastEnvironment) mkSPRDetAuto_implements: "SPR.implements (mkSPRDetAuto agents jkbp envInit envAction envTrans envVal envObsC envObs)" using SPRdet.k_mkAlgAuto_implements unfolding mkSPRDetAuto_def mkAlgAuto_def SPRdet.k_frontier_def by simp (* We actually run this unfolding of the algorithm. The lemma is keeping us honest. *) definition "SPRDetAutoDFS \<equiv> \<lambda>agents jkbp envInit envAction envTrans envVal envObsC envObs. \<lambda>a. alg_dfs acts_MapOps trans_MapOps (spr_simObs envObsC a) (spr_simTrans agents jkbp envAction envTrans envVal envObsC envObs a) (spr_simAction jkbp envVal envObs a) (map (spr_simInit envInit envObsC envObs a \<circ> envObs a) envInit)" lemma (in FiniteDetBroadcastEnvironment) "mkSPRDetAuto agents jkbp envInit envAction envTrans envVal envObsC envObs = (\<lambda>a. alg_mk_auto acts_MapOps trans_MapOps (spr_simInit a) (SPRDetAutoDFS agents jkbp envInit envAction envTrans envVal envObsC envObs a))" unfolding mkSPRDetAuto_def mkAlgAuto_def SPRDetAutoDFS_def alg_mk_auto_def by (simp add: Let_def) (*>*) text\<open> As we remarked earlier in this section, in general it may be difficult to establish the determinacy of a KBP as it is a function of the environment. However in many cases determinism is syntactically manifest as the guards are logically disjoint, independently of the knowledge subformulas. The following lemma generates the required proof obligations for this case: \<close> lemma (in PreEnvironmentJView) jkbpDetI: assumes tC: "t \<in> jkbpC" assumes jkbpSynDet: "\<forall>a. distinct (map guard (jkbp a))" assumes jkbpSemDet: "\<forall>a gc gc'. gc \<in> set (jkbp a) \<and> gc' \<in> set (jkbp a) \<and> t \<in> jkbpC \<longrightarrow> guard gc = guard gc' \<or> \<not>(MC, t \<Turnstile> guard gc \<and> MC, t \<Turnstile> guard gc')" shows "length (jAction MC t a) \<le> 1" (*<*) proof - { fix a X assume "set X \<subseteq> set (jkbp a)" and "distinct (map guard X)" with tC have "length [ action gc . gc \<leftarrow> X, MC, t \<Turnstile> guard gc ] \<le> 1" apply (induct X) using jkbpSemDet[rule_format, where a=a] apply auto done } from this[OF subset_refl jkbpSynDet[rule_format]] show ?thesis unfolding jAction_def by simp qed (*>*) text\<open> The scenario presented here is a variant of the broadcast environments treated by \citet{Ron:1996}, which we cover in the next section. \FloatBarrier \<close> (*<*) end (*>*)
Declare ML Module "test_plugin". TestCommand. Goal True. Proof. test_tactic. exact I. Qed.
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.basic import algebra.star.module import analysis.special_functions.exponential /-! # The exponential map from selfadjoint to unitary In this file, we establish various propreties related to the map `λ a, exp ℂ A (I • a)` between the subtypes `self_adjoint A` and `unitary A`. ## TODO * Show that any exponential unitary is path-connected in `unitary A` to `1 : unitary A`. * Prove any unitary whose distance to `1 : unitary A` is less than `1` can be expressed as an exponential unitary. * A unitary is in the path component of `1` if and only if it is a finite product of exponential unitaries. -/ section star variables {A : Type*} [normed_ring A] [normed_algebra ℂ A] [star_ring A] [has_continuous_star A] [complete_space A] [star_module ℂ A] open complex lemma self_adjoint.exp_i_smul_unitary {a : A} (ha : a ∈ self_adjoint A) : exp ℂ (I • a) ∈ unitary A := begin rw [unitary.mem_iff, star_exp], simp only [star_smul, is_R_or_C.star_def, self_adjoint.mem_iff.mp ha, conj_I, neg_smul], rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_left), rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_right), simpa only [add_right_neg, add_left_neg, and_self] using (exp_zero : exp ℂ (0 : A) = 1), end /-- The map from the selfadjoint real subspace to the unitary group. This map only makes sense over ℂ. -/ @[simps] noncomputable def self_adjoint.exp_unitary (a : self_adjoint A) : unitary A := ⟨exp ℂ (I • a), self_adjoint.exp_i_smul_unitary (a.property)⟩ open self_adjoint lemma commute.exp_unitary_add {a b : self_adjoint A} (h : commute (a : A) (b : A)) : exp_unitary (a + b) = exp_unitary a * exp_unitary b := begin ext, have hcomm : commute (I • (a : A)) (I • (b : A)), calc _ = _ : by simp only [h.eq, algebra.smul_mul_assoc, algebra.mul_smul_comm], simpa only [exp_unitary_coe, add_subgroup.coe_add, smul_add] using exp_add_of_commute hcomm, end lemma commute.exp_unitary {a b : self_adjoint A} (h : commute (a : A) (b : A)) : commute (exp_unitary a) (exp_unitary b) := calc (exp_unitary a) * (exp_unitary b) = (exp_unitary b) * (exp_unitary a) : by rw [←h.exp_unitary_add, ←h.symm.exp_unitary_add, add_comm] end star
-- An ATP conjecture must be used with postulates. -- This error is detected by TypeChecking.Rules.Decl. module ATPBadConjecture2 where data Bool : Set where false true : Bool {-# ATP prove Bool #-}
MODULE IOmod !------------------------------------------------------------------- ! ! Module containing definitions of subroutines needed to read ! and write files. ! ! USES: ! netcdf -> netCDF-Fortran lib ! CODEmat -> chooses lname,sname and units from kcode ! ! CONTAINS: ! sraReader -> reads .SRA files ! check -> checks for errors in netCDF lib funcs ! ncgen -> creates netCDF files from SRA files ! getdims -> reads netCDF and gets dims ! ncread -> reads netCDF files ! sragen -> creates SRA files from netCDF files ! ! Created: Mateo Duque Villegas ! Last updated: 17-Nov-2017 ! !------------------------------------------------------------------- IMPLICIT NONE CONTAINS SUBROUTINE sraReader(srafile,nmon,nlon,nlat,hcols,dcols& &,ihead,data) IMPLICIT NONE ! Global namespace. Var description in main program. CHARACTER(LEN=*), INTENT(in) :: srafile INTEGER(KIND=4), INTENT(in) :: nmon INTEGER(KIND=4), INTENT(in) :: nlon INTEGER(KIND=4), INTENT(in) :: nlat INTEGER(KIND=4), INTENT(in) :: hcols INTEGER(KIND=4), INTENT(in) :: dcols INTEGER(KIND=4), DIMENSION(hcols,nmon), INTENT(out) :: ihead REAL(KIND=8), DIMENSION(nlon,nlat,nmon), INTENT(out) :: data ! Local namespace. INTEGER(KIND=4) :: unit = 11 ! Reading unit INTEGER(KIND=4) :: i ! Counter INTEGER(KIND=4) :: operr ! Error variable INTEGER(KIND=4) :: rderr ! Error variable ! Open .SRA file and check for problems. OPEN(unit,file=srafile,form='FORMATTED',status='old',action='read'& &,iostat=operr) IF(operr>0) THEN WRITE(*,'(A)') "sraReader: error: could not open .sra file." CALL EXIT(0) END IF DO i = 1,nmon ! Read header info and check for problems. READ(unit,'(8I10)',iostat=rderr) ihead(:,i) IF(rderr>0) THEN WRITE(*,'(A)') "sraReader: error: could not read .sra file." CALL EXIT(0) END IF ! Because formatting is different in some .SRA files IF (dcols == 4) THEN READ(unit,'(4E16.6)',iostat=rderr) data(:,:,i) IF(rderr>0) THEN WRITE(*,'(A)') "sraReader: error: wrong reading format." CALL EXIT(0) END IF ELSE IF (dcols == 8) THEN READ(unit,'(8F10.8)',iostat=rderr) data(:,:,i) IF(rderr>0) THEN WRITE(*,'(A)') "sraReader: error: wrong reading format." CALL EXIT(0) END IF ELSE WRITE(*,'(A)') "IOmodul: error: unknown reading format." CALL EXIT(0) END IF END DO CLOSE(unit) RETURN END SUBROUTINE sraReader SUBROUTINE check(istatus) USE netcdf IMPLICIT NONE INTEGER(KIND=4), INTENT (IN) :: istatus ! Check for errors everytime run netcdf library stuff IF (istatus /= nf90_noerr) THEN WRITE(*,*) TRIM(ADJUSTL(nf90_strerror(istatus))) CALL EXIT(0) END IF RETURN END SUBROUTINE check SUBROUTINE getdims(ncfile,ndims,nvars,namearr,dimarr) USE netcdf IMPLICIT NONE ! Global namespace CHARACTER(LEN=*), INTENT(IN) :: ncfile INTEGER(KIND=4), INTENT(OUT) :: ndims INTEGER(KIND=4), INTENT(OUT) :: nvars CHARACTER(LEN=50), DIMENSION(3), INTENT(OUT) :: namearr INTEGER(KIND=4), DIMENSION(3), INTENT(OUT) :: dimarr ! Local namespace INTEGER(KIND=4) :: i INTEGER(KIND=4) :: ncid ! Open netCDF and read CALL check(nf90_open(ncfile,nf90_nowrite,ncid)) ! Generic inquire of information CALL check(nf90_inquire(ncid,ndims,nvars)) ! Inquire for dimensions DO i=1,ndims CALL check(nf90_inquire_dimension(ncid,i,namearr(i),dimarr(i))) END DO ! Close netCDF file CALL check(nf90_close(ncid)) RETURN END SUBROUTINE getdims SUBROUTINE ncread(ncfile,ndims,nvars,nmon,nlon,nlat,vtime,lon,lat,data) USE netcdf IMPLICIT NONE ! Global namespace CHARACTER(LEN=*), INTENT(IN) :: ncfile INTEGER(KIND=4), INTENT(IN) :: ndims INTEGER(KIND=4), INTENT(IN) :: nvars INTEGER(KIND=4), INTENT(IN) :: nmon INTEGER(KIND=4), INTENT(IN) :: nlon INTEGER(KIND=4), INTENT(IN) :: nlat INTEGER(KIND=4), DIMENSION(nmon), INTENT(OUT) :: vtime REAL(KIND=8), DIMENSION(nlon), INTENT(OUT) :: lon REAL(KIND=8), DIMENSION(nlat), INTENT(OUT) :: lat REAL(KIND=8), DIMENSION(nlon,nlat,nmon), INTENT(OUT) :: data ! Local namespace INTEGER(KIND=4) :: i INTEGER(KIND=4) :: ncid CHARACTER(LEN=50), DIMENSION(nvars) :: vnames INTEGER(KIND=4), DIMENSION(nvars) :: dtypes INTEGER(KIND=4), DIMENSION(nvars,ndims) :: dids INTEGER(KIND=4), DIMENSION(nvars) :: vids INTEGER(KIND=4), DIMENSION(nvars) :: vndims ! Open netcdf CALL check(nf90_open(ncfile,nf90_nowrite,ncid)) ! Find out the names of variables and their ids and dimensions DO i=1,nvars dids(i,:) = 0 ! Make array 0 to actually see dim ids CALL check(nf90_inquire_variable(ncid,i,vnames(i),dtypes(i)& &,vndims(i),dids(i,:))) CALL check(nf90_inq_varid(ncid,vnames(i),vids(i))) END DO ! Now actually fill correct arrays with correct dims and vars DO i=1,nvars IF(vnames(i) == "time") THEN CALL check(nf90_get_var(ncid,vids(i),vtime)) ELSE IF(vnames(i) == "lat" .OR. vnames(i) == "latitude") THEN CALL check(nf90_get_var(ncid,vids(i),lat)) ELSE IF(vnames(i) == "lon" .OR. vnames(i) == "longitude") THEN CALL check(nf90_get_var(ncid,vids(i),lon)) ELSE CALL check(nf90_get_var(ncid,vids(i),data)) END IF END DO RETURN END SUBROUTINE ncread SUBROUTINE ncgen(ncfile,kcode,vtime,lon,lat,data,nmon,nlon,nlat) USE CODEmat USE netcdf IMPLICIT NONE ! Global namespace. Var description in main program CHARACTER(LEN=*), INTENT(IN) :: ncfile INTEGER(KIND=4), INTENT(IN) :: kcode INTEGER(KIND=4), INTENT(IN) :: nmon INTEGER(KIND=4), INTENT(IN) :: nlon INTEGER(KIND=4), INTENT(IN) :: nlat INTEGER(KIND=4), DIMENSION(nmon), INTENT(IN) :: vtime REAL(KIND=8), DIMENSION(nlon), INTENT(IN) :: lon REAL(KIND=8), DIMENSION(nlat), INTENT(IN) :: lat REAL(KIND=8), DIMENSION(nlon,nlat,nmon), INTENT(IN) :: data ! Local namespace CHARACTER(LEN=50) :: lname CHARACTER(LEN=50) :: timestr CHARACTER(LEN=15) :: units CHARACTER(LEN=10) :: time CHARACTER(LEN=8) :: date CHARACTER(LEN=4) :: sname ! NetCDF stuff INTEGER(KIND=4) :: ncid ! Unit ID for netCDF INTEGER(KIND=4) :: t_dimid ! ID for time dimension INTEGER(KIND=4) :: x_dimid ! ID for X dimension INTEGER(KIND=4) :: y_dimid ! ID for Y dimension INTEGER(KIND=4) :: varid ! ID for data variable INTEGER(KIND=4) :: t_varid ! ID for time variable INTEGER(KIND=4) :: x_varid ! ID for X variable INTEGER(KIND=4) :: y_varid ! ID for Y variable INTEGER(KIND=4), DIMENSION(3) :: dimids ! ID for all dimensions ! Create the netCDF file and assign unit. CALL check(nf90_create(ncfile, NF90_CLOBBER, ncid)) ! Define the dimensions numbers. CALL check(nf90_def_dim(ncid, "time", 0, t_dimid)) CALL check(nf90_def_dim(ncid, "lon", nlon, x_dimid)) CALL check(nf90_def_dim(ncid, "lat", nlat, y_dimid)) ! Define coordinate variable LON and attributes CALL check(nf90_def_var(ncid, "time", NF90_INT, t_dimid,& & t_varid)) CALL check(nf90_put_att(ncid, t_varid, "standard_name","time")) CALL check(nf90_put_att(ncid, t_varid, "units", "months since 001& &-01-01 12:00:00")) CALL check(nf90_put_att(ncid, t_varid, "calendar","360_day")) CALL check(nf90_put_att(ncid, t_varid, "axis","T")) ! Define coordinate variable LON and attributes CALL check(nf90_def_var(ncid, "lon", NF90_REAL, x_dimid, x_varid)) CALL check(nf90_put_att(ncid, x_varid, "standard_name", "longitude")) CALL check(nf90_put_att(ncid, x_varid, "long_name", "longitude")) CALL check(nf90_put_att(ncid, x_varid, "units", "degrees_east")) CALL check(nf90_put_att(ncid, x_varid, "axis", "X")) ! Define coordinate variable LAT and attributes CALL check(nf90_def_var(ncid, "lat", NF90_REAL, y_dimid, y_varid)) CALL check(nf90_put_att(ncid, y_varid, "standard_name", "latitude")) CALL check(nf90_put_att(ncid, y_varid, "long_name", "latitude")) CALL check(nf90_put_att(ncid, y_varid, "units", "degrees_north")) CALL check(nf90_put_att(ncid, y_varid, "axis", "Y")) ! Dims for data array dimids = (/ x_dimid, y_dimid, t_dimid /) ! Get stuff for variable attributes CALL kcoder(kcode,lname,sname,units) ! Define variable CALL check(nf90_def_var(ncid, sname, NF90_DOUBLE, dimids& &, varid)) CALL check(nf90_put_att(ncid, varid, "standard_name", lname)) CALL check(nf90_put_att(ncid, varid, "long_name", sname)) CALL check(nf90_put_att(ncid, varid, "units", units)) CALL check(nf90_put_att(ncid, varid, "code", kcode)) CALL check(nf90_put_att(ncid, varid, "grid_type", "gaussian")) ! Global attributes CALL DATE_AND_TIME(date,time) timestr = "Created on " //date(1:4) //"-"//date(5:6)//"-"//& &date(7:8)//" "//time(1:2)//":"//time(3:4)//":"//time(5:6) CALL check(nf90_put_att(ncid,NF90_GLOBAL, "history", timestr)) CALL check(nf90_put_att(ncid,NF90_GLOBAL, "Conventions", "CF& &-1.0")) ! End definitions CALL check(nf90_enddef(ncid)) ! Write Data CALL check(nf90_put_var(ncid, t_varid, vtime)) CALL check(nf90_put_var(ncid, x_varid, lon)) CALL check(nf90_put_var(ncid, y_varid, lat)) CALL check(nf90_put_var(ncid, varid, data)) CALL check(nf90_close(ncid)) RETURN END SUBROUTINE ncgen SUBROUTINE sragen(srafile,kcode,hcols,dcols,nmon,nlon,nlat,ihead& &,data) IMPLICIT NONE ! Global namespace CHARACTER(LEN=*), INTENT(IN) :: srafile INTEGER(KIND=4), INTENT(IN) :: kcode INTEGER(KIND=4), INTENT(IN) :: hcols INTEGER(KIND=4), INTENT(IN) :: dcols INTEGER(KIND=4), INTENT(IN) :: nmon INTEGER(KIND=4), INTENT(IN) :: nlon INTEGER(KIND=4), INTENT(IN) :: nlat INTEGER(KIND=4), DIMENSION(hcols,nmon), INTENT(IN) :: ihead REAL(KIND=8), DIMENSION(nlon,nlat,nmon), INTENT(IN) :: data ! Local namespace INTEGER(KIND=4) :: i INTEGER(KIND=4) :: operr INTEGER(KIND=4) :: unit = 11 ! Open .SRA file OPEN(unit,file=srafile,form='FORMATTED',action='write',iostat& &=operr) IF(operr>0) THEN WRITE(*,'(A)') "sragen: error: could not create .sra file." CALL EXIT(0) END IF ! Write for every month DO i = 1,nmon WRITE(unit,'(8I10)') ihead(:,i) IF (dcols == 4) THEN WRITE(unit,'(4E16.6)') data(:,:,i) ELSE IF (dcols == 8) THEN ! LSmask is the only with 6 decimal places IF (kcode == 172) THEN WRITE(unit,'(8F10.6)') data(:,:,i) ELSE WRITE(unit,'(8F10.3)') data(:,:,i) END IF END IF END DO RETURN END SUBROUTINE sragen END MODULE IOmod
On returning to London , Wheeler moved into a top @-@ floor flat near Gordon Square with his wife and child . He returned to working for the Royal Commission , examining and cataloguing the historic structures of Essex . In doing so , he produced his first publication , an academic paper on Colchester 's Roman <unk> Gate which was published in the Transactions of the Essex Archaeological Society in 1920 . He soon followed this with two papers in the Journal of Roman Studies ; the first offered a wider analysis of Roman Colchester , while the latter outlined his discovery of the vaulting for the city 's Temple of Claudius which was destroyed by Boudica 's revolt . In doing so , he developed a reputation as a Roman archaeologist in Britain . He then submitted his research on Romano @-@ Rhenish pots to the University of London , on the basis of which he was awarded his Doctorate of Letters ; thenceforth until his knighthood he styled himself as Dr Wheeler . He was unsatisfied with his job in the Commission , unhappy that he was receiving less pay and a lower status than he had had in the army , and so began to seek out alternative employment .
------------------------------------------------------------------------------ -- Simple example of a nested recursive function ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} -- From: Ana Bove and Venanzio Capretta. Nested general recursion and -- partiality in type theory. Vol. 2152 of LNCS. 2001. module FOT.FOTC.Program.Nest.NestConditional where open import FOTC.Base ------------------------------------------------------------------------------ -- The nest function. postulate nest : D → D nest-eq : ∀ n → nest n ≡ (if (iszero₁ n) then zero else (nest (nest (pred₁ n)))) {-# ATP axiom nest-eq #-}
using Base.Test addprocs(2) using PmapProgressMeter using ProgressMeter # just make sure it runs vals = 1:10 p = Progress(length(vals)) @test pmap(x->begin sleep(1); x*2 end, p, vals)[1] == vals[1]*2 # test the do-block syntax pmap(p, vals) do x sleep(1) x*2 end # make sure it runs it kwargs vals = 1:10 p = Progress(length(vals)) @test pmap(x->begin sleep(.1); x*2 end, p, vals, err_stop=true)[1] == vals[1]*2 # try with multiple lists vals2 = 10:-1:1 p = Progress(length(vals)) @test pmap(+, p, vals, vals2) == 11*ones(Int,length(vals)) # make sure callback passing works vals = 1:10 @test pmap((cb, x) -> begin sleep(.1); cb(1); x*2 end, Progress(length(vals)),vals,passcallback=true)[1] == vals[1]*2
All books in good condition. Make me an offer - buyer pays postage if outside Canberra. Are the 'reference' books no good for you to use to build scenarios for other rule sets?
module Examples.ConferenceManager import DepSec.DIO import DepSec.Labeled import DepSec.Ref import Examples.ConferenceLattice %default total -- Examples derived from "Luísa Lourenço and Luís Caires. 2015. -- Dependent Information Flow Types (POPL '15)" -------------------------------------------------------------------------------- -- Types -------------------------------------------------------------------------------- record User where constructor MkUser uid : Uid name : Labeled (U uid) String univ : Labeled (U uid) String email : Labeled (U uid) String record Submission where constructor MkSubmission uid : Uid sid : Sid title : Labeled (A uid sid) String abs : Labeled (A uid sid) String paper : Labeled (A uid sid) String record Review where constructor MkReview uid : Uid sid : Sid PC_only : Labeled (PC uid sid) String review : Labeled (A Top sid) String grade : Labeled (A Top sid) Integer Bot' : Compartment Bot' = Bottom Users : Type Users = SecRef Bot' (List (SecRef Bot' User)) Submissions : Type Submissions = SecRef Bot' (List (SecRef Bot' Submission)) Reviews : Type Reviews = SecRef Bot' (List (SecRef Bot' Review)) -------------------------------------------------------------------------------- -- Hints -------------------------------------------------------------------------------- %hint botFlowsToBot : Bot' `leq` Bot' botFlowsToBot = reflexive Bot' implicit stringToLabeled : Poset labelType => {l : labelType} -> String -> Labeled l String stringToLabeled = label -------------------------------------------------------------------------------- -- Examples -------------------------------------------------------------------------------- -- Example 2.1 assignReviewer : Reviews -> Uid -> Sid -> DIO Bot' () assignReviewer revRef uid1 sid1 = do reviews <- unlabel !(readRef revRef) new <- (newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label (MkReview uid1 sid1 "" "" (label 0)))) let newreviews = label (new :: reviews) writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} revRef newreviews -- Example 2.2 viewAuthorPapers : Submissions -> (uid1 : Uid) -> DIO Bot' (List (sub : Submission ** uid1 = (uid sub))) viewAuthorPapers subRef uid1 = do submissions <- unlabel !(readRef subRef) findPapers submissions where findPapers : (List (SecRef Bot' Submission)) -> DIO Bot' (List (sub : Submission ** uid1 = (uid sub))) findPapers [] = pure [] findPapers (x :: xs) = do sub <- unlabel !(readRef x) case decEq (uid sub) uid1 of (Yes prf) => pure $ (sub ** (sym prf)) :: !(findPapers xs) (No _) => findPapers xs -- Example 2.3 viewAssignedPapers : Reviews -> Submissions -> Uid -> DIO Bot' (List (SecRef Bot' Submission)) viewAssignedPapers reviewsRef subsRef id = do reviews <- unlabel !(readRef reviewsRef) subs <- unlabel !(readRef subsRef) sids <- getSids reviews findPapers sids subs where getSids : List (SecRef (U Bot) Review) -> DIO Bot' $ List Sid getSids [] = pure [] getSids (x :: xs) = do rev <- unlabel !(readRef x) case decEq (uid rev) id of (Yes _) => pure $ (sid rev) :: !(getSids xs) (No _) => getSids xs findPapers : List Sid -> List (SecRef Bot' Submission) -> DIO Bot' (List (SecRef Bot' Submission)) findPapers xs [] = pure [] findPapers xs (x :: ys) = do sub <- unlabel !(readRef x) case elemBy (==) (sid sub) xs of True => pure $ x :: !(findPapers xs ys) False => findPapers xs ys -- Example 2.4 emphasizeTitle : Uid -> Sid -> Submissions -> DIO Bot' () emphasizeTitle uid1 sid1 subsRef = do subs <- unlabel !(readRef subsRef) ltitle <- getTitleOfSub subs lNewTitle <- appendToTitle "!" ltitle searchAndReplaceTitle lNewTitle subs pure () where searchAndReplaceTitle : Labeled (A uid1 sid1) String -> List (SecRef Bot' Submission) -> DIO Bot' () searchAndReplaceTitle newTitle [] = pure () searchAndReplaceTitle newTitle (x :: xs) = do sub <- unlabel !(readRef x) case (decEq (uid sub) uid1, decEq (sid sub) sid1) of (Yes prf1, Yes prf2) => let abs'= abs sub paper' = paper sub title' : Labeled (A (uid sub) (sid sub)) String = rewrite prf1 in rewrite prf2 in newTitle newSub = MkSubmission (uid sub) (sid sub) title' abs' paper' newlsub : Labeled Bot' Submission = label newSub in writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} x newlsub (_ , _ ) => searchAndReplaceTitle newTitle xs getTitleOfSub : List (SecRef Bot' Submission) -> DIO Bot' (Labeled (A uid1 sid1) String) getTitleOfSub [] = pure "" getTitleOfSub (x :: xs) = do sub <- unlabel !(readRef x) case (decEq (uid sub) uid1, decEq (sid sub) sid1) of (Yes prf1, Yes prf2) => rewrite sym $ prf1 in rewrite sym $ prf2 in pure $ title sub (_,_) => getTitleOfSub xs appendToTitle : String -> Labeled (A x y) String -> DIO Bot' (Labeled (A x y) String) appendToTitle {x} {y} str lstr = do let oldStrDIO : DIO (A x y) String = unlabel {flow = reflexive (A x y)} lstr let newStrDIO : DIO (A x y) String = do pure $ (!oldStrDIO ++ str) plug newStrDIO -- Example 2.5 addCommentSubmission : Reviews -> (uid1 : Uid) -> (sid1 : Sid) -> (comment : Labeled (A uid1 sid1) String) -> DIO Bot' () addCommentSubmission revsRef uid1 sid1 comment = do revs <- unlabel !(readRef revsRef) addComment revs where addComment : List (SecRef (U Bot) Review) -> DIO Bot' () addComment [] = pure () addComment (x :: xs) = do rev <- unlabel !(readRef x) case (decEq (uid rev) uid1, decEq (sid rev) sid1) of (Yes prf1, Yes prf2) => let review' = review rev grade' = grade rev PC_only' : Labeled (PC (uid rev) (sid rev)) String = rewrite prf1 in rewrite prf2 in relabel {flow=A_leq_PC {uid1}} comment newRev = MkReview (uid rev) (sid rev) PC_only' review' grade' newlRev : Labeled Bot' Review = label newRev in writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} x newlRev _ => addComment xs -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- User1 : User User1 = MkUser (Nat 1) "Alice" "Foo University" "[email protected]" User2 : User User2 = MkUser (Nat 2) "Bob" "Bar University" "[email protected]" User3 : User User3 = MkUser (Nat 3) "Chuck" "Baz University" "[email protected]" Paper1 : Submission Paper1 = MkSubmission (Nat 1) (Nat 1) "IFC in Idris" "Dependent types seems good?" "QED" Paper2 : Submission Paper2 = MkSubmission (Nat 2) (Nat 2) "Haskell is old fashioned" "Why not more Idris?" "QED" Paper3 : Submission Paper3 = MkSubmission (Nat 1) (Nat 3) "Messing with Idris" "Idris is fun!" "QED" Review1 : Review Review1 = MkReview (Nat 3) (Nat 1) "Pretty good" "That's okay" (label 12) Review2 : Review Review2 = MkReview (Nat 3) (Nat 2) "Yay!" "OK!" (label 12) initUsers : DIO Bot' Users initUsers = newRef {flow=reflexive Bot'} {flow'=reflexive Bot'} (label Nil) initSubmissions : DIO Bot' Submissions initSubmissions = newRef (label Nil) initReviews : DIO Bot' Reviews initReviews = newRef {flow=reflexive Bot'} {flow'=reflexive Bot'} (label Nil) dummyDB : Users -> Submissions -> Reviews -> DIO Bot' () dummyDB users submissions reviews= do user1 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label User1) user2 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label User2) let newusers = label {l=Bot'} [user1, user2] writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} users newusers sub1 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label Paper1) sub2 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label Paper2) sub3 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label Paper3) let newsubmissions = label {l=Bot'} [sub1, sub2, sub3] writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} submissions newsubmissions rev1 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label Review1) rev2 <- newRef {l = Bot'} {l' = Bot'} {l'' = Bot'} (label Review2) let newreviews = label {l=Bot'} [rev1, rev2] writeRef {l = Bot'} {l' = Bot'} {l'' = Bot'} reviews newreviews -------------------------------------------------------------------------------- -- Main -------------------------------------------------------------------------------- main : IO () main = do putStrLn "Starting conference manager ..." run $ do users <- initUsers submissions <- initSubmissions reviews <- initReviews dummyDB users submissions reviews assignReviewer reviews (Nat 42) (Nat 1) addCommentSubmission reviews (Nat 2) (Nat 2) "Cool paper!" reviews' <- unlabel !(readRef reviews) lift $ putStrLn $ "No. of reviews: " ++ (cast $ length reviews') alice <- viewAuthorPapers submissions (Nat 1) lift $ putStrLn $ "No. of submissions from Alice: " ++ (cast $ length alice) papersToReview <- viewAssignedPapers reviews submissions (Nat 3) lift $ putStrLn $ "No. of papers to review Chuck: " ++ (cast $ length papersToReview) pure () putStrLn "Shutting down conference manager ..."
/** * Simple and fast kmeans-implementation making use of multithreading. * * Author: Anders Bennehag * * The MIT License (MIT) * * Copyright (c) 2016 Anders Bennehag * */ #ifndef FASTKMEANS_H_ #define FASTKMEANS_H_ #include <gsl/gsl_matrix.h> int fkm_kmeans(const gsl_matrix* points, gsl_matrix* clusters, size_t max_iter, int num_threads); gsl_matrix* fkm_matrix_load(FILE* fout); int fkm_matrix_save(FILE* fout, gsl_matrix* mat); #define WHERESTR "[%s:%d]: " #define WHEREARG __FILE__, __LINE__ #define DEBUGPRINT2(...) fprintf(stderr, __VA_ARGS__) #define FKM_LOGFMT(_fmt, ...) DEBUGPRINT2(WHERESTR _fmt "\n", WHEREARG, __VA_ARGS__) #define FKM_LOG(_s) DEBUGPRINT2(WHERESTR "%s\n", WHEREARG, _s) #define FKM_LOGTYPE(_tp, _s) DEBUGPRINT2(WHERESTR "%s: %s" "\n", WHEREARG, _tp, _s) #define FKM_LOGTYPEFMT(_tp, _fmt, ...) DEBUGPRINT2(WHERESTR "%s: " _fmt "\n", WHEREARG, _tp, __VA_ARGS__) #if (ISDEBUG + 0) #define FKM_DEBUGFMT(_fmt, ...) FKM_LOGTYPEFMT("DEBUG", _fmt, __VA_ARGS__) #define FKM_DEBUG(_s) FKM_LOGTYPE("DEBUG", _s) #else #define FKM_DEBUGFMT(...) #define FKM_DEBUG(...) #endif #define FKM_INFOFMT(_fmt, ...) FKM_LOGTYPEFMT("INFO", _fmt, __VA_ARGS__) #define FKM_WARNFMT(_fmt, ...) FKM_LOGTYPEFMT("WARN", _fmt, __VA_ARGS__) #define FKM_ERRORFMT(_fmt, ...) FKM_LOGTYPEFMT("ERROR", _fmt, __VA_ARGS__) #define FKM_INFO(_s) FKM_LOGTYPE("INFO", _s) #define FKM_WARN(_s) FKM_LOGTYPE("WARN", _s) #define FKM_ERROR(_s) FKM_LOGTYPE("ERROR", _s) #endif
universes u v /- This unit is about the functor. A functor is a collection of objects (such as lists or options over some type, α) with a function, map : (α → β) → f α → f β, overloaded for each specified type constructors, f, lifting the (α → β) function to an (f α → f β) function. Map lifts functions on elements to become functions on data structures that can contain such elements. It converts a data structure containing such α values into an isomorphic data structure amy α valuesreplaced by the β values obtained by applying the (α → β) function to each α value.+ -/ /- We define a simple "binary tree of α values" data type for use later in this file. Tuck it away in memory for now. -/ inductive tree (α : Type u) | empty : tree | node (a : α) (left right : tree) : tree def aTree := tree.node 0 (tree.node 1 tree.empty tree.empty) (tree.node 2 tree.empty tree.empty) namespace hidden /- We've seen a function for mapping a (different) function over a list. -/ def list_map {α : Type u} {β : Type v} : (α → β) → list α → list β | f [] := [] | f (h::t) := (f h)::(list_map f t) /- But we can imagine analogous functions over any kind of structure that contains objects of some arbitrary other type. For example, here is a function for mapping a function, f, over an object of type (option α), for any type α. -/ def option_map {α : Type u} {β : Type v} : (α → β) → option α → option β | f none := none | f (some a) := some (f a) /- As a third example, consider mapping over trees. -/ /- We can also write a function for mapping trees of α values to trees of β values in an analogous manner. -/ def tree_map {α : Type u} {β : Type v} : (α → β) → (tree α) → (tree β) | f tree.empty := tree.empty | f (tree.node a l r) := tree.node (f a) (tree_map f l) (tree_map f r) /- What we're seeing are different implementations of "the same idea" for mapping an element-level mapping function over a various types of data structures containing such elements. The implementations of these functions differ significantly; but look at their types. What we see is that they're identical but for the types of containers we envision transforming by the application of element-level functions to their contents. def list_map {α : Type u} {β : Type v} : (α → β) → (list α) → (list β) def option_map {α : Type u} {β : Type v} : (α → β) → (option α) → (option β) def tree_map {α : Type u} {β : Type v} : (α → β) → (tree α) → (tree β) As usual, we can generalize by introducing a new parameter. But what is its type? Well, question: What is the type of list? Of option? Of tree? Answer: Each is Type u → Type u We can't just add a parameter, m : Type u → Type u: the *implementations* differ We have a common abstraction but with different implementations for different types Ad hoc polymorphism, aka, overloading, aka generics, to the rescue! The new pattern that we see here is that the parameter of the typeclass is no longer a concrete type (such as bool or nat), but a polymorphic type builder, i.e., a value such as list α, option α, or tree α (each of type, Type → Type) -/ class functor (m : Type u → Type v) := (map : ∀ {α β : Type u}, (α → β) → m α → m β) -- (law1 : _) -- how mapping identify function works -- (law2 : _) -- how mapping composition works /- As a shorthand notaton, we enable the developer to write f<$>l as an expression that reduces to f mapped over l. -/ local infixr ` <$> `:100 := functor.map /- Finally, we instantiate the typeclass once for each "type builder," such as list, option, or tree, over which we want to be able to map functions using this notation. -/ instance list_mapper : functor list := ⟨ @list_map ⟩ instance option_mapper : functor option := ⟨ @option_map ⟩ instance tree_mapper : functor tree := ⟨ @tree_map ⟩ /- We now have an overloaded map operator (in Haskell it's called fmap) that can be used to map functions over lists, options, and trees. We can now view lists, options, and trees as "functors" in the functional programming (rather than category theory) sense of the term: that is, as structured containers for objects of some source type that can be "mapped" to corresponding structured containers for objects of some destination type. -/ #reduce nat.succ <$> [] #reduce nat.succ <$> [1,2,3] #reduce string.length <$> ["Hello", "Lean!!!"] #reduce nat.succ <$> option.none #reduce nat.succ <$> option.some 0 #reduce nat.succ <$> (tree.empty) #reduce nat.succ <$> aTree #check @functor /- What we've done is to make list, option, and tree into "members of the functor typeclass," thereby overloading the operator that the typeclass defines for each of these otherwise unrelated types. -/ end hidden /- Now let's have a quick look at Lean's functor typeclass. It's just like ours but it adds a second function that is to be overloaded for each type (such as list or option) in the functor typeclass. -/ #check @functor #print functor /- class functor (f : Type u → Type v) : Type (max (u+1) v) := (map : Π {α β : Type u}, (α → β) → f α → f β) (map_const : Π {α β : Type u}, α → f β → f α := λ α β, map ∘ const β) The const function (polymorphic in α and β) takes a value, a, of type α, and yields a function that takes any value of type β and returns a. The function, map ∘ const β, thus takes any value, a, of type α, and returns a function that converts a list of β values into a list of a values (not just α values, but constant a values). def const (β : Sort u₂) (a : α) : β → α := λ x, a -/ #check @list.map instance : functor list := ⟨ @list.map, _ ⟩ def list_map_const {α β : Type u} : α → list β → list α | a [] := [] | a (h::t) := a::list_map_const a t -- E.g., replace each natural number in list with tt #eval list_map_const tt [1,2,3] instance list_functor : functor list := ⟨ @list.map, @list_map_const ⟩ #check @option.map def option_map_const {α β : Type u} : α → option β → option α | a option.none := option.none | a (option.some b) := option.some a instance : functor option := ⟨ @option.map, @option_map_const ⟩ #reduce nat.succ <$> [1,2,3] #reduce ff <$ [1,2,3] #reduce [1,2,3] $> ff /- One of the ways in which we can use the functor typeclass is in defining generic versions of concrete functions. For example, consider the simple increment function on natural numbers. -/ def inc := λ (n : nat), n + 1 /- We've seen how we can map such functions over lists of natural numbers. And, with this capability, we can define a new function, here called inc_list_nat, that maps the inc function over lists of nats. We can say that we have lifted the inc function to be applicable to lists of nats. -/ def inc_list_nat ( l : list nat) := list.map inc l /- Challenge: Generalize from this idea to write a generic (ad hoc polymorphic) function, inc', that lifts inc to be be applicable to objects of any "functorial" type over int. Given what we've got so far, for example, you should be able to apply inc_m_nat not only to objects of type list nat, but also option nat, tree nat, and so on, for any type constructor parameterized by the type, nat. -/ def inc' {f : Type → Type} [functor f] (i : f nat) : f nat := functor.map inc i -- a generic increment operation on functorial data structures containing nats example : inc' [1,2,3] = [2,3,4] := rfl example : inc' (some 1) = some 2 := rfl instance : functor tree := ⟨ @hidden.tree_map, _ ⟩ -- you can fill in second field example : inc' aTree = tree.node 1 (tree.node 2 tree.empty tree.empty) (tree.node 3 tree.empty tree.empty) := rfl /- Generalize this function, from mapping *inc* over any functorial context (data structure!) over values of type nat, to mapping *any function* of type α → β over any functorial context/container over values of type, α. -/ def map_f {α β : Type u} {f : Type u → Type v} [functor f] : (α → β) → f α → f β | h i := functor.map h i /- Examples: -/ def l_str := ["Hello", " Lean!"] def o_str := some "Hello" def t_str := tree.node "Hello" (tree.node " There!" tree.empty tree.empty) tree.empty #reduce map_f string.length l_str #reduce map_f string.length o_str #reduce map_f string.length t_str /- Finally, let's look at the type of map_f to get a set of its nature. In particular, look at this: (α → β) → f α → f β. What we've done is to lift a "pure" function, h : α → β to one that takes a "functorial" object, i : f α, and returns a functorial object of type f β. And by the magic of typeclass resolution, we've overloaded this function for three functorial types, namely list, option, and tree. -/
# verify that our README.md examples are in working order doc = Spiderman.http_get("http://en.wikipedia.org/") news_headlines = text(select(css"#mp-itn b a", doc)) # most of the value in this test is the above code running... # but it's still nice to know the query still works. @test length(news_headlines) > 1 doc = Spiderman.http_get("https://news.ycombinator.com/") scores = select(css".score", doc) hrefs = parent(select(css".deadmark", doc)) items = [] for i=1:length(scores) score = parse(Int, replace(text(scores[i]), " points", "")) story_title = text(select(css"a", hrefs[i]))[1] story_href = getattr(select(css"a", hrefs[i])[1], "href") comment_href = getattr(select(css"a", parent(scores[i]))[end], "href") push!(items, (score, story_title, story_href, comment_href)) end @test length(items) > 2
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!! !!!! MIT License !!!! !!!! ParaMonte: plain powerful parallel Monte Carlo library. !!!! !!!! Copyright (C) 2012-present, The Computational Data Science Lab !!!! !!!! This file is part of the ParaMonte library. !!!! !!!! Permission is hereby granted, free of charge, to any person obtaining a !!!! copy of this software and associated documentation files (the "Software"), !!!! to deal in the Software without restriction, including without limitation !!!! the rights to use, copy, modify, merge, publish, distribute, sublicense, !!!! and/or sell copies of the Software, and to permit persons to whom the !!!! Software is furnished to do so, subject to the following conditions: !!!! !!!! The above copyright notice and this permission notice shall be !!!! included in all copies or substantial portions of the Software. !!!! !!!! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, !!!! EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF !!!! MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. !!!! IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, !!!! DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR !!!! OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE !!!! OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. !!!! !!!! ACKNOWLEDGMENT !!!! !!!! ParaMonte is an honor-ware and its currency is acknowledgment and citations. !!!! As per the ParaMonte library license agreement terms, if you use any parts of !!!! this library for any purposes, kindly acknowledge the use of ParaMonte in your !!!! work (education/research/industry/development/...) by citing the ParaMonte !!!! library as described on this page: !!!! !!!! https://github.com/cdslaborg/paramonte/blob/master/ACKNOWLEDGMENT.md !!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! module Test_Decoration_mod !use, intrinsic :: iso_fortran_env, only: output_unit use Test_mod, only: Test_type use Constants_mod, only: IK use Decoration_mod implicit none type(Test_type) :: Test !*********************************************************************************************************************************** !*********************************************************************************************************************************** contains !*********************************************************************************************************************************** !*********************************************************************************************************************************** subroutine test_Decoration() implicit none type(Decoration_type) :: Decor Test = Test_type(moduleName=MODULE_NAME) if (Test%Image%isFirst) call Test%testing("Decoration_type") if (Test%isDebugMode .and. Test%Image%isFirst) then allocate(Decor%List(4)) Decor%List(1)%record = "Have you asked yourself:" Decor%List(2)%record = "Why does the Universe bother to exist?" Decor%List(3)%record = "What is the origin of mass and matter?" Decor%List(4)%record = "What is the origin of life?" call Decor%writeDecoratedList(Decor%List) Decor%text = "\n\n" // & Decor%List(1)%record // "\n\n" // & Decor%List(2)%record // "\n\n" // & Decor%List(3)%record // "\n\n" // & Decor%List(4)%record // "\n\n\n" call Decor%writeDecoratedText( Decor%text & , newLine="\n" & , width = 32 & , symbol="&" & , thicknessHorz=4 & , thicknessVert=2 & , marginTop=2 & , marginBot=1 & ) call write(Test%outputUnit,1,0,1, "Here is the output of drawLine('HelloWorld!'):" ) call write(Test%outputUnit,1,0,1, drawLine(symbol="HelloWorld!",width=132) ) call write(Test%outputUnit,1,0,1, "Here is the output of sandwich():" ) call write(Test%outputUnit,1,0,1, sandwich() ) call write(Test%outputUnit,1,0,1, "Here is the output of sandwich( text='Hello World!', symbol='@', width=20 ) :" ) call write(Test%outputUnit,1,0,1, sandwich(text='Hello World!',symbol='@',width=20) ) call write(Test%outputUnit,1,0,1, "Here is the output of sandwich( text='Hello World!', symbol='@', width=10 ) :" ) call write(Test%outputUnit,1,0,1, sandwich(text='Hello World!',symbol='@',width=10) ) call write(Test%outputUnit,1,0,1, "Here is the output of sandwich( text='Hello World!', symbol='@', width=10 ) :" ) call write(Test%outputUnit,1,0,1, sandwich(text='Hello World!',symbol='@',width=5) ) write(Test%outputUnit,"(A)") end if !Test%assertion = .true. !call Test%verify() call Test%skipping() call Test%finalize() end subroutine test_Decoration !*********************************************************************************************************************************** !*********************************************************************************************************************************** end module Test_Decoration_mod
module Test.Assertions %access export %default total describe : String -> IO () -> IO () describe label body = do putStrLn "" putStr label body assert : Bool -> Lazy (List String) -> IO () assert False report = do putStrLn "*FAIL*" traverse_ (\x => putStrLn (" " ++ x)) report assert True report = putStr "." shouldBe : (Eq a, Show a) => a -> a -> IO () shouldBe a expected = assert (a == expected) [ "Expected " ++ show expected, "But got " ++ show a ] shouldShow : Show a => a -> String -> IO () shouldShow a expected = assert (show a == expected) [ "Expected to show " ++ expected, "But got " ++ show a ] shouldSatisfy : Show a => a -> (a -> Bool) -> IO () shouldSatisfy a pred = assert (pred a) [ "Expectation unsatisfied: " ++ show a ] castIdentical : (Cast a b, Cast b a, Eq a, Eq b) => (a, b) -> Bool castIdentical (a, b) = cast a == b && cast b == a shouldBe' : (Eq a, Show a) => IO a -> a -> IO () shouldBe' a b = a >>= (`shouldBe` b) shouldShow' : Show a => IO a -> String -> IO () shouldShow' a b = a >>= (`shouldShow` b) shouldSatisfy' : Show a => IO a -> (a -> Bool) -> IO () shouldSatisfy' a b = a >>= (`shouldSatisfy` b)
If $p$ and $q$ are polynomials such that $p(x) = 0$ implies $q(x) = 0$, then $p$ divides $q^n$ if $p$ has degree $n$.
theory Exercise4 imports Main begin inductive ev :: "nat \<Rightarrow> bool" where ev0: "ev 0" | evSS: "ev n \<Longrightarrow> ev (Suc (Suc n))" lemma "\<not> ev (Suc (Suc (Suc 0)))" (is "\<not> ?EVEN3") proof assume "?EVEN3" hence "ev (Suc 0)" by cases thus False by cases qed end
%% test modulate for all oasis functions. col = {[0 114 178],[0 158 115], [213 94 0],[230 159 0],... [86 180 233], [204 121 167], [64 224 208], [240 228 66]}; % colors plot_cvx = false; %% example 3: foopsi, convolution kernel g = [1.7, -0.712]; % AR coefficient noise = 1; T = 3000; framerate = 30; firerate = 0.5; b = 0; % baseline N = 20; % number of trials seed = 3; % seed for genrating random variables [Y, trueC, trueS] = gen_data(g, noise, T, framerate, firerate, b, N, seed); y = Y(1,:); true_c = trueC(1,:); %#ok<*NASGU> true_s = trueS(1,:); taus = ar2exp(g); w = 200; taus = ar2exp(g); ht = exp2kernel(taus, w); % case 1: use the difference of two exponential functions to construct a % kernel lambda = 0.1; [c_oasis, s_oasis] = deconvolveCa(y, 'exp2', taus, 'foopsi', 'lambda', lambda, ... 'shift', 100, 'window', 200); %#ok<*ASGLU> figure('name', 'FOOPSI, exp2, known: g, lambda', 'papersize', [15, 4]); show_results; % case 2: use the kernel directly lambda = 0.1; [c_oasis, s_oasis] = deconvolveCa(y, 'kernel', ht, 'foopsi', 'lambda', ... lambda, 'shift', 100, 'window', 200); %#ok<*ASGLU> figure('name', 'FOOPSI, kernel, known: g, lambda', 'papersize', [15, 4]); show_results; %% case 3: estimate the time constants lambda = 0; taus = ar2exp(g); [c_oasis, s_oasis, options] = deconvolveCa(y, 'exp2', 'foopsi', 'lambda', lambda, ... 'shift', 100, 'window', 200, 'smin', 0.5); %#ok<*ASGLU> figure('name', 'FOOPSI, exp2, known: g, lambda', 'papersize', [15, 4]); show_results;
= = = Fragrance = = =
module Main import Language.Reflection %language ElabReflection -- A performance test - previously this was slowing down hugely due to -- quoting back HNFs on >>=, and as the environment gets bigger, the -- environment of holes gets bigger and bigger, so quoting can start to take -- far too long perftest : Elab () perftest = do logMsg "" 0 "Progress" traverse (traverse (logMsg "" 1 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 2 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 3 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 4 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 5 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 6 . show)) [[the Int 1..10]] -- minor difference logMsg "" 0 "Progress" traverse (traverse (logMsg "" 7 . show)) [[the Int 1..10]] -- 0.3s logMsg "" 0 "Progress" traverse (traverse (logMsg "" 8 . show)) [[the Int 1..10]] -- 0.4s logMsg "" 0 "Progress" traverse (traverse (logMsg "" 9 . show)) [[the Int 1..10]] -- 0.5s logMsg "" 0 "Progress" traverse (traverse (logMsg "" 10 . show)) [[the Int 1..10]] -- 1.5s logMsg "" 0 "Progress" traverse (traverse (logMsg "" 11 . show)) [[the Int 1..10]] -- 4s logMsg "" 0 "Progress" traverse (traverse (logMsg "" 12 . show)) [[the Int 1..10]] -- 13s pure () %runElab perftest
/** * * @file zcgels.c * * PLASMA computational routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Emmanuel Agullo * @date 2010-11-15 * @precisions mixed zc -> ds * **/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <lapacke.h> #include "common.h" #define PLASMA_zlag2c(_descA, _descSB) \ plasma_parallel_call_4(plasma_pzlag2c, \ PLASMA_desc, (_descA), \ PLASMA_desc, (_descSB), \ PLASMA_sequence*, sequence, \ PLASMA_request*, request) #define PLASMA_clag2z(_descSA, _descB) \ plasma_parallel_call_4(plasma_pclag2z, \ PLASMA_desc, (_descSA), \ PLASMA_desc, (_descB), \ PLASMA_sequence*, sequence, \ PLASMA_request*, request) #define PLASMA_zlange(_norm, _descA, _result, _work) \ _result = 0; \ plasma_parallel_call_6(plasma_pzlange, \ PLASMA_enum, (_norm), \ PLASMA_desc, (_descA), \ double*, (_work), \ double*, &(_result), \ PLASMA_sequence*, sequence, \ PLASMA_request*, request); #define PLASMA_zlacpy(_descA, _descB) \ plasma_parallel_call_5(plasma_pzlacpy, \ PLASMA_enum, PlasmaUpperLower, \ PLASMA_desc, (_descA), \ PLASMA_desc, (_descB), \ PLASMA_sequence*, sequence, \ PLASMA_request*, request) #define PLASMA_zgeadd(_alpha, _descA, _descB) \ plasma_parallel_call_5(plasma_pzgeadd, \ PLASMA_Complex64_t, (_alpha), \ PLASMA_desc, (_descA), \ PLASMA_desc, (_descB), \ PLASMA_sequence*, sequence, \ PLASMA_request*, request) /***************************************************************************//** * * @ingroup PLASMA_Complex64_t * * PLASMA_zcgels - Solves overdetermined or underdetermined linear systems involving an M-by-N * matrix A using the QR or the LQ factorization of A. It is assumed that A has full rank. * The following options are provided: * * # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined * system, i.e., solve the least squares problem: minimize || B - A*X ||. * * # trans = PlasmaNoTrans and M < N: find the minimum norm solution of an underdetermined * system A * X = B. * * Several right hand side vectors B and solution vectors X can be handled in a single call; * they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS * solution matrix X. * * PLASMA_zcgels first attempts to factorize the matrix in COMPLEX and use this * factorization within an iterative refinement procedure to produce a * solution with COMPLEX*16 normwise backward error quality (see below). * If the approach fails the method switches to a COMPLEX*16 * factorization and solve. * * The iterative refinement is not going to be a winning strategy if * the ratio COMPLEX performance over COMPLEX*16 performance is too * small. A reasonable strategy should take the number of right-hand * sides and the size of the matrix into account. This might be done * with a call to ILAENV in the future. Up to now, we always try * iterative refinement. * * The iterative refinement process is stopped if ITER > ITERMAX or * for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX * where: * * - ITER is the number of the current iteration in the iterative refinement process * - RNRM is the infinity-norm of the residual * - XNRM is the infinity-norm of the solution * - ANRM is the infinity-operator-norm of the matrix A * - EPS is the machine epsilon returned by DLAMCH('Epsilon'). * * Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed. * * The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively. * * We follow Bjorck's algorithm proposed in "Iterative Refinement of Linear * Least Squares solutions I", BIT, 7:257-278, 1967. * ******************************************************************************* * * @param[in] trans * Intended usage: * = PlasmaNoTrans: the linear system involves A; * = PlasmaConjTrans: the linear system involves A**H. * Currently only PlasmaNoTrans is supported. * * @param[in] M * The number of rows of the matrix A. M >= 0. * * @param[in] N * The number of columns of the matrix A. N >= 0. * * @param[in] NRHS * The number of right hand sides, i.e., the number of columns of the matrices B and X. * NRHS >= 0. * * @param[in] A * The M-by-N matrix A. This matrix is not modified. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,M). * * @param[in] B * The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified. * * @param[in] LDB * The leading dimension of the array B. LDB >= MAX(1,M,N). * * @param[out] X * If return value = 0, the solution vectors, stored columnwise. * if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual * sum of squares for the solution in each column is given by the sum of squares of the * modulus of elements N+1 to M in that column; * if M < N, rows 1 to N of X contain the minimum norm solution vectors; * * @param[in] LDX * The leading dimension of the array X. LDX >= MAX(1,M,N). * * @param[out] ITER * The number of the current iteration in the iterative refinement process * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************* * * @sa PLASMA_zcgels_Tile * @sa PLASMA_zcgels_Tile_Async * @sa PLASMA_dsgels * @sa PLASMA_zgels * ******************************************************************************/ int PLASMA_zcgels(PLASMA_enum trans, int M, int N, int NRHS, PLASMA_Complex64_t *A, int LDA, PLASMA_Complex64_t *B, int LDB, PLASMA_Complex64_t *X, int LDX, int *ITER) { int i, j; int NB, NBNB, MT, NT, NTRHS; int status; PLASMA_desc descA; PLASMA_desc descB; PLASMA_desc *descT; PLASMA_desc descX; plasma_context_t *plasma; PLASMA_sequence *sequence = NULL; PLASMA_request request = PLASMA_REQUEST_INITIALIZER; plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA_zcgels", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } *ITER = 0; /* Check input arguments */ if (trans != PlasmaNoTrans && trans != PlasmaConjTrans && trans != PlasmaTrans ) { plasma_error("PLASMA_zcgels", "illegal value of trans"); return -1; } if (trans != PlasmaNoTrans) { plasma_error("PLASMA_zcgels", "only PlasmaNoTrans supported"); return PLASMA_ERR_NOT_SUPPORTED; } if (M < 0) { plasma_error("PLASMA_zcgels", "illegal value of M"); return -2; } if (N < 0) { plasma_error("PLASMA_zcgels", "illegal value of N"); return -3; } if (NRHS < 0) { plasma_error("PLASMA_zcgels", "illegal value of NRHS"); return -4; } if (LDA < max(1, M)) { plasma_error("PLASMA_zcgels", "illegal value of LDA"); return -6; } if (LDB < max(1, max(M, N))) { plasma_error("PLASMA_zcgels", "illegal value of LDB"); return -9; } if (LDX < max(1, max(M, N))) { plasma_error("PLASMA_zcgels", "illegal value of LDX"); return -10; } /* Quick return */ if (min(M, min(N, NRHS)) == 0) { for (i = 0; i < max(M, N); i++) for (j = 0; j < NRHS; j++) B[j*LDB+i] = 0.0; return PLASMA_SUCCESS; } /* Tune NB & IB depending on M, N & NRHS; Set NBNB */ status = plasma_tune(PLASMA_FUNC_ZCGELS, M, N, NRHS); if (status != PLASMA_SUCCESS) { plasma_error("PLASMA_zcgels", "plasma_tune() failed"); return status; } /* Set MT, NT & NTRHS */ NB = PLASMA_NB; NBNB = NB*NB; NT = (N%NB==0) ? (N/NB) : (N/NB+1); MT = (M%NB==0) ? (M/NB) : (M/NB+1); NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1); printf("M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\n", M, N, NRHS, NB, MT, NT, NTRHS); plasma_sequence_create(plasma, &sequence); descA = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, M, N, 0, 0, M, N); if (M >= N) { descB = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, M, NRHS, 0, 0, M, NRHS); descX = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, M, NRHS, 0, 0, M, NRHS); } else { descB = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, N, NRHS, 0, 0, N, NRHS); descX = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, N, NRHS, 0, 0, N, NRHS); } /* DOUBLE PRECISION INITIALIZATION */ /* Allocate memory for matrices in block layout */ if (plasma_desc_mat_alloc(&descA) || plasma_desc_mat_alloc(&descB) || plasma_desc_mat_alloc(&descX)) { plasma_error("PLASMA_zcgels", "plasma_shared_alloc() failed"); plasma_desc_mat_free(&descA); plasma_desc_mat_free(&descB); plasma_desc_mat_free(&descX); return PLASMA_ERR_OUT_OF_RESOURCES; } plasma_parallel_call_5(plasma_pzlapack_to_tile, PLASMA_Complex64_t*, A, int, LDA, PLASMA_desc, descA, PLASMA_sequence*, sequence, PLASMA_request*, &request); plasma_parallel_call_5(plasma_pzlapack_to_tile, PLASMA_Complex64_t*, B, int, LDB, PLASMA_desc, descB, PLASMA_sequence*, sequence, PLASMA_request*, &request); /* Allocate workspace */ PLASMA_Alloc_Workspace_zgels_Tile(M, N, &descT); /* Call the native interface */ status = PLASMA_zcgels_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER, sequence, &request); if (status == PLASMA_SUCCESS) { plasma_parallel_call_5(plasma_pztile_to_lapack, PLASMA_desc, descX, PLASMA_Complex64_t*, X, int, LDX, PLASMA_sequence*, sequence, PLASMA_request*, &request); } plasma_dynamic_sync(); PLASMA_Dealloc_Handle_Tile(&descT); plasma_sequence_destroy(plasma, sequence); plasma_desc_mat_free(&descA); plasma_desc_mat_free(&descB); plasma_desc_mat_free(&descX); return status; } /***************************************************************************//** * * @ingroup PLASMA_Complex64_t_Tile * * PLASMA_zcgels_Tile - Solves overdetermined or underdetermined linear system of equations * using the tile QR or the tile LQ factorization and mixed-precision iterative refinement. * Tile equivalent of PLASMA_zcgesv(). * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * ******************************************************************************* * * @param[in] trans * Intended usage: * = PlasmaNoTrans: the linear system involves A; * = PlasmaConjTrans: the linear system involves A**H. * Currently only PlasmaNoTrans is supported. * * @param[in,out] A * - If the iterative refinement converged, A is not modified; * - otherwise, it fell back to double precision solution, and * on exit the M-by-N matrix A contains: * if M >= N, A is overwritten by details of its QR factorization as returned by * PLASMA_zgeqrf; * if M < N, A is overwritten by details of its LQ factorization as returned by * PLASMA_zgelqf. * * @param[out] T * On exit: * - if the iterative refinement converged, T is not modified; * - otherwise, it fell back to double precision solution, * and then T is an auxiliary factorization data. * * @param[in,out] B * On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise; * On exit, if return value = 0, B is overwritten by the solution vectors, stored * columnwise: * if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual * sum of squares for the solution in each column is given by the sum of squares of the * modulus of elements N+1 to M in that column; * if M < N, rows 1 to N of B contain the minimum norm solution vectors; * * @param[in] B * The descriptor of the M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified. * * @param[in,out] X * On entry, it's only the descriptor where to store the result. * On exit, if return value = 0, X is the solution vectors, stored columnwise: * if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual * sum of squares for the solution in each column is given by the sum of squares of the * modulus of elements N+1 to M in that column; * if M < N, rows 1 to N of X contain the minimum norm solution vectors; * * @param[out] ITER * If > 0, ITER is the number of the current iteration in the iterative refinement process. * -ITERMAX-1, if the refinment step failed and the double precision factorization has been used. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * ******************************************************************************* * * @sa PLASMA_zcgels * @sa PLASMA_zcgels_Tile_Async * @sa PLASMA_dsgels_Tile * @sa PLASMA_zgels_Tile * ******************************************************************************/ int PLASMA_zcgels_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T, PLASMA_desc *B, PLASMA_desc *X, int *ITER) { plasma_context_t *plasma; PLASMA_sequence *sequence = NULL; PLASMA_request request = PLASMA_REQUEST_INITIALIZER; int status; plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA_zcgels_Tile", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } plasma_sequence_create(plasma, &sequence); status = PLASMA_zcgels_Tile_Async(trans, A, T, B, X, ITER, sequence, &request); if (status != PLASMA_SUCCESS) return status; plasma_dynamic_sync(); status = sequence->status; plasma_sequence_destroy(plasma, sequence); return status; } /***************************************************************************//** * * @ingroup PLASMA_Complex64_t_Tile_Async * * PLASMA_zcgels_Tile_Async - Solves overdetermined or underdetermined linear * system of equations using the tile QR or the tile LQ factorization and * mixed-precision iterative refinement. * Non-blocking equivalent of PLASMA_zcgels_Tile(). * May return before the computation is finished. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). * * @param[out] request * Identifies this function call (for exception handling purposes). * ******************************************************************************* * * @sa PLASMA_zcgels * @sa PLASMA_zcgels_Tile * @sa PLASMA_dsgels_Tile_Async * @sa PLASMA_zgels_Tile_Async * ******************************************************************************/ int PLASMA_zcgels_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T, PLASMA_desc *B, PLASMA_desc *X, int *ITER, PLASMA_sequence *sequence, PLASMA_request *request) { int M, N, NRHS, NB, NBNB, MT, NT, NTRHS; PLASMA_desc descA; PLASMA_desc descT; PLASMA_desc descB; PLASMA_desc descX; plasma_context_t *plasma; double *work; const int itermax = 30; const double bwdmax = 1.0; const PLASMA_Complex64_t negone = -1.0; const PLASMA_Complex64_t one = 1.0; int iiter; double Anorm, cte, eps, Rnorm, Xnorm; *ITER=0; plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA_zcgels_Tile", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } if (sequence == NULL) { plasma_fatal_error("PLASMA_zcgels_Tile", "NULL sequence"); return PLASMA_ERR_UNALLOCATED; } if (request == NULL) { plasma_fatal_error("PLASMA_zcgels_Tile", "NULL request"); return PLASMA_ERR_UNALLOCATED; } /* Check sequence status */ if (sequence->status == PLASMA_SUCCESS) request->status = PLASMA_SUCCESS; else return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED); /* Check descriptors for correctness */ if (plasma_desc_check(A) != PLASMA_SUCCESS) { plasma_error("PLASMA_zcgels_Tile", "invalid first descriptor"); return PLASMA_ERR_ILLEGAL_VALUE; } else { descA = *A; } if (plasma_desc_check(T) != PLASMA_SUCCESS) { plasma_error("PLASMA_zcgels_Tile", "invalid second descriptor"); return PLASMA_ERR_ILLEGAL_VALUE; } else { descT = *T; } if (plasma_desc_check(B) != PLASMA_SUCCESS) { plasma_error("PLASMA_zcgels_Tile", "invalid third descriptor"); return PLASMA_ERR_ILLEGAL_VALUE; } else { descB = *B; } if (plasma_desc_check(X) != PLASMA_SUCCESS) { plasma_error("PLASMA_zcgels_Tile", "invalid fourth descriptor"); return PLASMA_ERR_ILLEGAL_VALUE; } else { descX = *X; } /* Check input arguments */ if (descA.nb != descA.mb || descB.nb != descB.mb || descX.nb != descX.mb) { plasma_error("PLASMA_zcgels_Tile", "only square tiles supported"); return PLASMA_ERR_ILLEGAL_VALUE; } if (trans != PlasmaNoTrans) { plasma_error("PLASMA_zcgels_Tile", "only PlasmaNoTrans supported"); return PLASMA_ERR_NOT_SUPPORTED; } /* Quick return - currently NOT equivalent to LAPACK's: if (min(M, min(N, NRHS)) == 0) { for (i = 0; i < max(M, N); i++) for (j = 0; j < NRHS; j++) B[j*LDB+i] = 0.0; return PLASMA_SUCCESS; } */ if (0 == 0) { // START SPECIFIC /* Set M, M, NRHS, NB, MT, NT & NTRHS */ M = descA.lm; N = descA.ln; NRHS = descB.ln; NB = descA.nb; NBNB = NB*NB; MT = (M%NB==0) ? (M/NB) : (M/NB+1); NT = (N%NB==0) ? (N/NB) : (N/NB+1); NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1); printf("M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\n", M, N, NRHS, NB, MT, NT, NTRHS); work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble); if (work == NULL) { plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed"); plasma_shared_free(plasma, work); return PLASMA_ERR_OUT_OF_RESOURCES; } PLASMA_desc descR = plasma_desc_init( PlasmaComplexDouble, NB, NB, NBNB, M, NRHS, 0, 0, M, NRHS); if (plasma_desc_mat_alloc(&descR)) { plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed"); plasma_desc_mat_free(&descR); plasma_shared_free(plasma, work); return PLASMA_ERR_OUT_OF_RESOURCES; } PLASMA_desc descSA = plasma_desc_init( PlasmaComplexFloat, NB, NB, NBNB, M, N, 0, 0, M, N); PLASMA_desc descST = plasma_desc_init( PlasmaComplexFloat, IB, NB, IBNB, M, N, 0, 0, M, N); PLASMA_desc descSX = plasma_desc_init( PlasmaComplexFloat, NB, NB, NBNB, M, NRHS, 0, 0, M, NRHS); /* Allocate memory for single precision matrices in block layout */ if (plasma_desc_mat_alloc(&descSA) || plasma_desc_mat_alloc(&descST) || plasma_desc_mat_alloc(&descSX)) { plasma_error("PLASMA_zcgesv", "plasma_shared_alloc() failed"); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX); plasma_desc_mat_free(&descR); plasma_shared_free(plasma, work); return PLASMA_ERR_OUT_OF_RESOURCES; } /* Compute some constants */ PLASMA_zlange(PlasmaInfNorm, descA, Anorm, work); eps = LAPACKE_dlamch_work('e'); printf("Anorm=%e, cte=%e\n", Anorm, cte); /* Convert B from double precision to single precision and store the result in SX. */ PLASMA_zlag2c(descB, descSX); if (sequence->status != PLASMA_SUCCESS) return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED); /* Convert A from double precision to single precision and store the result in SA. */ PLASMA_zlag2c(descA, descSA); if (sequence->status != PLASMA_SUCCESS) return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED); if (descSA.m >= descSA.n) { /* Compute the QR factorization of SA */ printf("Facto\n"); fflush(stdout); plasma_parallel_call_4(plasma_pcgeqrf, PLASMA_desc, descSA, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); printf("Solve\n"); fflush(stdout); plasma_parallel_call_5(plasma_pcunmqr, PLASMA_desc, descSA, PLASMA_desc, descSX, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9(plasma_pctrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaUpper, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex32_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n), PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); } else { plasma_parallel_call_3(plasma_pztile_zero, PLASMA_desc, plasma_desc_submatrix(descSX, descSA.m, 0, descSA.n-descSA.m, descSX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_4(plasma_pcgelqf, PLASMA_desc, descSA, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9(plasma_pctrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaLower, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex32_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m), PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_5(plasma_pcunmlq, PLASMA_desc, descSA, PLASMA_desc, descSX, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); } /* Convert SX back to double precision */ PLASMA_clag2z(descSX, descX); /* Compute R = B - AX. */ printf("R = B - Ax\n"); fflush(stdout); printf("R = B - Ax ... cpy\n"); fflush(stdout); PLASMA_zlacpy(descB,descR); printf("R = B - Ax ... gemm\n"); fflush(stdout); plasma_parallel_call_9(plasma_pzgemm, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNoTrans, PLASMA_Complex64_t, negone, PLASMA_desc, descA, PLASMA_desc, descX, PLASMA_Complex64_t, one, PLASMA_desc, descR, PLASMA_sequence*, sequence, PLASMA_request*, request); /* Check whether the NRHS normwise backward error satisfies the stopping criterion. If yes return. Note that ITER=0 (already set). */ printf("Norm of X and R\n"); fflush(stdout); PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work); PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work); /* Wait the end of Anorm, Xnorm and Bnorm computations */ plasma_dynamic_sync(); cte = Anorm*eps*((double) N)*bwdmax; if (Rnorm < Xnorm * cte){ /* The NRHS normwise backward errors satisfy the stopping criterion. We are good to exit. */ plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX); plasma_desc_mat_free(&descR); plasma_shared_free(plasma, work); return PLASMA_SUCCESS; } printf("Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\n", Rnorm, Xnorm * cte, Rnorm, cte); /* Iterative refinement */ for (iiter = 0; iiter < itermax; iiter++){ /* Convert R from double precision to single precision and store the result in SX. */ PLASMA_zlag2c(descR, descSX); /* Solve the system SA*SX = SR */ if (descSA.m >= descSA.n) { plasma_parallel_call_5(plasma_pcunmqr, PLASMA_desc, descSA, PLASMA_desc, descSX, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9(plasma_pctrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaUpper, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex32_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n), PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); } else { plasma_parallel_call_9(plasma_pctrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaLower, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex32_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m), PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_5(plasma_pcunmlq, PLASMA_desc, descSA, PLASMA_desc, descSX, PLASMA_desc, descST, PLASMA_sequence*, sequence, PLASMA_request*, request); } /* Convert SX back to double precision and update the current iterate. */ PLASMA_clag2z(descSX, descR); PLASMA_zgeadd(one, descR, descX); /* Compute R = B - AX. */ PLASMA_zlacpy(descB,descR); plasma_parallel_call_9(plasma_pzgemm, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNoTrans, PLASMA_Complex64_t, negone, PLASMA_desc, descA, PLASMA_desc, descX, PLASMA_Complex64_t, one, PLASMA_desc, descR, PLASMA_sequence*, sequence, PLASMA_request*, request); /* Check whether the NRHS normwise backward errors satisfy the stopping criterion. If yes, set ITER=IITER>0 and return. */ PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work); PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work); /* Wait the end of Xnorm and Bnorm computations */ plasma_dynamic_sync(); printf("Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\n", Rnorm, Xnorm * cte, Rnorm, cte); if (Rnorm < Xnorm * cte){ /* The NRHS normwise backward errors satisfy the stopping criterion. We are good to exit. */ *ITER = iiter; plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX); plasma_desc_mat_free(&descR); plasma_shared_free(plasma, work); return PLASMA_SUCCESS; } } /* We have performed ITER=itermax iterations and never satisified the stopping criterion, set up the ITER flag accordingly and follow up on double precision routine. */ *ITER = -itermax - 1; plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX); plasma_desc_mat_free(&descR); plasma_shared_free(plasma, work); printf("Go back DOUBLE\n"); // END SPECIFIC } /* Single-precision iterative refinement failed to converge to a satisfactory solution, so we resort to double precision. */ PLASMA_zlacpy(descB, descX); if (descA.m >= descA.n) { plasma_parallel_call_4(plasma_pzgeqrf, PLASMA_desc, descA, PLASMA_desc, descT, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_5(plasma_pzunmqr, PLASMA_desc, descA, PLASMA_desc, descX, PLASMA_desc, descT, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9(plasma_pztrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaUpper, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex64_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.n, descA.n), PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.n, descX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); } else { plasma_parallel_call_3(plasma_pztile_zero, PLASMA_desc, plasma_desc_submatrix(descX, descA.m, 0, descA.n-descA.m, descX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_4(plasma_pzgelqf, PLASMA_desc, descA, PLASMA_desc, descT, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9(plasma_pztrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaLower, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, PLASMA_Complex64_t, 1.0, PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.m, descA.m), PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.m, descX.n), PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_5(plasma_pzunmlq, PLASMA_desc, descA, PLASMA_desc, descX, PLASMA_desc, descT, PLASMA_sequence*, sequence, PLASMA_request*, request); } return PLASMA_SUCCESS; }
// Copyright 2016 Peter Jankuliak // // 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. #include <boost/uuid/uuid_generators.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/range/adaptor/indirected.hpp> #include <boost/range/adaptor/reversed.hpp> #include "club/hub.h" #include "node.h" #include "binary/encoder.h" #include "binary/dynamic_encoder.h" #include "binary/serialize/uuid.h" #include "binary/serialize/list.h" #include "message.h" #include "protocol_versions.h" #include "stun_client.h" #include <chrono> #include <iostream> #include "get_external_port.h" #include "connection_graph.h" #include "broadcast_routing_table.h" #include "log.h" #include "seen_messages.h" #include <club/socket.h> #include "reliable_exchange.h" using namespace club; using std::shared_ptr; using std::make_shared; using std::make_pair; using std::pair; using std::vector; using std::move; using std::set; using boost::asio::ip::udp; using boost::adaptors::map_values; using boost::adaptors::map_keys; using boost::adaptors::indirected; using boost::adaptors::reversed; using boost::system::error_code; namespace ip = boost::asio::ip; #include <club/debug/log.h> #define USE_LOG 0 #if USE_LOG # define IF_USE_LOG(a) a # define LOG(...) club::log("CLUB: ", _id, " ", __VA_ARGS__) # define LOG_(...) club::log("CLUB: ", _id, " ", __VA_ARGS__) #else # define IF_USE_LOG(a) # define LOG(...) do {} while(0) # define LOG_(...) club::log("CLUB: ", _id, " ", __VA_ARGS__) #endif // ----------------------------------------------------------------------------- template<class Message> shared_ptr<vector<uint8_t>> encode_message(const Message& msg) { binary::dynamic_encoder<uint8_t> e; e.put(Message::type()); e.put(msg); return make_shared<vector<uint8_t>>(e.move_data()); } shared_ptr<vector<uint8_t>> encode_message(const LogMessage& msg) { return match( msg , [](const Fuse& m) { return encode_message(m); } , [](const PortOffer& m) { return encode_message(m); } , [](const UserData& m) { return encode_message(m); }); } // ----------------------------------------------------------------------------- static Graph<uuid> single_node_graph(const uuid& id) { Graph<uuid> g; g.nodes.insert(id); return g; } // ----------------------------------------------------------------------------- template<class F> struct Callback { F func; bool was_reset; template<class... Args> void operator()(Args&&... args) { // Calling a callback may try to replace itself with another function // (or nullptr), this could destroy the original function's captured // variables. We preserve them by temporarily moving them to a local // variable. was_reset = false; auto f = std::move(func); f(std::forward<Args>(args)...); if (!was_reset) { func = std::move(f); } } void reset(F f) { was_reset = true; func = std::move(f); } operator bool() const { return (bool) func; } }; struct hub::Callbacks : public std::enable_shared_from_this<hub::Callbacks> { Callback<OnInsert> _on_insert; Callback<OnRemove> _on_remove; Callback<OnReceive> _on_receive; Callback<OnReceiveUnreliable> _on_receive_unreliable; Callback<OnDirectConnect> _on_direct_connect; template<class... Args> void on_insert(Args&&... args) { safe_exec(_on_insert, std::forward<Args>(args)...); } template<class... Args> void on_remove(Args&&... args) { safe_exec(_on_remove, std::forward<Args>(args)...); } template<class... Args> void on_receive(Args&&... args) { safe_exec(_on_receive, std::forward<Args>(args)...); } template<class... Args> void on_receive_unreliable(Args&&... args) { safe_exec(_on_receive_unreliable, std::forward<Args>(args)...); } template<class... Args> void on_direct_connect(Args&&... args) { safe_exec(_on_direct_connect, std::forward<Args>(args)...); } template<class F, class... Args> void safe_exec(F& f, Args&&... args) { if (!f) return; auto self = shared_from_this(); f(std::forward<Args>(args)...); } }; // ----------------------------------------------------------------------------- hub::hub(boost::asio::io_service& ios) : _callbacks(std::make_shared<Callbacks>()) , _io_service(ios) , _work(new Work(_io_service)) , _id(boost::uuids::random_generator()()) , _log(new Log()) , _time_stamp(0) , _broadcast_routing_table(new BroadcastRoutingTable(_id)) , _was_destroyed(make_shared<bool>(false)) , _seen(new SeenMessages()) { LOG("Created"); _nodes[_id] = std::unique_ptr<Node>(new Node(this, _id)); _log->last_commit_op = _id; _configs.emplace(MessageId(_time_stamp, _id), set<uuid>{_id}); _broadcast_routing_table->recalculate(single_node_graph(_id)); } // ----------------------------------------------------------------------------- void hub::fuse(Socket&& xsocket, const OnFused& on_fused) { using boost::asio::buffer; using namespace boost::asio::error; auto socket = make_shared<Socket>(move(xsocket)); static const size_t buffer_size = sizeof(NET_PROTOCOL_VERSION) + sizeof(_id); binary::dynamic_encoder<uint8_t> e(buffer_size); e.put(NET_PROTOCOL_VERSION); e.put(_id); auto was_destroyed = _was_destroyed; LOG("fusing ", _nodes | map_keys); reliable_exchange(e.move_data(), *socket, [this, socket, on_fused, was_destroyed] (error_code error, boost::asio::const_buffer buffer) { if (*was_destroyed) return; auto fusion_failed = [&](error_code error, const char* /*msg*/) { socket->close(); on_fused(error, uuid()); }; if (error) return fusion_failed(error, "socket error"); binary::decoder d( boost::asio::buffer_cast<const uint8_t*>(buffer) , boost::asio::buffer_size(buffer)); auto his_protocol_version = d.get<decltype(NET_PROTOCOL_VERSION)>(); auto his_id = d.get<uuid>(); if (d.error()) { return fusion_failed(connection_refused, "invalid data"); } if (his_protocol_version != NET_PROTOCOL_VERSION) { return fusion_failed(no_protocol_option, "protocol michmatch"); } ASSERT(_id != his_id); if (_id == his_id) { return fusion_failed(already_connected, "sender is myself"); } LOG(socket->local_endpoint().port(), " Exchanged ID with ", his_id); auto n = find_node(his_id); if (n) { n->assign_socket(move(socket)); } else { n = &insert_node(his_id, move(socket)); } auto fuse_msg = construct_ackable<Fuse>(his_id); broadcast(fuse_msg); add_log_entry(move(fuse_msg)); //LOG_("fused with ", his_id, " ;sent ", sync); add_connection(this_node(), his_id, n->address()); if (destroys_this([&]() { on_fused(error_code(), his_id); })) { return; } commit_what_was_seen_by_everyone(); }); } // ----------------------------------------------------------------------------- void hub::total_order_broadcast(Bytes data) { auto msg = construct_ackable<UserData>(move(data)); broadcast(msg); add_log_entry(move(msg)); auto was_destroyed = _was_destroyed; _io_service.post([=]() { if (*was_destroyed) return; commit_what_was_seen_by_everyone(); }); } // ----------------------------------------------------------------------------- void hub::add_connection(Node& from, uuid to, ip::address addr) { ASSERT(from.peers.count(to) == 0); from.peers[to] = Node::Peer({addr}); } // ----------------------------------------------------------------------------- void hub::on_peer_connected(const Node& node) { // TODO } // ----------------------------------------------------------------------------- void hub::on_peer_disconnected(const Node& node, std::string reason) { auto fuse_msg = construct_ackable<Fuse>(node.id); broadcast(fuse_msg); add_log_entry(move(fuse_msg)); commit_what_was_seen_by_everyone(); } // ----------------------------------------------------------------------------- void hub::process(Node&, Ack msg) { _log->apply_ack(original_poster(msg), move(msg.ack_data)); } // ----------------------------------------------------------------------------- void hub::process(Node& op, Fuse msg) { ASSERT(original_poster(msg) != _id); auto msg_id = message_id(msg); add_log_entry(move(msg)); auto fuse_entry = _log->find_highest_fuse_entry(); if (fuse_entry) { if (msg_id >= message_id(fuse_entry->message)) { broadcast(construct_ack(msg_id)); commit_what_was_seen_by_everyone(); } } else { broadcast(construct_ack(msg_id)); commit_what_was_seen_by_everyone(); } } // ----------------------------------------------------------------------------- void hub::process(Node& op, PortOffer msg) { if (msg.addressor != _id) { return; } LOG("Got port offer: ", msg); op.set_remote_port( msg.internal_port , msg.external_port); } // ----------------------------------------------------------------------------- void hub::process(Node&, UserData msg) { broadcast(construct_ack(message_id(msg))); add_log_entry(move(msg)); } // ----------------------------------------------------------------------------- static Graph<uuid> acks_to_graph(const std::map<uuid, AckData>& acks) { Graph<uuid> g; for (const auto& pair : acks) { g.nodes.insert(pair.first); for (const auto& peer : pair.second.neighbors) { g.add_edge(pair.first, peer); } } return g; } // ----------------------------------------------------------------------------- struct Diff { using Set = std::set<uuid>; Set removed; Set added; static Set set_difference(const Set& from, const Set& to) { Set result; std::set_difference( from.begin(), from.end() , to.begin(), to.end() , std::inserter(result, result.begin())); return result; } Diff(const std::set<uuid>& from, const std::set<uuid>& to) : removed(set_difference(from, to)) , added(set_difference(to, from)) { } }; // ----------------------------------------------------------------------------- void hub::on_commit_fuse(LogEntry entry) { if (!entry.acked_by_quorum()) return; auto new_graph = acks_to_graph(entry.acks); _broadcast_routing_table->recalculate(new_graph); LOG("Commit config: ", entry.message_id(), ": ", new_graph); ASSERT(!_configs.empty()); auto prev_quorum = _configs.rbegin()->second; Diff diff(prev_quorum, entry.quorum); _configs.emplace(entry.message_id(), std::move(entry.quorum)); // Forget about the lost nodes for (auto id : diff.removed) { _seen->forget_messages_from_user(id); _nodes.erase(id); } if (!diff.added.empty()) { if (destroys_this([&]() { _callbacks->on_insert(move(diff.added)); })) { return; } } if (!diff.removed.empty()) { if (destroys_this([&]() { _callbacks->on_remove(move(diff.removed)); })) { return; } } } // ----------------------------------------------------------------------------- template<class Message> void hub::on_recv(Node& IF_USE_LOG(proxy), Message msg) { #if USE_LOG # define ON_RECV_LOG(...) \ if (true || Message::type() == port_offer) { \ LOG("Recv(", proxy.id, "): ", __VA_ARGS__); \ } #else # define ON_RECV_LOG(...) do {} while(0) #endif // if USE_LOG msg.header.visited.insert(_id); auto op_id = original_poster(msg); auto op = find_node(op_id); //LOG_("Received ", msg); //debug("received: ", msg); if (_seen->is_in(message_id(msg))) { ON_RECV_LOG(msg, " (ignored: already seen ", message_id(msg), ")"); return; } _seen->insert(message_id(msg)); _time_stamp = std::max(_time_stamp, msg.header.time_stamp); if (!op) { ON_RECV_LOG(msg, " (unknown node: creating one)"); op = &insert_node(op_id); } // Peers shouldn't broadcast to us back our own messages. ASSERT(op_id != _id); if (op_id == _id) { ON_RECV_LOG(msg, " (ignored: is our own message)"); return; } ON_RECV_LOG(msg); broadcast(msg); if (destroys_this([&]() { process(*op, move(msg)); })) { return; } commit_what_was_seen_by_everyone(); } // ----------------------------------------------------------------------------- template<class Message> void hub::parse_message(Node& proxy, binary::decoder& decoder) { auto msg = decoder.get<Message>(); if (decoder.error()) return; ASSERT(!msg.header.visited.empty()); on_recv<Message>(proxy, move(msg)); ASSERT(msg.header.visited.empty()); } // ----------------------------------------------------------------------------- void hub::on_recv_raw(Node& proxy, boost::asio::const_buffer& buffer) { binary::decoder decoder( boost::asio::buffer_cast<const uint8_t*>(buffer) , boost::asio::buffer_size(buffer)); auto msg_type = decoder.get<MessageType>(); switch (msg_type) { case ::club::fuse: parse_message<Fuse> (proxy, decoder); break; case port_offer: parse_message<PortOffer> (proxy, decoder); break; case user_data: parse_message<UserData> (proxy, decoder); break; case ack: parse_message<Ack> (proxy, decoder); break; default: decoder.set_error(); } if (decoder.error()) { ASSERT(0 && "Error parsing message"); proxy.disconnect(); } } // ----------------------------------------------------------------------------- void hub::commit_what_was_seen_by_everyone() { const LogEntry* last_committable_fuse = nullptr; ASSERT(!_configs.empty()); auto live_nodes = _configs.rbegin()->second; for (auto& e : *_log | reversed | map_values) { if (e.message_type() == ::club::fuse && e.acked_by_quorum()) { last_committable_fuse = &e; live_nodes = e.quorum; break; } } #if USE_LOG { LOG("Checking what can be commited"); LOG(" Last committed: ", str(_log->last_committed)); LOG(" Last committed fuse: ", str(_log->last_fuse_commit)); LOG(" Live nodes: ", str(live_nodes)); LOG(" Entries:"); for (const auto& e : *_log | map_values) { LOG(" ", e); } } #endif auto entry_j = _log->begin(); auto was_destroyed = _was_destroyed; for ( auto entry_i = entry_j ; entry_i != _log->end() ; entry_i = entry_j) { entry_j = next(entry_i); auto& entry = entry_i->second; //------------------------------------------------------ if (entry.message_type() == ::club::fuse) { // NOTE: Committable in the context of this function means that // a quorum of a message is equal of the set of nodes that acked it. if (last_committable_fuse) { // TODO: The code here is supposed to erase all messages concurrent // to last_committable_fuse. But it may also erase a fuse message // that causally precedes last_committable_fuse. How do I distinguish // between the two? Or alternatively, is it OK if I erase those as // well? if (entry.message_id() < last_committable_fuse->message_id()) { if (!entry.acked_by_quorum(live_nodes)) { _log->last_committed = message_id(entry_i->second.message); _log->last_commit_op = original_poster(entry_i->second.message); _log->erase(entry_i); continue; } } else { if (entry.message_id() != last_committable_fuse->message_id()) { break; } } } else { // It is a fuse message, but we know it isn't committable. break; } } else { if (!entry.acked_by_quorum(live_nodes)) { break; } } //------------------------------------------------------ if (!entry.predecessors.empty()) { auto i = entry.predecessors.rbegin(); for (; i != entry.predecessors.rend(); ++i) { if (i->first == _log->last_committed) break; if (_configs.count(config_id(entry.message)) == 0) continue; break; } if (i != entry.predecessors.rend()) { LOG(" Predecessor: ", str(*i)); if (i->first != _log->last_committed && i->first > _log->last_fuse_commit) { LOG(" entry.predecessor != _log.last_committed " , i->first, " != ", _log->last_committed); break; } } } //------------------------------------------------------ if (&entry_i->second == last_committable_fuse) { last_committable_fuse = nullptr; } LOG(" Committing: ", entry); auto e = move(entry_i->second); _log->erase(entry_i); _seen->seen_everything_up_to(message_id(e.message)); if (e.message_type() == ::club::fuse) { _log->last_fuse_commit = message_id(e.message); } _log->last_committed = message_id(e.message); _log->last_commit_op = original_poster(e.message); commit(move(e)); if (*was_destroyed) return; } } // ----------------------------------------------------------------------------- hub::~hub() { _work.reset(); *_was_destroyed = true; } // ----------------------------------------------------------------------------- template<class Message> void hub::add_log_entry(Message message) { LOG("Adding entry for message: ", message); if(message_id(message) <= _log->last_committed) { if (Message::type() != ::club::fuse) { LOG_("!!! message_id(message) should be > than _log.last_committed"); LOG_("!!! message_id(message) = ", message_id(message)); LOG_("!!! _log.last_committed = ", _log->last_committed); for (const auto& d : debug_log) { LOG_("!!! ", d); } ASSERT(0); return; } } _log->insert_entry(LogEntry(move(message))); } //------------------------------------------------------------------------------ template<class Message, class... Args> Message hub::construct(Args&&... args) { ASSERT(!_configs.empty()); // TODO: The _id argument in `visited` member is redundant. return Message( Header{ _id , ++_time_stamp , _configs.rbegin()->first , boost::container::flat_set<uuid>{_id} } , std::forward<Args>(args)...); } //------------------------------------------------------------------------------ template<class Message, class... Args> Message hub::construct_ackable(Args&&... args) { ASSERT(!_configs.empty()); ++_time_stamp; auto m_id = MessageId(_time_stamp, _id); const auto& predecessor_id = _log->get_predecessor_time(m_id); // TODO: m_id here is redundant, can be calculated from header. AckData ack_data { move(m_id) , move(predecessor_id) , neighbors() }; // TODO: The _id argument in `visited` member is redundant. return Message( Header{ _id , _time_stamp , _configs.rbegin()->first , boost::container::flat_set<uuid>{_id} } , move(ack_data) , std::forward<Args>(args)...); } // ----------------------------------------------------------------------------- Ack hub::construct_ack(const MessageId& msg_id) { const auto& predecessor_id = _log->get_predecessor_time(msg_id); auto ack = construct<Ack> ( msg_id , predecessor_id , neighbors()); // We don't receive our own message back, so need to apply it manually. _log->apply_ack(_id, ack.ack_data); return ack; } //------------------------------------------------------------------------------ template<class Message> void hub::broadcast(const Message& msg) { //debug("broadcasting: ", msg); auto data = encode_message(msg); for (auto& node : _nodes | map_values | indirected) { if (node.id == _id) continue; if (!node.is_connected()) { LOG(" skipped: ", node.id, " (not connected)"); continue; } bool already_visited = msg.header.visited.count(node.id) != 0; if (already_visited) { continue; } ASSERT(original_poster(msg) != node.id && "Why are we sending the message back?"); node.send(data); } } // ----------------------------------------------------------------------------- void hub::unreliable_broadcast(Bytes payload, std::function<void()> handler) { using std::make_pair; using boost::asio::const_buffer; // Encoding std::vector adds 4 bytes for size. auto bytes = make_shared<Bytes>(uuid::static_size() + payload.size() + 4); auto counter = make_shared<size_t>(0); // TODO: Unfortunately, ConnectedSocket doesn't support sending multiple // buffers at once (yet?), so we need to *copy* the payload into one buffer. binary::encoder e(reinterpret_cast<uint8_t*>(bytes->data()), bytes->size()); e.put(_id); e.put(payload); ASSERT(!e.error()); for (auto& node : _nodes | map_values | indirected) { if (node.id == _id || !node.is_connected()) continue; ++(*counter); const_buffer b(bytes->data(), bytes->size()); node.send_unreliable(b, [counter, bytes, handler](auto /* error */) { if (--(*counter) == 0) handler(); }); } if (*counter == 0) { get_io_service().post(move(handler)); } } // ----------------------------------------------------------------------------- void hub::node_received_unreliable_broadcast(boost::asio::const_buffer buffer) { namespace asio = boost::asio; using boost::asio::const_buffer; auto start = asio::buffer_cast<const uint8_t*>(buffer); auto size = asio::buffer_size(buffer); binary::decoder d(start, size); auto source = d.get<uuid>(); if (d.error() || _nodes.count(source) == 0) { return; } auto shared_bytes = make_shared<Bytes>(start, start + size); // Rebroadcast for (const auto& id : _broadcast_routing_table->get_targets(source)) { auto node = find_node(id); if (!node || !node->is_connected()) continue; node->send_unreliable( const_buffer( shared_bytes->data() , shared_bytes->size() ) , [shared_bytes](auto /* error */) {}); } _callbacks->on_receive_unreliable( source , const_buffer( d.current() + 4 , d.size() - 4)); } // ----------------------------------------------------------------------------- boost::container::flat_set<uuid> hub::neighbors() const { size_t size = 1; for (auto& node : _nodes | map_values | indirected) { if (node.id == _id) continue; if (node.is_connected()) { ++size; } } boost::container::flat_set<uuid> lc; lc.reserve(size); lc.insert(_id); for (auto& node : _nodes | map_values | indirected) { if (node.id == _id) continue; if (node.is_connected()) { lc.insert(node.id); } } return lc; } // ----------------------------------------------------------------------------- //void hub::broadcast_port_offer_to(Node& node, Address addr) { // auto was_destroyed = _was_destroyed; // // auto node_id = node.id; // // if (addr.is_loopback()) { // // If the remote address is on our PC, then there is no need // // to send him our external address. // // TODO: Remove code duplication. // // TODO: Similar optimization when the node is on local LAN. // _io_service.post([=]{ // if (*was_destroyed) return; // // auto node = find_node(node_id); // // if (!node || node->is_connected()) return; // // udp::socket udp_socket(_io_service, udp::endpoint(udp::v4(), 0)); // uint16_t internal_port = udp_socket.local_endpoint().port(); // uint16_t external_port = 0; // // auto socket = make_shared<Socket>(std::move(udp_socket)); // node->set_remote_address(move(socket), addr); // // broadcast(construct<PortOffer>( node_id // , internal_port // , external_port)); // }); // return; // } // // _stun_requests.emplace_back(nullptr); // auto iter = std::prev(_stun_requests.end()); // // iter->reset(new GetExternalPort(_io_service // , std::chrono::seconds(2) // , [=] ( error_code error // , udp::socket udp_socket // , udp::endpoint reflexive_ep) { // if (*was_destroyed) return; // // _stun_requests.erase(iter); // // auto node = find_node(node_id); // // if (!node || node->is_connected()) return; // // uint16_t internal_port = udp_socket.local_endpoint().port(); // uint16_t external_port = reflexive_ep.port(); // // auto socket = make_shared<Socket>(std::move(udp_socket)); // node->set_remote_address(move(socket), addr); // // broadcast(construct<PortOffer>( node_id // , internal_port // , external_port)); // })); //} // ----------------------------------------------------------------------------- template<class F> bool hub::destroys_this(F f) { auto was_destroyed = _was_destroyed; f(); return *was_destroyed; } // ----------------------------------------------------------------------------- hub::Address hub::find_address_to(uuid id) const { ConnectionGraph g; for (const auto& node : _nodes | map_values | indirected) { if (node.id == _id) continue; auto addr = node.address(); if (!addr.is_unspecified()) { g.add_connection(_id, node.id, addr); } for (const auto& peer_id_info : node.peers) { auto peer_id = peer_id_info.first; auto peer_addr = peer_id_info.second.address; g.add_connection(node.id, peer_id, peer_addr); } } return g.find_address(_id, id); } // ----------------------------------------------------------------------------- inline Node& hub::this_node() { // TODO: We can store this node instead of searching the rb-tree // each time. return *_nodes[_id]; } // ----------------------------------------------------------------------------- inline Node& hub::insert_node(uuid id) { auto node = std::unique_ptr<Node>(new Node(this, id)); auto ret = node.get(); _nodes.insert(std::make_pair(id, move(node))); return *ret; } // ----------------------------------------------------------------------------- inline Node& hub::insert_node(uuid id, shared_ptr<Socket> socket) { auto node = std::unique_ptr<Node>(new Node(this, id, move(socket))); auto ret = node.get(); _nodes.insert(std::make_pair(id, move(node))); return *ret; } // ----------------------------------------------------------------------------- inline Node* hub::find_node(uuid id) { auto i = _nodes.find(id); if (i == _nodes.end()) return nullptr; return i->second.get(); } inline const Node* hub::find_node(uuid id) const { auto i = _nodes.find(id); if (i == _nodes.end()) return nullptr; return i->second.get(); } // ----------------------------------------------------------------------------- void hub::commit(LogEntry&& entry) { struct Visitor { hub& h; LogEntry& entry; Visitor(hub& h, LogEntry& entry) : h(h), entry(entry) {} void operator () (Fuse& m) const { h.commit_fuse(std::move(entry)); } void operator () (PortOffer&) const { ASSERT(0 && "TODO"); } void operator () (UserData& m) const { h.commit_user_data(original_poster(m), std::move(m.data)); } }; boost::apply_visitor(Visitor(*this, entry), entry.message); } inline void hub::commit_user_data(uuid op, std::vector<char>&& data) { if (!find_node(op)) return; _callbacks->on_receive(op, move(data)); } inline void hub::commit_fuse(LogEntry&& entry) { on_commit_fuse(move(entry)); } // ----------------------------------------------------------------------------- void hub::on_insert(OnInsert f) { _callbacks->_on_insert.reset(std::move(f)); } void hub::on_remove(OnRemove f) { _callbacks->_on_remove.reset(std::move(f)); } void hub::on_receive(OnReceive f) { _callbacks->_on_receive.reset(std::move(f)); } void hub::on_receive_unreliable(OnReceiveUnreliable f) { _callbacks->_on_receive_unreliable.reset(std::move(f)); } void hub::on_direct_connect(OnDirectConnect f) { _callbacks->_on_direct_connect.reset(std::move(f)); } // ----------------------------------------------------------------------------- template<class T> inline void debug_(std::stringstream& os, std::list<std::string>& debug_log, T&& arg) { os << arg; debug_log.push_back(os.str()); } template<class T, class... Ts> inline void debug_(std::stringstream& os, std::list<std::string>& debug_log, T&& arg, Ts&&... args) { os << arg; debug_(os, debug_log, std::forward<Ts>(args)...); } template<class... Ts> inline void hub::debug(Ts&&... args) { std::stringstream ss; debug_(ss, debug_log, std::forward<Ts>(args)...); }
open import Relation.Binary.Core module PLRTree.DropLast.Heap {A : Set} (_≤_ : A → A → Set) (tot≤ : Total _≤_) where open import PLRTree {A} open import PLRTree.Drop _≤_ tot≤ open import PLRTree.Heap _≤_ lemma-dropLast-≤* : {x : A}{t : PLRTree} → x ≤* t → x ≤* dropLast t lemma-dropLast-≤* {x} (lf≤* .x) = lf≤* x lemma-dropLast-≤* (nd≤* {perfect} {x} {y} {l} {r} x≤y x≤*l x≤*r) with r ... | leaf = x≤*r ... | node _ _ _ _ = nd≤* x≤y x≤*l (lemma-dropLast-≤* x≤*r) lemma-dropLast-≤* (nd≤* {left} {x} {y} {l} {r} x≤y x≤*l x≤*r) with l | x≤*l | dropLast l | lemma-dropLast-≤* x≤*l ... | leaf | _ | _ | _ = lf≤* x ... | node perfect _ _ _ | _ | node perfect y' l' r' | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node perfect _ _ _ | _ | leaf | (lf≤* .x) = nd≤* x≤y (lf≤* x) x≤*r ... | node perfect _ _ _ | _ | node left _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node perfect _ _ _ | _ | node right _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node left _ _ _ | _ | node perfect y' l' r' | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node left _ _ _ | _ | leaf | (lf≤* .x) = nd≤* x≤y (lf≤* x) x≤*r ... | node left _ _ _ | _ | node left _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node left _ _ _ | _ | node right _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node right _ _ _ | _ | node perfect y' l' r' | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node right _ _ _ | _ | leaf | (lf≤* .x) = nd≤* x≤y (lf≤* x) x≤*r ... | node right _ _ _ | _ | node left _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r ... | node right _ _ _ | _ | node right _ _ _ | x≤*dll = nd≤* x≤y x≤*dll x≤*r lemma-dropLast-≤* (nd≤* {right} {x} {y} {l} {r} x≤y x≤*l x≤*r) with r ... | leaf = nd≤* x≤y x≤*r x≤*r ... | node perfect y' l' r' = nd≤* x≤y (lemma-dropLast-≤* x≤*l) x≤*r ... | node left _ _ _ = nd≤* x≤y x≤*l (lemma-dropLast-≤* x≤*r) ... | node right _ _ _ = nd≤* x≤y x≤*l (lemma-dropLast-≤* x≤*r) lemma-dropLast-heap : {t : PLRTree} → Heap t → Heap (dropLast t) lemma-dropLast-heap leaf = leaf lemma-dropLast-heap (node {perfect} {x} {l} {r} x≤*l x≤*r hl hr) with r ... | leaf = hr ... | node _ _ _ _ = node x≤*l (lemma-dropLast-≤* x≤*r) hl (lemma-dropLast-heap hr) lemma-dropLast-heap (node {left} {x} {l} {r} x≤*l x≤*r hl hr) with l | x≤*l | hl | dropLast l | lemma-dropLast-≤* x≤*l | lemma-dropLast-heap hl ... | leaf | _ | _ | _ | _ | _ = leaf ... | node perfect _ _ _ | _ | _ | node perfect y' l' r' | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node perfect _ _ _ | _ | _ | leaf | (lf≤* .x) | leaf = node (lf≤* x) x≤*r leaf hr ... | node perfect _ _ _ | _ | _ | node left _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node perfect _ _ _ | _ | _ | node right _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node left _ _ _ | _ | _ | node perfect y' l' r' | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node left _ _ _ | _ | _ | leaf | (lf≤* .x) | leaf = node (lf≤* x) x≤*r leaf hr ... | node left _ _ _ | _ | _ | node left _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node left _ _ _ | _ | _ | node right _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node right _ _ _ | _ | _ | node perfect y' l' r' | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node right _ _ _ | _ | _ | leaf | (lf≤* .x) | leaf = node (lf≤* x) x≤*r leaf hr ... | node right _ _ _ | _ | _ | node left _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr ... | node right _ _ _ | _ | _ | node right _ _ _ | x≤*dll | hdll = node x≤*dll x≤*r hdll hr lemma-dropLast-heap (node {right} {x} {l} {r} x≤*l x≤*r hl hr) with r ... | leaf = node x≤*r x≤*r hr hr ... | node perfect y' l' r' = node (lemma-dropLast-≤* x≤*l) x≤*r (lemma-dropLast-heap hl) hr ... | node left _ _ _ = node x≤*l (lemma-dropLast-≤* x≤*r) hl (lemma-dropLast-heap hr) ... | node right _ _ _ = node x≤*l (lemma-dropLast-≤* x≤*r) hl (lemma-dropLast-heap hr)
[STATEMENT] lemma less_bot_Bot_Value_code [code]: "Bot < Value x \<longleftrightarrow> True" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (Bot < Value x) = True [PROOF STEP] by simp
-- SPDX-FileCopyrightText: 2021 The ipkg-idr developers -- -- SPDX-License-Identifier: MPL-2.0 module Language.IPKG.Value import Data.List import Data.List1 import Data.Strings public export Identifier : Type Identifier = String public export ModuleIdent : Type ModuleIdent = List1 Identifier public export record PkgDesc where constructor MkPkgDesc name : Identifier version : String -- TODO should be a proper type authors : String maintainers : Maybe String license : Maybe String brief : Maybe String readme : Maybe String homepage : Maybe String sourceloc : Maybe String bugtracker : Maybe String depends : List Identifier -- packages to add to search path modules : List ModuleIdent -- modules to install (namespace, filename) mainmod : Maybe ModuleIdent -- main file (i.e. file to load at REPL) executable : Maybe String -- name of executable options : Maybe String sourcedir : Maybe String builddir : Maybe String outputdir : Maybe String prebuild : Maybe String -- Script to run before building postbuild : Maybe String -- Script to run after building preinstall : Maybe String -- Script to run after building, before installing postinstall : Maybe String -- Script to run after installing preclean : Maybe String -- Script to run before cleaning postclean : Maybe String -- Script to run after cleaning private showModule : ModuleIdent -> String showModule m = fastConcat . intersperse "." $ forget m export Show PkgDesc where show pkg = "Package: " ++ name pkg ++ "\n" ++ "Version: " ++ version pkg ++ "\n" ++ "Authors: " ++ authors pkg ++ "\n" ++ maybe "" (\m => "Maintainers: " ++ m ++ "\n") (maintainers pkg) ++ maybe "" (\m => "License: " ++ m ++ "\n") (license pkg) ++ maybe "" (\m => "Brief: " ++ m ++ "\n") (brief pkg) ++ maybe "" (\m => "ReadMe: " ++ m ++ "\n") (readme pkg) ++ maybe "" (\m => "HomePage: " ++ m ++ "\n") (homepage pkg) ++ maybe "" (\m => "SourceLoc: " ++ m ++ "\n") (sourceloc pkg) ++ maybe "" (\m => "BugTracker: " ++ m ++ "\n") (bugtracker pkg) ++ "Depends: " ++ show (depends pkg) ++ "\n" ++ "Modules: " ++ show (map showModule $ modules pkg) ++ "\n" ++ maybe "" (\m => "Main: " ++ showModule m ++ "\n") (mainmod pkg) ++ maybe "" (\m => "Exec: " ++ m ++ "\n") (executable pkg) ++ maybe "" (\m => "Opts: " ++ m ++ "\n") (options pkg) ++ maybe "" (\m => "SourceDir: " ++ m ++ "\n") (sourcedir pkg) ++ maybe "" (\m => "BuildDir: " ++ m ++ "\n") (builddir pkg) ++ maybe "" (\m => "OutputDir: " ++ m ++ "\n") (outputdir pkg) ++ maybe "" (\m => "Prebuild: " ++ m ++ "\n") (prebuild pkg) ++ maybe "" (\m => "Postbuild: " ++ m ++ "\n") (postbuild pkg) ++ maybe "" (\m => "Preinstall: " ++ m ++ "\n") (preinstall pkg) ++ maybe "" (\m => "Postinstall: " ++ m ++ "\n") (postinstall pkg) ++ maybe "" (\m => "Preclean: " ++ m ++ "\n") (preclean pkg) ++ maybe "" (\m => "Postclean: " ++ m ++ "\n") (postclean pkg)
From F_mu_ref_conc_sub Require Export lang fundamental_binary. Export F_mu_ref_conc. Inductive ctx_item := | CTX_Rec | CTX_AppL (e2 : expr) | CTX_AppR (e1 : expr) (* Products *) | CTX_PairL (e2 : expr) | CTX_PairR (e1 : expr) | CTX_Fst | CTX_Snd (* Sums *) | CTX_InjL | CTX_InjR | CTX_CaseL (e1 : expr) (e2 : expr) | CTX_CaseM (e0 : expr) (e2 : expr) | CTX_CaseR (e0 : expr) (e1 : expr) (* Nat bin op *) | CTX_BinOpL (op : binop) (e2 : expr) | CTX_BinOpR (op : binop) (e1 : expr) (* If *) | CTX_IfL (e1 : expr) (e2 : expr) | CTX_IfM (e0 : expr) (e2 : expr) | CTX_IfR (e0 : expr) (e1 : expr) (* Recursive Types *) | CTX_Fold | CTX_Unfold (* Polymorphic Types *) | CTX_TLam | CTX_TApp (* Concurrency *) | CTX_Fork (* Reference Types *) | CTX_Alloc | CTX_Load | CTX_StoreL (e2 : expr) | CTX_StoreR (e1 : expr) (* Compare and swap used for fine-grained concurrency *) | CTX_CAS_L (e1 : expr) (e2 : expr) | CTX_CAS_M (e0 : expr) (e2 : expr) | CTX_CAS_R (e0 : expr) (e1 : expr). Fixpoint fill_ctx_item (ctx : ctx_item) (e : expr) : expr := match ctx with | CTX_Rec => Rec e | CTX_AppL e2 => App e e2 | CTX_AppR e1 => App e1 e | CTX_PairL e2 => Pair e e2 | CTX_PairR e1 => Pair e1 e | CTX_Fst => Fst e | CTX_Snd => Snd e | CTX_InjL => InjL e | CTX_InjR => InjR e | CTX_CaseL e1 e2 => Case e e1 e2 | CTX_CaseM e0 e2 => Case e0 e e2 | CTX_CaseR e0 e1 => Case e0 e1 e | CTX_BinOpL op e2 => BinOp op e e2 | CTX_BinOpR op e1 => BinOp op e1 e | CTX_IfL e1 e2 => If e e1 e2 | CTX_IfM e0 e2 => If e0 e e2 | CTX_IfR e0 e1 => If e0 e1 e | CTX_Fold => Fold e | CTX_Unfold => Unfold e | CTX_TLam => TLam e | CTX_TApp => TApp e | CTX_Fork => Fork e | CTX_Alloc => Alloc e | CTX_Load => Load e | CTX_StoreL e2 => Store e e2 | CTX_StoreR e1 => Store e1 e | CTX_CAS_L e1 e2 => CAS e e1 e2 | CTX_CAS_M e0 e2 => CAS e0 e e2 | CTX_CAS_R e0 e1 => CAS e0 e1 e end. Definition ctx := list ctx_item. Definition fill_ctx (K : ctx) (e : expr) : expr := foldr fill_ctx_item e K. (** typed ctx *) Inductive typed_ctx_item : ctx_item → list type → list type → type → list type → list type → type → Prop := | TP_CTX_Rec Ξ Γ τ τ' : typed_ctx_item CTX_Rec Ξ (TArrow τ τ' :: τ :: Γ) τ' Ξ Γ (TArrow τ τ') | TP_CTX_AppL Ξ Γ e2 τ τ' : typed Ξ Γ e2 τ → typed_ctx_item (CTX_AppL e2) Ξ Γ (TArrow τ τ') Ξ Γ τ' | TP_CTX_AppR Ξ Γ e1 τ τ' : typed Ξ Γ e1 (TArrow τ τ') → typed_ctx_item (CTX_AppR e1) Ξ Γ τ Ξ Γ τ' | TP_CTX_PairL Ξ Γ e2 τ τ' : typed Ξ Γ e2 τ' → typed_ctx_item (CTX_PairL e2) Ξ Γ τ Ξ Γ (TProd τ τ') | TP_CTX_PairR Ξ Γ e1 τ τ' : typed Ξ Γ e1 τ → typed_ctx_item (CTX_PairR e1) Ξ Γ τ' Ξ Γ (TProd τ τ') | TP_CTX_Fst Ξ Γ τ τ' : typed_ctx_item CTX_Fst Ξ Γ (TProd τ τ') Ξ Γ τ | TP_CTX_Snd Ξ Γ τ τ' : typed_ctx_item CTX_Snd Ξ Γ (TProd τ τ') Ξ Γ τ' | TP_CTX_InjL Ξ Γ τ τ' : typed_ctx_item CTX_InjL Ξ Γ τ Ξ Γ (TSum τ τ') | TP_CTX_InjR Ξ Γ τ τ' : typed_ctx_item CTX_InjR Ξ Γ τ' Ξ Γ (TSum τ τ') | TP_CTX_CaseL Ξ Γ e1 e2 τ1 τ2 τ' : typed Ξ (τ1 :: Γ) e1 τ' → typed Ξ (τ2 :: Γ) e2 τ' → typed_ctx_item (CTX_CaseL e1 e2) Ξ Γ (TSum τ1 τ2) Ξ Γ τ' | TP_CTX_CaseM Ξ Γ e0 e2 τ1 τ2 τ' : typed Ξ Γ e0 (TSum τ1 τ2) → typed Ξ (τ2 :: Γ) e2 τ' → typed_ctx_item (CTX_CaseM e0 e2) Ξ (τ1 :: Γ) τ' Ξ Γ τ' | TP_CTX_CaseR Ξ Γ e0 e1 τ1 τ2 τ' : typed Ξ Γ e0 (TSum τ1 τ2) → typed Ξ (τ1 :: Γ) e1 τ' → typed_ctx_item (CTX_CaseR e0 e1) Ξ (τ2 :: Γ) τ' Ξ Γ τ' | TP_CTX_IfL Ξ Γ e1 e2 τ : typed Ξ Γ e1 τ → typed Ξ Γ e2 τ → typed_ctx_item (CTX_IfL e1 e2) Ξ Γ (TBool) Ξ Γ τ | TP_CTX_IfM Ξ Γ e0 e2 τ : typed Ξ Γ e0 (TBool) → typed Ξ Γ e2 τ → typed_ctx_item (CTX_IfM e0 e2) Ξ Γ τ Ξ Γ τ | TP_CTX_IfR Ξ Γ e0 e1 τ : typed Ξ Γ e0 (TBool) → typed Ξ Γ e1 τ → typed_ctx_item (CTX_IfR e0 e1) Ξ Γ τ Ξ Γ τ | TP_CTX_BinOpL op Ξ Γ e2 : typed Ξ Γ e2 TNat → typed_ctx_item (CTX_BinOpL op e2) Ξ Γ TNat Ξ Γ (binop_res_type op) | TP_CTX_BinOpR op e1 Ξ Γ : typed Ξ Γ e1 TNat → typed_ctx_item (CTX_BinOpR op e1) Ξ Γ TNat Ξ Γ (binop_res_type op) | TP_CTX_Fold Ξ Γ τ : typed_ctx_item CTX_Fold Ξ Γ τ.[(TRec τ)/] Ξ Γ (TRec τ) | TP_CTX_Unfold Ξ Γ τ : typed_ctx_item CTX_Unfold Ξ Γ (TRec τ) Ξ Γ τ.[(TRec τ)/] | TP_CTX_TLam Ξ Γ σ τ : typed_ctx_item CTX_TLam (σ.[ren (+1)] :: (subst (ren (+1)) <$> Ξ)) (subst (ren (+1)) <$> Γ) τ Ξ Γ (TForall σ τ) | TP_CTX_TApp Ξ Γ σ τ τ' : subtype Ξ τ' σ → typed_ctx_item CTX_TApp Ξ Γ (TForall σ τ) Ξ Γ τ.[τ'/] | TP_CTX_Fork Ξ Γ : typed_ctx_item CTX_Fork Ξ Γ TUnit Ξ Γ TUnit | TPCTX_Alloc Ξ Γ τ : typed_ctx_item CTX_Alloc Ξ Γ τ Ξ Γ (Tref τ) | TP_CTX_Load Ξ Γ τ : typed_ctx_item CTX_Load Ξ Γ (Tref τ) Ξ Γ τ | TP_CTX_StoreL Ξ Γ e2 τ : typed Ξ Γ e2 τ → typed_ctx_item (CTX_StoreL e2) Ξ Γ (Tref τ) Ξ Γ TUnit | TP_CTX_StoreR Ξ Γ e1 τ : typed Ξ Γ e1 (Tref τ) → typed_ctx_item (CTX_StoreR e1) Ξ Γ τ Ξ Γ TUnit | TP_CTX_CasL Ξ Γ e1 e2 τ : EqType τ → typed Ξ Γ e1 τ → typed Ξ Γ e2 τ → typed_ctx_item (CTX_CAS_L e1 e2) Ξ Γ (Tref τ) Ξ Γ TBool | TP_CTX_CasM Ξ Γ e0 e2 τ : EqType τ → typed Ξ Γ e0 (Tref τ) → typed Ξ Γ e2 τ → typed_ctx_item (CTX_CAS_M e0 e2) Ξ Γ τ Ξ Γ TBool | TP_CTX_CasR Ξ Γ e0 e1 τ : EqType τ → typed Ξ Γ e0 (Tref τ) → typed Ξ Γ e1 τ → typed_ctx_item (CTX_CAS_R e0 e1) Ξ Γ τ Ξ Γ TBool. Lemma typed_ctx_item_typed k Ξ Γ τ Ξ' Γ' τ' e : typed Ξ Γ e τ → typed_ctx_item k Ξ Γ τ Ξ' Γ' τ' → typed Ξ' Γ' (fill_ctx_item k e) τ'. Proof. induction 2; simpl; eauto using typed. Qed. Inductive typed_ctx : ctx → list type → list type → type → list type → list type → type → Prop := | TPCTX_nil Ξ Γ τ : typed_ctx nil Ξ Γ τ Ξ Γ τ | TPCTX_cons Ξ1 Γ1 τ1 Ξ2 Γ2 τ2 Ξ3 Γ3 τ3 k K : typed_ctx_item k Ξ2 Γ2 τ2 Ξ3 Γ3 τ3 → typed_ctx K Ξ1 Γ1 τ1 Ξ2 Γ2 τ2 → typed_ctx (k :: K) Ξ1 Γ1 τ1 Ξ3 Γ3 τ3. Lemma typed_ctx_typed K Ξ Γ τ Ξ' Γ' τ' e : typed Ξ Γ e τ → typed_ctx K Ξ Γ τ Ξ' Γ' τ' → typed Ξ' Γ' (fill_ctx K e) τ'. Proof. induction 2; simpl; eauto using typed_ctx_item_typed. Qed. (* Lemma typed_ctx_n_closed K Ξ Γ τ Ξ' Γ' τ' e : *) (* (∀ f, e.[upn (length Γ) f] = e) → typed_ctx K Ξ Γ τ Ξ' Γ' τ' → *) (* ∀ f, (fill_ctx K e).[upn (length Γ') f] = (fill_ctx K e). *) (* Proof. *) (* intros H1 H2; induction H2; simpl; auto. *) (* induction H => f; asimpl; simpl in *; *) (* repeat match goal with H : _ |- _ => rewrite fmap_length in H end; *) (* try f_equal; *) (* eauto using typed_n_closed; *) (* try match goal with H : _ |- _ => eapply (typed_n_closed _ _ _ H) end. *) (* Qed. *) Definition ctx_refines (Ξ Γ : list type) (e e' : expr) (τ : type) := typed Ξ Γ e τ ∧ typed Ξ Γ e' τ ∧ ∀ K thp σ v, typed_ctx K Ξ Γ τ [] [] TUnit → rtc erased_step ([fill_ctx K e], ∅) (of_val v :: thp, σ) → ∃ thp' σ' v', rtc erased_step ([fill_ctx K e'], ∅) (of_val v' :: thp', σ'). Notation "Ξ ∣ Γ ⊨ e '≤ctx≤' e' : τ" := (ctx_refines Ξ Γ e e' τ) (at level 74, e, e', τ at next level). Section bin_log_related_under_typed_ctx. Context `{heapIG Σ, cfgSG Σ}. Lemma bin_log_related_under_typed_ctx Ξ Γ e e' τ Ξ' Γ' τ' K : typed_ctx K Ξ Γ τ Ξ' Γ' τ' → Ξ ∣ Γ ⊨ e ≤log≤ e' : τ → Ξ' ∣ Γ' ⊨ fill_ctx K e ≤log≤ fill_ctx K e' : τ'. Proof. revert Ξ Γ τ Ξ' Γ' τ' e e'. induction K as [|k K]=> Ξ Γ τ Ξ' Γ' τ' e e' H1 H2; simpl. - inversion H1; subst; trivial. - inversion H1 as [|? ? ? ? ? ? ? ? ? ? ? Hx1 Hx2]; simplify_eq. specialize (IHK _ _ _ _ _ _ e e' Hx2 H2). inversion Hx1; subst; simpl. + eapply bin_log_related_rec; eauto. + eapply bin_log_related_app; eauto using binary_fundamental. + eapply bin_log_related_app; eauto using binary_fundamental. + eapply bin_log_related_pair; eauto using binary_fundamental. + eapply bin_log_related_pair; eauto using binary_fundamental. + eapply bin_log_related_fst; eauto. + eapply bin_log_related_snd; eauto. + eapply bin_log_related_injl; eauto. + eapply bin_log_related_injr; eauto. + eapply bin_log_related_case; eauto using binary_fundamental. + eapply bin_log_related_case; eauto using binary_fundamental. + eapply bin_log_related_case; eauto using binary_fundamental. + eapply bin_log_related_if; eauto using typed_ctx_typed, binary_fundamental. + eapply bin_log_related_if; eauto using typed_ctx_typed, binary_fundamental. + eapply bin_log_related_if; eauto using typed_ctx_typed, binary_fundamental. + eapply bin_log_related_nat_binop; eauto using typed_ctx_typed, binary_fundamental. + eapply bin_log_related_nat_binop; eauto using typed_ctx_typed, binary_fundamental. + eapply bin_log_related_fold; eauto. + eapply bin_log_related_unfold; eauto. + eapply bin_log_related_tlam; eauto with typeclass_instances. + eapply bin_log_related_tapp; eauto. + eapply bin_log_related_fork; eauto. + eapply bin_log_related_alloc; eauto. + eapply bin_log_related_load; eauto. + eapply bin_log_related_store; eauto using binary_fundamental. + eapply bin_log_related_store; eauto using binary_fundamental. + eapply bin_log_related_CAS; eauto using binary_fundamental. + eapply bin_log_related_CAS; eauto using binary_fundamental. + eapply bin_log_related_CAS; eauto using binary_fundamental. Qed. End bin_log_related_under_typed_ctx.
[GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(bind₁ (frobeniusPolyRat p)) (wittPolynomial p ℚ n) = wittPolynomial p ℚ (n + 1) [PROOFSTEP] delta frobeniusPolyRat [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(bind₁ fun n => ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ n)) (wittPolynomial p ℚ n) = wittPolynomial p ℚ (n + 1) [PROOFSTEP] rw [← bind₁_bind₁, bind₁_xInTermsOfW_wittPolynomial, bind₁_X_right, Function.comp_apply] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ frobeniusPolyAux p n = X (n + 1) - ∑ i in range n, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * frobeniusPolyAux p i ^ (j + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) [PROOFSTEP] rw [frobeniusPolyAux, ← Fin.sum_univ_eq_sum_range] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n j : ℕ hj : j < p ^ n ⊢ p ^ (n - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) ∣ Nat.choose (p ^ n) (j + 1) [PROOFSTEP] apply multiplicity.pow_dvd_of_le_multiplicity [GOAL] case a p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n j : ℕ hj : j < p ^ n ⊢ ↑(n - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) ≤ multiplicity p (Nat.choose (p ^ n) (j + 1)) [PROOFSTEP] rw [hp.out.multiplicity_choose_prime_pow hj j.succ_ne_zero] [GOAL] case a p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n j : ℕ hj : j < p ^ n ⊢ ↑(n - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) ≤ ↑(n - Part.get (multiplicity p (Nat.succ j)) (_ : multiplicity.Finite p (Nat.succ j))) [PROOFSTEP] rfl [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n i j : ℕ hi : i ≤ n hj : j < p ^ (n - i) ⊢ j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) } + n = i + j + (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) [PROOFSTEP] generalize h : v p ⟨j + 1, j.succ_pos⟩ = m [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n i j : ℕ hi : i ≤ n hj : j < p ^ (n - i) m : ℕ h : v p { val := j + 1, property := (_ : 0 < Nat.succ j) } = m ⊢ j - m + n = i + j + (n - i - m) [PROOFSTEP] rsuffices ⟨h₁, h₂⟩ : m ≤ n - i ∧ m ≤ j [GOAL] case intro p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n i j : ℕ hi : i ≤ n hj : j < p ^ (n - i) m : ℕ h : v p { val := j + 1, property := (_ : 0 < Nat.succ j) } = m h₁ : m ≤ n - i h₂ : m ≤ j ⊢ j - m + n = i + j + (n - i - m) [PROOFSTEP] rw [tsub_add_eq_add_tsub h₂, add_comm i j, add_tsub_assoc_of_le (h₁.trans (Nat.sub_le n i)), add_assoc, tsub_right_comm, add_comm i, tsub_add_cancel_of_le (le_tsub_of_add_le_right ((le_tsub_iff_left hi).mp h₁))] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n i j : ℕ hi : i ≤ n hj : j < p ^ (n - i) m : ℕ h : v p { val := j + 1, property := (_ : 0 < Nat.succ j) } = m ⊢ m ≤ n - i ∧ m ≤ j [PROOFSTEP] have hle : p ^ m ≤ j + 1 := h ▸ Nat.le_of_dvd j.succ_pos (multiplicity.pow_multiplicity_dvd _) [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n i j : ℕ hi : i ≤ n hj : j < p ^ (n - i) m : ℕ h : v p { val := j + 1, property := (_ : 0 < Nat.succ j) } = m hle : p ^ m ≤ j + 1 ⊢ m ≤ n - i ∧ m ≤ j [PROOFSTEP] exact ⟨(pow_le_pow_iff hp.1.one_lt).1 (hle.trans hj), Nat.le_of_lt_succ ((Nat.lt_pow_self hp.1.one_lt m).trans_le hle)⟩ [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPoly p n) = frobeniusPolyRat p n [PROOFSTEP] rw [frobeniusPoly, RingHom.map_add, RingHom.map_mul, RingHom.map_pow, map_C, map_X, eq_intCast, Int.cast_ofNat, frobeniusPolyRat] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ n) [PROOFSTEP] refine Nat.strong_induction_on n ?_ [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ∀ (n : ℕ), (∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m)) → X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ n) [PROOFSTEP] clear n [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (n : ℕ), (∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m)) → X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ n) [PROOFSTEP] intro n IH [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) ⊢ X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ n) [PROOFSTEP] rw [xInTermsOfW_eq] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) ⊢ X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) ((X n - ∑ i in range n, ↑C (↑p ^ i) * xInTermsOfW p ℚ i ^ p ^ (n - i)) * ↑C (⅟↑p ^ n)) [PROOFSTEP] simp only [AlgHom.map_sum, AlgHom.map_sub, AlgHom.map_mul, AlgHom.map_pow, bind₁_C_right] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) ⊢ X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = (↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (X n) - ∑ x in range n, ↑C (↑p ^ x) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ x) ^ p ^ (n - x)) * ↑C (⅟↑p ^ n) [PROOFSTEP] have h1 : (p : ℚ) ^ n * ⅟(p : ℚ) ^ n = 1 := by rw [← mul_pow, mul_invOf_self, one_pow] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) ⊢ ↑p ^ n * ⅟↑p ^ n = 1 [PROOFSTEP] rw [← mul_pow, mul_invOf_self, one_pow] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 ⊢ X n ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p n) = (↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (X n) - ∑ x in range n, ↑C (↑p ^ x) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ x) ^ p ^ (n - x)) * ↑C (⅟↑p ^ n) [PROOFSTEP] rw [bind₁_X_right, Function.comp_apply, wittPolynomial_eq_sum_C_mul_X_pow, sum_range_succ, sum_range_succ, tsub_self, add_tsub_cancel_left, pow_zero, pow_one, pow_one, sub_mul, add_mul, add_mul, mul_right_comm, mul_right_comm (C ((p : ℚ) ^ (n + 1))), ← C_mul, ← C_mul, pow_succ, mul_assoc (p : ℚ) ((p : ℚ) ^ n), h1, mul_one, C_1, one_mul, add_comm _ (X n ^ p), add_assoc, ← add_sub, add_right_inj, frobeniusPolyAux_eq, RingHom.map_sub, map_X, mul_sub, sub_eq_add_neg, add_comm _ (C (p : ℚ) * X (n + 1)), ← add_sub, show (Int.castRingHom ℚ) ↑p = (p : ℚ) from rfl, add_right_inj, neg_eq_iff_eq_neg, neg_sub, eq_comm] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 ⊢ (∑ x in range n, ↑C (↑p ^ x) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ x) ^ p ^ (n - x)) * ↑C (⅟↑p ^ n) - (∑ x in range n, ↑C (↑p ^ x) * X x ^ p ^ (n + 1 - x)) * ↑C (⅟↑p ^ n) = ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (∑ i in range n, ∑ j in range (p ^ (n - i)), (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * frobeniusPolyAux p i ^ (j + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) [PROOFSTEP] simp only [map_sum, mul_sum, sum_mul, ← sum_sub_distrib] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 ⊢ ∑ x in range n, (↑C (↑p ^ x) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ x) ^ p ^ (n - x) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ x) * X x ^ p ^ (n + 1 - x) * ↑C (⅟↑p ^ n)) = ∑ x in range n, ∑ x_1 in range (p ^ (n - x)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X x ^ p) ^ (p ^ (n - x) - (x_1 + 1)) * frobeniusPolyAux p x ^ (x_1 + 1) * ↑C ↑(Nat.choose (p ^ (n - x)) (x_1 + 1) / p ^ (n - x - v p { val := x_1 + 1, property := (_ : 0 < Nat.succ x_1) }) * p ^ (x_1 - v p { val := x_1 + 1, property := (_ : 0 < Nat.succ x_1) }))) [PROOFSTEP] apply sum_congr rfl [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 ⊢ ∀ (x : ℕ), x ∈ range n → ↑C (↑p ^ x) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ x) ^ p ^ (n - x) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ x) * X x ^ p ^ (n + 1 - x) * ↑C (⅟↑p ^ n) = ∑ x_1 in range (p ^ (n - x)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X x ^ p) ^ (p ^ (n - x) - (x_1 + 1)) * frobeniusPolyAux p x ^ (x_1 + 1) * ↑C ↑(Nat.choose (p ^ (n - x)) (x_1 + 1) / p ^ (n - x - v p { val := x_1 + 1, property := (_ : 0 < Nat.succ x_1) }) * p ^ (x_1 - v p { val := x_1 + 1, property := (_ : 0 < Nat.succ x_1) }))) [PROOFSTEP] intro i hi [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i ∈ range n ⊢ ↑C (↑p ^ i) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ i) ^ p ^ (n - i) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ i) * X i ^ p ^ (n + 1 - i) * ↑C (⅟↑p ^ n) = ∑ x in range (p ^ (n - i)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] rw [mem_range] at hi [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n ⊢ ↑C (↑p ^ i) * ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ i) ^ p ^ (n - i) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ i) * X i ^ p ^ (n + 1 - i) * ↑C (⅟↑p ^ n) = ∑ x in range (p ^ (n - i)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] rw [← IH i hi] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ IH : ∀ (m : ℕ), m < n → X m ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p m) = ↑(bind₁ (wittPolynomial p ℚ ∘ fun n => n + 1)) (xInTermsOfW p ℚ m) h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n ⊢ ↑C (↑p ^ i) * (X i ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ p ^ (n - i) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ i) * X i ^ p ^ (n + 1 - i) * ↑C (⅟↑p ^ n) = ∑ x in range (p ^ (n - i)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] clear IH [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n ⊢ ↑C (↑p ^ i) * (X i ^ p + ↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ p ^ (n - i) * ↑C (⅟↑p ^ n) - ↑C (↑p ^ i) * X i ^ p ^ (n + 1 - i) * ↑C (⅟↑p ^ n) = ∑ x in range (p ^ (n - i)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] rw [add_comm (X i ^ p), add_pow, sum_range_succ', pow_zero, tsub_zero, Nat.choose_zero_right, one_mul, Nat.cast_one, mul_one, mul_add, add_mul, Nat.succ_sub (le_of_lt hi), Nat.succ_eq_add_one (n - i), pow_succ, pow_mul, add_sub_cancel, mul_sum, sum_mul] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n ⊢ ∑ x in range (p ^ (n - i)), ↑C (↑p ^ i) * ((↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ (x + 1) * (X i ^ p) ^ (p ^ (n - i) - (x + 1)) * ↑(Nat.choose (p ^ (n - i)) (x + 1))) * ↑C (⅟↑p ^ n) = ∑ x in range (p ^ (n - i)), ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] apply sum_congr rfl [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n ⊢ ∀ (x : ℕ), x ∈ range (p ^ (n - i)) → ↑C (↑p ^ i) * ((↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ (x + 1) * (X i ^ p) ^ (p ^ (n - i) - (x + 1)) * ↑(Nat.choose (p ^ (n - i)) (x + 1))) * ↑C (⅟↑p ^ n) = ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (x + 1)) * frobeniusPolyAux p i ^ (x + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (x + 1) / p ^ (n - i - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }) * p ^ (x - v p { val := x + 1, property := (_ : 0 < Nat.succ x) }))) [PROOFSTEP] intro j hj [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j ∈ range (p ^ (n - i)) ⊢ ↑C (↑p ^ i) * ((↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ (j + 1) * (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * ↑(Nat.choose (p ^ (n - i)) (j + 1))) * ↑C (⅟↑p ^ n) = ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (j + 1)) * frobeniusPolyAux p i ^ (j + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) [PROOFSTEP] rw [mem_range] at hj [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑C (↑p ^ i) * ((↑C (↑(Int.castRingHom ℚ) ↑p) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i)) ^ (j + 1) * (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * ↑(Nat.choose (p ^ (n - i)) (j + 1))) * ↑C (⅟↑p ^ n) = ↑C ↑p * ↑(MvPolynomial.map (Int.castRingHom ℚ)) ((X i ^ p) ^ (p ^ (n - i) - (j + 1)) * frobeniusPolyAux p i ^ (j + 1) * ↑C ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) [PROOFSTEP] rw [RingHom.map_mul, RingHom.map_mul, RingHom.map_pow, RingHom.map_pow, RingHom.map_pow, RingHom.map_pow, RingHom.map_pow, map_C, map_X, mul_pow] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑C ↑p ^ i * (↑C (↑(Int.castRingHom ℚ) ↑p) ^ (j + 1) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * ↑(Nat.choose (p ^ (n - i)) (j + 1))) * ↑C ⅟↑p ^ n = ↑C ↑p * ((X i ^ p) ^ (p ^ (n - i) - (j + 1)) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * ↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })))) [PROOFSTEP] rw [mul_comm (C (p : ℚ) ^ i), mul_comm _ ((X i ^ p) ^ _), show (Int.castRingHom ℚ) ↑p = (p : ℚ) from rfl, mul_comm (C (p : ℚ) ^ (j + 1)), mul_comm (C (p : ℚ))] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * ↑C ↑p ^ (j + 1)) * ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑C ↑p ^ i * ↑C ⅟↑p ^ n = (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * ↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) * ↑C ↑p [PROOFSTEP] simp only [mul_assoc] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * (↑C ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑C ↑p ^ i * ↑C ⅟↑p ^ n)))) = (X i ^ p) ^ (p ^ (n - i) - (j + 1)) * (↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * (↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) * ↑C ↑p)) [PROOFSTEP] apply congr_arg [GOAL] case h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * (↑C ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑C ↑p ^ i * ↑C ⅟↑p ^ n))) = ↑(MvPolynomial.map (Int.castRingHom ℚ)) (frobeniusPolyAux p i) ^ (j + 1) * (↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) * ↑C ↑p) [PROOFSTEP] apply congr_arg [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑C ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑C ↑p ^ i * ↑C ⅟↑p ^ n)) = ↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) * ↑C ↑p [PROOFSTEP] rw [← C_eq_coe_nat] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑C ↑p ^ (j + 1) * (↑C ↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑C ↑p ^ i * ↑C ⅟↑p ^ n)) = ↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) * ↑C ↑p [PROOFSTEP] simp only [← RingHom.map_pow, ← C_mul] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑C (↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * ⅟↑p ^ n))) = ↑C (↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑p) [PROOFSTEP] rw [C_inj] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * ⅟↑p ^ n)) = ↑(Int.castRingHom ℚ) ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑p [PROOFSTEP] simp only [invOf_eq_inv, eq_intCast, inv_pow, Int.cast_ofNat, Nat.cast_mul, Int.cast_mul] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * (↑p ^ n)⁻¹)) = ↑(Nat.choose (p ^ (n - i)) (j + 1) / p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑(p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑p [PROOFSTEP] rw [Rat.coe_nat_div _ _ (map_frobeniusPoly.key₁ p (n - i) j hj)] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑p ^ (j + 1) * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * (↑p ^ n)⁻¹)) = ↑(Nat.choose (p ^ (n - i)) (j + 1)) / ↑(p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑(p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) })) * ↑p [PROOFSTEP] simp only [Nat.cast_pow, pow_add, pow_one] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑p ^ j * ↑p * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * (↑p ^ n)⁻¹)) = ↑(Nat.choose (p ^ (n - i)) (j + 1)) / ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p [PROOFSTEP] suffices (((p ^ (n - i)).choose (j + 1) : ℚ) * (p : ℚ) ^ (j - v p ⟨j + 1, j.succ_pos⟩) * ↑p * (p ^ n : ℚ)) = (p : ℚ) ^ j * p * ↑((p ^ (n - i)).choose (j + 1) * p ^ i) * (p : ℚ) ^ (n - i - v p ⟨j + 1, j.succ_pos⟩) by have aux : ∀ k : ℕ, (p : ℚ) ^ k ≠ 0 := by intro; apply pow_ne_zero; exact_mod_cast hp.1.ne_zero simpa [aux, -one_div, field_simps] using this.symm [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) this : ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) ⊢ ↑p ^ j * ↑p * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * (↑p ^ n)⁻¹)) = ↑(Nat.choose (p ^ (n - i)) (j + 1)) / ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p [PROOFSTEP] have aux : ∀ k : ℕ, (p : ℚ) ^ k ≠ 0 := by intro; apply pow_ne_zero; exact_mod_cast hp.1.ne_zero [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) this : ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) ⊢ ∀ (k : ℕ), ↑p ^ k ≠ 0 [PROOFSTEP] intro [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) this : ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) k✝ : ℕ ⊢ ↑p ^ k✝ ≠ 0 [PROOFSTEP] apply pow_ne_zero [GOAL] case h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) this : ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) k✝ : ℕ ⊢ ↑p ≠ 0 [PROOFSTEP] exact_mod_cast hp.1.ne_zero [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) this : ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) aux : ∀ (k : ℕ), ↑p ^ k ≠ 0 ⊢ ↑p ^ j * ↑p * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * (↑p ^ i * (↑p ^ n)⁻¹)) = ↑(Nat.choose (p ^ (n - i)) (j + 1)) / ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p [PROOFSTEP] simpa [aux, -one_div, field_simps] using this.symm [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (j - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) * ↑p * ↑(p ^ n) = ↑p ^ j * ↑p * ↑(Nat.choose (p ^ (n - i)) (j + 1) * p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) [PROOFSTEP] rw [mul_comm _ (p : ℚ), mul_assoc, Nat.cast_pow, mul_assoc, ← pow_add, map_frobeniusPoly.key₂ p hi.le hj, Nat.cast_mul, Nat.cast_pow] [GOAL] case h.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ h1 : ↑p ^ n * ⅟↑p ^ n = 1 i : ℕ hi : i < n j : ℕ hj : j < p ^ (n - i) ⊢ ↑p * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ (i + j + (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }))) = ↑p ^ j * ↑p * (↑(Nat.choose (p ^ (n - i)) (j + 1)) * ↑p ^ i) * ↑p ^ (n - i - v p { val := j + 1, property := (_ : 0 < Nat.succ j) }) [PROOFSTEP] ring [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n) = X n ^ p [PROOFSTEP] rw [frobeniusPoly, RingHom.map_add, RingHom.map_pow, RingHom.map_mul, map_X, map_C] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ X n ^ p + ↑C (↑(Int.castRingHom (ZMod p)) ↑p) * ↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPolyAux p n) = X n ^ p [PROOFSTEP] simp only [Int.cast_ofNat, add_zero, eq_intCast, ZMod.nat_cast_self, zero_mul, C_0] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(bind₁ (frobeniusPoly p)) (wittPolynomial p ℤ n) = wittPolynomial p ℤ (n + 1) [PROOFSTEP] apply MvPolynomial.map_injective (Int.castRingHom ℚ) Int.cast_injective [GOAL] case a p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ ⊢ ↑(MvPolynomial.map (Int.castRingHom ℚ)) (↑(bind₁ (frobeniusPoly p)) (wittPolynomial p ℤ n)) = ↑(MvPolynomial.map (Int.castRingHom ℚ)) (wittPolynomial p ℤ (n + 1)) [PROOFSTEP] simp only [map_bind₁, map_frobeniusPoly, bind₁_frobeniusPolyRat_wittPolynomial, map_wittPolynomial] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S x : 𝕎 R n : ℕ ⊢ coeff (frobeniusFun x) n = ↑(aeval x.coeff) (frobeniusPoly p n) [PROOFSTEP] rw [frobeniusFun, coeff_mk] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ ⦃R : Type ?u.420485⦄ [inst : CommRing R] (x : 𝕎 R), (frobeniusFun x).coeff = fun n => ↑(aeval x.coeff) (frobeniusPoly p n) [PROOFSTEP] intros [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S R✝ : Type ?u.420485 inst✝ : CommRing R✝ x✝ : 𝕎 R✝ ⊢ (frobeniusFun x✝).coeff = fun n => ↑(aeval x✝.coeff) (frobeniusPoly p n) [PROOFSTEP] funext n [GOAL] case h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S R✝ : Type ?u.420485 inst✝ : CommRing R✝ x✝ : 𝕎 R✝ n : ℕ ⊢ coeff (frobeniusFun x✝) n = ↑(aeval x✝.coeff) (frobeniusPoly p n) [PROOFSTEP] apply coeff_frobeniusFun [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S n : ℕ x : 𝕎 R ⊢ ↑(ghostComponent n) (frobeniusFun x) = ↑(ghostComponent (n + 1)) x [PROOFSTEP] simp only [ghostComponent_apply, frobeniusFun, coeff_mk, ← bind₁_frobeniusPoly_wittPolynomial, aeval_bind₁] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ frobeniusFun 1 = 1 [PROOFSTEP] refine -- Porting note: removing the placeholders give an errorIsPoly.ext (@IsPoly.comp p _ _ (frobeniusFun_isPoly p) WittVector.oneIsPoly) (@IsPoly.comp p _ _ WittVector.oneIsPoly (frobeniusFun_isPoly p)) ?_ _ 0 [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (R : Type u_1) [_Rcr : CommRing R] (x : 𝕎 R) (n : ℕ), ↑(ghostComponent n) ((frobeniusFun ∘ fun x => 1) x) = ↑(ghostComponent n) (((fun x => 1) ∘ frobeniusFun) x) [PROOFSTEP] simp only [Function.comp_apply, map_one, forall_const] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (R : Type u_1) [_Rcr : CommRing R] (n : ℕ), ↑(ghostComponent n) (frobeniusFun 1) = 1 [PROOFSTEP] ghost_simp [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y [PROOFSTEP] ghost_calc _ _ [GOAL] case refine_3 p : ℕ S : Type u_2 hp : Fact (Nat.Prime p) inst✝ : CommRing S R : Type u_1 R._inst : CommRing R x✝ y✝ : 𝕎 R ⊢ ∀ (n : ℕ), ↑(ghostComponent n) (OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x✝ * y✝)) = ↑(ghostComponent n) (OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x✝ * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y✝) [PROOFSTEP] ghost_simp [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) 0 = 0 [PROOFSTEP] refine IsPoly.ext (@IsPoly.comp p _ _ (frobeniusFun_isPoly p) WittVector.zeroIsPoly) (@IsPoly.comp p _ _ WittVector.zeroIsPoly (frobeniusFun_isPoly p)) ?_ _ 0 [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (R : Type u_1) [_Rcr : CommRing R] (x : 𝕎 R) (n : ℕ), ↑(ghostComponent n) ((frobeniusFun ∘ fun x => 0) x) = ↑(ghostComponent n) (((fun x => 0) ∘ frobeniusFun) x) [PROOFSTEP] simp only [Function.comp_apply, map_zero, forall_const] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (R : Type u_1) [_Rcr : CommRing R] (n : ℕ), ↑(ghostComponent n) (frobeniusFun 0) = 0 [PROOFSTEP] ghost_simp [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝¹ : CommRing R inst✝ : CommRing S ⊢ ∀ (x y : 𝕎 R), OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) (x + y) = OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) x + OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) y [PROOFSTEP] ghost_calc _ _ [GOAL] case refine_3 p : ℕ S : Type u_2 hp : Fact (Nat.Prime p) inst✝ : CommRing S R : Type u_1 R._inst : CommRing R x✝ y✝ : 𝕎 R ⊢ ∀ (n : ℕ), ↑(ghostComponent n) (OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) (x✝ + y✝)) = ↑(ghostComponent n) (OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) x✝ + OneHom.toFun (↑{ toOneHom := { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) }, map_mul' := (_ : ∀ (x y : 𝕎 R), OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } (x * y) = OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } x * OneHom.toFun { toFun := frobeniusFun, map_one' := (_ : (frobeniusFun ∘ fun x => 1) 0 = ((fun x => 1) ∘ frobeniusFun) 0) } y) }) y✝) [PROOFSTEP] ghost_simp [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ ⊢ coeff (↑frobenius x) n = coeff x n ^ p [PROOFSTEP] rw [coeff_frobenius] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ ⊢ ↑(aeval x.coeff) (frobeniusPoly p n) = coeff x n ^ p [PROOFSTEP] letI : Algebra (ZMod p) R := ZMod.algebra _ _ -- outline of the calculation, proofs follow below [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p ⊢ ↑(aeval x.coeff) (frobeniusPoly p n) = coeff x n ^ p [PROOFSTEP] calc aeval (fun k => x.coeff k) (frobeniusPoly p n) = aeval (fun k => x.coeff k) (MvPolynomial.map (Int.castRingHom (ZMod p)) (frobeniusPoly p n)) := ?_ _ = aeval (fun k => x.coeff k) (X n ^ p : MvPolynomial ℕ (ZMod p)) := ?_ _ = x.coeff n ^ p := ?_ [GOAL] case calc_1 p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p ⊢ ↑(aeval fun k => coeff x k) (frobeniusPoly p n) = ↑(aeval fun k => coeff x k) (↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n)) [PROOFSTEP] conv_rhs => rw [aeval_eq_eval₂Hom, eval₂Hom_map_hom] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p | ↑(aeval fun k => coeff x k) (↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n)) [PROOFSTEP] rw [aeval_eq_eval₂Hom, eval₂Hom_map_hom] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p | ↑(aeval fun k => coeff x k) (↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n)) [PROOFSTEP] rw [aeval_eq_eval₂Hom, eval₂Hom_map_hom] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p | ↑(aeval fun k => coeff x k) (↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n)) [PROOFSTEP] rw [aeval_eq_eval₂Hom, eval₂Hom_map_hom] [GOAL] case calc_1 p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p ⊢ ↑(aeval fun k => coeff x k) (frobeniusPoly p n) = ↑(eval₂Hom (RingHom.comp (algebraMap (ZMod p) R) (Int.castRingHom (ZMod p))) fun k => coeff x k) (frobeniusPoly p n) [PROOFSTEP] apply eval₂Hom_congr (RingHom.ext_int _ _) rfl rfl [GOAL] case calc_2 p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p ⊢ ↑(aeval fun k => coeff x k) (↑(MvPolynomial.map (Int.castRingHom (ZMod p))) (frobeniusPoly p n)) = ↑(aeval fun k => coeff x k) (X n ^ p) [PROOFSTEP] rw [frobeniusPoly_zmod] [GOAL] case calc_3 p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ this : Algebra (ZMod p) R := ZMod.algebra R p ⊢ ↑(aeval fun k => coeff x k) (X n ^ p) = coeff x n ^ p [PROOFSTEP] rw [map_pow, aeval_X] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p ⊢ frobenius = map (_root_.frobenius R p) [PROOFSTEP] ext (x n) [GOAL] case a.h p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 R n : ℕ ⊢ coeff (↑frobenius x) n = coeff (↑(map (_root_.frobenius R p)) x) n [PROOFSTEP] simp only [coeff_frobenius_charP, map_coeff, frobenius_def] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝² : CommRing R inst✝¹ : CommRing S inst✝ : CharP R p x : 𝕎 (ZMod p) ⊢ ↑frobenius x = x [PROOFSTEP] simp only [ext_iff, coeff_frobenius_charP, ZMod.pow_card, eq_self_iff_true, forall_const] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝³ : CommRing R inst✝² : CommRing S inst✝¹ : CharP R p inst✝ : PerfectRing R p src✝ : 𝕎 R →+* 𝕎 R := frobenius f : 𝕎 R n : ℕ ⊢ coeff (↑(map ↑(RingEquiv.symm (_root_.frobeniusEquiv R p))) (↑frobenius f)) n = coeff f n [PROOFSTEP] rw [frobenius_eq_map_frobenius] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝³ : CommRing R inst✝² : CommRing S inst✝¹ : CharP R p inst✝ : PerfectRing R p src✝ : 𝕎 R →+* 𝕎 R := frobenius f : 𝕎 R n : ℕ ⊢ coeff (↑(map ↑(RingEquiv.symm (_root_.frobeniusEquiv R p))) (↑(map (_root_.frobenius R p)) f)) n = coeff f n [PROOFSTEP] exact frobeniusEquiv_symm_apply_frobenius R p _ [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝³ : CommRing R inst✝² : CommRing S inst✝¹ : CharP R p inst✝ : PerfectRing R p src✝ : 𝕎 R →+* 𝕎 R := frobenius f : 𝕎 R n : ℕ ⊢ coeff (↑frobenius (↑(map ↑(RingEquiv.symm (_root_.frobeniusEquiv R p))) f)) n = coeff f n [PROOFSTEP] rw [frobenius_eq_map_frobenius] [GOAL] p : ℕ R : Type u_1 S : Type u_2 hp : Fact (Nat.Prime p) inst✝³ : CommRing R inst✝² : CommRing S inst✝¹ : CharP R p inst✝ : PerfectRing R p src✝ : 𝕎 R →+* 𝕎 R := frobenius f : 𝕎 R n : ℕ ⊢ coeff (↑(map (_root_.frobenius R p)) (↑(map ↑(RingEquiv.symm (_root_.frobeniusEquiv R p))) f)) n = coeff f n [PROOFSTEP] exact frobenius_apply_frobeniusEquiv_symm R p _
Jordan and the Bulls compiled a 62 – 20 record in the 1997 – 98 season . Jordan led the league with 28 @.@ 7 points per game , securing his fifth regular @-@ season MVP award , plus honors for All @-@ NBA First Team , First Defensive Team and the All @-@ Star Game MVP . The Bulls won the Eastern Conference Championship for a third straight season , including surviving a seven @-@ game series with the Indiana Pacers in the Eastern Conference Finals ; it was the first time Jordan had played in a Game 7 since the 1992 Eastern Conference Semifinals with the Knicks . After winning , they moved on for a rematch with the Jazz in the Finals .
[STATEMENT] lemma filter_pm_code [code]: "filter_pm P (Pm_fmap m) = Pm_fmap (fmfilter P m)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. filter_pm P (Pm_fmap m) = Pm_fmap (fmfilter P m) [PROOF STEP] by (auto intro!: poly_mapping_eqI simp: fmlookup_default_def lookup_filter_pm)