Datasets:
AI4M
/

text
stringlengths
0
3.34M
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__149.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash_nodata_cub Protocol Case Study*} theory n_flash_nodata_cub_lemma_on_inv__149 imports n_flash_nodata_cub_base begin section{*All lemmas on causal relation between inv__149 and some rule r*} lemma n_PI_Remote_PutXVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_ReplaceVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_PutVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_DirtyVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__149: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_Put_HomeVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_1Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_2Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_3Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_4Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_5Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_6Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_HomeVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8Vsinv__149: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__149: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10_HomeVsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10Vsinv__149: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_11Vsinv__149: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__149: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HeadVld'')) (Const false)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvVsinv__149: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__149: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__149: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutXAcksDoneVsinv__149: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_WbVsinv__149: assumes a1: "(r=n_NI_Wb )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__149 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_Get_Get__part__1Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetVsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__0Vsinv__149: assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__1Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_1Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__1Vsinv__149: assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__0Vsinv__149: assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_ReplaceVsinv__149: assumes a1: "r=n_PI_Local_Replace " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__1Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__1Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Get__part__0Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__149: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__2Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Put_HeadVsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_PutXVsinv__149: assumes a1: "r=n_PI_Local_PutX " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__2Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__0Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_PutVsinv__149: assumes a1: "r=n_PI_Local_Get_Put " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__149: assumes a1: "r=n_NI_ShWb N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_Nak_HomeVsinv__149: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_NakVsinv__149: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_NakVsinv__149: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetXVsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__1Vsinv__149: assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Nak_HomeVsinv__149: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__0Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__149: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_PutVsinv__149: assumes a1: "r=n_NI_Local_Put " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_NakVsinv__149: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__149: assumes a1: "r=n_NI_Nak_Clear " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__0Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_GetVsinv__149: assumes a1: "r=n_PI_Local_Get_Get " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_HomeVsinv__149: assumes a1: "r=n_NI_Nak_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__149: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__149: assumes a1: "r=n_NI_FAck " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__149 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
function F = vertcat(F , G) %VERTCAT Vertical concatenation of SPHEREFUNV objects. % [F ; f] where F is a SPHEREFUNV with two components, and f is a SPHEREFUN or % scalar then returns a SPHEREFUNV with three components. The first and second % component remain unchanged and the third component is f. % % [f ; F] where F is a SPHEREFUNV with two components, and f is a SPHEREFUN or % scalar then returns a SPHEREFUNV with three components. The first is f, and % the second and third are the first and second components of F. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. if ( isempty(F) || isempty(G) ) F = spherefunv; return end if ( isa(G, 'double') ) Fc = F.components; dom = Fc{1}.domain; G = spherefun(G, Fc{1}.domain); elseif ( isa(F, 'double') ) Gc = G.components; dom = Gc{1}.domain; F = spherefun(F, Gc{1}.domain); elseif ( isa(G, 'spherefun') ) if ( ~domainCheck(F.components{1}, G) ) error('SPHEREFUN:SPHEREFUNV:vertcat:domain', 'Inconsistent domains.') end dom = G.domain; else error('SPHEREFUN:SPHEREFUNV:vertcat:notSupported', ... 'Vertical concatenation of these objects is not supported.') end if ( isa(F, 'spherefunv') ) op = [ F.components, {G} ]; else op = [ {F}, G.components ]; end F = spherefunv(op, dom); end
subroutine php_bounod(a) !----------------------------------------------------------------------- ! Passes conditions on boundaries to nodal conditions. !----------------------------------------------------------------------- use typre use Mod_PhysicalProblem implicit none class(PhysicalProblem) :: a integer(ip) :: nboun,pnodb,ipoin,idime,iboun,mnodb,inodb integer(ip), allocatable :: lnodb(:) character(150) :: outstr call a%Mesh%GetMnodb(mnodb) call a%Mesh%GetNboun(nboun) a%gmnodb = mnodb !Output outstr = adjustl(trim(a%exmod))//'_bounod' call a%Memor%alloc(mnodb,lnodb,'lnodb',outstr) ! Loop over boundaries do iboun=1,nboun !For Specific call a%giboun = iboun ! Dirichlet if(a%kfl_fixbo(iboun)==1) then a%kfl_fixbo(iboun) = 0 call a%Mesh%GetLnodb(iboun,pnodb,lnodb) do inodb=1,pnodb ipoin = lnodb(inodb) if(maxval(a%kfl_fixno(:,ipoin)) == -1) then a%kfl_fixno(:,ipoin)=1 do idime=1,a%ndofbc a%bvess(idime,ipoin,1)=a%bvnat(iboun)%a((inodb-1)*a%ndofbc+idime) end do if(a%kfl_conbc==0) then a%kfl_funno(ipoin)=a%kfl_funbo(iboun) do idime=1,a%ndofbc a%bvess(idime,ipoin,2)=a%bvess(idime,ipoin,1) end do end if !Specific call a%gipoin = ipoin call a%SpecificBounod(1) end if end do endif call a%SpecificBounod(2) end do call a%SpecificBounod(3) call a%Memor%dealloc(mnodb,lnodb,'lnodb',outstr) end subroutine php_bounod
Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Specific.solinas32_2e450m2e225m1_20limbs.Synthesis. (* TODO : change this to field once field isomorphism happens *) Definition freeze : { freeze : feBW_tight -> feBW_limbwidths | forall a, phiBW_limbwidths (freeze a) = phiBW_tight a }. Proof. Set Ltac Profiling. Time synthesize_freeze (). Show Ltac Profile. Time Defined. Print Assumptions freeze.
% TODO: Proofread % FINISHED: % explain bundling environments % explain the construction and implementation of DSemi and DEmpty % rewrite the semantic rules % rewrite rules to have a single env % explain the CBR and CBV declarations % rewrite rules to include CBR and CBV % explain and demonstrate next being contined in the environment itself % rewrite to include the next var in the sto % explain the unionE operator on envs % \newrule{top}{bot}{name} \input{frontmatter.tex} \begin{document} \input{4780_heading.tex} The following document describes the language of \bold{Bumps+}, an extension of the language \bold{Bumps} presented in Transitions and Trees\footnote{Huttel, 2010}. \bold{Bumps+} describes the semantics for a variation of \bold{Bumps} where the Variable Declarations and Procedure Declarations have been combined so that the Variable Environments, \bold{EnvV}, and the Procedure Environments, \bold{EnvP}, are combined into a single environment record, \bold{Env}. \section{6.1}{Abstract Syntax of Bumps+} In order to facilitate the bundling of environment records into a single record, we modify the abstract syntax rules to describe only two categories. \begin{itemize} \item \bold{Pnames - } the category of procedure names (unchanged from \bold{Bips}) \item \bold{Dec - } the category of declarations, both variable and procedure \end{itemize} We continue to denote elements of \bold{Pnames} by $p,q,...$ and now denote elements of \bold{Dec} by $V$. The formation rules of \bold{Aexp} and \bold{BExp} remain unchanged from their description in the book, but the formation rules below now describe the new rules for \bold{Stm} and \bold{Dec}. Furthermore, $\epsilon$ continues to denote the empty declaration. \begin{align*} S ::=\;& x := a \;|\; \texttt{skip} \;|\; S_1;S_2 \;|\; \texttt{if } b \texttt{ then } S_1 \texttt{ else } S_2 \;|\; \\ &\texttt{while } b \texttt{ do } S \;|\; \texttt{begin } V \; S \texttt{ end} \;|\; \texttt{call } p(y) \;|\; \code{call } p(\code{\&}y)\\ V ::=& \texttt{ var } x := a \;|\; \texttt{proc } p(\code{var } x) \texttt{ is } S \;|\; \code{proc } p(x) \code{ is } S \;|\; V_1 ; V_2 \;|\; \epsilon \end{align*} \newpage Walking through the changes to the syntax of \bold{Bumps} to get \bold{Bumps+} we see the following changes: \begin{itemize} \item The \code{begin...end} command has changed to combine the $D_V \; D_P$ representation of the environments into a single representation $V$ to be consistent with our new declarations for the environment. \item Two \code{call...} options are present, one with an ampersand preceding the parameter and one without. These correspond to calling the procedure $p$ by reference and by value respectively. \item $D_V$ and $D_P$ have been combined into a single environment record, $V$. \item There are two declarations for procedures, one containing the keyword \code{var} and one without. These correspond to call by reference and call by value respectively. \item $V$ no longer contains a recursive description at the end of a declaration, but contains the sequencing like operation $V_1;V_2$. This functions in the same manner as sequencing for statements and allows declarations to be sequenced. It also corresponds to the implementation of \bold{Bumps} in \code{Bumps\_Final.hs}.\footnote{This construction and implementation will be discussed in more detail below.} \end{itemize} \section{6.2}{Changes to the Environment Model in \bold{Bumps+}} The changes to the environment system allow us to eliminate the complexity of passing both a $EnvV$ and $EnvP$ argument around as we evaluate code written in \bold{Bumps+}. It also has the beneficial side effect of allowing us to declare procedures and variables in any order, a change from Huttel's descriptions that forced variables to be declared before procedures. This simplicity will become apparent in further sections of this paper where the semantic rules are updated to conform to this new paradigm. \par In the implementation of these rules, the haskell code makes use of two constructors in the declaration data type, \code{Decl}, namely \code{DSemi} and \code{DEmpty}. Through comparison, we can see that the constructor \code{DSemi} is identical to the constructor \code{Seq} for sequences. \code{DSemi Decl Decl} and \code{Seq Stm Stm} both sequence two objects of their parent data type, \code{Decl} and \code{Stm} respectively which correspond to our abstract syntax of $V$ and $S$. \code{DEmpty} is a constructor of \code{Decl} as well and takes no arguments. Because of this, we know that it acts as a terminal character or the implementation of $\epsilon$. Without it, it would be impossible to have 0 declarations, but since it is present, it is therefore possible to have any number of declarations in any combination of variables and procedures. \par The final addition that makes this bundling possible is the addition of the \code{`unionE`} operator on environments. It functions in the way one would expect a union operator to work, returning the environment made up of the union of variable declarations and the union of procedure declarations. Something worth note is that due to implementation restrictions, the values stored in the first environment take precedence over those stored in the second when using the \code{`unionE`} operation. \section{6.3}{Evaluation of expressions in the new environment paradigm} As noted by Huttel, the semantics of statements and declarations both depend on the semantics of \bold{Aexp} and those expressions may contain variables. Since the way in which variables are processed and stored has been completely renovated, the rules for evaluating these epxressions will be redefined. The transition system remains the same, but all all transitions will now be of the form $\start a \; \to_a \; v$ and can be read as "given the variables and procedures known by $env$ and the storage content of $sto$, the arithmetic expression $a$ evaluates to the value $v$." \par The following rules now represent the new Big Step Semantic rules\footnote{A change from the textbook, the BSS is omitted from the name of rules for simplicity and since small step semantic rules will not be defined in this paper.}: % % BSS Rules for evaluating A expressions % \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} \newrulewhere{$\start a_1 \to_a \; v_1 \;|\; \start a_2 \to_a v_2$}{$\start a_1 + a_2 \to_a v$}{PLUS-BUMPS+}{$v = v_1 + v_2$} \newrulewhere{$\start a_1 \to_a \; v_1 \;|\; \start a_2 \to_a v_2$}{$\start a_1 - a_2 \to_a v$}{MINUS-BUMPS+}{$v = v_1 - v_2$} \newrulewhere{$\start a_1 \to_a \; v_1 \;|\; \start a_2 \to_a v_2$}{$\start a_1 * a_2 \to_a v$}{MULT-BUMPS+}{$v = v_1 \cdot v_2$} \newrule{$\start a_1 \to_a v_1$}{$\start (a_1) \to_a v_1$}{PARENT-BUMPS+} \newruleflat{$\start n \to_a v$ if $\aleph[|n|]=v$\footnote{$\aleph$ will stand in for the scripty N in Huttel's book and [$|$ will stand in for the double bar bracket.}}{NUM-BUMPS+} \newruleflat{$\start x \to_a v$ if $env \; x = l$ and $sto \; l = v$}{VAR-BUMPS+} \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} \section{6.4}{Changes to Declaration Big Step Semantics} With the changes to declarations presented in this paper, the declaration operational semantics presented by Huttel must be modified. The execution of a \code{begin...end} block will evaluate all types of declarations before executing statements. Now these environment operational semantic changes will be described. % % BSS Rules for Statements % \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} \newruleflatwhere{$env \; \vdash \langle x := a, sto \rangle \to sto[l \mapsto v]$}{ASS-BUMPS+}{$\start a \to_a v$ and $env \; x = l$} \newruleflat{$env \; \vdash \langle \code{skip}, sto \rangle \to sto$}{SKIP-BUMPS+} \begin{center} $env \; \vdash \langle S_1, sto \rangle \to sto''$ \\ $env \; \vdash \langle S_2, sto'' \rangle \to sto'$ \\ $[$COMP-BUMPS+$]$ \line(1,0){300} \\ $env \; \vdash \langle S_1;S_2,sto \rangle \to sto'$ \end{center} \newrulewhere{$env \; \vdash \langle S_1, sto \rangle \to sto'$}{$env \; \vdash \langle \code{if } b \code{ then } S_1 \code{ else } S_2, sto \rangle \to sto'$}{IF-TRUE-BUMPS+}{$\start b \to_b tt$} \newrulewhere{$env \; \vdash \langle S_2, sto \rangle \to sto'$}{$env \; \vdash \langle \code{if } b \code{ then } S_1 \code{ else } S_2, sto \rangle \to sto'$}{IF-TRUE-BUMPS+}{$\start b \to_b ff$} \begin{center} $env \; \vdash \langle S, sto \rangle \to sto''$ \\ $env \; \vdash \langle \code{while } b \code{ do } S, sto'' \rangle \to sto'$ \\ $[$WHILE-TRUE-BUMPS+$]$ \line(1,0){300} \\ $env \; \vdash \langle \code{while } b \code{ do } S,sto \rangle \to sto'$ \\ where $\start b \to_b tt$ \end{center} \newruleflatwhere{$env \; \vdash \langle \code{while } b \code{ do } S, sto \rangle \to sto$}{WHILE-FALSE-BUMPS+}{$\start b \to_b ff$} \begin{center} $\langle V, env, sto \rangle \to_V (env' sto'')$ \\ $env' \; \vdash \langle S, sto'' \rangle \to sto'$ \\ $[$BLOCK-BUMPS+$]$ \line(1,0){300} \\ $env \; \vdash \langle \code{begin } V \; S \code{ end},sto \rangle \to sto'$ \end{center} \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} To complete this new set of Big Step Semantic rules for everything except procedure calls, a new transition is declared, $\to_V$. This transtion system is defined as a union between the transitions $\to_{DP}$ and $\to_{DV}$ presented in the Huttel text. Furthermore, this transition system, allows the big step semantics for procedures as: \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} \newrule{$env \; \vdash \langle V, env[p \mapsto (S, x, env)]\rangle \to_V env'$}{$env \; \vdash \langle \code{proc } p(\code{var } x) \code{ is } S; V, env \rangle \to_V env'$}{PROC-REF-BUMPS+} \newrule{$env \; \vdash \langle V, env[p \mapsto (S, x, env)]\rangle \to_V env'$}{$env \; \vdash \langle \code{proc } p(x) \code{ is } S; V, env \rangle \to_V env'$}{PROC-VAL-BUMPS+} \newruleflat{$env \; \vdash \langle \epsilon, env \rangle \to_V env$}{PROC-EMPTY-BUMPS+} \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} These new definitions of the big step semantic rules for \bold{BUMPS+} fully define the language in terms of the new bundled environment record. The only missing operation is the \code{call} operation that allows us to call procedures. \section{6.5}{Call-by-reference and Call-by-value Syntax} The code in \code{Bumps\_Final.hs} supports both call by reference and call by value, as a result, rules for both will be defined using the syntax notation presented in the haskell file and defined in the abstract syntax rules presented in \bold{Section 6.1}. \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} \newrulewhere{$env'[x \mapsto l] \; \vdash \langle S, sto \rangle \to sto'$}{$env \; \vdash \langle \code{call } p(\code{\&}y), sto \rangle \to sto' $}{CALL-REF-BUMPS+}{$env \; p = (S, x, env')$ and $l = env \; y$} \newrulewhere{$env'[x \mapsto l] \; \vdash \langle S, sto[l \mapsto v]\rangle \to sto'$}{$env \; \vdash \langle \code{call } p(y), sto \rangle \to sto'$}{CALL-VAL-BUMPS+}{$env \; p = (S, x, env')$ and $\start a \to_a v$} \noindent\makebox[\linewidth]{\rule{\textwidth}{0.4pt}} An observant reader will notice that nowhere is the value of $l$ updated to the new/next free storage location. This is because the implementation of \bold{BUMPS+} in \code{Bumps\_Final.hs} abstracts this operation away from the environment and places it within the \bold{Sto}. This abstraction simplifies the abstract syntax rules and tasks the \code{alloc} function with automatically updating it whenever a new variable is placed within the \bold{Sto}. \end{document}
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall O E Eprime P A B C A1 B1 C1 C1prime M D1prime N : Universe, ((wd_ O E /\ (wd_ A C /\ (wd_ B P /\ (wd_ A B /\ (wd_ O M /\ (wd_ O C1 /\ (wd_ C1 C1prime /\ (wd_ O C1prime /\ (wd_ E Eprime /\ (wd_ O Eprime /\ (wd_ P A /\ (wd_ P C /\ (wd_ O A1 /\ (wd_ O B1 /\ (wd_ M C1 /\ (wd_ M C1prime /\ (wd_ A1 Eprime /\ (wd_ A1 C1prime /\ (col_ P A B /\ (col_ P C P /\ (col_ C B P /\ (col_ O E A1 /\ (col_ O E B1 /\ (col_ O E C1 /\ (col_ O E O /\ (col_ O M N /\ (col_ N O D1prime /\ col_ M C1 C1prime))))))))))))))))))))))))))) -> col_ P A C)). Proof. time tac. Qed. End FOFProblem.
\chapter{Theoretical Analysis} \label{chap:analysis} In literature, flow across the equator is often treated in less detail than mid-latitude circulations, which is probably due to the fact that it is impossible to formulate a leading-order balance as simple as geostrophy. This in turn makes it hard to find simple analytical solutions and gain an intuition of the dominant mechanics in the equatorial regions. In order to understand the findings presented in \chapref{chap:cesm-runs}, it seemed necessary to review the equatorial processes from a more theoretical point of view, which is done in this chapter. \secref{sec:equatorial-theory} gives an introduction to the general nature of cross-equatorial flow and ties a first connection between potential vorticity, friction and viscosity, and the overturning. By considering the \ac{PV} balance at the equator, it is found that the presence of friction is indeed crucial to enable cross-equatorial flow. However, the efficiency of the \ac{PV} transformation is found to be \emph{independent} of the given viscosity to a leading order. \secref{sec:equatorial-shallow-water} describes a custom equatorial shallow-water model that is then used to test whether the observed dependency of the overturning on viscosity can be recreated in a highly idealized model. To this end, the response of the equatorial flow and inter-hemispheric mass balance to different viscosities and model resolutions is tested. It is found that neither a simple viscosity reduction, explicitly resolving equatorial eddies, nor an under-resolution of the western boundary layer leads to a similar response as in \acs{CESM}. \section{Theory of Cross-Equatorial Flow} \label{sec:equatorial-theory} As a starting point, the following sections present some pictures of cross-equatorial flow, and how exactly it connects to friction and viscosity. \secref{sec:equatorial-vorticity} describes how friction in general acts to enable cross-equatorial flow due to potential vorticity constraints. \secref{sec:killworth} then proceeds to analyze cross-equatorial flow quantitatively using a picture brought forward by \citet{killworth}. \subsection{Equatorial Vorticity Balance} \label{sec:equatorial-vorticity} Currents crossing the equator are strongly suppressed due to potential vorticity conservation constraints. This becomes most evident from the expression for \ac{PV} conservation in a layered ocean, \eqref{eq:pv-conservation-layer}: % \begin{equation} \Ddx\Pi_s = \Ddx\left(\frac{\zeta + f}{h}\right) = \frac{1}{h} \nabla_H\times \vec{\mathcal{F}}. \end{equation} % As the equator is approached, \(f\) becomes smaller and smaller until it vanishes at \ang{0} latitude, and \emph{changes its sign} as the flow penetrates into the opposite hemisphere. Since the layer height \(h\) is strictly positive, there are two possibilities how \eqref{eq:pv-conservation-layer} can be fulfilled: % \begin{enum} \item \ac{PV} can actually be conserved across the equator by creating excessive relative vorticity \(\zeta\) (\ie through nonlinear effects) --- however, the resulting velocity shear will usually heavily alter the flow paths and prevent water from deeply penetrating the other hemisphere\sidenote[-3]{An exception to this is presented by \citet{nofbc2}, who show that topography such as the Mid-Atlantic Ridge may allow flow to cross the equator while conserving \ac{PV}, based on a model from \cite{anderson}.}; or \item the advection of excess \ac{PV} along a streamline is balanced by a substantial amount of friction (\(\mathcal{F}\)), causing the \ac{PV} to change sign, until it joins the mid-latitude circulation. \end{enum} % Another way to recognize the processes that drive flow into the opposite hemisphere stems from a non-dimensional formulation of the vorticity equation given in \cite{bryan1963}. \citeauthor{bryan1963} assumes a lateral friction term of the form % \begin{equation} \nabla_H \times \vec{\mathcal{F}} = A_H \nabla^2 \zeta \approx A_H \nabla^2 v_x \end{equation} % as before, and assumes that the conversion of \ac{PV} happens predominantly inside western boundary currents. According to \citeauthor{bryan1963}, the steady-state vorticity balance in non-dimensional form can then be approximated as\sidenote[-2]{With non-dimensional coordinates \(x',y'\), depth-integrated velocities \(U,V\), and stream function \(\Psi\).} % \begin{equation} \underbrace{\varepsilon \left( U \zeta_x + V \zeta_y \right) \vphantom{\frac{\varepsilon}{\text{Re}}}}_{\mathclap{\text{Nonlinearity}}} % + \underbrace{V \vphantom{\frac{\varepsilon}{\text{Re}}}}_{\mathclap{\text{Coriolis}}} % + \underbrace{\sin(\pi y'/2) \vphantom{\frac{\varepsilon}{\text{Re}}}}_{\mathclap{\text{Wind stress}}} % =% \underbrace{\frac{\varepsilon}{\text{Re}} V^4 \Psi}_{\mathclap{\text{Friction}}} \end{equation} % where \(\varepsilon\) denotes the horizontal Ekman number, and \(\text{Re}\) the Reynolds number. From this formulation, it becomes clear that the sign of the lateral friction term \(\frac{\varepsilon}{\text{Re}} V^4 \Psi\) is only related to the sign of \(\Psi\) close to the boundary. Since we have assumed that the flow crosses in a western boundary current, the friction term \(\propto \Psi\) always has the same sign as the \(V\)-term\sidenote[-4]{Recall that the sign of the stream function is in fact tied to the direction of rotation: \(\Psi\) is positive for clockwise rotation, and negative otherwise.}, regardless if the crossing is north-to-south (\(V, \Psi < 0\)) or south-to-north (\(V, \Psi > 0\)). For the nonlinear term, no such argument can be made \emph{a priori}. \parabreak Both types of cross-equatorial flow (\ac{PV} conserving flow and flow in frictional balance) are studied in many models and applications throughout literature. In the upcoming sections, we shall assume that the second mode, which depends on friction, has the most relevance in the real ocean, based on a picture that was put forward in \cite{killworth} (see next section). However, we need to keep in mind that, in theory, \ac{PV} conserving modes are possible \citep{nofbc2}. \clearpage \subsection{The Killworth Model} \label{sec:killworth} A particularly interesting study of the dynamics of cross-equatorial geostrophic adjustment has been conducted by \citeauthorfull{killworth} \citep{killworth}. \sidefigure[Steady-state solutions of one-dimensional equatorial geostrophic adjustment.]{Two steady-state solutions (with different starting latitudes) of one-dimensional equatorial geostrophic adjustment. \acs{ODE} as in \cite{killworth}; solved with a shooting method.}[fig:killworth-ode]% {\importpgf{figures/cross-equatorial/killworth/}{killworth-h.pgf}\\[2ex]% \importpgf{figures/cross-equatorial/killworth/}{killworth-u.pgf}}[-1]% In the first part of his paper, \citeauthor{killworth} derives a set of nonlinear \acp{ODE} describing the long-time average solution of a dam-break scenario where water, starting with some height anomaly \(h\) from a latitude \(Y\) south of the equator, is released in an inviscid, one-dimensional ocean. He finds that the flow is able to penetrate at most two Rossby radii of deformation into the northern hemisphere, depending on the starting latitude \(Y\) (\figref{fig:killworth-ode}). In this scenario, \ac{PV} is conserved by creating excessive amounts of relative vorticity (\ie through the first mode as described in \secref{sec:equatorial-theory}), turning the flow into an eastward jet, until it cannot penetrate any further (layer height approaches zero). This shows that, in the absence of solid boundaries and friction, deeply penetrating cross-equatorial flow is impossible, or --- in other words --- that one-dimensional nonlinearities alone cannot enable a full-blown overturning. In the second part of the paper, \citeauthor{killworth} extends the model to a two-dimensional basin, and a lateral friction term is added. He proceeds to show that the circulation now spans the whole basin, because a western boundary current that is in frictional balance permits long migration of water parcels into the opposite hemisphere. By lowering the viscosity parameter, he finds a reduction of cross-equatorial flow in the interior, but not in the western boundary layer. This behavior can be understood by assuming that the flow occurs in a thin, strictly meridional western boundary layer in lateral friction balance\sidenote[-1]{This implies \(u=0\) and \(v_x \gg v_y\).}, \ie it can be described as a Munk layer (\cf \secref{sec:munk}). The dominant balance in the potential vorticity conservation equation for a layered ocean \eqref{eq:pv-conservation-layer} is then % \begin{equation} \Ddx \Pi_s \propto \frac{1}{h} A_H v_{xxx}. \label{eq:munk-friction-balance} \end{equation} % Since the typical zonal length scale in a Munk layer \(\delta_M\) is given by \eqref{eq:munkwidth}, \ie % \begin{equation} \delta_M = \left(\frac{A_H}{\beta}\right)^{1/3}, \end{equation} % the right hand side of \eqref{eq:munk-friction-balance} is of the order\sidenote{Assuming that the layer height \(h\) is approximately constant along stream lines.} \(\orderof{v} = V\). The left hand side of \eqref{eq:munk-friction-balance} (material derivative of \ac{PV}) involves a time derivative, and the total time spent in the boundary layer is \(\propto V^{-1}\). Thus, the total transformation of potential vorticity in the boundary current is of order \num{1} to a leading order. \emph{This implies that the magnitude of \(A_H\) does not influence the efficiency of \ac{PV} modification in a Munk layer in a first order approximation, as long as friction is present at all, and the Munk layer is resolved in the model.} \clearpage \section{An Equatorial Shallow-Water Model} \label{sec:equatorial-shallow-water} After these theoretical considerations, I wanted check whether the same behavior observed in the \acs{CESM} experiments from \chapref{chap:cesm-runs} can be reproduced by simply reducing viscosity in a highly idealized model\sidenote[-2]{As shown in the previous section, viscosity has no influence on a pure Munk layer --- however, it is not clear \emph{a priori} what happens when this layer is under-resolved, or how nonlinearities change the solution.}. For this purpose, I ran some additional experiments with a shallow-water model that I have developed, based on the models used in \cite{killworth} and \cite{kawase}. In particular, I wanted to obtain a similar dependence of total cross-equatorial transport and structure of the equatorial flow field on viscosity as observed in the Atlantic in my \ac{CESM} experiments (\secref{sec:obs-amoc}), while only modeling a single active layer of fluid with homogeneous velocities and density (as in \secref{sec:physics-layered}), and without any wind forcing. Instead, the model is forced by buoyancy only (a constant mass source in the north-western corner of the domain). I have specifically chosen the model equations and parameters to yield a solution that is somewhat similar to a long-term average of the deep branch of the \acs{AMOC}, while the upper branch is modeled implicitly by assuming that it always closes the meridional overturning. Like the real \ac{AMOC}, it is forced by a mass imbalance in the North\sidenote[-5]{Which is, however, assumed constant, to only observe the \emph{kinematic} effects of a reduced viscosity --- an assumption that is only a first order approximation of the real ocean.}, representing the creation of \ac{NADW}. However, I did not want to prescribe the magnitude of the cross-equatorial flow as in \eg \cite{edwards}. Hence, as a mass sink, I have chosen to implement uniform upwelling\sidenote[-1]{By simply removing water from the domain, implicitly assuming that it re-enters the \q{upper branch} of the basin instead.} proportional to the layer height anomaly as in \cite{kawase}, so a solution that stays entirely inside the northern hemisphere becomes possible. The following sections describe the equations that are solved by the model (\secref{sec:sw-equations}), and the experiments I have conducted, along with the observations I have made during the analysis (\secref{sec:sw-experiments}). \subsection{Model Equations} \label{sec:sw-equations} The shallow-water model I have implemented is basically a combination of the shallow-water models used in \cite{killworth} and \cite{kawase}, with an additional \ac{CESM}-style anisotropic friction term. \citeauthor{killworth} uses a non-dimensional unforced shallow-water model with lateral friction in Cartesian coordinates: % \sidedef{Killworth's model}{}{ \begin{align} u_t + uu_x + vu_y - \frac{1}{2} yv + h_x &= A_H (u_{xx} + u_{yy}) \\ v_t + uv_x + vv_y + \frac{1}{2} yu + h_y &= A_H (v_{xx} + v_{yy}) \\ h_t + (uh)_x + (vh)_y &= 0 \end{align} } % with (non-dimensional) velocities \(u, v\); layer height \(h\); meridional position \(y\); and turbulent diffusivity \(A_H\). \citeauthor{kawase} on the other hand uses a forced shallow-water model with bottom friction in spherical coordinates: % \sidedef{Kawase's model}{}{ \begin{align} u_t - 2 \Omega \sin \theta v + \frac{g}{R_e \cos\theta} \eta_\phi &= - \kappa u \\ v_t + 2 \Omega \sin \theta u + \frac{g}{R_e} \eta_\theta &= -\kappa v \\ \eta_t + \frac{H}{R_e \cos \theta} u_\phi + \frac{H}{R_e \cos\theta} (\cos\theta v)_\theta &= Q - \lambda \eta, \end{align} } % with Coriolis parameter \(2\Omega \sin\theta\); Earth's radius \(R_e\); reduced gravity \(g\); bottom friction parameter \(\kappa\); background layer height \(H\) and height anomaly \(\eta\); a localized water source \(Q\); and a water sink parameter \(\lambda\) parameterizing diapycnal mixing. The source in this model is located at the north-western corner of the domain, and the water sink is modeled as an exponential decay term\sidenote[-2]{Or exponential growth for \(\eta < 0\), \ie a negative displacement relative to the undisturbed layer height.}. Combining these two models, I arrived at a non-dimensional, Cartesian formulation with buoyancy forcing, anisotropic lateral friction as in \ac{CESM}, and proper treatment of the convection term in the \(h\) equation: % \sidedef{Dion's Shallow-Water Model}{}{ \begin{align} u_t + uu_x + vu_y - \frac{1}{2}yv + h_x &= (A u_x)_x + (B u_y)_y \\ v_t + uv_x + vv_y + \frac{1}{2}yu + h_y &= (B v_x)_x + (A v_y)_y \label{eq:shallowwater} \\ h_t + (uh)_x + (vh)_y &= Q - \lambda (h-1), \end{align} } % with definitions as in the \citeauthor{killworth} model, but with an additional sink as in \cite{kawase}\sidenote[-1]{\(h-1 = \eta\), since the non-dimensional undisturbed layer height \(H' \equiv 1\) in the Killworth model.}. Note that this term adds a diapycnal contribution to the \ac{PV} conservation equation \eqref{eq:pv-conservation}, so \ac{PV} is not strictly conserved, even in the absence of friction (however, we assume this term to be small, since all experiments are in the low-damping regime). The buoyancy forcing is modeled as an explicit mass source \(Q\) in the north-western corner of the basin. For a description of the numerical implementation and verification of this model refer to \appendixref{appendix:shallow-water}. \subsection{Experimental Setup} \label{sec:sw-experiments} After reproducing some published results with my model to verify that it is working correctly (\appendixref{appendix:shallow-water}), I ran a total of three sets of simulations to investigate the equatorial dynamics in different scenarios: % \begin{enum} \item High resolution, low forcing: In this first set, the model is forced by an explicit source \(Q\) in the north-western corner of the basin corresponding to a forcing of \SI{12}{\sv}. Between experiments, only the Munk layer viscosity \(\nu_M\) is changed (\(\nu_M = 0,\ 0.2,\ 2.0 \)). All other viscosity parameters as in the \ac{CESM} run \run{x3_default}. The model grid consists of \(60 \times 120\) equally spaced grid cells. \item High resolution, high forcing: As the first set, but with a stronger forcing of \SI{48}{\sv}, to allow for more nonlinearities in the solution. All runs are initialized with the final state of the \(\nu_M = 0.2\) experiment from set 1. To make computations more efficient, the grid spacing is reduced around the equator and western boundary, and increased everywhere else (same total number of grid cells). \item Low resolution, low forcing: Four low-resolution simulations with Munk layer viscosities \num{e3}, \num{e4}, \num{e5}, and \SI{e6}{\metre\squared\per\second}. 20 equally spaced grid cells in \(x\)-direction, and 80 cells in \(y\)-direction, with a four times finer grid at the equator than at the northern and southern boundaries\sidenote[-3]{This grid was chosen to achieve a similar spatial resolution as in the \grid{x3} \ac{CESM} runs.}. Forcing as in set 1. \end{enum} % Furthermore, all experiments share the following setup: % \begin{items} \item a rectangular basin that extends \SI{6000}{\kilo\metre} in zonal (\(x\)) and \SI{12000}{\kilo\metre} in meridional (\(y\)) direction, with the equator in the middle; \item a dampening time scale \(\lambda^{-1}\) of 1 year, putting the experiments into the weak damping regime as defined in \cite{greatbatch}; and \item an undisturbed layer height \(H\) of \SI{400}{\metre}, a reduced gravity \(g\) of \SI{0.02}{\metre\per\second\squared}, and a Coriolis parameter \(\beta\) of \SI{2e-11}{\per\second\per\metre}. \end{items} % All of these values were chosen with the deep branch of the \ac{AMOC} in mind, while still being sufficiently close to the studies in \cite{killworth} and \cite{greatbatch} to allow comparisons. The model is integrated forward using a finite volume solver for at least 1000 days, \ie approximately three damping time scales. To ensure stability and accuracy, the model uses adaptive time step control, with a typical time step lying in the order of 15 minutes. In every time step, an absolute solver precision of \num{e-8} in dimensionless units is enforced for both velocities and layer height. \clearpage \FloatBlock \subsection{Analysis} \subsubsection{Set 1: High resolution, low forcing} In% \sidefigure[Equatorial regions of the first set of shallow-water simulations.]{Equatorial regions of the first set of shallow-water simulations (with varying Munk layer viscosity). Shown are the streamlines, advection of \ac{PV} (shading), and contour of zero \ac{PV} (black line).}[fig:toy-flow-1]{\importpgf{figures/cross-equatorial/toy-flow}{set1.pgf}}[-2]% % this setup, the relatively weak forcing keeps nonlinearities small. As a consequence, all solutions are very similar, apart from a varying boundary layer width (which is, after all, \(\propto A_H^{1/3}\)) and different levels of numerical (dispersive) noise. The resulting steady-state solution is symmetric around the equator, similar to the weak-damping solutions in \cite{greatbatch} (\figref{fig:toy-steady-state}; see also \appendixref{appendix:shallow-water}), and flow seems to cross the equator in the western boundary layer only. The structure of the steady-state solution seems largely indifferent to viscosity (\figref{fig:toy-flow-1}) --- higher viscosities only lead to a wider boundary layer, and a more pronounced recirculation as predicted by the Munk solution, \ie \eqref{eq:munk-solution-noslip}. \begin{figure}[p] \centering \importpgf{figures/cross-equatorial/toy-steady-state}{toy-steady-state.pgf} \caption[Steady-state solution of the shallow-water model for high resolution and low forcing.]{The steady-state solution in the high resolution, low forcing case is symmetric around the equator. Contours and quivers in the forcing region / western boundary partly omitted. Shading left: layer height anomaly; right: velocity magnitude. Coordinates in non-dimensional units.} \label{fig:toy-steady-state} \end{figure} The amount of water \(H_\text{south}\) that manages to penetrate deep into the southern hemisphere can be used as a diagnostic for the \enquote{overturning} in the model, by simply evaluating a mass integral over some southern region, \ie% \sidefigure[Hemispheric mass balance for set 1 of the shallow water experiments.]{The steady-state mass balance between North and South seems to be largely independent of viscosity.}[fig:southern-water-1]{\importpgf{figures/cross-equatorial/southern-water}{set1.pgf}}[12]% % \begin{equation} H_\text{south} = \int_{x_w}^{x_e} \int_{y_s}^{y^*} h \dx{y} \dx{x}, \end{equation} % with the layer height \(h\), \(x_w, x_e, y_s\) denoting the position of the western, eastern, and southern boundary, respectively, and some bounding latitude \(y^*\) that separates north from south. Since the observed equatorial features tend to extend quite far into both hemispheres (\figref{fig:toy-steady-state}), I have chosen \(y^* = -10\) (non-dimensional; in multiples of the Rossby radius of deformation). A better estimate for the overturning that is comparable between different scenarios is the mass ratio between northern and southern parts of the domain, \ie \(H_\text{south} / H_\text{north}\). Calculating this value for every experiment reveals that the steady-state mass balance is indeed quite stable around \SI{7(1)}{\percent} for any Munk layer viscosity (\figref{fig:southern-water-1}), especially for the two runs with a non-vanishing Munk layer. However, it seems that higher viscosities lead to a \emph{weaker} overturning, which is in contradiction with the findings of \chapref{chap:cesm-runs}. It is also observed that higher viscosities lead to a delayed reaction of the southern part of the basin, \ie longer overall time scales. \clearpage \subsubsection{Set 2: High resolution, high forcing} In% \sidefigure[Equatorial regions of the second set of shallow-water simulations.]{Equatorial regions of the second set of shallow-water simulations (with varying Munk layer viscosity). Shown are the streamlines, advection of \ac{PV} (shading), and contour of zero \ac{PV} (black line).}[fig:toy-flow-2]{\importpgf{figures/cross-equatorial/toy-flow}{set2.pgf}}% % this scenario, the forcing strength has been quadrupled to increase velocity and height anomaly scales, which increases the nonlinearity of the solution. Indeed, while the overall structure of the solution is still the same as in the first scenario, the experiment without a Munk layer now features a number of eddies that constantly emerge in the equatorial region near the western boundary, travel southward, and dissipate. This is also visible in \figref{fig:toy-flow-2}, where the line of zero \ac{PV} is visibly distorted close to the western boundary. The inter-hemispheric mass balance (\figref{fig:southern-water-2}) reveals that all experiments converge to roughly the same steady-state, with differences of the order of \SI{1}{\permille}, which also seems to be roughly the same steady-state that the solution was initialized with (final state of the \(\nu_M=0.02\) experiment from set 1). Strictly speaking, the experiment with the highest viscosity \emph{does} lead to the largest amount of southern water after \SI{2200}{\day}, but differences are so small that this might as well change once more when integrating for even longer times. \sidefigure[Hemispheric mass balance for set 2 of the shallow water experiments.]{Even for nonlinear solutions, the steady-state mass balance between North and South seems to be independent of viscosity.}[fig:southern-water-2]{\importpgf{figures/cross-equatorial/southern-water}{set2.pgf}}[12] It seems curious that the low-viscosity run from set 1 was clearly set apart from the other experiments (\figref{fig:southern-water-1}), while this is not the case here. However, it is important to recall that I have also introduced a scaled numerical grid before running the experiments of set 2, which becomes finer near the equator and \emph{the western boundary}. My hypothesis to explain the observed behavior is thus that the western boundary layer was not fully resolved in the low-viscosity run of set 1, while it is well-resolved in set 2 due to the finer grid spacing at the western boundary. Hence, it seems that a fully resolved boundary layer \emph{always leads to an identical hemispheric mass balance in the steady-state}, regardless of nonlinearities (while during spin-up, the system reacts considerably faster with lower viscosities, which might be an important factor in the real ocean / \ac{CESM}). \clearpage \FloatBlock \subsubsection{Set 3: Low resolution, low forcing} This% \sidefigure[Height field of a low-viscosity shallow-water experiment.]{Lowering viscosity creates zonal re-circulations in the equatorial band. Shown is the smoothed layer height anomaly.}[fig:sw-height-lowvisc]{\importpgf{figures/cross-equatorial/toy-height}{toy-height-lowvisc.pgf}}% % set of simulations was deliberately run with a low spatial resolution to test the effects of under-resolving the western boundary layer. This creates excessive amounts of numerical noise, as also seen in the \ac{CESM} experiments --- thus, all variables have been smoothed with a boxcar filter in both dimensions before post-processing. \begin{figure} \begin{sidecaption}[Equatorial flow for shallow water experiment set 3.]{The equatorial flow pattern shows a distinct dependency on viscosity. Shading: \ac{PV} advection (different scale for each solution).}[fig:toy-flow-3] \antimpjustification \importpgf{figures/cross-equatorial/toy-flow}{set3.pgf} \end{sidecaption} \end{figure} Compared to the symmetric solutions obtained in set 1 and 2, the structure of the solution changes considerably in the low-viscosity runs (\figref{fig:sw-height-lowvisc}). The symmetry around the equator is broken, and, interestingly, the largest effect is seen in the circulation of the \emph{northern} hemisphere. Part of the flow crosses in the western boundary, but large parts of the flow do not make it across the equator, and are deflected eastward instead. When hitting the eastern boundary, this flow turns southward, and is deflected to the west by the equator. A similar process is observed \emph{after} the flow has crossed the equator, but fails to penetrate deeply into the southern hemisphere. It is deflected eastward until hitting the eastern boundary, where it dumps excess \ac{PV}, and joins the southern circulation (\figref{fig:toy-flow-3}). It seems odd that processes at the \emph{eastern} boundary actually manage to transform \ac{PV} in the same way as the western boundary, since it is analytically impossible to find a stable solution that balances friction and planetary vorticity at the eastern boundary \citep{pedloskyoct}. Possible explanations for the observed behavior could be: % \begin{enum} \item The diapycnal term in the \ac{PV} conservation equation \eqref{eq:pv-conservation} becomes important in this region and acts to remove some potential vorticity; \item Strong numerical noise may lead to an inaccurate solution; or \item Calculating relative vorticity during post-processing is quite inaccurate for low-resolution grids, and \ac{PV} \emph{could} in fact be conserved. In this case, the observed re-circulation would be purely inertial, which is a well-known solution (the Fofonoff mode, see \citebook{pedloskyoct}). \end{enum} % Thus, even though somewhat similar processes are observed in the Atlantic in my \ac{CESM} experiments for low viscosities (\figref{fig:amoc-velocity}), it is doubtful how realistic the interactions at the eastern boundary are modeled in this set of experiments. \parabreak The inter-hemispheric mass balance for this set seems curious, too (\figref{fig:southern-water-3}). Apparently, an under-resolved Munk layer does indeed lead to a \emph{much larger} amount of water that crosses the equator and reaches far south, as already suspected when comparing the results from set 1 and 2. While the high viscosity experiments lead to a mass balance that is similar to that of set 1, the low viscosity runs exceed it significantly. My only explanation for this observation is that, since northern water is effectively trapped in the equatorial region, there is simply more opportunity for a large portion of the flow to actually cross the equator, be it at the western boundary or in the interior, before it is removed from the basin. \begin{figure} \begin{sidecaption}[Hemispheric mass balance for set 3 of the shallow water experiments.]{The \emph{lower} the viscosity, the \emph{more} water reaches far south in my shallow water model. Division between north and south at \num{10} deformation radii south of the equator.}[fig:southern-water-3] \antimpjustification \importpgf{figures/cross-equatorial/southern-water}{set3.pgf} \end{sidecaption} \end{figure} \subsubsection{Summary} Albeit my buoyancy-forced shallow water model has shown some interesting features, it has eventually failed to reproduce the dependency of the \ac{MOC} on viscosity as seen in the \ac{CESM} experiments of \chapref{chap:cesm-runs} (\ie a slightly reduced transport for reduced viscosities), even when equatorial eddies were explicitly resolved (set 2) or when the equatorial Munk layer was under-resolved (set 3). I thus conclude that neither of the examined effects effects% % \sidenote{\Ie \\[1ex] \begin{marginenum} \item direct response to changed viscosity, \item simple nonlinearities, \item under-resolution of the western boundary layer. \end{marginenum} } % % is responsible for the observed response of \ac{CESM}. Further possible candidates that may cause the observed dependency are \eg topography, interactions between multiple layers, atmospheric forcing, or simply the fact that the \ac{NADW} forcing is not constant (since it depends both explicitly on time through \eg seasonal forcing and a on the actual cross-equatorial flow itself). Hence, further work seems necessary to identify the dominant processes in \ac{CESM}; some possible modifications are presented in \secref{sec:outro-moc-viscosity}.
# This file is part of the pyMOR project (https://www.pymor.org). # Copyright pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause) import numpy as np import scipy.linalg as spla from pymor.algorithms.to_matrix import to_matrix from pymor.core.cache import CacheableObject from pymor.core.cache import cached from pymor.operators.block import BlockOperator, BlockRowOperator, BlockColumnOperator, BlockDiagonalOperator from pymor.parameters.base import ParametricObject, Mu class TransferFunction(CacheableObject, ParametricObject): r"""Class for systems represented by a transfer function. This class describes input-output systems given by a (parametrized) transfer function :math:`H(s, \mu)`. Parameters ---------- dim_input The number of inputs. dim_output The number of outputs. tf The transfer function H, given by a callable that takes a complex value `s` and, if parametric, a |parameter value| `mu`. The result of `tf(s, mu)` is a |NumPy array| of shape `(dim_output, dim_input)`. dtf The complex derivative of `H` with respect to `s` (optional). parameters The |Parameters| of the transfer function. cont_time `True` if the system is continuous-time, otherwise `False`. name Name of the system. Attributes ---------- dim_input The number of inputs. dim_output The number of outputs. tf The transfer function. dtf The complex derivative of the transfer function. """ cache_region = 'memory' def __init__(self, dim_input, dim_output, tf, dtf=None, parameters={}, cont_time=True, name=None): self.parameters_own = parameters self.__auto_init(locals()) def __str__(self): return ( f'{self.name}\n' f' class: {self.__class__.__name__}\n' f' number of inputs: {self.dim_input}\n' f' number of outputs: {self.dim_output}\n' f' {"continuous" if self.cont_time else "discrete"}-time' ) @cached def eval_tf(self, s, mu=None): """Evaluate the transfer function. Parameters ---------- s Laplace variable as a complex number. mu |Parameter values|. Returns ------- Transfer function value as a 2D |NumPy array|. """ if not isinstance(mu, Mu): mu = self.parameters.parse(mu) assert self.parameters.assert_compatible(mu) if not self.parametric: return self.tf(s) else: return self.tf(s, mu=mu) @cached def eval_dtf(self, s, mu=None): """Evaluate the derivative of the transfer function. Parameters ---------- s Laplace variable as a complex number. mu |Parameter values|. Returns ------- Transfer function value as a 2D |NumPy array|. """ if not isinstance(mu, Mu): mu = self.parameters.parse(mu) assert self.parameters.assert_compatible(mu) if self.dtf is None: raise ValueError('The derivative was not given.') if not self.parametric: return self.dtf(s) else: return self.dtf(s, mu=mu) def freq_resp(self, w, mu=None): """Evaluate the transfer function on the imaginary axis. Parameters ---------- w A sequence of angular frequencies at which to compute the transfer function. mu |Parameter values| for which to evaluate the transfer function. Returns ------- tfw Transfer function values at frequencies in `w`, |NumPy array| of shape `(len(w), self.dim_output, self.dim_input)`. """ if not self.cont_time: raise NotImplementedError if not isinstance(mu, Mu): mu = self.parameters.parse(mu) assert self.parameters.assert_compatible(mu) return np.stack([self.eval_tf(1j * wi, mu=mu) for wi in w]) def bode(self, w, mu=None): """Compute magnitudes and phases. Parameters ---------- w A sequence of angular frequencies at which to compute the transfer function. mu |Parameter values| for which to evaluate the transfer function. Returns ------- mag Transfer function magnitudes at frequencies in `w`, |NumPy array| of shape `(len(w), self.dim_output, self.dim_input)`. phase Transfer function phases (in radians) at frequencies in `w`, |NumPy array| of shape `(len(w), self.dim_output, self.dim_input)`. """ w = np.asarray(w) mag = np.abs(self.freq_resp(w, mu=mu)) phase = np.angle(self.freq_resp(w, mu=mu)) phase = np.unwrap(phase, axis=0) return mag, phase def bode_plot(self, w, mu=None, ax=None, Hz=False, dB=False, deg=True, **mpl_kwargs): """Draw the Bode plot for all input-output pairs. Parameters ---------- w A sequence of angular frequencies at which to compute the transfer function. mu |Parameter values| for which to evaluate the transfer function. ax Axis of shape (2 * `self.dim_output`, `self.dim_input`) to which to plot. If not given, `matplotlib.pyplot.gcf` is used to get the figure and create axis. Hz Should the frequency be in Hz on the plot. dB Should the magnitude be in dB on the plot. deg Should the phase be in degrees (otherwise in radians). mpl_kwargs Keyword arguments used in the matplotlib plot function. Returns ------- artists List of matplotlib artists added. """ if ax is None: import matplotlib.pyplot as plt fig = plt.gcf() width, height = plt.rcParams['figure.figsize'] fig.set_size_inches(self.dim_input * width, 2 * self.dim_output * height) fig.set_constrained_layout(True) ax = fig.subplots(2 * self.dim_output, self.dim_input, sharex=True, squeeze=False) else: assert isinstance(ax, np.ndarray) and ax.shape == (2 * self.dim_output, self.dim_input) fig = ax[0, 0].get_figure() w = np.asarray(w) freq = w / (2 * np.pi) if Hz else w mag, phase = self.bode(w, mu=mu) if deg: phase *= 180 / np.pi artists = np.empty_like(ax) freq_label = f'Frequency ({"Hz" if Hz else "rad/s"})' mag_label = f'Magnitude{" (dB)" if dB else ""}' phase_label = f'Phase ({"deg" if deg else "rad"})' for i in range(self.dim_output): for j in range(self.dim_input): if dB: artists[2 * i, j] = ax[2 * i, j].semilogx(freq, 20 * np.log10(mag[:, i, j]), **mpl_kwargs) else: artists[2 * i, j] = ax[2 * i, j].loglog(freq, mag[:, i, j], **mpl_kwargs) artists[2 * i + 1, j] = ax[2 * i + 1, j].semilogx(freq, phase[:, i, j], **mpl_kwargs) for i in range(self.dim_output): ax[2 * i, 0].set_ylabel(mag_label) ax[2 * i + 1, 0].set_ylabel(phase_label) for j in range(self.dim_input): ax[-1, j].set_xlabel(freq_label) fig.suptitle('Bode plot') return artists def mag_plot(self, w, mu=None, ax=None, ord=None, Hz=False, dB=False, **mpl_kwargs): """Draw the magnitude plot. Parameters ---------- w A sequence of angular frequencies at which to compute the transfer function. mu |Parameter values| for which to evaluate the transfer function. ax Axis to which to plot. If not given, `matplotlib.pyplot.gca` is used. ord The order of the norm used to compute the magnitude (the default is the Frobenius norm). Hz Should the frequency be in Hz on the plot. dB Should the magnitude be in dB on the plot. mpl_kwargs Keyword arguments used in the matplotlib plot function. Returns ------- out List of matplotlib artists added. """ if ax is None: import matplotlib.pyplot as plt ax = plt.gca() w = np.asarray(w) freq = w / (2 * np.pi) if Hz else w mag = spla.norm(self.freq_resp(w, mu=mu), ord=ord, axis=(1, 2)) if dB: out = ax.semilogx(freq, 20 * np.log10(mag), **mpl_kwargs) else: out = ax.loglog(freq, mag, **mpl_kwargs) ax.set_title('Magnitude plot') freq_unit = ' (Hz)' if Hz else ' (rad/s)' ax.set_xlabel('Frequency' + freq_unit) mag_unit = ' (dB)' if dB else '' ax.set_ylabel('Magnitude' + mag_unit) return out @cached def h2_norm(self, return_norm_only=True, **quad_kwargs): """Compute the H2-norm using quadrature. This method uses `scipy.integrate.quad` and makes no assumptions on the form of the transfer function. It only assumes that `self.tf` is defined over the imaginary axis. By default, the absolute error tolerance in `scipy.integrate.quad` is set to zero (see its optional argument `epsabs`). It can be changed by using the `epsabs` keyword argument. Parameters ---------- return_norm_only Whether to only return the approximate H2-norm. quad_kwargs Keyword arguments passed to `scipy.integrate.quad`. Returns ------- norm Computed H2-norm. norm_relerr Relative error estimate (returned if `return_norm_only` is `False`). info Quadrature info (returned if `return_norm_only` is `False` and `full_output` is `True`). See `scipy.integrate.quad` documentation for more details. """ if not self.cont_time: raise NotImplementedError import scipy.integrate as spint quad_kwargs.setdefault('epsabs', 0) quad_out = spint.quad(lambda w: spla.norm(self.eval_tf(w * 1j))**2, 0, np.inf, **quad_kwargs) norm = np.sqrt(quad_out[0] / np.pi) if return_norm_only: return norm norm_relerr = quad_out[1] / (2 * quad_out[0]) if len(quad_out) == 2: return norm, norm_relerr else: return norm, norm_relerr, quad_out[2:] def h2_inner(self, lti): """Compute H2 inner product with an |LTIModel|. Uses the inner product formula based on the pole-residue form (see, e.g., Lemma 1 in :cite:`ABG10`). It assumes that `self.tf` is defined on `-lti.poles()`. Parameters ---------- lti |LTIModel| consisting of |Operators| that can be converted to |NumPy arrays|. The D operator is ignored. Returns ------- inner H2 inner product. """ from pymor.models.iosys import LTIModel, _lti_to_poles_b_c assert isinstance(lti, LTIModel) poles, b, c = _lti_to_poles_b_c(lti) inner = sum(c[i].dot(self.eval_tf(-poles[i]).dot(b[i])) for i in range(len(poles))) inner = inner.conjugate() return inner def __add__(self, other): assert isinstance(other, TransferFunction) or hasattr(other, 'transfer_function') if not isinstance(other, TransferFunction): other = other.transfer_function assert self.cont_time == other.cont_time assert self.dim_input == other.dim_input assert self.dim_output == other.dim_output tf = lambda s, mu=None: self.eval_tf(s, mu=mu) + other.eval_tf(s, mu=mu) dtf = (lambda s, mu=None: self.eval_dtf(s, mu=mu) + other.eval_dtf(s, mu=mu) if hasattr(other, 'eval_dtf') else None) return self.with_(tf=tf, dtf=dtf) __radd__ = __add__ def __sub__(self, other): return self + (-other) def __rsub__(self, other): assert isinstance(other, TransferFunction) or hasattr(other, 'transfer_function') if not isinstance(other, TransferFunction): other = other.transfer_function assert self.cont_time == other.cont_time assert self.dim_input == other.dim_input assert self.dim_output == other.dim_output tf = lambda s, mu=None: other.eval_tf(s, mu=mu) - self.eval_tf(s, mu=mu) dtf = (lambda s, mu=None: other.eval_dtf(s, mu=mu) - self.eval_dtf(s, mu=mu) if hasattr(other, 'eval_dtf') else None) return self.with_(tf=tf, dtf=dtf) def __neg__(self): tf = lambda s, mu=None: -self.eval_tf(s, mu=mu) dtf = (lambda s, mu=None: -self.eval_dtf(s, mu=mu)) if self.dtf is not None else None return self.with_(tf=tf, dtf=dtf) def __mul__(self, other): assert isinstance(other, TransferFunction) or hasattr(other, 'transfer_function') if not isinstance(other, TransferFunction): other = other.transfer_function assert self.cont_time == other.cont_time assert self.dim_input == other.dim_output tf = lambda s, mu=None: self.eval_tf(s, mu=mu) @ other.eval_tf(s, mu=mu) dtf = (lambda s, mu=None: (self.eval_dtf(s, mu=mu) @ other.eval_tf(s, mu=mu) + self.eval_tf(s, mu=mu) @ other.eval_dtf(s, mu=mu)) if hasattr(other, 'eval_dtf') else None) return self.with_(tf=tf, dtf=dtf) def __rmul__(self, other): assert isinstance(other, TransferFunction) or hasattr(other, 'transfer_function') if not isinstance(other, TransferFunction): other = other.transfer_function assert self.cont_time == other.cont_time assert self.dim_output == other.dim_input tf = lambda s, mu=None: other.eval_tf(s, mu=mu) @ self.eval_tf(s, mu=mu) dtf = (lambda s, mu=None: (other.eval_dtf(s, mu=mu) @ self.eval_tf(s, mu=mu) + other.eval_tf(s, mu=mu) @ self.eval_dtf(s, mu=mu)) if hasattr(other, 'eval_dtf') else None) return self.with_(tf=tf, dtf=dtf) class FactorizedTransferFunction(TransferFunction): r"""Transfer functions in generalized coprime factor form. This class describes input-output systems given by a transfer function of the form :math:`H(s, \mu) = \mathcal{C}(s, \mu) \mathcal{K}(s, \mu)^{-1} \mathcal{B}(s, \mu) + \mathcal{D}(s, \mu)`. Parameters ---------- dim_input The number of inputs. dim_output The number of outputs. K, B, C, D Functions that take `s` and return an |Operator|. dK, dB, dC, dD Functions that take `s` and return an |Operator| that is the derivative of K, B, C, D (optional). parameters The |Parameters| of the transfer function. cont_time `True` if the system is continuous-time, otherwise `False`. name Name of the system. """ def __init__(self, dim_input, dim_output, K, B, C, D, dK=None, dB=None, dC=None, dD=None, parameters={}, cont_time=True, name=None): def tf(s, mu=None): if dim_input <= dim_output: B_vec = B(s).as_range_array(mu=mu) Kinv_B = K(s).apply_inverse(B_vec, mu=mu) res = C(s).apply(Kinv_B, mu=mu).to_numpy().T else: C_vec_adj = C(s).as_source_array(mu=mu).conj() Kinvadj_Cadj = K(s).apply_inverse_adjoint(C_vec_adj, mu=mu) res = B(s).apply_adjoint(Kinvadj_Cadj, mu=mu).to_numpy().conj() res += to_matrix(D(s), format='dense', mu=mu) return res if dK is None or dB is None or dC is None: dtf = None else: def dtf(s, mu=None): if dim_input <= dim_output: B_vec = B(s).as_range_array(mu=mu) Ki_B = K(s).apply_inverse(B_vec, mu=mu) dC_Ki_B = dC(s).apply(Ki_B, mu=mu).to_numpy().T dB_vec = dB(s).as_range_array(mu=mu) Ki_dB = K(s).apply_inverse(dB_vec, mu=mu) C_Ki_dB = C(s).apply(Ki_dB, mu=mu).to_numpy().T dK_Ki_B = dK(s).apply(Ki_B, mu=mu) Ki_dK_Ki_B = K(s).apply_inverse(dK_Ki_B, mu=mu) C_Ki_dK_Ki_B = C(s).apply(Ki_dK_Ki_B, mu=mu).to_numpy().T res = dC_Ki_B + C_Ki_dB - C_Ki_dK_Ki_B else: C_vec_a = C(s).as_source_array(mu=mu).conj() Kia_Ca = K(s).apply_inverse_adjoint(C_vec_a, mu=mu) dC_Ki_B = dB(s).apply_adjoint(Kia_Ca, mu=mu).to_numpy().conj() dC_vec_a = dC(s).as_source_array(mu=mu).conj() Kia_dCa = K(s).apply_inverse_adjoint(dC_vec_a, mu=mu) CKidB = B(s).apply_adjoint(Kia_dCa, mu=mu).to_numpy().conj() dKa_Kiajd_Ca = dK(s).apply_adjoint(Kia_Ca, mu=mu) Kia_dKa_Kia_Ca = K(s).apply_inverse_adjoint(dKa_Kiajd_Ca, mu=mu) C_Ki_dK_Ki_B = B(s).apply_adjoint(Kia_dKa_Kia_Ca, mu=mu).to_numpy().conj() res = dC_Ki_B + CKidB - C_Ki_dK_Ki_B res += to_matrix(dD(s), format='dense', mu=mu) return res super().__init__(dim_input, dim_output, tf, dtf=dtf, parameters=parameters, cont_time=cont_time, name=name) self.__auto_init(locals()) def __add__(self, other): if (type(other) is not FactorizedTransferFunction and not hasattr(other, 'transfer_function')): return NotImplemented assert self.cont_time == other.cont_time assert self.dim_input == other.dim_input assert self.dim_output == other.dim_output if not type(other) is FactorizedTransferFunction: other = other.transfer_function K = lambda s: BlockDiagonalOperator([self.K(s), other.K(s)]) B = lambda s: BlockColumnOperator([self.B(s), other.B(s)]) C = lambda s: BlockRowOperator([self.C(s), other.C(s)]) D = lambda s: self.D(s) + other.D(s) dK = (lambda s: BlockDiagonalOperator([self.dK(s), other.dK(s)]) if self.dK is not None and other.dK is not None else None) dB = (lambda s: BlockColumnOperator([self.dB(s), other.dB(s)]) if self.dB is not None and other.dB is not None else None) dC = (lambda s: BlockRowOperator([self.dC(s), other.dC(s)]) if self.dC is not None and other.dC is not None else None) dD = (lambda s: self.dD(s) + other.dD(s) if self.dD is not None and other.dD is not None else None) return self.with_(K=K, B=B, C=C, D=D, dK=dK, dB=dB, dC=dC, dD=dD) __radd__ = __add__ def __neg__(self): C = lambda s: -self.C(s) D = lambda s: -self.D(s) dC = lambda s: -self.dC(s) if self.dC is not None else None dD = lambda s: -self.dD(s) if self.dD is not None else None return self.with_(C=C, D=D, dC=dC, dD=dD) def __mul__(self, other): if (type(other) is not FactorizedTransferFunction and not hasattr(other, 'transfer_function')): return NotImplemented assert self.cont_time == other.cont_time assert self.dim_input == other.dim_output if not type(other) is FactorizedTransferFunction: other = other.transfer_function K = lambda s: BlockOperator([[self.K(s), -self.B(s) @ other.C(s)], [None, other.K(s)]]) B = lambda s: BlockColumnOperator([self.B(s) @ other.D(s), other.B(s)]) C = lambda s: BlockRowOperator([self.C(s), self.D(s) @ other.C(s)]) D = lambda s: self.D(s) @ other.D(s) dK = (lambda s: BlockOperator([[self.dK(s), self.dB(s) @ other.C(s) + self.B(s) @ other.dC(s)], [None, other.dK(s)]]) if self.dK is not None and other.dK is not None and self.dB is not None and other.dC is not None else None) dB = (lambda s: BlockColumnOperator([self.dB(s) @ other.D(s) + self.B(s) @ other.dD(s), other.dB(s)]) if self.dB is not None and other.dB is not None and other.dD is not None else None) dC = (lambda s: BlockRowOperator([self.dC(s), self.dD(s) @ other.C(s) + self.D(s) @ other.dC(s)]) if self.dC is not None and other.dC is not None and self.dD is not None else None) dD = (lambda s: self.dD(s) @ other.D(s) + self.D(s) @ other.dD(s) if self.dD is not None and other.dD is not None else None) return self.with_(K=K, B=B, C=C, D=D, dK=dK, dB=dB, dC=dC, dD=dD) def __rmul__(self, other): if not hasattr(other, 'transfer_function'): return NotImplemented return other.transfer_function * self
/** * sudoku_tl.cpp * * By Sebastian Raaphorst, 2018. */ #include <iostream> #include <memory> #include <stdexcept> #include <boost/program_options.hpp> #include <GenSudokuBoard.h> #include <GenSudokuBoardAscenderPopulator.h> #include <TabuSearchAlgorithm.h> #include "progopts.h" namespace po = boost::program_options; using namespace vorpal::gensudoku; using namespace vorpal::stochastic; int main(int argc, const char * const argv[]) { using solver = TabuSearchAlgorithm<SudokuBoard>; solver::options_type options; try { auto desc = init_options(options); desc->add_options() ("tabu-list-length,t", po::value<size_t>()->default_value(20), "tabu list length"); auto done = end_options<SudokuBoardAscenderPopulator, solver::options_type>(argc, argv, desc, options, [](po::variables_map &vm, solver::options_type &options) { options.tabu_list_length = vm["tabu-list-length"].as<size_t>(); }); if (done) return 0; } catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; } run<solver>(options); }
As communications manager for a decade-old chain of boutique hotels, Phuong Hong has a close look at the latest business trend in booming Vietnam: the coming of Chinese money. As M&A activity heats up in the education sector, opinion is divided on whether it is a positive or negative development. Le roi de Thaïlande s’est vu accorder la pleine propriété des biens du palais en vertu d’une loi promulguée l’an dernier, selon une "note explicative" publiée par le bras financier de la puissante et opaque monarchie. This is no place for old-school investors. Vietnam's taxi operator Vinasun has initiated a lawsuit against the popular ride hailing service Grab on accusations of unfair business practices, with a court in Ho Chi Minh City looking into the matter on Tuesday (Feb 6) . The biggest difference between Vietnam and the West is the irrepressible desire of the Asian nation's young people to be successful and leave its poverty behind for ever. Tensions are high on the South China Sea as Vietnam faces off against China over their overlapping maritime claims. U.S. companies signed business deals with Vietnam worth over $8 billion on Wednesday, including power projects and jet engines from General Electric Co (GE.N) and diesel generator technology from Caterpillar (CAT.N), the Commerce Department said. On a typical Sunday evening in the heart of Vietnam's financial center, European cars and Japanese motorcycles jostle for parking lots close to restaurants. In the first quarter (Q1) of 2016, Vietnam spent $10.7 billion on imports from China, accounting for around 28 percent of Vietnam's total import revenue, according to Vietnam Customs on Tuesday. In China’s shadow, Hanoi is biting on the trade pact and swallowing its bitter past with the United States. Singapore has become Vietnam’s leading investment partner after investing more than US$36 billion in numerous local projects, including processing, technology, manufacturing, real estate, construction, transportation, and storage.
open import Level using (Level; suc; zero; _⊔_) open import Function using (const) open import Algebra open import Algebra.Structures open import Algebra.OrderedMonoid open import Algebra.Pregroup open import Algebra.FunctionProperties as FunctionProperties using (Op₁; Op₂) open import Data.Product using (_×_; _,_; proj₁; proj₂) open import Relation.Binary open import Relation.Binary.PartialOrderReasoning as ≤-Reasoning using () module Algebra.PregroupPlus where record IsPregroupPlus {a ℓ₁ ℓ₂} {A : Set a} (≈ : Rel A ℓ₁) (≤ : Rel A ℓ₂) (∙ : Op₂ A) (ε₁ : A) (ˡ : Op₁ A) (ʳ : Op₁ A) (+ : Op₂ A) (ε₀ : A) (ᵘ : Op₁ A) (ᵈ : Op₁ A) : Set (a ⊔ ℓ₁ ⊔ ℓ₂) where field ∙-isPregroup : IsPregroup ≈ ≤ ∙ ε₁ ˡ ʳ +-isPregroup : IsPregroup ≈ ≤ + ε₀ ᵘ ᵈ open IsPregroup ∙-isPregroup public using (ˡ-cong; ʳ-cong; ˡ-contract; ʳ-contract ;ˡ-expand; ʳ-expand; ∙-cong) renaming (assoc to ∙-assoc; identity to ∙-identity ;compatibility to ∙-compatibility) open IsPregroup +-isPregroup public using (≤-refl; ≤-reflexive; ≤-trans; ≤-resp-≈; refl; sym; trans; antisym) renaming (ˡ-cong to ᵈ-cong; ʳ-cong to ᵘ-cong ;ˡ-contract to ᵈ-contract; ʳ-contract to ᵘ-contract ;ˡ-expand to ᵈ-expand; ʳ-expand to ᵘ-expand ;∙-cong to +-cong; assoc to +-assoc; identity to +-identity ;compatibility to +-compatibility) record PregroupPlus c ℓ₁ ℓ₂ : Set (suc (c ⊔ ℓ₁ ⊔ ℓ₂)) where infixl 7 _∙_ infixl 6 _+_ infix 4 _≈_ infix 4 _≤_ field Carrier : Set c _≈_ : Rel Carrier ℓ₁ _≤_ : Rel Carrier ℓ₂ _∙_ : Op₂ Carrier ε₁ : Carrier _ˡ : Op₁ Carrier _ʳ : Op₁ Carrier _+_ : Op₂ Carrier ε₀ : Carrier _ᵘ : Op₁ Carrier _ᵈ : Op₁ Carrier isPregroupPlus : IsPregroupPlus _≈_ _≤_ _∙_ ε₁ _ˡ _ʳ _+_ ε₀ _ᵘ _ᵈ open IsPregroupPlus isPregroupPlus public ∙-pregroup : Pregroup _ _ _ ∙-pregroup = record { isPregroup = ∙-isPregroup } open Pregroup ∙-pregroup public using ( ˡ-unique; ˡ-identity; ˡ-distrib; ˡ-contra; ˡʳ-cancel; ʳ-unique; ʳ-identity; ʳ-distrib; ʳ-contra; ʳˡ-cancel) +-pregroup : Pregroup _ _ _ +-pregroup = record { isPregroup = +-isPregroup } open Pregroup +-pregroup public using () renaming ( ˡ-unique to ᵈ-unique; ˡ-identity to ᵈ-identity; ˡ-distrib to ᵈ-distrib; ˡ-contra to ᵈ-contra; ˡʳ-cancel to ᵈᵘ-cancel; ʳ-unique to ᵘ-unique; ʳ-identity to ᵘ-identity; ʳ-distrib to ᵘ-distrib; ʳ-contra to ᵘ-contra; ʳˡ-cancel to ᵘᵈ-calcel)
function test_bug2482 % MEM 2gb % WALLTIME 00:10:00 % DEPENDENCY ft_definetrial ft_preprocessing ft_trialfun_brainvision_segmented %% define the trials headerfile = dccnpath('/home/common/matlab/fieldtrip/data/test/bug2482/001 P11 M1 004_Seg_fs6.vhdr'); datafile = dccnpath('/home/common/matlab/fieldtrip/data/test/bug2482/001 P11 M1 004_Seg_fs6.eeg'); cfg = []; cfg.trialfun = 'ft_trialfun_brainvision_segmented'; cfg.trigformat = 'DIN%d'; cfg.dataset = headerfile; cfg1 = ft_definetrial(cfg); cfg.dataset = datafile; cfg2 = ft_definetrial(cfg); if ~isequal(cfg1.trl, cfg2.trl) error('different trl matrix generated when specifying data file or headerfile as cfg.dataset'); end %% read data data = ft_preprocessing(cfg1); %% test to see whether ERP is fine % no need to run this every time, just a one time check (ES 3-mar-2014) % cfg = []; % cfg.channel = 'Cz'; % cfg.vartrllength = 2; % tl = ft_timelockanalysis(cfg, data); % % cfg = []; % cfg.ylim = [-50 50]; % ft_singleplotER(cfg,tl);
// // Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_MYSQL_ERROR_HPP #define BOOST_MYSQL_ERROR_HPP #include <boost/system/error_code.hpp> #include <string> #include <ostream> #include "boost/mysql/errc.hpp" namespace boost { namespace mysql { /// An alias for boost::system error codes. using error_code = boost::system::error_code; /** * \brief Additional information about error conditions * \details Contains an error message describing what happened. Not all error * conditions are able to generate this extended information - those that * can't have an empty error message. */ class error_info { std::string msg_; public: /// Default constructor. error_info() = default; /// Initialization constructor. error_info(std::string&& err) noexcept: msg_(std::move(err)) {} /// Gets the error message. const std::string& message() const noexcept { return msg_; } /// Sets the error message. void set_message(std::string&& err) { msg_ = std::move(err); } /// Restores the object to its initial state. void clear() noexcept { msg_.clear(); } }; /** * \relates error_info * \brief Compare two error_info objects. */ inline bool operator==(const error_info& lhs, const error_info& rhs) noexcept { return lhs.message() == rhs.message(); } /** * \relates error_info * \brief Compare two error_info objects. */ inline bool operator!=(const error_info& lhs, const error_info& rhs) noexcept { return !(lhs==rhs); } /** * \relates error_info * \brief Streams an error_info. */ inline std::ostream& operator<<(std::ostream& os, const error_info& v) { return os << v.message(); } } // mysql } // boost #include "boost/mysql/impl/error.hpp" #endif
[STATEMENT] lemma inv_correspondence_conv_apply: "x \<in> pG \<Longrightarrow> \<ii>\<pp> x = x\<rightarrow>e" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> pG \<Longrightarrow> \<ii>\<pp> x = x \<rightarrow> e [PROOF STEP] using G_perm_apply_identity inj_on_\<pp>_G [PROOF STATE] proof (prove) using this: ?g \<in> G \<Longrightarrow> \<pp> ?g \<rightarrow> e = ?g inj_on \<pp> G goal (1 subgoal): 1. x \<in> pG \<Longrightarrow> \<ii>\<pp> x = x \<rightarrow> e [PROOF STEP] by (auto intro: the_inv_into_f_eq)
= = = Structure = = =
\documentclass[9pt,twocolumn,twoside]{styles/osajnl} \usepackage{fancyvrb} \usepackage[colorinlistoftodos,prependcaption,textsize=normal]{todonotes} \newcommand{\TODO}[2][]{\todo[color=red!10,inline,#1]{#2}} \newcommand{\GE}{\TODO{Grammar}} \newcommand{\SE}{\TODO{Spelling}} \newcommand{\TE}{\TODO{Term}} \newcommand{\CE}{\TODO{Citation}} \journal{i524} \title{Twister: A new approach to MapReduce Programming} \author[1,*]{Vasanth Methkupalli} \affil[1]{School of Informatics and Computing, Bloomington, IN 47408, U.S.A.} \affil[*]{Corresponding authors: [email protected]} \dates{Paper-1, \today} \ociscodes{MapReduce, Twister, Iterative, reduction, combine} % replace this with your url in github/gitlab \doi{\url{https://github.com/cloudmesh/sp17-i524/blob/master/paper1/S17-IR-2019/report.pdf}} \begin{abstract} MapReduce is a method to process vast sums of data in parallel without requiring the developer to write any other code other than the mapper and reduce functions. Starting with Google in 2004 there has been a lot of research going on in this particular field since the rate at which data is increasing is exponential. The need to store the data and analyze has become of paramount importance in the current situation. This has lead the researcher's to look for various parallel processing programming models to saturate the needs. Of these MPI, MapReduce are some of the examples which has produced good results to the scientific community. Here in this paper we examine an implementation of MapReduce programming model, Twister, which exhibits some improvements over the current model. \newline \end{abstract} \setboolean{displaycopyright}{true} \begin{document} \maketitle \TODO{This review document is provided for you to achieve your best. We have listed a number of obvious opportunities for improvement. When improving it, please keep this copy untouched and instead focus on improving report.tex. The review does not include all possible improvement suggestions and if you sea comment you may want to check if this comment applies elsewhere in the document.} \TODO{In the Abstract, "without requiring the developer to write any..." is a very strong statement, any citations to support it?} \section{Introduction} Emergence of massive data sets in many areas and settings have presented many challenges and opportunities in data storage and analysis\cite{dean2008mapreduce}\cite{mohebi2016iterative}. Traditional analytic tools many a times cannot live up to the needs and demands at the ongoing rate at which data is produced to store and analyze it\cite{lee2012parallel}. However, domain knowledge and research have given rise to new tools and technologies which has made many of these tasks easier\cite{zaharia2010spark}. Google’s MapReduce falls in to one of these categories. The MapReduce programming framework uses two tasks common in functional programming: Map and Reduce, Map() procedure (method) that performs filtering and sorting, Reduce() method that performs a summary operation(merging the results)\cite{wikipedia}\cite{mohammed2014applications}. MapReduce is a new parallel processing framework and Hadoop is its open-source implementation on a single computing node or on clusters. Compared with existing parallel processing paradigms (e.g. grid computing and graphical processing unit (GPU)), MapReduce and Hadoop have two advantages:1) Fault-tolerant storage resulting in reliable data processing by replicating the computing tasks, and cloning the data chunks on different computing nodes across the computing cluster. 2) High-throughput data processing via a batch processing framework and the Hadoop distributed file system (HDFS)\cite{elsayed2014mapreduce}\cite{ekanayake2010twister}\cite{lee2012parallel}. Data are stored in the HDFS and made available to the slave nodes for computation. A MapReduce program consists of the "MapReduce System" (also called "infrastructure" or "framework") orchestrates the processing by marshalling the distributed servers, running the various tasks in parallel, managing all communications and data transfers between the various parts of the system, and providing for redundancy and fault tolerance\cite{mohammed2014applications}. MapReduce programming model has simplified the implementations of many data parallel applications\cite{lee2012parallel}. The simplicity of the programming model and the quality of services provided by many implementations of MapReduce attract a lot of enthusiasm among parallel computing communities\cite{ekanayake2010twister}\cite{grolinger2014challenges}. It has been identified that MapReduce can be extended to many other applications by improving on the programming model and the architecture. In this regard, Twister attempts to extend the Google’s MapReduce application to more class of applications by including more features\cite{twister}\cite{doulkeridis2014survey}. \begin{figure}[htbp] \centering \fbox{\includegraphics[width=\linewidth]{images/a}} \caption{Twister Programming model.} \label{fig:Twister Programming model} \end{figure} \section{Twister:} \TODO{remove the colon in the section title} Twister was developed as a part of Ph.D. research and is an going research project by the SALSA team @IU\cite{grolinger2014challenges}\cite{dean2008mapreduce}. \TODO{how about "at Indiana University"?}Identifying many problems in MapReduce programming model, they have envisioned to develop a better version to apply it to various scientific applications\cite{zaharia2010spark}. A set of extensions to the programming model and improvements to its architecture that will expand the applicability of MapReduce to more classes of applications\cite{elsayed2014mapreduce}. Twister is a lightweight MapReduce runtime that has been developed by incorporating these enhancements\cite{ekanayake2010twister}\cite{lee2012parallel}. \TODO{reduce the above repeative description about how good it is} Twister provides the following features to support MapReduce computations. 1) Distinction on static and variable data 2) Configurable long running (cacheable) map/reduce tasks 3) Pub/sub messaging based communication/data transfers 4) Efficient support for Iterative MapReduce computations (extremely faster than Hadoop or Dryad/DryadLINQ) 5) Combine phase to collect all reduce outputs 6) Data access via local disks 7) Lightweight (~5600 lines of Java code) 8) Support for typical MapReduce computations 9) Tools to manage data\cite{twister}\cite{doulkeridis2014survey}. \section{Twister improvements over MapReduce programming model:} \label{sec:examples} \subsection{Static vs. Dynamic Data} In all the iterative applications which were observed, they showed two types of data formats, one-static data, two-dynamic data\cite{grolinger2014challenges}. Static data is data which is fixed throughout the computation whereas the variable data(Dynamic Data) is the computed results in each iteration and typically consumed in the next iteration in other applications, one of which example is an expectation minimization algorithms\cite{doulkeridis2014survey}. \TODO{good, they are different, but how the performance is improved?} \subsection{Canceable Mappers/Reducers} Although some of the typical MapReduce computations such as distributed sorting and information retrieval consume very large data sets, many iterative applications we encounter operate on moderately sized data sets which can fit into the distributed memory of the computation clusters\cite{elsayed2014mapreduce}. This observation led us to explore the idea of using long running map/reduce tasks similar to the long running parallel processes in many MPI applications which last throughout the life of the computation. The long running (cacheable) map/reduce tasks allow map/reduce tasks to be configured with static data and use them without loading again and again in each iteration\cite{lee2012parallel}. Current MapReduce implementations such as Hadoop and DryadLINQ do not support this behavior and hence they initiate new map/reduce tasks and load static data in each iteration incurring considerable performance overheads\cite{twister}. \subsection{Supports "side-effect-free" Programming} Twister has long running map-reduce takes by which it does not encourage users to store state information in the map/reduce tasks. Thereby, achieving the side-effect-free nature of MapReduce. Caching the static data across map/reduce tasks helps in achieving better thoroughput\cite{lee2012parallel}. This framework does not ensure the use of same set of map/reduce tasks throughout the life of an iterative computation\cite{twister}. \subsection{Combine Step as Further Reduction} Twister also introduce an optional reduction phase named "combine", which is another reduction phase that can be used to combine the results of the reduce phase into a single value. The user program and the combine operation run on a single process space allowing its output directly accessible to the user program\cite{grolinger2014challenges}. This enables the user to check conditions based on the output of the MapReduce computations\cite{twister}. \subsection{Uses Pub/sub messaging} Twister uses pub/sub messaging for all the communication/data transfer requirements which eliminates the overhead in transferring data via file systems as in Hadoop orDryadLINQ\cite{grolinger2014challenges}. The output <Key,Value> pairs produced during the map stage get transferred directly to the reduce stage and the output of the reduce stage get transferred directly to the combined stage via the pub-sub broker network\cite{lee2012parallel}. Currently Twister uses publish-subscribe messaging capabilities of NaradaBrokering messaging infrastructure, but the framework is extensible to support any other publish-subscribe messaging infrastructure such as Active MQ \cite{twister}. \subsection{Data Access via local disks} Two mechanisms about data access have been proposed in Twister; (i) Directly from the local disk of computer nodes, (ii) Directly from the pub-sub infrastructure\cite{elsayed2014mapreduce}. For the simplicity of the implementation, Twister provided a file based data access mechanism for the map/reduce tasks. Unlike Hadoop, twister does not come with the built in file system. Instead it provides a tool to manage the data across these distributed disks. Apart from the above the use of streaming enables Twister to support features such as directly sending input <Key,Value> pairs for the map stage from the user program and configuring map/reduce stages using the data sent from the user program\cite{mohammed2014applications}. \subsection{Fault Tolerance} Providing fault tolerance support for iterative computations with Twister is currently under development. \section{Application of Twister to present problems:} \TODO{this section needs to be improved in this way: you don't need to illustrate in detail each typical problem, focus on showing some results to prove Twister has better scores, as there are many aspects being listed in previous section claiming Twister's advantages.} \subsection{K-Means Clustering} Kmeans clustering is a well-known clustering algorithm aiming to cluster a set of data points to a predefined number of clusters. In that each map function gets a portion of the data, and it needs to access this data split in each iteration. These data items do not change over the iterations, and it is loaded once for the entire set of iterations. The variable data is the current cluster centers calculated during the previous iteration and hence used as the input value for the map function\cite{twister}\cite{dean2008mapreduce}. All the map functions get this same input data (current cluster centers) at each iteration and computes a partial cluster centers by going through its data set. A reduce function computes the average of the partial cluster centers and produce the cluster centers for the next step. Main program, once it gets these new cluster centers, calculates the difference between the new cluster centers and the previous cluster centers and determine if it needs to execute another cycle of MapReduce computation\cite{ekanayake2008mapreduce}\cite{twister}. \subsection{Matrix Multiplication} Let A and B, produce matrix C, as the result of the multiplication process. Here they split the matrix B into a set of column blocks and the matrix A into a set of row blocks. In each iteration, all the map tasks process two inputs: (i) a column block of matrix B, and (ii) a row block of matrix A; collectively, they produce a row block of the resultant matrix C. The column block associated with a particular map task is fixed throughout the computation, while the row blocks are changed in each iteration. However, in Hadoop's programming model (a typical MapReduce model), there is no way to specify this behavior. Hence, it loads both the column block and the row block in each iteration of the computation. Twister supports the notion of long running map/reduce tasks where these tasks are allowed to retain static data in the memory across invocations, yielding better performance for "Iterative MapReduce" computations\cite{dean2008mapreduce}\cite{twister}. \subsection{Page Rank} In Twister implementation of PageRank, we constructed web graphs with vertices where in-link degree of all pages comply with the power law distribution. These input data are partitioned into few parts and stored in the format of adjacency list. Each map function runs on one of the partitioned data, which are constant over the iterations. The variable data are the PageRank values calculated during previous iteration which in turns used as the input value for the next iteration. In each iteration, the MAP task updates the old PageRank values to new one by analyzing the local partial adjacency list file. The output of MAP task is partial of PageRank values. The reduce task receives all the partial output and produces the new PageRank values\cite{twister}. \subsection{Graph Search} This algorithm tries to use Twister Framework to process breadth-first graph search problem in parallel. This algorithm is based on Cailin's Hadoop version of breadth-first graph search[10]. The basic idea of this algorithm is to exploring the nodes of the same level parallel, and then explore the next levels iteratively\cite{twister}. \subsection{Word Count} In typical word count applications implemented using other MapReduce runtimes, the map task outputs (word,1) pairs for all the words it encounter. This approach is not optimized for performance rather simple to program. With small amount of more complexity we can simply convert this map task to produce a list of (word,count) pairs corresponding to the local data partion. This is the approach used in Twister word count application\cite{twister}. \subsection{High Energy Physics(HEP) Data Analysis} The goal of the analysis is to execute a set of analysis functions on a collection of data files produced by high-energy physics experiments. After processing each data file, the analysis produces a histogram of identified features. These histograms are then combined to produce the final result of the overall analysis. This data analysis task is both data and compute intensive and fits very well for MapReduce computation model. First figure shows the program flow of this analysis once it is converted to a MapReduce implementation and the second figure compares the performance of Twister and Hadoop for this data analysis[12]\cite{twister}. \section{Conclusion} It has been observed that changes in the programming model and the way the nodes interact with each other(pub-sub messaging)\cite{ekanayake2010twister}, has produced very good results with Twister MapReduce. This has in turn lead it benificial to many applications of which many have been discussed in the present paper. So it can be safe to assume that Twister has a very high scope for commercial applications even thought it is limited to scientific applications as of now. \bibliography{references} \end{document}
header{* The First Monotonicity Calculus *} theory Mcalc imports Mono begin context ProblemIk begin subsection{* Naked variables *} fun nvT where "nvT (Var x) = {x}" | "nvT (Fn f Tl) = {}" fun nvA where "nvA (Eq T1 T2) = nvT T1 \<union> nvT T2" | "nvA (Pr p Tl) = {}" fun nvL where "nvL (Pos at) = nvA at" | "nvL (Neg at) = {}" definition "nvC c \<equiv> \<Union> set (map nvL c)" definition "nvPB \<equiv> \<Union> c \<in> \<Phi>. nvC c" lemma nvT_vars[simp]: "x \<in> nvT T \<Longrightarrow> x \<in> vars T" by (induct T) (auto split: if_splits) lemma nvA_varsA[simp]: "x \<in> nvA at \<Longrightarrow> x \<in> varsA at" by (cases at, auto) lemma nvL_varsL[simp]: "x \<in> nvL l \<Longrightarrow> x \<in> varsL l" by (cases l, auto) lemma nvC_varsC[simp]: "x \<in> nvC c \<Longrightarrow> x \<in> varsC c" unfolding varsC_def nvC_def by(induct c, auto) lemma nvPB_varsPB[simp]: "x \<in> nvPB \<Longrightarrow> x \<in> varsPB \<Phi>" unfolding varsPB_def nvPB_def by auto subsection{* The calculus *} inductive mcalc (infix "\<turnstile>" 40) where [simp]: "infTp \<sigma> \<Longrightarrow> \<sigma> \<turnstile> c" |[simp]: "(\<forall> x \<in> nvC c. tpOfV x \<noteq> \<sigma>) \<Longrightarrow> \<sigma> \<turnstile> c" lemma mcalc_iff: "\<sigma> \<turnstile> c \<longleftrightarrow> infTp \<sigma> \<or> (\<forall> x \<in> nvC c. tpOfV x \<noteq> \<sigma>)" unfolding mcalc.simps by simp end (* context ProblemIk *) locale ProblemIkMcalc = ProblemIk wtFsym wtPsym arOf resOf parOf \<Phi> infTp for wtFsym :: "'fsym \<Rightarrow> bool" and wtPsym :: "'psym \<Rightarrow> bool" and arOf :: "'fsym \<Rightarrow> 'tp list" and resOf and parOf and \<Phi> and infTp + assumes mcalc: "\<And> \<sigma> c. c \<in> \<Phi> \<Longrightarrow> \<sigma> \<turnstile> c" locale ModelIkMcalc = ModelIk wtFsym wtPsym arOf resOf parOf \<Phi> infTp intT intF intP + ProblemIkMcalc wtFsym wtPsym arOf resOf parOf \<Phi> infTp for wtFsym :: "'fsym \<Rightarrow> bool" and wtPsym :: "'psym \<Rightarrow> bool" and arOf :: "'fsym \<Rightarrow> 'tp list" and resOf and parOf and \<Phi> and infTp and intT and intF and intP subsection{* Extension of a structure to an infinite structure by adding indistinguishable elements *} context ModelIkMcalc begin text{* The projection from univ to a structure: *} definition proj where "proj \<sigma> a \<equiv> if intT \<sigma> a then a else pickT \<sigma>" lemma intT_proj[simp]: "intT \<sigma> (proj \<sigma> a)" unfolding proj_def using pickT by auto lemma proj_id[simp]: "intT \<sigma> a \<Longrightarrow> proj \<sigma> a = a" unfolding proj_def by auto lemma surj_proj: assumes "intT \<sigma> a" shows "\<exists> b. proj \<sigma> b = a" using assms by (intro exI[of _ a]) simp definition "I_intT \<sigma> (a::univ) \<equiv> infTp \<sigma> \<longrightarrow> intT \<sigma> a" definition "I_intF f al \<equiv> intF f (map2 proj (arOf f) al)" definition "I_intP p al \<equiv> intP p (map2 proj (parOf p) al)" lemma not_infTp_I_intT[simp]: "\<not> infTp \<sigma> \<Longrightarrow> I_intT \<sigma> a" unfolding I_intT_def by simp lemma infTp_I_intT[simp]: "infTp \<sigma> \<Longrightarrow> I_intT \<sigma> a = intT \<sigma> a" unfolding I_intT_def by simp lemma NE_I_intT: "NE (I_intT \<sigma>)" using NE_intT by (cases "infTp \<sigma>", auto) lemma I_intF: assumes f: "wtFsym f" and al: "list_all2 I_intT (arOf f) al" shows "I_intT (resOf f) (I_intF f al)" unfolding I_intT_def I_intF_def apply safe apply(rule intF[OF f]) using al unfolding list_all2_length by auto lemma Tstruct_I_intT: "Tstruct I_intT" apply default using NE_I_intT . lemma inf_I_intT: "infinite {a. I_intT \<sigma> a}" by (cases "infTp \<sigma>", auto) lemma InfStruct: "IInfStruct I_intT I_intF I_intP" apply default using NE_I_intT I_intF Tstruct_I_intT inf_I_intT by auto end (* context ModelIkMcalc *) sublocale ModelIkMcalc < InfStruct where intT = I_intT and intF = I_intF and intP = I_intP using InfStruct . subsection{* The soundness of the calculus *} text{* In what follows, ``Ik'' stands for the original (augmented with infiniteness-knowledge) and ``I'' for the infinite structure constructed from it through the above sublocale statement. *} context ModelIkMcalc begin text{* The environment translation along the projection: *} definition "transE \<xi> \<equiv> \<lambda> x. proj (tpOfV x) (\<xi> x)" lemma wtE_transE[simp]: "I.wtE \<xi> \<Longrightarrow> Ik.wtE (transE \<xi>)" unfolding Ik.wtE_def I.wtE_def transE_def by auto abbreviation "Ik_intT \<equiv> intT" abbreviation "Ik_intF \<equiv> intF" abbreviation "Ik_intP \<equiv> intP" lemma Ik_intT_int: assumes wt: "Ik.wt T" and \<xi>: "I.wtE \<xi>" and snv: "\<And> \<sigma>. infTp \<sigma> \<or> (\<forall> x \<in> nvT T. tpOfV x \<noteq> \<sigma>)" shows "Ik_intT (tpOf T) (I.int \<xi> T)" proof(cases "\<exists> x. T = Var x") case True then obtain x where T: "T = Var x" by auto show ?thesis proof(cases "infTp (tpOf T)") case True thus ?thesis using T using wtE_transE[OF \<xi>] by (metis I.wt_int I_intT_def \<xi> wt) next case False hence "\<forall> x \<in> nvT T. tpOfV x \<noteq> tpOf T" using snv by auto hence "Ik.full (tpOf T)" using T by (cases T, simp_all) thus ?thesis unfolding Ik.full_def by simp qed next case False hence nonVar: "\<not> (\<exists> x. T = Var x)" by (cases T, auto) thus ?thesis using nonVar wt apply(induct T, force) unfolding I_intF_def tpOf.simps int.simps apply(rule Ik.intF, simp) apply(rule listAll2_map2I) by auto qed lemma int_transE_proj: assumes wt: "Ik.wt T" shows "Ik.int (transE \<xi>) T = proj (tpOf T) (I.int \<xi> T)" using wt proof (induct T) case (Fn f Tl) have 0: "Ik_intT (resOf f) (I_intF f (map (int \<xi>) Tl))" (is "Ik_intT ?\<sigma> ?a") unfolding I_intF_def apply(rule Ik.intF) using Fn unfolding list_all2_length list_all_iff by auto have 1: "proj ?\<sigma> ?a = ?a" using proj_id[OF 0] . show ?case unfolding Ik.int.simps int.simps tpOf.simps 1 unfolding I_intF_def apply(rule arg_cong[of _ _ "intF f"]) proof (rule nth_equalityI, safe) have l[simp]: "length (arOf f) = length Tl" using Fn by simp fix i assume "i < length (map (Ik.int (transE \<xi>)) Tl)" hence i[simp]: "i < length Tl" by simp have 0: "arOf f ! i = tpOf (Tl ! i)" using Fn by simp have [simp]: "Ik.int (transE \<xi>) (Tl ! i) = proj (arOf f ! i) (I.int \<xi> (Tl ! i))" unfolding 0 using Fn by (auto simp: list_all_length transE_def) show "map (Ik.int (transE \<xi>)) Tl ! i = map2 proj (arOf f) (map (I.int \<xi>) Tl) ! i" using Fn unfolding list_all_length by simp qed(insert Fn, simp) qed simp lemma int_transE_snv[simp]: assumes wt: "Ik.wt T" and \<xi>: "I.wtE \<xi>" and snv: "\<And> \<sigma>. infTp \<sigma> \<or> (\<forall> x \<in> nvT T. tpOfV x \<noteq> \<sigma>)" shows "Ik.int (transE \<xi>) T = I.int \<xi> T" unfolding int_transE_proj[OF wt] apply(rule proj_id) using Ik_intT_int[OF wt \<xi> snv] . lemma int_transE_Fn: assumes wt: "list_all wt Tl" and f: "wtFsym f" and \<xi>: "I.wtE \<xi>" and ar: "arOf f = map tpOf Tl" shows "Ik.int (transE \<xi>) (Fn f Tl) = I.int \<xi> (Fn f Tl)" apply(rule int_transE_snv) using assms by auto lemma intP_transE[simp]: assumes wt: "list_all wt Tl" and p: "wtPsym p" and ar: "parOf p = map tpOf Tl" shows "Ik_intP p (map (Ik.int (transE \<xi>)) Tl) = I_intP p (map (I.int \<xi>) Tl)" unfolding I_intP_def apply(rule arg_cong[of _ _ "Ik_intP p"]) apply(rule nth_equalityI) using assms using int_transE_proj unfolding list_all_length by auto lemma satA_snvA_transE[simp]: assumes wtA: "Ik.wtA at" and \<xi>: "I.wtE \<xi>" and pA: "\<And> \<sigma>. infTp \<sigma> \<or> (\<forall> x \<in> nvA at. tpOfV x \<noteq> \<sigma>)" shows "Ik.satA (transE \<xi>) at \<longleftrightarrow> I.satA \<xi> at" using assms apply (cases at, simp_all add: ball_Un) by (metis int_transE_snv) (* The next contrapositive twist is crucial for proving satL_transE: *) lemma satA_transE[simp]: assumes wtA: "Ik.wtA at" and "I.satA \<xi> at" shows "Ik.satA (transE \<xi>) at" using assms apply(cases at) using int_transE_proj by auto lemma satL_snvL_transE[simp]: assumes wtL: "Ik.wtL l" and \<xi>: "I.wtE \<xi>" and pL: "\<And> \<sigma>. infTp \<sigma> \<or> (\<forall> x \<in> nvL l. tpOfV x \<noteq> \<sigma>)" and "Ik.satL (transE \<xi>) l" shows "I.satL \<xi> l" using assms by (cases l) auto lemma satC_snvC_transE[simp]: assumes wtC: "Ik.wtC c" and \<xi>: "I.wtE \<xi>" and pC: "\<And> \<sigma>. \<sigma> \<turnstile> c" and "Ik.satC (transE \<xi>) c" shows "I.satC \<xi> c" using assms unfolding Ik.mcalc_iff Ik.satC_def satC_def Ik.wtC_def nvC_def unfolding list_all_iff list_ex_iff apply simp by (metis nth_mem satL_snvL_transE) lemma satPB_snvPB_transE[simp]: assumes \<xi>: "I.wtE \<xi>" shows "I.satPB \<xi> \<Phi>" using Ik.wt_\<Phi> Ik.sat_\<Phi>[OF wtE_transE[OF \<xi>]] using mcalc \<xi> unfolding Ik.satPB_def satPB_def Ik.wtPB_def nvPB_def by auto lemma I_SAT: "I.SAT \<Phi>" unfolding I.SAT_def by auto lemma InfModel: "IInfModel I_intT I_intF I_intP" apply default using I_SAT . end (* context ModelIkMcalc *) sublocale ModelIkMcalc < InfModel where intT = I_intT and intF = I_intF and intP = I_intP using InfModel . context ProblemIkMcalc begin abbreviation "MModelIkMcalc \<equiv> ModelIkMcalc wtFsym wtPsym arOf resOf parOf \<Phi> infTp" end (* context ProblemIkMcalc *) text{* Final theorem in sublocale form: Any problem that passes the monotonicity calculus is monotonic: *} sublocale ProblemIkMcalc < MonotProblem apply default using monot . end
Becoming a parent is supposed to be one of the most exciting and happiest days in one’s life. But as the stories of Serena Williams, Lauren Bloomstein, and many others published over the past year show, the very real threat of complications has made giving birth in America more scary than exciting. The US has the highest rate of maternal mortality in the developed world; in 2015, 26.4 out of every 100,000 live births resulted in maternal mortality. That’s more than three times the rate in Canada, four times the rate in Japan, and nearly five times as high as Australia’s. Further, women in certain states and regions of the US, and especially African American women, face extremely high rates of maternal mortality. The session featured Dr. Carol Sakala, Director of Childbirth Connection Programs at the National Partnership for Women & Families; Nan Strauss, Director of Policy and Advocacy at Every Mother Counts; Dr. Steven Calvin, Medical Director of the Minnesota Birth Center; and Dianna Jolles, faculty at Frontier Nursing University and practitioner at El Rio Community Health Center. The panelists pointed out that both overuse and underuse are prevalent in maternity care. Many women, especially those in rural areas, do not have easy access to maternal care. Additionally, high rates of obesity, diabetes, and high blood pressure (which are often untreated) create a greater risk of complications for American mothers. But at the same time, too many unnecessary interventions are being done during childbirth. The rate of cesarean sections in the US is about 32%, much higher than the rate recommended by the World Health Organization. C-section rates also vary widely across states. Why is there so much geographical variation? Diana Jolles explained that whether a mother has a c-section is not always dependent on medical need, but can depend on the hospital or clinic’s access to resources, payer source, and provider practice styles. Carol Sakala echoed this point in her presentation of the NPWF “State of the Science” on maternity care. Much of the obstetrics field is focused on the “rescue” of high-risk pregnancies, but this misses the chance to prevent complications in the first place, said Sakala. At the same time, we use specialized care for low-risk pregnancies unnecessarily, which can be harmful. In many of the stories of preventable maternal harm or near-harm, there is a prevalent theme of the patient not being heard. There are stories where the patient was highly educated, knew exactly what was wrong, had the same complication before, or even had a medical degree themselves, and doctors still ignored the patient when she insisted that something was wrong. One way to combat this dangerous and frustrating problem is by integrating support from a midwife and doula, said Nan Strauss. Midwives and doulas provide different but complimentary services (midwives are licensed health care providers that provide prenatal, labor, and post-partum support, while doulas provide non-clinical physical and emotional support during birth). Having continuous, one-on-one support from another person is associated with increased likelihood of spontaneous vaginal birth, reduced likelihood of a cesarean birth, and reduced negative feelings about childbirth, compared with just having physician care. “The goal is to put the person at the center of the equation,” said Strauss. The US is lagging behind other countries in maternal care, but several states are taking steps to change that. Recently, governor Andrew Cuomo of New York announced a pilot program allowing Medicaid to reimburse patients for doula services, making New York the third state to expand Medicaid coverage for doulas. Stuebe and others recently released a statement from a task force of the American College of Obstetricians and Gynecologists, urging doctors to make postpartum care an “ongoing process, rather than a single encounter, with services and support tailored to each woman’s individual needs.” Statements like these are long overdue, as are steps to facilitate continuous support and reduce unnecessary interventions during birth.
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import ring_theory.int.basic import tactic.ring /-! # ℤ[√d] The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), neg := has_neg.neg, mul := (*), sub := λ a b, a + -b, one := 1, npow := @npow_rec (ℤ√d) ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩, zsmul := @zsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ ⟨zsqrtd.neg⟩ }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- `conj` as an `add_monoid_hom`. -/ def conj_hom : ℤ√d →+ ℤ√d := { to_fun := conj, map_add' := λ ⟨a, ai⟩ ⟨b, bi⟩, ext.mpr ⟨rfl, neg_add _ _⟩, map_zero' := ext.mpr ⟨rfl, neg_zero⟩ } @[simp] lemma conj_zero : conj (0 : ℤ√d) = 0 := conj_hom.map_zero @[simp] lemma conj_one : conj (1 : ℤ√d) = 1 := by simp only [zsqrtd.ext, zsqrtd.conj_re, zsqrtd.conj_im, zsqrtd.one_im, neg_zero, eq_self_iff_true, and_self] @[simp] lemma conj_neg (x : ℤ√d) : (-x).conj = -x.conj := conj_hom.map_neg x @[simp] lemma conj_add (x y : ℤ√d) : (x + y).conj = x.conj + y.conj := conj_hom.map_add x y @[simp] lemma conj_sub (x y : ℤ√d) : (x - y).conj = x.conj - y.conj := conj_hom.map_sub x y @[simp] lemma conj_conj {d : ℤ} (x : ℤ√d) : x.conj.conj = x := by simp only [ext, true_and, conj_re, eq_self_iff_true, neg_neg, conj_im] instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul {a b : ℤ√d} : conj (a * b) = conj a * conj b := by { simp [ext], ring } protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h @[simp, norm_cast] lemma coe_int_dvd_coe_int (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := begin rw coe_int_dvd_iff, split, { rintro ⟨hre, -⟩, rwa [coe_int_re] at hre }, { rw [coe_int_re, coe_int_im], exact λ hc, ⟨hc, dvd_zero a⟩ }, end protected lemma eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := begin rw ext at h ⊢, apply and.imp _ _ h; { simp only [smul_re, smul_im], exact int.eq_of_mul_eq_mul_left ha }, end section gcd lemma gcd_eq_zero_iff (a : ℤ√d) : int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [int.gcd_eq_zero_iff, ext, eq_self_iff_true, zero_im, zero_re] lemma gcd_pos_iff (a : ℤ√d) : 0 < int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans $ not_congr a.gcd_eq_zero_iff lemma coprime_of_dvd_coprime {a b : ℤ√d} (hcoprime : is_coprime a.re a.im) (hdvd : b ∣ a) : is_coprime b.re b.im := begin apply is_coprime_of_dvd, { rintro ⟨hre, him⟩, obtain rfl : b = 0, { simp only [ext, hre, eq_self_iff_true, zero_im, him, and_self, zero_re] }, rw zero_dvd_iff at hdvd, simpa only [hdvd, zero_im, zero_re, not_coprime_zero_zero] using hcoprime }, { intros z hz hznezero hzdvdu hzdvdv, apply hz, obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im, { rw ←coe_int_dvd_iff, apply dvd_trans _ hdvd, rw coe_int_dvd_iff, exact ⟨hzdvdu, hzdvdv⟩ }, exact hcoprime.is_unit_of_dvd' ha hb }, end lemma exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ is_coprime b.re b.im := begin obtain ⟨re, im, H1, Hre, Him⟩ := int.exists_gcd_one hgcd, rw [mul_comm] at Hre Him, refine ⟨⟨re, im⟩, _, _⟩, { rw [smul_val, ext, ←Hre, ←Him], split; refl }, { rw [←int.gcd_eq_one_iff_coprime, H1] } end end gcd /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_neg, neg_mul, mul_neg, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : x.conj.norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_conj, mul_comm] lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff' left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) le_rfl xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (int.le.intro h)) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_add_sub_cancel'] theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_sq (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ mul_right_cancel₀ w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ mul_right_cancel₀ z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : is_domain ℤ√d := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, .. zsqrtd.comm_ring, .. zsqrtd.nontrivial } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_ring ℤ√d := by apply_instance instance : ordered_ring ℤ√d := by apply_instance end lemma norm_eq_zero {d : ℤ} (h_nonsquare : ∀ n : ℤ, d ≠ n*n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, λ h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≤ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊢, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} [comm_ring R] @[ext] lemma hom_ext {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : ℤ} : {r : R // r * r = ↑d} ≃ (ℤ√d →+* R) := { to_fun := λ r, { to_fun := λ a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := λ a b, by { simp, ring, }, map_one' := by simp, map_mul' := λ a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := λ f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, ring_hom.map_int_cast]⟩, left_inv := λ r, by { ext, simp }, right_inv := λ f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : ℤ} (r : {r : R // r * r = ↑d}) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (lift r) := (lift r).injective_iff.mpr $ λ a ha, begin have h_inj : function.injective (coe : ℤ → R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end end zsqrtd
Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Specific.montgomery32_2e389m21_13limbs.Synthesis. (* TODO : change this to field once field isomorphism happens *) Definition opp : { opp : feBW_small -> feBW_small | forall a, phiM_small (opp a) = F.opp (phiM_small a) }. Proof. Set Ltac Profiling. Time synthesize_opp (). Show Ltac Profile. Time Defined. Print Assumptions opp.
# DSPipeline Imports from DSPipeline.ds_pipeline import Pipeline from DSPipeline.data_transformations import StandardScalerStep from DSPipeline.feature_selection import PearsonCorrStep from DSPipeline.outlier_detection import ABODStep # Other Imports import numpy as np import pandas as pd from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error from sklearn.linear_model import LinearRegression # Load Data boston = load_boston() y_label = "MEDV" # The traditional name for Boston's target value X = pd.DataFrame(boston.data, columns=boston.feature_names) y = pd.Series(boston.target, name=y_label) # Split into test and train. # NOTE: Resetting the indices is very important and not doing so will result in errors train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.33) train_X = train_X.reset_index(drop=True) test_X = test_X.reset_index(drop=True) train_y = train_y.reset_index(drop=True) test_y = test_y.reset_index(drop=True) # Create Steps scale_step = StandardScalerStep() abod_step = ABODStep(num_remove=5, kwargs={'contamination':0.05}) corr_step = PearsonCorrStep(num_features=0.25) # Make Pipeline pipeline_steps = [scale_step, abod_step, corr_step] pipeline = Pipeline(pipeline_steps) # Transform data sets train_X_transformed, train_y_transformed = pipeline.fit_transform(train_X, train_y) test_X_transformed = pipeline.transform(test_X, allow_sample_removal=False) # Use data to make predictions model = LinearRegression() model.fit(train_X_transformed, train_y_transformed) y_hat = model.predict(test_X_transformed) print(f'MAE: {mean_absolute_error(test_y, y_hat):.3f}')
import tactic.tidy import set_category.diagram_lemmas import help_functions import category_theory.category namespace Coequalizer open set diagram_lemmas classical function help_functions category_theory universe u local notation f ` ⊚ `:80 g:80 := category_struct.comp g f def is_coequalizer {X : Type u} [category X] {A B C : X} (f g : A ⟶ B) (c : B ⟶ C) : Prop := c ⊚ f = c ⊚ g ∧ Π (Q : X) (q : B ⟶ Q), q ⊚ f = q ⊚ g → ∃! h : C ⟶ Q , h ⊚ c = q variables {A B C : Type u} variables (f g : A ⟶ B) def R : B → B → Prop := λ b₁ b₂ , ∃ a , f a = b₁ ∧ g a = b₂ def Θ : B → B → Prop := eqv_gen (R f g) def Θ_setoid : setoid B := eqv_gen.setoid (R f g) definition theta := quotient (Θ_setoid f g) local notation `⟦`:max a `⟧`:0 := @quotient.mk B (Θ_setoid f g) a definition coequalizer : B → theta f g := λ b, ⟦b⟧ open eqv_gen lemma quot_is_surjective : surjective (coequalizer f g) := by tidy lemma coequalizer_kern : Π (Q : Type u) (q : B → Q), q ∘ f = q ∘ g → sub_kern (coequalizer f g) q := begin intros Q q qfg, let co := (coequalizer f g), let ker := kern co, let ker_q := kern q, intros b₁ b₂ kb1b2, have quotb1b2 : ⟦b₁⟧ = ⟦b₂⟧ := kb1b2, let Θb1b2 : eqv_gen (R f g) b₁ b₂ := @quotient.exact B (Θ_setoid f g) b₁ b₂ quotb1b2, apply eqv_gen.rec_on Θb1b2, exact (λ b₁ b₂ (h: ∃ a : A , f a = b₁ ∧ g a = b₂), let a : A := some h in have fa_ga : f a = b₁ ∧ g a = b₂ := some_spec h, calc q b₁ = (q ∘ f) a : by simp [some_spec h] ... = (q ∘ g) a : by simp [qfg] ... = q b₂ : by simp [some_spec h] ), -- refl : ∀ (x : B), ker_q x x exact (λ x, rfl), -- symm : ∀ (x y : B), eqv_gen (R f g) x y → ker_q x y → ker_q y x exact (λ x y _ (h : q x = q y), eq.symm h), -- trans :∀ (x y z : B), -- eqv_gen (R f g) x y → eqv_gen (R f g) y z → -- ker_q x y → ker_q y z → ker_q x z exact (λ x y z _ _ (h₁ : q x = q y) (h₂ : q y = q z), eq.trans h₁ h₂), end lemma quot_is_coequalizer : is_coequalizer f g (coequalizer f g) := ⟨ have element : ∀ a : A, ((coequalizer f g) ∘ f) a = ((coequalizer f g) ∘ g) a := assume a, have Rfg : R f g (f a) (g a) := exists.intro a ⟨rfl , rfl⟩, have Θfg : Θ f g (f a) (g a) := eqv_gen.rel (f a) (g a) Rfg, quot.sound Θfg, funext element , begin intros Q q qfg, let co := (coequalizer f g), have sub_ker : sub_kern co q := coequalizer_kern f g Q q qfg, exact (diagram_surjective co q (quot_is_surjective f g)).elim_right sub_ker end ⟩ end Coequalizer
[STATEMENT] lemma llist_all2_cons_code [code]: "llist_all2_cons sg sh = (case g sg of Done \<Rightarrow> lnull_cons h sh | Skip sg' \<Rightarrow> llist_all2_cons sg' sh | Yield a sg' \<Rightarrow> llist_all2_cons1 a sg' sh)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.llist_all2_cons sg sh = (case g sg of Done \<Rightarrow> lnull_cons h sh | Skip sg' \<Rightarrow> local.llist_all2_cons sg' sh | Yield a sg' \<Rightarrow> local.llist_all2_cons1 a sg' sh) [PROOF STEP] by(simp split: step.split add: llist_all2_cons_def lnull_cons_def llist_all2_cons1_def lunstream_simps lnull_def)
If $S$ is a compact set with more than one point, and $g$ is a function from $S$ to $S$ such that $g(x)$ is closer to $g(y)$ than $x$ is to $y$ for all $x$ and $y$ in $S$, then $g$ has a unique fixed point.
[STATEMENT] lemma semicategoryE': assumes "semicategory \<alpha> \<CC>" obtains "\<Z> \<alpha>" and "vfsequence \<CC>" and "vsv (\<CC>\<lparr>Comp\<rparr>)" and "vcard \<CC> = 5\<^sub>\<nat>" and "vsv (\<CC>\<lparr>Dom\<rparr>)" and "vsv (\<CC>\<lparr>Cod\<rparr>)" and "\<D>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) = \<CC>\<lparr>Arr\<rparr>" and "\<R>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>" and "\<D>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) = \<CC>\<lparr>Arr\<rparr>" and "\<R>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>" and "\<And>gf. gf \<in>\<^sub>\<circ> \<D>\<^sub>\<circ> (\<CC>\<lparr>Comp\<rparr>) \<longleftrightarrow> (\<exists>g f b c a. gf = [g, f]\<^sub>\<circ> \<and> g : b \<mapsto>\<^bsub>\<CC>\<^esub> c \<and> f : a \<mapsto>\<^bsub>\<CC>\<^esub> b)" and "\<And>b c g a f. \<lbrakk> g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b \<rbrakk> \<Longrightarrow> g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f : a \<mapsto>\<^bsub>\<CC>\<^esub> c" and "\<And>c d h b g a f. \<lbrakk> h : c \<mapsto>\<^bsub>\<CC>\<^esub> d; g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b \<rbrakk> \<Longrightarrow> (h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> g) \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f = h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> (g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f)" and "\<CC>\<lparr>Obj\<rparr> \<subseteq>\<^sub>\<circ> Vset \<alpha>" and "\<And>A B. \<lbrakk> A \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; B \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; A \<in>\<^sub>\<circ> Vset \<alpha>; B \<in>\<^sub>\<circ> Vset \<alpha> \<rbrakk> \<Longrightarrow> (\<Union>\<^sub>\<circ>a\<in>\<^sub>\<circ>A. \<Union>\<^sub>\<circ>b\<in>\<^sub>\<circ>B. Hom \<CC> a b) \<in>\<^sub>\<circ> Vset \<alpha>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<lbrakk>\<Z> \<alpha>; vfsequence \<CC>; vsv (\<CC>\<lparr>Comp\<rparr>); vcard \<CC> = 5\<^sub>\<nat>; vsv (\<CC>\<lparr>Dom\<rparr>); vsv (\<CC>\<lparr>Cod\<rparr>); \<D>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) = \<CC>\<lparr>Arr\<rparr>; \<R>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; \<D>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) = \<CC>\<lparr>Arr\<rparr>; \<R>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; \<And>gf. (gf \<in>\<^sub>\<circ> \<D>\<^sub>\<circ> (\<CC>\<lparr>Comp\<rparr>)) = (\<exists>g f b c a. gf = [g, f]\<^sub>\<circ> \<and> g : b \<mapsto>\<^bsub>\<CC>\<^esub> c \<and> f : a \<mapsto>\<^bsub>\<CC>\<^esub> b); \<And>b c g a f. \<lbrakk>g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b\<rbrakk> \<Longrightarrow> g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f : a \<mapsto>\<^bsub>\<CC>\<^esub> c; \<And>c d h b g a f. \<lbrakk>h : c \<mapsto>\<^bsub>\<CC>\<^esub> d; g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b\<rbrakk> \<Longrightarrow> h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f = h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> (g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f); \<CC>\<lparr>Obj\<rparr> \<subseteq>\<^sub>\<circ> Vset \<alpha>; \<And>A B. \<lbrakk>A \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; B \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; A \<in>\<^sub>\<circ> Vset \<alpha>; B \<in>\<^sub>\<circ> Vset \<alpha>\<rbrakk> \<Longrightarrow> \<Union>\<^sub>\<circ> ((\<lambda>a\<in>\<^sub>\<circ>A. \<Union>\<^sub>\<circ> (VLambda B (Hom \<CC> a) `\<^sub>\<circ> B)) `\<^sub>\<circ> A) \<in>\<^sub>\<circ> Vset \<alpha>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: semicategory \<alpha> \<CC> goal (1 subgoal): 1. (\<lbrakk>\<Z> \<alpha>; vfsequence \<CC>; vsv (\<CC>\<lparr>Comp\<rparr>); vcard \<CC> = 5\<^sub>\<nat>; vsv (\<CC>\<lparr>Dom\<rparr>); vsv (\<CC>\<lparr>Cod\<rparr>); \<D>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) = \<CC>\<lparr>Arr\<rparr>; \<R>\<^sub>\<circ> (\<CC>\<lparr>Dom\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; \<D>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) = \<CC>\<lparr>Arr\<rparr>; \<R>\<^sub>\<circ> (\<CC>\<lparr>Cod\<rparr>) \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; \<And>gf. (gf \<in>\<^sub>\<circ> \<D>\<^sub>\<circ> (\<CC>\<lparr>Comp\<rparr>)) = (\<exists>g f b c a. gf = [g, f]\<^sub>\<circ> \<and> g : b \<mapsto>\<^bsub>\<CC>\<^esub> c \<and> f : a \<mapsto>\<^bsub>\<CC>\<^esub> b); \<And>b c g a f. \<lbrakk>g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b\<rbrakk> \<Longrightarrow> g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f : a \<mapsto>\<^bsub>\<CC>\<^esub> c; \<And>c d h b g a f. \<lbrakk>h : c \<mapsto>\<^bsub>\<CC>\<^esub> d; g : b \<mapsto>\<^bsub>\<CC>\<^esub> c; f : a \<mapsto>\<^bsub>\<CC>\<^esub> b\<rbrakk> \<Longrightarrow> h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f = h \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> (g \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f); \<CC>\<lparr>Obj\<rparr> \<subseteq>\<^sub>\<circ> Vset \<alpha>; \<And>A B. \<lbrakk>A \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; B \<subseteq>\<^sub>\<circ> \<CC>\<lparr>Obj\<rparr>; A \<in>\<^sub>\<circ> Vset \<alpha>; B \<in>\<^sub>\<circ> Vset \<alpha>\<rbrakk> \<Longrightarrow> \<Union>\<^sub>\<circ> ((\<lambda>a\<in>\<^sub>\<circ>A. \<Union>\<^sub>\<circ> (VLambda B (Hom \<CC> a) `\<^sub>\<circ> B)) `\<^sub>\<circ> A) \<in>\<^sub>\<circ> Vset \<alpha>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (simp add: semicategoryD')
(* Title: Jinja/Compiler/Correctness2.thy Author: Tobias Nipkow Copyright TUM 2003 *) section \<open>Correctness of Stage 2\<close> theory Correctness2 imports "HOL-Library.Sublist" Compiler2 begin (*<*)hide_const (open) Throw(*>*) subsection\<open>Instruction sequences\<close> text\<open>How to select individual instructions and subsequences of instructions from a program given the class, method and program counter.\<close> definition before :: "jvm_prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> nat \<Rightarrow> instr list \<Rightarrow> bool" ("(_,_,_,_/ \<rhd> _)" [51,0,0,0,51] 50) where "P,C,M,pc \<rhd> is \<longleftrightarrow> prefix is (drop pc (instrs_of P C M))" definition at :: "jvm_prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> nat \<Rightarrow> instr \<Rightarrow> bool" ("(_,_,_,_/ \<triangleright> _)" [51,0,0,0,51] 50) where "P,C,M,pc \<triangleright> i \<longleftrightarrow> (\<exists>is. drop pc (instrs_of P C M) = i#is)" lemma [simp]: "P,C,M,pc \<rhd> (i#is) = (P,C,M,pc \<triangleright> i \<and> P,C,M,pc + 1 \<rhd> is)" (*<*)by(fastforce simp add:before_def at_def prefix_def drop_Suc drop_tl)(*>*) (*<*) declare drop_drop[simp del] (*>*) lemma [simp]: "P,C,M,pc \<rhd> (is\<^sub>1 @ is\<^sub>2) = (P,C,M,pc \<rhd> is\<^sub>1 \<and> P,C,M,pc + size is\<^sub>1 \<rhd> is\<^sub>2)" (*<*) by(subst add.commute) (fastforce simp add:before_def prefix_def drop_drop[symmetric]) (*>*) (*<*) declare drop_drop[simp] (*>*) lemma [simp]: "P,C,M,pc \<triangleright> i \<Longrightarrow> instrs_of P C M ! pc = i" (*<*)by(clarsimp simp add:at_def strict_prefix_def nth_via_drop)(*>*) lemma beforeM: "P \<turnstile> C sees M: Ts\<rightarrow>T = body in D \<Longrightarrow> compP\<^sub>2 P,D,M,0 \<rhd> compE\<^sub>2 body @ [Return]" (*<*) by(drule sees_method_idemp) (simp add:before_def compP\<^sub>2_def compMb\<^sub>2_def) (*>*) text\<open>This lemma executes a single instruction by rewriting:\<close> lemma [simp]: "P,C,M,pc \<triangleright> instr \<Longrightarrow> (P \<turnstile> (None, h, (vs,ls,C,M,pc) # frs) -jvm\<rightarrow> \<sigma>') = ((None, h, (vs,ls,C,M,pc) # frs) = \<sigma>' \<or> (\<exists>\<sigma>. exec(P,(None, h, (vs,ls,C,M,pc) # frs)) = Some \<sigma> \<and> P \<turnstile> \<sigma> -jvm\<rightarrow> \<sigma>'))" (*<*) by(simp only: exec_all_def) (blast intro: converse_rtranclE converse_rtrancl_into_rtrancl) (*>*) subsection\<open>Exception tables\<close> definition pcs :: "ex_table \<Rightarrow> nat set" where "pcs xt \<equiv> \<Union>(f,t,C,h,d) \<in> set xt. {f ..< t}" lemma pcs_subset: shows "\<And>pc d. pcs(compxE\<^sub>2 e pc d) \<subseteq> {pc..<pc+size(compE\<^sub>2 e)}" and "\<And>pc d. pcs(compxEs\<^sub>2 es pc d) \<subseteq> {pc..<pc+size(compEs\<^sub>2 es)}" (*<*) proof(induct e and es rule: compxE\<^sub>2.induct compxEs\<^sub>2.induct) case Cast then show ?case by (fastforce simp:pcs_def) next case BinOp then show ?case by (fastforce simp:pcs_def split:bop.splits) next case LAss then show ?case by (fastforce simp: pcs_def) next case FAcc then show ?case by (fastforce simp: pcs_def) next case FAss then show ?case by (fastforce simp: pcs_def) next case Call then show ?case by (fastforce simp: pcs_def) next case Seq then show ?case by (fastforce simp: pcs_def) next case Cond then show ?case by (fastforce simp: pcs_def) next case While then show ?case by (fastforce simp: pcs_def) next case throw then show ?case by (fastforce simp: pcs_def) next case TryCatch then show ?case by (fastforce simp: pcs_def) next case Cons_exp then show ?case by (fastforce simp: pcs_def) qed (simp_all add:pcs_def) (*>*) lemma [simp]: "pcs [] = {}" (*<*)by(simp add:pcs_def)(*>*) lemma [simp]: "pcs (x#xt) = {fst x ..< fst(snd x)} \<union> pcs xt" (*<*)by(auto simp add: pcs_def)(*>*) lemma [simp]: "pcs(xt\<^sub>1 @ xt\<^sub>2) = pcs xt\<^sub>1 \<union> pcs xt\<^sub>2" (*<*)by(simp add:pcs_def)(*>*) lemma [simp]: "pc < pc\<^sub>0 \<or> pc\<^sub>0+size(compE\<^sub>2 e) \<le> pc \<Longrightarrow> pc \<notin> pcs(compxE\<^sub>2 e pc\<^sub>0 d)" (*<*)using pcs_subset by fastforce(*>*) lemma [simp]: "pc < pc\<^sub>0 \<or> pc\<^sub>0+size(compEs\<^sub>2 es) \<le> pc \<Longrightarrow> pc \<notin> pcs(compxEs\<^sub>2 es pc\<^sub>0 d)" (*<*)using pcs_subset by fastforce(*>*) lemma [simp]: "pc\<^sub>1 + size(compE\<^sub>2 e\<^sub>1) \<le> pc\<^sub>2 \<Longrightarrow> pcs(compxE\<^sub>2 e\<^sub>1 pc\<^sub>1 d\<^sub>1) \<inter> pcs(compxE\<^sub>2 e\<^sub>2 pc\<^sub>2 d\<^sub>2) = {}" (*<*)using pcs_subset by fastforce(*>*) lemma [simp]: "pc\<^sub>1 + size(compE\<^sub>2 e) \<le> pc\<^sub>2 \<Longrightarrow> pcs(compxE\<^sub>2 e pc\<^sub>1 d\<^sub>1) \<inter> pcs(compxEs\<^sub>2 es pc\<^sub>2 d\<^sub>2) = {}" (*<*)using pcs_subset by fastforce(*>*) lemma [simp]: "pc \<notin> pcs xt\<^sub>0 \<Longrightarrow> match_ex_table P C pc (xt\<^sub>0 @ xt\<^sub>1) = match_ex_table P C pc xt\<^sub>1" (*<*)by (induct xt\<^sub>0) (auto simp: matches_ex_entry_def)(*>*) lemma [simp]: "\<lbrakk> x \<in> set xt; pc \<notin> pcs xt \<rbrakk> \<Longrightarrow> \<not> matches_ex_entry P D pc x" (*<*)by(auto simp:matches_ex_entry_def pcs_def)(*>*) lemma [simp]: assumes xe: "xe \<in> set(compxE\<^sub>2 e pc d)" and outside: "pc' < pc \<or> pc+size(compE\<^sub>2 e) \<le> pc'" shows "\<not> matches_ex_entry P C pc' xe" (*<*) proof assume "matches_ex_entry P C pc' xe" with xe have "pc' \<in> pcs(compxE\<^sub>2 e pc d)" by(force simp add:matches_ex_entry_def pcs_def) with outside show False by simp qed (*>*) lemma [simp]: assumes xe: "xe \<in> set(compxEs\<^sub>2 es pc d)" and outside: "pc' < pc \<or> pc+size(compEs\<^sub>2 es) \<le> pc'" shows "\<not> matches_ex_entry P C pc' xe" (*<*) proof assume "matches_ex_entry P C pc' xe" with xe have "pc' \<in> pcs(compxEs\<^sub>2 es pc d)" by(force simp add:matches_ex_entry_def pcs_def) with outside show False by simp qed (*>*) lemma match_ex_table_app[simp]: "\<forall>xte \<in> set xt\<^sub>1. \<not> matches_ex_entry P D pc xte \<Longrightarrow> match_ex_table P D pc (xt\<^sub>1 @ xt) = match_ex_table P D pc xt" (*<*)by(induct xt\<^sub>1) simp_all(*>*) lemma [simp]: "\<forall>x \<in> set xtab. \<not> matches_ex_entry P C pc x \<Longrightarrow> match_ex_table P C pc xtab = None" (*<*)using match_ex_table_app[where ?xt = "[]"] by fastforce(*>*) lemma match_ex_entry: "matches_ex_entry P C pc (start, end, catch_type, handler) = (start \<le> pc \<and> pc < end \<and> P \<turnstile> C \<preceq>\<^sup>* catch_type)" (*<*)by(simp add:matches_ex_entry_def)(*>*) definition caught :: "jvm_prog \<Rightarrow> pc \<Rightarrow> heap \<Rightarrow> addr \<Rightarrow> ex_table \<Rightarrow> bool" where "caught P pc h a xt \<longleftrightarrow> (\<exists>entry \<in> set xt. matches_ex_entry P (cname_of h a) pc entry)" definition beforex :: "jvm_prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> ex_table \<Rightarrow> nat set \<Rightarrow> nat \<Rightarrow> bool" ("(2_,/_,/_ \<rhd>/ _ /'/ _,/_)" [51,0,0,0,0,51] 50) where "P,C,M \<rhd> xt / I,d \<longleftrightarrow> (\<exists>xt\<^sub>0 xt\<^sub>1. ex_table_of P C M = xt\<^sub>0 @ xt @ xt\<^sub>1 \<and> pcs xt\<^sub>0 \<inter> I = {} \<and> pcs xt \<subseteq> I \<and> (\<forall>pc \<in> I. \<forall>C pc' d'. match_ex_table P C pc xt\<^sub>1 = \<lfloor>(pc',d')\<rfloor> \<longrightarrow> d' \<le> d))" definition dummyx :: "jvm_prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> ex_table \<Rightarrow> nat set \<Rightarrow> nat \<Rightarrow> bool" ("(2_,_,_ \<triangleright>/ _ '/_,_)" [51,0,0,0,0,51] 50) where "P,C,M \<triangleright> xt/I,d \<longleftrightarrow> P,C,M \<rhd> xt/I,d" abbreviation "beforex\<^sub>0 P C M d I xt xt\<^sub>0 xt\<^sub>1 \<equiv> ex_table_of P C M = xt\<^sub>0 @ xt @ xt\<^sub>1 \<and> pcs xt\<^sub>0 \<inter> I = {} \<and> pcs xt \<subseteq> I \<and> (\<forall>pc \<in> I. \<forall>C pc' d'. match_ex_table P C pc xt\<^sub>1 = \<lfloor>(pc',d')\<rfloor> \<longrightarrow> d' \<le> d)" lemma beforex_beforex\<^sub>0_eq: "P,C,M \<rhd> xt / I,d \<equiv> \<exists>xt\<^sub>0 xt\<^sub>1. beforex\<^sub>0 P C M d I xt xt\<^sub>0 xt\<^sub>1" using beforex_def by auto lemma beforexD1: "P,C,M \<rhd> xt / I,d \<Longrightarrow> pcs xt \<subseteq> I" (*<*)by(auto simp add:beforex_def)(*>*) lemma beforex_mono: "\<lbrakk> P,C,M \<rhd> xt/I,d'; d' \<le> d \<rbrakk> \<Longrightarrow> P,C,M \<rhd> xt/I,d" (*<*)by(fastforce simp:beforex_def)(*>*) lemma [simp]: "P,C,M \<rhd> xt/I,d \<Longrightarrow> P,C,M \<rhd> xt/I,Suc d" (*<*)by(fastforce intro:beforex_mono)(*>*) lemma beforex_append[simp]: "pcs xt\<^sub>1 \<inter> pcs xt\<^sub>2 = {} \<Longrightarrow> P,C,M \<rhd> xt\<^sub>1 @ xt\<^sub>2/I,d = (P,C,M \<rhd> xt\<^sub>1/I-pcs xt\<^sub>2,d \<and> P,C,M \<rhd> xt\<^sub>2/I-pcs xt\<^sub>1,d \<and> P,C,M \<triangleright> xt\<^sub>1@xt\<^sub>2/I,d)" (*<*)(is "?Q \<Longrightarrow> ?P = (?P1 \<and> ?P2 \<and> ?P3)" is "?Q \<Longrightarrow> ?P = ?P123") proof - assume pcs: ?Q show ?thesis proof(rule iffI) assume "?P123" then show ?P by(simp add:dummyx_def) next assume hyp: ?P let ?xt = "xt\<^sub>1 @ xt\<^sub>2" let ?beforex = "beforex\<^sub>0 P C M d" obtain xt\<^sub>0 xt\<^sub>1' where beforex: "?beforex I ?xt xt\<^sub>0 xt\<^sub>1'" using hyp by(clarsimp simp: beforex_def) have "\<exists>xt\<^sub>0 xt\<^sub>1'. ?beforex (I - pcs xt\<^sub>2) xt\<^sub>1 xt\<^sub>0 xt\<^sub>1'" \<comment> \<open>?P1\<close> using pcs beforex by(rule_tac x=xt\<^sub>0 in exI) auto moreover have "\<exists>xt\<^sub>0 xt\<^sub>1'. ?beforex (I - pcs xt\<^sub>1) xt\<^sub>2 xt\<^sub>0 xt\<^sub>1'" \<comment> \<open>?P2\<close> using pcs beforex by(rule_tac x="xt\<^sub>0@xt\<^sub>1" in exI) auto moreover have ?P3 using hyp by(simp add: dummyx_def) ultimately show ?P123 by (simp add: beforex_def) qed qed (*>*) lemma beforex_appendD1: assumes bx: "P,C,M \<rhd> xt\<^sub>1 @ xt\<^sub>2 @ [(f,t,D,h,d)] / I,d" and pcs: "pcs xt\<^sub>1 \<subseteq> J" and JI: "J \<subseteq> I" and Jpcs: "J \<inter> pcs xt\<^sub>2 = {}" shows "P,C,M \<rhd> xt\<^sub>1 / J,d" (*<*) proof - let ?beforex = "beforex\<^sub>0 P C M d" obtain xt\<^sub>0 xt\<^sub>1' where bx': "?beforex I (xt\<^sub>1 @ xt\<^sub>2 @ [(f,t,D,h,d)]) xt\<^sub>0 xt\<^sub>1'" using bx by(clarsimp simp:beforex_def) let ?xt0 = xt\<^sub>0 and ?xt1 = "xt\<^sub>2 @ (f, t, D, h, d) # xt\<^sub>1'" have "pcs xt\<^sub>0 \<inter> J = {}" using bx' JI by blast moreover { fix pc C pc' d' assume pcJ: "pc\<in>J" then have "pc \<notin> pcs xt\<^sub>2" using bx' Jpcs by blast then have "match_ex_table P C pc (xt\<^sub>2 @ (f, t, D, h, d) # xt\<^sub>1') = \<lfloor>(pc', d')\<rfloor> \<longrightarrow> d' \<le> d" using bx' JI pcJ by (auto split:if_split_asm) } ultimately have "?beforex J xt\<^sub>1 ?xt0 ?xt1" using bx' pcs by simp then show ?thesis using beforex_def by blast qed (*>*) lemma beforex_appendD2: assumes bx: "P,C,M \<rhd> xt\<^sub>1 @ xt\<^sub>2 @ [(f,t,D,h,d)] / I,d" and pcs: "pcs xt\<^sub>2 \<subseteq> J" and JI: "J \<subseteq> I" and Jpcs: "J \<inter> pcs xt\<^sub>1 = {}" shows "P,C,M \<rhd> xt\<^sub>2 / J,d" (*<*) proof - let ?beforex = "beforex\<^sub>0 P C M d" obtain xt\<^sub>0 xt\<^sub>1' where bx': "?beforex I (xt\<^sub>1 @ xt\<^sub>2 @ [(f,t,D,h,d)]) xt\<^sub>0 xt\<^sub>1'" using bx by(clarsimp simp:beforex_def) then have "\<exists>xt\<^sub>1''. beforex\<^sub>0 P C M d J xt\<^sub>2 (xt\<^sub>0 @ xt\<^sub>1) xt\<^sub>1''" using assms by fastforce then show ?thesis using beforex_def by blast qed (*>*) lemma beforexM: "P \<turnstile> C sees M: Ts\<rightarrow>T = body in D \<Longrightarrow> compP\<^sub>2 P,D,M \<rhd> compxE\<^sub>2 body 0 0/{..<size(compE\<^sub>2 body)},0" (*<*) proof - assume cM: "P \<turnstile> C sees M: Ts\<rightarrow>T = body in D" let ?xt0 = "[]" have "\<exists>xt1. beforex\<^sub>0 (compP\<^sub>2 P) D M 0 ({..<size(compE\<^sub>2 body)}) (compxE\<^sub>2 body 0 0) ?xt0 xt1" using sees_method_compP[where f = compMb\<^sub>2, OF sees_method_idemp[OF cM]] pcs_subset by(fastforce simp add: compP\<^sub>2_def compMb\<^sub>2_def) then show ?thesis using beforex_def by blast qed (*>*) lemma match_ex_table_SomeD2: assumes met: "match_ex_table P D pc (ex_table_of P C M) = \<lfloor>(pc',d')\<rfloor>" and bx: "P,C,M \<rhd> xt/I,d" and nmet: "\<forall>x \<in> set xt. \<not> matches_ex_entry P D pc x" and pcI: "pc \<in> I" shows "d' \<le> d" (*<*) proof - obtain xt\<^sub>0 xt\<^sub>1 where bx': "beforex\<^sub>0 P C M d I xt xt\<^sub>0 xt\<^sub>1" using bx by(clarsimp simp:beforex_def) then have "pc \<notin> pcs xt\<^sub>0" using pcI by blast then show ?thesis using bx' met nmet pcI by simp qed (*>*) lemma match_ex_table_SomeD1: "\<lbrakk> match_ex_table P D pc (ex_table_of P C M) = \<lfloor>(pc',d')\<rfloor>; P,C,M \<rhd> xt / I,d; pc \<in> I; pc \<notin> pcs xt \<rbrakk> \<Longrightarrow> d' \<le> d" (*<*)by(auto elim: match_ex_table_SomeD2)(*>*) subsection\<open>The correctness proof\<close> (*<*) declare nat_add_distrib[simp] caught_def[simp] declare fun_upd_apply[simp del] (*>*) definition handle :: "jvm_prog \<Rightarrow> cname \<Rightarrow> mname \<Rightarrow> addr \<Rightarrow> heap \<Rightarrow> val list \<Rightarrow> val list \<Rightarrow> nat \<Rightarrow> frame list \<Rightarrow> jvm_state" where "handle P C M a h vs ls pc frs = find_handler P a h ((vs,ls,C,M,pc) # frs)" lemma handle_Cons: "\<lbrakk> P,C,M \<rhd> xt/I,d; d \<le> size vs; pc \<in> I; \<forall>x \<in> set xt. \<not> matches_ex_entry P (cname_of h xa) pc x \<rbrakk> \<Longrightarrow> handle P C M xa h (v # vs) ls pc frs = handle P C M xa h vs ls pc frs" (*<*)by(auto simp:handle_def Suc_diff_le dest: match_ex_table_SomeD2)(*>*) lemma handle_append: assumes bx: "P,C,M \<rhd> xt/I,d" and d: "d \<le> size vs" and pcI: "pc \<in> I" and pc_not: "pc \<notin> pcs xt" shows "handle P C M xa h (ws @ vs) ls pc frs = handle P C M xa h vs ls pc frs" (*<*) proof - { fix pc' d' assume "match_ex_table P (cname_of h xa) pc (ex_table_of P C M) = \<lfloor>(pc', d')\<rfloor>" then have "length ws \<le> length ws + length vs - d'" using assms by(fastforce dest:match_ex_table_SomeD2 split:nat_diff_split) } then show ?thesis by(simp add: handle_def) qed (*>*) lemma aux_isin[simp]: "\<lbrakk> B \<subseteq> A; a \<in> B \<rbrakk> \<Longrightarrow> a \<in> A" (*<*)by blast(*>*) lemma fixes P\<^sub>1 defines [simp]: "P \<equiv> compP\<^sub>2 P\<^sub>1" shows Jcc: "P\<^sub>1 \<turnstile>\<^sub>1 \<langle>e,(h\<^sub>0,ls\<^sub>0)\<rangle> \<Rightarrow> \<langle>ef,(h\<^sub>1,ls\<^sub>1)\<rangle> \<Longrightarrow> (\<And>C M pc v xa vs frs I. \<lbrakk> P,C,M,pc \<rhd> compE\<^sub>2 e; P,C,M \<rhd> compxE\<^sub>2 e pc (size vs)/I,size vs; {pc..<pc+size(compE\<^sub>2 e)} \<subseteq> I \<rbrakk> \<Longrightarrow> (ef = Val v \<longrightarrow> P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(v#vs,ls\<^sub>1,C,M,pc+size(compE\<^sub>2 e))#frs)) \<and> (ef = Throw xa \<longrightarrow> (\<exists>pc\<^sub>1. pc \<le> pc\<^sub>1 \<and> pc\<^sub>1 < pc + size(compE\<^sub>2 e) \<and> \<not> caught P pc\<^sub>1 h\<^sub>1 xa (compxE\<^sub>2 e pc (size vs)) \<and> P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> handle P C M xa h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs)))" (*<*) (is "_ \<Longrightarrow> (\<And>C M pc v xa vs frs I. PROP ?P e h\<^sub>0 ls\<^sub>0 ef h\<^sub>1 ls\<^sub>1 C M pc v xa vs frs I)") (*>*) and "P\<^sub>1 \<turnstile>\<^sub>1 \<langle>es,(h\<^sub>0,ls\<^sub>0)\<rangle> [\<Rightarrow>] \<langle>fs,(h\<^sub>1,ls\<^sub>1)\<rangle> \<Longrightarrow> (\<And>C M pc ws xa es' vs frs I. \<lbrakk> P,C,M,pc \<rhd> compEs\<^sub>2 es; P,C,M \<rhd> compxEs\<^sub>2 es pc (size vs)/I,size vs; {pc..<pc+size(compEs\<^sub>2 es)} \<subseteq> I \<rbrakk> \<Longrightarrow> (fs = map Val ws \<longrightarrow> P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(rev ws @ vs,ls\<^sub>1,C,M,pc+size(compEs\<^sub>2 es))#frs)) \<and> (fs = map Val ws @ Throw xa # es' \<longrightarrow> (\<exists>pc\<^sub>1. pc \<le> pc\<^sub>1 \<and> pc\<^sub>1 < pc + size(compEs\<^sub>2 es) \<and> \<not> caught P pc\<^sub>1 h\<^sub>1 xa (compxEs\<^sub>2 es pc (size vs)) \<and> P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> handle P C M xa h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs)))" (*<*) (is "_ \<Longrightarrow> (\<And>C M pc ws xa es' vs frs I. PROP ?Ps es h\<^sub>0 ls\<^sub>0 fs h\<^sub>1 ls\<^sub>1 C M pc ws xa es' vs frs I)") proof (induct rule:eval\<^sub>1_evals\<^sub>1_inducts) case New\<^sub>1 thus ?case by (clarsimp simp add:blank_def fun_eq_iff) next case NewFail\<^sub>1 thus ?case by(auto simp: handle_def pcs_def) next case (Cast\<^sub>1 e h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 D fs C') let ?pc = "pc + length(compE\<^sub>2 e)" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Addr a#vs,ls\<^sub>1,C,M,?pc)#frs)" using Cast\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(Addr a#vs,ls\<^sub>1,C,M,?pc+1)#frs)" using Cast\<^sub>1 by (auto simp add:cast_ok_def) finally show ?case by auto next case (CastNull\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 C') let ?pc = "pc + length(compE\<^sub>2 e)" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Null#vs,ls\<^sub>1,C,M,?pc)#frs)" using CastNull\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(Null#vs,ls\<^sub>1,C,M,?pc+1)#frs)" using CastNull\<^sub>1 by (auto simp add:cast_ok_def) finally show ?case by auto next case (CastFail\<^sub>1 e h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 D fs C') let ?pc = "pc + length(compE\<^sub>2 e)" let ?xa = "addr_of_sys_xcpt ClassCast" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Addr a#vs,ls\<^sub>1,C,M,?pc)#frs)" using CastFail\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M ?xa h\<^sub>1 (Addr a#vs) ls\<^sub>1 ?pc frs" using CastFail\<^sub>1 by (auto simp add:handle_def cast_ok_def) also have "handle P C M ?xa h\<^sub>1 (Addr a#vs) ls\<^sub>1 ?pc frs = handle P C M ?xa h\<^sub>1 vs ls\<^sub>1 ?pc frs" using CastFail\<^sub>1.prems by(auto simp:handle_Cons) finally have exec: "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> \<dots>". show ?case (is "?N \<and> (?eq \<longrightarrow> (\<exists>pc\<^sub>1. ?H pc\<^sub>1))") proof show ?N by simp next have "?eq \<longrightarrow> ?H ?pc" using exec by auto thus "?eq \<longrightarrow> (\<exists>pc\<^sub>1. ?H pc\<^sub>1)" by blast qed next case CastThrow\<^sub>1 thus ?case by fastforce next case Val\<^sub>1 thus ?case by simp next case Var\<^sub>1 thus ?case by auto next case (BinOp\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 v\<^sub>1 h\<^sub>1 ls\<^sub>1 e\<^sub>2 v\<^sub>2 h\<^sub>2 ls\<^sub>2 bop w) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compE\<^sub>2 e\<^sub>2)" have IH\<^sub>2: "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 (Val v\<^sub>2) h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 v\<^sub>2 xa (v\<^sub>1#vs) frs (I - pcs(compxE\<^sub>2 e\<^sub>1 pc (size vs)))" by fact have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(v\<^sub>1#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using BinOp\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(v\<^sub>2#v\<^sub>1#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using BinOp\<^sub>1.prems IH\<^sub>2 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(w#vs,ls\<^sub>2,C,M,?pc\<^sub>2+1)#frs)" using BinOp\<^sub>1 by(cases bop) auto finally show ?case by (auto split: bop.splits simp:add.assoc) next case BinOpThrow\<^sub>1\<^sub>1 thus ?case by(fastforce) next case (BinOpThrow\<^sub>2\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 v\<^sub>1 h\<^sub>1 ls\<^sub>1 e\<^sub>2 e h\<^sub>2 ls\<^sub>2 bop) let ?pc = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(v\<^sub>1#vs,ls\<^sub>1,C,M,?pc)#frs)" have 1: "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> ?\<sigma>\<^sub>1" using BinOpThrow\<^sub>2\<^sub>1 by fastforce show ?case (is "?N \<and> (?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2))") proof show ?N by simp next { assume ?eq moreover have "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 (throw e) h\<^sub>2 ls\<^sub>2 C M ?pc v xa (v\<^sub>1#vs) frs (I - pcs(compxE\<^sub>2 e\<^sub>1 pc (size vs)))" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "?pc \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc + size(compE\<^sub>2 e\<^sub>2) \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>2 ?pc (size vs + 1))" and 2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 (v\<^sub>1#vs) ls\<^sub>2 pc\<^sub>2 frs" using BinOpThrow\<^sub>2\<^sub>1.prems by fastforce have 3: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using 2 BinOpThrow\<^sub>2\<^sub>1.prems pc\<^sub>2 by(auto simp:handle_Cons) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 3] by auto hence "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover } thus "?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)" by iprover qed next case (FAcc\<^sub>1 e h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 C fs F D w) let ?pc = "pc + length(compE\<^sub>2 e)" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Addr a#vs,ls\<^sub>1,C,M,?pc)#frs)" using FAcc\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(w#vs,ls\<^sub>1,C,M,?pc+1)#frs)" using FAcc\<^sub>1 by auto finally show ?case by auto next case (FAccNull\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 F D) let ?pc = "pc + length(compE\<^sub>2 e)" let ?xa = "addr_of_sys_xcpt NullPointer" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Null#vs,ls\<^sub>1,C,M,?pc)#frs)" using FAccNull\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M ?xa h\<^sub>1 (Null#vs) ls\<^sub>1 ?pc frs" using FAccNull\<^sub>1.prems by(fastforce simp:split_beta handle_def simp del: split_paired_Ex) also have "handle P C M ?xa h\<^sub>1 (Null#vs) ls\<^sub>1 ?pc frs = handle P C M ?xa h\<^sub>1 vs ls\<^sub>1 ?pc frs" using FAccNull\<^sub>1.prems by(auto simp add:handle_Cons) finally show ?case by (auto intro: exI[where x = ?pc]) next case FAccThrow\<^sub>1 thus ?case by fastforce next case (LAss\<^sub>1 e h\<^sub>0 ls\<^sub>0 w h\<^sub>1 ls\<^sub>1 i ls\<^sub>2) let ?pc = "pc + length(compE\<^sub>2 e)" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(w#vs,ls\<^sub>1,C,M,?pc)#frs)" using LAss\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(Unit#vs,ls\<^sub>2,C,M,?pc+2)#frs)" using LAss\<^sub>1 by auto finally show ?case using LAss\<^sub>1 by auto next case LAssThrow\<^sub>1 thus ?case by fastforce next case (FAss\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 e\<^sub>2 w h\<^sub>2 ls\<^sub>2 C fs fs' F D h\<^sub>2') let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compE\<^sub>2 e\<^sub>2)" have IH\<^sub>2: "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 (Val w) h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 w xa (Addr a#vs) frs (I - pcs(compxE\<^sub>2 e\<^sub>1 pc (size vs)))" by fact have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Addr a#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using FAss\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(w#Addr a#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using FAss\<^sub>1.prems IH\<^sub>2 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2',(Unit#vs,ls\<^sub>2,C,M,?pc\<^sub>2+2)#frs)" using FAss\<^sub>1 by auto finally show ?case using FAss\<^sub>1 by (auto simp:add.assoc) next case (FAssNull\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 e\<^sub>2 w h\<^sub>2 ls\<^sub>2 F D) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compE\<^sub>2 e\<^sub>2)" let ?xa = "addr_of_sys_xcpt NullPointer" have IH\<^sub>2: "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 (Val w) h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 w xa (Null#vs) frs (I - pcs(compxE\<^sub>2 e\<^sub>1 pc (size vs)))" by fact have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Null#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using FAssNull\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(w#Null#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using FAssNull\<^sub>1.prems IH\<^sub>2 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M ?xa h\<^sub>2 (w#Null#vs) ls\<^sub>2 ?pc\<^sub>2 frs" using FAssNull\<^sub>1.prems by(fastforce simp:split_beta handle_def simp del: split_paired_Ex) also have "handle P C M ?xa h\<^sub>2 (w#Null#vs) ls\<^sub>2 ?pc\<^sub>2 frs = handle P C M ?xa h\<^sub>2 vs ls\<^sub>2 ?pc\<^sub>2 frs" using FAssNull\<^sub>1.prems by(auto simp add:handle_Cons) finally show ?case by (auto intro: exI[where x = ?pc\<^sub>2]) next case (FAssThrow\<^sub>2\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 w h\<^sub>1 ls\<^sub>1 e\<^sub>2 e' h\<^sub>2 ls\<^sub>2 F D) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(w#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" have 1: "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> ?\<sigma>\<^sub>1" using FAssThrow\<^sub>2\<^sub>1 by fastforce show ?case (is "?N \<and> (?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2))") proof show ?N by simp next { assume ?eq moreover have "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 (throw e') h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 v xa (w#vs) frs (I - pcs (compxE\<^sub>2 e\<^sub>1 pc (length vs)))" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>1 + size(compE\<^sub>2 e\<^sub>2) \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>2 ?pc\<^sub>1 (size vs + 1))" and 2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 (w#vs) ls\<^sub>2 pc\<^sub>2 frs" using FAssThrow\<^sub>2\<^sub>1.prems by fastforce have 3: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using 2 FAssThrow\<^sub>2\<^sub>1.prems pc\<^sub>2 by(auto simp:handle_Cons) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 3] by auto hence "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover } thus "?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)" by iprover qed next case FAssThrow\<^sub>1\<^sub>1 thus ?case by fastforce next case (Call\<^sub>1 e h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 es pvs h\<^sub>2 ls\<^sub>2 Ca fs M' Ts T body D ls\<^sub>2' f h\<^sub>3 ls\<^sub>3) have "P\<^sub>1 \<turnstile>\<^sub>1 \<langle>es,(h\<^sub>1, ls\<^sub>1)\<rangle> [\<Rightarrow>] \<langle>map Val pvs,(h\<^sub>2, ls\<^sub>2)\<rangle>" by fact hence [simp]: "length es = length pvs" by(auto dest:evals\<^sub>1_preserves_elen) let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs, ls\<^sub>0, C,M,pc)#frs)" let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(Addr a # vs, ls\<^sub>1, C,M,?pc\<^sub>1)#frs)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compEs\<^sub>2 es)" let ?frs\<^sub>2 = "(rev pvs @ Addr a # vs, ls\<^sub>2, C,M,?pc\<^sub>2)#frs" let ?\<sigma>\<^sub>2 = "(None,h\<^sub>2,?frs\<^sub>2)" let ?frs\<^sub>2' = "([], ls\<^sub>2', D,M',0) # ?frs\<^sub>2" let ?\<sigma>\<^sub>2' = "(None, h\<^sub>2, ?frs\<^sub>2')" have IH_es: "PROP ?Ps es h\<^sub>1 ls\<^sub>1 (map Val pvs) h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 pvs xa (map Val pvs) (Addr a # vs) frs (I - pcs(compxE\<^sub>2 e pc (size vs)))" by fact have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1" using Call\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>2" using IH_es Call\<^sub>1.prems by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>2'" using Call\<^sub>1 by(auto simp add: nth_append compMb\<^sub>2_def) finally have 1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>2'". have "P\<^sub>1 \<turnstile> Ca sees M': Ts\<rightarrow>T = body in D" by fact then have M'_in_D: "P\<^sub>1 \<turnstile> D sees M': Ts\<rightarrow>T = body in D" by(rule sees_method_idemp) hence M'_code: "compP\<^sub>2 P\<^sub>1,D,M',0 \<rhd> compE\<^sub>2 body @ [Return]" and M'_xtab: "compP\<^sub>2 P\<^sub>1,D,M' \<rhd> compxE\<^sub>2 body 0 0/{..<size(compE\<^sub>2 body)},0" by(rule beforeM, rule beforexM) have IH_body: "PROP ?P body h\<^sub>2 ls\<^sub>2' f h\<^sub>3 ls\<^sub>3 D M' 0 v xa [] ?frs\<^sub>2 ({..<size(compE\<^sub>2 body)})" by fact show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note 1 also have "P \<turnstile> ?\<sigma>\<^sub>2' -jvm\<rightarrow> (None,h\<^sub>3,([v],ls\<^sub>3,D,M',size(compE\<^sub>2 body))#?frs\<^sub>2)" using val IH_body Call\<^sub>1.prems M'_code M'_xtab by (fastforce simp del:split_paired_Ex) also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None, h\<^sub>3, (v # vs, ls\<^sub>2, C,M,?pc\<^sub>2+1)#frs)" using Call\<^sub>1 M'_code M'_in_D by(auto simp: nth_append compMb\<^sub>2_def) finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw with IH_body obtain pc\<^sub>2 where pc\<^sub>2: "0 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < size(compE\<^sub>2 body) \<and> \<not> caught P pc\<^sub>2 h\<^sub>3 xa (compxE\<^sub>2 body 0 0)" and 2: "P \<turnstile> ?\<sigma>\<^sub>2' -jvm\<rightarrow> handle P D M' xa h\<^sub>3 [] ls\<^sub>3 pc\<^sub>2 ?frs\<^sub>2" using Call\<^sub>1.prems M'_code M'_xtab by (fastforce simp del:split_paired_Ex) have "handle P D M' xa h\<^sub>3 [] ls\<^sub>3 pc\<^sub>2 ?frs\<^sub>2 = handle P C M xa h\<^sub>3 (rev pvs @ Addr a # vs) ls\<^sub>2 ?pc\<^sub>2 frs" using pc\<^sub>2 M'_in_D by(auto simp add:handle_def) also have "\<dots> = handle P C M xa h\<^sub>3 vs ls\<^sub>2 ?pc\<^sub>2 frs" using Call\<^sub>1.prems by(auto simp add:handle_append handle_Cons) finally have "?H ?pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case (CallParamsThrow\<^sub>1 e h\<^sub>0 ls\<^sub>0 w h\<^sub>1 ls\<^sub>1 es es' h\<^sub>2 ls\<^sub>2 pvs ex es'' M') let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs, ls\<^sub>0, C,M,pc)#frs)" let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(w # vs, ls\<^sub>1, C,M,?pc\<^sub>1)#frs)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compEs\<^sub>2 es)" have 1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1" using CallParamsThrow\<^sub>1 by fastforce show ?case (is "?N \<and> (?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2))") proof show ?N by simp next { assume ?eq moreover have "PROP ?Ps es h\<^sub>1 ls\<^sub>1 es' h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 pvs xa es'' (w#vs) frs (I - pcs (compxE\<^sub>2 e pc (length vs)))" by fact ultimately have "\<exists>pc\<^sub>2. (?pc\<^sub>1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>1 + size(compEs\<^sub>2 es) \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxEs\<^sub>2 es ?pc\<^sub>1 (size vs + 1))) \<and> P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 (w#vs) ls\<^sub>2 pc\<^sub>2 frs" (is "\<exists>pc\<^sub>2. ?PC pc\<^sub>2 \<and> ?Exec pc\<^sub>2") using CallParamsThrow\<^sub>1 by force then obtain pc\<^sub>2 where pc\<^sub>2: "?PC pc\<^sub>2" and 2: "?Exec pc\<^sub>2" by iprover have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 2] CallParamsThrow\<^sub>1 by(auto simp:handle_Cons) hence "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover } thus "?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)" by iprover qed next case (CallNull\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 es pvs h\<^sub>2 ls\<^sub>2 M') have "P\<^sub>1 \<turnstile>\<^sub>1 \<langle>es,(h\<^sub>1, ls\<^sub>1)\<rangle> [\<Rightarrow>] \<langle>map Val pvs,(h\<^sub>2, ls\<^sub>2)\<rangle>" by fact hence [simp]: "length es = length pvs" by(auto dest:evals\<^sub>1_preserves_elen) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compEs\<^sub>2 es)" let ?xa = "addr_of_sys_xcpt NullPointer" have IH_es: "PROP ?Ps es h\<^sub>1 ls\<^sub>1 (map Val pvs) h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 pvs xa (map Val pvs) (Null#vs) frs (I - pcs(compxE\<^sub>2 e pc (size vs)))" by fact have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Null#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using CallNull\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(rev pvs@Null#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using CallNull\<^sub>1 IH_es by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M ?xa h\<^sub>2 (rev pvs@Null#vs) ls\<^sub>2 ?pc\<^sub>2 frs" using CallNull\<^sub>1.prems by(auto simp:split_beta handle_def nth_append simp del: split_paired_Ex) also have "handle P C M ?xa h\<^sub>2 (rev pvs@Null#vs) ls\<^sub>2 ?pc\<^sub>2 frs = handle P C M ?xa h\<^sub>2 vs ls\<^sub>2 ?pc\<^sub>2 frs" using CallNull\<^sub>1.prems by(auto simp:handle_Cons handle_append) finally show ?case by (auto intro: exI[where x = ?pc\<^sub>2]) next case CallObjThrow\<^sub>1 thus ?case by fastforce next case Block\<^sub>1 thus ?case by auto next case (Seq\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 w h\<^sub>1 ls\<^sub>1 e\<^sub>2 e\<^sub>2' h\<^sub>2 ls\<^sub>2) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc\<^sub>1+1)#frs)" have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,(w#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using Seq\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using Seq\<^sub>1 by auto finally have eval\<^sub>1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1". let ?pc\<^sub>2 = "?pc\<^sub>1 + 1 + length(compE\<^sub>2 e\<^sub>2)" have IH\<^sub>2: "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 e\<^sub>2' h\<^sub>2 ls\<^sub>2 C M (?pc\<^sub>1+1) v xa vs frs (I - pcs(compxE\<^sub>2 e\<^sub>1 pc (size vs)))" by fact show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note eval\<^sub>1 also have "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> (None,h\<^sub>2,(v#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using val Seq\<^sub>1.prems IH\<^sub>2 by fastforce finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw then obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1+1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>2 \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>2 (?pc\<^sub>1+1) (size vs))" and eval\<^sub>2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using IH\<^sub>2 Seq\<^sub>1.prems by fastforce have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF eval\<^sub>1 eval\<^sub>2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case SeqThrow\<^sub>1 thus ?case by fastforce next case (CondT\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 e\<^sub>1 e' h\<^sub>2 ls\<^sub>2 e\<^sub>2) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc\<^sub>1+1)#frs)" have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,(Bool(True)#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using CondT\<^sub>1 by (fastforce simp add: Int_Un_distrib) also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using CondT\<^sub>1 by auto finally have eval\<^sub>1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1". let ?pc\<^sub>1' = "?pc\<^sub>1 + 1 + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>2' = "?pc\<^sub>1' + 1 + length(compE\<^sub>2 e\<^sub>2)" show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note eval\<^sub>1 also have "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> (None,h\<^sub>2,(v#vs,ls\<^sub>2,C,M,?pc\<^sub>1')#frs)" using val CondT\<^sub>1 by(fastforce simp:Int_Un_distrib) also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(v#vs,ls\<^sub>2,C,M,?pc\<^sub>2')#frs)" using CondT\<^sub>1 by(auto simp:add.assoc) finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof let ?d = "size vs" let ?I = "I - pcs(compxE\<^sub>2 e pc ?d) - pcs(compxE\<^sub>2 e\<^sub>2 (?pc\<^sub>1'+1) ?d)" assume throw: ?throw moreover have "PROP ?P e\<^sub>1 h\<^sub>1 ls\<^sub>1 e' h\<^sub>2 ls\<^sub>2 C M (?pc\<^sub>1+1) v xa vs frs ?I" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1+1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>1' \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>1 (?pc\<^sub>1+1) (size vs))" and eval\<^sub>2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using CondT\<^sub>1.prems by (fastforce simp:Int_Un_distrib) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF eval\<^sub>1 eval\<^sub>2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case (CondF\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 e\<^sub>2 e' h\<^sub>2 ls\<^sub>2 e\<^sub>1) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?pc\<^sub>2 = "?pc\<^sub>1 + 1 + length(compE\<^sub>2 e\<^sub>1)+ 1" let ?pc\<^sub>2' = "?pc\<^sub>2 + length(compE\<^sub>2 e\<^sub>2)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc\<^sub>2)#frs)" have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,(Bool(False)#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using CondF\<^sub>1 by (fastforce simp add: Int_Un_distrib) also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using CondF\<^sub>1 by auto finally have eval\<^sub>1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1". show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note eval\<^sub>1 also have "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> (None,h\<^sub>2,(v#vs,ls\<^sub>2,C,M,?pc\<^sub>2')#frs)" using val CondF\<^sub>1 by(fastforce simp:Int_Un_distrib) finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof let ?d = "size vs" let ?I = "I - pcs(compxE\<^sub>2 e pc ?d) - pcs(compxE\<^sub>2 e\<^sub>1 (?pc\<^sub>1+1) ?d)" assume throw: ?throw moreover have "PROP ?P e\<^sub>2 h\<^sub>1 ls\<^sub>1 e' h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>2 v xa vs frs ?I" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>2 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>2' \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>2 ?pc\<^sub>2 ?d)" and eval\<^sub>2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using CondF\<^sub>1.prems by(fastforce simp:Int_Un_distrib) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF eval\<^sub>1 eval\<^sub>2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case (CondThrow\<^sub>1 e h\<^sub>0 ls\<^sub>0 f h\<^sub>1 ls\<^sub>1 e\<^sub>1 e\<^sub>2) let ?d = "size vs" let ?xt\<^sub>1 = "compxE\<^sub>2 e\<^sub>1 (pc+size(compE\<^sub>2 e)+1) ?d" let ?xt\<^sub>2 = "compxE\<^sub>2 e\<^sub>2 (pc+size(compE\<^sub>2 e)+size(compE\<^sub>2 e\<^sub>1)+2) ?d" let ?I = "I - (pcs ?xt\<^sub>1 \<union> pcs ?xt\<^sub>2)" have "pcs(compxE\<^sub>2 e pc ?d) \<inter> pcs(?xt\<^sub>1 @ ?xt\<^sub>2) = {}" using CondThrow\<^sub>1.prems by (simp add:Int_Un_distrib) moreover have "PROP ?P e h\<^sub>0 ls\<^sub>0 (throw f) h\<^sub>1 ls\<^sub>1 C M pc v xa vs frs ?I" by fact ultimately show ?case using CondThrow\<^sub>1.prems by fastforce next case (WhileF\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 c) let ?pc = "pc + length(compE\<^sub>2 e)" let ?pc' = "?pc + length(compE\<^sub>2 c) + 3" have "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(Bool False#vs,ls\<^sub>1,C,M,?pc)#frs)" using WhileF\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc')#frs)" using WhileF\<^sub>1 by (auto simp:add.assoc) also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(Unit#vs,ls\<^sub>1,C,M,?pc'+1)#frs)" using WhileF\<^sub>1.prems by (auto simp:eval_nat_numeral) finally show ?case by (simp add:add.assoc eval_nat_numeral) next case (WhileT\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 c v\<^sub>1 h\<^sub>2 ls\<^sub>2 e\<^sub>3 h\<^sub>3 ls\<^sub>3) let ?pc = "pc + length(compE\<^sub>2 e)" let ?pc' = "?pc + length(compE\<^sub>2 c) + 1" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>2 = "(None,h\<^sub>2,(vs,ls\<^sub>2,C,M,pc)#frs)" have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,(Bool True#vs,ls\<^sub>1,C,M,?pc)#frs)" using WhileT\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc+1)#frs)" using WhileT\<^sub>1.prems by auto also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>2,(v\<^sub>1#vs,ls\<^sub>2,C,M,?pc')#frs)" using WhileT\<^sub>1 by(fastforce) also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>2" using WhileT\<^sub>1.prems by auto finally have 1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>2". show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note 1 also have "P \<turnstile> ?\<sigma>\<^sub>2 -jvm\<rightarrow> (None,h\<^sub>3,(v#vs,ls\<^sub>3,C,M,?pc'+3)#frs)" using val WhileT\<^sub>1 by (auto simp add:add.assoc eval_nat_numeral) finally show ?trans by(simp add:add.assoc eval_nat_numeral) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw moreover have "PROP ?P (while (e) c) h\<^sub>2 ls\<^sub>2 e\<^sub>3 h\<^sub>3 ls\<^sub>3 C M pc v xa vs frs I" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "pc \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc'+3 \<and> \<not> caught P pc\<^sub>2 h\<^sub>3 xa (compxE\<^sub>2 (while (e) c) pc (size vs))" and 2: "P \<turnstile> ?\<sigma>\<^sub>2 -jvm\<rightarrow> handle P C M xa h\<^sub>3 vs ls\<^sub>3 pc\<^sub>2 frs" using WhileT\<^sub>1.prems by (auto simp:add.assoc eval_nat_numeral) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case WhileCondThrow\<^sub>1 thus ?case by fastforce next case (WhileBodyThrow\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1 c e' h\<^sub>2 ls\<^sub>2) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(vs,ls\<^sub>1,C,M,?pc\<^sub>1+1)#frs)" have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,(Bool(True)#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using WhileBodyThrow\<^sub>1 by (fastforce simp add: Int_Un_distrib) also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using WhileBodyThrow\<^sub>1 by auto finally have eval\<^sub>1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1". let ?pc\<^sub>1' = "?pc\<^sub>1 + 1 + length(compE\<^sub>2 c)" show ?case (is "?Norm \<and> ?Err") proof show ?Norm by simp next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw moreover have "PROP ?P c h\<^sub>1 ls\<^sub>1 (throw e') h\<^sub>2 ls\<^sub>2 C M (?pc\<^sub>1+1) v xa vs frs (I - pcs (compxE\<^sub>2 e pc (size vs)))" by fact ultimately obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1+1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>1' \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 c (?pc\<^sub>1+1) (size vs))" and eval\<^sub>2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using WhileBodyThrow\<^sub>1.prems by (fastforce simp:Int_Un_distrib) have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF eval\<^sub>1 eval\<^sub>2] by auto thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case (Throw\<^sub>1 e h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1) let ?pc = "pc + size(compE\<^sub>2 e)" show ?case (is "?Norm \<and> ?Err") proof show ?Norm by simp next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>1. ?H pc\<^sub>1)") proof assume ?throw hence "P \<turnstile> (None, h\<^sub>0, (vs, ls\<^sub>0, C, M, pc) # frs) -jvm\<rightarrow> (None, h\<^sub>1, (Addr xa#vs, ls\<^sub>1, C, M, ?pc) # frs)" using Throw\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M xa h\<^sub>1 (Addr xa#vs) ls\<^sub>1 ?pc frs" using Throw\<^sub>1.prems by(auto simp add:handle_def) also have "handle P C M xa h\<^sub>1 (Addr xa#vs) ls\<^sub>1 ?pc frs = handle P C M xa h\<^sub>1 vs ls\<^sub>1 ?pc frs" using Throw\<^sub>1.prems by(auto simp add:handle_Cons) finally have "?H ?pc" by simp thus "\<exists>pc\<^sub>1. ?H pc\<^sub>1" by iprover qed qed next case (ThrowNull\<^sub>1 e h\<^sub>0 ls\<^sub>0 h\<^sub>1 ls\<^sub>1) let ?pc = "pc + size(compE\<^sub>2 e)" let ?xa = "addr_of_sys_xcpt NullPointer" show ?case (is "?Norm \<and> ?Err") proof show ?Norm by simp next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>1. ?H pc\<^sub>1)") proof assume throw: ?throw have "P \<turnstile> (None, h\<^sub>0, (vs, ls\<^sub>0, C, M, pc) # frs) -jvm\<rightarrow> (None, h\<^sub>1, (Null#vs, ls\<^sub>1, C, M, ?pc) # frs)" using ThrowNull\<^sub>1 by fastforce also have "P \<turnstile> \<dots> -jvm\<rightarrow> handle P C M ?xa h\<^sub>1 (Null#vs) ls\<^sub>1 ?pc frs" using ThrowNull\<^sub>1.prems by(auto simp add:handle_def) also have "handle P C M ?xa h\<^sub>1 (Null#vs) ls\<^sub>1 ?pc frs = handle P C M ?xa h\<^sub>1 vs ls\<^sub>1 ?pc frs" using ThrowNull\<^sub>1.prems by(auto simp add:handle_Cons) finally have "?H ?pc" using throw by simp thus "\<exists>pc\<^sub>1. ?H pc\<^sub>1" by iprover qed qed next case ThrowThrow\<^sub>1 thus ?case by fastforce next case (Try\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 v\<^sub>1 h\<^sub>1 ls\<^sub>1 Ci i e\<^sub>2) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>1' = "?pc\<^sub>1 + 2 + length(compE\<^sub>2 e\<^sub>2)" have "P,C,M \<rhd> compxE\<^sub>2 (try e\<^sub>1 catch(Ci i) e\<^sub>2) pc (size vs) / I,size vs" by fact hence "P,C,M \<rhd> compxE\<^sub>2 e\<^sub>1 pc (size vs) / {pc..<pc + length (compE\<^sub>2 e\<^sub>1)},size vs" using Try\<^sub>1.prems by (fastforce simp:beforex_def split:if_split_asm) hence "P \<turnstile> (None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs) -jvm\<rightarrow> (None,h\<^sub>1,(v\<^sub>1#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" using Try\<^sub>1 by auto also have "P \<turnstile> \<dots> -jvm\<rightarrow> (None,h\<^sub>1,(v\<^sub>1#vs,ls\<^sub>1,C,M,?pc\<^sub>1')#frs)" using Try\<^sub>1.prems by auto finally show ?case by (auto simp:add.assoc) next case (TryCatch\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 D fs Ci i e\<^sub>2 e\<^sub>2' h\<^sub>2 ls\<^sub>2) let ?e = "try e\<^sub>1 catch(Ci i) e\<^sub>2" let ?xt = "compxE\<^sub>2 ?e pc (size vs)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?ls\<^sub>1 = "ls\<^sub>1[i := Addr a]" let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?pc\<^sub>1' = "?pc\<^sub>1 + 2" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(vs,?ls\<^sub>1,C,M, ?pc\<^sub>1') # frs)" have I: "{pc..<pc + length (compE\<^sub>2 (try e\<^sub>1 catch(Ci i) e\<^sub>2))} \<subseteq> I" and beforex: "P,C,M \<rhd> ?xt/I,size vs" by fact+ have "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h\<^sub>1,((Addr a)#vs,ls\<^sub>1,C,M, ?pc\<^sub>1+1) # frs)" proof - have "PROP ?P e\<^sub>1 h\<^sub>0 ls\<^sub>0 (Throw a) h\<^sub>1 ls\<^sub>1 C M pc w a vs frs {pc..<pc + length (compE\<^sub>2 e\<^sub>1)}" by fact moreover have "P,C,M \<rhd> compxE\<^sub>2 e\<^sub>1 pc (size vs)/{pc..<?pc\<^sub>1},size vs" using beforex I pcs_subset by(force elim!: beforex_appendD1) ultimately have "\<exists>pc\<^sub>1. pc \<le> pc\<^sub>1 \<and> pc\<^sub>1 < ?pc\<^sub>1 \<and> \<not> caught P pc\<^sub>1 h\<^sub>1 a (compxE\<^sub>2 e\<^sub>1 pc (size vs)) \<and> P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> handle P C M a h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs" using TryCatch\<^sub>1.prems by auto then obtain pc\<^sub>1 where pc\<^sub>1_in_e\<^sub>1: "pc \<le> pc\<^sub>1" "pc\<^sub>1 < ?pc\<^sub>1" and pc\<^sub>1_not_caught: "\<not> caught P pc\<^sub>1 h\<^sub>1 a (compxE\<^sub>2 e\<^sub>1 pc (size vs))" and 0: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> handle P C M a h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs" by iprover from beforex obtain xt\<^sub>0 xt\<^sub>1 where ex_tab: "ex_table_of P C M = xt\<^sub>0 @ ?xt @ xt\<^sub>1" and disj: "pcs xt\<^sub>0 \<inter> I = {}" by(auto simp:beforex_def) have hp: "h\<^sub>1 a = Some (D, fs)" "P\<^sub>1 \<turnstile> D \<preceq>\<^sup>* Ci" by fact+ have "pc\<^sub>1 \<notin> pcs xt\<^sub>0" using pc\<^sub>1_in_e\<^sub>1 I disj by auto with pc\<^sub>1_in_e\<^sub>1 pc\<^sub>1_not_caught hp show ?thesis using ex_tab 0 by(simp add:handle_def matches_ex_entry_def) qed also have "P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using TryCatch\<^sub>1 by auto finally have 1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1" . let ?pc\<^sub>2 = "?pc\<^sub>1' + length(compE\<^sub>2 e\<^sub>2)" let ?I\<^sub>2 = "{?pc\<^sub>1' ..< ?pc\<^sub>2}" have "P,C,M \<rhd> compxE\<^sub>2 ?e pc (size vs) / I,size vs" by fact hence beforex\<^sub>2: "P,C,M \<rhd> compxE\<^sub>2 e\<^sub>2 ?pc\<^sub>1' (size vs) / ?I\<^sub>2, size vs" using I pcs_subset[of _ ?pc\<^sub>1'] by(auto elim!:beforex_appendD2) have IH\<^sub>2: "PROP ?P e\<^sub>2 h\<^sub>1 ?ls\<^sub>1 e\<^sub>2' h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1' v xa vs frs ?I\<^sub>2" by fact show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note 1 also have "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> (None,h\<^sub>2,(v#vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using val beforex\<^sub>2 IH\<^sub>2 TryCatch\<^sub>1.prems by auto finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw then obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1+2 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>2 \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxE\<^sub>2 e\<^sub>2 ?pc\<^sub>1' (size vs))" and 2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 vs ls\<^sub>2 pc\<^sub>2 frs" using IH\<^sub>2 beforex\<^sub>2 TryCatch\<^sub>1.prems by auto have "?H pc\<^sub>2" using pc\<^sub>2 jvm_trans[OF 1 2] by (simp add:match_ex_entry) (fastforce) thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case (TryThrow\<^sub>1 e\<^sub>1 h\<^sub>0 ls\<^sub>0 a h\<^sub>1 ls\<^sub>1 D fs Ci i e\<^sub>2) let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e\<^sub>1)" let ?e = "try e\<^sub>1 catch(Ci i) e\<^sub>2" let ?xt = "compxE\<^sub>2 ?e pc (size vs)" have I: "{pc..<pc + length (compE\<^sub>2 (try e\<^sub>1 catch(Ci i) e\<^sub>2))} \<subseteq> I" and beforex: "P,C,M \<rhd> ?xt/I,size vs" by fact+ have "PROP ?P e\<^sub>1 h\<^sub>0 ls\<^sub>0 (Throw a) h\<^sub>1 ls\<^sub>1 C M pc w a vs frs {pc..<pc + length (compE\<^sub>2 e\<^sub>1)}" by fact moreover have "P,C,M \<rhd> compxE\<^sub>2 e\<^sub>1 pc (size vs)/{pc..<?pc\<^sub>1},size vs" using beforex I pcs_subset by(force elim!: beforex_appendD1) ultimately have "\<exists>pc\<^sub>1. pc \<le> pc\<^sub>1 \<and> pc\<^sub>1 < ?pc\<^sub>1 \<and> \<not> caught P pc\<^sub>1 h\<^sub>1 a (compxE\<^sub>2 e\<^sub>1 pc (size vs)) \<and> P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> handle P C M a h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs" using TryThrow\<^sub>1.prems by auto then obtain pc\<^sub>1 where pc\<^sub>1_in_e\<^sub>1: "pc \<le> pc\<^sub>1" "pc\<^sub>1 < ?pc\<^sub>1" and pc\<^sub>1_not_caught: "\<not> caught P pc\<^sub>1 h\<^sub>1 a (compxE\<^sub>2 e\<^sub>1 pc (size vs))" and 0: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> handle P C M a h\<^sub>1 vs ls\<^sub>1 pc\<^sub>1 frs" by iprover show ?case (is "?N \<and> (?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2))") proof show ?N by simp next { assume ?eq with TryThrow\<^sub>1 pc\<^sub>1_in_e\<^sub>1 pc\<^sub>1_not_caught 0 have "?H pc\<^sub>1" by (simp add:match_ex_entry) auto hence "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover } thus "?eq \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)" by iprover qed next case Nil\<^sub>1 thus ?case by simp next case (Cons\<^sub>1 e h\<^sub>0 ls\<^sub>0 v h\<^sub>1 ls\<^sub>1 es fs h\<^sub>2 ls\<^sub>2) let ?pc\<^sub>1 = "pc + length(compE\<^sub>2 e)" let ?\<sigma>\<^sub>0 = "(None,h\<^sub>0,(vs,ls\<^sub>0,C,M,pc)#frs)" let ?\<sigma>\<^sub>1 = "(None,h\<^sub>1,(v#vs,ls\<^sub>1,C,M,?pc\<^sub>1)#frs)" have 1: "P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1" using Cons\<^sub>1 by fastforce let ?pc\<^sub>2 = "?pc\<^sub>1 + length(compEs\<^sub>2 es)" have IHs: "PROP ?Ps es h\<^sub>1 ls\<^sub>1 fs h\<^sub>2 ls\<^sub>2 C M ?pc\<^sub>1 (tl ws) xa es' (v#vs) frs (I - pcs (compxE\<^sub>2 e pc (length vs)))" by fact show ?case (is "?Norm \<and> ?Err") proof show ?Norm (is "?val \<longrightarrow> ?trans") proof assume val: ?val note 1 also have "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> (None,h\<^sub>2,(rev(ws) @ vs,ls\<^sub>2,C,M,?pc\<^sub>2)#frs)" using val IHs Cons\<^sub>1.prems by fastforce finally show ?trans by(simp add:add.assoc) qed next show ?Err (is "?throw \<longrightarrow> (\<exists>pc\<^sub>2. ?H pc\<^sub>2)") proof assume throw: ?throw then obtain pc\<^sub>2 where pc\<^sub>2: "?pc\<^sub>1 \<le> pc\<^sub>2 \<and> pc\<^sub>2 < ?pc\<^sub>2 \<and> \<not> caught P pc\<^sub>2 h\<^sub>2 xa (compxEs\<^sub>2 es ?pc\<^sub>1 (size vs + 1))" and 2: "P \<turnstile> ?\<sigma>\<^sub>1 -jvm\<rightarrow> handle P C M xa h\<^sub>2 (v#vs) ls\<^sub>2 pc\<^sub>2 frs" using IHs Cons\<^sub>1.prems by(fastforce simp:Cons_eq_append_conv neq_Nil_conv) have "?H pc\<^sub>2" using Cons\<^sub>1.prems pc\<^sub>2 jvm_trans[OF 1 2] by (auto simp add: handle_Cons) thus "\<exists>pc\<^sub>2. ?H pc\<^sub>2" by iprover qed qed next case ConsThrow\<^sub>1 thus ?case by (fastforce simp:Cons_eq_append_conv) qed (*>*) (*FIXME move! *) lemma atLeast0AtMost[simp]: "{0::nat..n} = {..n}" by auto lemma atLeast0LessThan[simp]: "{0::nat..<n} = {..<n}" by auto fun exception :: "'a exp \<Rightarrow> addr option" where "exception (Throw a) = Some a" | "exception e = None" lemma comp\<^sub>2_correct: assumes "method": "P\<^sub>1 \<turnstile> C sees M:Ts\<rightarrow>T = body in C" and eval: "P\<^sub>1 \<turnstile>\<^sub>1 \<langle>body,(h,ls)\<rangle> \<Rightarrow> \<langle>e',(h',ls')\<rangle>" shows "compP\<^sub>2 P\<^sub>1 \<turnstile> (None,h,[([],ls,C,M,0)]) -jvm\<rightarrow> (exception e',h',[])" (*<*) (is "_ \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> ?\<sigma>\<^sub>1") proof - let ?P = "compP\<^sub>2 P\<^sub>1" have code: "?P,C,M,0 \<rhd> compE\<^sub>2 body" using beforeM[OF "method"] by auto have xtab: "?P,C,M \<rhd> compxE\<^sub>2 body 0 (size[])/{..<size(compE\<^sub>2 body)},size[]" using beforexM[OF "method"] by auto \<comment> \<open>Distinguish if e' is a value or an exception\<close> { fix v assume [simp]: "e' = Val v" have "?P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> (None,h',[([v],ls',C,M,size(compE\<^sub>2 body))])" using Jcc[OF eval code xtab] by auto also have "?P \<turnstile> \<dots> -jvm\<rightarrow> ?\<sigma>\<^sub>1" using beforeM[OF "method"] by auto finally have ?thesis . } moreover { fix a assume [simp]: "e' = Throw a" obtain pc where pc: "0 \<le> pc \<and> pc < size(compE\<^sub>2 body) \<and> \<not> caught ?P pc h' a (compxE\<^sub>2 body 0 0)" and 1: "?P \<turnstile> ?\<sigma>\<^sub>0 -jvm\<rightarrow> handle ?P C M a h' [] ls' pc []" using Jcc[OF eval code xtab] by fastforce from pc have "handle ?P C M a h' [] ls' pc [] = ?\<sigma>\<^sub>1" using xtab "method" by(auto simp:handle_def compMb\<^sub>2_def) with 1 have ?thesis by simp } ultimately show ?thesis using eval\<^sub>1_final[OF eval] by(auto simp:final_def) qed (*>*) end
SUBROUTINE LS_ICEA ( lsfrpt, ipt, iret) C************************************************************************ C* LS_ICEA * C* * C* This subroutine decodes the ship ice accretion group, * C* 6I(s)E(s)E(s)R(s). Ice accretion on ships uses WMO Code Table 1751 * C* and the rate of ice accretion on ships uses WMO Code Table 3551. * C* * C* LS_ICEA ( LSFRPT, IPT, IRET ) * C* * C* Input parameters: * C* LSFRPT CHAR* Report array * C* * C* Input and Output parameters: * C* IPT INTEGER On input, points to 'I' in 6IEER* C* group; on output, points to 'R' * C* * C* Output parameters: * C* RIVALS(IRCOIA) REAL Ice accretion on ships; * C* RIVALS(IRIDTH) REAL Thickness of ice on ship in m * C* RIVALS(IRROIA) REAL Rate of ice accretion on * C* IRET INTEGER Return code * C* 0 = Normal return * C* * C** * C* Log: * C* R. Hollern/NCEP 6/96 * C* R. Hollern/NCEP 12/96 Replaced ST_C2R with ST_INTG * C* R. Hollern/NCEP 1/98 Changes based on MA_ICEA * C* A. Hardy/GSC 1/98 Cleaned up prolog * C************************************************************************ INCLUDE 'GEMPRM.PRM' INCLUDE 'lscmn.cmn' C* CHARACTER*(*) lsfrpt C* CHARACTER fld2*2, fld1*1 C------------------------------------------------------------------------ iret = 0 C C* Get ice accretion on ships from WMO Code Table 1751. C IF ( lsfrpt ( ipt:ipt ) .ne. '/' ) THEN fld1 = lsfrpt ( ipt:ipt ) CALL ST_INTG ( fld1, ival, ier ) IF ( ier .eq. 0 ) rivals ( ircoia ) = FLOAT ( ival ) END IF C C* Get thickness of ice on ships in meters. C ipt = ipt + 1 IF ( lsfrpt ( ipt:ipt+1 ) .ne. '//' ) THEN fld2 = lsfrpt ( ipt:ipt+1 ) CALL ST_INTG ( fld2, ival, ier ) IF ( ier .eq. 0 ) rivals ( iridth ) = .01 * FLOAT ( ival ) END IF C C* Get rate of ice accretion on ships from WMO Code Table 3551. C ipt = ipt + 2 IF ( lsfrpt ( ipt:ipt ) .ne. '/' ) THEN fld1 = lsfrpt ( ipt:ipt ) CALL ST_INTG ( fld1, ival, ier ) IF ( ier .eq. 0 ) rivals ( irroia ) = FLOAT ( ival ) END IF C* RETURN END
# This file contains code related to the following situation. # We have P0 in ICP_N(A) restricting to Q0 in ICP_N(B), # where B = A \ {a}. We also have Q1 in ICP_N(B) refining Q0. # We let U denote the poset of elements M in ICP_N(A) such that # the restriction of M to B is Q1, and M refines P0. # The claim is that |U| is contractible. `random_element/PQQ` := (N::posint) -> (A::set,a) -> proc() local B,P0,Q0,Q1; B := A minus {a}; P0 := `random_element/ICP`(N)(A)(): Q0 := `res/ICP`(N)(A,B)(P0): Q1 := NULL: while Q1 = NULL or not(`is_leq/ICP`(N)(B)(Q0,Q1)) do Q1 := `random_element/ICP`(N)(B)(): od: return [P0,Q0,Q1]; end: ###################################################################### `analyse/PQQ` := (N::posint) -> (A::set,a) -> proc(PQQ) local B,P0,Q0,Q1,P0r,Q0r,Q1r,L1,n1,T,M,RR,SS,US,PN,PS,U,nU,U0,UR0, Q1B,AQ1B,RT,Bm,Bo,Bp,Bmr,Bpr,NB,NU,VV,b,i,j,k,l,beta,kk,ee; B := A minus {a}; P0,Q0,Q1 := op(PQQ); T := table(): T["N"] := N; T["A"] := A; T["B"] := B; T["a"] := a; T["P0"] := P0; T["Q0"] := Q0; T["Q1"] := Q1; T["P0_tot"] := `totalise/ICP/ord`(N)(A)(P0); T["Q0_tot"] := `totalise/ICP/ord`(N)(B)(Q0); T["Q1_tot"] := `totalise/ICP/ord`(N)(B)(Q1); P0r := table(): Q0r := table(): Q1r := table(): for i from 1 to N do P0r[i] := `rank_table/preord`(A)(P0[i]); Q0r[i] := `rank_table/preord`(B)(Q0[i]); Q1r[i] := `rank_table/preord`(B)(Q1[i]); od: T["P0_rank_table"] := eval(P0r); T["Q0_rank_table"] := eval(Q0r); T["Q1_rank_table"] := eval(Q1r); RR := table(): SS := table(): US := table(): for b in B do RR[b] := `list_elements/ICP`(N)({a,b}): SS[b] := map(`f/fibre_sphere/ICP`(N)(A)(a,b,Q1),RR[b]): US[b] := select(M -> `is_leq/ICP`(N)(A)(P0,M),SS[b]): PN[b] := evalb(nops(US[b]) > 0); PS[b] := evalb(modp(nops(US[b]),2) = 0); k := 1; while member([a,b],P0[k]) and member([b,a],P0[k]) do k := k+1; od: kk[b] := k; ee[b] := `if`(member([a,b],P0[k]),-1,+1); od: T["fibre_sphere"] := eval(SS); T["upper_fibre_part"] := eval(US); T["part_is_empty"] := eval(PE); T["part_is_sphere"] := eval(PS); T["P0_split_stage"] := eval(kk); T["P0_split_direction"] := eval(ee); T["fibre"] := {seq(op(SS[b]),b in B)}; U := {seq(op(US[b]),b in B)}; nU := nops(U); U0,UR0 := op(`skeleton/partord/from_comparator`(U)(`is_leq/ICP`(N)(A))); T["upper_fibre"] := U; T["U0"] := U0; T["upper_fibre_size"] := nU; T["upper_fibre_skeleton"] := UR0; T["upper_fibre_hasse_diagram"] := `hasse_diagram/partord`(U0)(UR0); L1 := T["Q1_tot"]; n1 := nops(L1); T["part_list"] := [seq(US[L1[i]],i=1..n1)]; T["part_is_nonempty_list"] := [seq(PN[L1[i]],i=1..n1)]; T["part_is_sphere_list"] := [seq(PS[L1[i]],i=1..n1)]; T["left_nested_list"] := [FAIL,seq(evalb({op(US[L1[i]])} minus {op(US[L1[i-1]])} = {}),i=2..n1)]; T["right_nested_list"] := [seq(evalb({op(US[L1[i]])} minus {op(US[L1[i+1]])} = {}),i=1..n1-1),FAIL]; T["part_skeleton"] := [ seq(select(i -> member(U[i],US[L1[j]]),U0),j=1..n1) ]; Q1B := table(): AQ1B := table(): RT := table(): Bm := table(): Bo := table(): Bp := table(): Bmr := table(): Bpr := table(): NU := table(): for i from 1 to N do Q1B[i] := `block_partition/equiv`(B)(Q1[i] union `op/autorel`(B)(Q1[i])); AQ1B[i] := select(u -> member([u[1],a],P0[i]) or member([a,u[1]],P0[i]),Q1B[i]); for beta in AQ1B[i] do RT[i,beta] := `rank_table/preord`(beta)(Q1[i]); NB[i,beta] := max(0,seq(RT[i,beta][b]+1,b in beta)); Bm[i,beta] := select(b -> not(member([a,b],P0[i])),beta); Bo[i,beta] := select(b -> member([a,b],P0[i]) and member([b,a],P0[i]),beta); Bp[i,beta] := select(b -> not(member([b,a],P0[i])),beta); Bmr[i,beta] := max(0,seq(RT[i,beta][b]+1,b in Bm[i,beta])); Bpr[i,beta] := min(NB[i,beta],seq(RT[i,beta][b],b in Bp[i,beta])); NU[i,beta] := Bpr[i,beta] - Bmr[i,beta] + 1; VV[i,beta] := {seq([i,beta,l-0.5],l=Bmr[i,beta]..Bpr[i,beta])}; od: od: Q1B[N+1] := {seq({b},b in B)}; AQ1B[N+1] := {}; T["Q1_comparability_blocks"] := eval(Q1B): T["admissible_blocks"] := eval(AQ1B); T["admissible_tree"] := [seq(seq([i,beta],beta in AQ1B[i]),i=1..N)]; T["Q1_rank_table"] := eval(RT); T["lower_set"] := eval(Bm); T["middle_set"] := eval(Bo); T["upper_set"] := eval(Bp); T["lower_rank"] := eval(Bmr); T["upper_rank"] := eval(Bpr); T["block_quotient_size"] := eval(NB); T["num_U"] := eval(NU); T["V"] := {seq(seq(op(VV[i,beta]),beta in AQ1B[i]),i=1..N)}; return eval(T): end: ###################################################################### `f/PQQ/U/V` := (T) -> proc(M) local a,b,j,k,beta,beta0,gamma,rt,r; k := 1: beta := T["B"]: a := T["a"]: for j from 2 to T["N"] do beta0 := select(b -> member([a,b],M[j]) or member([b,a],M[j]),beta); if beta0 <> {} then beta := beta0; k := j; else break; fi; od: gamma := select(b -> not(member([a,b],M[k])),beta); rt := eval(T["Q1_rank_table"][k,beta]): r := max(-1,seq(rt[b],b in gamma)) + 0.5; return [k,beta,r]; end: ###################################################################### `g/PQQ/V/U` := (T) -> proc(x) local i,k,N,a,b,B,MT,QQ,MM,M,beta,r,b0,L,U,rt; k,beta,r := op(x); N := T["N"]; a := T["a"]; B := T["B"]; MT := table(): for i from 1 to N do QQ := T["Q1"][i]; MM := QQ union {[a,a]}; if i < k then b0 := beta[1]; L := select(b -> member([b,b0],QQ),B); U := select(b -> member([b0,b],QQ),B); MM := {op(MM),seq([b,a],b in L),seq([a,b],b in U)}; elif i = k then rt := T["Q1_rank_table"][k,beta]; L := select(b -> rt[b] < r,beta); U := select(b -> rt[b] > r,beta); MM := {op(MM),seq([b,a],b in L),seq([a,b],b in U)}; fi; MT[i] := MM; od: M := [seq(MT[i],i=1..N)]; return M; end: ###################################################################### `is_leq/PQQ/V` := (T) -> proc(x0,x1) local k0,k1,beta0,beta1,r0,r1,r2,b0; k0,beta0,r0 := op(x0); k1,beta1,r1 := op(x1); if k0 < k1 then return false; fi; if k0 = k1 then return evalb(beta0 = beta1 and r0 = r1); fi; b0 := beta0[1]; if not(member(b0,beta1)) then return false; fi; r2 := T["Q1_rank_table"][k1,beta1][b0]; if not(r1 = r2 - 0.5 or r1 = r2 + 0.5) then return false; fi; return true; end: ###################################################################### `rho/PQQ` := (T) -> (j,e) -> proc(x) local k,beta,gamma,beta1,b0,QQ,rt,r1; k,beta,gamma := op(x); if j >= k then return FAIL; fi; b0 := beta[1]; QQ := T["Q1"][j]; beta1 := select(b -> member([b,b0],QQ) or member([b0,b],QQ),T["B"]); rt := T["Q1_rank_table"][j,beta1]; r1 := rt[beta[1]] + 0.5 * e; return [j,beta1,r1]; end: ###################################################################### `describe/PQQ` := proc(T) cat(`describe/ICP`(T["N"])(T["A"])(T["P0"]),"\n", `describe/ICP`(T["N"])(T["B"])(T["Q0"]),"\n", `describe/ICP`(T["N"])(T["B"])(T["Q1"]),"\n"); end: ###################################################################### `check_UV/PQQ` := proc(T) local N,A,U,V,ff,gg,M,M0,M1,x,x0,x1,cU,cV; N := T["N"]; A := T["A"]; U := T["upper_fibre"]: V := T["V"]: ff := table(): gg := table(): for M in U do x := `f/PQQ/U/V`(T)(M); if not(member(x,V)) then return false; fi; M1 := `g/PQQ/V/U`(T)(x); if M <> M1 then return false; fi; ff[M] := x; od: for x in V do M := `g/PQQ/V/U`(T)(x); if not(member(M,U)) then return false; fi; x1 := `f/PQQ/U/V`(T)(M); if x <> x1 then return false; fi; gg[x] := M; od: for x0 in V do for x1 in V do M0 := gg[x0]; M1 := gg[x1]; cU := `is_leq/ICP`(N)(A)(M0,M1); cV := `is_leq/PQQ/V`(T)(x0,x1); if cU <> cV then return false; fi; od; od; return true; end: ###################################################################### `check_rho/PQQ` := proc(T) global reason; local VV,i,j,k,x,y,z,C,y1,y2,y3,y4,y5,y6; VV := table(): for k from 1 to T["N"] do VV[k] := select(x -> x[1] = k,T["V"]): od: for k from 2 to T["N"] do for j from 1 to k-1 do for x in VV[k] do y := `rho/PQQ`(T)(j,-1)(x); z := `rho/PQQ`(T)(j,+1)(x); C := select(w -> `is_leq/PQQ/V`(T)(x,w),VV[j]); if (y = z) or (C <> {y,z}) then return false; fi; od; od; od; for k from 3 to T["N"] do for j from 2 to k-1 do for i from 1 to j-1 do for x in VV[k] do y1 := `rho/PQQ`(T)(i,-1)(x); y2 := `rho/PQQ`(T)(i,+1)(x); y3 := `rho/PQQ`(T)(i,-1)(`rho/PQQ`(T)(j,-1)(x)); y4 := `rho/PQQ`(T)(i,-1)(`rho/PQQ`(T)(j,+1)(x)); y5 := `rho/PQQ`(T)(i,+1)(`rho/PQQ`(T)(j,-1)(x)); y6 := `rho/PQQ`(T)(i,+1)(`rho/PQQ`(T)(j,+1)(x)); if not(y3 = y1 and y4 = y1 and y5 = y2 and y6 = y2) then reason := [i,j,k,x,y1,y2,y3,y4,y5,y6]; return false; fi; od; od; od; od; return true; end: ###################################################################### `check_UL/PQQ` := proc(T) global reason; local N,A,B,a,b,Q,kk,k,L,U,S,i,e; N := T["N"]; a := T["a"]; A := T["A"]; B := T["B"]; Q := T["Q1"]; kk := T["P0_split_stage"]; for b in B do k := kk[b]; L := {seq(seq(`f_alt/fibre_sphere/ICP`(N)(A)(a,b,Q)([i,e]),e in {-1,1}),i=1..k-1)}; U := {seq(seq(`f_alt/fibre_sphere/ICP`(N)(A)(a,b,Q)([i,e]),e in {-1,1}),i=k+1..N)}; S := {op(T["upper_fibre_part"][b])}; if not((U intersect S = {}) and (L minus S = {})) then return false; fi; od: return true; end: ###################################################################### `check_is_sphere/PQQ` := proc(T) global reason; local N,A,B,a,b,P0,Q0,Q1,kk,k,ee,e,C,D,E,F,u; N := T["N"]; a := T["a"]; A := T["A"]; B := T["B"]; P0 := T["P0"]; Q0 := T["Q0"]; Q1 := T["Q1"]; kk := eval(T["P0_split_stage"]); ee := eval(T["P0_split_direction"]); for b in B do k := kk[b]; e := ee[b]; if e = -1 then C := select(x -> member([x,b],Q0[k]) and member([b,x],Q0[k]),B); D := select(x -> member([x,b],Q1[k]) and not(member([b,x],Q1[k])),C); E := select(x -> member([a,x],P0[k]) and member([x,b],P0[k]) and not(member([x,a],P0[k])) and not(member([b,x],P0[k])),B); F := select(x -> member([x,b],Q1[k]) or member([b,x],Q1[k]),E); else C := select(x -> member([x,b],Q0[k]) and member([b,x],Q0[k]),B); D := select(x -> member([b,x],Q1[k]) and not(member([x,b],Q1[k])),C); E := select(x -> member([x,a],P0[k]) and member([b,x],P0[k]) and not(member([a,x],P0[k])) and not(member([x,b],P0[k])),B); F := select(x -> member([x,b],Q1[k]) or member([b,x],Q1[k]),E); fi; u := not(evalb(D = {} and F = {})); if u <> T["part_is_sphere"][b] then reason := [b,k,e,C,D,E,F]: return false; fi; od: return true; end: ###################################################################### `check_sphere_in_ball/PQQ` := proc(T) global reason; local N,A,B,a,b,P0,Q0,Q1,US,kk,k,ee,e,C,C1,b1; N := T["N"]; a := T["a"]; A := T["A"]; B := T["B"]; P0 := T["P0"]; Q0 := T["Q0"]; Q1 := T["Q1"]; kk := eval(T["P0_split_stage"]); ee := eval(T["P0_split_direction"]); US := eval(T["upper_fibre_part"]); for b in B do if T["part_is_sphere"][b] then k := kk[b]; e := ee[b]; if e = -1 then C := select(x -> member([x,b],Q1[k]) and not(member([x,a],P0[k])),B); if C = {} then reason := [b,k,e,C]; return false; fi; # Choose b1 to be Q1[k]-minimal in C C1 := C; while C1 <> {} do b1 := C1[1]; C1 := select(x -> not(member([b1,x],Q1[k])),C1); od: if T["part_is_sphere"][b1] or ({op(US[b])} minus {op(US[b1])} <> {}) or member([b,b1],Q1[k]) then reason := [b,k,e,C,b1]; return false; fi; else C := select(x -> member([b,x],Q1[k]) and not(member([a,x],P0[k])),B); if C = {} then reason := [b,k,e,C]; return false; fi; # Choose b1 to be Q1[k]-maximal in C C1 := C; while C1 <> {} do b1 := C1[1]; C1 := select(x -> not(member([x,b1],Q1[k])),C1); od: if T["part_is_sphere"][b1] or ({op(US[b])} minus {op(US[b1])} <> {}) or member([b1,b],Q1[k]) then reason := [b,k,e,C,b1]; return false; fi; fi; fi; od: return true; end: ###################################################################### `check_nonempty_interval/PQQ` := proc(T) local L,J,i,j,j0,j1; L := T["part_is_nonempty_list"]; if not(`or`(op(L))) then return false; fi; J := select(i -> L[i],[seq(i,i=1..nops(L))]); j0 := min(op(J)); j1 := max(op(J)); return `and`(seq(L[j],j=j0..j1)); end: ###################################################################### `check_adjacent_nonempty/PQQ` := proc(T) local L,P,i; L := T["part_is_nonempty_list"]; P := T["part_list"]; for i from 1 to nops(L)-1 do if L[i] and L[i+1] and ({op(P[i])} intersect {op(P[i+1])} = {}) then return false; fi; od; return true; end: ###################################################################### `check_incomparable_min/PQQ` := proc(T) local n,LN,RN,P,i,b,P1; n := nops(T["B"]); LN := T["left_nested_list"]; RN := T["right_nested_list"]; P := T["part_list"]; for i from 1 to n-1 do if not(LN[i+1]) and not(RN[i]) then b := T["Q1_tot"][i]; P1 := `m/fibre_sphere/ICP`(T["N"])(T["A"])(a,b,T["Q1"]): if not (member(P1,{op(P[i])}) and member(P1,{op(P[i+1])})) then return false; fi; fi; od; return true; end: ###################################################################### `check_intersections_nested/PQQ` := proc(T) global reason; local n,P,PS,i,j,k; n := nops(T["B"]); P := T["part_list"]; for i from 1 to n do PS[i] := {op(P[i])}; od: for i from 1 to n-2 do for j from i+1 to n-1 do for k from j+1 to n do if (PS[i] intersect PS[k]) minus PS[j] <> {} then reason := [i,j,k]; return false; fi; od; od; od; return true; end:
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2008-2016 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: [email protected]. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #ifndef OBITSPECTRUMFIT_H #define OBITSPECTRUMFIT_H #include "Obit.h" #include "ObitErr.h" #include "ObitImage.h" #include "ObitBeamShape.h" #include "ObitThread.h" #include "ObitInfoList.h" #ifdef HAVE_GSL #include <gsl/gsl_multifit_nlin.h> #endif /* HAVE_GSL */ /*-------- Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitSpectrumFit.h * * ObitSpectrumFit Class for fitting spectra to image pixels * * This class does least squares fitting of log(s) as a polynomial in log($\nu$). * Either an image cube or a set of single plane images at arbitrary * frequencies may be fitted. * The result is an image cube of Log(S) with multiples of powers of log($\nu$) * as the planes. * The function ObitSpectrumFitEval will evaluate this fit and return an image * with the flux densities at the desired frequencies. * * \section ObitSpectrumFitaccess Creators and Destructors * An ObitSpectrumFit will usually be created using ObitSpectrumFitCreate which allows * specifying a name for the object as well as other information. * * A copy of a pointer to an ObitSpectrumFit should always be made using the * #ObitSpectrumFitRef function which updates the reference count in the object. * Then whenever freeing an ObitSpectrumFit or changing a pointer, the function * #ObitSpectrumFitUnref will decrement the reference count and destroy the object * when the reference count hits 0. * There is no explicit destructor. */ /*--------------Class definitions-------------------------------------*/ /** ObitSpectrumFit Class structure. */ typedef struct { #include "ObitSpectrumFitDef.h" /* this class definition */ } ObitSpectrumFit; /*----------------- Macroes ---------------------------*/ /** * Macro to unreference (and possibly destroy) an ObitSpectrumFit * returns a ObitSpectrumFit*. * in = object to unreference */ #define ObitSpectrumFitUnref(in) ObitUnref (in) /** * Macro to reference (update reference count) an ObitSpectrumFit. * returns a ObitSpectrumFit*. * in = object to reference */ #define ObitSpectrumFitRef(in) ObitRef (in) /** * Macro to determine if an object is the member of this or a * derived class. * Returns TRUE if a member, else FALSE * in = object to reference */ #define ObitSpectrumFitIsA(in) ObitIsA (in, ObitSpectrumFitGetClass()) /*---------------Public functions---------------------------*/ /** Public: Class initializer. */ void ObitSpectrumFitClassInit (void); /** Public: Default Constructor. */ ObitSpectrumFit* newObitSpectrumFit (gchar* name); /** Public: Create/initialize ObitSpectrumFit structures */ ObitSpectrumFit* ObitSpectrumFitCreate (gchar* name, olong nterm); /** Typedef for definition of class pointer structure */ typedef ObitSpectrumFit* (*ObitSpectrumFitCreateFP) (gchar* name, olong nterm); /** Public: ClassInfo pointer */ gconstpointer ObitSpectrumFitGetClass (void); /** Public: Copy (deep) constructor. */ ObitSpectrumFit* ObitSpectrumFitCopy (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err); /** Public: Copy structure. */ void ObitSpectrumFitClone (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err); /** Public: Fit spectrum to an image cube */ void ObitSpectrumFitCube (ObitSpectrumFit* in, ObitImage *inImage, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitCubeFP) (ObitSpectrumFit* in, ObitImage *inImage, ObitImage *outImage, ObitErr *err); /** Public: Fit spectrum to an array of images */ void ObitSpectrumFitImArr (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitImArrFP) (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, ObitImage *outImage, ObitErr *err); /* Do actual fitting */ void ObitSpectrumFitter (ObitSpectrumFit* in, ObitErr *err); typedef void(*ObitSpectrumFitterFP) (ObitSpectrumFit* in, ObitErr *err); /** Public: Evaluate spectrum */ void ObitSpectrumFitEval (ObitSpectrumFit* in, ObitImage *inImage, odouble outFreq, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitEvalFP) (ObitSpectrumFit* in, ObitImage *inImage, odouble outFreq, ObitImage *outImage, ObitErr *err); /** Private: Write output image */ void ObitSpectrumWriteOutput (ObitSpectrumFit* in, ObitImage *outImage, ObitErr *err); typedef void (*ObitSpectrumWriteOutputFP) (ObitSpectrumFit* in, ObitImage *outImage, ObitErr *err); /** Public: Fit single spectrum */ ofloat* ObitSpectrumFitSingle (olong nfreq, olong nterm, odouble refFreq, odouble *freq, ofloat *flux, ofloat *sigma, gboolean doBrokePow, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef ofloat*(*ObitSpectrumFitSingleFP) (olong nfreq, olong nterm, odouble refFreq, odouble *freq, ofloat *flux, ofloat *sigma, gboolean doBrokePow, ObitErr *err); /** Public: Make fitting arg structure */ gpointer ObitSpectrumFitMakeArg (olong nfreq, olong nterm, odouble refFreq, odouble *freq, gboolean doBrokePow, ofloat **out, ObitErr *err); /** Public: Fit single spectrum using arg */ void ObitSpectrumFitSingleArg (gpointer arg, ofloat *flux, ofloat *sigma, ofloat *out); /** Public: Kill fitting arg structure */ void ObitSpectrumFitKillArg (gpointer arg); /*----------- ClassInfo Structure -----------------------------------*/ /** * ClassInfo Structure. * Contains class name, a pointer to any parent class * (NULL if none) and function pointers. */ typedef struct { #include "ObitSpectrumFitClassDef.h" } ObitSpectrumFitClassInfo; #endif /* OBITFSPECTRUMFIT_H */
#pragma once #include <Eigen/Core> #include <memory> #include <numeric> #include <set> #include <string> #include "ear/layout.hpp" #include "ear/metadata.hpp" namespace ear { /** @brief An interface for objects that can calculate gains for some * positions, e.g. a triangle of loudspeakers. */ class RegionHandler { public: RegionHandler(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions); virtual boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) const = 0; virtual ~RegionHandler() = default; boost::optional<Eigen::VectorXd> handleRemap(Eigen::Vector3d position, int numberOfChannels) const; Eigen::VectorXi outputChannels(); protected: Eigen::VectorXi _outputChannels; Eigen::MatrixXd _positions; }; /** @brief Region handler representing a triplet of loudspeakers, implementing * VBAP. * * This is implemented such that if handle(pos) returns array x: * * - dot(x, positions) is collinear with pos * - x[i] >= 0 for all i * - norm(x) == 1 * * Note that the positions are *not* normalised, as this is not always * desirable. */ class Triplet : public RegionHandler { public: /** @brief Ctor * * @param output_channels The channel numbers of the values returned by * handle. * @param positions Cartesian positions of the three speakers; index order * is speaker, axis. */ Triplet(Eigen::Vector3i outputChannels, Eigen::Matrix3d positions); boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) const override; private: Eigen::Matrix3d _basis; }; /** @brief Region handler representing n real loudspeakers and a central * virtual loudspeaker, whose gain is distributed to the real loudspeakers. * * Triplet regions are formed between the virtual speaker and pairs of real * speakers on the edge of the ngon. Any gain sent to the virtual speaker is * multiplied by centre_downmix and summed into the gains for the real * loudspeakers,which are then normalised. */ class VirtualNgon : public RegionHandler { public: /** @brief Ctor * * @param output_channels The channel numbers of the values returned by * handle. * @param positions Cartesian positions of the n loudspeakers. * @param centrePosition Cartesian position of the central virtual * loudspeaker * @param centreDownmix Downmix coefficients for distributing gains from * the centre virtual loudspeaker to the loudspeakers defined by * positions. */ VirtualNgon(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions, Eigen::Vector3d centrePosition, Eigen::VectorXd centreDownmix); boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) const override; private: Eigen::Vector3d _centrePosition; Eigen::VectorXd _centreDownmix; std::vector<std::unique_ptr<RegionHandler>> _regions; }; class QuadRegion : public RegionHandler { public: QuadRegion(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions); boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) const override; private: Eigen::Matrix3d _calcPolyBasis(Eigen::MatrixXd positions); boost::optional<double> _pan(Eigen::Vector3d position, Eigen::Matrix3d polyBasis) const; Eigen::VectorXi _order; Eigen::Matrix3d _polyBasisX; Eigen::Matrix3d _polyBasisY; }; /** @brief Base class for all PointSourcePanner like classes */ class PointSourcePanner { public: virtual boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) = 0; virtual int numberOfOutputChannels() const = 0; }; /** @brief Wrapper around multiple regions. */ class PolarPointSourcePanner : public PointSourcePanner { public: /** @brief Ctor * * @param regions Regions used to handle a position. * @param numberOfChannels Number of output channels; this is computed * from the output channels of the regions if not provided. */ PolarPointSourcePanner(std::vector<std::unique_ptr<RegionHandler>> regions, boost::optional<int> numberOfChannels = boost::none); boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override; int numberOfOutputChannels() const override; private: int _numberOfRequiredChannels(); const std::vector<std::unique_ptr<RegionHandler>> _regions; int _numberOfOutputChannels; }; /** @brief Wrapper around a point source panner with an additional downmix. */ class PointSourcePannerDownmix : public PointSourcePanner { public: /** @brief Ctor * * @param psp Inner point source panner. * @param downmix Downmix matrix (mxn) from m inputs to n outputs. */ PointSourcePannerDownmix(std::shared_ptr<PointSourcePanner> psp, Eigen::MatrixXd downmix); ~PointSourcePannerDownmix() = default; boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override; int numberOfOutputChannels() const override; private: std::shared_ptr<PointSourcePanner> _psp; Eigen::MatrixXd _downmix; }; /** @brief Generate extra loudspeaker positions to fill gaps in layers. * * @param layout Original layout without the LFE channels * * @returns * - list of extra channels (layout.Channel). * - downmix matrix to mix the extra channel outputs to the real channels */ std::pair<std::vector<Channel>, Eigen::MatrixXd> extraPosVerticalNominal( Layout layout); // given a layout, determine the full set of loudspeaker positions used for // panning. returns: // // - the real position of real and virtual loudspeakers // - the nominal position of the real and virtual loudspeakers // - the indices of the virtual loudspeakers in the two position lists // - a downmix matrix to be applied to the output of the real loudspeakers std::tuple<std::vector<Eigen::Vector3d>, std::vector<Eigen::Vector3d>, std::set<int>, Eigen::MatrixXd> getAugmentedLayout(const Layout& layout); std::shared_ptr<PointSourcePanner> configureFullPolarPanner( const Layout& layout); class StereoPannerDownmix : public RegionHandler { public: StereoPannerDownmix(Eigen::VectorXi outputChannels, Eigen::MatrixXd positions); boost::optional<Eigen::VectorXd> handle( Eigen::Vector3d position) const override; private: std::shared_ptr<PointSourcePanner> _psp; }; class AllocentricPanner : public PointSourcePanner { public: AllocentricPanner() = default; ~AllocentricPanner() = default; boost::optional<Eigen::VectorXd> handle(Eigen::Vector3d position) override; int numberOfOutputChannels() const override; }; std::shared_ptr<PointSourcePanner> configureStereoPolarPanner( const Layout& layout); std::shared_ptr<PointSourcePanner> configureFullPolarPanner( const Layout& layout); std::shared_ptr<PointSourcePanner> configureAllocentricPanner( const Layout& layout); std::shared_ptr<PointSourcePanner> configurePolarPanner(const Layout& layout); } // namespace ear
{- 55 -} module Main main : IO () main = printLn $ foldl (+) 0 [1..10]
module datatype-util where open import constants open import ctxt open import syntax-util open import general-util open import type-util open import cedille-types open import subst open import rename open import free-vars {-# TERMINATING #-} decompose-arrows : ctxt → type → params × type decompose-arrows Γ (TpAbs me x atk T) = let x' = fresh-var-new Γ x in case decompose-arrows (ctxt-var-decl x' Γ) (rename-var Γ x x' T) of λ where (ps , T') → Param me x' atk :: ps , T' decompose-arrows Γ T = [] , T decompose-ctr-type : ctxt → type → type × params × 𝕃 tmtp decompose-ctr-type Γ T with decompose-arrows Γ T ...| ps , Tᵣ with decompose-tpapps Tᵣ ...| Tₕ , as = Tₕ , ps , as {-# TERMINATING #-} kind-to-indices : ctxt → kind → indices kind-to-indices Γ (KdAbs x atk k) = let x' = fresh-var-new Γ x in Index x' atk :: kind-to-indices (ctxt-var-decl x' Γ) (rename-var Γ x x' k) kind-to-indices Γ _ = [] rename-indices-h : ctxt → renamectxt → indices → 𝕃 tmtp → indices rename-indices-h Γ ρ (Index x atk :: is) (ty :: tys) = Index x' atk' :: rename-indices-h (ctxt-var-decl x' Γ) (renamectxt-insert ρ x x') is tys where x' = fresh-var-renamectxt Γ ρ (maybe-else x id (is-var-unqual ty)) atk' = subst-renamectxt Γ ρ -tk atk rename-indices-h Γ ρ (Index x atk :: is) [] = let x' = fresh-var-renamectxt Γ ρ x in Index x' (subst-renamectxt Γ ρ -tk atk) :: rename-indices-h (ctxt-var-decl x' Γ) (renamectxt-insert ρ x x') is [] rename-indices-h _ _ [] _ = [] rename-indices : ctxt → indices → 𝕃 tmtp → indices rename-indices Γ = rename-indices-h Γ empty-renamectxt positivity : Set positivity = 𝔹 × 𝔹 -- occurs positively × occurs negatively pattern occurs-nil = ff , ff pattern occurs-pos = tt , ff pattern occurs-neg = ff , tt pattern occurs-all = tt , tt --positivity-inc : positivity → positivity --positivity-dec : positivity → positivity positivity-neg : positivity → positivity positivity-add : positivity → positivity → positivity --positivity-inc = map-fst λ _ → tt --positivity-dec = map-snd λ _ → tt positivity-neg = uncurry $ flip _,_ positivity-add (+ₘ , -ₘ) (+ₙ , -ₙ) = (+ₘ || +ₙ) , (-ₘ || -ₙ) data ctorCheckT : Set where ctorOk : ctorCheckT ctorNotInReturnType : ctorCheckT ctorNegative : ctorCheckT posₒ = fst negₒ = snd occurs : positivity → ctorCheckT occurs p = if (negₒ p) then ctorNegative else ctorOk or-ctorCheckT : ctorCheckT → ctorCheckT → ctorCheckT or-ctorCheckT ctorOk r = r or-ctorCheckT ctorNegative _ = ctorNegative or-ctorCheckT ctorNotInReturnType _ = ctorNotInReturnType posM : Set → Set posM A = 𝕃 tpkd → A × 𝕃 tpkd run-posM : ∀{A : Set} → posM A → A × 𝕃 tpkd run-posM p = p [] extract-pos : ∀{A : Set} → posM A → A extract-pos = fst ∘ run-posM instance posM-monad : monad posM return ⦃ posM-monad ⦄ a = λ l → a , l _>>=_ ⦃ posM-monad ⦄ p ap l with p l _>>=_ ⦃ posM-monad ⦄ p ap l | a , l' = ap a l' posM-functor : functor posM fmap ⦃ posM-functor ⦄ g m l with m l fmap ⦃ posM-functor ⦄ g m l | a , l' = g a , l' posM-applicative : applicative posM pure ⦃ posM-applicative ⦄ = return _<*>_ ⦃ posM-applicative ⦄ mab ma l with mab l _<*>_ ⦃ posM-applicative ⦄ mab ma l | f , l' with ma l' _<*>_ ⦃ posM-applicative ⦄ mab ma l | f , l' | a , l'' = f a , l'' add-posM : tpkd → posM ⊤ add-posM x = λ l → triv , x :: l module positivity (x : var) where open import conversion if-free : ∀ {ed} → ⟦ ed ⟧ → positivity if-free t with is-free-in x t ...| f = f , f if-free-args : args → positivity if-free-args as = let c = stringset-contains (free-vars-args as) x in c , c hnf' : ∀ {ed} → ctxt → ⟦ ed ⟧ → ⟦ ed ⟧ hnf' Γ T = hnf Γ unfold-no-defs T mtt = maybe-else tt id mff = maybe-else ff id {-# TERMINATING #-} type+ : ctxt → type → posM positivity kind+ : ctxt → kind → posM positivity tpkd+ : ctxt → tpkd → posM positivity tpapp+ : ctxt → type → posM positivity type+h : ctxt → type → posM positivity kind+h : ctxt → kind → posM positivity tpkd+h : ctxt → tpkd → posM positivity tpapp+h : ctxt → type → posM positivity type+ Γ T = type+h Γ T -- >>= λ p → add-posM (Tkt T) >> return p kind+ Γ k = kind+h Γ k tpkd+ Γ x = tpkd+h Γ x tpapp+ Γ T = tpapp+h Γ T type+h Γ (TpAbs me x' atk T) = let Γ' = ctxt-var-decl x' Γ in pure positivity-add <*> (fmap positivity-neg $ tpkd+ Γ $ hnf' Γ -tk atk) <*> (type+ Γ' $ hnf' Γ' T) type+h Γ (TpIota x' T T') = let Γ' = ctxt-var-decl x' Γ in pure positivity-add <*> (type+ Γ $ hnf' Γ T) <*> (type+ Γ' $ hnf' Γ' T') type+h Γ (TpApp T tT) = tpapp+ Γ $ hnf' Γ $ TpApp T tT type+h Γ (TpEq tₗ tᵣ) = pure occurs-nil type+h Γ (TpHole _) = pure occurs-nil type+h Γ (TpLam x' atk T)= let Γ' = ctxt-var-decl x' Γ in pure positivity-add <*> (fmap positivity-neg $ tpkd+ Γ $ hnf' Γ -tk atk) <*> (type+ Γ' (hnf' Γ' T)) type+h Γ (TpVar x') = pure $ x =string x' , ff kind+h Γ (KdAbs x' atk k) = let Γ' = ctxt-var-decl x' Γ in pure positivity-add <*> (fmap positivity-neg $ tpkd+ Γ $ hnf' Γ -tk atk) <*> (kind+ Γ' k) kind+h Γ _ = pure occurs-nil tpkd+h Γ (Tkt T) = type+ Γ (hnf' Γ T) tpkd+h Γ (Tkk k) = kind+ Γ k tpapp+h Γ T with decompose-tpapps T tpapp+h Γ T | TpVar x' , as = let f = if-free-args (tmtps-to-args NotErased as) in if x =string x' then pure (positivity-add occurs-pos f) else maybe-else' (data-lookup Γ x' as) (pure f) λ {(mk-data-info x'' xₒ'' asₚ asᵢ ps kᵢ k cs csₚₛ eds gds) → let s = (inst-type Γ ps asₚ (hnf' Γ $ TpAbs tt x'' (Tkk k) $ foldr (uncurry λ cₓ cₜ → TpAbs ff ignored-var (Tkt cₜ)) (TpVar x'') cs)) in add-posM (Tkt s) >> type+ Γ s } tpapp+h Γ T | _ , _ = pure $ if-free T {-# TERMINATING #-} arrs+ : ctxt → type → posM ctorCheckT arrs+ Γ (TpAbs me x' atk T) = let Γ' = ctxt-var-decl x' Γ in pure or-ctorCheckT <*> (fmap occurs (tpkd+ Γ $ hnf' Γ -tk atk)) <*> (arrs+ Γ' (hnf' Γ' T)) arrs+ Γ (TpApp T tT) = fmap occurs (tpapp+ Γ $ hnf' Γ (TpApp T tT)) arrs+ Γ (TpLam x' atk T) = let Γ' = ctxt-var-decl x' Γ in pure or-ctorCheckT <*> (fmap occurs (tpkd+ Γ $ hnf' Γ -tk atk)) <*> (arrs+ Γ' (hnf' Γ' T)) arrs+ Γ (TpVar x') = return $ if (x =string x') then ctorOk else ctorNotInReturnType arrs+ _ _ = return ctorNegative ctr-positive : ctxt → type → posM ctorCheckT ctr-positive Γ = (arrs+ Γ ∘ hnf' Γ) -- build the evidence for a sigma-term, given datatype X with associated info μ sigma-build-evidence : var → datatype-info → term sigma-build-evidence X μ = if datatype-info.name μ =string X then recompose-apps (datatype-info.asₚ μ) (Var (data-is/ X)) else Var (mu-isType/' X)
[STATEMENT] lemma list2_middle_singleton: assumes "length xs = 3" shows "butlast (tl xs) = [xs ! 1]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. butlast (tl xs) = [xs ! 1] [PROOF STEP] proof (simp add: list_eq_iff_nth_eq assms) [PROOF STATE] proof (state) goal (1 subgoal): 1. butlast (tl xs) ! 0 = xs ! Suc 0 [PROOF STEP] have l: "length (butlast (tl xs)) = 1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length (butlast (tl xs)) = 1 [PROOF STEP] using length_butlast length_tl assms [PROOF STATE] proof (prove) using this: length (butlast ?xs) = length ?xs - 1 length (tl ?xs) = length ?xs - 1 length xs = 3 goal (1 subgoal): 1. length (butlast (tl xs)) = 1 [PROOF STEP] by simp [PROOF STATE] proof (state) this: length (butlast (tl xs)) = 1 goal (1 subgoal): 1. butlast (tl xs) ! 0 = xs ! Suc 0 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: length (butlast (tl xs)) = 1 [PROOF STEP] have " butlast (tl xs) ! 0 = (tl xs) ! 0" [PROOF STATE] proof (prove) using this: length (butlast (tl xs)) = 1 goal (1 subgoal): 1. butlast (tl xs) ! 0 = tl xs ! 0 [PROOF STEP] using nth_butlast[of 0 "tl xs"] [PROOF STATE] proof (prove) using this: length (butlast (tl xs)) = 1 0 < length (butlast (tl xs)) \<Longrightarrow> butlast (tl xs) ! 0 = tl xs ! 0 goal (1 subgoal): 1. butlast (tl xs) ! 0 = tl xs ! 0 [PROOF STEP] by simp [PROOF STATE] proof (state) this: butlast (tl xs) ! 0 = tl xs ! 0 goal (1 subgoal): 1. butlast (tl xs) ! 0 = xs ! Suc 0 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: butlast (tl xs) ! 0 = tl xs ! 0 [PROOF STEP] show "butlast (tl xs) ! 0 = xs ! Suc 0" [PROOF STATE] proof (prove) using this: butlast (tl xs) ! 0 = tl xs ! 0 goal (1 subgoal): 1. butlast (tl xs) ! 0 = xs ! Suc 0 [PROOF STEP] using nth_tl[of 0 xs] l [PROOF STATE] proof (prove) using this: butlast (tl xs) ! 0 = tl xs ! 0 0 < length (tl xs) \<Longrightarrow> tl xs ! 0 = xs ! Suc 0 length (butlast (tl xs)) = 1 goal (1 subgoal): 1. butlast (tl xs) ! 0 = xs ! Suc 0 [PROOF STEP] by simp [PROOF STATE] proof (state) this: butlast (tl xs) ! 0 = xs ! Suc 0 goal: No subgoals! [PROOF STEP] qed
If two paths are homotopic loops, then they are loops.
import os import random import cv2 import numpy as np import matplotlib.pyplot as plt from itertools import cycle from scipy import interp from sklearn import metrics from sklearn.decomposition import PCA from sklearn.preprocessing import label_binarize from sklearn.neighbors import KNeighborsClassifier def read_data(): img_size = (200, 200) train_all = [] test_all = [] current_base = os.path.abspath('.') train_path = os.path.join(current_base, "train") test_path = os.path.join(current_base, "test") # read train for dir_name in os.listdir(train_path): dir_path = os.path.join(train_path, dir_name) class_id = int(dir_name) for img_name in os.listdir(dir_path): img_path = os.path.join(dir_path, img_name) img_vec = cv2.imread(img_path, flags=1) # print img_vec.shape # res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC) res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC) nor_res = np.zeros_like(res) nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) # print nor_res.shape nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], ) train_all.append((class_id, nor_res)) # read test for dir_name in os.listdir(test_path): dir_path = os.path.join(test_path, dir_name) class_id = int(dir_name) for img_name in os.listdir(dir_path): img_path = os.path.join(dir_path, img_name) img_vec = cv2.imread(img_path, flags=1) # print img_vec.shape # res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC) res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC) nor_res = np.zeros_like(res) nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], ) test_all.append((class_id, nor_res)) return train_all, test_all def draw_multi_ROC(y_test, prob, paras): y_test_bin = label_binarize(y_test, classes=[(i+1) for i in xrange(n_classes)]) # Compute macro-average ROC curve and ROC area fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = metrics.roc_curve(y_test_bin[:, i], prob[:, i]) roc_auc[i] = metrics.auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = metrics.roc_curve(y_test_bin.ravel(), prob.ravel()) roc_auc["micro"] = metrics.auc(fpr["micro"], tpr["micro"]) # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) # print mean_tpr for i in range(n_classes): # print interp(all_fpr, fpr[i], tpr[i]) mean_tpr += interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= n_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = metrics.auc(fpr["macro"], tpr["macro"]) # Plot all ROC curves plt.figure(str(paras[1]), figsize=(20,10)) plt.title("Score: " + str(paras[0]) + " knn_k: " + str(paras[1]) + " pca_k: " + str(paras[2])) plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4) plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["macro"]), color='navy', linestyle=':', linewidth=4) lw = 2 colors = cycle([ ((round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2))) for i in xrange(n_classes) ]) for i, color in zip(range(n_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=lw, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) plt.plot([0, 1], [0, 1], 'k--', lw=lw) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') # plt.title('Some extension of Receiver operating characteristic to multi-class') plt.legend(loc='lower right') if not os.path.exists("task1"): os.mkdir("task1") if not os.path.exists("task1/color/"+str(paras[2])): os.mkdir("task1/color/"+str(paras[2])) plt.savefig("task1/color/"+str(paras[2])+'/'+str(paras[1])+'.png') # plt.show() plt.close() def draw_ROC(y_test, prob): y_test_bin = label_binarize(y_test, classes=[(i + 1) for i in xrange(n_classes)]) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = metrics.roc_curve(y_test_bin[:, i], prob[:, i]) roc_auc[i] = metrics.auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = metrics.roc_curve(y_test_bin.ravel(), prob.ravel()) roc_auc["micro"] = metrics.auc(fpr["micro"], tpr["micro"]) plt.figure() lw = 2 plt.plot(fpr[2], tpr[2], color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() if __name__ == "__main__": train_all, test_all = read_data() X_train = [ i[1] for i in train_all ] y_train = [ i[0] for i in train_all ] X_test = [ i[1] for i in test_all ] y_test = [ i[0] for i in test_all ] n_components = 1 n_classes = len(set(y_train)) while n_components < 201.1: pca = PCA(n_components=n_components) pca.fit(X_train) X_pca_train = pca.transform(X_train) X_pca_test = pca.transform(X_test) print "pca:", n_components expl = pca.explained_variance_ratio_ sim = 0.0 for i in expl: sim += i print "expl ratio:", sim # X_mat = np.mat(X_train) # print 1 - np.sum(np.square(X_mat - X_recompose_train)) / np.sum(np.square(X_mat)), "%" k = 1 while k < 6: neigh = KNeighborsClassifier(n_neighbors=k) neigh.fit(X_pca_train, y_train) # predict = neigh.predict(X_pca_test) score = neigh.score(X_pca_test, y_test) prob = neigh.predict_proba(X_pca_test) print "score:", "%.4f" % score, "knn_k:", k, "pca_k:", n_components # input predict prob as ROC parameter draw_multi_ROC(y_test, prob, (score, k, n_components)) k += 1 n_components += 50
using HypothesisTests using Distances using DelayEmbeddings function normalise_minmax(x, vmin, vmax) (x - vmin)/(vmax - vmin) end """ jdd(source, target; distance_metric = SqEuclidean(), B::Int = 10, D::Int = 2, τ::Int = 1) → Vector{Float64} Compute the joint distance distribution [^1] from `source` to `target` using the provided `distance_metric`, with `B` controlling the number of subintervals, `D` the embedding dimension and `τ` the embedding lag. ## Example ```julia using CausalityTools x, y = rand(1000), rand(1000) jdd(x, y) ``` ## Keyword arguments - **`distance_metric::Metric`**: An instance of a valid distance metric from `Distances.jl`. Defaults to `SqEuclidean()`. - **`B`**: The number of equidistant subintervals to divide the interval `[0, 1]` into when comparing the normalised distances. - **`D`**: Embedding dimension. - **`τ`**: Embedding delay. ## References [^1] Amigó, José M., and Yoshito Hirata. "Detecting directional couplings from multivariate flows by the joint distance distribution." Chaos: An Interdisciplinary Journal of Nonlinear Science 28.7 (2018): 075302. """ function jdd(source, target; distance_metric = Euclidean(), B::Int = 10, D::Int = 2, τ::Int = 1) js = ([1 for i = 1:D]...,) τs = (collect(0:-τ:-(D-1)*τ)...,) Ex = DelayEmbeddings.genembed(source, τs, js) Ey = DelayEmbeddings.genembed(target, τs, js) Mx = DelayEmbeddings.Matrix(Ex) My = DelayEmbeddings.Matrix(Ey) npts = length(Ex) Dx = pairwise(distance_metric, Mx, Mx, dims = 1) Dy = pairwise(distance_metric, My, My, dims = 1) # Normalise the distances to the interval [0, 1] Dx_min = minimum(Dx[Dx .> 0]) Dy_min = minimum(Dy[Dy .> 0]) Dx_max = maximum(Dx[Dx .> 0]) Dy_max = maximum(Dy[Dy .> 0]) Dx_norm = zeros(Float64, size(Dx)) Dy_norm = zeros(Float64, size(Dy)) for i in LinearIndices(Dx[Dx .> 0]) Dx_norm[i] = normalise_minmax(Dx[i], Dx_min, Dx_max) end for i in LinearIndices(Dy[Dy .> 0]) Dy_norm[i] = normalise_minmax(Dy[i], Dy_min, Dy_max) end mins_δ_yi_yj = fill(2.0, 2*B) for (k, b) in enumerate(1:2*B) bmin = (b-1)/(2*B) bmax = b/(2*B) # Find the indices of all pairs (i, j) in Dx whose distances fall inside the interval Ib #idxs_Dxs_in_Ib = findall(Dx[]) # We don't need to store any indices or distances explicitly, but only # keep track of whether a smaller distance has has been detected. # The maximum possible distance after normalisation is 1.0, so this # value can only decrease as we update. min_δ_yi_yj = 1.0 for i = 1:npts for j = (i+1):npts δ_xi_xj = Dx_norm[i, j] if bmin < δ_xi_xj <= bmax δ_yi_yj = Dy_norm[i, j] if δ_yi_yj < min_δ_yi_yj min_δ_yi_yj = δ_yi_yj end end end end mins_δ_yi_yj[k] = min_δ_yi_yj end Δjdd = [mins_δ_yi_yj[B + i] - mins_δ_yi_yj[i] for i in 1:B] return Δjdd end """ jdd(test::OneSampleTTest, source, target; distance_metric = SqEuclidean(), B::Int = 10, D::Int = 2, τ::Int = 1, μ0 = 0.0) → OneSampleTTest Perform a one sample t-test to check that the joint distance distribution[^Amigo] computed from `source` to `target` is biased towards positive values, using the null hypothesis that the mean of the distribution is `μ0`. The interpretation of the t-test is that if we can reject the null, then the joint distance distribution is biased towards positive values, and then there exists an underlying coupling from `source` to `target`. ## Example ```julia using CausalityTools, HypothesisTests x, y = rand(1000), rand(1000) jdd(OneSampleTTest, x, y) ``` which gives ```julia One sample t-test ----------------- Population details: parameter of interest: Mean value under h_0: 0.0 point estimate: 0.06361857324022721 95% confidence interval: (0.0185, 0.1087) Test summary: outcome with 95% confidence: reject h_0 two-sided p-value: 0.0082 Details: number of observations: 20 t-statistic: 2.9517208721082873 degrees of freedom: 19 empirical standard error: 0.0215530451545668 ``` The lower bound of the confidence interval for the mean of the joint distance distribution is `0.0185` at confidence level `α = 0.05`. The meaning that the test falsely detected causality from `x` to `y` between these two random time series. To get the confidence intervals at confidence level `α`, run ```confinf(jdd(OneSampleTTest, x, y), α)```. If you just want the p-value at 95% confidence, run ```pvalue(jdd(OneSampleTTest, x, y), tail = :right)``` ## Keyword arguments - **`distance_metric::Metric`**: An instance of a valid distance metric from `Distances.jl`. Defaults to `SqEuclidean()`. - **`B`**: The number of equidistant subintervals to divide the interval `[0, 1]` into when comparing the normalised distances. - **`D`**: Embedding dimension. - **`τ`**: Embedding delay. - **`μ0`**: The hypothetical mean value of the joint distance distribution if there is no coupling between `x` and `y` (default is `μ0 = 0.0`). ## References [^Amigo]: Amigó, José M., and Yoshito Hirata. "Detecting directional couplings from multivariate flows by the joint distance distribution." Chaos: An Interdisciplinary Journal of Nonlinear Science 28.7 (2018): 075302. """ function jdd(test::Type{OneSampleTTest}, source, target; distance_metric = SqEuclidean(), B::Int = 10, D::Int = 2, τ::Int = 1, μ0 = 0.0) Δjdd = jdd(source, target, distance_metric = distance_metric, B = B, D = D, τ = τ) OneSampleTTest(Δjdd, μ0) end export jdd
[STATEMENT] lemma connected_iff6: assumes "is_inj x" and "is_p_fun x" shows "connected x \<longleftrightarrow> x\<^sup>+;1;(x\<^sup>+)\<^sup>T \<le> x\<^sup>\<star> + x\<^sup>T\<^sup>\<star>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. connected x = (x\<^sup>+ ; 1 ; (x\<^sup>+)\<^sup>T \<le> x\<^sup>\<star> + x\<^sup>T\<^sup>\<star>) [PROOF STEP] using assms connected_iff2 comp_assoc plus_conv plus_top top_plus [PROOF STATE] proof (prove) using this: is_inj x is_p_fun x \<lbrakk>is_inj ?x; is_p_fun ?x\<rbrakk> \<Longrightarrow> connected ?x = (?x ; 1 ; ?x\<^sup>T \<le> ?x\<^sup>\<star> + ?x\<^sup>T\<^sup>\<star>) ?x ; ?y ; ?z = ?x ; (?y ; ?z) (?x\<^sup>+)\<^sup>T = ?x\<^sup>T\<^sup>+ ?x\<^sup>+ ; 1 = ?x ; 1 1 ; ?x\<^sup>+ = 1 ; ?x goal (1 subgoal): 1. connected x = (x\<^sup>+ ; 1 ; (x\<^sup>+)\<^sup>T \<le> x\<^sup>\<star> + x\<^sup>T\<^sup>\<star>) [PROOF STEP] by fastforce
/- Copyright (c) 2020 Zhangir Azerbayev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Zhangir Azerbayev -/ import group_theory.perm.sign import group_theory.perm.subgroup import group_theory.quotient_group import linear_algebra.linear_independent import linear_algebra.multilinear.basis import linear_algebra.multilinear.tensor_product import logic.equiv.fin /-! # Alternating Maps We construct the bundled function `alternating_map`, which extends `multilinear_map` with all the arguments of the same type. ## Main definitions * `alternating_map R M N ι` is the space of `R`-linear alternating maps from `ι → M` to `N`. * `f.map_eq_zero_of_eq` expresses that `f` is zero when two inputs are equal. * `f.map_swap` expresses that `f` is negated when two inputs are swapped. * `f.map_perm` expresses how `f` varies by a sign change under a permutation of its inputs. * An `add_comm_monoid`, `add_comm_group`, and `module` structure over `alternating_map`s that matches the definitions over `multilinear_map`s. * `multilinear_map.alternatization`, which makes an alternating map out of a non-alternating one. * `alternating_map.dom_coprod`, which behaves as a product between two alternating maps. ## Implementation notes `alternating_map` is defined in terms of `map_eq_zero_of_eq`, as this is easier to work with than using `map_swap` as a definition, and does not require `has_neg N`. `alternating_map`s are provided with a coercion to `multilinear_map`, along with a set of `norm_cast` lemmas that act on the algebraic structure: * `alternating_map.coe_add` * `alternating_map.coe_zero` * `alternating_map.coe_sub` * `alternating_map.coe_neg` * `alternating_map.coe_smul` -/ -- semiring / add_comm_monoid variables {R : Type*} [semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] -- semiring / add_comm_group variables {M' : Type*} [add_comm_group M'] [module R M'] variables {N' : Type*} [add_comm_group N'] [module R N'] variables {ι : Type*} [decidable_eq ι] set_option old_structure_cmd true section variables (R M N ι) /-- An alternating map is a multilinear map that vanishes when two of its arguments are equal. -/ structure alternating_map extends multilinear_map R (λ i : ι, M) N := (map_eq_zero_of_eq' : ∀ (v : ι → M) (i j : ι) (h : v i = v j) (hij : i ≠ j), to_fun v = 0) end /-- The multilinear map associated to an alternating map -/ add_decl_doc alternating_map.to_multilinear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! Basic coercion simp lemmas, largely copied from `ring_hom` and `multilinear_map` -/ section coercions instance : has_coe_to_fun (alternating_map R M N ι) (λ _, (ι → M) → N) := ⟨λ x, x.to_fun⟩ initialize_simps_projections alternating_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) = f := rfl theorem congr_fun {f g : alternating_map R M N ι} (h : f = g) (x : ι → M) : f x = g x := congr_arg (λ h : alternating_map R M N ι, h x) h theorem congr_arg (f : alternating_map R M N ι) {x y : ι → M} (h : x = y) : f x = f y := congr_arg (λ x : ι → M, f x) h theorem coe_injective : injective (coe_fn : alternating_map R M N ι → ((ι → M) → N)) := λ f g h, by { cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : alternating_map R M N ι} : (f : (ι → M) → N) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : alternating_map R M N ι} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : alternating_map R M N ι} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : has_coe (alternating_map R M N ι) (multilinear_map R (λ i : ι, M) N) := ⟨λ x, x.to_multilinear_map⟩ @[simp, norm_cast] lemma coe_multilinear_map : ⇑(f : multilinear_map R (λ i : ι, M) N) = f := rfl lemma coe_multilinear_map_injective : function.injective (coe : alternating_map R M N ι → multilinear_map R (λ i : ι, M) N) := λ x y h, ext $ multilinear_map.congr_fun h @[simp] lemma to_multilinear_map_eq_coe : f.to_multilinear_map = f := rfl @[simp] lemma coe_multilinear_map_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = ⟨f, h₁, h₂⟩ := rfl end coercions /-! ### Simp-normal forms of the structure fields These are expressed in terms of `⇑f` instead of `f.to_fun`. -/ @[simp] lemma map_add (i : ι) (x y : M) : f (update v i (x + y)) = f (update v i x) + f (update v i y) := f.to_multilinear_map.map_add' v i x y @[simp] lemma map_sub (i : ι) (x y : M') : g' (update v' i (x - y)) = g' (update v' i x) - g' (update v' i y) := g'.to_multilinear_map.map_sub v' i x y @[simp] lemma map_neg (i : ι) (x : M') : g' (update v' i (-x)) = -g' (update v' i x) := g'.to_multilinear_map.map_neg v' i x @[simp] lemma map_smul (i : ι) (r : R) (x : M) : f (update v i (r • x)) = r • f (update v i x) := f.to_multilinear_map.map_smul' v i r x @[simp] lemma map_eq_zero_of_eq (v : ι → M) {i j : ι} (h : v i = v j) (hij : i ≠ j) : f v = 0 := f.map_eq_zero_of_eq' v i j h hij @[simp] lemma map_update_zero (m : ι → M) (i : ι) : f (update m i 0) = 0 := f.to_multilinear_map.map_update_zero m i @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero lemma map_eq_zero_of_not_injective (v : ι → M) (hv : ¬function.injective v) : f v = 0 := begin rw function.injective at hv, push_neg at hv, rcases hv with ⟨i₁, i₂, heq, hne⟩, exact f.map_eq_zero_of_eq v heq hne end /-! ### Algebraic structure inherited from `multilinear_map` `alternating_map` carries the same `add_comm_monoid`, `add_comm_group`, and `module` structure as `multilinear_map` -/ section has_scalar variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : has_scalar S (alternating_map R M N ι) := ⟨λ c f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..((c • f : multilinear_map R (λ i : ι, M) N)) }⟩ @[simp] lemma smul_apply (c : S) (m : ι → M) : (c • f) m = c • f m := rfl @[norm_cast] lemma coe_smul (c : S): ((c • f : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = c • f := rfl lemma coe_fn_smul (c : S) (f : alternating_map R M N ι) : ⇑(c • f) = c • f := rfl end has_scalar instance : has_add (alternating_map R M N ι) := ⟨λ a b, { map_eq_zero_of_eq' := λ v i j h hij, by simp [a.map_eq_zero_of_eq v h hij, b.map_eq_zero_of_eq v h hij], ..(a + b : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma add_apply : (f + f') v = f v + f' v := rfl @[norm_cast] lemma coe_add : (↑(f + f') : multilinear_map R (λ i : ι, M) N) = f + f' := rfl instance : has_zero (alternating_map R M N ι) := ⟨{map_eq_zero_of_eq' := λ v i j h hij, by simp, ..(0 : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma zero_apply : (0 : alternating_map R M N ι) v = 0 := rfl @[norm_cast] lemma coe_zero : ((0 : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = 0 := rfl instance : inhabited (alternating_map R M N ι) := ⟨0⟩ instance : add_comm_monoid (alternating_map R M N ι) := coe_injective.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, coe_fn_smul _ _) instance : has_neg (alternating_map R M N' ι) := ⟨λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(-(f : multilinear_map R (λ i : ι, M) N')) }⟩ @[simp] lemma neg_apply (m : ι → M) : (-g) m = -(g m) := rfl @[norm_cast] lemma coe_neg : ((-g : alternating_map R M N' ι) : multilinear_map R (λ i : ι, M) N') = -g := rfl instance : has_sub (alternating_map R M N' ι) := ⟨λ f g, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij, g.map_eq_zero_of_eq v h hij], ..(f - g : multilinear_map R (λ i : ι, M) N') }⟩ @[simp] lemma sub_apply (m : ι → M) : (g - g₂) m = g m - g₂ m := rfl @[norm_cast] lemma coe_sub : (↑(g - g₂) : multilinear_map R (λ i : ι, M) N') = g - g₂ := rfl instance : add_comm_group (alternating_map R M N' ι) := coe_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, coe_fn_smul _ _) (λ _ _, coe_fn_smul _ _) section distrib_mul_action variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : distrib_mul_action S (alternating_map R M N ι) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {S : Type*} [semiring S] [module S N] [smul_comm_class R S N] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module S (alternating_map R M N ι) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } instance [no_zero_smul_divisors S N] : no_zero_smul_divisors S (alternating_map R M N ι) := coe_injective.no_zero_smul_divisors _ rfl coe_fn_smul end module section variables (R N) /-- The evaluation map from `ι → N` to `N` at a given `i` is alternating when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i : ι) : alternating_map R N N ι := { to_fun := function.eval i, map_eq_zero_of_eq' := λ v i j hv hij, (hij $ subsingleton.elim _ _).elim, ..multilinear_map.of_subsingleton R N i } end end alternating_map /-! ### Composition with linear maps -/ namespace linear_map variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] /-- Composing a alternating map with a linear map on the left gives again an alternating map. -/ def comp_alternating_map (g : N →ₗ[R] N₂) : alternating_map R M N ι →+ alternating_map R M N₂ ι := { to_fun := λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(g.comp_multilinear_map (f : multilinear_map R (λ _ : ι, M) N)) }, map_zero' := by { ext, simp }, map_add' := λ a b, by { ext, simp } } @[simp] lemma coe_comp_alternating_map (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) : ⇑(g.comp_alternating_map f) = g ∘ f := rfl lemma comp_alternating_map_apply (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) (m : ι → M) : g.comp_alternating_map f m = g (f m) := rfl end linear_map namespace alternating_map variables {M₂ : Type*} [add_comm_monoid M₂] [module R M₂] variables {M₃ : Type*} [add_comm_monoid M₃] [module R M₃] /-- Composing a alternating map with the same linear map on each argument gives again an alternating map. -/ def comp_linear_map (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : alternating_map R M₂ N ι := { map_eq_zero_of_eq' := λ v i j h hij, f.map_eq_zero_of_eq _ (linear_map.congr_arg h) hij, .. (f : multilinear_map R (λ _ : ι, M) N).comp_linear_map (λ _, g) } lemma coe_comp_linear_map (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : ⇑(f.comp_linear_map g) = f ∘ ((∘) g) := rfl @[simp] lemma comp_linear_map_apply (f : alternating_map R M N ι) (g : M₂ →ₗ[R] M) (v : ι → M₂) : f.comp_linear_map g v = f (λ i, g (v i)) := rfl /-- Composing an alternating map twice with the same linear map in each argument is the same as composing with their composition. -/ lemma comp_linear_map_assoc (f : alternating_map R M N ι) (g₁ : M₂ →ₗ[R] M) (g₂ : M₃ →ₗ[R] M₂) : (f.comp_linear_map g₁).comp_linear_map g₂ = f.comp_linear_map (g₁ ∘ₗ g₂) := rfl @[simp] lemma zero_comp_linear_map (g : M₂ →ₗ[R] M) : (0 : alternating_map R M N ι).comp_linear_map g = 0 := by { ext, simp only [comp_linear_map_apply, zero_apply] } @[simp] lemma add_comp_linear_map (f₁ f₂ : alternating_map R M N ι) (g : M₂ →ₗ[R] M) : (f₁ + f₂).comp_linear_map g = f₁.comp_linear_map g + f₂.comp_linear_map g := by { ext, simp only [comp_linear_map_apply, add_apply] } @[simp] lemma comp_linear_map_zero [nonempty ι] (f : alternating_map R M N ι) : f.comp_linear_map (0 : M₂ →ₗ[R] M) = 0 := begin ext, simp_rw [comp_linear_map_apply, linear_map.zero_apply, ←pi.zero_def, map_zero, zero_apply], end /-- Composing an alternating map with the identity linear map in each argument. -/ @[simp] lemma comp_linear_map_id (f : alternating_map R M N ι) : f.comp_linear_map linear_map.id = f := ext $ λ _, rfl /-- Composing with a surjective linear map is injective. -/ lemma comp_linear_map_injective (f : M₂ →ₗ[R] M) (hf : function.surjective f) : function.injective (λ g : alternating_map R M N ι, g.comp_linear_map f) := λ g₁ g₂ h, ext $ λ x, by simpa [function.surj_inv_eq hf] using ext_iff.mp h (function.surj_inv hf ∘ x) lemma comp_linear_map_inj (f : M₂ →ₗ[R] M) (hf : function.surjective f) (g₁ g₂ : alternating_map R M N ι) : g₁.comp_linear_map f = g₂.comp_linear_map f ↔ g₁ = g₂ := (comp_linear_map_injective _ hf).eq_iff section dom_lcongr variables (ι R N) (S : Type*) [semiring S] [module S N] [smul_comm_class R S N] /-- Construct a linear equivalence between maps from a linear equivalence between domains. -/ @[simps apply] def dom_lcongr (e : M ≃ₗ[R] M₂) : alternating_map R M N ι ≃ₗ[S] alternating_map R M₂ N ι := { to_fun := λ f, f.comp_linear_map e.symm, inv_fun := λ g, g.comp_linear_map e, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, left_inv := λ f, alternating_map.ext $ λ v, f.congr_arg $ funext $ λ i, e.symm_apply_apply _, right_inv := λ f, alternating_map.ext $ λ v, f.congr_arg $ funext $ λ i, e.apply_symm_apply _ } @[simp] lemma dom_lcongr_refl : dom_lcongr R N ι S (linear_equiv.refl R M) = linear_equiv.refl S _ := linear_equiv.ext $ λ _, alternating_map.ext $ λ v, rfl @[simp] lemma dom_lcongr_symm (e : M ≃ₗ[R] M₂) : (dom_lcongr R N ι S e).symm = dom_lcongr R N ι S e.symm := rfl lemma dom_lcongr_trans (e : M ≃ₗ[R] M₂) (f : M₂ ≃ₗ[R] M₃): (dom_lcongr R N ι S e).trans (dom_lcongr R N ι S f) = dom_lcongr R N ι S (e.trans f) := rfl end dom_lcongr /-- Composing an alternating map with the same linear equiv on each argument gives the zero map if and only if the alternating map is the zero map. -/ @[simp] lemma comp_linear_equiv_eq_zero_iff (f : alternating_map R M N ι) (g : M₂ ≃ₗ[R] M) : f.comp_linear_map (g : M₂ →ₗ[R] M) = 0 ↔ f = 0 := (dom_lcongr R N ι ℕ g.symm).map_eq_zero_iff variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! ### Other lemmas from `multilinear_map` -/ section open_locale big_operators lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M) (m : ι → M): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := f.to_multilinear_map.map_update_sum t i g m end /-! ### Theorems specific to alternating maps Various properties of reordered and repeated inputs which follow from `alternating_map.map_eq_zero_of_eq`. -/ lemma map_update_self {i j : ι} (hij : i ≠ j) : f (function.update v i (v j)) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij.symm]) hij lemma map_update_update {i j : ι} (hij : i ≠ j) (m : M) : f (function.update (function.update v i m) j m) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij, function.update_same]) hij lemma map_swap_add {i j : ι} (hij : i ≠ j) : f (v ∘ equiv.swap i j) + f v = 0 := begin rw equiv.comp_swap_eq_update, convert f.map_update_update v hij (v i + v j), simp [f.map_update_self _ hij, f.map_update_self _ hij.symm, function.update_comm hij (v i + v j) (v _) v, function.update_comm hij.symm (v i) (v i) v], end lemma map_add_swap {i j : ι} (hij : i ≠ j) : f v + f (v ∘ equiv.swap i j) = 0 := by { rw add_comm, exact f.map_swap_add v hij } lemma map_swap {i j : ι} (hij : i ≠ j) : g (v ∘ equiv.swap i j) = - g v := eq_neg_of_add_eq_zero (g.map_swap_add v hij) lemma map_perm [fintype ι] (v : ι → M) (σ : equiv.perm ι) : g (v ∘ σ) = σ.sign • g v := begin apply equiv.perm.swap_induction_on' σ, { simp }, { intros s x y hxy hI, simpa [g.map_swap (v ∘ s) hxy, equiv.perm.sign_swap hxy] using hI, } end lemma map_congr_perm [fintype ι] (σ : equiv.perm ι) : g v = σ.sign • g (v ∘ σ) := by { rw [g.map_perm, smul_smul], simp } lemma coe_dom_dom_congr [fintype ι] (σ : equiv.perm ι) : (g : multilinear_map R (λ _ : ι, M) N').dom_dom_congr σ = σ.sign • (g : multilinear_map R (λ _ : ι, M) N') := multilinear_map.ext $ λ v, g.map_perm v σ /-- If the arguments are linearly dependent then the result is `0`. -/ lemma map_linear_dependent {K : Type*} [ring K] {M : Type*} [add_comm_group M] [module K M] {N : Type*} [add_comm_group N] [module K N] [no_zero_smul_divisors K N] (f : alternating_map K M N ι) (v : ι → M) (h : ¬linear_independent K v) : f v = 0 := begin obtain ⟨s, g, h, i, hi, hz⟩ := not_linear_independent_iff.mp h, suffices : f (update v i (g i • v i)) = 0, { rw [f.map_smul, function.update_eq_self, smul_eq_zero] at this, exact or.resolve_left this hz, }, conv at h in (g _ • v _) { rw ←if_t_t (i = x) (g _ • v _), }, rw [finset.sum_ite, finset.filter_eq, finset.filter_ne, if_pos hi, finset.sum_singleton, add_eq_zero_iff_eq_neg] at h, rw [h, f.map_neg, f.map_update_sum, neg_eq_zero, finset.sum_eq_zero], intros j hj, obtain ⟨hij, _⟩ := finset.mem_erase.mp hj, rw [f.map_smul, f.map_update_self _ hij.symm, smul_zero], end end alternating_map open_locale big_operators namespace multilinear_map open equiv variables [fintype ι] private lemma alternization_map_eq_zero_of_eq_aux (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) (i j : ι) (i_ne_j : i ≠ j) (hv : v i = v j) : (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ) v = 0 := begin rw sum_apply, exact finset.sum_involution (λ σ _, swap i j * σ) (λ σ _, by simp [perm.sign_swap i_ne_j, apply_swap_eq_self hv]) (λ σ _ _, (not_congr swap_mul_eq_iff).mpr i_ne_j) (λ σ _, finset.mem_univ _) (λ σ _, swap_mul_involutive i j σ) end /-- Produce an `alternating_map` out of a `multilinear_map`, by summing over all argument permutations. -/ def alternatization : multilinear_map R (λ i : ι, M) N' →+ alternating_map R M N' ι := { to_fun := λ m, { to_fun := ⇑(∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ), map_eq_zero_of_eq' := λ v i j hvij hij, alternization_map_eq_zero_of_eq_aux m v i j hij hvij, .. (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ)}, map_add' := λ a b, begin ext, simp only [ finset.sum_add_distrib, smul_add, add_apply, dom_dom_congr_apply, alternating_map.add_apply, alternating_map.coe_mk, smul_apply, sum_apply], end, map_zero' := begin ext, simp only [ finset.sum_const_zero, smul_zero, zero_apply, dom_dom_congr_apply, alternating_map.zero_apply, alternating_map.coe_mk, smul_apply, sum_apply], end } lemma alternatization_def (m : multilinear_map R (λ i : ι, M) N') : ⇑(alternatization m) = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := rfl lemma alternatization_coe (m : multilinear_map R (λ i : ι, M) N') : ↑m.alternatization = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := coe_injective rfl lemma alternatization_apply (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) : alternatization m v = ∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ v := by simp only [alternatization_def, smul_apply, sum_apply] end multilinear_map namespace alternating_map /-- Alternatizing a multilinear map that is already alternating results in a scale factor of `n!`, where `n` is the number of inputs. -/ lemma coe_alternatization [fintype ι] (a : alternating_map R M N' ι) : (↑a : multilinear_map R (λ ι, M) N').alternatization = nat.factorial (fintype.card ι) • a := begin apply alternating_map.coe_injective, simp_rw [multilinear_map.alternatization_def, coe_dom_dom_congr, smul_smul, int.units_mul_self, one_smul, finset.sum_const, finset.card_univ, fintype.card_perm, ←coe_multilinear_map, coe_smul], end end alternating_map namespace linear_map variables {N'₂ : Type*} [add_comm_group N'₂] [module R N'₂] [fintype ι] /-- Composition with a linear map before and after alternatization are equivalent. -/ lemma comp_multilinear_map_alternatization (g : N' →ₗ[R] N'₂) (f : multilinear_map R (λ _ : ι, M) N') : (g.comp_multilinear_map f).alternatization = g.comp_alternating_map (f.alternatization) := by { ext, simp [multilinear_map.alternatization_def] } end linear_map section coprod open_locale big_operators open_locale tensor_product variables {ιa ιb : Type*} [decidable_eq ιa] [decidable_eq ιb] [fintype ιa] [fintype ιb] variables {R' : Type*} {Mᵢ N₁ N₂ : Type*} [comm_semiring R'] [add_comm_group N₁] [module R' N₁] [add_comm_group N₂] [module R' N₂] [add_comm_monoid Mᵢ] [module R' Mᵢ] namespace equiv.perm /-- Elements which are considered equivalent if they differ only by swaps within α or β -/ abbreviation mod_sum_congr (α β : Type*) := _ ⧸ (equiv.perm.sum_congr_hom α β).range lemma mod_sum_congr.swap_smul_involutive {α β : Type*} [decidable_eq (α ⊕ β)] (i j : α ⊕ β) : function.involutive (has_scalar.smul (equiv.swap i j) : mod_sum_congr α β → mod_sum_congr α β) := λ σ, begin apply σ.induction_on' (λ σ, _), exact _root_.congr_arg quotient.mk' (equiv.swap_mul_involutive i j σ) end end equiv.perm namespace alternating_map open equiv /-- summand used in `alternating_map.dom_coprod` -/ def dom_coprod.summand (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗[R'] N₂) := quotient.lift_on' σ (λ σ, σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ) (λ σ₁ σ₂ ⟨⟨sl, sr⟩, h⟩, begin ext v, simp only [multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, coe_multilinear_map, multilinear_map.smul_apply], replace h := inv_mul_eq_iff_eq_mul.mp h.symm, have : (σ₁ * perm.sum_congr_hom _ _ (sl, sr)).sign = σ₁.sign * (sl.sign * sr.sign) := by simp, rw [h, this, mul_smul, mul_smul, smul_left_cancel_iff, ←tensor_product.tmul_smul, tensor_product.smul_tmul'], simp only [sum.map_inr, perm.sum_congr_hom_apply, perm.sum_congr_apply, sum.map_inl, function.comp_app, perm.coe_mul], rw [←a.map_congr_perm (λ i, v (σ₁ _)), ←b.map_congr_perm (λ i, v (σ₁ _))], end) lemma dom_coprod.summand_mk' (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : equiv.perm (ιa ⊕ ιb)) : dom_coprod.summand a b (quotient.mk' σ) = σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ := rfl /-- Swapping elements in `σ` with equal values in `v` results in an addition that cancels -/ lemma dom_coprod.summand_add_swap_smul_eq_zero (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : dom_coprod.summand a b σ v + dom_coprod.summand a b (swap i j • σ) v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', mul_action.quotient.smul_mk, dom_coprod.summand], rw [perm.sign_mul, perm.sign_swap hij], simp only [one_mul, neg_mul, function.comp_app, units.neg_smul, perm.coe_mul, units.coe_neg, multilinear_map.smul_apply, multilinear_map.neg_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply], convert add_right_neg _; { ext k, rw equiv.apply_swap_eq_self hv }, end /-- Swapping elements in `σ` with equal values in `v` result in zero if the swap has no effect on the quotient. -/ lemma dom_coprod.summand_eq_zero_of_smul_invariant (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : swap i j • σ = σ → dom_coprod.summand a b σ v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', multilinear_map.smul_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, dom_coprod.summand], intro hσ, with_cases { cases hi : σ⁻¹ i; cases hj : σ⁻¹ j; rw perm.inv_eq_iff_eq at hi hj; substs hi hj, }, case [sum.inl sum.inr : i' j', sum.inr sum.inl : i' j'] { -- the term pairs with and cancels another term all_goals { obtain ⟨⟨sl, sr⟩, hσ⟩ := quotient.exact' hσ, }, work_on_goal 1 { replace hσ := equiv.congr_fun hσ (sum.inl i'), }, work_on_goal 2 { replace hσ := equiv.congr_fun hσ (sum.inr i'), }, all_goals { rw [←equiv.mul_swap_eq_swap_mul, mul_inv_rev, equiv.swap_inv, inv_mul_cancel_right] at hσ, simpa using hσ, }, }, case [sum.inr sum.inr : i' j', sum.inl sum.inl : i' j'] { -- the term does not pair but is zero all_goals { convert smul_zero _, }, work_on_goal 1 { convert tensor_product.tmul_zero _ _, }, work_on_goal 2 { convert tensor_product.zero_tmul _ _, }, all_goals { exact alternating_map.map_eq_zero_of_eq _ _ hv (λ hij', hij (hij' ▸ rfl)), } }, end /-- Like `multilinear_map.dom_coprod`, but ensures the result is also alternating. Note that this is usually defined (for instance, as used in Proposition 22.24 in [Gallier2011Notes]) over integer indices `ιa = fin n` and `ιb = fin m`, as $$ (f \wedge g)(u_1, \ldots, u_{m+n}) = \sum_{\operatorname{shuffle}(m, n)} \operatorname{sign}(\sigma) f(u_{\sigma(1)}, \ldots, u_{\sigma(m)}) g(u_{\sigma(m+1)}, \ldots, u_{\sigma(m+n)}), $$ where $\operatorname{shuffle}(m, n)$ consists of all permutations of $[1, m+n]$ such that $\sigma(1) < \cdots < \sigma(m)$ and $\sigma(m+1) < \cdots < \sigma(m+n)$. Here, we generalize this by replacing: * the product in the sum with a tensor product * the filtering of $[1, m+n]$ to shuffles with an isomorphic quotient * the additions in the subscripts of $\sigma$ with an index of type `sum` The specialized version can be obtained by combining this definition with `fin_sum_fin_equiv` and `algebra.lmul'`. -/ @[simps] def dom_coprod (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := { to_fun := λ v, ⇑(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) v, map_eq_zero_of_eq' := λ v i j hv hij, begin dsimp only, rw multilinear_map.sum_apply, exact finset.sum_involution (λ σ _, equiv.swap i j • σ) (λ σ _, dom_coprod.summand_add_swap_smul_eq_zero a b σ hv hij) (λ σ _, mt $ dom_coprod.summand_eq_zero_of_smul_invariant a b σ hv hij) (λ σ _, finset.mem_univ _) (λ σ _, equiv.perm.mod_sum_congr.swap_smul_involutive i j σ), end, ..(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) } lemma dom_coprod_coe (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (↑(a.dom_coprod b) : multilinear_map R' (λ _, Mᵢ) _) = ∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ := multilinear_map.ext $ λ _, rfl /-- A more bundled version of `alternating_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : (alternating_map R' Mᵢ N₁ ιa ⊗[R'] alternating_map R' Mᵢ N₂ ιb) →ₗ[R'] alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := tensor_product.lift $ by refine linear_map.mk₂ R' (dom_coprod) (λ m₁ m₂ n, _) (λ c m n, _) (λ m n₁ n₂, _) (λ c m n, _); { ext, simp only [dom_coprod_apply, add_apply, smul_apply, ←finset.sum_add_distrib, finset.smul_sum, multilinear_map.sum_apply, dom_coprod.summand], congr, ext σ, apply σ.induction_on' (λ σ, _), simp only [quotient.lift_on'_mk', coe_add, coe_smul, multilinear_map.smul_apply, ←multilinear_map.dom_coprod'_apply], simp only [tensor_product.add_tmul, ←tensor_product.smul_tmul', tensor_product.tmul_add, tensor_product.tmul_smul, linear_map.map_add, linear_map.map_smul], rw ←smul_add <|> rw smul_comm, congr } @[simp] lemma dom_coprod'_apply (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : dom_coprod' (a ⊗ₜ[R'] b) = dom_coprod a b := by simp only [dom_coprod', tensor_product.lift.tmul, linear_map.mk₂_apply] end alternating_map open equiv /-- A helper lemma for `multilinear_map.dom_coprod_alternization`. -/ lemma multilinear_map.dom_coprod_alternization_coe (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : multilinear_map.dom_coprod ↑a.alternatization ↑b.alternatization = ∑ (σa : perm ιa) (σb : perm ιb), σa.sign • σb.sign • multilinear_map.dom_coprod (a.dom_dom_congr σa) (b.dom_dom_congr σb) := begin simp_rw [←multilinear_map.dom_coprod'_apply, multilinear_map.alternatization_coe], simp_rw [tensor_product.sum_tmul, tensor_product.tmul_sum, linear_map.map_sum, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower], end open alternating_map /-- Computing the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` is the same as computing the `alternating_map.dom_coprod` of the `multilinear_map.alternatization`s. -/ lemma multilinear_map.dom_coprod_alternization (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : (multilinear_map.dom_coprod a b).alternatization = a.alternatization.dom_coprod b.alternatization := begin apply coe_multilinear_map_injective, rw [dom_coprod_coe, multilinear_map.alternatization_coe, finset.sum_partition (quotient_group.left_rel (perm.sum_congr_hom ιa ιb).range)], congr' 1, ext1 σ, apply σ.induction_on' (λ σ, _), -- unfold the quotient mess left by `finset.sum_partition` conv in (_ = quotient.mk' _) { change quotient.mk' _ = quotient.mk' _, rw quotient.eq', rw [quotient_group.left_rel], dsimp only [setoid.r] }, -- eliminate a multiplication have : @finset.univ (perm (ιa ⊕ ιb)) _ = finset.univ.image ((*) σ) := (finset.eq_univ_iff_forall.mpr $ λ a, let ⟨a', ha'⟩ := mul_left_surjective σ a in finset.mem_image.mpr ⟨a', finset.mem_univ _, ha'⟩).symm, rw [this, finset.image_filter], simp only [function.comp, mul_inv_rev, inv_mul_cancel_right, subgroup.inv_mem_iff], simp only [monoid_hom.mem_range], -- needs to be separate from the above `simp only` rw [finset.filter_congr_decidable, finset.univ_filter_exists (perm.sum_congr_hom ιa ιb), finset.sum_image (λ x _ y _ (h : _ = _), mul_right_injective _ h), finset.sum_image (λ x _ y _ (h : _ = _), perm.sum_congr_hom_injective h)], dsimp only, -- now we're ready to clean up the RHS, pulling out the summation rw [dom_coprod.summand_mk', multilinear_map.dom_coprod_alternization_coe, ←finset.sum_product', finset.univ_product_univ, ←multilinear_map.dom_dom_congr_equiv_apply, add_equiv.map_sum, finset.smul_sum], congr' 1, ext1 ⟨al, ar⟩, dsimp only, -- pull out the pair of smuls on the RHS, by rewriting to `_ →ₗ[ℤ] _` and back rw [←add_equiv.coe_to_add_monoid_hom, ←add_monoid_hom.coe_to_int_linear_map, linear_map.map_smul_of_tower, linear_map.map_smul_of_tower, add_monoid_hom.coe_to_int_linear_map, add_equiv.coe_to_add_monoid_hom, multilinear_map.dom_dom_congr_equiv_apply], -- pick up the pieces rw [multilinear_map.dom_dom_congr_mul, perm.sign_mul, perm.sum_congr_hom_apply, multilinear_map.dom_coprod_dom_dom_congr_sum_congr, perm.sign_sum_congr, mul_smul, mul_smul], end /-- Taking the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` of two `alternating_map`s gives a scaled version of the `alternating_map.coprod` of those maps. -/ lemma multilinear_map.dom_coprod_alternization_eq (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (multilinear_map.dom_coprod a b : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗ N₂)) .alternatization = ((fintype.card ιa).factorial * (fintype.card ιb).factorial) • a.dom_coprod b := begin rw [multilinear_map.dom_coprod_alternization, coe_alternatization, coe_alternatization, mul_smul, ←dom_coprod'_apply, ←dom_coprod'_apply, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower dom_coprod', linear_map.map_smul_of_tower dom_coprod'], -- typeclass resolution is a little confused here apply_instance, apply_instance, end end coprod section basis open alternating_map variables {ι₁ : Type*} [fintype ι] variables {R' : Type*} {N₁ N₂ : Type*} [comm_semiring R'] [add_comm_monoid N₁] [add_comm_monoid N₂] variables [module R' N₁] [module R' N₂] /-- Two alternating maps indexed by a `fintype` are equal if they are equal when all arguments are distinct basis vectors. -/ lemma basis.ext_alternating {f g : alternating_map R' N₁ N₂ ι} (e : basis ι₁ R' N₁) (h : ∀ v : ι → ι₁, function.injective v → f (λ i, e (v i)) = g (λ i, e (v i))) : f = g := begin refine alternating_map.coe_multilinear_map_injective (basis.ext_multilinear e $ λ v, _), by_cases hi : function.injective v, { exact h v hi }, { have : ¬function.injective (λ i, e (v i)) := hi.imp function.injective.of_comp, rw [coe_multilinear_map, coe_multilinear_map, f.map_eq_zero_of_not_injective _ this, g.map_eq_zero_of_not_injective _ this], } end end basis
State Before: k : Type u₁ G : Type u₂ R : Type ?u.366813 inst✝¹ : Semiring k inst✝ : Monoid G a : G b : k ⊢ single a b ^ 0 = single (a ^ 0) (b ^ 0) State After: k : Type u₁ G : Type u₂ R : Type ?u.366813 inst✝¹ : Semiring k inst✝ : Monoid G a : G b : k ⊢ 1 = single 1 1 Tactic: simp only [pow_zero] State Before: k : Type u₁ G : Type u₂ R : Type ?u.366813 inst✝¹ : Semiring k inst✝ : Monoid G a : G b : k ⊢ 1 = single 1 1 State After: no goals Tactic: rfl State Before: k : Type u₁ G : Type u₂ R : Type ?u.366813 inst✝¹ : Semiring k inst✝ : Monoid G a : G b : k n : ℕ ⊢ single a b ^ (n + 1) = single (a ^ (n + 1)) (b ^ (n + 1)) State After: no goals Tactic: simp only [pow_succ, single_pow n, single_mul_single]
The square of the norm of a complex number is equal to the product of the complex number with its complex conjugate.
function ivec = s_to_i4vec ( s, n ) %*****************************************************************************80 % %% S_TO_I4VEC reads a integer vector from a string. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 19 June 2006 % % Author: % % John Burkardt % % Parameters: % % Input, character S(*), the string to be read. % % Input, integer N, the number of values expected. % % Output, integer IVEC(N), the values read from the string. % i = 0; ivec = []; ilo = 1; while ( i < n ) i = i + 1; [ ivec(i), lchar ] = s_to_i4 ( s(ilo:end) ); ilo = ilo + lchar; end return end
lemma ball_subset_cball_iff: "ball a r \<subseteq> cball a' r' \<longleftrightarrow> dist a a' + r \<le> r' \<or> r \<le> 0" (is "?lhs = ?rhs") for a :: "'a::euclidean_space"
#include <boost/mpl/aux_/preprocessed/no_ttp/fold_impl.hpp>
------------------------------------------------------------------------ -- The Agda standard library -- -- The lifting of a strict order to incorporate a new supremum ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} -- This module is designed to be used with -- Relation.Nullary.Construct.Add.Supremum open import Relation.Binary module Relation.Binary.Construct.Add.Supremum.Strict {a r} {A : Set a} (_<_ : Rel A r) where open import Level using (_⊔_) open import Data.Product open import Function open import Relation.Nullary import Relation.Nullary.Decidable as Dec import Relation.Binary.PropositionalEquality as P open import Relation.Nullary.Construct.Add.Supremum import Relation.Binary.Construct.Add.Supremum.Equality as Equality import Relation.Binary.Construct.Add.Supremum.NonStrict as NonStrict ------------------------------------------------------------------------ -- Definition infix 4 _<⁺_ data _<⁺_ : Rel (A ⁺) (a ⊔ r) where [_] : {k l : A} → k < l → [ k ] <⁺ [ l ] [_]<⊤⁺ : (k : A) → [ k ] <⁺ ⊤⁺ ------------------------------------------------------------------------ -- Relational properties [<]-injective : ∀ {k l} → [ k ] <⁺ [ l ] → k < l [<]-injective [ p ] = p <⁺-asym : Asymmetric _<_ → Asymmetric _<⁺_ <⁺-asym <-asym [ p ] [ q ] = <-asym p q <⁺-asym <-asym [ k ]<⊤⁺ () <⁺-trans : Transitive _<_ → Transitive _<⁺_ <⁺-trans <-trans [ p ] [ q ] = [ <-trans p q ] <⁺-trans <-trans [ p ] [ k ]<⊤⁺ = [ _ ]<⊤⁺ <⁺-dec : Decidable _<_ → Decidable _<⁺_ <⁺-dec _<?_ [ k ] [ l ] = Dec.map′ [_] [<]-injective (k <? l) <⁺-dec _<?_ [ k ] ⊤⁺ = yes [ k ]<⊤⁺ <⁺-dec _<?_ ⊤⁺ [ l ] = no (λ ()) <⁺-dec _<?_ ⊤⁺ ⊤⁺ = no (λ ()) <⁺-irrelevant : Irrelevant _<_ → Irrelevant _<⁺_ <⁺-irrelevant <-irr [ p ] [ q ] = P.cong _ (<-irr p q) <⁺-irrelevant <-irr [ k ]<⊤⁺ [ k ]<⊤⁺ = P.refl module _ {e} {_≈_ : Rel A e} where open Equality _≈_ <⁺-cmp : Trichotomous _≈_ _<_ → Trichotomous _≈⁺_ _<⁺_ <⁺-cmp <-cmp ⊤⁺ ⊤⁺ = tri≈ (λ ()) ⊤⁺≈⊤⁺ (λ ()) <⁺-cmp <-cmp ⊤⁺ [ l ] = tri> (λ ()) (λ ()) [ l ]<⊤⁺ <⁺-cmp <-cmp [ k ] ⊤⁺ = tri< [ k ]<⊤⁺ (λ ()) (λ ()) <⁺-cmp <-cmp [ k ] [ l ] with <-cmp k l ... | tri< a ¬b ¬c = tri< [ a ] (¬b ∘ [≈]-injective) (¬c ∘ [<]-injective) ... | tri≈ ¬a b ¬c = tri≈ (¬a ∘ [<]-injective) [ b ] (¬c ∘ [<]-injective) ... | tri> ¬a ¬b c = tri> (¬a ∘ [<]-injective) (¬b ∘ [≈]-injective) [ c ] <⁺-irrefl : Irreflexive _≈_ _<_ → Irreflexive _≈⁺_ _<⁺_ <⁺-irrefl <-irrefl [ p ] [ q ] = <-irrefl p q <⁺-irrefl <-irrefl ⊤⁺≈⊤⁺ () <⁺-respˡ-≈⁺ : _<_ Respectsˡ _≈_ → _<⁺_ Respectsˡ _≈⁺_ <⁺-respˡ-≈⁺ <-respˡ-≈ [ p ] [ q ] = [ <-respˡ-≈ p q ] <⁺-respˡ-≈⁺ <-respˡ-≈ [ p ] ([ l ]<⊤⁺) = [ _ ]<⊤⁺ <⁺-respˡ-≈⁺ <-respˡ-≈ ⊤⁺≈⊤⁺ q = q <⁺-respʳ-≈⁺ : _<_ Respectsʳ _≈_ → _<⁺_ Respectsʳ _≈⁺_ <⁺-respʳ-≈⁺ <-respʳ-≈ [ p ] [ q ] = [ <-respʳ-≈ p q ] <⁺-respʳ-≈⁺ <-respʳ-≈ ⊤⁺≈⊤⁺ q = q <⁺-resp-≈⁺ : _<_ Respects₂ _≈_ → _<⁺_ Respects₂ _≈⁺_ <⁺-resp-≈⁺ = map <⁺-respʳ-≈⁺ <⁺-respˡ-≈⁺ module _ {r} {_≤_ : Rel A r} where open NonStrict _≤_ <⁺-transʳ : Trans _≤_ _<_ _<_ → Trans _≤⁺_ _<⁺_ _<⁺_ <⁺-transʳ <-transʳ [ p ] [ q ] = [ <-transʳ p q ] <⁺-transʳ <-transʳ [ p ] [ k ]<⊤⁺ = [ _ ]<⊤⁺ <⁺-transˡ : Trans _<_ _≤_ _<_ → Trans _<⁺_ _≤⁺_ _<⁺_ <⁺-transˡ <-transˡ [ p ] [ q ] = [ <-transˡ p q ] <⁺-transˡ <-transˡ [ p ] ([ _ ] ≤⊤⁺) = [ _ ]<⊤⁺ <⁺-transˡ <-transˡ [ k ]<⊤⁺ (⊤⁺ ≤⊤⁺) = [ k ]<⊤⁺ ------------------------------------------------------------------------ -- Structures module _ {e} {_≈_ : Rel A e} where open Equality _≈_ <⁺-isStrictPartialOrder : IsStrictPartialOrder _≈_ _<_ → IsStrictPartialOrder _≈⁺_ _<⁺_ <⁺-isStrictPartialOrder strict = record { isEquivalence = ≈⁺-isEquivalence isEquivalence ; irrefl = <⁺-irrefl irrefl ; trans = <⁺-trans trans ; <-resp-≈ = <⁺-resp-≈⁺ <-resp-≈ } where open IsStrictPartialOrder strict <⁺-isDecStrictPartialOrder : IsDecStrictPartialOrder _≈_ _<_ → IsDecStrictPartialOrder _≈⁺_ _<⁺_ <⁺-isDecStrictPartialOrder dectot = record { isStrictPartialOrder = <⁺-isStrictPartialOrder isStrictPartialOrder ; _≟_ = ≈⁺-dec _≟_ ; _<?_ = <⁺-dec _<?_ } where open IsDecStrictPartialOrder dectot <⁺-isStrictTotalOrder : IsStrictTotalOrder _≈_ _<_ → IsStrictTotalOrder _≈⁺_ _<⁺_ <⁺-isStrictTotalOrder strictot = record { isEquivalence = ≈⁺-isEquivalence isEquivalence ; trans = <⁺-trans trans ; compare = <⁺-cmp compare } where open IsStrictTotalOrder strictot
Yue lives in a shed by his grave through the winter and in the second lunar month of the following year , his martial brothers come and pull the building down , forcing him to return home and take care of his mother .
import numpy as np import tensorflow as tf from VFF.matrix_structures import DiagMat, Rank1Mat, LowRankMat, BlockDiagMat from unittest import TestCase np.random.seed(0) class TestDiagMats(TestCase): def setUp(self): self.N = 20 self.d_np = np.random.rand(self.N) + 0.1 self.A_np = np.diag(self.d_np) self.d_tf = tf.convert_to_tensor(self.d_np) self.mat = DiagMat(self.d_tf) def test_get(self): A_tf = self.mat.get() np.testing.assert_allclose(A_tf, self.A_np) def test_logdet(self): logdet_tf = self.mat.logdet() _, logdet_np = np.linalg.slogdet(self.A_np) np.testing.assert_allclose(logdet_tf, logdet_np) def test_matmul(self): B = np.random.randn(self.N, self.N + 2) AB_tf = self.mat.matmul(B) np.testing.assert_allclose(AB_tf, np.dot(self.A_np, B)) def test_solve(self): B = np.random.randn(self.N, self.N + 2) AiB_tf = self.mat.solve(B) np.testing.assert_allclose(AiB_tf, np.linalg.solve(self.A_np, B)) def test_trace_KiX(self): B = np.random.randn(self.N, self.N) tr_AiB_tf = self.mat.trace_KiX(B) np.testing.assert_allclose(tr_AiB_tf, np.trace(np.linalg.solve(self.A_np, B))) def test_trace_KiX_against_solve(self): B = np.random.randn(self.N, self.N) tr_AiB_tf = self.mat.trace_KiX(B) tr_AiB_tf2 = tf.reduce_sum(tf.linalg.diag_part(self.mat.solve(B))) np.testing.assert_allclose(tr_AiB_tf, tr_AiB_tf2) def test_get_diag(self): d_tf = self.mat.get_diag() np.testing.assert_allclose(d_tf, np.diag(self.A_np)) def test_inv_diag(self): di_tf = self.mat.inv_diag() np.testing.assert_allclose(di_tf, np.diag(np.linalg.inv(self.A_np))) class TestR1Mat(TestDiagMats): def setUp(self): self.N = 20 self.d_np = np.random.rand(self.N) + 0.1 self.v_np = np.random.randn(self.N) self.A_np = np.diag(self.d_np) + self.v_np[:, None] * self.v_np[None, :] self.d_tf = tf.convert_to_tensor(self.d_np) self.v_tf = tf.convert_to_tensor(self.v_np) self.mat = Rank1Mat(self.d_tf, self.v_tf) class TestLRMat(TestDiagMats): def setUp(self): self.N = 20 self.d_np = np.random.rand(self.N) + 0.1 self.W_np = np.random.randn(self.N, 2) self.A_np = np.diag(self.d_np) + np.dot(self.W_np, self.W_np.T) self.d_tf = tf.convert_to_tensor(self.d_np) self.W_tf = tf.convert_to_tensor(self.W_np) self.mat = LowRankMat(self.d_tf, self.W_tf) class TestBlockMat(TestDiagMats): def setUp(self): self.N1, self.N2 = 20, 30 self.N = self.N1 + self.N2 self.d1_np, self.d2_np = np.random.rand(self.N1) + 0.1, np.random.rand(self.N2) + 0.1 self.W1_np = np.random.randn(self.N1, 2) self.W2_np = np.random.randn(self.N2, 2) self.A1_np = np.diag(self.d1_np) + np.dot(self.W1_np, self.W1_np.T) self.A2_np = np.diag(self.d2_np) + np.dot(self.W2_np, self.W2_np.T) self.A_np = np.vstack( [ np.hstack([self.A1_np, np.zeros([self.N1, self.N2])]), np.hstack([np.zeros([self.N2, self.N1]), self.A2_np]), ] ) self.d1_tf = tf.convert_to_tensor(self.d1_np) self.W1_tf = tf.convert_to_tensor(self.W1_np) self.d2_tf = tf.convert_to_tensor(self.d2_np) self.W2_tf = tf.convert_to_tensor(self.W2_np) self.mat = BlockDiagMat( LowRankMat(self.d1_tf, self.W1_tf), LowRankMat(self.d2_tf, self.W2_tf) )
SUBROUTINE IJKGDS0(IGDTNUM,IGDTMPL,IGDTLEN,IJKGDSA) !$$$ SUBPROGRAM DOCUMENTATION BLOCK ! ! $Revision: 74685 $ ! ! SUBPROGRAM: IJKGDS0 SET UP PARAMETERS FOR FUNCTION IJKGDS1 ! PRGMMR: IREDELL ORG: W/NMC23 DATE: 96-04-10 ! ! ABSTRACT: THIS SUBPROGRAM DECODES THE GRIB 2 GRID DEFINITION TEMPLATE ! AND RETURNS A NAVIGATION PARAMETER ARRAY TO ALLOW FUNCTION ! IJKGDS1 TO DECODE THE FIELD POSITION FOR A GIVEN GRID POINT. ! ! PROGRAM HISTORY LOG: ! 96-04-10 IREDELL ! 97-03-11 IREDELL ALLOWED HEMISPHERIC GRIDS TO WRAP OVER ONE POLE ! 98-07-13 BALDWIN ADD 2D STAGGERED ETA GRID INDEXING (203) ! 1999-04-08 IREDELL SPLIT IJKGDS INTO TWO ! 2015-01-27 GAYNO REMOVE REFERENCES TO OBSOLETE NCEP GRIDS 201 ! AND 202. ! 2015-07-13 GAYNO CONVERT TO GRIB 2. REPLACE GRIB 1 KGDS ARRAY ! WITH GRIB 2 GRID DEFINITION TEMPLATE ARRAY. ! ! USAGE: CALL IJKGDS0(IGDTNUM,IGDTMPL,IGDTLEN,IJKGDSA) ! ! INPUT ARGUMENT LIST: ! IGDTNUM - INTEGER GRID DEFINITION TEMPLATE NUMBER. ! CORRESPONDS TO THE GFLD%IGDTNUM COMPONENT OF THE ! NCEP G2 LIBRARY GRIDMOD DATA STRUCTURE: ! 00 - EQUIDISTANT CYLINDRICAL ! 01 - ROTATED EQUIDISTANT CYLINDRICAL. "E" ! AND NON-"E" STAGGERED ! 10 - MERCATOR CYCLINDRICAL ! 20 - POLAR STEREOGRAPHIC AZIMUTHAL ! 30 - LAMBERT CONFORMAL CONICAL ! 40 - GAUSSIAN EQUIDISTANT CYCLINDRICAL ! IGDTMPL - INTEGER (IGDTLEN) GRID DEFINITION TEMPLATE ARRAY. ! CORRESPONDS TO THE GFLD%IGDTMPL COMPONENT ! OF THE NCEP G2 LIBRARY GRIDMOD DATA STRUCTURE ! (SECTION 3 INFO): ! ALL PROJECTIONS: ! (1): SHAPE OF EARTH, OCTET 15 ! (2): SCALE FACTOR OF SPHERICAL EARTH RADIUS, ! OCTET 16 ! (3): SCALED VALUE OF RADIUS OF SPHERICAL EARTH, ! OCTETS 17-20 ! (4): SCALE FACTOR OF MAJOR AXIS OF ELLIPTICAL EARTH, ! OCTET 21 ! (5): SCALED VALUE OF MAJOR AXIS OF ELLIPTICAL EARTH, ! OCTETS 22-25 ! (6): SCALE FACTOR OF MINOR AXIS OF ELLIPTICAL EARTH, ! OCTET 26 ! (7): SCALED VALUE OF MINOR AXIS OF ELLIPTICAL EARTH, ! OCTETS 27-30 ! EQUIDISTANT CYCLINDRICAL: ! (8): NUMBER OF POINTS ALONG A PARALLEL, OCTS 31-34 ! (9): NUMBER OF POINTS ALONG A MERIDIAN, OCTS 35-38 ! (10): BASIC ANGLE OF INITIAL PRODUCTION DOMAIN, ! OCTETS 39-42. ! (11): SUBDIVISIONS OF BASIC ANGLE, OCTETS 43-46 ! (12): LATITUDE OF FIRST GRID POINT, OCTETS 47-50 ! (13): LONGITUDE OF FIRST GRID POINT, OCTETS 51-54 ! (14): RESOLUTION AND COMPONENT FLAGS, OCTET 55 ! (15): LATITUDE OF LAST GRID POINT, OCTETS 56-59 ! (16): LONGITUDE OF LAST GRID POINT, OCTETS 60-63 ! (17): I-DIRECTION INCREMENT, OCTETS 64-67 ! (18): J-DIRECTION INCREMENT, OCTETS 68-71 ! (19): SCANNING MODE, OCTET 72 ! MERCATOR CYCLINDRICAL: ! (8): NUMBER OF POINTS ALONG A PARALLEL, OCTS 31-34 ! (9): NUMBER OF POINTS ALONG A MERIDIAN, OCTS 35-38 ! (10): LATITUDE OF FIRST POINT, OCTETS 39-42 ! (11): LONGITUDE OF FIRST POINT, OCTETS 43-46 ! (12): RESOLUTION AND COMPONENT FLAGS, OCTET 47 ! (13): TANGENT LATITUDE, OCTETS 48-51 ! (14): LATITUDE OF LAST POINT, OCTETS 52-55 ! (15): LONGITUDE OF LAST POINT, OCTETS 56-59 ! (16): SCANNING MODE FLAGS, OCTET 60 ! (17): ORIENTATION OF GRID, OCTETS 61-64 ! (18): LONGITUDINAL GRID LENGTH, OCTETS 65-68 ! (19): LATITUDINAL GRID LENGTH, OCTETS 69-72 ! LAMBERT CONFORMAL CONICAL: ! (8): NUMBER OF POINTS ALONG X-AXIS, OCTS 31-34 ! (9): NUMBER OF POINTS ALONG Y-AXIS, OCTS 35-38 ! (10): LATITUDE OF FIRST POINT, OCTETS 39-42 ! (11): LONGITUDE OF FIRST POINT, OCTETS 43-46 ! (12): RESOLUTION OF COMPONENT FLAG, OCTET 47 ! (13): LATITUDE WHERE GRID LENGTHS SPECIFIED, ! OCTETS 48-51 ! (14): LONGITUDE OF MERIDIAN THAT IS PARALLEL TO ! Y-AXIS, OCTETS 52-55 ! (15): X-DIRECTION GRID LENGTH, OCTETS 56-59 ! (16): Y-DIRECTION GRID LENGTH, OCTETS 60-63 ! (17): PROJECTION CENTER FLAG, OCTET 64 ! (18): SCANNING MODE, OCTET 65 ! (19): FIRST TANGENT LATITUDE FROM POLE, OCTETS 66-69 ! (20): SECOND TANGENT LATITUDE FROM POLE, OCTETS 70-73 ! (21): LATITUDE OF SOUTH POLE OF PROJECTION, ! OCTETS 74-77 ! (22): LONGITUDE OF SOUTH POLE OF PROJECTION, ! OCTETS 78-81 ! GAUSSIAN CYLINDRICAL: ! (8): NUMBER OF POINTS ALONG A PARALLEL, OCTS 31-34 ! (9): NUMBER OF POINTS ALONG A MERIDIAN, OCTS 35-38 ! (10): BASIC ANGLE OF INITIAL PRODUCTION DOMAIN, ! OCTETS 39-42 ! (11): SUBDIVISIONS OF BASIC ANGLE, OCTETS 43-46 ! (12): LATITUDE OF FIRST GRID POINT, OCTETS 47-50 ! (13): LONGITUDE OF FIRST GRID POINT, OCTETS 51-54 ! (14): RESOLUTION AND COMPONENT FLAGS, OCTET 55 ! (15): LATITUDE OF LAST GRID POINT, OCTETS 56-59 ! (16): LONGITUDE OF LAST GRID POINT, OCTETS 60-63 ! (17): I-DIRECTION INCREMENT, OCTETS 64-67 ! (18): NUMBER OF PARALLELS BETWEEN POLE AND EQUATOR, ! OCTETS 68-71 ! (19): SCANNING MODE, OCTET 72 ! POLAR STEREOGRAPHIC AZIMUTHAL: ! (8): NUMBER OF POINTS ALONG X-AXIS, OCTETS 31-34 ! (9): NUMBER OF POINTS ALONG Y-AXIS, OCTETS 35-38 ! (10): LATITUDE OF FIRST GRID POINT, OCTETS 39-42 ! (11): LONGITUDE OF FIRST GRID POINT, OCTETS 43-46 ! (12): RESOLUTION AND COMPONENT FLAGS, OCTET 47 ! (13): TRUE LATITUDE, OCTETS 48-51 ! (14): ORIENTATION LONGITUDE, OCTETS 52-55 ! (15): X-DIRECTION GRID LENGTH, OCTETS 56-59 ! (16): Y-DIRECTION GRID LENGTH, OCTETS 60-63 ! (17): PROJECTION CENTER FLAG, OCTET 64 ! (18): SCANNING MODE FLAGS, OCTET 65 ! ROTATED EQUIDISTANT CYCLINDRICAL: ! (8): NUMBER OF POINTS ALONG A PARALLEL, OCTS 31-34 ! (9): NUMBER OF POINTS ALONG A MERIDIAN, OCTS 35-38 ! (10): BASIC ANGLE OF INITIAL PRODUCTION DOMAIN, ! OCTETS 39-42 ! (11): SUBDIVISIONS OF BASIC ANGLE, OCTETS 43-46 ! (12): LATITUDE OF FIRST GRID POINT, OCTETS 47-50 ! (13): LONGITUDE OF FIRST GRID POINT, OCTETS 51-54 ! (14): RESOLUTION AND COMPONENT FLAGS, OCTET 55 ! (15): LATITUDE OF LAST GRID POINT, OCTETS 56-59 ! (16): LONGITUDE OF LAST GRID POINT, OCTETS 60-63 ! (17): I-DIRECTION INCREMENT, OCTETS 64-67 ! (18): J-DIRECTION INCREMENT, OCTETS 68-71 ! (19): SCANNING MODE, OCTET 72 ! (20): LATITUDE OF SOUTHERN POLE OF PROJECTION, ! OCTETS 73-76 ! (21): LONGITUDE OF SOUTHERN POLE OF PROJECTION, ! OCTETS 77-80 ! (22): ANGLE OF ROTATION OF PROJECTION, OCTS 81-84 ! IGDTLEN - INTEGER NUMBER OF ELEMENTS OF THE GRID DEFINITION ! TEMPLATE ARRAY. CORRESPONDS TO THE GFLD%IGDTLEN ! COMPONENT OF THE NCEP G2 LIBRARY GRIDMOD DATA STRUCTURE. ! ! OUTPUT ARGUMENT LIST: ! IJKGDSA - INTEGER (20) NAVIGATION PARAMETER ARRAY ! IJKGDSA(1) IS NUMBER OF X POINTS ! IJKGDSA(2) IS NUMBER OF Y POINTS ! IJKGDSA(3) IS X WRAPAROUND INCREMENT ! (0 IF NO WRAPAROUND) ! IJKGDSA(4) IS Y WRAPAROUND LOWER PIVOT POINT ! (0 IF NO WRAPAROUND) ! IJKGDSA(5) IS Y WRAPAROUND UPPER PIVOT POINT ! (0 IF NO WRAPAROUND) ! IJKGDSA(6) IS SCANNING MODE ! (0 IF X FIRST THEN Y; 1 IF Y FIRST THEN X; ! 3 IF STAGGERED DIAGONAL LIKE ARAKAWA "E") ! IJKGDSA(7) IS MASS/WIND FLAG FOR STAGGERED DIAGONAL ! (0 IF MASS; 1 IF WIND) ! IJKGDSA(8:20) ARE UNUSED AT THE MOMENT ! ! ATTRIBUTES: ! LANGUAGE: FORTRAN 90 ! !$$$ IMPLICIT NONE ! INTEGER, INTENT(IN ) :: IGDTNUM, IGDTLEN INTEGER, INTENT(IN ) :: IGDTMPL(IGDTLEN) INTEGER, INTENT( OUT) :: IJKGDSA(20) ! INTEGER :: IM, JM, IWRAP, JG INTEGER :: I_OFFSET_ODD, I_OFFSET_EVEN INTEGER :: ISCAN, KSCAN, NSCAN INTEGER :: JWRAP1, JWRAP2, ISCALE ! REAL :: DLAT, DLON REAL :: RLAT1, RLAT2 REAL :: RLON1, RLON2 ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR LAT/LON PROJECTION IF(IGDTNUM.EQ.0) THEN IM=IGDTMPL(8) JM=IGDTMPL(9) NSCAN=MOD(IGDTMPL(19)/32,2) KSCAN=0 ISCALE=IGDTMPL(10)*IGDTMPL(11) IF(ISCALE==0) ISCALE=10**6 RLON1=FLOAT(IGDTMPL(13))/FLOAT(ISCALE) RLON2=FLOAT(IGDTMPL(16))/FLOAT(ISCALE) ISCAN=MOD(IGDTMPL(19)/128,2) IF(ISCAN.EQ.0) THEN DLON=(MOD(RLON2-RLON1-1+3600,360.)+1)/(IM-1) ELSE DLON=-(MOD(RLON1-RLON2-1+3600,360.)+1)/(IM-1) ENDIF IWRAP=NINT(360/ABS(DLON)) IF(IM.LT.IWRAP) IWRAP=0 JWRAP1=0 JWRAP2=0 IF(IWRAP.GT.0.AND.MOD(IWRAP,2).EQ.0) THEN RLAT1=FLOAT(IGDTMPL(12))/FLOAT(ISCALE) RLAT2=FLOAT(IGDTMPL(15))/FLOAT(ISCALE) DLAT=ABS(RLAT2-RLAT1)/(JM-1) IF(ABS(RLAT1).GT.90-0.25*DLAT) THEN JWRAP1=2 ELSEIF(ABS(RLAT1).GT.90-0.75*DLAT) THEN JWRAP1=1 ENDIF IF(ABS(RLAT2).GT.90-0.25*DLAT) THEN JWRAP2=2*JM ELSEIF(ABS(RLAT2).GT.90-0.75*DLAT) THEN JWRAP2=2*JM+1 ENDIF ENDIF ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR ROTATED LAT/LON ELSEIF(IGDTNUM.EQ.1) THEN I_OFFSET_ODD=MOD(IGDTMPL(19)/8,2) I_OFFSET_EVEN=MOD(IGDTMPL(19)/4,2) IM=IGDTMPL(8) JM=IGDTMPL(9) IWRAP=0 JWRAP1=0 JWRAP2=0 KSCAN=0 NSCAN=MOD(IGDTMPL(19)/32,2) IF(I_OFFSET_ODD/=I_OFFSET_EVEN)THEN KSCAN=I_OFFSET_ODD NSCAN=3 ENDIF ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR MERCATOR. ELSEIF(IGDTNUM.EQ.10) THEN IM=IGDTMPL(8) JM=IGDTMPL(9) RLON1=FLOAT(IGDTMPL(11))*1.0E-6 RLON2=FLOAT(IGDTMPL(15))*1.0E-6 ISCAN=MOD(IGDTMPL(16)/128,2) IF(ISCAN.EQ.0) THEN DLON=(MOD(RLON2-RLON1-1+3600,360.)+1)/(IM-1) ELSE DLON=-(MOD(RLON1-RLON2-1+3600,360.)+1)/(IM-1) ENDIF IWRAP=NINT(360/ABS(DLON)) IF(IM.LT.IWRAP) IWRAP=0 JWRAP1=0 JWRAP2=0 KSCAN=0 NSCAN=MOD(IGDTMPL(16)/32,2) ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR POLAR STEREOGRAPHIC ELSEIF(IGDTNUM.EQ.20) THEN IM=IGDTMPL(8) JM=IGDTMPL(9) NSCAN=MOD(IGDTMPL(18)/32,2) IWRAP=0 JWRAP1=0 JWRAP2=0 KSCAN=0 ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR LAMBERT CONFORMAL. ELSEIF(IGDTNUM.EQ.30) THEN IM=IGDTMPL(8) JM=IGDTMPL(9) NSCAN=MOD(IGDTMPL(18)/32,2) IWRAP=0 JWRAP1=0 JWRAP2=0 KSCAN=0 ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! SET EXCEPTIONAL VALUES FOR GAUSSIAN LAT/LON ELSEIF(IGDTNUM.EQ.40) THEN IM=IGDTMPL(8) JM=IGDTMPL(9) ISCALE=IGDTMPL(10)*IGDTMPL(11) IF(ISCALE==0) ISCALE=10**6 RLON1=FLOAT(IGDTMPL(13))/FLOAT(ISCALE) RLON2=FLOAT(IGDTMPL(16))/FLOAT(ISCALE) ISCAN=MOD(IGDTMPL(19)/128,2) IF(ISCAN.EQ.0) THEN DLON=(MOD(RLON2-RLON1-1+3600,360.)+1)/(IM-1) ELSE DLON=-(MOD(RLON1-RLON2-1+3600,360.)+1)/(IM-1) ENDIF IWRAP=NINT(360/ABS(DLON)) IF(IM.LT.IWRAP) IWRAP=0 JWRAP1=0 JWRAP2=0 IF(IWRAP.GT.0.AND.MOD(IWRAP,2).EQ.0) THEN JG=IGDTMPL(18)*2 IF(JM.EQ.JG) THEN JWRAP1=1 JWRAP2=2*JM+1 ENDIF ENDIF NSCAN=MOD(IGDTMPL(19)/32,2) KSCAN=0 ENDIF ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ! FILL NAVIGATION PARAMETER ARRAY IJKGDSA(1)=IM IJKGDSA(2)=JM IJKGDSA(3)=IWRAP IJKGDSA(4)=JWRAP1 IJKGDSA(5)=JWRAP2 IJKGDSA(6)=NSCAN IJKGDSA(7)=KSCAN ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - END SUBROUTINE IJKGDS0
If $T$ is a subset of $S$ and $T$ is open, and if $T'$ is any other open subset of $S$ that is contained in $T$, then $T$ is the interior of $S$.
[STATEMENT] lemma finite_top_fun: "(top :: ('a::finite \<Rightarrow> 'b::finite_lattice_complete)) = Sup_fin UNIV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. top = \<Squnion>\<^sub>f\<^sub>i\<^sub>n UNIV [PROOF STEP] by (metis Sup_UNIV Sup_fin_Sup empty_not_UNIV finite)
library(cellrangerRkit) context('Normalization') gene_names = c('a', 'b') sample_names = c('sample1', 'sample2', 'sample3') # Generate a test dataset test_matrix = Matrix(matrix(c(1,2,10,20,100,200), ncol=3)) row.names(test_matrix) = gene_names colnames(test_matrix) = sample_names test_genes = data.frame(id=gene_names, symbol=gene_names) row.names(test_genes) = gene_names test_sample_data = data.frame(barcode=sample_names) row.names(test_sample_data) = sample_names # Create GBM from it test_gbm <- newGeneBCMatrix(test_matrix, test_genes, test_sample_data) # Test median normalization test_gbm_bcnorm <- normalize_barcode_sums_to_median(test_gbm) test_that("bc normalization gives correct result", { expect_true(all(colSums(test_gbm_bcnorm) == 30)) }) # Test log normalization test_gbm <- newGeneBCMatrix(test_matrix, test_genes, test_sample_data) test_gbm_log2 <- log_gene_bc_matrix(test_gbm, base=2) test_that("bc normalization gives correct result", { expect_true(all(test_gbm_log2 == log2(1+test_gbm))) })
#include "software/networking/threaded_unix_sender.h" #include <boost/asio.hpp> #include <boost/bind.hpp> #include <string> ThreadedUnixSender::ThreadedUnixSender(const std::string& unix_socket_path) : io_service(), unix_sender(io_service, unix_socket_path), io_service_thread([this]() { io_service.run(); }) { } ThreadedUnixSender::~ThreadedUnixSender() { // Stop the io_service. This is safe to call from another thread. // https://stackoverflow.com/questions/4808848/boost-asio-stopping-io-service // This MUST be done before attempting to join the thread because otherwise the // io_service will not stop and the thread will not join io_service.stop(); // Join the io_service_thread so that we wait for it to exit before destructing the // thread object. If we do not wait for the thread to finish executing, it will call // `std::terminate` when we deallocate the thread object and kill our whole program io_service_thread.join(); } void ThreadedUnixSender::sendString(const std::string& message) { unix_sender.sendString(message); }
Formal statement is: lemma complex_mod_triangle_sub: "cmod w \<le> cmod (w + z) + norm z" Informal statement is: The modulus of a complex number is less than or equal to the modulus of the sum of that number and another complex number plus the modulus of the second complex number.
% !TEX root = developer.tex \chapter{How \sstmacro Launches} \label{chapter:launching} It is useful for an intuitive understanding of the code to walk through the steps starting from \inlinecode{main} and proceeding to the discrete event simulation actually launching. The code follows these basic steps: \begin{itemize} \item Configuration of the simulation via environment variables, command line parameters, and the input file \item Building and configuration of simulator components \item Running of the actual simulation \end{itemize} We can walk through each of these steps in more detail. \section{Configuration of Simulation}\label{sec:simConfig} The configuration proceeds through the following basic steps: \begin{itemize} \item Basic initialization of the \inlinecode{parallel_runtime} object from environment variables and command line parameters \item Processing and parallel broadcast of the input file parameters \item Creation of the simulation \inlinecode{manager} object \item Detailed configuration of the \inlinecode{manager} and \inlinecode{parallel_runtime} object \end{itemize} The first step in most programs is to initialize the parallel communication environment via calls to MPI\_Init or similar. Only rank 0 should read in the input file to minimize filesystem traffic in a parallel job. Rank 0 then broadcasts the parameters to all other ranks. We are thus left with the problem of wanting to tune initialization of the parallel environment via the input file, but the input file is not yet available. Thus, we have an initial bootstrap step where the all parameters affecting initialization of the parallel runtime must be given either via command line parameters or environment variables. These automatically get distributed to all processes via the job launcher. Most critically the environment variable \inlineshell{SSTMC_PARALLEL} takes on values of \inlineshell{serial} or \inlineshell{mpi}. As stated above, only rank 0 ever touches the filesystem. A utility is provided within the Sprockit library for automatically distributing files via the \inlinecode{parallel_build_params} function within \inlinecode{sim_parameters}. Once broadcast, all ranks now have all they need to configure, setup, and run. Some additional processing is done here to map parameters. If parameters are missing, \sstmacro may fill in sensible defaults at this stage. For deprecated parameters, \sstmacro also does some remapping to ensure backwards compatibility. After creation of the \inlinecode{manager} object, since all of the parameters even from the input file are now available, a more detailed configuration of the \inlinecode{manager} and \inlinecode{parallel_runtime} can be done. \section{Building and configuration of simulator components}\label{sec:buildConfig} Inside the constructor for \inlinecode{manager}, the simulation manager now proceeds to build all the necessary components. There are three important components to build. \begin{itemize} \item The event manager that drives the discrete event simulation \item The interconnect object that directs the creation of all the hardware components \item The generation of application objects that will drive the software events. This is built indirectly through node objects that are built by the interconnect. \end{itemize} \subsection{Event Manager}\label{sec:eventMan} The \inlinecode{event_manager} object is a polymorphic type that depends on 1) what sort of parallelism is being used and 2) what sort of data structure is being used. Some allowed values include \inlineshell{event_map} or \inlineshell{event_calendar} via the \inlineshell{event_manager} variable in the input file. For parallel simulation, only the \inlineshell{event_map} data structure is currently supported. For MPI parallel simulations, the \inlineshell{event_manager} parameter should be set to \inlineshell{clock_cycle_parallel}. For multithreaded simulations (single process or coupled with MPI), this should be set to \inlineshell{multithread}. In most cases, \sstmacro chooses a sensible default based on the configuration and installation. As of right now, the event manager is also responsible for partitioning the simulation. This may be refactored in future versions. This creates something of a circular dependency between the \inlinecode{event_manager} and the \inlinecode{interconnect} objects. When scheduling events and sending events remotely, it is highly convenient to have the partition information accessible by the event manager. For now, the event manager reads the topology information from the input file. It then determines the total number of hardware components and does the partitioning. This partitioning object is passed on to the interconnect. \subsection{Interconnect}\label{subsec:interconnect} The interconnect is the workhorse for building all hardware components. After receiving the partition information from the \inlinecode{event_manager}, the interconnect creates all the nodes, switches, and NICs the current MPI rank is responsible for. In parallel runs, each MPI rank only gets assigned a unique, disjoint subset of the components. The interconnect then also creates all the connections between components that are linked based on the topology input (see Section \ref{sec:connectables}). For components that are not owned by the current MPI rank, the interconnect inserts a dummy handler that informs the \inlinecode{event_manager} that the message needs to be re-routed to another MPI rank. \subsection{Applications}\label{subsec:apps} All events generated in the simulation ultimately originate from application objects. All hardware events start from real application code. The interconnect builds a set of node objects corresponding to compute nodes in the system. In the constructor for \inlinecode{node} we have: \begin{CppCode} job_launcher_ = job_launcher::static_job_launcher(params, mgr; \end{CppCode} This job launcher roughly corresponds to SLURM, PBS, or MOAB - some process manager that will allocate nodes to a job request and spawn processes on the nodes. For implementation reasons, each node grabs a reference to a static job launcher. After construction, each node will have its \inlinecode{init} function invoked. \begin{CppCode} void node::init(unsigned int phase) { if (phase == 0){ build_launchers(params_); } } \end{CppCode} The \inlinecode{build_launchers} will detect all the launch requests from the input file. After the init phases are completed, a final setup function is invoked on the node. \begin{CppCode} void node::schedule_launches() { for (app_launch* appman : launchers_){ schedule(appman->time(), new_callback(this, &node::job_launch, appman)); } } \end{CppCode} The function \inlinecode{appman->time()} returns the time that the application launch is \emph{requested}, not when the application necessarily launches. This corresponds to when a user would type, e.g. \inlinecode{srun} or \inlinecode{qsub} to put the job in a queue. When the time for a job launch request is reached, the callback function is invoked. \begin{CppCode} void node::job_launch(app_launch* appman) { job_launcher_->handle_new_launch_request(appman, this); } \end{CppCode} For the default job launcher (in most cases SST/macro only simulates a single job in which case no scheduler is needed) the job launches immediately. The code for the default job launcher is: \begin{CppCode} ordered_node_set allocation; appman->request_allocation(available_, allocation); for (const node_id& nid : allocation){ if (available_.find(nid) == available_.end()){ spkt_throw_printf(sprockit::value_error, "allocation requested node %d, but it's not available", int(nid)); } available_.erase(nid); } appman->index_allocation(allocation); for (int& rank : appman->rank_assignment(nd->addr()){ sw::launch_event* lev = new launch_event(appman->app_template(), appman->aid(), rank, appman->core_affinities()); nd->handle(lev); } \end{CppCode} Here the application manager first allocates the correct number of nodes and indexes (assigns task numbers to nodes). This is detailed in the user's manual. The application manager has a launch info object that contains all the information needed to launch a new instance of the application on each node. The application manager then loops through all processes it is supposed to launch, queries for the correct node assignment, and fetches the physical node that will launch the application. Every application gets assigned a \inlinecode{software_id}, which is a struct containing a \inlinecode{task_id} and \inlinecode{app_id}. The task ID identifies the process number (essentially MPI rank). The application ID identifies which currently running application instance is being used. This is only relevant where two distinct applications are running. In most cases, only a single application is being used, in which case the application ID is always one. \section{Running}\label{sec:running} Now that all hardware components have been created and all application objects have been assigned to physical nodes, the \inlinecode{event_manager} created above is started. It begins looping through all events in the queue ordered by timestamp and runs them. As stated above, all events originate from application code. Thus, the first events to run are always the application launch events generated from the launch messages sent to the nodes generated the job launcher.
#ifndef alphas_H_INCLUDED #define alphas_H_INCLUDED //for fixed alpha //#define g2 (4.6) #include <gsl/gsl_spline.h> //http://pdg.lbl.gov/2010/reviews/rpp2010-rev-qcd.pdf #define Mz 91.1876 #define LamQCD 0.217 //fixednf = 0 for nf(mu) #define fixednf 3 //extrapolates below mu0*LamQCD to value of (mu0-1.0)*LamQCD at mu=0 #define mu0 4. #define pi 3.14159265359 #define Nc (3.) #define Cf ((Nc*Nc-1.)/(2.*Nc)) void TabulateAlpha(); double alpha(double mu); double nf(double mu); double alpha_b0(double nf); double alpha_b1(double nf); double alpha_b2(double nf); double alpha_s0(double mu); double alpha_s1(double mu); double alpha_s2(double mu); gsl_interp_accel *accAlpha; gsl_spline *Alpha; #endif
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal71. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj4eqsynthconj1 : forall , (@eq natural (Zero) (Zero)). Admitted. QuickChick conj4eqsynthconj1.
module Connectives where -- Imports import Relation.Binary.PropositionalEquality as Eq open Eq using (_≡_; refl; cong) open Eq.≡-Reasoning open import Data.Nat using (ℕ) open import Function using (_∘_) -- open import plfa.part1.Isomorphism using (_≃_; _≲_; extensionality) -- open plfa.part1.Isomorphism.≃-Reasoning postulate -- 外延性の公理 extensionality : ∀ {A B : Set} {f g : A → B} → (∀ (x : A) → f x ≡ g x) ----------------------- → f ≡ g -- 同型 infix 0 _≃_ record _≃_ (A B : Set) : Set where field to : A → B from : B → A from∘to : ∀ (x : A) → from (to x) ≡ x to∘from : ∀ (y : B) → to (from y) ≡ y open _≃_ ≃-refl : ∀ {A : Set} ----- → A ≃ A ≃-refl = record { to = λ{x → x} ; from = λ{y → y} ; from∘to = λ{x → refl} ; to∘from = λ{y → refl} } ≃-trans : ∀ {A B C : Set} → A ≃ B → B ≃ C ----- → A ≃ C ≃-trans A≃B B≃C = record { to = to B≃C ∘ to A≃B ; from = from A≃B ∘ from B≃C ; from∘to = λ{x → begin (from A≃B ∘ from B≃C) ((to B≃C ∘ to A≃B) x) ≡⟨⟩ from A≃B (from B≃C (to B≃C (to A≃B x))) ≡⟨ cong (from A≃B) (from∘to B≃C (to A≃B x)) ⟩ from A≃B (to A≃B x) ≡⟨ from∘to A≃B x ⟩ x ∎} ; to∘from = λ{y → begin (to B≃C ∘ to A≃B) ((from A≃B ∘ from B≃C) y) ≡⟨⟩ to B≃C (to A≃B (from A≃B (from B≃C y))) ≡⟨ cong (to B≃C) (to∘from A≃B (from B≃C y)) ⟩ to B≃C (from B≃C y) ≡⟨ to∘from B≃C y ⟩ y ∎} } module ≃-Reasoning where infix 1 ≃-begin_ infixr 2 _≃⟨_⟩_ infix 3 _≃-∎ ≃-begin_ : ∀ {A B : Set} → A ≃ B ----- → A ≃ B ≃-begin A≃B = A≃B _≃⟨_⟩_ : ∀ (A : Set) {B C : Set} → A ≃ B → B ≃ C ----- → A ≃ C A ≃⟨ A≃B ⟩ B≃C = ≃-trans A≃B B≃C _≃-∎ : ∀ (A : Set) ----- → A ≃ A A ≃-∎ = ≃-refl open ≃-Reasoning -- 埋め込み infix 0 _≲_ record _≲_ (A B : Set) : Set where field to : A → B from : B → A from∘to : ∀ (x : A) → from (to x) ≡ x open _≲_ -- Conjunction is product -- 直積 data _×_ (A B : Set) : Set where ⟨_,_⟩ : A → B ----- → A × B proj₁ : ∀ {A B : Set} → A × B ----- → A proj₁ ⟨ x , y ⟩ = x proj₂ : ∀ {A B : Set} → A × B ----- → B proj₂ ⟨ x , y ⟩ = y record _×′_ (A B : Set) : Set where field proj₁′ : A proj₂′ : B open _×′_ η-× : ∀ {A B : Set} (w : A × B) → ⟨ proj₁ w , proj₂ w ⟩ ≡ w η-× ⟨ x , y ⟩ = refl infixr 2 _×_ data Bool : Set where true : Bool false : Bool data Tri : Set where aa : Tri bb : Tri cc : Tri ×-count : Bool × Tri → ℕ ×-count ⟨ true , aa ⟩ = 1 ×-count ⟨ true , bb ⟩ = 2 ×-count ⟨ true , cc ⟩ = 3 ×-count ⟨ false , aa ⟩ = 4 ×-count ⟨ false , bb ⟩ = 5 ×-count ⟨ false , cc ⟩ = 6 ×-comm : ∀ {A B : Set} → A × B ≃ B × A ×-comm = record { to = λ{ ⟨ x , y ⟩ → ⟨ y , x ⟩ } ; from = λ{ ⟨ y , x ⟩ → ⟨ x , y ⟩ } ; from∘to = λ{ ⟨ x , y ⟩ → refl } ; to∘from = λ{ ⟨ y , x ⟩ → refl } } ×-assoc : ∀ {A B C : Set} → (A × B) × C ≃ A × (B × C) ×-assoc = record { to = λ{ ⟨ ⟨ x , y ⟩ , z ⟩ → ⟨ x , ⟨ y , z ⟩ ⟩ } ; from = λ{ ⟨ x , ⟨ y , z ⟩ ⟩ → ⟨ ⟨ x , y ⟩ , z ⟩ } ; from∘to = λ{ ⟨ ⟨ x , y ⟩ , z ⟩ → refl } ; to∘from = λ{ ⟨ x , ⟨ y , z ⟩ ⟩ → refl } } -- Truth is unit data ⊤ : Set where tt : -- ⊤ η-⊤ : ∀ (w : ⊤) → tt ≡ w η-⊤ tt = refl ⊤-count : ⊤ → ℕ ⊤-count tt = 1 ⊤-identityˡ : ∀ {A : Set} → ⊤ × A ≃ A ⊤-identityˡ = record { to = λ{ ⟨ tt , x ⟩ → x } ; from = λ{ x → ⟨ tt , x ⟩ } ; from∘to = λ{ ⟨ tt , x ⟩ → refl } ; to∘from = λ{ x → refl } } ⊤-identityʳ : ∀ {A : Set} → (A × ⊤) ≃ A ⊤-identityʳ {A} = ≃-begin (A × ⊤) ≃⟨ ×-comm ⟩ (⊤ × A) ≃⟨ ⊤-identityˡ ⟩ A ≃-∎ -- Disjunction is sum -- 直和 data _⊎_ (A B : Set) : Set where inj₁ : A ----- → A ⊎ B inj₂ : B ----- → A ⊎ B case-⊎ : ∀ {A B C : Set} → (A → C) → (B → C) → A ⊎ B ----------- → C case-⊎ f g (inj₁ x) = f x case-⊎ f g (inj₂ y) = g y η-⊎ : ∀ {A B : Set} (w : A ⊎ B) → case-⊎ inj₁ inj₂ w ≡ w η-⊎ (inj₁ x) = refl η-⊎ (inj₂ y) = refl uniq-⊎ : ∀ {A B C : Set} (h : A ⊎ B → C) (w : A ⊎ B) → case-⊎ (h ∘ inj₁) (h ∘ inj₂) w ≡ h w uniq-⊎ h (inj₁ x) = refl uniq-⊎ h (inj₂ y) = refl infixr 1 _⊎_ ⊎-count : Bool ⊎ Tri → ℕ ⊎-count (inj₁ true) = 1 ⊎-count (inj₁ false) = 2 ⊎-count (inj₂ aa) = 3 ⊎-count (inj₂ bb) = 4 ⊎-count (inj₂ cc) = 5 -- False is empty data ⊥ : Set where -- no clauses! ⊥-elim : ∀ {A : Set} → ⊥ -- → A ⊥-elim () uniq-⊥ : ∀ {C : Set} (h : ⊥ → C) (w : ⊥) → ⊥-elim w ≡ h w uniq-⊥ h () ⊥-count : ⊥ → ℕ ⊥-count () -- Implication is function →-elim : ∀ {A B : Set} → (A → B) → A ------- → B →-elim L M = L M η-→ : ∀ {A B : Set} (f : A → B) → (λ (x : A) → f x) ≡ f η-→ f = refl →-count : (Bool → Tri) → ℕ →-count f with f true | f false ... | aa | aa = 1 ... | aa | bb = 2 ... | aa | cc = 3 ... | bb | aa = 4 ... | bb | bb = 5 ... | bb | cc = 6 ... | cc | aa = 7 ... | cc | bb = 8 ... | cc | cc = 9 currying : ∀ {A B C : Set} → (A → B → C) ≃ (A × B → C) currying = record { to = λ{ f → λ{ ⟨ x , y ⟩ → f x y }} ; from = λ{ g → λ{ x → λ{ y → g ⟨ x , y ⟩ }}} ; from∘to = λ{ f → refl } ; to∘from = λ{ g → extensionality λ{ ⟨ x , y ⟩ → refl }} } →-distrib-⊎ : ∀ {A B C : Set} → (A ⊎ B → C) ≃ ((A → C) × (B → C)) →-distrib-⊎ = record { to = λ{ f → ⟨ f ∘ inj₁ , f ∘ inj₂ ⟩ } ; from = λ{ ⟨ g , h ⟩ → λ{ (inj₁ x) → g x ; (inj₂ y) → h y } } ; from∘to = λ{ f → extensionality λ{ (inj₁ x) → refl ; (inj₂ y) → refl } } ; to∘from = λ{ ⟨ g , h ⟩ → refl } } →-distrib-× : ∀ {A B C : Set} → (A → B × C) ≃ (A → B) × (A → C) →-distrib-× = record { to = λ{ f → ⟨ proj₁ ∘ f , proj₂ ∘ f ⟩ } ; from = λ{ ⟨ g , h ⟩ → λ x → ⟨ g x , h x ⟩ } ; from∘to = λ{ f → extensionality λ{ x → η-× (f x) } } ; to∘from = λ{ ⟨ g , h ⟩ → refl } } -- Distribution ×-distrib-⊎ : ∀ {A B C : Set} → (A ⊎ B) × C ≃ (A × C) ⊎ (B × C) ×-distrib-⊎ = record { to = λ{ ⟨ inj₁ x , z ⟩ → (inj₁ ⟨ x , z ⟩) ; ⟨ inj₂ y , z ⟩ → (inj₂ ⟨ y , z ⟩) } ; from = λ{ (inj₁ ⟨ x , z ⟩) → ⟨ inj₁ x , z ⟩ ; (inj₂ ⟨ y , z ⟩) → ⟨ inj₂ y , z ⟩ } ; from∘to = λ{ ⟨ inj₁ x , z ⟩ → refl ; ⟨ inj₂ y , z ⟩ → refl } ; to∘from = λ{ (inj₁ ⟨ x , z ⟩) → refl ; (inj₂ ⟨ y , z ⟩) → refl } } ⊎-distrib-× : ∀ {A B C : Set} → (A × B) ⊎ C ≲ (A ⊎ C) × (B ⊎ C) ⊎-distrib-× = record { to = λ{ (inj₁ ⟨ x , y ⟩) → ⟨ inj₁ x , inj₁ y ⟩ ; (inj₂ z) → ⟨ inj₂ z , inj₂ z ⟩ } ; from = λ{ ⟨ inj₁ x , inj₁ y ⟩ → (inj₁ ⟨ x , y ⟩) ; ⟨ inj₁ x , inj₂ z ⟩ → (inj₂ z) ; ⟨ inj₂ z , _ ⟩ → (inj₂ z) } ; from∘to = λ{ (inj₁ ⟨ x , y ⟩) → refl ; (inj₂ z) → refl } }
(* Evaluation contexts of the L6 CPS language * Part of the CertiCoq project *) From Coq Require Import Arith.Arith NArith.BinNat Lists.List omega.Omega. From SFS Require Import cps tactics set_util. Import ListNotations. (** Expression evaluation contexts *) Inductive exp_ctx : Type := | Hole_c : exp_ctx | Econstr_c : var -> cTag -> list var -> exp_ctx -> exp_ctx | Eproj_c : var -> cTag -> N -> var -> exp_ctx -> exp_ctx | Eprim_c : var -> prim -> list var -> exp_ctx -> exp_ctx | Ecase_c : var -> list (cTag * exp) -> cTag -> exp_ctx -> list (cTag * exp) -> exp_ctx | Efun1_c : fundefs -> exp_ctx -> exp_ctx | Efun2_c : fundefs_ctx -> exp -> exp_ctx with fundefs_ctx := | Fcons1_c: var -> cTag -> list var -> exp_ctx -> fundefs -> fundefs_ctx | Fcons2_c: var -> cTag -> list var -> exp -> fundefs_ctx -> fundefs_ctx. (** Evaluation context application - Relational definition *) Inductive app_ctx: exp_ctx -> exp -> exp -> Prop := | Hole_ac: forall e, app_ctx Hole_c e e | Constr_ac : forall x t c ys e ce, app_ctx c e ce -> app_ctx (Econstr_c x t ys c) e (Econstr x t ys ce) | Proj_ac : forall x t n y e c ce, app_ctx c e ce -> app_ctx (Eproj_c x t n y c) e (Eproj x t n y ce) | Case_ac : forall x te t e te' c ce, app_ctx c e ce -> app_ctx (Ecase_c x te t c te') e (Ecase x (te ++ (t, ce) :: te')) | Prim_ac : forall x f ys e c ce, app_ctx c e ce -> app_ctx (Eprim_c x f ys c) e (Eprim x f ys ce) | Fun1_ac : forall c e ce fds, app_ctx c e ce -> app_ctx (Efun1_c fds c) e (Efun fds ce) | Fun2_ac : forall e cfds cfdse e', app_f_ctx cfds e cfdse -> app_ctx (Efun2_c cfds e') e (Efun cfdse e') with app_f_ctx : fundefs_ctx -> exp -> fundefs -> Prop := | Fcons1_ac : forall c e ce f t ys fds, app_ctx c e ce -> app_f_ctx (Fcons1_c f t ys c fds) e (Fcons f t ys ce fds) | Fcons2_ac: forall e cfdse f cfds ys e' t, app_f_ctx cfds e cfdse -> app_f_ctx (Fcons2_c f t ys e' cfds) e (Fcons f t ys e' cfdse). Hint Constructors app_ctx app_f_ctx. (** Evaluation context application - Computational definition *) Fixpoint app_ctx_f (c:exp_ctx) (e:exp) : exp := match c with | Hole_c => e | Econstr_c x t ys c => Econstr x t ys (app_ctx_f c e) | Eproj_c x t n y c => Eproj x t n y (app_ctx_f c e) | Ecase_c x te t c te' => Ecase x (te ++ (t, app_ctx_f c e) :: te') | Eprim_c x f ys c => Eprim x f ys (app_ctx_f c e) | Efun1_c fds c => Efun fds (app_ctx_f c e) | Efun2_c cfds e' => Efun (app_f_ctx_f cfds e) e' end with app_f_ctx_f (c: fundefs_ctx) (e:exp) : fundefs := match c with | Fcons1_c f t ys c fds => Fcons f t ys (app_ctx_f c e) fds | Fcons2_c f t ys e' cfds => Fcons f t ys e' (app_f_ctx_f cfds e) end. (** Composition of evaluation context - Relational definition *) Inductive comp_ctx: exp_ctx -> exp_ctx -> exp_ctx -> Prop := | Hole_cc: forall e, comp_ctx Hole_c e e | Constr_cc : forall x t c ys e ce, comp_ctx c e ce -> comp_ctx (Econstr_c x t ys c) e (Econstr_c x t ys ce) | Proj_cc : forall x t n y e c ce, comp_ctx c e ce -> comp_ctx (Eproj_c x t n y c) e (Eproj_c x t n y ce) | Case_cc : forall x te t c te' c' cc, comp_ctx c c' cc -> comp_ctx (Ecase_c x te t c te') c' (Ecase_c x te t cc te') | Prim_cc : forall x f ys e c ce, comp_ctx c e ce -> comp_ctx (Eprim_c x f ys c) e (Eprim_c x f ys ce) | Fun1_cc : forall c e ce fds, comp_ctx c e ce -> comp_ctx (Efun1_c fds c) e (Efun1_c fds ce) | Fun2_cc : forall e cfds cfdse e', comp_f_ctx cfds e cfdse -> comp_ctx (Efun2_c cfds e') e (Efun2_c cfdse e') with comp_f_ctx : fundefs_ctx -> exp_ctx -> fundefs_ctx -> Prop := | Fcons1_cc : forall c e ce f t ys fds, comp_ctx c e ce -> comp_f_ctx (Fcons1_c f t ys c fds) e (Fcons1_c f t ys ce fds) | Fcons2_cc: forall e cfdse f cfds ys e' t, comp_f_ctx cfds e cfdse -> comp_f_ctx (Fcons2_c f t ys e' cfds) e (Fcons2_c f t ys e' cfdse). (** Composition of evaluation context - Computational definition *) Fixpoint comp_ctx_f (c1:exp_ctx) (c2:exp_ctx) : exp_ctx := match c1 with | Hole_c => c2 | Econstr_c x t ys c => Econstr_c x t ys (comp_ctx_f c c2) | Eproj_c x t n y c => Eproj_c x t n y (comp_ctx_f c c2) | Ecase_c x te t c te' => Ecase_c x te t (comp_ctx_f c c2) te' | Eprim_c x f ys c => Eprim_c x f ys (comp_ctx_f c c2) | Efun1_c fds c => Efun1_c fds (comp_ctx_f c c2) | Efun2_c cfds e' => Efun2_c (comp_f_ctx_f cfds c2) e' end with comp_f_ctx_f (c: fundefs_ctx) (c2:exp_ctx) : fundefs_ctx := match c with | Fcons1_c f t ys c fds => Fcons1_c f t ys (comp_ctx_f c c2) fds | Fcons2_c f t ys e' cfds => Fcons2_c f t ys e' (comp_f_ctx_f cfds c2) end. Notation "c '|[' e ']|' " := (app_ctx_f c e) (at level 28, no associativity) : ctx_scope. Notation "f '<[' e ']>'" := (app_f_ctx_f f e) (at level 28, no associativity) : ctx_scope. Open Scope ctx_scope. Scheme ctx_exp_mut := Induction for exp_ctx Sort Prop with ctx_fundefs_mut := Induction for fundefs_ctx Sort Prop. Scheme ctx_exp_mut' := Induction for exp_ctx Sort Type with ctx_fundefs_mut' := Induction for fundefs_ctx Sort Type. Lemma exp_fundefs_ctx_mutual_ind : forall (P : exp_ctx -> Prop) (P0 : fundefs_ctx -> Prop), P Hole_c -> (forall (v : var) (t : cTag) (l : list var) (e : exp_ctx), P e -> P (Econstr_c v t l e)) -> (forall (v : var) (t : cTag) (n : N) (v0 : var) (e : exp_ctx), P e -> P (Eproj_c v t n v0 e)) -> (forall (v : var) (p : prim) (l : list var) (e : exp_ctx), P e -> P (Eprim_c v p l e)) -> (forall (v : var) (l : list (cTag * exp)) (t : cTag) (e : exp_ctx), P e -> forall l0 : list (cTag * exp), P (Ecase_c v l t e l0)) -> (forall (f4 : fundefs) (e : exp_ctx), P e -> P (Efun1_c f4 e)) -> (forall f5 : fundefs_ctx, P0 f5 -> forall e : exp, P (Efun2_c f5 e)) -> (forall (v : var) (t : fTag) (l : list var) (e : exp_ctx), P e -> forall f6 : fundefs, P0 (Fcons1_c v t l e f6)) -> (forall (v : var) (t : fTag) (l : list var) (e : exp) (f7 : fundefs_ctx), P0 f7 -> P0 (Fcons2_c v t l e f7)) -> (forall e : exp_ctx, P e) /\ (forall f : fundefs_ctx, P0 f). Proof. intros. split. apply (ctx_exp_mut P P0); assumption. apply (ctx_fundefs_mut P P0); assumption. Qed. (** Name the induction hypotheses only *) Ltac exp_fundefs_ctx_induction IH1 IH2 := apply exp_fundefs_ctx_mutual_ind; [ | intros ? ? ? ? IH1 | intros ? ? ? ? ? IH1 | intros ? ? ? ? IH1 | intros ? ? ? ? IH1 | intros ? ? IH1 | intros ? IH2 ? | intros ? ? ? ? IH1 ? | intros ? ? ? ? ? IH2 ]. (** Alternative definition of subterm relation *) Definition subterm_e' (e':exp) (e:exp): Prop := exists c, Hole_c <> c /\ app_ctx c e' e. Definition subterm_or_eq' (e':exp) (e:exp) : Prop := exists c, app_ctx c e' e. (** Theorems about context application and composition *) Lemma app_ctx_f_correct_mut: (forall c e e', c |[ e ]| = e' <-> app_ctx c e e') /\ (forall cf B B', cf <[ B ]> = B' <-> app_f_ctx cf B B'). Proof. exp_fundefs_ctx_induction IHe IHf; simpl; intros; split; intros H'; first [ inversion H'; subst; constructor; eapply IHe; congruence | inversion H'; subst; repeat f_equal; eapply IHe; eassumption | inversion H'; subst; constructor; eapply IHf; congruence | inversion H'; subst; repeat f_equal; eapply IHf ]; inversion H'; subst; eassumption. Qed. Corollary app_ctx_f_correct : forall c e e', c |[ e ]| = e' <-> app_ctx c e e'. Proof. now apply app_ctx_f_correct_mut. Qed. Corollary app_f_ctx_f_correct : forall cf B B', cf <[ B ]> = B' <-> app_f_ctx cf B B'. Proof. now apply app_ctx_f_correct_mut. Qed. Lemma comp_ctx_f_correct_mut: (forall c c' cc', comp_ctx_f c c' = cc' <-> comp_ctx c c' cc') /\ (forall cf cf' ccf', comp_f_ctx_f cf cf' = ccf' <-> comp_f_ctx cf cf' ccf'). Proof. exp_fundefs_ctx_induction IHe IHf; simpl; intros; split; intros H'; first [ inversion H'; subst; constructor; eapply IHe; congruence | inversion H'; subst; repeat f_equal; eapply IHe; eassumption | inversion H'; subst; constructor; eapply IHf; congruence | inversion H'; subst; repeat f_equal; eapply IHf ]; inversion H'; subst; eassumption. Qed. Corollary comp_ctx_f_correct : forall c c' cc', comp_ctx_f c c' = cc' <-> comp_ctx c c' cc'. Proof. now apply comp_ctx_f_correct_mut. Qed. Corollary comp_f_ctx_f_correct : forall cf cf' ccf', comp_f_ctx_f cf cf' = ccf' <-> comp_f_ctx cf cf' ccf'. Proof. now apply comp_ctx_f_correct_mut. Qed. Lemma app_ctx_f_fuse_mut : (forall c c' e, c |[ c' |[ e ]| ]| = (comp_ctx_f c c') |[ e ]|) /\ (forall cf c e, cf <[ c |[ e ]| ]> = (comp_f_ctx_f cf c) <[ e ]>). Proof. exp_fundefs_ctx_induction IHe IHf; simpl; intros; try (rewrite IHe; reflexivity); try (rewrite IHf; reflexivity). reflexivity. Qed. Corollary app_ctx_f_fuse : forall c c' e, c |[ c' |[ e ]| ]| = (comp_ctx_f c c') |[ e ]|. Proof. now apply app_ctx_f_fuse_mut. Qed. Corollary app_f_ctx_f_fuse : forall cf c e, cf <[ c |[ e ]| ]> = (comp_f_ctx_f cf c) <[ e ]>. Proof. now apply app_ctx_f_fuse_mut. Qed. Lemma app_ctx_fuse: forall (c c' : exp_ctx) (e1 e2 e3 : exp), app_ctx c e1 e2 -> app_ctx c' e2 e3 -> app_ctx (comp_ctx_f c' c) e1 e3. Proof. intros c c' e1 e2 e3 H1 H2. rewrite <- app_ctx_f_correct. rewrite <- app_ctx_f_fuse. rewrite <- app_ctx_f_correct in H1, H2. rewrite H1. eauto. Qed. Lemma comp_ctx_f_assoc_mut: (forall c1 c2 c3, comp_ctx_f (comp_ctx_f c1 c2) c3 = comp_ctx_f c1 (comp_ctx_f c2 c3)) /\ (forall f c2 c3, comp_f_ctx_f (comp_f_ctx_f f c2) c3 = comp_f_ctx_f f (comp_ctx_f c2 c3)). Proof. exp_fundefs_ctx_induction IHc1 IHf; intros; simpl; auto; try (rewrite IHc1; auto). - rewrite IHf; auto. - rewrite IHf; auto. Qed. Theorem comp_ctx_f_assoc: (forall c1 c2 c3, comp_ctx_f (comp_ctx_f c1 c2) c3 = comp_ctx_f c1 (comp_ctx_f c2 c3)). Proof. intros; apply comp_ctx_f_assoc_mut; auto. Qed. Theorem comp_f_ctx_f_assoc: (forall f c2 c3, comp_f_ctx_f (comp_f_ctx_f f c2) c3 = comp_f_ctx_f f (comp_ctx_f c2 c3)). Proof. intros; apply comp_ctx_f_assoc_mut; auto. Qed. Theorem comp_ctx_split_mut: (forall c1 c2 c3 c4, comp_ctx_f c1 c2 = comp_ctx_f c3 c4 -> (exists c41 c42, c4 = comp_ctx_f c41 c42 /\ c1 = comp_ctx_f c3 c41 /\ c2 = c42) \/ (exists c31 c32, c3 = comp_ctx_f c31 c32 /\ c1 = c31 /\ c2 = comp_ctx_f c32 c4)) /\ (forall f1 c2 f3 c4, comp_f_ctx_f f1 c2 = comp_f_ctx_f f3 c4 -> (exists c41 c42, c4 = comp_ctx_f c41 c42 /\ f1 = comp_f_ctx_f f3 c41 /\ c2 = c42) \/ (exists f31 c32, f3 = comp_f_ctx_f f31 c32 /\ f1 = f31 /\ c2 = comp_ctx_f c32 c4)). Proof. exp_fundefs_ctx_induction IHc1 IHf; intros. - simpl in H. right. exists Hole_c, c3. auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. destruct c4; inv H0. exists ( Econstr_c v0 c l0 e), c2. auto. + apply IHc1 in H4. destruct H4. * left. destructAll. exists x, x0. auto. * right. destructAll. exists (Econstr_c v0 c l0 x), x0. auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. destruct c4; inv H0. exists ( Eproj_c v1 c n0 v2 e ), c2; auto. + apply IHc1 in H5. destruct H5. * left. destructAll. exists x, x0. auto. * right. destructAll. exists ( Eproj_c v1 c n0 v2 x), x0; auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. destruct c4; inv H0. exists ( Eprim_c v0 p0 l0 e ), c2; auto. + apply IHc1 in H4. destruct H4. * left. destructAll. exists x, x0. auto. * right. destructAll. exists (Eprim_c v0 p0 l0 x ), x0; auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. exists (Ecase_c v l t e l0), c2. auto. + apply IHc1 in H4. destruct H4; destructAll. * left. exists x, x0; auto. * right. exists (Ecase_c v0 l1 c x l2), x0. auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. exists (Efun1_c f4 e), c2. auto. + apply IHc1 in H2. destruct H2; destructAll. * left. exists x, x0; auto. * right. exists (Efun1_c f x), x0. auto. - simpl in H. destruct c3; inv H. + simpl in H0. left. exists (Efun2_c f5 e), c2. auto. + apply IHf in H1. destruct H1. * left. destructAll. simpl. exists x, x0. auto. * right. destructAll. exists ( Efun2_c x e0), x0. auto. - destruct f3; inv H. apply IHc1 in H4. destruct H4; destructAll. * left. simpl. exists x, x0. auto. * right. exists (Fcons1_c v0 c l0 x f), x0; auto. - simpl in H. destruct f3; inv H. apply IHf in H5. destruct H5. * left. destructAll. simpl. exists x, x0. auto. * right. destructAll. exists (Fcons2_c v0 c l0 e0 x), x0. auto. Qed. Theorem comp_ctx_split: (forall c1 c2 c3 c4, comp_ctx_f c1 c2 = comp_ctx_f c3 c4 -> (exists c41 c42, c4 = comp_ctx_f c41 c42 /\ c1 = comp_ctx_f c3 c41 /\ c2 = c42) \/ (exists c31 c32, c3 = comp_ctx_f c31 c32 /\ c1 = c31 /\ c2 = comp_ctx_f c32 c4)). Proof. apply comp_ctx_split_mut; auto. Qed. Theorem comp_f_ctx_split: (forall f1 c2 f3 c4, comp_f_ctx_f f1 c2 = comp_f_ctx_f f3 c4 -> (exists c41 c42, c4 = comp_ctx_f c41 c42 /\ f1 = comp_f_ctx_f f3 c41 /\ c2 = c42) \/ (exists f31 c32, f3 = comp_f_ctx_f f31 c32 /\ f1 = f31 /\ c2 = comp_ctx_f c32 c4)). Proof. apply comp_ctx_split_mut; auto. Qed. (* prefix a fundefs ctx with a fundefs *) Fixpoint app_fundefs_ctx (f:fundefs) (fc:fundefs_ctx): fundefs_ctx:= match f with | Fnil => fc | Fcons x t xs e f' => Fcons2_c x t xs e (app_fundefs_ctx f' fc) end. Lemma comp_ctx_f_Hole_c C : comp_ctx_f C Hole_c = C with comp_f_ctx_f_Hole_c f : comp_f_ctx_f f Hole_c = f. Proof. - destruct C; simpl; eauto; try (rewrite comp_ctx_f_Hole_c; reflexivity). rewrite comp_f_ctx_f_Hole_c. reflexivity. - destruct f; simpl; eauto. rewrite comp_ctx_f_Hole_c; reflexivity. rewrite comp_f_ctx_f_Hole_c. reflexivity. Qed.
import tactic.simps import algebra.group.hom universe variables v u w -- set_option trace.simps.verbose true -- set_option trace.simps.debug true -- set_option trace.app_builder true open function tactic expr structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) local infix ` ≃ `:25 := equiv -- initialize_simps_projections equiv /- Since `prod` and `pprod` are a special case for `@[simps]`, we define a new structure to test the basic functionality.-/ structure my_prod (α β : Type*) := (fst : α) (snd : β) def myprod.map {α α' β β'} (f : α → α') (g : β → β') (x : my_prod α β) : my_prod α' β' := ⟨f x.1, g x.2⟩ namespace foo @[simps] protected def rfl {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- simps adds declarations -/ run_cmd do e ← get_env, e.get `foo.rfl_to_fun, e.get `foo.rfl_inv_fun, success_if_fail (e.get `foo.rfl_left_inv), success_if_fail (e.get `foo.rfl_right_inv) example (n : ℕ) : foo.rfl.to_fun n = n := by rw [foo.rfl_to_fun, id] example (n : ℕ) : foo.rfl.inv_fun n = n := by rw [foo.rfl_inv_fun] /- the declarations are simp-lemmas -/ @[simps] def foo : ℕ × ℤ := (1, 2) example : foo.1 = 1 := by simp example : foo.2 = 2 := by simp example : foo.1 = 1 := by { dsimp, refl } -- check that dsimp also unfolds example : foo.2 = 2 := by { dsimp, refl } example {α} (x : α) : foo.rfl.to_fun x = x := by simp example {α} (x : α) : foo.rfl.inv_fun x = x := by simp example {α} (x : α) : foo.rfl.to_fun = @id α := by { success_if_fail {simp}, refl } /- check some failures -/ def bar1 : ℕ := 1 -- type is not a structure noncomputable def bar2 {α} : α ≃ α := classical.choice ⟨foo.rfl⟩ run_cmd do success_if_fail_with_msg (simps_tac `foo.bar1) "Invalid `simps` attribute. Target nat is not a structure", success_if_fail_with_msg (simps_tac `foo.bar2) "Invalid `simps` attribute. The body is not a constructor application: classical.choice bar2._proof_1", e ← get_env, let nm := `foo.bar1, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), simps_add_projections e nm "" d.type lhs d.value [] d.univ_params ff {} [] [] /- test that if a non-constructor is given as definition, then `{rhs_md := semireducible, simp_rhs := tt}` is applied automatically. -/ @[simps] def rfl2 {α} : α ≃ α := foo.rfl example {α} (x : α) : rfl2.to_fun x = x ∧ rfl2.inv_fun x = x := begin dsimp only [rfl2_to_fun, rfl2_inv_fun], guard_target (x = x ∧ x = x), exact ⟨rfl, rfl⟩ end /- test `fully_applied` option -/ @[simps {fully_applied := ff}] def rfl3 {α} : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ end foo /- we reduce the type when applying [simps] -/ def my_equiv := equiv @[simps] def baz : my_equiv ℕ ℕ := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ /- test name clashes -/ def name_clash_fst := 1 def name_clash_snd := 1 def name_clash_snd_2 := 1 @[simps] def name_clash := (2, 3) run_cmd do e ← get_env, e.get `name_clash_fst_2, e.get `name_clash_snd_3 /- check projections for nested structures -/ namespace count_nested @[simps {attrs := [`simp, `norm]}] def nested1 : my_prod ℕ $ my_prod ℤ ℕ := ⟨2, -1, 1⟩ @[simps {attrs := []}] def nested2 : ℕ × my_prod ℕ ℕ := ⟨2, myprod.map nat.succ nat.pred ⟨1, 2⟩⟩ end count_nested run_cmd do e ← get_env, e.get `count_nested.nested1_fst, e.get `count_nested.nested1_snd_fst, e.get `count_nested.nested1_snd_snd, e.get `count_nested.nested2_fst, e.get `count_nested.nested2_snd, is_simp_lemma `count_nested.nested1_fst >>= λ b, guard b, -- simp attribute is global is_simp_lemma `count_nested.nested2_fst >>= λ b, guard $ ¬b, --lemmas_only doesn't add simp lemma guard $ 7 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `count_nested then 1 else 0) -- testing with arguments @[simps] def bar {α : Type*} (n m : ℕ) : ℕ × ℤ := ⟨n - m, n + m⟩ structure equiv_plus_data (α β) extends α ≃ β := (P : (α → β) → Prop) (data : P to_fun) structure automorphism_plus_data α extends α ⊕ α ≃ α ⊕ α := (P : (α ⊕ α → α ⊕ α) → Prop) (data : P to_fun) (extra : bool → my_prod ℕ ℕ) @[simps] def refl_with_data {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, ..foo.rfl } @[simps] def refl_with_data' {α} : equiv_plus_data α α := { P := λ f, f = id, data := rfl, to_equiv := foo.rfl } /- test whether eta expansions are reduced correctly -/ @[simps] def test {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(⟨3, 5⟩ : my_prod _ _).1, (⟨3, 5⟩ : my_prod _ _).2⟩, ..foo.rfl } /- test whether this is indeed rejected as a valid eta expansion -/ @[simps] def test_sneaky {α} : automorphism_plus_data α := { P := λ f, f = id, data := rfl, extra := λ b, ⟨(3,5).1,(3,5).2⟩, ..foo.rfl } run_cmd do e ← get_env, e.get `refl_with_data_to_equiv, e.get `refl_with_data'_to_equiv, e.get `test_extra, e.get `test_sneaky_extra_fst, success_if_fail (e.get `refl_with_data_to_equiv_to_fun), success_if_fail (e.get `refl_with_data'_to_equiv_to_fun), success_if_fail (e.get `test_extra_fst), success_if_fail (e.get `test_sneaky_extra) structure partially_applied_str := (data : ℕ → my_prod ℕ ℕ) /- if we have a partially applied constructor, we treat it as if it were eta-expanded -/ @[simps] def partially_applied_term : partially_applied_str := ⟨my_prod.mk 3⟩ run_cmd do e ← get_env, e.get `partially_applied_term_data_fst, e.get `partially_applied_term_data_snd structure very_partially_applied_str := (data : ∀β, ℕ → β → my_prod ℕ β) /- if we have a partially applied constructor, we treat it as if it were eta-expanded. (this is not very useful, and we could remove this behavior if convenient) -/ @[simps] def very_partially_applied_term : very_partially_applied_str := ⟨@my_prod.mk ℕ⟩ run_cmd do e ← get_env, e.get `very_partially_applied_term_data_fst, e.get `very_partially_applied_term_data_snd @[simps] def let1 : ℕ × ℤ := let n := 3 in ⟨n + 4, 5⟩ @[simps] def let2 : ℕ × ℤ := let n := 3, m := 4 in let k := 5 in ⟨n + m, k⟩ @[simps] def let3 : ℕ → ℕ × ℤ := λ n, let m := 4, k := 5 in ⟨n + m, k⟩ @[simps] def let4 : ℕ → ℕ × ℤ := let m := 4, k := 5 in λ n, ⟨n + m, k⟩ run_cmd do e ← get_env, e.get `let1_fst, e.get `let2_fst, e.get `let3_fst, e.get `let4_fst, e.get `let1_snd, e.get `let2_snd, e.get `let3_snd, e.get `let4_snd namespace specify @[simps fst] def specify1 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd] def specify2 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd_fst] def specify3 : ℕ × ℕ × ℕ := (1, 2, 3) @[simps snd snd_snd snd_snd] def specify4 : ℕ × ℕ × ℕ := (1, 2, 3) -- last argument is ignored @[simps] noncomputable def specify5 : ℕ × ℕ × ℕ := (1, classical.choice ⟨(2, 3)⟩) end specify run_cmd do e ← get_env, e.get `specify.specify1_fst, e.get `specify.specify2_snd, e.get `specify.specify3_snd_fst, e.get `specify.specify4_snd_snd, e.get `specify.specify4_snd, e.get `specify.specify5_fst, e.get `specify.specify5_snd, guard $ 12 = e.fold 0 -- there are no other lemmas generated (λ d n, n + if d.to_name.components.init.ilast = `specify then 1 else 0), success_if_fail_with_msg (simps_tac `specify.specify1 {} ["fst_fst"]) "Invalid simp-lemma specify.specify1_fst_fst. Projection fst doesn't exist, because target is not a structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["foo_fst"]) "Invalid simp-lemma specify.specify1_foo_fst. Structure prod does not have projection foo. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify1 {} ["snd_bar"]) "Invalid simp-lemma specify.specify1_snd_bar. Structure prod does not have projection bar. The known projections are: [fst, snd] You can also see this information by running `initialize_simps_projections? prod`. Note: these projection names might not correspond to the projection names of the structure.", success_if_fail_with_msg (simps_tac `specify.specify5 {} ["snd_snd"]) "Invalid simp-lemma specify.specify5_snd_snd. The given definition is not a constructor application: classical.choice specify.specify5._proof_1" /- We also eta-reduce if we explicitly specify the projection. -/ attribute [simps extra] test run_cmd do e ← get_env, d1 ← e.get `test_extra, d2 ← e.get `test_extra_2, guard $ d1.type =ₐ d2.type, skip /- check short_name option -/ @[simps {short_name := tt}] def short_name1 : my_prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ run_cmd do e ← get_env, e.get `short_name1_fst, e.get `short_name1_fst_2, e.get `short_name1_snd, e.get `short_name1_snd_2 /- check simp_rhs option -/ @[simps {simp_rhs := tt}] def equiv.trans {α β γ} (f : α ≃ β) (g : β ≃ γ) : α ≃ γ := ⟨g.to_fun ∘ f.to_fun, f.inv_fun ∘ g.inv_fun, by { intro x, simp [equiv.left_inv _ _] }, by { intro x, simp [equiv.right_inv _ _] }⟩ example {α β γ : Type} (f : α ≃ β) (g : β ≃ γ) (x : α) : (f.trans g).to_fun x = (f.trans g).to_fun x := begin dsimp only [equiv.trans_to_fun], guard_target g.to_fun (f.to_fun x) = g.to_fun (f.to_fun x), refl, end local attribute [simp] nat.zero_add nat.one_mul nat.mul_one @[simps {simp_rhs := tt}] def my_nat_equiv : ℕ ≃ ℕ := ⟨λ n, 0 + n, λ n, 1 * n * 1, by { intro n, simp }, by { intro n, simp }⟩ run_cmd success_if_fail (has_attribute `_refl_lemma `my_nat_equiv_to_fun) >> has_attribute `_refl_lemma `equiv.trans_to_fun example (n : ℕ) : my_nat_equiv.to_fun (my_nat_equiv.to_fun $ my_nat_equiv.inv_fun n) = n := by { success_if_fail { refl }, simp only [my_nat_equiv_to_fun, my_nat_equiv_inv_fun] } @[simps {simp_rhs := tt}] def succeed_without_simplification_possible : ℕ ≃ ℕ := ⟨λ n, n, λ n, n, by { intro n, refl }, by { intro n, refl }⟩ /- test that we don't recursively take projections of `prod` and `pprod` -/ @[simps] def pprod_equiv_prod : pprod ℕ ℕ ≃ ℕ × ℕ := { to_fun := λ x, ⟨x.1, x.2⟩, inv_fun := λ x, ⟨x.1, x.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun, e.get `pprod_equiv_prod_inv_fun attribute [simps to_fun_fst inv_fun_snd] pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod_to_fun_fst, e.get `pprod_equiv_prod_inv_fun_snd -- we can disable this behavior with the option `not_recursive`. @[simps {not_recursive := []}] def pprod_equiv_prod2 : pprod ℕ ℕ ≃ ℕ × ℕ := pprod_equiv_prod run_cmd do e ← get_env, e.get `pprod_equiv_prod2_to_fun_fst, e.get `pprod_equiv_prod2_to_fun_snd, e.get `pprod_equiv_prod2_inv_fun_fst, e.get `pprod_equiv_prod2_inv_fun_snd /- Tests with universe levels -/ class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg @[simps] instance types : category_struct (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } example (X : Type u) : (X ⟶ X) = (X → X) := by simp example (X : Type u) : 𝟙 X = (λ x, x) := by { funext, simp } example (X Y Z : Type u) (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := by { funext, simp } namespace coercing structure foo_str := (c : Type) (x : c) instance : has_coe_to_sort foo_str := ⟨_, foo_str.c⟩ @[simps] def foo : foo_str := ⟨ℕ, 3⟩ @[simps] def foo2 : foo_str := ⟨ℕ, 34⟩ example : ↥foo = ℕ := by simp only [foo_c] example : foo.x = (3 : ℕ) := by simp only [foo_x] structure voo_str (n : ℕ) := (c : Type) (x : c) instance has_coe_voo_str (n : ℕ) : has_coe_to_sort (voo_str n) := ⟨_, voo_str.c⟩ @[simps] def voo : voo_str 7 := ⟨ℕ, 3⟩ @[simps] def voo2 : voo_str 4 := ⟨ℕ, 34⟩ example : ↥voo = ℕ := by simp only [voo_c] example : voo.x = (3 : ℕ) := by simp only [voo_x] structure equiv2 (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) instance {α β} : has_coe_to_fun $ equiv2 α β := ⟨_, equiv2.to_fun⟩ @[simps] protected def rfl2 {α} : equiv2 α α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ example {α} (x : α) : coercing.rfl2 x = x := by rw [coercing.rfl2_to_fun] example {α} (x : α) : coercing.rfl2 x = x := by simp example {α} (x : α) : coercing.rfl2.inv_fun x = x := by simp @[simps] protected def equiv2.symm {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ @[simps] protected def equiv2.symm2 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f.to_fun, f.right_inv, f.left_inv⟩ /- we can use the `md` attribute to not unfold the `has_coe_to_fun` attribute, so that `@[simps]` doesn't recognize that the type of `⇑f` is still a function type. -/ @[simps {type_md := reducible}] protected def equiv2.symm3 {α β} (f : equiv2 α β) : equiv2 β α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ example {α β} (f : equiv2 α β) (y : β) : f.symm y = f.inv_fun y := by simp example {α β} (f : equiv2 α β) (x : α) : f.symm.inv_fun x = f x := by simp example {α β} (f : equiv2 α β) : f.symm.inv_fun = f := by { success_if_fail {simp}, refl } example {α β} (f : equiv2 α β) : f.symm3.inv_fun = f := by simp section set_option old_structure_cmd true class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) end @[simps] instance {α β} [semigroup α] [semigroup β] : semigroup (α × β) := { mul := λ x y, (x.1 * y.1, x.2 * y.2), mul_assoc := by { intros, simp only [semigroup.mul_assoc], refl } } example {α β} [semigroup α] [semigroup β] (x y : α × β) : x * y = (x.1 * y.1, x.2 * y.2) := by simp example {α β} [semigroup α] [semigroup β] (x y : α × β) : (x * y).1 = x.1 * y.1 := by simp structure Semigroup := (G : Type*) (op : G → G → G) (infix * := op) (op_assoc : ∀ (x y z : G), (x * y) * z = x * (y * z)) namespace Group instance : has_coe_to_sort Semigroup := ⟨_, Semigroup.G⟩ -- We could try to generate lemmas with this `has_mul` instance, but it is unused in mathlib. -- Therefore, this is ignored. instance (G : Semigroup) : has_mul G := ⟨G.op⟩ @[simps] def prod_Semigroup (G H : Semigroup) : Semigroup := { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc := by { intros, dsimp [Group.has_mul], simp [Semigroup.op_assoc] }} end Group section set_option old_structure_cmd true class extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) end @[simps] def bar : extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end class new_extending_stuff (G : Type u) extends has_mul G, has_zero G, has_neg G, has_subset G := (new_axiom : ∀ x : G, x * - 0 ⊆ - x) @[simps] def new_bar : new_extending_stuff ℕ := { mul := (*), zero := 0, neg := nat.succ, subset := λ x y, true, new_axiom := λ x, trivial } section local attribute [instance] new_bar example (x : ℕ) : x * - 0 ⊆ - x := by simp end end coercing namespace manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := manual_coercion.equiv variables {α β γ : Sort*} instance : has_coe_to_fun $ α ≃ β := ⟨_, equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_inv_fun] end manual_coercion namespace faulty_manual_coercion structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := faulty_manual_coercion.equiv variables {α β γ : Sort*} /-- See Note [custom simps projection] -/ noncomputable def equiv.simps.inv_fun (e : α ≃ β) : β → α := classical.choice ⟨e.inv_fun⟩ run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_manual_coercion.equiv) "Invalid custom projection: λ {α : Sort u_1} {β : Sort u_2} (e : α ≃ β), classical.choice _ Expression is not definitionally equal to λ (α : Sort u_1) (β : Sort u_2) (x : α ≃ β), x.inv_fun." end faulty_manual_coercion namespace manual_initialize /- defining a manual coercion. -/ variables {α β γ : Sort*} structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := manual_initialize.equiv instance : has_coe_to_fun $ α ≃ β := ⟨_, equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv run_cmd has_attribute `_simps_str `manual_initialize.equiv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ end manual_initialize namespace faulty_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := faulty_universes.equiv instance : has_coe_to_fun $ α ≃ β := ⟨_, equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different names for the universe variables for equiv.symm than for -- equiv def equiv.simps.inv_fun {α : Type u} {β : Type v} (e : α ≃ β) : β → α := e.symm run_cmd do e ← get_env, success_if_fail_with_msg (simps_get_raw_projections e `faulty_universes.equiv) "Invalid custom projection: λ {α : Type u} {β : Type v} (e : α ≃ β), ⇑(e.symm) Expression has different type than faulty_universes.equiv.inv_fun. Given type: Π {α : Type u} {β : Type v} (e : α ≃ β), has_coe_to_fun.F e.symm Expected type: Π (α : Sort u) (β : Sort v), α ≃ β → β → α" end faulty_universes namespace manual_universes variables {α β γ : Sort*} structure equiv (α : Sort u) (β : Sort v) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := manual_universes.equiv instance : has_coe_to_fun $ α ≃ β := ⟨_, equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ -- test: intentionally using different unvierse levels for equiv.symm than for equiv def equiv.simps.inv_fun {α : Sort w} {β : Sort u} (e : α ≃ β) : β → α := e.symm -- check whether we can generate custom projections even if the universe names don't match initialize_simps_projections equiv end manual_universes namespace manual_projection_names structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := manual_projection_names.equiv variables {α β γ : Sort*} instance : has_coe_to_fun $ α ≃ β := ⟨_, equiv.to_fun⟩ def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ /-- See Note [custom simps projection] -/ def equiv.simps.symm_apply (e : α ≃ β) : β → α := e.symm -- set_option trace.simps.debug true initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) run_cmd do e ← get_env, data ← simps_get_raw_projections e `manual_projection_names.equiv, guard $ data.2.map prod.fst = [`apply, `symm_apply] @[simps {simp_rhs := tt}] protected def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : α) : (e₁.trans e₂) x = e₂ (e₁ x) := by simp only [equiv.trans_apply] example (e₁ : α ≃ β) (e₂ : β ≃ γ) (x : γ) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := by simp only [equiv.trans_symm_apply] -- the new projection names are parsed correctly (the old projection names won't work anymore) @[simps apply symm_apply] protected def equiv.trans2 (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ -- initialize_simps_projections equiv end manual_projection_names -- test transparency setting structure set_plus (α : Type) := (s : set α) (x : α) (h : x ∈ s) @[simps] def nat_set_plus : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus.s = set.univ := begin dsimp only [nat_set_plus_s], guard_target @set.univ ℕ = set.univ, refl end @[simps {type_md := semireducible}] def nat_set_plus2 : set_plus ℕ := ⟨set.univ, 1, trivial⟩ example : nat_set_plus2.s = set.univ := begin success_if_fail { dsimp only [nat_set_plus2_s] }, refl end @[simps {rhs_md := semireducible}] def nat_set_plus3 : set_plus ℕ := nat_set_plus example : nat_set_plus3.s = set.univ := begin dsimp only [nat_set_plus3_s], guard_target @set.univ ℕ = set.univ, refl end namespace nested_non_fully_applied structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) local infix ` ≃ `:25 := nested_non_fully_applied.equiv variables {α β γ : Sort*} @[simps] def equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun⟩ @[simps {rhs_md := semireducible, fully_applied := ff}] def equiv.symm2 : (α ≃ β) ≃ (β ≃ α) := ⟨equiv.symm, equiv.symm⟩ example (e : α ≃ β) : (equiv.symm2.inv_fun e).to_fun = e.inv_fun := begin dsimp only [equiv.symm2_inv_fun_to_fun], guard_target e.inv_fun = e.inv_fun, refl end /- do not prematurely unfold `equiv.symm`, unless necessary -/ @[simps to_fun to_fun_to_fun {rhs_md := semireducible}] def equiv.symm3 : (α ≃ β) ≃ (β ≃ α) := equiv.symm2 example (e : α ≃ β) (y : β) : (equiv.symm3.to_fun e).to_fun y = e.inv_fun y ∧ (equiv.symm3.to_fun e).to_fun y = e.inv_fun y := begin split, { dsimp only [equiv.symm3_to_fun], guard_target e.symm.to_fun y = e.inv_fun y, refl }, { dsimp only [equiv.symm3_to_fun_to_fun], guard_target e.inv_fun y = e.inv_fun y, refl } end end nested_non_fully_applied -- test that type classes which are props work class prop_class (n : ℕ) : Prop := (has_true : true) instance has_prop_class (n : ℕ) : prop_class n := ⟨trivial⟩ structure needs_prop_class (n : ℕ) [prop_class n] := (t : true) @[simps] def test_prop_class : needs_prop_class 1 := { t := trivial } /- check that when the coercion is given in eta-expanded form, we can also find the coercion. -/ structure alg_hom (R A B : Type*) := (to_fun : A → B) instance (R A B : Type*) : has_coe_to_fun (alg_hom R A B) := ⟨_, λ f, f.to_fun⟩ @[simps] def my_alg_hom : alg_hom unit bool bool := { to_fun := id } example (x : bool) : my_alg_hom x = id x := by simp only [my_alg_hom_to_fun] structure ring_hom (A B : Type*) := (to_fun : A → B) instance (A B : Type*) : has_coe_to_fun (ring_hom A B) := ⟨_, λ f, f.to_fun⟩ @[simps] def my_ring_hom : ring_hom bool bool := { to_fun := id } example (x : bool) : my_ring_hom x = id x := by simp only [my_ring_hom_to_fun] /- check interaction with the `@[to_additive]` attribute -/ @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ run_cmd do e ← get_env, e.get `prod.has_mul_mul, e.get `prod.has_add_add, has_attribute `to_additive `prod.has_mul, has_attribute `to_additive `prod.has_mul_mul, has_attribute `simp `prod.has_mul_mul, has_attribute `simp `prod.has_add_add example {M N} [has_mul M] [has_mul N] (p q : M × N) : p * q = ⟨p.1 * q.1, p.2 * q.2⟩ := by simp example {M N} [has_add M] [has_add N] (p q : M × N) : p + q = ⟨p.1 + q.1, p.2 + q.2⟩ := by simp /- The names of the generated simp lemmas for the additive version are not great if the definition had a custom additive name -/ @[to_additive my_add_instance, simps] instance my_instance {M N} [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ run_cmd do e ← get_env, e.get `my_instance_one, e.get `my_instance_zero, has_attribute `to_additive `my_instance, has_attribute `to_additive `my_instance_one, has_attribute `simp `my_instance_one, has_attribute `simp `my_instance_zero example {M N} [has_one M] [has_one N] : (1 : M × N) = ⟨1, 1⟩ := by simp example {M N} [has_zero M] [has_zero N] : (0 : M × N) = ⟨0, 0⟩ := by simp section /-! Test `dsimp, simp` with the option `simp_rhs` -/ local attribute [simp] nat.add structure my_type := (A : Type) @[simps {simp_rhs := tt}] def my_type_def : my_type := ⟨{ x : fin (nat.add 3 0) // 1 + 1 = 2 }⟩ example (h : false) (x y : { x : fin (nat.add 3 0) // 1 + 1 = 2 }) : my_type_def.A = unit := begin simp only [my_type_def_A], guard_target ({ x : fin 3 // true } = unit), /- note: calling only one of `simp` or `dsimp` does not produce the current target, as the following tests show. -/ success_if_fail { guard_hyp x : { x : fin 3 // true } }, dsimp at x, success_if_fail { guard_hyp x : { x : fin 3 // true } }, simp at y, success_if_fail { guard_hyp y : { x : fin 3 // true } }, simp at x, dsimp at y, guard_hyp x : { x : fin 3 // true }, guard_hyp y : { x : fin 3 // true }, contradiction end /- Test that `to_additive` copies the `@[_refl_lemma]` attribute correctly -/ @[to_additive, simps] def monoid_hom.my_comp {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } -- `simps` adds the `_refl_lemma` attribute to `monoid_hom.my_comp_apply` example {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } -- `to_additive` adds the `_refl_lemma` attribute to `add_monoid_hom.my_comp_apply` example {M N P : Type*} [add_zero_class M] [add_zero_class N] [add_zero_class P] (hnp : N →+ P) (hmn : M →+ N) (m : M) : hnp.my_comp hmn m = hnp (hmn m) := by { dsimp, guard_target (hnp (hmn m) = hnp (hmn m)), refl } end /- Test custom compositions of projections. -/ section comp_projs instance {α β} : has_coe_to_fun (α ≃ β) := ⟨λ _, α → β, equiv.to_fun⟩ @[simps] protected def equiv.symm {α β} (f : α ≃ β) : β ≃ α := ⟨f.inv_fun, f, f.right_inv, f.left_inv⟩ structure decorated_equiv (α : Sort*) (β : Sort*) extends equiv α β := (P_to_fun : function.injective to_fun ) (P_inv_fun : function.injective inv_fun) instance {α β} : has_coe_to_fun (decorated_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv⟩ def decorated_equiv.symm {α β : Sort*} (e : decorated_equiv α β) : decorated_equiv β α := { to_equiv := e.to_equiv.symm, P_to_fun := e.P_inv_fun, P_inv_fun := e.P_to_fun } def decorated_equiv.simps.apply {α β : Sort*} (e : decorated_equiv α β) : α → β := e def decorated_equiv.simps.symm_apply {α β : Sort*} (e : decorated_equiv α β) : β → α := e.symm initialize_simps_projections decorated_equiv (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) @[simps] def foo (α : Type) : decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h } example {α : Type} (x : α) : (foo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps to_equiv apply symm_apply] def foo2 (α : Type) : decorated_equiv α α := { P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, ..foo.rfl } example {α : Type} (x : α) : (foo2 α).to_equiv x = x := by { dsimp, guard_target (foo.rfl x = x), refl } example {α : Type} (x : α) : foo2 α x = x := by { dsimp, guard_target (x = x), refl } structure further_decorated_equiv (α : Sort*) (β : Sort*) extends decorated_equiv α β := (Q_to_fun : function.surjective to_fun ) (Q_inv_fun : function.surjective inv_fun ) instance {α β} : has_coe_to_fun (further_decorated_equiv α β) := ⟨λ _, α → β, λ f, f.to_decorated_equiv⟩ def further_decorated_equiv.symm {α β : Sort*} (e : further_decorated_equiv α β) : further_decorated_equiv β α := { to_decorated_equiv := e.to_decorated_equiv.symm, Q_to_fun := e.Q_inv_fun, Q_inv_fun := e.Q_to_fun } def further_decorated_equiv.simps.apply {α β : Sort*} (e : further_decorated_equiv α β) : α → β := e def further_decorated_equiv.simps.symm_apply {α β : Sort*} (e : further_decorated_equiv α β) : β → α := e.symm initialize_simps_projections further_decorated_equiv (to_decorated_equiv_to_equiv_to_fun → apply, to_decorated_equiv_to_equiv_inv_fun → symm_apply, -to_decorated_equiv, to_decorated_equiv_to_equiv → to_equiv, -to_equiv) @[simps] def ffoo (α : Type) : further_decorated_equiv α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (ffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps] def ffoo3 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, .. foo α } @[simps apply to_equiv_to_fun to_decorated_equiv_apply] def ffoo4 (α : Type) : further_decorated_equiv α α := { Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩, to_decorated_equiv := foo α } structure one_more (α : Sort*) (β : Sort*) extends further_decorated_equiv α β instance {α β} : has_coe_to_fun (one_more α β) := ⟨λ _, α → β, λ f, f.to_further_decorated_equiv⟩ def one_more.symm {α β : Sort*} (e : one_more α β) : one_more β α := { to_further_decorated_equiv := e.to_further_decorated_equiv.symm } def one_more.simps.apply {α β : Sort*} (e : one_more α β) : α → β := e def one_more.simps.symm_apply {α β : Sort*} (e : one_more α β) : β → α := e.symm initialize_simps_projections one_more (to_further_decorated_equiv_to_decorated_equiv_to_equiv_to_fun → apply, to_further_decorated_equiv_to_decorated_equiv_to_equiv_inv_fun → symm_apply, -to_further_decorated_equiv, to_further_decorated_equiv_to_decorated_equiv → to_dequiv, -to_dequiv) @[simps] def fffoo (α : Type) : one_more α α := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, P_to_fun := λ x y h, h, P_inv_fun := λ x y h, h, Q_to_fun := λ y, ⟨y, rfl⟩, Q_inv_fun := λ y, ⟨y, rfl⟩ } example {α : Type} (x : α) : (fffoo α).symm x = x := by { dsimp, guard_target (x = x), refl } @[simps apply to_dequiv_apply to_further_decorated_equiv_apply to_dequiv] def fffoo2 (α : Type) : one_more α α := fffoo α end comp_projs
C$Procedure WRENCD ( Write encoded d.p. numbers to text file ) SUBROUTINE WRENCD ( UNIT, N, DATA ) C$ Abstract C C Encode and write d.p. numbers to a text file. C C$ Disclaimer C C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE C SOFTWARE AND RELATED MATERIALS, HOWEVER USED. C C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. C C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. C C$ Required_Reading C C None. C C$ Keywords C C CONVERSION C NUMBERS C UTILITY C C$ Declarations INTEGER UNIT INTEGER N DOUBLE PRECISION DATA(*) C$ Brief_I/O C C Variable I/O Description C -------- --- -------------------------------------------------- C UNIT I Fortran unit number of output text file. C N I Number of d.p. numbers to encode and write. C DATA I List of d.p. numbers to encode and write. C C$ Detailed_Input C C UNIT The Fortran unit number for a previously opened text C file. All writing will begin at the CURRENT POSITION C in the text file. C C N The number of double precision numbers to be encoded C and written to the text file attached to UNIT. C C DATA List of double precision numbers to be encoded and C written to the text file attached to UNIT. C C$ Detailed_Output C C See the Particulars section for a description of the effect of C this routine. C C$ Parameters C C None. C C$ Exceptions C C 1) If N, the number of data items, is not positive, the error C SPICE(INVALIDARGUMENT) will be signalled. C C 2) If an error occurs while writing to the text file attached C to UNIT, the error SPICE(FILEWRITEFAILED) will be signalled. C C 3) If the Fortran logical unit UNIT is not defined, the results C of this routine are unpredictable. C C$ Files C C See the description of UNIT in the Detailed_Input section. C C$ Particulars C C This routine will accept a list of one or more double precision C numbers which it will encode into equivalent text strings and C write to the current position in a text file. The current C position in a file is defined to be the text line immediately C following the last text line that was written or read. The C encoded d.p. numbers are written to the output text file as C quoted character strings so that a Fortran list directed read may C be used to read the encoded values, rather than a formatted read C with the format specifier FMT = '(A)'. C C This routine is one of a pair of routines which are used to C encode and decode d.p. numbers: C C WRENCD -- Encode and write d.p. numbers to a file. C RDENCD -- Read and decode d.p. numbers from a file. C C The encoding/decoding of d.p.numbers is performed to provide a C portable means for transferring data values. C C Currently the text string produced will be in a base 16 C ``scientific notation.'' This format retains the full precision C available for d.p. numbers on any given computer architecture. C See DP2HX.FOR and HX2DP.FOR for details. C C$ Examples C C Please note that the output format in the examples is not C intended to be exactly identical with the output format of this C routine in actual use. The output format used in the examples is C intended to aid in the understanding of how this routine works. C It is NOT intended to be a specification of the output format for C this routine. C C Let C C UNIT be the Fortran logical unit of a previously opened C text file. C C N = 100 C C DATA(I) = DBLE(I), I = 1,N C C Then, the subroutine call C C CALL WRENCD( UNIT, N, DATA ) C C will write the first 100 integers as encoded d.p. numbers to the C output text file attached to UNIT, beginning at the current C position in the output file, which is marked by an arrow, '-->'. C The resulting output will look something like the following: C C -->'1^1' '2^1' '3^1' '4^1' '5^1' '6^1' '7^1' '8^1' '9^1' C 'A^1' 'B^1' 'C^1' 'D^1' 'E^1' 'F^1' '1^2' '11^2' '12^2' C '13^2' '14^2' '15^2' '16^2' '17^2' '18^2' '19^2' '1A^2' C '1B^2' '1C^2' '1D^2' '1E^2' '1F^2' '2^2' '21^2' '22^2' C '23^2' '24^2' '25^2' '26^2' '27^2' '28^2' '29^2' '2A^2' C '2B^2' '2C^2' '2D^2' '2E^2' '2F^2' '3^2' '31^2' '32^2' C '33^2' '34^2' '35^2' '36^2' '37^2' '38^2' '39^2' '3A^2' C '3B^2' '3C^2' '3D^2' '3E^2' '3F^2' '4^2' C '41^2' '42^2' '43^2' '44^2' '45^2' '46^2' '47^2' '48^2' C '49^2' '4A^2' '4B^2' '4C^2' '4D^2' '4E^2' '4F^2' '5^2' C '51^2' '52^2' '53^2' '54^2' '55^2' '56^2' '57^2' '58^2' C '59^2' '5A^2' '5B^2' '5C^2' '5D^2' '5E^2' '5F^2' '6^2' C '61^2' '62^2' '63^2' '64^2' C --> C C At this point, the arrow marks the position of the file pointer C immediately after the call to WRENCD. C C$ Restrictions C C None. C C$ Literature_References C C None. C C$ Author_and_Institution C C K.R. Gehringer (JPL) C C$ Version C C- SPICELIB Version 1.2.0, 09-SEP-1993 (KRG) C C The list directed write was changed to a formatted write using C the specifier FMT='(A)'. This was done in order to prevent a C space from appearing as the first character on each line of the C file for certian computer platforms. C C- SPICELIB Version 1.1.0, 21-JUN-1993 (KRG) C C This routine was modified to avoid the creation of long output C lines on some of the supported systems, such as the NeXT with C Absoft Fortran 3.2. C C A disclaimer was added to the $ Examples section concerning C the output format used. The disclaimer simply states that the C output format used in the example is not necessarily the C output format actually used by the routine. C C- SPICELIB Version 1.0.0, 20-OCT-1992 (KRG) C C-& C$ Index_Entries C C encode and write d.p. numbers to a text file C C-& C$ Revisions C C- SPICELIB Version 1.2.0, 09-SEP-1993 (KRG) C C The list directed write was changed to a formatted write using C the specifier FMT='(A)'. This was done in order to prevent a C space from appearing as the first character on each line of the C file for certian computer platforms. C C- SPICELIB Version 1.1.0, 21-JUN-1993 (KRG) C C This routine was modified to avoid the creation of long output C lines on some of the supported systems, such as the NeXT with C Absoft Fortran 3.2. C C On some of the supported computers this routine would produce C very long (greater than 1000 characters) output lines due to C the implicit DO loop used in the WRITE statment: C C WRITE (UNIT,IOSTAT=IOSTAT,FMT=*) C . ( QUOTE//WORK(I)(1:LENGTH(I))//QUOTE//' ', I=1,NITMS ) C C This problem was fixed by removing the implicit DO loop from C the WRITE statement and placing an equivalent DO loop around C the WRITE statemtent: C C DO I = 1, NITMS C WRITE (UNIT,IOSTAT=IOSTAT,FMT=*) C . QUOTE//WORK(I)(1:LENGTH(I))//QUOTE C END DO C C The net effect of this will be that only a single datum will C be written on each line of output. C C A disclaimer was added to the $ Examples section concerning C the output format used. The disclaimer simply states that the C output format used in the example is not necessarily the C output format actually used by the routine. C C- SPICELIB Version 1.0.0, 20-OCT-1992 (KRG) C C-& C C SPICELIB functions C LOGICAL RETURN C C Local parameters C CHARACTER*(1) QUOTE PARAMETER ( QUOTE = '''' ) INTEGER MAXENC PARAMETER ( MAXENC = 64 ) INTEGER WRKSIZ PARAMETER ( WRKSIZ = 64 ) C C Local variables C CHARACTER*(MAXENC) WORK(WRKSIZ) INTEGER I INTEGER IOSTAT INTEGER ITMBEG INTEGER NITMS INTEGER LENGTH(WRKSIZ) C C Standard SPICE error handling. C IF ( RETURN () ) THEN RETURN ELSE CALL CHKIN ( 'WRENCD' ) END IF C C Check to see if the number of data items is less than or equal C to zero. If it is, signal an error. C IF ( N .LT. 1 ) THEN CALL SETMSG ( 'The number of data items to be written was' // . ' not positive: #.' ) CALL ERRINT ( '#', N ) CALL SIGERR ( 'SPICE(INVALIDARGUMENT)' ) CALL CHKOUT ( 'WRENCD' ) RETURN END IF C C Initialize the beginning location for the data items to be C encoded. C ITMBEG = 1 C C Begin encoding the input data items in blocks of size NITMS. C Each time the number of data items NITMS is reached, write C out the encoded items in the workspace. C DO WHILE ( ITMBEG .LE. N ) C C The number of items is either the size of the workspace, or C the number of data items which remain to be processed, which C should always be less than or equal to the size of the C workspace. C NITMS = MIN ( WRKSIZ, N - ITMBEG + 1 ) C C Encode each of the numbers into an equivalent character string. C DO I = 1, NITMS CALL DP2HX ( DATA(ITMBEG + I - 1), WORK(I), LENGTH(I) ) END DO C C Write out the current workspace, placing single quotes around C each of the character strings so that they may be read using C Fortran list directed read statements rather than the format C specifier FMT = '(A)'. C DO I = 1, NITMS WRITE ( UNIT,FMT='(A)',IOSTAT=IOSTAT ) . QUOTE//WORK(I)(1:LENGTH(I))//QUOTE C C Check to see if we got a write error, IOSTAT .NE. 0. C IF ( IOSTAT .NE. 0 ) THEN CALL SETMSG ( 'Error writing to logical unit #,' // . ' IOSTAT = #.' ) CALL ERRINT ( '#', UNIT ) CALL ERRINT ( '#', IOSTAT ) CALL SIGERR ( 'SPICE(FILEWRITEFAILED)' ) CALL CHKOUT ( 'WRENCD' ) RETURN END IF END DO C C Position the data item pointer at the next location to begin C encoding the items in the array DATA, and continue processing C the data items until done. C ITMBEG = ITMBEG + NITMS END DO CALL CHKOUT ( 'WRENCD' ) RETURN END
import algebra.group data.set.basic group_theory.subgroup group_theory.quotient_group open function quotient_group is_subgroup is_group_hom universe u --Todo: prove the first isomorphism theorem variables {G : Type*} {H : Type*} [group G] [group H] variables (N K : set G) variables [is_subgroup N] [is_subgroup K] -- introducing the group isomorphism class is_group_isom (f : G → H) extends is_group_hom f : Prop := (group_bij : bijective f) namespace is_group_isom variables (f : G → H) [is_group_isom f] def automorphism (f₁ : G → G) := is_group_isom f₁ --lemma quot_is_isom (f :) theorem isomorphism_thm_one (φ : G → H) [is_group_hom φ] : surjective φ → ∃ (f₂ : (quotient (ker φ)) → H), is_group_isom f₂ := begin intros, existsi _, swap, sorry, end end is_group_isom class is_ring_isom {α : Type*} {β : Type*} [ring α] [ring β] (f : α → β) extends is_ring_hom f : Prop := (ring_bij : bijective f) #print notation $ -- s $ t means s(t) where s is a function, and t is the input. the reason this exists is because it has very low binding power, so you can evaluate t first, then s $ t, making it a better alternative to s(t)
Know Lamar High Class of 2017 graduates that are NOT on this List? Help us Update the 2017 Class List by adding missing names. More 2017 alumni from Lamar HS Lamar, SC have posted profiles on Classmates.com®. Click here to register for free at Classmates.com® and view other 2017 alumni. If you are trying to find people that graduated in '17 at LHS in Lamar, SC, check the alumni list below that shows the class of 2017. If you are an alumn of Lamar High you should register now in the alumni directory. We also encourage you to interact with the rest of the alumni on this site. You can find old friends, share photos and stay updated on the latest school news.
The boundary of a ball is the sphere.
The boundary of a ball is the sphere.
-- -- Pool : image pool -- module Pool ( PoolClass , Pool , getImages , getImagesRandomly , nSample , nClass , initSamplePool , initFilePool , loadImage ) where import Control.Exception import Control.Monad import Data.List import qualified Data.Map as Map import Data.Maybe import Debug.Trace import Numeric.LinearAlgebra import System.Directory import qualified System.IO.Strict as SIO import qualified System.Random.Mersenne as MT import CNN.Image class PoolClass p where {- getImages IN : pool batch size offset -} getImages :: p -> Int -> Int -> IO [Trainer] getImagesRandomly :: p -> Int -> Int -> IO [Trainer] nSample :: p -> Int nClass :: p -> Int type ImageFile = (Int, String) data Pool = MemPool { m :: Map.Map Int Trainer , c :: Int } | FilePool { imageFiles :: [[ImageFile]] , numclass :: Int , classvec :: [Class] } instance PoolClass Pool where getImages p@(MemPool m _) bt ofs = do let s = nSample p o = ofs `mod` s mx0 = o + bt - 1 mx2 = mx0 - s mx1 = if mx2 < 0 then mx0 else s - 1 im0 = mapMaybe (`Map.lookup` m) [o..mx1] im1 = mapMaybe (`Map.lookup` m) [0..mx2] return (im0 ++ im1) getImages (FilePool flist nc cv) bt ofs = do let flist' = selectPerClass flist bt ofs ts <- forM flist' $ \(c, fn) -> do im <- loadImage fn return $ Just (im, cv !! c) let trainers = catMaybes ts return trainers getImagesRandomly p@(MemPool m _) bt s = do r0 <- MT.randomIO :: IO Double let r = if r0 == 1.0 then 0.0 else r0 s = nSample p ofs = floor (r * (fromIntegral s)) getImages p bt ofs getImagesRandomly p@(FilePool flist nc _) bt s = do r0 <- MT.randomIO :: IO Double let r = if r0 == 1.0 then 0.0 else r0 s = nSample p `div` nc ofs = floor (r * (fromIntegral s)) getImages p bt ofs nSample (MemPool m _) = Map.size m nSample (FilePool flist _ _) = count flist where count :: [[ImageFile]] -> Int count [] = 0 count (x:xs) = length x + count xs nClass (MemPool _ c) = c nClass (FilePool _ c _) = c ---- IMAGE POOL ON MEMORY ---- ------------------------------ {- initSamplePool IN : channel image size output size (#class) probablity n samples OUT: memory pool -} initSamplePool :: Int -> (Int, Int) -> Int -> Double -> Int -> IO Pool initSamplePool c (sx, sy) o p n = do s0 <- forM [0..(n-1)] $ \i -> do let cl = i `mod` o -- class of this image -- Image data s1 <- forM [1..c] $ \j -> do w <-forM [0..(sy-1)] $ \y -> do let p' = if y `div` st == cl then p else 1-p forM [1..sx] $ \x -> pixel p' return $ fromLists w -- Trainer data e1 <- forM [0..(o-1)] $ \j -> return $ if j == cl then 1.0 else 0.0 return (s1, fromList e1) return (MemPool (Map.fromList $ zip [0..] s0) c) where st = sy `div` o pixel :: Double -> IO Double pixel p = do v <- MT.randomIO :: IO Double let v' = if v < p then 0.5 else 0.0 return v' ---- IMAGE POOL FROM FILES ---- ------------------------------- {- | initFilePool IN : pool dir path number of class OUT: -} initFilePool :: String -> Int -> IO Pool initFilePool path nc = do let classv = map (classNumToVec nc) [0..(nc-1)] flist <- forM [0..(nc-1)] $ \i -> do let dir = path ++ "/" ++ (show i) ++ "/" --files <- listDirectory dir files <- getDirectoryContents dir let files' = map (makeImageFile i dir) $ filter (isSuffixOf ".dat") files return files' return (FilePool flist nc classv) where makeImageFile :: Int -> String -> String -> ImageFile makeImageFile i dir fn = (i, dir ++ fn) loadImage :: String -> IO Image loadImage fn = do res <- try $ (SIO.run $ SIO.readFile fn) :: IO (Either SomeException String) return $ case res of Left e -> error ("read error:" ++ (show e)) Right s -> read s :: Image -- -- PRIVATE FUNCTIONS -- selectPerClass :: [[ImageFile]] -> Int -> Int -> [ImageFile] selectPerClass [] _ _ = [] selectPerClass (x:xs) bt ofs = fl ++ (selectPerClass xs bt ofs) where len = length x ofs' = ofs `mod` len ed = ofs' + bt - 1 ed' = if ed > len then (ed - len) `mod` len else ed range = if ed' >= ofs' then [ofs' .. ed'] else [0..ed'] ++ [ofs'..(len - 1)] fl = map (x !!) range
[STATEMENT] lemma Iff_Dis: assumes \<open>A; B \<turnstile>\<^sub>! p \<^bold>\<longleftrightarrow>\<^sub>! p'\<close> \<open>A; B \<turnstile>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! q'\<close> shows \<open>A; B \<turnstile>\<^sub>! ((p \<^bold>\<or>\<^sub>! q) \<^bold>\<longleftrightarrow>\<^sub>! (p' \<^bold>\<or>\<^sub>! q'))\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] have \<open>A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! ((p \<^bold>\<or>\<^sub>! q) \<^bold>\<longleftrightarrow>\<^sub>! (p' \<^bold>\<or>\<^sub>! q'))\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] by (simp add: PA1) [PROOF STATE] proof (state) this: A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] then [PROOF STATE] proof (chain) picking this: A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] using assms PR1 [PROOF STATE] proof (prove) using this: A; B \<turnstile>\<^sub>! (p \<^bold>\<longleftrightarrow>\<^sub>! p') \<^bold>\<longrightarrow>\<^sub>! (q \<^bold>\<longleftrightarrow>\<^sub>! q') \<^bold>\<longrightarrow>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' A; B \<turnstile>\<^sub>! p \<^bold>\<longleftrightarrow>\<^sub>! p' A; B \<turnstile>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! q' \<lbrakk>?A; ?B \<turnstile>\<^sub>! ?p; ?A; ?B \<turnstile>\<^sub>! ?p \<^bold>\<longrightarrow>\<^sub>! ?q\<rbrakk> \<Longrightarrow> ?A; ?B \<turnstile>\<^sub>! ?q goal (1 subgoal): 1. A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' [PROOF STEP] by blast [PROOF STATE] proof (state) this: A; B \<turnstile>\<^sub>! p \<^bold>\<or>\<^sub>! q \<^bold>\<longleftrightarrow>\<^sub>! p' \<^bold>\<or>\<^sub>! q' goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma has_typ1_imp_typ_of1: "has_typ1 Ts t ty \<Longrightarrow> typ_of1 Ts t = Some ty" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Ts \<turnstile>\<^sub>\<tau> t : ty \<Longrightarrow> typ_of1 Ts t = Some ty [PROOF STEP] by (induction rule: has_typ1.induct) auto
Require Export XR_R. Require Export XR_Ropp. Local Open Scope R_scope. Implicit Type r : R. Lemma Ropp_eq_compat : forall r1 r2, r1 = r2 -> - r1 = - r2. Proof. intros x y h. subst y. reflexivity. Qed.
/* Copyright (c) 2015, Max Krasnyansky <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <getopt.h> #include <sys/time.h> #include "hogl/detail/ostrbuf.hpp" #define BOOST_TEST_MODULE ostrbuf_test #include <boost/test/included/unit_test.hpp> class my_ostrbuf : public hogl::ostrbuf { private: void dump(const char *how, const uint8_t* data, size_t len) { fprintf(stdout, "\t%s: len %u [", how, (unsigned int) len); if (len > 60) { fwrite(data, 1, 57, stdout); fwrite("...", 1, 3, stdout); } else fwrite(data, 1, len, stdout); fprintf(stdout, "]\n"); } void do_flush(const uint8_t* data, size_t len) { fprintf(stdout, "my-ostrbuf::flush\n"); if (_size) { dump("flush-buffered", _data, _size); reset(); } if (len > room()) { dump("skip-buffering", data, len); return; } if (len) do_copy(data, len); } public: my_ostrbuf(unsigned int capacity) : hogl::ostrbuf(capacity) {} }; static void generate_output(hogl::ostrbuf &ob) { ob.cat("0123"); ob.cat("4567"); ob.cat("abcd"); ob.cat("0123456789abcdef"); ob.printf("arg0=%d arg1=%x arg2=%f arg3=%s", -125, ~0U, 125.67, "just-a-string"); ob.cat("efgh"); ob.cat("iklm"); ob.cat("xyz"); char insanely_long_string[64 * 1024]; for (unsigned int i = 0; i < sizeof(insanely_long_string)-1; i++) insanely_long_string[i] = 'A' + i % 26; insanely_long_string[sizeof(insanely_long_string)-1] = '\0'; ob.printf("insanely-long-string=%s", insanely_long_string); } BOOST_AUTO_TEST_CASE(basic) { my_ostrbuf ob8(8); generate_output(ob8); for (unsigned int i = 1; i <= 16; i *= 4) { my_ostrbuf *ob = new my_ostrbuf(i * 1024); generate_output(*ob); delete ob; } }
bathymetry_figures = function( p=NULL, varnames="z", logyvar=FALSE, isodepths = c( 100, 300, 500 ), savetofile="", width=1365, height=1024, pointsize=12, res=96, quality=80 ) { b = bathymetry_db( p=p, DS="complete" ) b = b[b$z > 0 , ] for (vn in varnames) { print(vn) if (logyvar) { b = b[ b[,vn]>0, ] b[,vn] = log(b[,vn]) } # oc = landmask( db="worldHires", regions=c("Canada", "US"), return.value="not.land", tag="predictions", crs=p$aegis_proj4string_planar_km ) # if (length(oc) > 0) { # b = b[oc,] # } b[,vn] = zapsmall( b[,vn] ) datarange = quantile( b[,vn], probs=c(0.05, 0.95), na.rm=TRUE ) dr = seq( datarange[1], datarange[2], length.out=100) ll = which( b[,vn] < datarange[1] ) if (length(ll>0)) b[ll,vn] = datarange[1] ul = which( b[,vn] > datarange[2] ) if (length(ul>0)) b[ul,vn] = datarange[2] levplt = levelplot( b[,vn] ~ plon + plat, data=b[,], aspect="iso", main=NULL, at=dr, col.regions=rev(color.code( "seis", dr)) , contour=FALSE, labels=FALSE, pretty=TRUE, xlab=NULL,ylab=NULL,scales=list(draw=FALSE), panel = function(x, y, subscripts, ...) { panel.levelplot (x, y, subscripts, aspect="iso", rez=c(1,1), ...) sp.lines( as( isobath_db( DS="isobath", depths=isodepths, project_to=p$aegis_proj4string_planar_km ), "Spatial" ), col = "gray80", cex=0.1 ) sp.lines( as( coastline_db( p=p, project_to=p$aegis_proj4string_planar_km ), "Spatial" ), col = "steelblue", cex=0.1 ) } ) if ( savetofile != "" ) { outdir = file.path( p$modeldir, p$stmv_model_label, p$project_class, paste( p$stmv_global_modelengine, p$stmv_local_modelengine, sep="_"), p$stmv_variables$Y, "maps", p$spatial_domain ) dir.create( outdir, showWarnings = TRUE, recursive = TRUE ) for (i in 1:length(savetofile)){ devtype = savetofile[i] if (devtype =="jpeg") devtype="jpg" fn = file.path( outdir, paste( "bathymetry", vn, p$spatial_domain, devtype, sep=".") ) print(fn) if (devtype == "pdf" ) { pdf(file=fn, width=5, height=4, bg='white') } else if (devtype == "png" ) { png(filename=fn, width=width, height=height, pointsize=pointsize, res=res, bg='white' ) } else if (devtype == "jpg" ) { jpeg(filename=fn, width=width, height=height, pointsize=pointsize, res=res, bg='white', quality=quality ) } else { stop( "device not supported ... add it here") } print( levplt ) dev.off() } } else { print( levplt ) } } return(varnames) }
Formal statement is: lemma continuous_on_open_Union: "(\<And>s. s \<in> S \<Longrightarrow> open s) \<Longrightarrow> (\<And>s. s \<in> S \<Longrightarrow> continuous_on s f) \<Longrightarrow> continuous_on (\<Union>S) f" Informal statement is: If $f$ is continuous on each open set $s \in S$, then $f$ is continuous on $\bigcup S$.
# Lecture 10: Expectation Continued ## Stat 110, Prof. Joe Blitzstein, Harvard University ---- ## A Proof of Linearity (discrete case) Let $T = X + Y$, and show that $\mathbb{E}(T) = \mathbb{E}(X) + \mathbb{E}(Y)$. We will also show that $\mathbb{E}(cX) = c \mathbb{E}(X)$. In general, we'd like to be in a position where \begin{align} \sum_{t} t P(T=t) \stackrel{?}{=} \sum_{x} x P(X=x) + \sum_{y} y P(Y=y) \end{align} so, let's try attacking this from the l.h.s. Considering the image above of a discrete r.v. in Pebble World, note that \begin{align} \mathbb{E}(X) &= \sum_{x} x P(X=x) & &\text{grouping the pebbles per X value; weighted average} \\ &= \sum_{s}X(s)P(\{s\}) & &\text{ungrouped; sum each pebble separately} \\ \\ \\ \Rightarrow \mathbb{E}(T) &= \sum_{s} (X+Y)(s)P(\{s\}) \\ &= \sum_{s}X(s)P(\{s\}) + \sum_{s}Y(s)P(\{s\}) \\ &= \sum_{x} x P(X=x) + \sum_{y} y P(Y=y) \\ &= \mathbb{E}(X) + \mathbb{E}(Y) ~~~~ \blacksquare \\ \\ \\ \Rightarrow \mathbb{E}(cX) &= \sum_{x} cx P(X=x) \\ &= c \sum_{x} x P(X=x) \\ &= c \mathbb{E}(X) ~~~~ \blacksquare \end{align} ---- ## Negative Binomial Distribution ### Description A misnomer: this distribution is actually non-negative, and neither is it binomial. The Negative Binomial is a generalization of the Geometric distribution, where we have a series of independent $Bern(p)$ trials and we want to know # failures before the r<sup>th</sup> success. We can codify this using a bit string: \begin{align} & \text{1000100100001001} & \text{0 denotes failure, 1 denotes success} & \\ & r = 5 \\ & n = 11 & \text{failures} \end{align} Note that the very last bit position is, of course, a success. Note also that we can permutate the preceding $r-1$ successes amongst the $n+r-1$ slots that come before that final r<sup>th</sup> success. ### Notation $X \sim \operatorname{NB}(r,p)$ ### Parameters * $r$ - the total number of successes before we stop counting * $p$ - probability of success ### Probability mass function \begin{align} P(X=n) &= \binom{n+r-1}{r-1} p^r (1-p)^n & &\text{for } n = 0,1,2,\dots\\ &= \binom{n+r-1}{n} p^r (1-p)^n & &\text{or conversely}\\ \end{align} ### Expected value Let $X_j$ be the # failures before the $(j-1)^{\text{st}}$ and $j^{\text{th}}$ success. Then we could write \begin{align} \mathbb{E}(X) &= \mathbb{E}(X_1 + X_2 + \dots + X_r) \\ &= \mathbb{E}(X_1) + \mathbb{E}(X_2) + \dots + \mathbb{E}(X_r) & &\text{by Linearity} \\ &= r \mathbb{E}(X_1) & &\text{by symmetry} \\ &= r \frac{q}{p} ~~~~ \blacksquare \end{align} ---- ```python import matplotlib import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) from scipy.stats import nbinom %matplotlib inline plt.xkcd() _, ax = plt.subplots(figsize=(12,8)) # seme Negative Binomial parameters r_values = [1, 2, 4, 8] p_values = [0.25]*len(r_values) #p_values = [0.25, 0.24, 0.23, 0.22] params = list(zip(r_values, p_values)) # colorblind-safe, divergent color scheme colors = ['#018571', '#80cdc1', '#dfc27d', '#a6611a'] for i,(r,p) in enumerate(params): x = np.arange(nbinom.ppf(0.01, r, p), nbinom.ppf(0.99, r, p)) pmf = nbinom.pmf(x, r, p) ax.plot(x, pmf, 'o', color=colors[i], ms=8, label='r={}, p={}'.format(r,p)) ax.vlines(x, 0, pmf, lw=2, color=colors[i], alpha=0.3) # legend styling legend = ax.legend() for label in legend.get_texts(): label.set_fontsize('large') for label in legend.get_lines(): label.set_linewidth(1.5) # y-axis ax.set_ylim([0.0, 0.251]) ax.set_ylabel(r'$P(X=n)$') # x-axis ax.set_xlim([0, 55]) ax.set_xlabel(r'total # of failures $n$ before seeing $r^{th}$ success') # x-axis tick formatting majorLocator = MultipleLocator(5) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(1) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.grid(color='grey', linestyle='-', linewidth=0.3) plt.suptitle(r'Negative Binomial PMF: $P(X=n) = \binom{n+r-1}{r-1} p^r (1-p)^n$') plt.show() ``` ## Revisting the Geometric: the First Success Distribution $X \sim \operatorname{FS}(p)$ is the geometric distribution that counts the trials until first success, *including that first success*. Let $Y = X - 1$. Then $Y \sim \operatorname{Geom}(p)$ Expected value of $\operatorname{FS}(p)$ is \begin{align} \mathbb{E}(X) &= E(Y) + 1 \\ &= \frac{q}{p} + 1 \\ &= \boxed{\frac{1}{p}} \end{align} ---- ## Putnam Problem Consider a random permutation of $1, 2, 3, \dots , n$, where $n \ge 2$. Find expected # local maxima. For example, given the permuation $\boxed{3} ~~ 2 ~~ 1 ~~ 4 ~~ \boxed{7} ~~ 5 ~~ \boxed{6}$ we have 3 local maxima: - $\boxed{3} \gt 2$ - $4 \lt \boxed{7} \gt 5$ - $ 5 \lt \boxed{6}$ Now, there are 2 kinds of cases we need to consider: - non-edge case: $4 ~~ \boxed{7} ~~ 5$ has probability of $\frac{1}{3}$ that the largest number is in the middle position - edge case: in both left-edge $\boxed{3} ~~ 2$ and right-edge $5 ~~ \boxed{6}$, the probability that the larger number is in the right position is $\frac{1}{2}$ Let $I_j$ be the indicator r.v. of position $j$ having a local maximum, $1 \le j \le n$. Using Linearity, we can say that the expected number of local maxima is given by \begin{align} \mathbb{E}(I_j) &= \mathbb{E}(I_1 + I_2 + \dots + I_n) \\ &= \mathbb{E}(I_1) + \mathbb{E}(I_2) + \dots + \mathbb{E}(I_n) & &\text{by Linearity} \\ &= (n-2) \frac{1}{3} + 2 \frac{1}{2} \\ &= \boxed{\frac{n+1}{3}} \end{align} Idiot-checking this, we have: \begin{align} \mathbb{E}(I_{n=2}) &= \frac{2+1}{3} & &\text{... case where } n=2 \\ &= 1 \\ \\ \\ \mathbb{E}(I_{n=\infty}) &= \frac{\infty+1}{3} & &\text{... case where } n= \infty \\ &= \infty \\ \end{align} ---- ## St. Petersburg Paradox Consider a game of chance involving a fair coin. We will flip the coin until the very first heads shows (hypergeometric distribution). - If heads shows on the very first flip, you get $\$2$. - If the first heads shows on the second flip, you get $\$4$. - If the first heads shows on the third flip, you get $\$8$. So you will get $\$2^n$ if the first heads shows up on the n<sup>th</sup> trial, including the heads flip. _How much would you be willing to pay to play this game?_ Let's tackle this by thinking about the expected amount of $\$\$\$$ we stand to make. Given $Y = 2^n$, find $\mathbb{E}(Y)$: \begin{align} \mathbb{E}(Y) &= \sum_{k=1}^\infty 2^k \frac{1}{2^{k-1}} ~ \frac{1}{2}\\ &= \sum_{k=1}^\infty 2^k \frac{1}{2^k}\\ &= \sum_{k=1}^\infty 1\\ \\ \\ \mathbb{E}(Y_{k=40}) &= \sum_{k=1}^{40} 1 \\ &= 40 \end{align} So, the "paradox" here is that even if we capped the payout to $2^{40} \approx \$1000000000$, Linearity shows us we would only pay $40. It is very hard to grasp this, but the truth is that if you were offered this game at any price, you should take it. ---- View [Lecture 10: Expectation Continued | Statistics 110](http://bit.ly/2vXxPsj) on YouTube.
# POL280 Bayesian Modeling Homework 1 ### Gento Kato (May 2, 2017) --- ## Q1 *Use the Gamma-Poisson conjugate specification to analyze data on the number of presidential appointments from 1960 to 2000. The data are in the file called **appointments.dta** in the Dropbox folder.* --- To start with, it is shown in the class that $gamma(\alpha, \beta)$ prior distribution and poisson likelihood produces $gamma(\alpha + \Sigma y, \beta + n)$ posterior distribution, as follows: * **Gamma (Prior) - Poisson (Likelihood) $\Rightarrow$ Gamma Posterior** \begin{align} \mbox{Prior Distribution} = \mbox{Gamma}(\alpha, \beta) &= \frac{\beta^{\alpha}}{\Gamma (\alpha)} \theta^{\alpha-1} e^{- \beta \theta} \\ \mbox{Poisson PMF } &= p(y | \theta) = \frac{e^{-\theta} \theta^{y_i}}{y_i !} \\ \mbox{Poisson Likelihood } &= \mathit{L}(\theta | y) = \hat{\Pi}_{i=1}^n \frac{e^{-\theta} \theta^{y_i}}{y_i !} \\ &= \frac{e^{-\theta n} \theta^{\sum_{i=1}^{n} y_i} }{y_1 ! y_2 ! \dots y_n !} \\ \mbox{Posterior Distribution } \pi(\theta | y) &\propto \frac{\beta^{\alpha}}{\Gamma (\alpha)} \theta^{\alpha-1} e^{- \beta \theta} \times \frac{e^{-\theta n} \theta^{\sum_{i=1}^{n} y_i} }{y_1 ! y_2 ! \dots y_n !} \\ &\propto \theta^{\alpha - 1 + \Sigma y} e^{- \theta (\beta + n)} \\ &\propto \mbox{Gamma }(\alpha + \Sigma y, \beta + n) \end{align} Now, the observed posterior value from <code>appointments.dta</code> can be extracted as follows: ```R library(foreign) appdta <- read.dta("../data/POL280/appointments.dta") ## Open Data y <- appdta$appoints ; y ## Store observed y ``` <ol class=list-inline> <li>2</li> <li>3</li> <li>3</li> <li>2</li> <li>0</li> <li>1</li> <li>2</li> <li>1</li> <li>2</li> <li>1</li> </ol> Then, using R function <code>rgamma(alpha, beta)</code>, we can create function to produce posterior distribution: ```R posterior <- function(sample, y, alpha, beta){ n = length(y); sigmay = sum(y) # n is y's sample size, sigmay is the sum of all y values return(rgamma(sample, alpha+sigmay, beta+n)) # generate posterior distribution from prior's parameters } ``` I will use the above function in Q3 and Q4. ## Q2 *The posterior distribution for $\theta$ is $gamma(\delta_1, \delta_2)$ according to some parameters $\delta_1$ and $\delta_2$, which of course depend on your choice of the parameters for the gamma prior. You should model $\theta$ using two sets of priors: one which specifies a great deal of certainty regarding your best guess as to the value of $\theta$ and one that represents ignorance regarding this value. * --- Before turning to the analysis, for the gamma distribution specification in Q1, the mean and variance of the distribution are defined as follows: \begin{align} Mean\left[gamma(\alpha, \beta)\right] &= \frac{\alpha}{\beta}\\ Var\left[gamma(\alpha, \beta)\right] &= \frac{\alpha}{\beta^2}\\ \end{align} Now, suppose that there are two prior belief gamma distribution with the same mean (let's say 5), but different variance (certainty), as follows: \begin{align} \mbox{Prior 1 (ignorant): Mean } &= \frac{\alpha}{\beta} = \frac{5}{1} = 5 \\ \mbox{Variance } &= \frac{\alpha}{\beta^2} = \frac{5}{1} = 5\\ \mbox{Prior 2 (certain): Mean } &= \frac{\alpha}{\beta} = \frac{50}{10} = 5 \\ \mbox{Variance } &= \frac{\alpha}{\beta^2} = \frac{50}{100} = \frac{1}{2} \end{align} We can generate those two prior distributions in R as follows ```R ## Set Alpha and Betas a1 = 5; b1 = 1 ## Ignorant a2 = 50; b2 = 10 ## Certain ## Generate Prior distribution set.seed(27674) # Make this replicable prior1 <- rgamma(10000, a1, b1) # Ignorant prior2 <- rgamma(10000, a2, b2) # Certain ## Check Result paste("For prior 1, mean is ", round(mean(prior1),2), ", variance is ", round(var(prior1),2)) paste("For prior 2, mean is ", round(mean(prior2),2), ", variance is ", round(var(prior2),2)) ``` Now, the above two distributions can be plotted as follows: ```R library(ggplot2); source("https://raw.githubusercontent.com/gentok/Method_Notes/master/sources/gktheme.R") bayesdata <- data.frame(prior1 = prior1, prior2 = prior2) ## Plot Result ## bgraph <- ggplot(bayesdata) + gktheme + geom_density(aes(prior1, fill="1"), alpha = 0.5, size=0.5) + geom_density(aes(prior2, fill="2"), alpha = 0.5, size=0.5) + scale_y_continuous(limits=c(0,0.6),breaks=c(0,0.2,0.4,0.6))+ scale_x_continuous(limits=c(0,16.03),breaks=c(0,2.5,5,7.5,10,12.5,15))+ scale_linetype_manual(name="Gamma Parameters",values=c(1,2), labels = c(expression(paste("1. Ignorant: ", alpha == 5, "; " , beta == 1)), expression(paste("2. Certain: ", alpha == 50, "; " , beta == 10))))+ scale_fill_manual(name="Gamma Parameters",values=c(1,2), labels = c(expression(paste("1. Ignorant: ", alpha == 5, "; " , beta == 1)), expression(paste("2. Certain: ", alpha == 50, "; " , beta == 10))))+ xlab("Prior Belief")+ ylab("Density")+ ggtitle("Prior Distributions by Different Parameters")+ theme(legend.position = "right") ``` ```R options(repr.plot.width=7, repr.plot.height=3.5) bgraph ``` ## Q3 *Generate a large number of values from this distribution in **R**, say 10, 000 or so, using the command:* **posterior.sample <- rgamma(10000,d1,d2)** --- Note that in Q1, I created following objects: * <code>y</code> variable, which is number of appointments by each president. * <code>posterior</code> function, to generate posterior distribution from gamma prior parameters and poisson likelihood <code>posterior</code> function utilizes <code>rgamma</code>, so those two functions are essentially the same. Therefore, I use <code>posterior</code> function to generate posterior distribution, as follows: ```R set.seed(8900786) # Make this replicable #posterior(y, alpha, beta) ## Alpha and Beta from prior distribution posterior1 <- posterior(10000, y, a1, b1) posterior2 <- posterior(10000, y, a2, b2) ``` ## Q4 Summarize the posteriors with quantities of interest such as means, medians, and variances. Also supply plots of the density of the posterior distributions. --- Before starting the analysis, note that mean, median and variance of observed y is shown as follows: ```R paste("For observed y, mean is ", round(mean(y),2), ", median is ", round(median(y),2), ", variance is ", round(var(y),2)) ``` <span style=white-space:pre-wrap>'For observed y, mean is 1.7 , median is 2 , variance is 0.9'</span> Now the characteristics of posterior distribution can be extracted as follows: ```R ## Check Result paste("For posterior 1, mean is ", round(mean(posterior1),2), ", median is ", round(median(posterior1),2), ", variance is ", round(var(posterior1),2)) paste("For posterior 2, mean is ", round(mean(posterior2),2), ", median is ", round(median(posterior2),2), ", variance is ", round(var(posterior2),2)) ``` <span style=white-space:pre-wrap>'For posterior 1, mean is 2 , median is 1.96 , variance is 0.18'</span> <span style=white-space:pre-wrap>'For posterior 2, mean is 3.35 , median is 3.33 , variance is 0.17'</span> From the above result, the mean of posterior distrbution from more ignorant prior distribution (i.e., prior 1) is more strongly pulled by the observed y values than the mean of posterior distibution from certain prior distributon (i.e., prior 2). In other words, posterior distribution 1 has closer mean (i.e., mean is 2) to observed y (i.e., mean is 1.7) than posterior distribution 2 (i.e, mean is 3.35). The observed y has stronger influence on ignorant (high variance) prior belief than on certain (low variance) prior belief. Note that the variance for two posterior distributions are identical. Now the Result can be plotted as follows: ```R bayesdata$posterior1 <- posterior1 bayesdata$posterior2 <- posterior2 ## Plot Result ## bgraph2 <- ggplot(bayesdata) + gktheme + geom_density(aes(posterior1, fill="1"), alpha = 0.5, size=0.5) + geom_density(aes(posterior2, fill="2"), alpha = 0.5, size=0.5) + scale_y_continuous(limits=c(0,1),breaks=c(0,0.25,0.5,0.75,1))+ scale_x_continuous(limits=c(0,6),breaks=c(0,1,2,3,4,5,6))+ scale_linetype_manual(name="Gamma Prior Parameters",values=c(1,2), labels = c(expression(paste("1. Ignorant: ", alpha == 5, "; " , beta == 1)), expression(paste("2. Certain: ", alpha == 50, "; " , beta == 10))))+ scale_fill_manual(name="Gamma Prior Parameters",values=c(1,2), labels = c(expression(paste("1. Ignorant: ", alpha == 5, "; " , beta == 1)), expression(paste("2. Certain: ", alpha == 50, "; " , beta == 10))))+ xlab("Posterior Belief")+ ylab("Density")+ ggtitle("Posterior Distributions by Prior Parameters")+ theme(legend.position = "right") ``` ```R options(repr.plot.width=7, repr.plot.height=3.5) bgraph2 ``` The above plot further confirmes the implication. While the shape of two posterior distributions are almost identical, the posterior distribution for ignorant prior is placed left of the posterior distribution for certain prior. Given that both prior distribution had the same mean of 5, ignorant prior holders are more strongly pulled by the observation of y (mean of 2) than certain prior holders.
function dataCorners2 = atlasMergeAdjacentCorners(dataCorners,dataCorners2); % % dataCorners2 = atlasMergeAdjacentCorners(dataCorners,dataCorners2); % % Author: Wandell % Purpose: % When adding an atlas segment, sometimes we want the corners from % adjacent segments to be the same. This routine finds the two closest % corners and makes the corner positions in the second segment equal to % the closest ones in the first segment % %Examples % % First, we check the distance from each corner in corners2 to each corner % in corners. This is a 4x4 distance matrix. % for ii=1:4 for jj=1:4 d(ii,jj) = norm(dataCorners(ii,:) - dataCorners2(jj,:)); end end % Find the two points with the closest values [v,idx] = sort(d(:)); % Find the row and column coordinates of these two points [r1,c1] = ind2sub(size(d),idx(1)); % Set the dataCorners2(c,:) equal to the positions of dataCorners(r,:) dataCorners2(c1,:) = dataCorners(r1,:); % Choose the second point that is closest with the constraint that this % second point in dataCorners2 cannot be attached to the point we have % already chosen. Another way to do this is to remove the row containing % point at r1, recalculale the distance matrix, and then find the minimum. for ii=2:length(idx) [r2,c2] = ind2sub(size(d),idx(ii)); if r1 ~= r2 dataCorners2(c2,:) = dataCorners(r2,:); break; end end return;
/- First localization test. R[1/a][1/b] ≅ R[1/ab]. -/ import ring_theory.localization import to_mathlib.localization.localization_alt universes u v w open localization_alt -- Define localisation on a set of generators. section localization_on_generators parameters {A : Type u} {B : Type v} {C : Type w} parameters [comm_ring A] [comm_ring B] [comm_ring C] parameters (G : set A) (f : A → B) [is_ring_hom f] def S : set A := monoid.closure G instance S_submonoid : is_submonoid S := monoid.closure.is_submonoid G def is_localization' := is_localization S f def is_localization_data' := is_localization_data S f end localization_on_generators -- We show that R[1/a][1/b] = R[1/ab], i.e. is_localization' R[1/a][1/b] (a*b). section localization_ab parameters {R : Type u} [comm_ring R] parameters (a b : R) -- I need this because localization on generators is defined using monoid.closure. lemma powers_closure_eq : ∀ x : R, powers x = S {x} := begin intros x, apply set.eq_of_subset_of_subset, { rintros y ⟨n, Hy⟩, revert x y, induction n with n Hn, { intros x y Hx, simp at Hx, rw ←Hx, exact monoid.in_closure.one {x}, }, { intros x y Hx, rw pow_succ at Hx, have Hxx : x ∈ {x} := set.mem_singleton x, have Hxclo := monoid.in_closure.basic Hxx, have Hxnclo := Hn x (eq.refl (x ^ n)), rw ←Hx, apply monoid.in_closure.mul Hxclo Hxnclo, } }, { intros y Hy, induction Hy, case monoid.in_closure.basic : z Hz { cases Hz, { rw Hz, exact ⟨1, by simp⟩, }, { cases Hz, } }, case monoid.in_closure.one { exact (powers.is_submonoid x).one_mem, }, case monoid.in_closure.mul : x y HxS HyS Hx Hy { rcases Hx with ⟨n, Hx⟩, rcases Hy with ⟨m, Hy⟩, rw [←Hx, ←Hy, ←pow_add], exact ⟨n + m, by simp⟩, } } end -- Definition of R[1/a]. @[reducible] def Ra := localization.away a instance Ra_comm_ring : comm_ring Ra := by apply_instance instance powers_a_submonoid : is_submonoid (powers a) := powers.is_submonoid a lemma one_powers_a : (1:R) ∈ powers a := powers_a_submonoid.one_mem -- Definition of R[1/a][1/b]. def b1 : Ra := ⟦⟨b, 1, one_powers_a⟩⟧ @[reducible] def Rab := localization Ra (powers b1) instance Afg_comm_ring : comm_ring Rab := by apply_instance instance powers_b1_submonoid : is_submonoid (powers b1) := powers.is_submonoid b1 lemma one_powers_b1 : (1:Ra) ∈ powers b1 := powers_b1_submonoid.one_mem -- Basically saying that b1 is b/1. lemma elem_powers_b1_bn : ∀ {x : Ra}, x ∈ powers b1 ↔ ∃ n : ℕ, x = ⟦⟨b ^ n, 1, one_powers_a⟩⟧ := begin intros x, split, { intros Hx, rcases Hx with ⟨n, Hx⟩, existsi n, revert x, induction n with n Hn, { simp, apply quotient.sound; use [1, one_powers_a]; simp, }, { intros x Hx, rw pow_succ at *, rw ←Hx, rw @Hn (b1 ^ n); try { refl }, apply quotient.sound; use [1, one_powers_a]; simp, } }, { rintros ⟨n, Hx⟩, existsi n, revert x, induction n with n Hn, { simp, apply quotient.sound; use [1, one_powers_a]; simp, }, { intros x Hx, rw pow_succ at *, rw Hx, rw @Hn (⟦(b ^ n, ⟨1, _⟩)⟧); try { refl }, apply quotient.sound; use [1, one_powers_a]; simp, } } end lemma elem_powers_b1 : ∀ {x : Ra}, x ∈ powers b1 ↔ ∃ y ∈ powers b, x = ⟦⟨y, 1, one_powers_a⟩⟧ := begin intros x, split, { intros Hx, have Hbn := elem_powers_b1_bn.1 Hx, rcases Hbn with ⟨n, Hx⟩, existsi (b ^ n), existsi (⟨n, by simp⟩ : b ^ n ∈ powers b), exact Hx, }, { rintros ⟨y, ⟨n, Hy⟩, Hx⟩, rw ←Hy at Hx, apply elem_powers_b1_bn.2 ⟨n, Hx⟩, } end -- Localization map A --> A[1/a][1/b]. @[reducible] def h : R → Rab := λ x, ⟦⟨⟦⟨x, 1, is_submonoid.one_mem _⟩⟧, 1, is_submonoid.one_mem _⟩⟧ instance is_ring_hom_h : is_ring_hom h := { map_one := rfl, map_add := λ x y, begin apply quotient.sound; use [1, one_powers_b1]; simp, apply quotient.sound; use [1, one_powers_a]; simp, end, map_mul := λ x y, begin apply quotient.sound; use [1, one_powers_b1]; simp, apply quotient.sound; use [1, one_powers_a]; simp, end} -- Proving the lemmas: inverts, denom and ker = ann. section localization_ab_proof -- Inverses. def one_Rab : Rab := 1 def binv_Rab : Rab := ⟦⟨⟦⟨1, 1, one_powers_a⟩⟧, b1, ⟨1, by simp⟩⟩⟧ def ainv_Rab : Rab := ⟦⟨⟦⟨1, a, ⟨1, by simp⟩⟩⟧, 1, one_powers_b1⟩⟧ lemma loc_inverts : inverts (S {a * b}) h := begin rintros ⟨x, Hx⟩, induction Hx, case monoid.in_closure.basic : y Hy { rcases Hy with ⟨Hya, Hyb⟩, { existsi (ainv_Rab * binv_Rab), apply quotient.sound; use [1, one_powers_b1]; simp, apply quotient.sound; use [1, one_powers_a]; simp, rw Hy; simp, }, { cases Hy, } }, case monoid.in_closure.one { existsi one_Rab, simp, rw is_ring_hom_h.map_one, simpa, }, case monoid.in_closure.mul : x y HxS HyS Hx Hy { rcases Hx with ⟨xinv, Hxinv⟩, rcases Hy with ⟨yinv, Hyinv⟩, existsi (xinv * yinv), simp at *, rw [is_ring_hom_h.map_mul, mul_comm _ yinv, mul_assoc, ←mul_assoc (h y)], rw [Hyinv, one_mul], exact Hxinv, } end -- Denoms. def homogenizer (n m : ℕ) : R := if n ≤ m then a^(m - n) else b^(n - m) lemma homogenizer_a {n m : ℕ} : n ≤ m → homogenizer n m = a^(m - n) := begin intros Hnm, dunfold homogenizer, rw if_eq_of_eq_true, apply eq_true_intro Hnm, end lemma homogenizer_b {n m : ℕ} : ¬(n ≤ m) → homogenizer n m = b^(n - m) := begin intros Hnm, dunfold homogenizer, rw if_eq_of_eq_false, apply eq_false_intro Hnm, end lemma homogenizer_mul : ∀ n m, a^n * b^m * homogenizer n m = a^(max n m) * b^(max n m) := begin intros n m, cases (classical.em (n ≤ m)) with Htt Hff, { rw homogenizer_a Htt, rw max_eq_right Htt, rw mul_assoc, rw mul_comm, rw mul_assoc, rw ←pow_add, rw nat.sub_add_cancel Htt, rw mul_comm, }, { rw homogenizer_b Hff, replace Hff := le_of_not_le Hff, rw max_eq_left Hff, rw mul_assoc, rw ←pow_add, rw add_comm, rw nat.sub_add_cancel Hff, } end lemma loc_has_denom : has_denom (S {a * b}) h := begin intros x, refine quotient.induction_on x _, rintros ⟨xRa, xdenRab⟩, refine quotient.induction_on xRa _, rintros ⟨xR, xdenRa⟩, rcases xdenRa with ⟨y, Hy⟩, rcases xdenRab with ⟨w, Hw⟩, have Hb := elem_powers_b1.1 Hw, rcases Hb with ⟨z, Hz, Hweq⟩, have Hy' := Hy, rcases Hy with ⟨n, Hy⟩, rcases Hz with ⟨m, Hz⟩, have HyzkSab : (a * b)^(max n m) ∈ powers (a * b) := ⟨(max n m), by simp⟩, rw powers_closure_eq at HyzkSab, simp, existsi (a * b)^(max n m), existsi HyzkSab, existsi xR * homogenizer n m, apply quotient.sound, use [w, Hw]; simp, rw Hweq, apply quotient.sound, simp, existsi y, existsi Hy', simp, rw [←Hy, ←Hz], rw mul_comm xR, rw ←mul_assoc (b^m), rw ←mul_assoc (a^n), rw ←mul_assoc (a^n), rw homogenizer_mul n m, rw mul_pow a b, simp, end -- Kernel is monoid annihilator. lemma loc_ker_ann_sub : ker h ≤ submonoid_ann (S {a * b}) := λ x Hx, begin unfold submonoid_ann, unfold ker at *, unfold ideal.mk at *, have Hx : x ∈ {x : R | h x = 0} := Hx, have Hx0 : h x = 0 := by apply_assumption, dunfold ann_aux, unfold set.range, simp, show ∃ (c z : R), z ∈ S {a * b} ∧ c * z = 0 ∧ c = x, existsi x, dunfold h at Hx0, have Hx01 := quotient.exact Hx0, rcases Hx01 with ⟨t, Ht, Hx01⟩, simp at Hx01, have Hty1 := elem_powers_b1.1 Ht, rcases Hty1 with ⟨y, Hy, Hty1⟩, rw Hty1 at Hx01, have Hxy0 := quotient.exact Hx01, rcases Hxy0 with ⟨z, Hz, Hxyz0⟩, simp at Hxyz0, rcases Hy with ⟨m, Hy⟩, rcases Hz with ⟨n, Hz⟩, existsi (z * y * homogenizer n m), split, { rw [←Hy, ←Hz, homogenizer_mul n m, ←mul_pow, ←powers_closure_eq], exact ⟨max n m, rfl⟩, }, { split; try { refl }, rw [←mul_assoc, mul_comm z, ←mul_assoc, Hxyz0], simp, } end lemma loc_ker_ann : ker h = submonoid_ann (S {a * b}) := begin apply le_antisymm, { exact loc_ker_ann_sub, }, { exact inverts_ker (S {a * b}) h loc_inverts, } end -- R[1/a][1/b] = R[1/ab]. open localization lemma loc_Rab : is_localization' {a * b} ((of ∘ of) : R → Rab) := ⟨loc_inverts, loc_has_denom, loc_ker_ann⟩ end localization_ab_proof end localization_ab
""" Partition the numbers using the Complete Greedy number partitioning algorithm (Korf, 1995): https://en.wikipedia.org/wiki/Greedy_number_partitioning Credit: based on code by Søren Fuglede Jørgensen in the numberpartitioning package: https://github.com/fuglede/numberpartitioning/blob/master/src/numberpartitioning/greedy.py """ from typing import List, Tuple, Callable, Iterator, Any import numpy as np import logging, time from prtpy import objectives as obj, Bins, partitioning logger = logging.getLogger(__name__) def anytime( bins: Bins, items: List[any], valueof: Callable[[Any], float] = lambda x: x, objective: obj.Objective = obj.MinimizeDifference, time_in_seconds: float = np.inf, ) -> Iterator: """ An anytime algorithm for finding a partition using the Complete Greedy algorithm. It generates partitions using the order from the greedy algorithm. Concretely, it searches through all combinations by following the strategy that adds to each part the largest number not yet added to any part, so that smaller parts are prioritized. This is done depth-first, meaning that the smallest of the input numbers are shuffled between different parts before larger input numbers are. It stops when the optimal partition is found, OR when the time runs out. >>> from prtpy.bins import BinsKeepingContents, BinsKeepingSums >>> anytime(BinsKeepingContents(2), [4,5,6,7,8], objective=obj.MinimizeDifference, time_in_seconds=1) Bin #0: [6, 5, 4], sum=15.0 Bin #1: [8, 7], sum=15.0 The following examples are based on: Walter (2013), 'Comparing the minimum completion times of two longest-first scheduling-heuristics'. >>> walter_numbers = [46, 39, 27, 26, 16, 13, 10] >>> anytime(BinsKeepingContents(3), walter_numbers, objective=obj.MinimizeDifference, time_in_seconds=1) Bin #0: [27, 26, 10], sum=63.0 Bin #1: [39, 16], sum=55.0 Bin #2: [46, 13], sum=59.0 >>> anytime(BinsKeepingContents(3), walter_numbers, objective=obj.MinimizeLargestSum, time_in_seconds=1) Bin #0: [27, 26], sum=53.0 Bin #1: [39, 13, 10], sum=62.0 Bin #2: [46, 16], sum=62.0 >>> anytime(BinsKeepingContents(3), walter_numbers, objective=obj.MaximizeSmallestSum, time_in_seconds=1) Bin #0: [27, 16, 13], sum=56.0 Bin #1: [39, 26], sum=65.0 Bin #2: [46, 10], sum=56.0 >>> from prtpy import partition, outputtypes as out >>> partition(algorithm=anytime, numbins=3, items={"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9}) [['e', 'c', 'd'], ['g', 'a'], ['f', 'b']] >>> partition(algorithm=anytime, numbins=2, items={"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9}, outputtype=out.Sums) array([16., 16.]) :param objective: represents the function that should be optimized. Default is minimizing the difference between bin sums. :param time_in_seconds: determines how much time the function should run before it stops. Default is infinity. """ sorted_items = sorted(items, key=valueof, reverse=True) max_depth = len(items) start_time = time.perf_counter() # Create a stack whose elements are bins and the current depth. # Initially, it contains a single tuple: an empty partition with depth 0. to_visit: List[Tuple[Bins, int]] = [(bins, 0)] best_objective_value = np.inf best_bins = bins while len(to_visit) > 0: bins, depth = to_visit.pop() # If we have reached the leaves of the DFS tree, check if we have an improvement, and yield if we do. if depth == max_depth: new_objective_value = objective.get_value_to_minimize(bins.sums) if new_objective_value < best_objective_value: best_objective_value = new_objective_value best_bins = bins if time.perf_counter() - start_time > time_in_seconds: break else: item = sorted_items[depth] # Order bins by decreasing sum, so bin with smallest sum ends up on top of stack. for bin_index in sorted(range(bins.num), key=lambda i: bins.sums[i], reverse=True): # Create the next vertex. new_bins = bins.add_item_to_bin( item, bin_index, inplace=False ) new_depth = depth + 1 to_visit.append((new_bins, new_depth)) return best_bins if __name__ == "__main__": # logger.setLevel(logging.INFO) # logger.addHandler(logging.StreamHandler()) import doctest (failures, tests) = doctest.testmod(report=True) print("{} failures, {} tests".format(failures, tests))
function Average = LMaverage(D, objectname, HOMEIMAGES, object_size, average_size) % % Average = LMaverage(D, objectname, HOMEIMAGES) % Parameters: if nargin<4 object_size = [256 256]; % scale normalized end if nargin<5 average_size = object_size*4; % scale normalized end b = [ceil((average_size(1)- object_size(1))/2) ceil((average_size(2)- object_size(2))/2)]; L = 128; disp('selecting objects to average') if isempty(D) D = LMdatabase(HOMEIMAGES, HOMEIMAGES); for i = 1:length(D(1:10)) img = LMimread(D, i, HOMEIMAGES); disp(i) bb = labelimage(img); % [xmin ymin width height] if size(bb,1) >0 for n = 1:size(bb,1) min(bb(n,3), bb(n,4)) D(i).annotation.object(n).name = objectname; D(i).annotation.object(n).crop = '0'; x = [bb(n,1) bb(n,1)+bb(n,3) bb(n,1)+bb(n,3) bb(n,1)]; y = [bb(n,2) bb(n,2) bb(n,2)+bb(n,4) bb(n,2)+bb(n,4)]; D(i).annotation.object(n).polygon.x = x; D(i).annotation.object(n).polygon.y = y; end end close end end D = LMquery(D, 'object.name', objectname,'exact'); disp('removing small and cropped objects from the averaging') D = addsmallobjectlabel(D, object_size(1)/4, object_size(2)/4); D = LMquery(D, 'object.name', '-smallobject'); D = LMquery(D, 'object.occluded', 'no'); % Align all images (scale and translate) and compute averages Average = zeros([average_size 3], 'single'); [nrows, ncols, cc] = size(Average); Counts = zeros([nrows ncols], 'single'); %[x,y] = meshgrid(0:ncols-1, 0:nrows-1); %x = x - ncols/2; %y = y - nrows/2; figure for n = 1:length(D) n clear img Tmp img = LMimread(D, n, HOMEIMAGES); %img = single(img); %img = img - min(img(:)); %img = 256*img / max(img(:)); %img = uint8(253*img / max(img(:))+2); if size(img,3)>1 for k = 1:length(D(n).annotation.object); [imgCrop, ~, ~, ~, valid] = LMobjectnormalizedcrop(img, D(n).annotation, k, b, object_size(1), object_size(2)); if valid(1,1) < 0.5 || valid(end,end)<0.5 valid = 2*single(valid)-1; w = hamming(L); w= w/sum(w); valid2 = conv2(valid, w, 'same'); valid2 = conv2(valid2, w', 'same'); valid = max(0,valid2.*(valid>0)); end imgCrop(isnan(imgCrop))=0; imgCrop = single(imgCrop); imgCrop(:,:,1) = imgCrop(:,:,1).*valid; imgCrop(:,:,2) = imgCrop(:,:,2).*valid; imgCrop(:,:,3) = imgCrop(:,:,3).*valid; Counts = Counts + valid; Average = Average + imgCrop; if 1 Tmp = Average(1:4:end,1:4:end,:) ./ repmat(Counts(1:4:end,1:4:end)+.000000001, [1 1 3]); Tmp = Tmp - min(Tmp(:)); Tmp = Tmp / max(Tmp(:))*256; imshow(uint8(Tmp)) title(n) drawnow end end end end Average = Average ./ repmat(Counts+.00000001, [1 1 3]); Average = Average - min(Average(:)); Average = Average / max(Average(:))*65535; %average = average-prctile(average(:), 3); %average = 255*average/prctile(average(:), 97);
{-# OPTIONS --without-K --safe #-} module Categories.Functor.Profunctor where open import Level open import Data.Product open import Relation.Binary.Bundles open import Categories.Category open import Categories.Category.Instance.Setoids open import Categories.Functor hiding (id) open import Categories.Functor.Bifunctor open import Categories.Functor.Hom open import Categories.NaturalTransformation open import Categories.NaturalTransformation.Equivalence open import Function.Equality using (Π; _⟨$⟩_; cong) Profunctor : ∀ {o ℓ e} {o′ ℓ′ e′} → Category o ℓ e → Category o′ ℓ′ e′ → Set _ Profunctor {ℓ = ℓ} {e} {ℓ′ = ℓ′} {e′} C D = Bifunctor (Category.op D) C (Setoids (ℓ ⊔ ℓ′) (e ⊔ e′)) -- Calling the profunctor identity "id" is a bad idea proid : ∀ {o ℓ e} → {C : Category o ℓ e} → Profunctor C C proid {C = C} = Hom[ C ][-,-] module Profunctor {o ℓ e} {o′} (C : Category o ℓ e) (D : Category o′ ℓ e) where module C = Category C open module D = Category D hiding (id) open D.HomReasoning open import Categories.Morphism.Reasoning D using (assoc²''; elimˡ; elimʳ) -- representable profunctors -- hom(f,1) repˡ : ∀ (F : Functor C D) → Profunctor D C repˡ F = record { F₀ = λ (c , d) → record { Carrier = D [ F₀ c , d ] ; _≈_ = D._≈_ ; isEquivalence = D.equiv } ; F₁ = λ (f , g) → record { _⟨$⟩_ = λ x → g ∘ x ∘ F₁ f ; cong = λ x → begin _ ≈⟨ refl⟩∘⟨ x ⟩∘⟨refl ⟩ _ ∎ } ; identity = λ {x} {y} {y'} y≈y' → begin D.id ∘ y ∘ F₁ C.id ≈⟨ D.identityˡ ⟩ y ∘ F₁ C.id ≈⟨ elimʳ identity ⟩ y ≈⟨ y≈y' ⟩ y' ∎ ; homomorphism = λ { {f = f0 , f1} {g = g0 , g1} {x} {y} x≈y → begin (g1 ∘ f1) ∘ x ∘ F₁ (f0 C.∘ g0) ≈⟨ refl⟩∘⟨ x≈y ⟩∘⟨ F.homomorphism ⟩ (g1 ∘ f1) ∘ y ∘ F₁ f0 ∘ F₁ g0 ≈⟨ refl⟩∘⟨ D.sym-assoc ⟩ (g1 ∘ f1) ∘ (y ∘ F₁ f0) ∘ F₁ g0 ≈⟨ Equiv.sym assoc²'' ⟩ g1 ∘ (f1 ∘ y ∘ F₁ f0) ∘ F₁ g0 ∎ } ; F-resp-≈ = λ { {f = f0 , f1} {g = g0 , g1} (f0≈g0 , f1≈g1) {x} {y} x≈y → begin f1 ∘ x ∘ F₁ f0 ≈⟨ f1≈g1 ⟩∘⟨ x≈y ⟩∘⟨ F-resp-≈ f0≈g0 ⟩ g1 ∘ y ∘ F₁ g0 ∎ } } where open module F = Functor F -- hom(1,f) repʳ : (F : Functor C D) → Profunctor C D repʳ F = record { F₀ = λ (c , d) → record { Carrier = D [ c , F₀ d ] ; _≈_ = D._≈_ ; isEquivalence = D.equiv } ; F₁ = λ (f , g) → record { _⟨$⟩_ = λ x → F₁ g ∘ x ∘ f ; cong = λ x → begin _ ≈⟨ refl⟩∘⟨ x ⟩∘⟨refl ⟩ _ ∎ } ; identity = λ {x} {y} {y'} y≈y' → begin F₁ C.id ∘ y ∘ D.id ≈⟨ elimˡ identity ⟩ y ∘ D.id ≈⟨ D.identityʳ ⟩ y ≈⟨ y≈y' ⟩ y' ∎ ; homomorphism = λ { {f = f0 , f1} {g = g0 , g1} {x} {y} x≈y → begin F₁ (g1 C.∘ f1) ∘ x ∘ f0 ∘ g0 ≈⟨ F.homomorphism ⟩∘⟨ x≈y ⟩∘⟨refl ⟩ (F₁ g1 ∘ F₁ f1) ∘ y ∘ f0 ∘ g0 ≈⟨ refl⟩∘⟨ D.sym-assoc ⟩ (F₁ g1 ∘ F₁ f1) ∘ (y ∘ f0) ∘ g0 ≈⟨ Equiv.sym assoc²'' ⟩ F₁ g1 ∘ (F₁ f1 ∘ y ∘ f0) ∘ g0 ∎ } ; F-resp-≈ = λ { {f = f0 , f1} {g = g0 , g1} (f0≈g0 , f1≈g1) {x} {y} x≈y → begin F₁ f1 ∘ x ∘ f0 ≈⟨ F-resp-≈ f1≈g1 ⟩∘⟨ x≈y ⟩∘⟨ f0≈g0 ⟩ F₁ g1 ∘ y ∘ g0 ∎ } } where open module F = Functor F -- each Prof(C,D) is a category homProf : {o o′ ℓ e : Level} → (C : Category o ℓ e) → (D : Category o′ ℓ e) → Category _ _ _ homProf C D = record { Obj = Profunctor C D ; _⇒_ = NaturalTransformation ; _≈_ = _≃_ ; id = id ; _∘_ = _∘ᵥ_ ; assoc = λ { {f = f} {g} {h} → assoc-lemma {f = f} {g} {h}} ; sym-assoc = λ { {f = f} {g} {h} → sym-assoc-lemma {f = f} {g} {h}} ; identityˡ = λ { {f = f} → id-lemmaˡ {f = f} } ; identityʳ = λ { {f = f} → id-lemmaʳ {f = f} } ; identity² = λ z → z ; equiv = ≃-isEquivalence ; ∘-resp-≈ = λ { {f = f} {h} {g} {i} eq eq' → ∘ᵥ-resp-≃ {f = f} {h} {g} {i} eq eq' } } where id-lemmaˡ : ∀ {o o′ ℓ ℓ′ e e′} {C : Category o ℓ e} {D : Category o′ ℓ′ e′} {P K : Functor C D} {f : NaturalTransformation P K} → id ∘ᵥ f ≃ f id-lemmaˡ {D = D} = Category.identityˡ D id-lemmaʳ : ∀ {o o′ ℓ ℓ′ e e′} {C : Category o ℓ e} {D : Category o′ ℓ′ e′} {P K : Functor C D} {f : NaturalTransformation P K} → f ∘ᵥ id ≃ f id-lemmaʳ {D = D} = Category.identityʳ D assoc-lemma : ∀ {o o′ ℓ ℓ′ e e′} {C : Category o ℓ e} {D : Category o′ ℓ′ e′} {E F G H : Functor C D} {f : NaturalTransformation E F} {g : NaturalTransformation F G} {h : NaturalTransformation G H} → (h ∘ᵥ g) ∘ᵥ f ≃ h ∘ᵥ g ∘ᵥ f assoc-lemma {D = D} = Category.assoc D sym-assoc-lemma : ∀ {o o′ ℓ ℓ′ e e′} {C : Category o ℓ e} {D : Category o′ ℓ′ e′} {E F G H : Functor C D} {f : NaturalTransformation E F} {g : NaturalTransformation F G} {h : NaturalTransformation G H} → h ∘ᵥ g ∘ᵥ f ≃ (h ∘ᵥ g) ∘ᵥ f sym-assoc-lemma {D = D} = Category.sym-assoc D ∘ᵥ-resp-≃ : ∀ {o o′ ℓ ℓ′ e e′} {C : Category o ℓ e} {D : Category o′ ℓ′ e′} {R P K : Functor C D} {f h : NaturalTransformation P K} {g i : NaturalTransformation R P} → f ≃ h → g ≃ i → f ∘ᵥ g ≃ h ∘ᵥ i ∘ᵥ-resp-≃ {D = D} fh gi = Category.∘-resp-≈ D fh gi
# Importo los paquetes ```python from sympy import Symbol,integrate,sin ``` # Ejercicio propuesto para resolver $$c_n = \frac{2}{L}\left[\underbrace{\int_0^{\frac{L}{2}}\frac{2c}{L}x\sin{\left(\frac{n\pi}{L}x\right)dx}}_{f_1}+\underbrace{\int_{\frac{L}{2}}^{L} \frac{2c}{L}(L-x)\sin{\left(\frac{n\pi}{L}x\right)}dx}_{f_2} \right] $$ # Defino los simbolos necesarios ```python x=Symbol("x") L=Symbol("L",positive=True) c=Symbol("C") n=Symbol("n",integer=True,positive=True) pi=Symbol("\u03c0",positive=True) # Funciones para integrar f_1=((2*c*x)/L)*sin((n*pi*x)/L) f_2=((2*c)/L)*(L-x)*sin((n*pi*x)/L) ``` # Resuelvo las integrales ```python integrate(f_1,(x,0,L/2)) ``` ```python integrate(f_2,(x,L/2,L)) ```
# *Ab* *initio* molecular dynamics of the vibrational motion of HF We are going to construct what is often referred to as an *ab* *initio* potential energy surface of the diatomic molecule hydrogen fluoride. That is, we are going to use various electronic structure theories (Hartree-Fock theory (RHF), 2nd-order perturbation theory (MP2), and Coupled Cluster theory with single and double substitutions (CCSD)) to compute the electronic energy at different geometries of a simple diatomic molecule. The same basis set (correlation consistent polarized triple-zeta, cc-pVTZ) will be used for all calculations. We will use Psi4numpy to facilitate the electronic structure calculations, and then the interpolation capabilities of scipy to simplify the evalution of the potential energy at separations for which we did not explicitly evaluate the electronic energy. We will also use scipy to differentiate the interpolated potential energy surface to obtain the forces acting on the atoms at different separations. We will start by importing the necessary libraries: ```python import numpy as np import psi4 from matplotlib import pyplot as plt from scipy.interpolate import InterpolatedUnivariateSpline ``` ```python ### template for the z-matrix mol_tmpl = """H F 1 **R**""" ### array of bond-lengths in anstromgs r_array = np.array([0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3]) ### array for different instances of the HF molecule molecules =[] ### array for the different RHF energies for different HF bond-lengths HF_E_array = [] ### array for the different MP2 energies for different HF bond-lengths MP2_E_array = [] ### array for the different CCSD energies for different HF bond-lengths CCSD_E_array = [] ### loop over the different bond-lengths, create different instances ### of HF molecule for r in r_array: molecule = psi4.geometry(mol_tmpl.replace("**R**", str(r))) molecules.append(molecule) ### loop over instances of molecules, compute the RHF, MP2, and CCSD ### energies and store them in their respective arrays for mol in molecules: energy = psi4.energy("SCF/cc-pVTZ", molecule=mol) HF_E_array.append(energy) energy = psi4.energy("MP2/cc-pVTZ", molecule=mol) MP2_E_array.append(energy) energy = psi4.energy("CCSD/cc-pVTZ",molecule=mol) CCSD_E_array.append(energy) ### Plot the 3 different PES plt.plot(r_array,HF_E_array,'r*', label='RHF') plt.plot(r_array,MP2_E_array,'g*', label='MP2') plt.plot(r_array,CCSD_E_array,'b*', label='CCSD') ``` Now that you have the raw data, we will interpolate this data using cubic splines. This will permit us to estimate the potential energy at any arbitrary separation between 0.5 and 2.3 Angstroms (roughly 1 and 4.3 a.u.) with fairly high confidence, and will also allow us to estimate the force (the negative of the derivative of the PES with respect to separation) at any separation between 1.0 and 4.3 a.u. since the derivative of cubic splines are readily available. ```python ### use cubic spline interpolation order = 3 ### get separation vector in atomic units r_array_au = 1.89*r_array ### spline for RHF Energy RHF_E_Spline = InterpolatedUnivariateSpline(r_array_au, HF_E_array, k=order) ### spline for MP2 Energy MP2_E_Spline = InterpolatedUnivariateSpline(r_array_au, MP2_E_array, k=order) ### spline for CCSD Energy CCSD_E_Spline = InterpolatedUnivariateSpline(r_array_au, CCSD_E_array, k=order) ### form a much finer grid r_fine = np.linspace(0.5/0.529,2.3/0.529,200) ### compute the interpolated/extrapolated values for RHF Energy on this grid RHF_E_fine = RHF_E_Spline(r_fine) ### compute the interpolated/extrapolated values for RHF Energy on this grid MP2_E_fine = MP2_E_Spline(r_fine) ### compute the interpolated/extrapolated values for RHF Energy on this grid CCSD_E_fine = CCSD_E_Spline(r_fine) ### plot the interpolated data plt.plot(r_fine, RHF_E_fine, 'red', r_array_au, HF_E_array, 'r*') plt.plot(r_fine, MP2_E_fine, 'green', r_array_au, MP2_E_array, 'g*') plt.plot(r_fine, CCSD_E_fine, 'blue', r_array_au, CCSD_E_array, 'b*') plt.show() ``` We can estimate the equilibrium bond length by finding the separation at which the potential is minimum; note this would also be the position that the force goes to zero: \begin{equation} \frac{d}{dr} V(r_{eq}) = -F(r_{eq}) = 0. \end{equation} First we will compute the forces at each level of theory: ```python ### take the derivative of the potential to get the negative of the force from RHF RHF_Force = RHF_E_Spline.derivative() ### negative of the force from MP2 MP2_Force = MP2_E_Spline.derivative() ### negative of the force from CCSD CCSD_Force = CCSD_E_Spline.derivative() ### let's plot the forces for each level of theory! ### plot the forces... note we need to multiply by -1 since the spline ### derivative gave us the negative of the force! plt.plot(r_fine, -1*RHF_Force(r_fine), 'red') plt.plot(r_fine, -1*MP2_Force(r_fine), 'green') plt.plot(r_fine, -1*CCSD_Force(r_fine), 'blue') plt.show() ``` Next we will find where the minimum of the potential energy surfaces are and use that to find the equilibrium bond length: ```python ### Find Equilibrium Bond-Lengths for each level of theory RHF_Req_idx = np.argmin(RHF_E_fine) MP2_Req_idx = np.argmin(MP2_E_fine) CCSD_Req_idx = np.argmin(CCSD_E_fine) ### find the value of the separation corresponding to that index RHF_Req = r_fine[RHF_Req_idx] MP2_Req = r_fine[MP2_Req_idx] CCSD_Req = r_fine[CCSD_Req_idx] ### print equilibrium bond-lengths at each level of theory! print(" Equilibrium bond length at RHF/cc-pVDZ level is ",RHF_Req, "atomic units") print(" Equilibrium bond length at MP2/cc-pVDZ level is ",MP2_Req, "atomic units") print(" Equilibrium bond lengthat CCSD/cc-pVDZ level is ",CCSD_Req, "atomic units") ``` Equilibrium bond length at RHF/cc-pVDZ level is 1.6975235344966797 atomic units Equilibrium bond length at MP2/cc-pVDZ level is 1.7317209867864842 atomic units Equilibrium bond lengthat CCSD/cc-pVDZ level is 1.7317209867864842 atomic units At this point, take a moment to compare your equilibrium bond length with other teams who have used different levels of theory to compute their potential energy surfaces. Which equilibrium bond length should be most trustworthy? You might have learned that the Harmonic Oscillator potential, which is a reasonable model for the vibrational motion of diatomic atomcs near their equilibrium bond length, is given by \begin{equation} V(r) = \frac{1}{2} k r^2 \end{equation} and that the vibrational frequency of the molecule within the Harmonic oscillator model is given by \begin{equation} \nu = \frac{1}{2\pi}\sqrt{\frac{k}{\mu}} \end{equation} where $\mu$ is the reduced mass of the molecule and $k$ is known as the force constant. We can estimate the force constant as \begin{equation} k = \frac{d^2}{dr^2} V(r_{eq}). \end{equation} Let's go ahead and get the force constants at each level of theory and estimate the potential energy within the Harmonic approximation! ```python ### get second derivative of potential energy curve... recall that we fit a spline to ### to the first derivative already and called that spline function X_Force, where ### X is either RHF, MP2, or CCSD RHF_Curvature = RHF_Force.derivative() MP2_Curvature = MP2_Force.derivative() CCSD_Curvature = CCSD_Force.derivative() ### evaluate the second derivative at r_eq to get k RHF_k = RHF_Curvature(RHF_Req) MP2_k = MP2_Curvature(MP2_Req) CCSD_k = CCSD_Curvature(CCSD_Req) ### Print force constants for each level of theory! print("Hartree-Fock force constant is ",RHF_k," atomic units") print("MP2 force constant is ",MP2_k," atomic units") print("CCSD force constant is ",CCSD_k," atomic units") ### define harmonic potential for each level of theory RHF_Harm_Pot = RHF_k*(r_fine-RHF_Req)**2 + RHF_E_Spline(RHF_Req) MP2_Harm_Pot = MP2_k*(r_fine-MP2_Req)**2 + MP2_E_Spline(MP2_Req) CCSD_Harm_Pot = CCSD_k*(r_fine-CCSD_Req)**2 + CCSD_E_Spline(CCSD_Req) ### plot! plt.plot(r_fine, RHF_Harm_Pot, 'red') plt.plot(r_fine, MP2_Harm_Pot, 'green') plt.plot(r_fine, CCSD_Harm_Pot, 'blue') plt.show() ``` And we can actually estimate the fundamental vibrational frequency of the molecule within this model using the force constant and the reduced mass of the molecule. ### Question 1: What is the reduced mass of the HF molecule in atomic units? ### Question 2: Use your spline fit to the PES of HF to estimate the vibrational frequency of HF. Express your number in atomic units and also convert to a common spectroscopic unit system of your choosing (wavenumbers, nm, microns, Hertz, THz are all acceptable choices). ```python #HE = InterpolatedUnivariateSpline(r_fine, harm_pot, k=order) #HF = -HE.derivative() ### define reduced mass of HF as m_H * m_H /(m_F + m_H) where mass is in atomic units (electron mass = 1) m_F = 34883. m_H = 1836. mu = (m_F * m_H)/(m_F + m_H) ### compute the fundamental frequency at each level of theory RHF_nu = 1/(np.pi*2) * np.sqrt(RHF_k/mu) MP2_nu = 1/(np.pi*2) * np.sqrt(MP2_k/mu) CCSD_nu = 1/(np.pi*2) * np.sqrt(CCSD_k/mu) ### print the values in atomic units! print("Vibrational frequency of HF at the RHF/cc-pVDZ level is ",RHF_nu," atomic units") print("Vibrational frequency of HF at the MP2/cc-pVDZ level is ",MP2_nu," atomic units") print("Vibrational frequency of HF at the CCSD/cc-pVDZ level is ",CCSD_nu," atomic units") ``` 1744.1974999319154 Vibrational frequency of HF at the RHF/cc-pVDZ level is 0.0032340020089343204 atomic units Vibrational frequency of HF at the MP2/cc-pVDZ level is 0.0030541643010280816 atomic units Vibrational frequency of HF at the CCSD/cc-pVDZ level is 0.003047094936694507 atomic units ### Question 3: How does these vibrational frequencies compare to the experimental vibrational frequency of HF? Next, we want to actually simulate the dynamics of the HF molecule on this _ab_ _initio_ potential energy surface. To do so, we need to solve Newton's equations of motion subject to some initial condition for the position (separation) and momentum (in a relative sense) of the particles. Newton's equations can be written \begin{equation} F(r) = \mu \frac{d^2}{dr^2} \end{equation} where $\mu$ is the reduced mass in atomic units and $F(r)$ is the Force vs separation in atomic units that was determined previously. ### Question 4: What will be the accelation of the bond stretch when H is separated by F by 3 atomic units? You can express your acceleration in atomic units, also. If the acceleration, position, and velocity of the bond stretch coordinate are known at some instant in time $t_i$, then the position and velocity can be estimated at some later time $t_{i+1} = t_i + \Delta t$: \begin{equation} r(t_i + \Delta t) = r(t_i) + v(t_i)\Delta t + \frac{1}{2}a(t_i)\Delta t^2 \end{equation} and \begin{equation} v(t_i + \Delta t) = v(t_i) + \frac{1}{2} \left(a(t_i) + a(t_i + \Delta t) \right) \Delta t. \end{equation} This prescription for updating the velocities and positions is known as the Velocity-Verlet algorithm. Note that we need to perform 2 force evaluations per Velocity-Verlet iteration: one corresponding to position $r(t_i)$ to update the position, and then a second time at the updated position $r(t_i + \Delta t)$ to complete the velocity update. ```python def Velocity_Verlet(r_curr, v_curr, mu, f_interp, dt): ### get acceleration at current time a_curr = -1*f_interp(r_curr)/mu ### use current acceleration and velocity to update position r_fut = r_curr + v_curr * dt + 0.5 * a_curr * dt**2 ### use r_fut to get future acceleration a_fut a_fut = -1*f_interp(r_fut)/mu ### use current and future acceleration to get future velocity v_fut v_fut = v_curr + 0.5*(a_curr + a_fut) * dt result = [r_fut, v_fut] return result ``` To be able to define the very first update, an initial position and velocity must be specified. Typically, these are chosen at random from a sensible range of values. ### Question 5: What makes a "sensible range of values" for position and velocity? In this case, we will initialize the position to be a random number between 1.0 and 4.0; for the velocity, we will use the fact that we can estimate the expectation value of kinetic energy for a very similar system (the Harmonic oscillator) in the ground state as follows: \begin{equation} \langle T \rangle = \frac{1}{2} E_g, \end{equation} where $E_g$ is the ground state of the Harmonic oscillator (this is making use of the Virial theorem). We can easily find the ground state energy in the Harmonic oscillator approximation of $HF$ using our frequency calculation described above as \begin{equation} E_g = \frac{1}{2} h \nu, \end{equation} which implies the kinetic energy expectation value is \begin{equation} \langle T \rangle = \frac{h}{8 \pi} \sqrt{\frac{k}{\mu}}. \end{equation} Since we can say classically that the kinetic energy is given by $T = \frac{1}{2}\mu v^2$, we can estimate the velocity of the bond stretch as follows: \begin{equation} v = \sqrt{\frac{2 \langle T \rangle}{\mu}} = \sqrt{ \frac{\hbar \sqrt{\frac{k}{\mu}}}{2\mu}} \end{equation} where we have simplified using the fact that $\hbar = \frac{h}{2\pi}$ ($\hbar$ has the value 1 in the atomic unit system we are using up to this point!). We will assume that a reasonable range of velocities spans plus or minus 3 times this "ground-state" velocity. ```python ### define "ground-state" velocity for each level of theory v_RHF = np.sqrt( np.sqrt(RHF_k/mu)/(2*mu)) v_MP2 = np.sqrt( np.sqrt(MP2_k/mu)/(2*mu)) v_CCSD = np.sqrt( np.sqrt(CCSD_k/mu)/(2*mu)) ### get random position and velocity for RHF HF within a reasonable range r_init = np.random.uniform(0.75*RHF_Req,2*RHF_Req) v_init = np.random.uniform(-2*v_RHF,2*v_RHF) ### print initial position and velocity print("Initial separation is ",r_init, "atomic units") print("Initial velocity is ",v_init, "atomic units") ### get initial force on the particle based on its separation RHF_F_init = -1*RHF_Force(r_init) print("Initial Force is ", RHF_F_init, "atomic units") ``` Initial separation is 2.472236235287161 atomic units Initial velocity is -2.727188785244146e-05 atomic units Initial Force is -0.1563776103880313 atomic units Now that we have our initial conditions chosen, our force as a function of separation known, and our Velocity Verlet function completed, we are ready to run our simulations! ```python ### how many updates do you want to perform? N_updates = 200000 ### establish time-step for integration to be 0.02 atomic units... this is about 0.0005 femtoseconds ### so total time is 200000*0.02 atomic units of time which is ~9.6e-13 s, or 960 fs dt = 0.02 ### Now use r_init and v_init and run velocity verlet update N_updates times, plot results ### these arrays will store the time, the position vs time, and the velocity vs time r_vs_t = np.zeros(N_updates) v_vs_t = np.zeros(N_updates) t_array = np.zeros(N_updates) ### harmonic results hr_vs_t = np.zeros(N_updates) hv_vs_t = np.zeros(N_updates) ### first entry is the intial position and velocity r_vs_t[0] = r_init v_vs_t[0] = v_init hr_vs_t[0] = r_init hv_vs_t[0] = v_init ### first Velocity Verlet update result_array = Velocity_Verlet(r_init, v_init, mu, RHF_Force, dt) #hresult_array = Velocity_Verlet(r_init, v_init, mu, HF, dt) print(result_array) #print(hresult_array) ### do the update N_update-1 more times for i in range(1,N_updates): tmp = Velocity_Verlet(result_array[0], result_array[1], mu, RHF_Force, dt) result_array = tmp t_array[i] = dt*i r_vs_t[i] = result_array[0] v_vs_t[i] = result_array[1] #tmp = Velocity_Verlet(hresult_array[0], hresult_array[1], mu, HF, dt) #hr_vs_t[i] = hresult_array[0] #hv_vs_t[i] = hresult_array[1] ### Plot the trajectory of bondlength vs time: #plt.plot(t_array, r_vs_t, 'red', t_array, hr_vs_t, 'blue') plt.plot(t_array, r_vs_t) plt.show() ### plot the phase space trajectory of position vs momentum #plt.plot(mu*v_vs_t, r_vs_t, 'blue', mu*hv_vs_t, hr_vs_t, 'purple') #plt.show() ``` ```python ```
Most samplers have an alphabet or several of them, so I decided to create one with just numbers! Have fun stitching it! Look for smaller samplers in the design, they can be stitched separately! This 10 page booklet includes an alphabet---just in case you want add it or personalize the piece, plus two more alphabets for dating your piece, plus 4 smalls for creating scissor fobs.
[STATEMENT] lemma bdd_above_Iio[simp, intro]: "bdd_above {..<\<^sub>ab}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. local.bdd_above {..<\<^sub>ab} [PROOF STEP] by (auto intro: less_imp_le)
[STATEMENT] lemma norm1_ge_0: "norm1 v \<ge> 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 \<le> norm1 v [PROOF STEP] unfolding norm1_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 \<le> (\<Sum>i\<in>UNIV. norm (v $h i)) [PROOF STEP] by (rule sum_nonneg, auto)
Require Import HoTT.Basics Coq.Unicode.Utf8. (* Can explore replacing U with i+1 everywhere, but probably difficult *) (* Infinitary arguments/indices are hard. *) (* Do we care that El ((a : A) -> B a) = (a : A) -> El (B a) ? *) (* Is it actually worth splitting TySort and TyOp? *) Module Sem. Record t@{i U | i < U} := { Ctx : Type@{U}; TySort (Γ : Ctx) : Type@{U}; TyOp (Γ : Ctx) : Type@{U}; Data (Γ : Ctx) : Type@{U}; data_to_op {Γ} : Data Γ → TyOp Γ; Indices : Ctx → Type@{i}; (* a small set *) emp : Ctx; ext_sort (Γ : Ctx) (A : TySort Γ) : Ctx; ext_op (Γ : Ctx) (A : TyOp Γ) : Ctx; ext_data (Γ : Ctx) (A : Data Γ) : Ctx := ext_op Γ (data_to_op A); inc {Γ} (i : Indices Γ) : Data Γ; inf {Γ} (A : Type@{i}) `{IsHSet A} (B : A → Indices Γ): Data Γ; u {Γ} : TySort Γ; ind_ix {Γ} (A : Data Γ) (B : TySort (ext_data Γ A)) : TySort Γ; nonind_ix {Γ} (A : Type@{i}) `{IsTrunc 1 A} (B : A → TySort Γ) : TySort Γ; el {Γ} (i : Indices Γ) := data_to_op (inc i) : TyOp Γ; ind_arg {Γ} (A : Data Γ) (B : TyOp (ext_data Γ A)) : TyOp Γ; nonind_arg {Γ} (A : Type@{i}) `{IsHSet A} (B : A → TyOp Γ) : TyOp Γ; (* We expect that: data_to_op (inf A f) = nonind_arg A (data_to_op o f) *) }. End Sem. Section specs. Universes i U. Constraint i < U. Context (sem : Sem.t@{i U}). (* Close Indices under external products *) Inductive Data (Indices : Type@{i}) : Type@{i+1} := | inc (i : Indices) | inf (A : Type@{i}) `{IsHSet A} (B : A → Indices) . Global Arguments inc {Indices} i. Global Arguments inf {Indices} A {_} B. Fixpoint ElData {Γ : sem.(Sem.Ctx)} (A : Data (sem.(Sem.Indices) Γ)) : sem.(Sem.Data) Γ := match A with | inc i => sem.(Sem.inc) i | inf A _ B => sem.(Sem.inf) A B end. (*TySort and TyOp use Γ as a large non-uniform parameter, but not essentially*) Inductive TySort (Γ : sem.(Sem.Ctx)) : Type@{i+1} := | u | ind_ix (A : Data (sem.(Sem.Indices) Γ)) (B : TySort (sem.(Sem.ext_data) Γ (ElData A))) | nonind_ix (A : Type@{i}) `{IsTrunc@{i} 1 A} (B : A → TySort Γ) . Global Arguments u {Γ}. Global Arguments ind_ix {Γ} A B. Global Arguments nonind_ix {Γ} A {_} B. Fixpoint ElTySort {Γ} (A : TySort Γ) : sem.(Sem.TySort) Γ := match A with | u => sem.(Sem.u) | ind_ix A B => sem.(Sem.ind_ix) (ElData A) (ElTySort B) | nonind_ix A _ B => sem.(Sem.nonind_ix) A (ElTySort o B) end. Inductive TyOp (Γ : sem.(Sem.Ctx)) : Type@{i+1} := | el (i : sem.(Sem.Indices) Γ) | ind_arg (A : Data (sem.(Sem.Indices) Γ)) (B : TyOp (sem.(Sem.ext_data) Γ (ElData A))) | nonind_arg (A : Type@{i}) `{IsHSet A} (B : A → TyOp Γ) . Global Arguments el {Γ} i. Global Arguments ind_arg {Γ} A B. Global Arguments nonind_arg {Γ} A {_} B. Fixpoint ElTyOp {Γ} (A : TyOp Γ) : sem.(Sem.TyOp) Γ := match A with | el i => sem.(Sem.el) i | ind_arg A B => sem.(Sem.ind_arg) (ElData A) (ElTyOp B) | nonind_arg A _ B => sem.(Sem.nonind_arg) A (ElTyOp o B) end. (* Data is a subset of TyOp *) Fixpoint data_to_op {Γ} (A : Data (sem.(Sem.Indices) Γ)) : TyOp Γ := match A with | inc i => el i | inf A _ B => nonind_arg A (el o B) end. (* If the equations in the semantics hold definitionally then ElTyOp o sem.(Sem.data_to_op) = data_to_op o ElData definitionally on concrete specifications. (an outrageous coincidence) Proving this internally requires function extensionality. *) (* Here we define Ctx as the inductive recursive: data Ctx : Type@{j} ElCtx : Ctx → sem.(Sem.Ctx) data Ctx where emp : Ctx ext_sort : (Γ : Ctx) → TySort (ElCtx Γ) → Ctx ext_op : (Γ : Ctx) → TyOp (ElCtx Γ) → Ctx ElCtx emp = sem.(Sem.emp) ElCtx (ext_sort Γ A) = sem.(Sem.ext_sort) (ElCtx Γ) (ElTySort A) ElCtx (ext_op Γ A) = sem.(Sem.ext_op ) (ElCtx Γ) (ElTyOp A) We don't include ext_data, expecting data_to_op to work by coincidence. *) (* If sem.(Sem.Ctx) : Type@{i+1}, can take Ctx to be (indexing by final sem ctx) data PreCtx : sem.(Sem.Ctx) → Type@{i+1} where pre_emp : PreCtx sem.(Sem.emp) pre_ext_sort { γ : sem.(Sem.Ctx) & PreCtx γ } (A : TySort γ) pre_ext_op { γ : sem.(Sem.Ctx) & PreCtx γ } (A : TyOp γ) Ctx := { γ : sem.(Sem.Ctx) & PreCtx γ } or in the reverse order (right-nested): data PreCtx (γ : sem.(Sem.Ctx)) : Type@{i+1} where pre_end pre_push_sort (A : TySort γ) (Γ : PreCtx (sem.(Sem.ext_sort) γ A)) pre_push_op (A : TyOp γ) (Γ : PreCtx (sem.(Sem.ext_op ) γ A)) Ctx := PreCtx sem.(Sem.emp) Both of these have the advantage that Ctx lands in Type@{i+1} not Type@{U > i}. However, the first keeps semantic contexts around, while the second has a bad induction principle. Probably best is to do everything as an ornament, exploiting the fact that we never branch on the semantics, and that the extra information is small. *) Inductive PreCtx : Type@{i} := | pre_emp | pre_ext_sort (Γ : PreCtx) | pre_ext_op (Γ : PreCtx) . Record CtxPair := { GoodCtx : Type@{U} ; ElGoodCtx : GoodCtx → sem.(Sem.Ctx) }. Fixpoint ElPreCtx (Γ : PreCtx) : CtxPair := match Γ with | pre_emp => {| GoodCtx := Unit; ElGoodCtx _ := sem.(Sem.emp) |} | pre_ext_sort Γ => {| GoodCtx := { γ : _ & TySort ((ElPreCtx Γ).(ElGoodCtx) γ) }; ElGoodCtx x := sem.(Sem.ext_sort) _ (ElTySort x.2); |} | pre_ext_op Γ => {| GoodCtx := { γ : _ & TyOp ((ElPreCtx Γ).(ElGoodCtx) γ) }; ElGoodCtx x := sem.(Sem.ext_op) _ (ElTyOp x.2); |} end. Definition Ctx : Type@{U} := { Γ : PreCtx & (ElPreCtx Γ).(GoodCtx) }. Definition ElCtx (Γ : Ctx) : sem.(Sem.Ctx) := (ElPreCtx Γ.1).(ElGoodCtx) Γ.2. Definition emp : Ctx := (pre_emp ; tt). Definition ext_sort (Γ : Ctx) (A : TySort (ElCtx Γ)) : Ctx := (pre_ext_sort Γ.1; Γ.2; A). Definition ext_op (Γ : Ctx) (A : TyOp (ElCtx Γ)) : Ctx := (pre_ext_op Γ.1; Γ.2; A). (* TODO: Define the recursion principle for Ctx *) End specs. (* inductive-inductive specifications are given by Ctx. *)
!==============================================================================! subroutine Find_Parents(grid) !------------------------------------------------------------------------------! ! Looks boundary cells' parents for meshes in which they are not given ! !------------------------------------------------------------------------------! !----------------------------------[Modules]-----------------------------------! use Grid_Mod, only: Grid_Type !------------------------------------------------------------------------------! implicit none !---------------------------------[Arguments]----------------------------------! type(Grid_Type) :: grid !------------------------------------------------------------------------------! include 'Cell_Numbering_Neu.f90' !-----------------------------------[Locals]-----------------------------------! integer :: fn(6,4), j, n1, n2, c1, c2, bc integer :: n_match integer :: n_bnd_proj ! bnd. cells projected from cells integer :: n_face_nodes ! number of nodes in a face integer :: n_cell_faces ! number of faces in a cell logical, allocatable :: is_node_bnd(:) !==============================================================================! print *, '#=================================================' print *, '# Parent information not given in the input file!' print *, '# Looking for parents. This may take a few minutes' print *, '#-------------------------------------------------' print *, '# Number of boundary cells: ', grid % n_bnd_cells print *, '# Number of inside cells: ', grid % n_cells if(grid % n_cells .eq. 0) then print *, '# Number of cells inside the domain is zero' print *, '# Are you sure you meshed the domain in 3D?' print *, '# Exiting!' print *, '#-------------------------------------------------' stop end if allocate(is_node_bnd(grid % n_nodes)) n_bnd_proj = 0 do bc = 1, grid % n_bnd_cond ! Re-initialize the logical array is_node_bnd(:) = .false. ! Mark boundary nodes in this section do c2 = -grid % n_bnd_cells, -1 if( grid % bnd_cond % color(c2) .eq. bc ) then do n2 = 1, grid % cells_n_nodes(c2) ! 3 or 4 is_node_bnd( grid % cells_n(n2, c2) ) = .true. end do end if end do do c1 = 1, grid % n_cells ! Fetch the faces from this cell if(grid % cells_n_nodes(c1) .eq. 4) fn = neu_tet if(grid % cells_n_nodes(c1) .eq. 5) fn = neu_pyr if(grid % cells_n_nodes(c1) .eq. 6) fn = neu_wed if(grid % cells_n_nodes(c1) .eq. 8) fn = neu_hex n_cell_faces = 6 ! assume it is a hexahedron if(grid % cells_n_nodes(c1) .eq. 4) n_cell_faces = 4 if(grid % cells_n_nodes(c1) .eq. 5) n_cell_faces = 5 if(grid % cells_n_nodes(c1) .eq. 6) n_cell_faces = 5 ! Browse through all possible faces do j = 1, n_cell_faces n_match = 0 n_face_nodes = 4 ! assume it is a quad if( fn(j, 4) < 0 ) then ! nope, it was a triangle n_face_nodes = 3 end if do n1 = 1, n_face_nodes if(fn(j, n1) > 0) then ! if this node exists if( is_node_bnd( grid % cells_n(fn(j, n1), c1) ) ) then n_match = n_match + 1 end if end if end do ! n1 ! This face is matching if(n_match .eq. n_face_nodes) then grid % cells_bnd_color(j, c1) = bc n_bnd_proj = n_bnd_proj + 1 end if ! n_match .eq. n_face_nodes end do ! j end do end do !-------------------------------------------! ! Update number of boundary cells ! ! (This is probably not needed because ! ! it is re-calculated in Grid_Topology) ! !-------------------------------------------! if(n_bnd_proj > grid % n_bnd_cells) then grid % n_bnd_cells = n_bnd_proj end if end subroutine
@testset "Matrix" begin @testset "Matrix: Determinant" begin M1 = [1 0; 2 2] M2 = rand(3,3) M3 = rand(4,4) @test determinant(M1) == det(M1) @test round(determinant(M2),digits = 4) == round(det(M2),digits = 4) @test round(determinant(M3),digits = 4) == round(det(M3),digits = 4) end @testset "Matrix: LU Decompose" begin mat = [ 2 -1 -2; -4 6 3; -4 -2 8 ] L = [ 1 0 0; -2 1 0; -2 -1 1 ] U = [ 2 -1 -2; 0 4 -1; 0 0 3 ] @test lu_decompose(mat) == (L,U) end @testset "Matrix: rotation matrix" begin theta = pi/6 a = [1;0] b = [0;1] @test rotation_matrix(theta)*a == [cos(theta);sin(theta)] @test rotation_matrix(theta)*b == [-sin(theta);cos(theta)] end end
If nicknames were rooted in a very player’s romance along with his organization, Victor ‘Found Money’ Mete would be rolling off tongues throughout Montreal.6 weeks ago, an enormous swath from the Canadiens enthusiast base had, at very best, a vague notion of who Mete was. And in some cases people with intimate knowledge of his skills including a sociates on the entrance busine s, most likely experienced no inclining he was the answer for the i sue, Hey, who the heck is gonna https://www.stylepanthers.com/ fill that Andrei Markov-sized hole within the left side from the 1st pair close to Shea Weber? Mete, drafted a hundredth overall in 2016, has absent from intriguing to indispensable for Montreal during the span of 7 online games, a lively vibrant place within an if not dreadful begin for that Habs. That is why, regardle s that he’s one particular of a couple of dozen entry-level slide candidates inside the league, there is practically no po sibility he’s returned by Montreal to your London Henrik Borgstrom Jersey Knights from the OHL.For a speedy refresher and when you want to go deeper and also a bit cro s-eyed, down load the CBA and dive into portion 9.one most young people that have however to engage in ten NHL games is often re-a signed to your reduced league without getting one on the a few several years on their own entry-level deal burned. Just one exception is Clayton Keller of the Arizona Coyotes. Keller didn’t sign his deal until finally his age 19 season and, acquiring now slid 1 season when he performed 3 game titles last year, Keller is over the clock despite in which he plays that will be from Roberto Luongo Jersey the NHL for your up coming fifteen many years. Cette entrée a été publiée dans Non classé, et marquée avec a lively vibrant place within an if not dreadful begin for that Habs. That is why, a vague notion of who Mete was. And in some cases people with intimate knowledge of his skills including a sociates on the entrance busine s, acquiring now slid 1 season when he performed 3 game titles last year, an enormous swath from the Canadiens enthusiast base had, at very best, down load the CBA and dive into portion 9.one most young people that have however to engage in ten NHL games is often re-a signed to your reduced league without getting one on the a few several years , drafted a hundredth overall in 2016, has absent from intriguing to indispensable for Montreal during the span of 7 online games, Hey, If nicknames were rooted in a very player's romance along with his organization, Keller is over the clock despite in which he plays that will be from Roberto Luongo Jersey the NHL for your up coming fifteen many years., most likely experienced no inclining he was the answer for the i sue, regardle s that he's one particular of a couple of dozen entry-level slide candidates inside the league, Remaining up or likely down: Entry-level contracts approaching 9 online games, there is practically no po sibility he's returned by Montreal to your London Henrik Borgstrom Jersey Knights from the OHL.For a speedy refresher and when you want to go deeper and also a bit cro s-eye, Victor 'Found Money' Mete would be rolling off tongues throughout Montreal.6 weeks ago, who the heck is gonna https://www.stylepanthers.com/ fill that Andrei Markov-sized hole within the left side from the 1st pair close to Shea Weber? Mete, le 2 janvier 2019 par Audrey Malacain.
(* Title: HOL/Auth/n_flash_lemma_on_inv__25.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash Protocol Case Study*} theory n_flash_lemma_on_inv__25 imports n_flash_base begin section{*All lemmas on causal relation between inv__25 and some rule r*} lemma n_PI_Remote_PutXVsinv__25: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''CacheState'')) (Const CACHE_E))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_Get_Put_DirtyVsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_1Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_2Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_3Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_4Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_5Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_6Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_8_HomeVsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_8Vsinv__25: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__25: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_GetX_PutX_11Vsinv__25: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_Get_PutVsinv__25: assumes a1: "(r=n_PI_Local_Get_Put )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__25: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__25: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__0Vsinv__25: assumes a1: "(r=n_PI_Local_GetX_PutX__part__0 )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__1Vsinv__25: assumes a1: "(r=n_PI_Local_GetX_PutX__part__1 )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_PutXVsinv__25: assumes a1: "(r=n_PI_Local_PutX )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_ReplaceVsinv__25: assumes a1: "(r=n_PI_Local_Replace )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__25: assumes a1: "(r=n_NI_Local_Put )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeProc'') ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_PutXAcksDoneVsinv__25: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_WbVsinv__25: assumes a1: "(r=n_NI_Wb )" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_Get_Get__part__1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_PutX_HomeVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__25: assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__1Vsinv__25: assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_GetX__part__0Vsinv__25: assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_ReplaceVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_Store_HomeVsinv__25: assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Get__part__0Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__25: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__2Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Put_HomeVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Put_HeadVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__2Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__0Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__25: assumes a1: "r=n_NI_ShWb N " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_Nak_HomeVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_NakVsinv__25: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_NakVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetXVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Nak_HomeVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_PutXVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_PutVsinv__25: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_10Vsinv__25: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_PutVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__0Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__25: assumes a1: "r=n_NI_Replace_Home " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_PutXVsinv__25: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_NakVsinv__25: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__25: assumes a1: "r=n_NI_Nak_Clear " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__0Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_GetVsinv__25: assumes a1: "r=n_PI_Local_Get_Get " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_PutVsinv__25: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_HomeVsinv__25: assumes a1: "r=n_NI_Nak_Home " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_10_HomeVsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__25: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__25: assumes a1: "r=n_NI_FAck " and a2: "(f=inv__25 )" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
"""Read in an Ortec SPE file.""" import os import warnings import dateutil.parser import numpy as np from ..core import calibration from .parsers import BecquerelParserError, BecquerelParserWarning def read(filename, verbose=False): """Parse the ASCII SPE file and return a dictionary of data. ORTEC's SPE file format is given on page 73 of this document: http://www.ortec-online.com/download/ortec-software-file-structure-manual.pdf Parameters ---------- filename : str The filename of the CNF file to read. verbose : bool (optional) Whether to print out debugging information. By default False. Returns ------- data : dict Dictionary of data that can be used to instantiate a Spectrum. cal : Calibration Energy calibration stored in the file. """ print("SpeFile: Reading file " + filename) _, ext = os.path.splitext(filename) if ext.lower() != ".spe": raise BecquerelParserError("File extension is incorrect: " + ext) # initialize a dictionary of spectrum data to populate as we parse data = {} # parse the file line-by-line collection_start = None livetime = None realtime = None counts = [] channels = [] cal_coeff = [] with open(filename) as f: # read & remove newlines from end of each line lines = [line.strip() for line in f.readlines()] i = 0 while i < len(lines): # check whether we have reached a keyword and parse accordingly if lines[i] == "$DATE_MEA:": i += 1 collection_start = dateutil.parser.parse(lines[i]) if verbose: print(collection_start) elif lines[i] == "$MEAS_TIM:": i += 1 livetime = float(lines[i].split(" ")[0]) realtime = float(lines[i].split(" ")[1]) if verbose: print(livetime, realtime) elif lines[i] == "$DATA:": i += 1 first_channel = int(lines[i].split(" ")[0]) # I don't know why it would be nonzero if first_channel != 0: raise BecquerelParserError( f"First channel is not 0: {first_channel}" ) num_channels = int(lines[i].split(" ")[1]) if verbose: print(first_channel, num_channels) j = first_channel while j <= num_channels + first_channel: i += 1 counts = np.append(counts, int(lines[i])) channels = np.append(channels, j) j += 1 elif lines[i] == "$MCA_CAL:": i += 1 n_coeff = int(lines[i]) i += 1 for j in range(n_coeff): cal_coeff.append(float(lines[i].split(" ")[j])) if verbose: print(cal_coeff) elif lines[i].startswith("$"): key = lines[i][1:].rstrip(":") i += 1 values = [] while i < len(lines) and not lines[i].startswith("$"): values.append(lines[i]) i += 1 if i < len(lines): if lines[i].startswith("$"): i -= 1 if len(values) == 1: values = values[0] data[key] = values else: warnings.warn( f"Line {i + 1} unknown: " + lines[i], BecquerelParserWarning, ) i += 1 # check the data that were read if collection_start is None: raise BecquerelParserError("Start time not found") if livetime is None: raise BecquerelParserError("Live time not found") if realtime is None: raise BecquerelParserError("Real time not found") if realtime <= 0.0: raise BecquerelParserError(f"Real time not parsed correctly: {realtime}") if livetime <= 0.0: raise BecquerelParserError(f"Live time not parsed correctly: {livetime}") if livetime > realtime: raise BecquerelParserError(f"Livetime > realtime: {livetime} > {realtime}") # finish populating data dict data["realtime"] = realtime data["livetime"] = livetime data["start_time"] = collection_start data["counts"] = counts # create an energy calibration object cal = None if len(cal_coeff) > 0 and not np.allclose(cal_coeff, 0): cal = calibration.Calibration.from_polynomial(cal_coeff) return data, cal
""" Julia library for solving PDEs with a focus on wave-propagation problems. """ module WaveProp using DocStringExtensions include("Utils/Utils.jl") include("Geometry/Geometry.jl") include("Interpolation/Interpolation.jl") include("Integration/Integration.jl") include("Mesh/Mesh.jl") include("PhysicalProblem/PhysicalProblem.jl") include("FEM/FEM.jl") include("Nystrom/Nystrom.jl") include("IO/IO.jl") end # module
module Builtin.Reflection where open import Prelude hiding (abs) open import Prelude.Equality.Unsafe open import Builtin.Float open import Container.Traversable open import Control.Monad.Zero open import Agda.Builtin.Reflection as Builtin open Builtin public hiding ( primQNameEquality ; primQNameLess ; primShowQName ; primMetaEquality ; primMetaLess ; primShowMeta ) --- Names --- instance ShowName : Show Name showsPrec {{ShowName}} _ x = showString (primShowQName x) instance EqName : Eq Name _==_ {{EqName}} x y with primQNameEquality x y ... | true = yes unsafeEqual ... | false = no unsafeNotEqual data LessName (x y : Name) : Set where less-name : primQNameLess x y ≡ true → LessName x y private cmpName : ∀ x y → Comparison LessName x y cmpName x y with inspect (primQNameLess x y) ... | true with≡ eq = less (less-name eq) ... | false with≡ _ with inspect (primQNameLess y x) ... | true with≡ eq = greater (less-name eq) ... | false with≡ _ = equal unsafeEqual instance OrdName : Ord Name OrdName = defaultOrd cmpName OrdLawsName : Ord/Laws Name Ord/Laws.super OrdLawsName = it less-antirefl {{OrdLawsName}} (less-name eq) = unsafeNotEqual eq less-trans {{OrdLawsName}} (less-name _) (less-name _) = less-name unsafeEqual --- Meta variables --- instance ShowMeta : Show Meta showsPrec {{ShowMeta}} _ x = showString (primShowMeta x) instance EqMeta : Eq Meta _==_ {{EqMeta}} x y with primMetaEquality x y ... | true = yes unsafeEqual ... | false = no unsafeNotEqual data LessMeta (x y : Meta) : Set where less-meta : primMetaLess x y ≡ true → LessMeta x y private cmpMeta : ∀ x y → Comparison LessMeta x y cmpMeta x y with inspect (primMetaLess x y) ... | true with≡ eq = less (less-meta eq) ... | false with≡ _ with inspect (primMetaLess y x) ... | true with≡ eq = greater (less-meta eq) ... | false with≡ _ = equal unsafeEqual instance OrdMeta : Ord Meta OrdMeta = defaultOrd cmpMeta OrdLawsMeta : Ord/Laws Meta Ord/Laws.super OrdLawsMeta = it less-antirefl {{OrdLawsMeta}} (less-meta eq) = unsafeNotEqual eq less-trans {{OrdLawsMeta}} (less-meta _) (less-meta _) = less-meta unsafeEqual --- Literals --- instance ShowLiteral : Show Literal showsPrec {{ShowLiteral}} _ (nat n) = shows n showsPrec {{ShowLiteral}} _ (word64 n) = shows n showsPrec {{ShowLiteral}} _ (float x) = shows x showsPrec {{ShowLiteral}} _ (char c) = shows c showsPrec {{ShowLiteral}} _ (string s) = shows s showsPrec {{ShowLiteral}} _ (name x) = shows x showsPrec {{ShowLiteral}} _ (meta x) = shows x --- Terms --- pattern vArg x = arg (arg-info visible relevant) x pattern hArg x = arg (arg-info hidden relevant) x pattern iArg x = arg (arg-info instance′ relevant) x unArg : ∀ {A} → Arg A → A unArg (arg _ x) = x getArgInfo : ∀ {A} → Arg A → ArgInfo getArgInfo (arg i _) = i getVisibility : ∀ {A} → Arg A → Visibility getVisibility (arg (arg-info v _) _) = v getRelevance : ∀ {A} → Arg A → Relevance getRelevance (arg (arg-info _ r) _) = r isVisible : ∀ {A} → Arg A → Bool isVisible (arg (arg-info visible _) _) = true isVisible _ = false instance FunctorArg : Functor Arg fmap {{FunctorArg}} f (arg i x) = arg i (f x) TraversableArg : Traversable Arg traverse {{TraversableArg}} f (arg i x) = ⦇ (arg i) (f x) ⦈ unAbs : ∀ {A} → Abs A → A unAbs (abs _ x) = x instance FunctorAbs : Functor Abs fmap {{FunctorAbs}} f (abs s x) = abs s (f x) TraversableAbs : Traversable Abs traverse {{TraversableAbs}} f (abs s x) = ⦇ (abs s) (f x) ⦈ absurd-lam : Term absurd-lam = pat-lam (absurd-clause (vArg absurd ∷ []) ∷ []) [] --- TC monad --- mapTC : ∀ {a b} {A : Set a} {B : Set b} → (A → B) → TC A → TC B mapTC f m = bindTC m λ x → returnTC (f x) instance FunctorTC : ∀ {a} → Functor {a} TC fmap {{FunctorTC}} = mapTC ApplicativeTC : ∀ {a} → Applicative {a} TC pure {{ApplicativeTC}} = returnTC _<*>_ {{ApplicativeTC}} = monadAp bindTC MonadTC : ∀ {a} → Monad {a} TC _>>=_ {{MonadTC}} = bindTC FunctorTC′ : ∀ {a b} → Functor′ {a} {b} TC fmap′ {{FunctorTC′}} = mapTC ApplicativeTC′ : ∀ {a b} → Applicative′ {a} {b} TC _<*>′_ {{ApplicativeTC′}} = monadAp′ bindTC MonadTC′ : ∀ {a b} → Monad′ {a} {b} TC _>>=′_ {{MonadTC′}} = bindTC FunctorZeroTC : ∀ {a} → FunctorZero {a} TC empty {{FunctorZeroTC}} = typeError [] AlternativeTC : ∀ {a} → Alternative {a} TC _<|>_ {{AlternativeTC}} = catchTC Tactic = Term → TC ⊤ give : Term → Tactic give v = λ hole → unify hole v define : Arg Name → Type → List Clause → TC ⊤ define f a cs = declareDef f a >> defineFun (unArg f) cs newMeta : Type → TC Term newMeta = checkType unknown newMeta! : TC Term newMeta! = newMeta unknown typeErrorS : ∀ {a} {A : Set a} → String → TC A typeErrorS s = typeError (strErr s ∷ []) blockOnMeta! : ∀ {a} {A : Set a} → Meta → TC A blockOnMeta! x = commitTC >>=′ λ _ → blockOnMeta x inferNormalisedType : Term → TC Type inferNormalisedType t = withNormalisation true (inferType t) --- Convenient wrappers --- -- Zero for non-datatypes getParameters : Name → TC Nat getParameters d = caseM getDefinition d of λ { (data-type n _) → pure n ; _ → pure 0 } getConstructors : Name → TC (List Name) getConstructors d = caseM getDefinition d of λ { (data-type _ cs) → pure cs ; (record-type c _) → pure (c ∷ []) ; _ → typeError (strErr "Cannot get constructors of non-data or record type" ∷ nameErr d ∷ []) } getClauses : Name → TC (List Clause) getClauses d = caseM getDefinition d of λ { (function cs) → pure cs ; _ → typeError (strErr "Cannot get constructors of non-function type" ∷ nameErr d ∷ []) } -- Get the constructor of a record type (or single-constructor data type) recordConstructor : Name → TC Name recordConstructor r = caseM getConstructors r of λ { (c ∷ []) → pure c ; _ → typeError $ strErr "Cannot get constructor of non-record type" ∷ nameErr r ∷ [] } -- Injectivity of constructors arg-inj₁ : ∀ {A i i′} {x x′ : A} → arg i x ≡ arg i′ x′ → i ≡ i′ arg-inj₁ refl = refl arg-inj₂ : ∀ {A i i′} {x x′ : A} → arg i x ≡ arg i′ x′ → x ≡ x′ arg-inj₂ refl = refl arg-info-inj₁ : ∀ {v v′ r r′} → arg-info v r ≡ arg-info v′ r′ → v ≡ v′ arg-info-inj₁ refl = refl arg-info-inj₂ : ∀ {v v′ r r′} → arg-info v r ≡ arg-info v′ r′ → r ≡ r′ arg-info-inj₂ refl = refl abs-inj₁ : ∀ {A s s′} {x x′ : A} → abs s x ≡ abs s′ x′ → s ≡ s′ abs-inj₁ refl = refl abs-inj₂ : ∀ {A s s′} {x x′ : A} → abs s x ≡ abs s′ x′ → x ≡ x′ abs-inj₂ refl = refl --- Terms --- var-inj₁ : ∀ {x x′ args args′} → Term.var x args ≡ var x′ args′ → x ≡ x′ var-inj₁ refl = refl var-inj₂ : ∀ {x x′ args args′} → Term.var x args ≡ var x′ args′ → args ≡ args′ var-inj₂ refl = refl con-inj₁ : ∀ {c c′ args args′} → Term.con c args ≡ con c′ args′ → c ≡ c′ con-inj₁ refl = refl con-inj₂ : ∀ {c c′ args args′} → Term.con c args ≡ con c′ args′ → args ≡ args′ con-inj₂ refl = refl def-inj₁ : ∀ {f f′ args args′} → def f args ≡ def f′ args′ → f ≡ f′ def-inj₁ refl = refl def-inj₂ : ∀ {f f′ args args′} → def f args ≡ def f′ args′ → args ≡ args′ def-inj₂ refl = refl meta-inj₁ : ∀ {f f′ args args′} → Term.meta f args ≡ meta f′ args′ → f ≡ f′ meta-inj₁ refl = refl meta-inj₂ : ∀ {f f′ args args′} → Term.meta f args ≡ meta f′ args′ → args ≡ args′ meta-inj₂ refl = refl lam-inj₁ : ∀ {v v′ t t′} → lam v t ≡ lam v′ t′ → v ≡ v′ lam-inj₁ refl = refl lam-inj₂ : ∀ {v v′ t t′} → lam v t ≡ lam v′ t′ → t ≡ t′ lam-inj₂ refl = refl pat-lam-inj₁ : ∀ {v v′ t t′} → pat-lam v t ≡ pat-lam v′ t′ → v ≡ v′ pat-lam-inj₁ refl = refl pat-lam-inj₂ : ∀ {v v′ t t′} → pat-lam v t ≡ pat-lam v′ t′ → t ≡ t′ pat-lam-inj₂ refl = refl pi-inj₁ : ∀ {t₁ t₁′ t₂ t₂′} → pi t₁ t₂ ≡ pi t₁′ t₂′ → t₁ ≡ t₁′ pi-inj₁ refl = refl pi-inj₂ : ∀ {t₁ t₁′ t₂ t₂′} → pi t₁ t₂ ≡ pi t₁′ t₂′ → t₂ ≡ t₂′ pi-inj₂ refl = refl sort-inj : ∀ {x y} → agda-sort x ≡ agda-sort y → x ≡ y sort-inj refl = refl lit-inj : ∀ {x y} → Term.lit x ≡ lit y → x ≡ y lit-inj refl = refl --- Sorts --- set-inj : ∀ {x y} → set x ≡ set y → x ≡ y set-inj refl = refl slit-inj : ∀ {x y} → Sort.lit x ≡ lit y → x ≡ y slit-inj refl = refl --- Patterns --- pcon-inj₁ : ∀ {x y z w} → Pattern.con x y ≡ con z w → x ≡ z pcon-inj₁ refl = refl pcon-inj₂ : ∀ {x y z w} → Pattern.con x y ≡ con z w → y ≡ w pcon-inj₂ refl = refl pvar-inj : ∀ {x y} → Pattern.var x ≡ var y → x ≡ y pvar-inj refl = refl plit-inj : ∀ {x y} → Pattern.lit x ≡ lit y → x ≡ y plit-inj refl = refl proj-inj : ∀ {x y} → Pattern.proj x ≡ proj y → x ≡ y proj-inj refl = refl --- Clauses --- clause-inj₁ : ∀ {x y z w} → clause x y ≡ clause z w → x ≡ z clause-inj₁ refl = refl clause-inj₂ : ∀ {x y z w} → clause x y ≡ clause z w → y ≡ w clause-inj₂ refl = refl absurd-clause-inj : ∀ {x y} → absurd-clause x ≡ absurd-clause y → x ≡ y absurd-clause-inj refl = refl --- Literals --- nat-inj : ∀ {x y} → nat x ≡ nat y → x ≡ y nat-inj refl = refl word64-inj : ∀ {x y} → word64 x ≡ word64 y → x ≡ y word64-inj refl = refl float-inj : ∀ {x y} → float x ≡ float y → x ≡ y float-inj refl = refl char-inj : ∀ {x y} → char x ≡ char y → x ≡ y char-inj refl = refl string-inj : ∀ {x y} → string x ≡ string y → x ≡ y string-inj refl = refl name-inj : ∀ {x y} → name x ≡ name y → x ≡ y name-inj refl = refl meta-inj : ∀ {x y} → Literal.meta x ≡ meta y → x ≡ y meta-inj refl = refl
From MetaCoq.Template Require Import monad_utils. From MetaCoq.Template Require Import MCList. From MetaCoq.TypedExtraction Require Import ExAst. From MetaCoq.TypedExtraction Require Import Extraction. From MetaCoq.TypedExtraction Require Import CertifyingInlining. From MetaCoq.TypedExtraction Require Import Optimize. From MetaCoq.TypedExtraction Require Import ResultMonad. From ConCert.Extraction Require Import Printing. From ConCert.Extraction Require Import TopLevelFixes. From Coq Require Import PeanoNat. From Coq Require Import Ascii. From Coq Require Import String. From Coq Require Import List. From Coq.Program Require Import Basics. From ConCert.Utils Require Import StringExtra. From ConCert.Extraction Require Import PrettyPrinterMonad. Module P := MetaCoq.PCUIC.PCUICAst. Module PT := MetaCoq.PCUIC.PCUICTyping. Module T2P := MetaCoq.PCUIC.TemplateToPCUIC. Module E := MetaCoq.Erasure.EAst. Module T := MetaCoq.Template.Ast. Module TUtil := MetaCoq.Template.AstUtils. Module EF := MetaCoq.Erasure.ErasureFunction. Module Ex := MetaCoq.TypedExtraction.ExAst. Local Open Scope string. Import MCMonadNotation. Local Definition indent_size := 2. Local Notation "a ^ b" := (a ++ b)%string. Section FixEnv. Context (Σ : Ex.global_env). Context (remaps : remaps). (* A printing config for Rust *) Class RustPrintConfig := { term_box_symbol : string; type_box_symbol : string; any_type_symbol : string; print_full_names : bool (* use fully-qualified names as identifiers to avoid name clashes *)}. Context `{RustPrintConfig}. Import Kernames. (* TODO: eventually, we should use bytestring everywhere, currently, we convert back and forth between Coq' standard [string] and MetaCoq's [bytestring]. *) Notation bs_to_s := bytestring.String.to_string. Notation s_to_bs := bytestring.String.of_string. Local Coercion bytestring.String.of_string : string >-> bytestring.string. Definition ind_attr_map := inductive -> string. Context (ind_attrs : ind_attr_map). Definition lookup_mind (name : kername) : option Ex.mutual_inductive_body := match Ex.lookup_env Σ name with | Some (Ex.InductiveDecl mib) => Some mib | _ => None end. Definition lookup_ind_decl (ind : inductive) : result Ex.one_inductive_body string := match Ex.lookup_env Σ (inductive_mind ind) with | Some (Ex.InductiveDecl {| Ex.ind_bodies := oibs |}) => match nth_error oibs (inductive_ind ind) with | Some body => Ok body | None => Err ("Could not find inductive " ++ bs_to_s (string_of_nat (inductive_ind ind)) ++ " in mutual inductive " ++ bs_to_s (string_of_kername (inductive_mind ind))) end | _ => Err ("Could not find inductive " ++ bs_to_s (string_of_kername (inductive_mind ind)) ++ " in environment") end. (* We clean global identifiers but do not generate any form of fresh names to make it straightforward to know what extracted code maps to what. *) Definition clean_global_ident (s : string) : string := replace_char "." "_" (replace_char "'" "_" s). (* Get identifier for a global constant function given its kername, without taking remappings into account *) Definition const_global_ident_of_kername (kn : kername) := clean_global_ident (if print_full_names then (bs_to_s (string_of_kername kn)) else (bs_to_s (snd kn))). (* Get identifier for a global constant meant to be used as a type, without taking remappings into account. This is also used for [inductive]. *) Definition ty_const_global_ident_of_kername (kn : kername) := s_to_bs (capitalize (clean_global_ident (bs_to_s (if print_full_names then string_of_kername kn else (snd kn))))). (* Get identifier for a global type alias taking remappings into account *) Definition get_ty_const_ident (name : kername) : _ := match remap_inline_constant remaps name with | Some s => s | None => ty_const_global_ident_of_kername name end. (* Get identifier for an inductive taking remappings into account *) Definition get_ind_ident (ind : inductive) : PrettyPrinter _ := match remap_inductive remaps ind with | Some rem => ret (re_ind_name rem) | None => oib <- wrap_result (lookup_ind_decl ind) id;; let kn := (fst (inductive_mind ind), Ex.ind_name oib) in ret (ty_const_global_ident_of_kername kn) end. (* Fine to remove primes here as we generate fresh names *) Definition clean_local_ident (name : ident) : string := remove_char "'" (bs_to_s name). Definition is_polymorphic (cst : Ex.constant_body) : bool := (0 <? #|fst (Ex.cst_type cst)|)%nat. Definition print_ind (ind : inductive) : PrettyPrinter unit := get_ind_ident ind >>= fun x => append (bs_to_s x). Definition print_parenthesized (parenthesize : bool) (print : PrettyPrinter unit) : PrettyPrinter unit := if parenthesize then append "(";; print;; append ")" else print. Definition print_parenthesized_with par_start par_end := fun (parenthesize : bool) (print : PrettyPrinter unit) => if parenthesize then append par_start;; print;; append par_end else print. Definition parenthesize_app_head (t : term) : bool := match t with | tLambda _ _ | tLetIn _ _ _ | tCase _ _ _ | tFix _ _ => true | _ => false end. Definition parenthesize_app_arg (t : term) : bool := match t with | tLambda _ _ | tLetIn _ _ _ | tApp _ _ | tCase _ _ _ | tProj _ _ | tFix _ _ => true | _ => false end. Definition parenthesize_case_discriminee (t : term) : bool := match t with | tLetIn _ _ _ | tCase _ _ _ => true | _ => false end. Definition fresh (name : ident) (used : list ident) : ident := if existsb (bytestring.String.eqb name) used then (fix f n i := match n with | 0 => s_to_bs "unreachable" | S n => let numbered_name := bytestring.String.append name (MCString.string_of_nat i) in if existsb (bytestring.String.eqb numbered_name) used then f n (S i) else numbered_name end) (S (List.length used)) 2 else name. Import BasicAst. Definition fresh_ident (name : name) (Γ : list ident) : PrettyPrinter ident := used_names <- get_used_names;; match name with | nAnon => ret (fresh "x" (Γ ++ used_names)) | nNamed name => ret (fresh (clean_local_ident name) (Γ ++ used_names)) end. Definition fresh_ty_arg_name (name : name) (Γ : list ident) : PrettyPrinter ident := used_names <- get_used_names;; match name with | nAnon => ret (fresh "a" (Γ ++ used_names)) | nNamed name => ret (fresh (clean_local_ident name) (Γ ++ used_names)) end. Definition parenthesize_ty_app_arg (t : box_type) : bool := match t with | TApp _ _ => true | _ => false end. Fixpoint print_type_aux (Γ : list ident) (t : box_type) (args : list (PrettyPrinter unit)) := match t with | TBox => append type_box_symbol | TAny => append any_type_symbol | TArr dom cod => append "&'a dyn Fn(";; print_type_aux Γ dom [];; append ") -> ";; print_type_aux Γ cod [] | TApp head arg => print_type_aux Γ head (print_type_aux Γ arg [] :: args) | TVar n => match nth_error Γ n with | Some name => append (bs_to_s name) | None => printer_fail ("unbound TVar " ++ string_of_nat n) end | TInd ind => if remap_inductive remaps ind then print_ind ind;; print_parenthesized_with "<" ">" (0 <? #|args|)%nat (monad_append_join (append ", ") args) else append "&'a ";; print_ind ind;; append "<";; monad_append_join (append ", ") (append "'a" :: args);; append ">" | TConst name => append (bs_to_s (get_ty_const_ident name) ++ "<");; monad_append_join (append ", ") (append "'a" :: args);; append ">" end. Definition print_type Γ t := print_type_aux Γ t []. (* Get number of arguments that a constant expects when we print it *) Definition get_num_inline_args (kn : kername) : PrettyPrinter nat := cst <- wrap_option (Ex.lookup_constant Σ kn) ("Could not find constant " ++ bs_to_s (string_of_kername kn));; match Ex.cst_body cst with | None => ret #|fst (decompose_arr (snd (Ex.cst_type cst)))| | Some body => let fix count body ty := match body, ty with | tLambda _ body, TArr dom cod => S (count body cod) | _, _ => 0 end in ret (count body (snd (Ex.cst_type cst))) end. Definition print_app (head : PrettyPrinter unit) (args : list (PrettyPrinter unit)) : PrettyPrinter unit := col <- get_current_line_length;; head;; push_indent (col + indent_size);; append "(";; (if 0 <? #|args| then append_nl else ret tt)%nat;; monad_append_join (append ",";; append_nl) args;; append ")";; pop_indent. Definition print_constructor (ind : inductive) (c : nat) (args : list (PrettyPrinter unit)) := match remap_inductive remaps ind with | Some rem => s <- wrap_option (nth_error (re_ind_ctors rem) c) (bs_to_s (string_of_inductive ind) ^ "' does not remap enough constructors ");; if (0 <? #|args|)%nat then print_app (append (bs_to_s s)) args else append (bs_to_s s) | None => oib <- wrap_result (lookup_ind_decl ind) id;; '(ctor, _, _) <- wrap_option (nth_error (Ex.ind_ctors oib) c) ("Could not find ctor " ^ string_of_nat c ^ " for inductive " ^ bs_to_s (string_of_inductive ind));; col <- get_current_line_length;; push_indent (col + indent_size);; append "self.alloc(";; append_nl;; let head := print_ind ind;; append "::";; append (clean_global_ident (bs_to_s ctor)) in let final_args := append "PhantomData" :: args in print_app head final_args;; append ")";; pop_indent end. Definition print_const (kn : kername) (args : list (PrettyPrinter unit)) : PrettyPrinter unit := num_inline_args <- get_num_inline_args kn;; let (expr, num_inline_args) := if (#|args| <? num_inline_args)%nat then (* Not enough args, use curried version *) ("self." ^ const_global_ident_of_kername kn ^ "__curried", 0) else (match remap_inline_constant remaps kn with | Some s => (bs_to_s s) | None => "self." ^ const_global_ident_of_kername kn end, num_inline_args) in head_col <- get_current_line_length;; let head := append expr in let args_in_head := firstn num_inline_args args in let args_in_tail := skipn num_inline_args args in print_app head args_in_head;; push_indent (head_col + indent_size);; let it_app a := append "(";; append_nl;; a;; append ")" in monad_append_concat (map it_app args_in_tail);; pop_indent. Section print_term. Context (print_term : list ident -> term -> PrettyPrinter unit). Definition print_case Γ ind npars discr brs : PrettyPrinter unit := col <- get_current_line_length;; push_indent col;; append "match ";; print_term Γ discr;; append " {";; oib <- wrap_result (lookup_ind_decl ind) id;; let rem := remap_inductive remaps ind in push_indent (col + indent_size);; (fix print_cases (brs : list (list name * term)) (ctors : list (ident * list (name * box_type) * nat)) (c : nat) := match brs, ctors with | [], [] => ret tt | (bctx, t) :: branches, (ctor_name, data, _) :: ctors => append_nl;; match rem with | Some rem => s <- wrap_option (nth_error (re_ind_ctors rem) c) (bs_to_s (string_of_inductive ind) ^ "' does not remap enough constructors");; append (bs_to_s s) | None => append "&";; print_ind ind;; append "::";; append (clean_global_ident (bs_to_s ctor_name)) end;; push_indent (col + 2*indent_size);; (fix print_branch (bctx : list name) (args : list ident) (Γ : list ident) {struct bctx} := match bctx with | [] => (* In Coq, parameters are not part of branches. But erasure adds the parameters to each constructor, so we need to get those out of the way first. These won't have any uses so we just print _. In addition, we add a phantom data when not remapped to make it valid to always have lifetimes. That gives another underscores. *) let nextra := if rem then npars else S npars in let extra := List.repeat "_" nextra in let args := (extra ++ map bs_to_s (rev args))%list in print_parenthesized (0 <? #|args|)%nat (append_join ", " args);; append " => {";; append_nl ;; print_term Γ t | name :: bctx0 => name <- fresh_ident name Γ;; print_branch bctx0 (name :: args) (name :: Γ) end) (List.rev bctx) [] Γ;; pop_indent;; append_nl;; append "},";; print_cases branches ctors (S c) | _, _ => printer_fail "wrong number of case branches compared to inductive" end) brs (Ex.ind_ctors oib) 0;; pop_indent;; append_nl;; append "}";; pop_indent. Definition print_remapped_case Γ ind discr brs eliminator : PrettyPrinter unit := col <- get_current_line_length;; push_indent col;; append (eliminator ^ "(");; oib <- wrap_result (lookup_ind_decl ind) id;; push_indent (col + indent_size);; let fix map_cases (brs : list (list name * term)) := match brs with | [] => [] | (bctx, t) :: brs0 => ((fix print_branch (bctx : list name) (args : list ident) (Γ : list ident) {struct bctx} := match bctx with | [] => let args := map bs_to_s (rev args) in append_nl;; append_concat (map (fun a => a ^ ", ") args);; append "{";; push_indent (col + 2*indent_size);; append_nl;; print_term Γ t;; pop_indent;; append_nl;; append "}," | name :: bctx0 => name <- fresh_ident name Γ;; print_branch bctx0 (name :: args) (name :: Γ) end) bctx [] Γ) :: map_cases brs0 end in monad_append_concat (map_cases brs);; append_nl;; print_term Γ discr;; append ")";; pop_indent;; pop_indent. End print_term. Definition needs_block (t : term) : bool := match t with | tLetIn _ _ _ | tFix _ _ => true | _ => false end. Fixpoint print_term (Γ : list ident) (t : term) {struct t} : PrettyPrinter unit := match t with | tBox => append term_box_symbol | tRel n => match nth_error Γ n with | Some name => append (bs_to_s name) | None => printer_fail ("unbound tRel " ++ string_of_nat n) end | tVar ident => printer_fail ("tVar " ++ bs_to_s ident) | tEvar _ _ => printer_fail "unexpected evar" | tLambda name t => name <- fresh_ident name Γ;; col <- get_current_line_length;; push_indent col;; append ("self.closure(move |" ++ (bs_to_s name) ++ "| {");; push_indent (col + indent_size);; append_nl;; let Γ := name :: Γ in print_term Γ t;; pop_indent;; append_nl;; append "})";; pop_indent | tLetIn na val body => name <- fresh_ident na Γ;; col <- get_current_line_length;; push_indent col;; append ("let " ++ (bs_to_s name) ++ " =");; (if needs_block val then append " {" else ret tt);; push_indent (col + indent_size);; append_nl;; print_term Γ val;; pop_indent;; (if needs_block val then append_nl;; append "};" else append ";");; append_nl;; print_term (name :: Γ) body;; pop_indent | tApp head arg => (fix f head args_printed {struct head} := match head with | tApp head arg => let printed_arg := (if needs_block arg then append "{ " else ret tt);; print_term Γ arg;; if needs_block arg then append " }" else ret tt in f head (printed_arg :: args_printed) | tConstruct ind i [] => print_constructor ind i args_printed | tConstruct ind i (_ :: _) => printer_fail ("Costructors-as-blocks is not supported: " ^ bs_to_s (string_of_kername ind.(inductive_mind))) | tConst kn => print_const kn args_printed | _ => (* For other heads we might need to guide type inference by repeatedly applying a hint function *) append (String.concat "" (repeat "hint_app(" #|args_printed|));; (if needs_block head then append "{ " else ret tt);; print_term Γ head;; (if needs_block head then append " }" else ret tt);; append ")";; monad_fold_left (fun pref a => append pref;; a;; append ")";; ret ")(") args_printed "(";; ret tt end) head [if needs_block arg then append "{ ";; print_term Γ arg;; append " }" else print_term Γ arg] | tConst kn => print_const kn [] | tConstruct ind i [] => print_constructor ind i [] | tConstruct ind i (_ :: _) => printer_fail ("Costructors-as-blocks is not supported: " ^ bs_to_s (string_of_kername ind.(inductive_mind))) | tCase (ind, npars) discr brs => match brs with | [] => (* If it's a match on an empty type, we just panic, since we should never reach this code *) append "panic!(""Absurd case!"")" | _ => match remap_inductive remaps ind with | Some rem => match re_ind_match rem with | Some s => print_remapped_case print_term Γ ind discr brs (bs_to_s s) | None => print_case print_term Γ ind npars discr brs end | None => print_case print_term Γ ind npars discr brs end end | tFix defs i => (* Rust does not have recursive closures. Instead, we have to do a trick where we recurse through the heap: we first create a cell on the heap that will point to the closure. Then, we create the closure that unwraps the heap location to get itself. Finally, we put the closure into that heap location and it is ready to use. It is complicated by the fact that fix points are also mutual and we must create many heap cells before assigning the closures, and each closure also needs its own clone of each cell. *) col <- get_current_line_length;; push_indent col;; (* Generate names and allocate cells *) '(Γ, cells) <- monad_fold_left (fun '(Γ, cells) d => (* This is hacky, but instead of putting proper names in the context, we put a string that unwraps the cell in the context. This is simpler for now, but as a side effect we need to push a use since the name won't be in the context. In the future we should unwrap it after the first closure or find a better way to handle this. *) na <- fresh_ident (EAst.dname d) Γ;; push_use na;; append ("let " ++ bs_to_s na ++ " = self.alloc(std::cell::Cell::new(None));");; append_nl;; ret ((bytestring.String.append na ".get().unwrap()") :: Γ, na :: cells)) defs (Γ, []);; let cells := rev cells in (* Print closures. *) monad_fold_left (fun _ '(print_def, cell) => append (cell ++ ".set(Some(");; push_indent (col + indent_size);; append_nl;; print_def;; append "));";; pop_indent;; append_nl) (combine (map (fun d => print_term Γ (EAst.dbody d)) defs) (map bs_to_s cells)) tt;; append (bs_to_s (nth i cells "") ++ ".get().unwrap()");; pop_indent | tProj (mkProjection ind pars c) t => printer_fail ("unhandled tProj on " ^ bs_to_s (string_of_kername (inductive_mind ind))) | tCoFix _ _ => printer_fail "Cannot handle tCoFix yet" | tPrim _ => printer_fail "Cannot handle Coq primitive types yet" end. Definition print_constant (kn : kername) (type : (list name * box_type)) (body : E.term) : PrettyPrinter unit := let rname := const_global_ident_of_kername kn in name_col <- get_current_line_length;; push_indent name_col;; let (type_vars, ty) := type in Γty <- monad_fold_left (fun Γty name => name <- fresh_ty_arg_name name Γty;; ret (Γty ++ [name])%list) type_vars [];; (* Print version with inlined args *) match remap_constant remaps kn with | Some s => append (StringExtra.replace "##name##" rname (bs_to_s s)) | None => if remap_inline_constant remaps kn then ret tt else append ("fn " ++ rname);; print_parenthesized_with "<" ">" (0 <? #|Γty|)%nat (append_join ", " (map (fun na => na ++ ": Copy") (map bs_to_s Γty)));; append "(&'a self";; (fix print_top Γ body ty := match body, ty with | tLambda na body, TArr dom cod => na <- fresh_ident na Γ;; append (", " ++ bs_to_s na ++ ": ");; print_type Γty dom;; print_top (na :: Γ) body cod | _, _ => append ") -> ";; print_type Γty ty;; append " {";; push_indent (name_col + indent_size);; append_nl;; push_use rname;; print_term Γ body;; pop_indent;; append_nl;; append "}" end) [] body ty end;; (* Print curried version if there were inlined args *) num_inline_args <- get_num_inline_args kn;; (if (0 <? num_inline_args)%nat then append_nl;; append ("fn " ++ rname ++ "__curried");; print_parenthesized_with "<" ">" (0 <? #|Γty|)%nat (append_join ", " (map (fun na => na ++ ": Copy") (map bs_to_s Γty)));; append "(&'a self) -> ";; print_type Γty ty;; append " {";; push_indent (name_col + indent_size);; append_nl;; push_use (rname ++ "__curried");; eta_term <- (fix make_eta_term n body ty := match body, ty with | tLambda na body, TArr dom cod => eta_term <- make_eta_term (S n) body cod;; ret (tLambda na eta_term) | _, _ => ret (mkApps (tConst kn) (rev_map tRel (seq 0 n))) end) 0 body ty;; print_term [] eta_term;; pop_indent;; append_nl;; append "}" else ret tt);; pop_indent;; ret tt. Open Scope program_scope. Definition print_ind_ctor_definition (Γ : list ident) (ctor_name : ident) (data : list (name * box_type)) : PrettyPrinter unit := append (clean_global_ident (bs_to_s ctor_name));; (* Make sure we always take a lifetime parameter in data types *) append "(";; (* All constructors take a PhantomData as their first argument which ensures that Rust does not complained about unused lifetimes/type parameters. This phantom type is a 'a lifetimed reference to a tuple of all the type args. *) let print_phantom := append "PhantomData<&'a ";; (if (#|Γ| =? 0)%nat then append "()" else print_parenthesized (1 <? #|Γ|)%nat (append_join ", " (map bs_to_s Γ)));; append ">" in let print_datas := print_phantom :: map (print_type Γ ∘ snd) data in monad_append_join (append ", ") print_datas;; append ")". Local Open Scope string. Definition print_mutual_inductive_body (kn : kername) (mib : Ex.mutual_inductive_body) : PrettyPrinter unit := col <- get_current_line_length;; push_indent col;; names <- (fix print_ind_bodies (l : list Ex.one_inductive_body) (prefix : PrettyPrinter unit) (i : nat) := match l with | [] => ret tt | oib :: l => prefix;; append (ind_attrs (mkInd kn i));; append_nl;; append "pub enum ";; print_ind (mkInd kn i);; (* Add type parameters. Note that since we are in prenex form, our context will have last type parameter last, not first. *) Γ <- monad_fold_left (fun Γ name => name <- fresh_ty_arg_name (tvar_name name) Γ;; ret (Γ ++ [name])%list) (ind_type_vars oib) [];; append "<";; append_join ", " ("'a" :: map bs_to_s Γ);; append "> {";; (* Print constructors *) push_indent (col + indent_size);; append_nl;; monad_append_join (append ",";; append_nl) (map (fun '(name, data, _) => print_ind_ctor_definition Γ name data) (Ex.ind_ctors oib));; pop_indent;; append_nl;; append "}";; print_ind_bodies l append_nl (S i) end) (Ex.ind_bodies mib) (ret tt) 0;; pop_indent;; ret names. Definition print_type_alias (nm : kername) (tvars : list type_var_info) (bt : box_type) : PrettyPrinter unit := let rname := ty_const_global_ident_of_kername nm in match remap_constant remaps nm with | Some s => append (StringExtra.replace "##name##" (bs_to_s rname) (bs_to_s s)) | None => append ("type " ++ (bs_to_s rname) ++ "<");; Γrev <- monad_fold_left (fun Γ tvar => name <- fresh_ty_arg_name (tvar_name tvar) Γ;; ret (name :: Γ)) tvars [];; let Γ := rev Γrev in append_join ", " ("'a" :: map bs_to_s Γ);; append "> = ";; print_type Γ bt;; append ";" end. Fixpoint print_decls_aux (decls : list (kername * bool * Ex.global_decl)) (prefix : PrettyPrinter unit) : PrettyPrinter unit := match decls with | [] => ret tt | (kn, has_deps, decl) :: decls => match decl with | Ex.ConstantDecl {| Ex.cst_type := type; Ex.cst_body := Some body |} => prefix;; print_constant kn type body | Ex.InductiveDecl mib => if remap_inductive remaps (mkInd kn 0) then ret tt else prefix;; print_mutual_inductive_body kn mib | Ex.TypeAliasDecl (Some (tvars, bt)) => prefix;; print_type_alias kn tvars bt | _ => ret tt end;; print_decls_aux decls (append_nl;; append_nl) end. Definition print_decls decls := print_decls_aux decls (ret tt). Class Preamble := { top_preamble : list string; program_preamble : list string }. Context `{Preamble}. Definition print_program : PrettyPrinter unit := sig_col <- get_current_line_length;; push_indent sig_col;; monad_append_join append_nl (map append top_preamble);; let is_const '(kn, decl) := match decl with | Ex.ConstantDecl _ => true | _ => false end in (* Filtering out empty type declarations *) (* TODO: possibly, move to extraction (requires modifications of the correctness proof) *) let Σ := filter (fun '(kn,d) => negb (is_empty_type_decl d)) Σ in ind_names <- print_decls_aux (filter (negb ∘ is_const) (List.rev Σ)) (append_nl;; append_nl);; (* First print a structure that has the arena and all (non-polymorphic) constants in the program *) let constants := flat_map (fun '(kn, has_deps, decl) => match decl with | Ex.ConstantDecl cst => [(kn, has_deps, cst)] | _ => [] end) (List.rev Σ) in append_nl;; append_nl;; push_indent (sig_col + indent_size);; append "struct Program {";; append_nl;; append "__alloc: bumpalo::Bump,";; pop_indent;; append_nl;; append "}";; (* Next we print all the code as associated members. First we print a way to create such a program. *) append_nl;; append_nl;; append "impl<'a> Program {";; append_nl;; append "fn new() -> Self {";; push_indent (sig_col + indent_size);; append_nl;; append "Program {";; push_indent (sig_col + 2*indent_size);; append_nl;; append "__alloc: bumpalo::Bump::new(),";; pop_indent;; append_nl;; append "}";; pop_indent;; append_nl;; append "}";; append_nl;; append_nl;; monad_append_join append_nl (map append program_preamble);; (* Finally print all constants *) const_names <- print_decls_aux (map (MCProd.on_snd Ex.ConstantDecl) constants) (append_nl;; append_nl);; append_nl;; append "}";; pop_indent. End FixEnv. Definition extract_rust_within_coq (overridden_masks : Kernames.kername -> option bitmask) (should_inline : Kernames.kername -> bool) : extract_template_env_params := {| check_wf_env_func := check_wf_env_func extract_within_coq; template_transforms := [template_inline should_inline]; pcuic_args := {| optimize_prop_discr := true; extract_transforms := [dearg_transform overridden_masks true false false false false; TopLevelFixes.transform] |} |}.
module Main where import Math.Probably.Sampler import Math.Probably.RandIO import Math.Probably.FoldingStats import Numeric.LinearAlgebra import Math.Probably.Unscented import Graphics.Gnewplot.Exec import Graphics.Gnewplot.Types import Graphics.Gnewplot.Style import Graphics.Gnewplot.Panels import Graphics.Gnewplot.Instances import Graphics.Gnewplot.Histogram dt = 0.1 f v = fromList [t1, x0 + dt * sin (t1) + noisex] where t0 = v @> 0 x0 = v @> 1 noiset = v @> 2 noisex = v @> 3 t1 = t0+dt + noiset f' v = fromList [t1, x0 + dt * sin (t1) ] where t0 = v @> 0 x0 = v @> 1 t1 = t0+dt g v = fromList [t1+noiset, x1+noisex] where t1 = v @> 0 x1 = v @> 1 noiset = v @> 2 noisex = v @> 3 g' v = fromList [t1, x1] where t1 = v @> 0 x1 = v @> 1 procCov = (2><2) [0.001, 0, 0, 0.01] obsCov = (2><2) [0.01, 0, 0, 0.01] --obsCov = (1><1) [0.01] testUT = do let cov = (2><2) [0.1,0.08,0.08,0.1] mn = (2 |> [1,1]) xform v = let [x,y] = toList v in fromList [x*x, y*y] mkpt = ((\[x,y] -> (x,y)) .toList) pts <- sample $ sequence $ replicate 1000 $ multiNormal mn cov let (mnU, covU, sigmapts) = unscentedTransform (mn,cov) xform let xformPts = map xform pts io $ gnuplotOnScreen $ map mkpt pts :+: map mkpt sigmapts -- :+: map mkpt xformPts io $ print mnU io $ print covU (mnE, covE) <- sample $ smellyTransform (multiNormal mn cov) 1000 xform io $ print mnE io $ print covE main = runRIO $ do xyvs <- sample $ simDynamical 2000 f g procCov obsCov (fromList [0, 0.1]) --let xyvs = flip map xyvs' $ \(xv,yv) -> (xv,negate yv) -- pts <- sample $ sequence $ replicate 1000 $ lastSDESampler dt --w <- sample $ fmap (eulerMaruyama dt 0 a b) $ weiner dt 1 let xhats = unscentedKalmanFilterAdditive f' g' procCov obsCov (fromList [0,0], ((2><2) [1,0,0,1])) $ map snd xyvs let get s f = (s, Lines [] $ zip [(0::Double)..] $ map f xyvs) io $ gnuplotOnScreen $ get "y" ((@>1) . snd) :+: get "x" ((@>1) . fst) :+: ("xhat", Lines [] $ zip [(0::Double)..] $ map ((@>1) . fst) xhats) io $ print $ take 10 $ map snd xyvs testUT -- io $ gnuplotOnScreen $ get "x" ((@>1) . fst) -- io $ print $ runStat meanSDF $ pts
%default total test : (f : () -> Bool) -> f === (\x => True) -> f () = True test (\x => True) Refl = Refl
Earlier this year, our very first signature beer “Bex” was brewed using with a specialist Belgian yeast strain. During the brewing process, we niftily cropped enough yeast to nurture and use for another beer, and so in June our Production Director John decided to brew a 7.0% Belgian style Dubbel. This was then filled into seven of our Burgundy white oak barriques and left to age in our cold store. However, each of these barriques had some different ingredients added in to represent each of the deadly sins… Behold! Spiked with bourbon oak chips. Aroma of black forest gateaux and a glace cherry flavour. Dominant bourbon finish. Spiked with raw cacao nibs and vanilla. Delicate milk chocolate aroma. Rum ‘n' raisin fudge flavour. Full bodied with a beautifully silky chocolate finish. Spiked with fresh orange and ginger. Aromas of orange and hints of clove. Fairly tangy orange, almost cranberry flavour, with ginger fruitcake. Spiked with fresh raspberries and vanilla. Full-on raspberry aroma and flavour. Schnapps-like warmth at the end. Spiked with fresh ground coffee. Aromas of coffee & sweet walnut. Slight cream soda flavour with dried fig and apricot. Warm, dry finish. Spiked with vanilla and an extra dose of molasses. Oak smoke aroma with Rioja notes. Very more-ish sweet sherry flavour with subtle vanilla. Spiked with coriander seed. Fresh coriander aroma. Slight spicy cracked pepper flavour with fruit and nut pudding coming through on the finish. As well as this, we're also releasing an unadulterated version of the Dubbel base beer. Being free from Sin, this one is simply Heavenly! Who will try them all?! There are only 5 firkins of each Sin, so keep your eyes peeled!
{-# OPTIONS --cubical --no-import-sorts --safe #-} open import Cubical.Core.Everything open import Cubical.Relation.Binary.Raw module Cubical.Relation.Binary.Raw.Construct.StrictToNonStrict {a ℓ} {A : Type a} (_<_ : RawRel A ℓ) where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Data.Prod open import Cubical.Data.Sum.Base renaming (rec to ⊎-rec) open import Cubical.Data.Empty renaming (elim to ⊥-elim) using () open import Cubical.Relation.Binary.Raw.Properties open import Cubical.Relation.Nullary ------------------------------------------------------------------------ -- Conversion -- _<_ can be turned into _≤_ as follows: _≤_ : RawRel A _ x ≤ y = (x < y) ⊎ (x ≡ y) ------------------------------------------------------------------------ -- The converted relations have certain properties -- (if the original relations have certain other properties) ≤-isPropValued : isSet A → isPropValued _<_ → Irreflexive _<_ → isPropValued _≤_ ≤-isPropValued isSetA propv irrefl x y (inl p) (inl q) = cong inl (propv x y p q) ≤-isPropValued isSetA propv irrefl x y (inl p) (inr q) = ⊥-elim (irrefl→tonoteq _<_ irrefl p q) ≤-isPropValued isSetA propv irrefl x y (inr p) (inl q) = ⊥-elim (irrefl→tonoteq _<_ irrefl q p) ≤-isPropValued isSetA propv irrefl x y (inr p) (inr q) = cong inr (isSetA x y p q) <⇒≤ : _<_ ⇒ _≤_ <⇒≤ = inl ≤-fromEq : FromEq _≤_ ≤-fromEq = inr ≤-reflexive : Reflexive _≤_ ≤-reflexive = fromeq→reflx _≤_ ≤-fromEq ≤-antisym : Transitive _<_ → Irreflexive _<_ → Antisymmetric _≤_ ≤-antisym transitive irrefl (inl x<y) (inl y<x) = ⊥-elim (trans∧irr→asym _<_ transitive irrefl x<y y<x) ≤-antisym _ _ _ (inr y≡x) = sym y≡x ≤-antisym _ _ (inr x≡y) _ = x≡y ≤-transitive : Transitive _<_ → Transitive _≤_ ≤-transitive <-trans (inl x<y) (inl y<z) = inl $ <-trans x<y y<z ≤-transitive _ (inl x<y) (inr y≡z) = inl $ Respectsʳ≡ _<_ y≡z x<y ≤-transitive _ (inr x≡y) (inl y<z) = inl $ Respectsˡ≡ _<_ (sym x≡y) y<z ≤-transitive _ (inr x≡y) (inr y≡z) = inr $ x≡y ∙ y≡z <-≤-trans : Transitive _<_ → Trans _<_ _≤_ _<_ <-≤-trans transitive x<y (inl y<z) = transitive x<y y<z <-≤-trans transitive x<y (inr y≡z) = Respectsʳ≡ _<_ y≡z x<y ≤-<-trans : Transitive _<_ → Trans _≤_ _<_ _<_ ≤-<-trans transitive (inl x<y) y<z = transitive x<y y<z ≤-<-trans transitive (inr x≡y) y<z = Respectsˡ≡ _<_ (sym x≡y) y<z ≤-total : Trichotomous _<_ → Total _≤_ ≤-total <-tri x y with <-tri x y ... | tri< x<y x≢y x≯y = inl (inl x<y) ... | tri≡ x≮y x≡y x≯y = inl (inr x≡y) ... | tri> x≮y x≢y x>y = inr (inl x>y) ≤-decidable : Discrete A → Decidable _<_ → Decidable _≤_ ≤-decidable _≟_ _<?_ x y with x ≟ y ... | yes p = yes (inr p) ... | no ¬p with x <? y ... | yes q = yes (inl q) ... | no ¬q = no (⊎-rec ¬q ¬p) ≤-decidable′ : Trichotomous _<_ → Decidable _≤_ ≤-decidable′ compare x y with compare x y ... | tri< x<y _ _ = yes (inl x<y) ... | tri≡ _ x≡y _ = yes (inr x≡y) ... | tri> x≮y x≢y _ = no (⊎-rec x≮y x≢y) ------------------------------------------------------------------------ -- Converting structures isPreorder : Transitive _<_ → IsPreorder _≤_ isPreorder transitive = record { reflexive = ≤-reflexive ; transitive = ≤-transitive transitive } isPartialOrder : IsStrictPartialOrder _<_ → IsPartialOrder _≤_ isPartialOrder spo = record { isPreorder = isPreorder S.transitive ; antisym = ≤-antisym S.transitive S.irrefl } where module S = IsStrictPartialOrder spo isTotalOrder : IsStrictTotalOrder _<_ → IsTotalOrder _≤_ isTotalOrder sto = record { isPartialOrder = isPartialOrder S.isStrictPartialOrder ; total = λ x y → ∣ ≤-total S.compare x y ∣ } where module S = IsStrictTotalOrder sto isDecTotalOrder : IsStrictTotalOrder _<_ → IsDecTotalOrder _≤_ isDecTotalOrder sto = record { isTotalOrder = isTotalOrder sto ; _≤?_ = ≤-decidable′ S.compare } where module S = IsStrictTotalOrder sto
#include <cblas.h> #ifdef LAPACKE_FOLDER #include <lapacke/lapacke.h> #include <lapacke/lapacke_utils.h> #else #include <lapacke.h> #include <lapacke_utils.h> #endif #include "math.h" #include "stdbool.h" #include "stdio.h" #include "string.h" #include "sv_matrix.h" #include <limits.h> #include <stdarg.h> #include "linmath.h" #ifdef _WIN32 #define SURVIVE_LOCAL_ONLY #include <malloc.h> #define alloca _alloca #else #define SURVIVE_LOCAL_ONLY __attribute__((visibility("hidden"))) #endif #define SV_Error(code, msg) assert(0 && msg); // cv::error( code, msg, SV_Func, __FILE__, __LINE__ ) const int DECOMP_SVD = 1; const int DECOMP_LU = 2; void print_mat(const SvMat *M); static size_t mat_size_bytes(const SvMat *mat) { return (size_t)sizeof(FLT) * mat->cols * mat->rows; } #ifdef USE_FLOAT #define cblas_gemm cblas_sgemm #define cblas_symm cblas_ssymm #define LAPACKE_getrs LAPACKE_sgetrs #define LAPACKE_getrf LAPACKE_sgetrf #define LAPACKE_getri LAPACKE_sgetri #define LAPACKE_gelss LAPACKE_sgelss #define LAPACKE_gesvd LAPACKE_sgesvd #define LAPACKE_gesvd_work LAPACKE_sgesvd_work #define LAPACKE_getri_work LAPACKE_sgetri_work #define LAPACKE_ge_trans LAPACKE_sge_trans #else #define cblas_gemm cblas_dgemm #define cblas_symm cblas_dsymm #define LAPACKE_getrs LAPACKE_dgetrs #define LAPACKE_getrf LAPACKE_dgetrf #define LAPACKE_getri LAPACKE_dgetri #define LAPACKE_gelss LAPACKE_dgelss #define LAPACKE_gesvd LAPACKE_dgesvd #define LAPACKE_gesvd_work LAPACKE_dgesvd_work #define LAPACKE_getri_work LAPACKE_dgetri_work #define LAPACKE_ge_trans LAPACKE_dge_trans #endif // dst = alpha * src1 * src2 + beta * src3 or dst = alpha * src2 * src1 + beta * src3 where src1 is symm SURVIVE_LOCAL_ONLY void svSYMM(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta, SvMat *dst, bool src1First) { int rows1 = src1->rows; int cols1 = src1->cols; int rows2 = src2->rows; int cols2 = src2->cols; if (src3) { int rows3 = src3->rows; int cols3 = src3->cols; assert(rows3 == dst->rows); assert(cols3 == dst->cols); } // assert(src3 == 0 || beta != 0); assert(cols1 == rows2); assert(rows1 == dst->rows); assert(cols2 == dst->cols); lapack_int lda = src1->cols; lapack_int ldb = src2->cols; if (src3) svCopy(src3, dst, 0); else beta = 0; assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src1)); assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src2)); /* void cblas_dsymm(OPENBLAS_CONST enum CBLAS_ORDER Order, OPENBLAS_CONST enum CBLAS_SIDE Side, OPENBLAS_CONST enum CBLAS_UPLO Uplo, OPENBLAS_CONST blasint M, OPENBLAS_CONST blasint N, OPENBLAS_CONST double alpha, OPENBLAS_CONST double *A, OPENBLAS_CONST blasint lda, OPENBLAS_CONST double *B, OPENBLAS_CONST blasint ldb, OPENBLAS_CONST double beta, double *C, OPENBLAS_CONST blasint ldc); */ cblas_symm(CblasRowMajor, src1First ? CblasLeft : CblasRight, CblasUpper, dst->rows, dst->cols, alpha, SV_RAW_PTR(src1), lda, SV_RAW_PTR(src2), ldb, beta, SV_RAW_PTR(dst), dst->cols); } // Special case dst = alpha * src2 * src1 * src2' + beta * src3 void mulBABt(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta, SvMat *dst) { size_t dims = src2->rows; assert(src2->cols == src2->rows); SV_CREATE_STACK_MAT(tmp, dims, dims); // This has been profiled; and weirdly enough the SYMM version is slower for a 19x19 matrix. Guessing access order // or some other cache thing matters more than the additional 2x multiplications. //#define USE_SYM #ifdef USE_SYM svSYMM(src1, src2, 1, 0, 0, &tmp, false); svGEMM(&tmp, src2, alpha, src3, beta, dst, SV_GEMM_B_T); #else svGEMM(src1, src2, 1, 0, 0, &tmp, SV_GEMM_FLAG_B_T); svGEMM(src2, &tmp, alpha, src3, beta, dst, 0); #endif SV_FREE_STACK_MAT(tmp); } // dst = alpha * src1 * src2 + beta * src3 SURVIVE_LOCAL_ONLY void svGEMM(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta, SvMat *dst, enum svGEMMFlags tABC) { int rows1 = (tABC & SV_GEMM_FLAG_A_T) ? src1->cols : src1->rows; int cols1 = (tABC & SV_GEMM_FLAG_A_T) ? src1->rows : src1->cols; int rows2 = (tABC & SV_GEMM_FLAG_B_T) ? src2->cols : src2->rows; int cols2 = (tABC & SV_GEMM_FLAG_B_T) ? src2->rows : src2->cols; if (src3) { int rows3 = (tABC & SV_GEMM_FLAG_C_T) ? src3->cols : src3->rows; int cols3 = (tABC & SV_GEMM_FLAG_C_T) ? src3->rows : src3->cols; assert(rows3 == dst->rows); assert(cols3 == dst->cols); } // assert(src3 == 0 || beta != 0); assert(cols1 == rows2); assert(rows1 == dst->rows); assert(cols2 == dst->cols); lapack_int lda = src1->cols; lapack_int ldb = src2->cols; if (src3) svCopy(src3, dst, 0); else beta = 0; assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src1)); assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src2)); assert(dst->cols > 0); cblas_gemm(CblasRowMajor, (tABC & SV_GEMM_FLAG_A_T) ? CblasTrans : CblasNoTrans, (tABC & SV_GEMM_FLAG_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha, SV_RAW_PTR(src1), lda, SV_RAW_PTR(src2), ldb, beta, SV_RAW_PTR(dst), dst->cols); } // dst = scale * src ^ t * src iff order == 1 // dst = scale * src * src ^ t iff order == 0 SURVIVE_LOCAL_ONLY void svMulTransposed(const SvMat *src, SvMat *dst, int order, const SvMat *delta, double scale) { lapack_int rows = src->rows; lapack_int cols = src->cols; lapack_int drows = order == 0 ? dst->rows : dst->cols; assert(drows == dst->cols); assert(order == 1 ? (dst->cols == src->cols) : (dst->cols == src->rows)); assert(delta == 0 && "This isn't implemented yet"); double beta = 0; bool isAT = order == 1; bool isBT = !isAT; lapack_int dstCols = dst->cols; assert(dstCols > 0); cblas_gemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, order == 1 ? src->rows : src->cols, scale, SV_RAW_PTR(src), src->cols, SV_RAW_PTR(src), src->cols, beta, SV_RAW_PTR(dst), dstCols); } /* IEEE754 constants and macros */ #define SV_TOGGLE_FLT(x) ((x) ^ ((int)(x) < 0 ? 0x7fffffff : 0)) #define SV_TOGGLE_DBL(x) ((x) ^ ((int64)(x) < 0 ? SV_BIG_INT(0x7fffffffffffffff) : 0)) #define SV_DbgAssert assert #define SV_CREATE_MAT_HEADER_ALLOCA(stack_mat, rows, cols) \ SvMat *stack_mat = svInitMatHeader(SV_MATRIX_ALLOC(sizeof(SvMat)), rows, cols); #define SV_CREATE_MAT_ALLOCA(stack_mat, height, width) \ SV_CREATE_MAT_HEADER_ALLOCA(stack_mat, height, width); \ (stack_mat)->data = SV_MATRIX_ALLOC(mat_size_bytes(stack_mat)); #define SV_MAT_ALLOCA_FREE(stack_mat) \ { \ SV_MATRIX_FREE(stack_mat->data); \ SV_MATRIX_FREE(stack_mat); \ } #define CREATE_SV_STACK_MAT(name, rows, cols, type) \ FLT *_##name = alloca(rows * cols * sizeof(FLT)); \ SvMat name = svMat(rows, cols, _##name); static lapack_int LAPACKE_gesvd_static_alloc(int matrix_layout, char jobu, char jobvt, lapack_int m, lapack_int n, FLT *a, lapack_int lda, FLT *s, FLT *u, lapack_int ldu, FLT *vt, lapack_int ldvt, FLT *superb) { lapack_int info = 0; lapack_int lwork = -1; FLT *work = NULL; FLT work_query; lapack_int i; if (matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR) { LAPACKE_xerbla("LAPACKE_dgesvd", -1); return -1; } /* Query optimal working array(s) size */ info = LAPACKE_gesvd_work(matrix_layout, jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, &work_query, lwork); if (info != 0) { goto exit_level_0; } lwork = (lapack_int)work_query; /* Allocate memory for work arrays */ work = (FLT *)SV_MATRIX_ALLOC(sizeof(FLT) * lwork); memset(work, 0, sizeof(FLT) * lwork); if (work == NULL) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Call middle-level interface */ info = LAPACKE_gesvd_work(matrix_layout, jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork); /* Backup significant data from working array(s) */ for (i = 0; i < MIN(m, n) - 1; i++) { superb[i] = work[i + 1]; } SV_MATRIX_FREE(work); exit_level_0: if (info == LAPACK_WORK_MEMORY_ERROR) { LAPACKE_xerbla("LAPACKE_dgesvd", info); } return info; } static inline lapack_int LAPACKE_getri_static_alloc(int matrix_layout, lapack_int n, FLT *a, lapack_int lda, const lapack_int *ipiv) { lapack_int info = 0; lapack_int lwork = -1; FLT *work = NULL; FLT work_query; if (matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR) { LAPACKE_xerbla("LAPACKE_dgetri", -1); return -1; } /* Query optimal working array(s) size */ info = LAPACKE_getri_work(matrix_layout, n, a, lda, ipiv, &work_query, lwork); if (info != 0) { goto exit_level_0; } lwork = (lapack_int)work_query; /* Allocate memory for work arrays */ work = (FLT *)alloca(sizeof(FLT) * lwork); memset(work, 0, sizeof(FLT) * lwork); if (work == NULL) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Call middle-level interface */ info = LAPACKE_getri_work(matrix_layout, n, a, lda, ipiv, work, lwork); /* Release memory and exit */ exit_level_0: if (info == LAPACK_WORK_MEMORY_ERROR) { LAPACKE_xerbla("LAPACKE_dgetri", info); } return info; } SURVIVE_LOCAL_ONLY double svInvert(const SvMat *srcarr, SvMat *dstarr, enum svInvertMethod method) { lapack_int inf; lapack_int rows = srcarr->rows; lapack_int cols = srcarr->cols; lapack_int lda = srcarr->cols; svCopy(srcarr, dstarr, 0); FLT *a = SV_RAW_PTR(dstarr); #ifdef DEBUG_PRINT printf("a: \n"); print_mat(srcarr); #endif if (method == SV_INVERT_METHOD_LU) { lapack_int *ipiv = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols)); lapack_int lda_t = MAX(1, rows); FLT *a_t = (FLT *)SV_MATRIX_ALLOC(sizeof(FLT) * lda_t * MAX(1, cols)); LAPACKE_ge_trans(LAPACK_ROW_MAJOR, rows, cols, a, lda, a_t, lda_t); inf = LAPACKE_getrf(LAPACK_COL_MAJOR, rows, cols, a_t, lda, ipiv); assert(inf == 0); inf = LAPACKE_getri_static_alloc(LAPACK_COL_MAJOR, rows, a_t, lda, ipiv); assert(inf >= 0); LAPACKE_ge_trans(LAPACK_COL_MAJOR, rows, cols, a_t, lda, a, lda_t); if (inf > 0) { printf("Warning: Singular matrix: \n"); // print_mat(srcarr); } SV_MATRIX_FREE(a_t); SV_MATRIX_FREE(ipiv); // free(ipiv); } else if (method == DECOMP_SVD) { // TODO: There is no way this needs this many allocations, // but in my defense I was very tired when I wrote this code SV_CREATE_STACK_MAT(w, 1, MIN(dstarr->rows, dstarr->cols)); SV_CREATE_STACK_MAT(u, dstarr->cols, dstarr->cols); SV_CREATE_STACK_MAT(v, dstarr->rows, dstarr->rows); SV_CREATE_STACK_MAT(um, w.cols, w.cols); svSVD(dstarr, &w, &u, &v, 0); svSetZero(&um); for (int i = 0; i < w.cols; i++) { if (_w[i] != 0.0) svMatrixSet(&um, i, i, 1. / (_w)[i]); } SvMat *tmp = svCreateMat(dstarr->cols, dstarr->rows); svGEMM(&v, &um, 1, 0, 0, tmp, SV_GEMM_FLAG_A_T); svGEMM(tmp, &u, 1, 0, 0, dstarr, SV_GEMM_FLAG_B_T); svReleaseMat(&tmp); SV_FREE_STACK_MAT(um); SV_FREE_STACK_MAT(v); SV_FREE_STACK_MAT(u); SV_FREE_STACK_MAT(w); } else { assert(0 && "Bad argument"); return -1; } return 0; } #define SV_CLONE_MAT_ALLOCA(stack_mat, mat) \ SV_CREATE_MAT_ALLOCA(stack_mat, mat->rows, mat->cols) \ svCopy(mat, stack_mat, 0); static int svSolve_LU(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr) { lapack_int inf; lapack_int arows = Aarr->rows; lapack_int acols = Aarr->cols; lapack_int xcols = Barr->cols; lapack_int xrows = Barr->rows; lapack_int lda = acols; // Aarr->step / sizeof(double); assert(Aarr->cols == xarr->rows); assert(Barr->rows == Aarr->rows); assert(xarr->cols == Barr->cols); svCopy(Barr, xarr, 0); FLT *a_ws = SV_MATRIX_ALLOC(mat_size_bytes(Aarr)); memcpy(a_ws, SV_RAW_PTR(Aarr), mat_size_bytes(Aarr)); lapack_int brows = xarr->rows; lapack_int bcols = xarr->cols; lapack_int ldb = bcols; // Barr->step / sizeof(double); lapack_int *ipiv = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols)); inf = LAPACKE_getrf(LAPACK_ROW_MAJOR, arows, acols, (a_ws), lda, ipiv); assert(inf >= 0); if (inf > 0) { printf("Warning: Singular matrix: \n"); // print_mat(a_ws); } #ifdef DEBUG_PRINT printf("Solve A * x = B:\n"); // print_mat(a_ws); print_mat(Barr); #endif inf = LAPACKE_getrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, (a_ws), lda, ipiv, SV_RAW_PTR(xarr), ldb); assert(inf == 0); SV_MATRIX_FREE(a_ws); SV_MATRIX_FREE(ipiv); return 0; } static inline int svSolve_SVD(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr) { lapack_int arows = Aarr->rows; lapack_int acols = Aarr->cols; lapack_int xcols = Barr->cols; bool xLargerThanB = Barr->rows > acols; SvMat *xCpy = 0; if (xLargerThanB) { SV_CLONE_MAT_ALLOCA(xCpyStack, Barr); xCpy = xCpyStack; } else { xCpy = xarr; memcpy(SV_RAW_PTR(xarr), SV_RAW_PTR(Barr), mat_size_bytes(Barr)); } // SvMat *aCpy = svCloneMat(Aarr); FLT *aCpy = SV_MATRIX_ALLOC(mat_size_bytes(Aarr)); memcpy(aCpy, SV_RAW_PTR(Aarr), mat_size_bytes(Aarr)); FLT *S = SV_MATRIX_ALLOC(sizeof(FLT) * MIN(arows, acols)); // FLT *S = malloc(sizeof(FLT) * MIN(arows, acols)); FLT rcond = -1; lapack_int *rank = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(arows, acols)); lapack_int inf = LAPACKE_gelss(LAPACK_ROW_MAJOR, arows, acols, xcols, (aCpy), acols, SV_RAW_PTR(xCpy), xcols, S, rcond, rank); assert(xarr->rows == acols); assert(xarr->cols == xCpy->cols); if (xLargerThanB) { xCpy->rows = acols; svCopy(xCpy, xarr, 0); // svReleaseMat(&xCpy); } SV_MATRIX_FREE(rank); SV_MATRIX_FREE(aCpy); SV_MATRIX_FREE(S); if (xLargerThanB) { SV_MAT_ALLOCA_FREE(xCpy); } assert(inf == 0); if (inf != 0) return inf; return 0; } SURVIVE_LOCAL_ONLY int svSolve(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr, enum svInvertMethod method) { if (method == SV_INVERT_METHOD_LU) { return svSolve_LU(Aarr, Barr, xarr); } else if (method == SV_INVERT_METHOD_SVD || method == SV_INVERT_METHOD_QR) { return svSolve_SVD(Aarr, Barr, xarr); } else { assert("Unknown method to solve" && 0); } return -1; } SURVIVE_LOCAL_ONLY void svTranspose(const SvMat *M, SvMat *dst) { bool inPlace = M == dst || SV_RAW_PTR(M) == SV_RAW_PTR(dst); FLT *src = SV_RAW_PTR(M); if (inPlace) { src = alloca(mat_size_bytes(M)); memcpy(src, SV_RAW_PTR(M), mat_size_bytes(M)); } else { assert(M->rows == dst->cols); assert(M->cols == dst->rows); } for (unsigned i = 0; i < M->rows; i++) { for (unsigned j = 0; j < M->cols; j++) { SV_RAW_PTR(dst)[j * M->rows + i] = src[i * M->cols + j]; } } } #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define MEMORY_SANITIZER_IGNORE __attribute__((no_sanitize("memory"))) #endif #endif #ifndef MEMORY_SANITIZER_IGNORE #define MEMORY_SANITIZER_IGNORE #endif #define CALLOCA(size) memset(alloca(size), 0, size) SURVIVE_LOCAL_ONLY void svSVD(SvMat *aarr, SvMat *warr, SvMat *uarr, SvMat *varr, enum svSVDFlags flags) { char jobu = 'A'; char jobvt = 'A'; lapack_int inf; if ((flags & SV_SVD_MODIFY_A) == 0) { aarr = svCloneMat(aarr); } if (uarr == 0) jobu = 'N'; if (varr == 0) jobvt = 'N'; lapack_int arows = aarr->rows, acols = aarr->cols; FLT *pw = warr ? SV_RAW_PTR(warr) : (FLT *)CALLOCA(sizeof(FLT) * arows * acols); FLT *pu = uarr ? SV_RAW_PTR(uarr) : (FLT *)CALLOCA(sizeof(FLT) * arows * arows); FLT *pv = varr ? SV_RAW_PTR(varr) : (FLT *)CALLOCA(sizeof(FLT) * acols * acols); lapack_int ulda = uarr ? uarr->cols : acols; lapack_int plda = varr ? varr->cols : acols; FLT *superb = CALLOCA(sizeof(FLT) * MIN(arows, acols)); inf = LAPACKE_gesvd_static_alloc(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, SV_RAW_PTR(aarr), acols, pw, pu, ulda, pv, plda, superb); switch (inf) { case -6: assert(false && "matrix has NaNs"); break; case 0: break; default: assert(inf == 0); } if (uarr && (flags & SV_SVD_U_T)) { svTranspose(uarr, uarr); } if (varr && (flags & SV_SVD_V_T) == 0) { svTranspose(varr, varr); } if ((flags & SV_SVD_MODIFY_A) == 0) { svReleaseMat(&aarr); } } SURVIVE_LOCAL_ONLY double svDet(const SvMat *M) { assert(M->rows == M->cols); assert(M->rows <= 3 && "svDet unimplemented for matrices >3"); FLT *m = SV_RAW_PTR(M); switch (M->rows) { case 1: return m[0]; case 2: { return m[0] * m[3] - m[1] * m[2]; } case 3: { FLT m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7], m22 = m[8]; return m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20); } default: abort(); } }
Formal statement is: lemma continuous_within: "continuous (at x within s) f \<longleftrightarrow> (f \<longlongrightarrow> f x) (at x within s)" Informal statement is: A function $f$ is continuous at $x$ within $S$ if and only if the limit of $f$ at $x$ within $S$ exists and is equal to $f(x)$.
FUNCTION GAUSS(X,X0,SIGMA) c Returns value of gaussian function normalized to area = 1 c Normalization constant data a/0./ if (a.eq.0) then pi=4.*atan(1.) a=1./sqrt(2.*pi) endif c=a/sigma gauss=c*exp(-(x-x0)**2/sigma**2/2) ! write (998,*) x,x0,a,sigma,c return end
= = Music video and live performances = =
= = = Writing and power = = =