src/HOL/Probability/Probability_Mass_Function.thy
author hoelzl
Tue Nov 25 17:30:05 2014 +0100 (2014-11-25)
changeset 59053 43e07797269b
parent 59052 a05c8305781e
child 59092 d469103c0737
permissions -rw-r--r--
tuned proof that pmfs are bnfs
     1 (*  Title:      HOL/Probability/Probability_Mass_Function.thy
     2     Author:     Johannes Hölzl, TU München 
     3     Author:     Andreas Lochbihler, ETH Zurich
     4 *)
     5 
     6 section \<open> Probability mass function \<close>
     7 
     8 theory Probability_Mass_Function
     9 imports
    10   Giry_Monad
    11   "~~/src/HOL/Library/Multiset"
    12 begin
    13 
    14 lemma bind_return'': "sets M = sets N \<Longrightarrow> M \<guillemotright>= return N = M"
    15    by (cases "space M = {}")
    16       (simp_all add: bind_empty space_empty[symmetric] bind_nonempty join_return'
    17                 cong: subprob_algebra_cong)
    18 
    19 
    20 lemma (in prob_space) distr_const[simp]:
    21   "c \<in> space N \<Longrightarrow> distr M N (\<lambda>x. c) = return N c"
    22   by (rule measure_eqI) (auto simp: emeasure_distr emeasure_space_1)
    23 
    24 lemma (in finite_measure) countable_support:
    25   "countable {x. measure M {x} \<noteq> 0}"
    26 proof cases
    27   assume "measure M (space M) = 0"
    28   with bounded_measure measure_le_0_iff have "{x. measure M {x} \<noteq> 0} = {}"
    29     by auto
    30   then show ?thesis
    31     by simp
    32 next
    33   let ?M = "measure M (space M)" and ?m = "\<lambda>x. measure M {x}"
    34   assume "?M \<noteq> 0"
    35   then have *: "{x. ?m x \<noteq> 0} = (\<Union>n. {x. ?M / Suc n < ?m x})"
    36     using reals_Archimedean[of "?m x / ?M" for x]
    37     by (auto simp: field_simps not_le[symmetric] measure_nonneg divide_le_0_iff measure_le_0_iff)
    38   have **: "\<And>n. finite {x. ?M / Suc n < ?m x}"
    39   proof (rule ccontr)
    40     fix n assume "infinite {x. ?M / Suc n < ?m x}" (is "infinite ?X")
    41     then obtain X where "finite X" "card X = Suc (Suc n)" "X \<subseteq> ?X"
    42       by (metis infinite_arbitrarily_large)
    43     from this(3) have *: "\<And>x. x \<in> X \<Longrightarrow> ?M / Suc n \<le> ?m x" 
    44       by auto
    45     { fix x assume "x \<in> X"
    46       from `?M \<noteq> 0` *[OF this] have "?m x \<noteq> 0" by (auto simp: field_simps measure_le_0_iff)
    47       then have "{x} \<in> sets M" by (auto dest: measure_notin_sets) }
    48     note singleton_sets = this
    49     have "?M < (\<Sum>x\<in>X. ?M / Suc n)"
    50       using `?M \<noteq> 0` 
    51       by (simp add: `card X = Suc (Suc n)` real_eq_of_nat[symmetric] real_of_nat_Suc field_simps less_le measure_nonneg)
    52     also have "\<dots> \<le> (\<Sum>x\<in>X. ?m x)"
    53       by (rule setsum_mono) fact
    54     also have "\<dots> = measure M (\<Union>x\<in>X. {x})"
    55       using singleton_sets `finite X`
    56       by (intro finite_measure_finite_Union[symmetric]) (auto simp: disjoint_family_on_def)
    57     finally have "?M < measure M (\<Union>x\<in>X. {x})" .
    58     moreover have "measure M (\<Union>x\<in>X. {x}) \<le> ?M"
    59       using singleton_sets[THEN sets.sets_into_space] by (intro finite_measure_mono) auto
    60     ultimately show False by simp
    61   qed
    62   show ?thesis
    63     unfolding * by (intro countable_UN countableI_type countable_finite[OF **])
    64 qed
    65 
    66 lemma (in finite_measure) AE_support_countable:
    67   assumes [simp]: "sets M = UNIV"
    68   shows "(AE x in M. measure M {x} \<noteq> 0) \<longleftrightarrow> (\<exists>S. countable S \<and> (AE x in M. x \<in> S))"
    69 proof
    70   assume "\<exists>S. countable S \<and> (AE x in M. x \<in> S)"
    71   then obtain S where S[intro]: "countable S" and ae: "AE x in M. x \<in> S"
    72     by auto
    73   then have "emeasure M (\<Union>x\<in>{x\<in>S. emeasure M {x} \<noteq> 0}. {x}) = 
    74     (\<integral>\<^sup>+ x. emeasure M {x} * indicator {x\<in>S. emeasure M {x} \<noteq> 0} x \<partial>count_space UNIV)"
    75     by (subst emeasure_UN_countable)
    76        (auto simp: disjoint_family_on_def nn_integral_restrict_space[symmetric] restrict_count_space)
    77   also have "\<dots> = (\<integral>\<^sup>+ x. emeasure M {x} * indicator S x \<partial>count_space UNIV)"
    78     by (auto intro!: nn_integral_cong split: split_indicator)
    79   also have "\<dots> = emeasure M (\<Union>x\<in>S. {x})"
    80     by (subst emeasure_UN_countable)
    81        (auto simp: disjoint_family_on_def nn_integral_restrict_space[symmetric] restrict_count_space)
    82   also have "\<dots> = emeasure M (space M)"
    83     using ae by (intro emeasure_eq_AE) auto
    84   finally have "emeasure M {x \<in> space M. x\<in>S \<and> emeasure M {x} \<noteq> 0} = emeasure M (space M)"
    85     by (simp add: emeasure_single_in_space cong: rev_conj_cong)
    86   with finite_measure_compl[of "{x \<in> space M. x\<in>S \<and> emeasure M {x} \<noteq> 0}"]
    87   have "AE x in M. x \<in> S \<and> emeasure M {x} \<noteq> 0"
    88     by (intro AE_I[OF order_refl]) (auto simp: emeasure_eq_measure set_diff_eq cong: conj_cong)
    89   then show "AE x in M. measure M {x} \<noteq> 0"
    90     by (auto simp: emeasure_eq_measure)
    91 qed (auto intro!: exI[of _ "{x. measure M {x} \<noteq> 0}"] countable_support)
    92 
    93 subsection {* PMF as measure *}
    94 
    95 typedef 'a pmf = "{M :: 'a measure. prob_space M \<and> sets M = UNIV \<and> (AE x in M. measure M {x} \<noteq> 0)}"
    96   morphisms measure_pmf Abs_pmf
    97   by (intro exI[of _ "uniform_measure (count_space UNIV) {undefined}"])
    98      (auto intro!: prob_space_uniform_measure AE_uniform_measureI)
    99 
   100 declare [[coercion measure_pmf]]
   101 
   102 lemma prob_space_measure_pmf: "prob_space (measure_pmf p)"
   103   using pmf.measure_pmf[of p] by auto
   104 
   105 interpretation measure_pmf!: prob_space "measure_pmf M" for M
   106   by (rule prob_space_measure_pmf)
   107 
   108 interpretation measure_pmf!: subprob_space "measure_pmf M" for M
   109   by (rule prob_space_imp_subprob_space) unfold_locales
   110 
   111 lemma subprob_space_measure_pmf: "subprob_space (measure_pmf x)"
   112   by unfold_locales
   113 
   114 locale pmf_as_measure
   115 begin
   116 
   117 setup_lifting type_definition_pmf
   118 
   119 end
   120 
   121 context
   122 begin
   123 
   124 interpretation pmf_as_measure .
   125 
   126 lift_definition pmf :: "'a pmf \<Rightarrow> 'a \<Rightarrow> real" is "\<lambda>M x. measure M {x}" .
   127 
   128 lift_definition set_pmf :: "'a pmf \<Rightarrow> 'a set" is "\<lambda>M. {x. measure M {x} \<noteq> 0}" .
   129 
   130 lift_definition map_pmf :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a pmf \<Rightarrow> 'b pmf" is
   131   "\<lambda>f M. distr M (count_space UNIV) f"
   132 proof safe
   133   fix M and f :: "'a \<Rightarrow> 'b"
   134   let ?D = "distr M (count_space UNIV) f"
   135   assume "prob_space M" and [simp]: "sets M = UNIV" and ae: "AE x in M. measure M {x} \<noteq> 0"
   136   interpret prob_space M by fact
   137   from ae have "AE x in M. measure M (f -` {f x}) \<noteq> 0"
   138   proof eventually_elim
   139     fix x
   140     have "measure M {x} \<le> measure M (f -` {f x})"
   141       by (intro finite_measure_mono) auto
   142     then show "measure M {x} \<noteq> 0 \<Longrightarrow> measure M (f -` {f x}) \<noteq> 0"
   143       using measure_nonneg[of M "{x}"] by auto
   144   qed
   145   then show "AE x in ?D. measure ?D {x} \<noteq> 0"
   146     by (simp add: AE_distr_iff measure_distr measurable_def)
   147 qed (auto simp: measurable_def prob_space.prob_space_distr)
   148 
   149 declare [[coercion set_pmf]]
   150 
   151 lemma countable_set_pmf [simp]: "countable (set_pmf p)"
   152   by transfer (metis prob_space.finite_measure finite_measure.countable_support)
   153 
   154 lemma sets_measure_pmf[simp]: "sets (measure_pmf p) = UNIV"
   155   by transfer metis
   156 
   157 lemma sets_measure_pmf_count_space[measurable_cong]:
   158   "sets (measure_pmf M) = sets (count_space UNIV)"
   159   by simp
   160 
   161 lemma space_measure_pmf[simp]: "space (measure_pmf p) = UNIV"
   162   using sets_eq_imp_space_eq[of "measure_pmf p" "count_space UNIV"] by simp
   163 
   164 lemma measure_pmf_in_subprob_algebra[measurable (raw)]: "measure_pmf x \<in> space (subprob_algebra (count_space UNIV))"
   165   by (simp add: space_subprob_algebra subprob_space_measure_pmf)
   166 
   167 lemma measurable_pmf_measure1[simp]: "measurable (M :: 'a pmf) N = UNIV \<rightarrow> space N"
   168   by (auto simp: measurable_def)
   169 
   170 lemma measurable_pmf_measure2[simp]: "measurable N (M :: 'a pmf) = measurable N (count_space UNIV)"
   171   by (intro measurable_cong_sets) simp_all
   172 
   173 lemma pmf_positive: "x \<in> set_pmf p \<Longrightarrow> 0 < pmf p x"
   174   by transfer (simp add: less_le measure_nonneg)
   175 
   176 lemma pmf_nonneg: "0 \<le> pmf p x"
   177   by transfer (simp add: measure_nonneg)
   178 
   179 lemma pmf_le_1: "pmf p x \<le> 1"
   180   by (simp add: pmf.rep_eq)
   181 
   182 lemma emeasure_pmf_single:
   183   fixes M :: "'a pmf"
   184   shows "emeasure M {x} = pmf M x"
   185   by transfer (simp add: finite_measure.emeasure_eq_measure[OF prob_space.finite_measure])
   186 
   187 lemma AE_measure_pmf: "AE x in (M::'a pmf). x \<in> M"
   188   by transfer simp
   189 
   190 lemma emeasure_pmf_single_eq_zero_iff:
   191   fixes M :: "'a pmf"
   192   shows "emeasure M {y} = 0 \<longleftrightarrow> y \<notin> M"
   193   by transfer (simp add: finite_measure.emeasure_eq_measure[OF prob_space.finite_measure])
   194 
   195 lemma AE_measure_pmf_iff: "(AE x in measure_pmf M. P x) \<longleftrightarrow> (\<forall>y\<in>M. P y)"
   196 proof -
   197   { fix y assume y: "y \<in> M" and P: "AE x in M. P x" "\<not> P y"
   198     with P have "AE x in M. x \<noteq> y"
   199       by auto
   200     with y have False
   201       by (simp add: emeasure_pmf_single_eq_zero_iff AE_iff_measurable[OF _ refl]) }
   202   then show ?thesis
   203     using AE_measure_pmf[of M] by auto
   204 qed
   205 
   206 lemma set_pmf_not_empty: "set_pmf M \<noteq> {}"
   207   using AE_measure_pmf[of M] by (intro notI) simp
   208 
   209 lemma set_pmf_iff: "x \<in> set_pmf M \<longleftrightarrow> pmf M x \<noteq> 0"
   210   by transfer simp
   211 
   212 lemma emeasure_measure_pmf_finite: "finite S \<Longrightarrow> emeasure (measure_pmf M) S = (\<Sum>s\<in>S. pmf M s)"
   213   by (subst emeasure_eq_setsum_singleton) (auto simp: emeasure_pmf_single)
   214 
   215 lemma measure_measure_pmf_finite: "finite S \<Longrightarrow> measure (measure_pmf M) S = setsum (pmf M) S"
   216 using emeasure_measure_pmf_finite[of S M]
   217 by(simp add: measure_pmf.emeasure_eq_measure)
   218 
   219 lemma nn_integral_measure_pmf_support:
   220   fixes f :: "'a \<Rightarrow> ereal"
   221   assumes f: "finite A" and nn: "\<And>x. x \<in> A \<Longrightarrow> 0 \<le> f x" "\<And>x. x \<in> set_pmf M \<Longrightarrow> x \<notin> A \<Longrightarrow> f x = 0"
   222   shows "(\<integral>\<^sup>+x. f x \<partial>measure_pmf M) = (\<Sum>x\<in>A. f x * pmf M x)"
   223 proof -
   224   have "(\<integral>\<^sup>+x. f x \<partial>M) = (\<integral>\<^sup>+x. f x * indicator A x \<partial>M)"
   225     using nn by (intro nn_integral_cong_AE) (auto simp: AE_measure_pmf_iff split: split_indicator)
   226   also have "\<dots> = (\<Sum>x\<in>A. f x * emeasure M {x})"
   227     using assms by (intro nn_integral_indicator_finite) auto
   228   finally show ?thesis
   229     by (simp add: emeasure_measure_pmf_finite)
   230 qed
   231 
   232 lemma nn_integral_measure_pmf_finite:
   233   fixes f :: "'a \<Rightarrow> ereal"
   234   assumes f: "finite (set_pmf M)" and nn: "\<And>x. x \<in> set_pmf M \<Longrightarrow> 0 \<le> f x"
   235   shows "(\<integral>\<^sup>+x. f x \<partial>measure_pmf M) = (\<Sum>x\<in>set_pmf M. f x * pmf M x)"
   236   using assms by (intro nn_integral_measure_pmf_support) auto
   237 lemma integrable_measure_pmf_finite:
   238   fixes f :: "'a \<Rightarrow> 'b::{banach, second_countable_topology}"
   239   shows "finite (set_pmf M) \<Longrightarrow> integrable M f"
   240   by (auto intro!: integrableI_bounded simp: nn_integral_measure_pmf_finite)
   241 
   242 lemma integral_measure_pmf:
   243   assumes [simp]: "finite A" and "\<And>a. a \<in> set_pmf M \<Longrightarrow> f a \<noteq> 0 \<Longrightarrow> a \<in> A"
   244   shows "(\<integral>x. f x \<partial>measure_pmf M) = (\<Sum>a\<in>A. f a * pmf M a)"
   245 proof -
   246   have "(\<integral>x. f x \<partial>measure_pmf M) = (\<integral>x. f x * indicator A x \<partial>measure_pmf M)"
   247     using assms(2) by (intro integral_cong_AE) (auto split: split_indicator simp: AE_measure_pmf_iff)
   248   also have "\<dots> = (\<Sum>a\<in>A. f a * pmf M a)"
   249     by (subst integral_indicator_finite_real) (auto simp: measure_def emeasure_measure_pmf_finite)
   250   finally show ?thesis .
   251 qed
   252 
   253 lemma integrable_pmf: "integrable (count_space X) (pmf M)"
   254 proof -
   255   have " (\<integral>\<^sup>+ x. pmf M x \<partial>count_space X) = (\<integral>\<^sup>+ x. pmf M x \<partial>count_space (M \<inter> X))"
   256     by (auto simp add: nn_integral_count_space_indicator set_pmf_iff intro!: nn_integral_cong split: split_indicator)
   257   then have "integrable (count_space X) (pmf M) = integrable (count_space (M \<inter> X)) (pmf M)"
   258     by (simp add: integrable_iff_bounded pmf_nonneg)
   259   then show ?thesis
   260     by (simp add: pmf.rep_eq measure_pmf.integrable_measure disjoint_family_on_def)
   261 qed
   262 
   263 lemma integral_pmf: "(\<integral>x. pmf M x \<partial>count_space X) = measure M X"
   264 proof -
   265   have "(\<integral>x. pmf M x \<partial>count_space X) = (\<integral>\<^sup>+x. pmf M x \<partial>count_space X)"
   266     by (simp add: pmf_nonneg integrable_pmf nn_integral_eq_integral)
   267   also have "\<dots> = (\<integral>\<^sup>+x. emeasure M {x} \<partial>count_space (X \<inter> M))"
   268     by (auto intro!: nn_integral_cong_AE split: split_indicator
   269              simp: pmf.rep_eq measure_pmf.emeasure_eq_measure nn_integral_count_space_indicator
   270                    AE_count_space set_pmf_iff)
   271   also have "\<dots> = emeasure M (X \<inter> M)"
   272     by (rule emeasure_countable_singleton[symmetric]) (auto intro: countable_set_pmf)
   273   also have "\<dots> = emeasure M X"
   274     by (auto intro!: emeasure_eq_AE simp: AE_measure_pmf_iff)
   275   finally show ?thesis
   276     by (simp add: measure_pmf.emeasure_eq_measure)
   277 qed
   278 
   279 lemma integral_pmf_restrict:
   280   "(f::'a \<Rightarrow> 'b::{banach, second_countable_topology}) \<in> borel_measurable (count_space UNIV) \<Longrightarrow>
   281     (\<integral>x. f x \<partial>measure_pmf M) = (\<integral>x. f x \<partial>restrict_space M M)"
   282   by (auto intro!: integral_cong_AE simp add: integral_restrict_space AE_measure_pmf_iff)
   283 
   284 lemma emeasure_pmf: "emeasure (M::'a pmf) M = 1"
   285 proof -
   286   have "emeasure (M::'a pmf) M = emeasure (M::'a pmf) (space M)"
   287     by (intro emeasure_eq_AE) (simp_all add: AE_measure_pmf)
   288   then show ?thesis
   289     using measure_pmf.emeasure_space_1 by simp
   290 qed
   291 
   292 lemma in_null_sets_measure_pmfI:
   293   "A \<inter> set_pmf p = {} \<Longrightarrow> A \<in> null_sets (measure_pmf p)"
   294 using emeasure_eq_0_AE[where ?P="\<lambda>x. x \<in> A" and M="measure_pmf p"]
   295 by(auto simp add: null_sets_def AE_measure_pmf_iff)
   296 
   297 lemma map_pmf_id[simp]: "map_pmf id = id"
   298   by (rule, transfer) (auto simp: emeasure_distr measurable_def intro!: measure_eqI)
   299 
   300 lemma map_pmf_ident[simp]: "map_pmf (\<lambda>x. x) = (\<lambda>x. x)"
   301   using map_pmf_id unfolding id_def .
   302 
   303 lemma map_pmf_compose: "map_pmf (f \<circ> g) = map_pmf f \<circ> map_pmf g"
   304   by (rule, transfer) (simp add: distr_distr[symmetric, where N="count_space UNIV"] measurable_def) 
   305 
   306 lemma map_pmf_comp: "map_pmf f (map_pmf g M) = map_pmf (\<lambda>x. f (g x)) M"
   307   using map_pmf_compose[of f g] by (simp add: comp_def)
   308 
   309 lemma map_pmf_cong:
   310   assumes "p = q"
   311   shows "(\<And>x. x \<in> set_pmf q \<Longrightarrow> f x = g x) \<Longrightarrow> map_pmf f p = map_pmf g q"
   312   unfolding `p = q`[symmetric] measure_pmf_inject[symmetric] map_pmf.rep_eq
   313   by (auto simp add: emeasure_distr AE_measure_pmf_iff intro!: emeasure_eq_AE measure_eqI)
   314 
   315 lemma emeasure_map_pmf[simp]: "emeasure (map_pmf f M) X = emeasure M (f -` X)"
   316   unfolding map_pmf.rep_eq by (subst emeasure_distr) auto
   317 
   318 lemma nn_integral_map_pmf[simp]: "(\<integral>\<^sup>+x. f x \<partial>map_pmf g M) = (\<integral>\<^sup>+x. f (g x) \<partial>M)"
   319   unfolding map_pmf.rep_eq by (intro nn_integral_distr) auto
   320 
   321 lemma ereal_pmf_map: "pmf (map_pmf f p) x = (\<integral>\<^sup>+ y. indicator (f -` {x}) y \<partial>measure_pmf p)"
   322 proof(transfer fixing: f x)
   323   fix p :: "'b measure"
   324   presume "prob_space p"
   325   then interpret prob_space p .
   326   presume "sets p = UNIV"
   327   then show "ereal (measure (distr p (count_space UNIV) f) {x}) = integral\<^sup>N p (indicator (f -` {x}))"
   328     by(simp add: measure_distr measurable_def emeasure_eq_measure)
   329 qed simp_all
   330 
   331 lemma pmf_set_map: 
   332   fixes f :: "'a \<Rightarrow> 'b"
   333   shows "set_pmf \<circ> map_pmf f = op ` f \<circ> set_pmf"
   334 proof (rule, transfer, clarsimp simp add: measure_distr measurable_def)
   335   fix f :: "'a \<Rightarrow> 'b" and M :: "'a measure"
   336   assume "prob_space M" and ae: "AE x in M. measure M {x} \<noteq> 0" and [simp]: "sets M = UNIV"
   337   interpret prob_space M by fact
   338   show "{x. measure M (f -` {x}) \<noteq> 0} = f ` {x. measure M {x} \<noteq> 0}"
   339   proof safe
   340     fix x assume "measure M (f -` {x}) \<noteq> 0"
   341     moreover have "measure M (f -` {x}) = measure M {y. f y = x \<and> measure M {y} \<noteq> 0}"
   342       using ae by (intro finite_measure_eq_AE) auto
   343     ultimately have "{y. f y = x \<and> measure M {y} \<noteq> 0} \<noteq> {}"
   344       by (metis measure_empty)
   345     then show "x \<in> f ` {x. measure M {x} \<noteq> 0}"
   346       by auto
   347   next
   348     fix x assume "measure M {x} \<noteq> 0"
   349     then have "0 < measure M {x}"
   350       using measure_nonneg[of M "{x}"] by auto
   351     also have "measure M {x} \<le> measure M (f -` {f x})"
   352       by (intro finite_measure_mono) auto
   353     finally show "measure M (f -` {f x}) = 0 \<Longrightarrow> False"
   354       by simp
   355   qed
   356 qed
   357 
   358 lemma set_map_pmf: "set_pmf (map_pmf f M) = f`set_pmf M"
   359   using pmf_set_map[of f] by (auto simp: comp_def fun_eq_iff)
   360 
   361 lemma nn_integral_pmf: "(\<integral>\<^sup>+ x. pmf p x \<partial>count_space A) = emeasure (measure_pmf p) A"
   362 proof -
   363   have "(\<integral>\<^sup>+ x. pmf p x \<partial>count_space A) = (\<integral>\<^sup>+ x. pmf p x \<partial>count_space (A \<inter> set_pmf p))"
   364     by(auto simp add: nn_integral_count_space_indicator indicator_def set_pmf_iff intro: nn_integral_cong)
   365   also have "\<dots> = emeasure (measure_pmf p) (\<Union>x\<in>A \<inter> set_pmf p. {x})"
   366     by(subst emeasure_UN_countable)(auto simp add: emeasure_pmf_single disjoint_family_on_def)
   367   also have "\<dots> = emeasure (measure_pmf p) ((\<Union>x\<in>A \<inter> set_pmf p. {x}) \<union> {x. x \<in> A \<and> x \<notin> set_pmf p})"
   368     by(rule emeasure_Un_null_set[symmetric])(auto intro: in_null_sets_measure_pmfI)
   369   also have "\<dots> = emeasure (measure_pmf p) A"
   370     by(auto intro: arg_cong2[where f=emeasure])
   371   finally show ?thesis .
   372 qed
   373 
   374 subsection {* PMFs as function *}
   375 
   376 context
   377   fixes f :: "'a \<Rightarrow> real"
   378   assumes nonneg: "\<And>x. 0 \<le> f x"
   379   assumes prob: "(\<integral>\<^sup>+x. f x \<partial>count_space UNIV) = 1"
   380 begin
   381 
   382 lift_definition embed_pmf :: "'a pmf" is "density (count_space UNIV) (ereal \<circ> f)"
   383 proof (intro conjI)
   384   have *[simp]: "\<And>x y. ereal (f y) * indicator {x} y = ereal (f x) * indicator {x} y"
   385     by (simp split: split_indicator)
   386   show "AE x in density (count_space UNIV) (ereal \<circ> f).
   387     measure (density (count_space UNIV) (ereal \<circ> f)) {x} \<noteq> 0"
   388     by (simp add: AE_density nonneg emeasure_density measure_def nn_integral_cmult_indicator)
   389   show "prob_space (density (count_space UNIV) (ereal \<circ> f))"
   390     by default (simp add: emeasure_density prob)
   391 qed simp
   392 
   393 lemma pmf_embed_pmf: "pmf embed_pmf x = f x"
   394 proof transfer
   395   have *[simp]: "\<And>x y. ereal (f y) * indicator {x} y = ereal (f x) * indicator {x} y"
   396     by (simp split: split_indicator)
   397   fix x show "measure (density (count_space UNIV) (ereal \<circ> f)) {x} = f x"
   398     by transfer (simp add: measure_def emeasure_density nn_integral_cmult_indicator nonneg)
   399 qed
   400 
   401 end
   402 
   403 lemma embed_pmf_transfer:
   404   "rel_fun (eq_onp (\<lambda>f. (\<forall>x. 0 \<le> f x) \<and> (\<integral>\<^sup>+x. ereal (f x) \<partial>count_space UNIV) = 1)) pmf_as_measure.cr_pmf (\<lambda>f. density (count_space UNIV) (ereal \<circ> f)) embed_pmf"
   405   by (auto simp: rel_fun_def eq_onp_def embed_pmf.transfer)
   406 
   407 lemma measure_pmf_eq_density: "measure_pmf p = density (count_space UNIV) (pmf p)"
   408 proof (transfer, elim conjE)
   409   fix M :: "'a measure" assume [simp]: "sets M = UNIV" and ae: "AE x in M. measure M {x} \<noteq> 0"
   410   assume "prob_space M" then interpret prob_space M .
   411   show "M = density (count_space UNIV) (\<lambda>x. ereal (measure M {x}))"
   412   proof (rule measure_eqI)
   413     fix A :: "'a set"
   414     have "(\<integral>\<^sup>+ x. ereal (measure M {x}) * indicator A x \<partial>count_space UNIV) = 
   415       (\<integral>\<^sup>+ x. emeasure M {x} * indicator (A \<inter> {x. measure M {x} \<noteq> 0}) x \<partial>count_space UNIV)"
   416       by (auto intro!: nn_integral_cong simp: emeasure_eq_measure split: split_indicator)
   417     also have "\<dots> = (\<integral>\<^sup>+ x. emeasure M {x} \<partial>count_space (A \<inter> {x. measure M {x} \<noteq> 0}))"
   418       by (subst nn_integral_restrict_space[symmetric]) (auto simp: restrict_count_space)
   419     also have "\<dots> = emeasure M (\<Union>x\<in>(A \<inter> {x. measure M {x} \<noteq> 0}). {x})"
   420       by (intro emeasure_UN_countable[symmetric] countable_Int2 countable_support)
   421          (auto simp: disjoint_family_on_def)
   422     also have "\<dots> = emeasure M A"
   423       using ae by (intro emeasure_eq_AE) auto
   424     finally show " emeasure M A = emeasure (density (count_space UNIV) (\<lambda>x. ereal (measure M {x}))) A"
   425       using emeasure_space_1 by (simp add: emeasure_density)
   426   qed simp
   427 qed
   428 
   429 lemma td_pmf_embed_pmf:
   430   "type_definition pmf embed_pmf {f::'a \<Rightarrow> real. (\<forall>x. 0 \<le> f x) \<and> (\<integral>\<^sup>+x. ereal (f x) \<partial>count_space UNIV) = 1}"
   431   unfolding type_definition_def
   432 proof safe
   433   fix p :: "'a pmf"
   434   have "(\<integral>\<^sup>+ x. 1 \<partial>measure_pmf p) = 1"
   435     using measure_pmf.emeasure_space_1[of p] by simp
   436   then show *: "(\<integral>\<^sup>+ x. ereal (pmf p x) \<partial>count_space UNIV) = 1"
   437     by (simp add: measure_pmf_eq_density nn_integral_density pmf_nonneg del: nn_integral_const)
   438 
   439   show "embed_pmf (pmf p) = p"
   440     by (intro measure_pmf_inject[THEN iffD1])
   441        (simp add: * embed_pmf.rep_eq pmf_nonneg measure_pmf_eq_density[of p] comp_def)
   442 next
   443   fix f :: "'a \<Rightarrow> real" assume "\<forall>x. 0 \<le> f x" "(\<integral>\<^sup>+x. f x \<partial>count_space UNIV) = 1"
   444   then show "pmf (embed_pmf f) = f"
   445     by (auto intro!: pmf_embed_pmf)
   446 qed (rule pmf_nonneg)
   447 
   448 end
   449 
   450 locale pmf_as_function
   451 begin
   452 
   453 setup_lifting td_pmf_embed_pmf
   454 
   455 lemma set_pmf_transfer[transfer_rule]: 
   456   assumes "bi_total A"
   457   shows "rel_fun (pcr_pmf A) (rel_set A) (\<lambda>f. {x. f x \<noteq> 0}) set_pmf"  
   458   using `bi_total A`
   459   by (auto simp: pcr_pmf_def cr_pmf_def rel_fun_def rel_set_def bi_total_def Bex_def set_pmf_iff)
   460      metis+
   461 
   462 end
   463 
   464 context
   465 begin
   466 
   467 interpretation pmf_as_function .
   468 
   469 lemma pmf_eqI: "(\<And>i. pmf M i = pmf N i) \<Longrightarrow> M = N"
   470   by transfer auto
   471 
   472 lemma pmf_eq_iff: "M = N \<longleftrightarrow> (\<forall>i. pmf M i = pmf N i)"
   473   by (auto intro: pmf_eqI)
   474 
   475 end
   476 
   477 context
   478 begin
   479 
   480 interpretation pmf_as_function .
   481 
   482 lift_definition bernoulli_pmf :: "real \<Rightarrow> bool pmf" is
   483   "\<lambda>p b. ((\<lambda>p. if b then p else 1 - p) \<circ> min 1 \<circ> max 0) p"
   484   by (auto simp: nn_integral_count_space_finite[where A="{False, True}"] UNIV_bool
   485            split: split_max split_min)
   486 
   487 lemma pmf_bernoulli_True[simp]: "0 \<le> p \<Longrightarrow> p \<le> 1 \<Longrightarrow> pmf (bernoulli_pmf p) True = p"
   488   by transfer simp
   489 
   490 lemma pmf_bernoulli_False[simp]: "0 \<le> p \<Longrightarrow> p \<le> 1 \<Longrightarrow> pmf (bernoulli_pmf p) False = 1 - p"
   491   by transfer simp
   492 
   493 lemma set_pmf_bernoulli: "0 < p \<Longrightarrow> p < 1 \<Longrightarrow> set_pmf (bernoulli_pmf p) = UNIV"
   494   by (auto simp add: set_pmf_iff UNIV_bool)
   495 
   496 lemma nn_integral_bernoulli_pmf[simp]: 
   497   assumes [simp]: "0 \<le> p" "p \<le> 1" "\<And>x. 0 \<le> f x"
   498   shows "(\<integral>\<^sup>+x. f x \<partial>bernoulli_pmf p) = f True * p + f False * (1 - p)"
   499   by (subst nn_integral_measure_pmf_support[of UNIV])
   500      (auto simp: UNIV_bool field_simps)
   501 
   502 lemma integral_bernoulli_pmf[simp]: 
   503   assumes [simp]: "0 \<le> p" "p \<le> 1"
   504   shows "(\<integral>x. f x \<partial>bernoulli_pmf p) = f True * p + f False * (1 - p)"
   505   by (subst integral_measure_pmf[of UNIV]) (auto simp: UNIV_bool)
   506 
   507 lift_definition geometric_pmf :: "nat pmf" is "\<lambda>n. 1 / 2^Suc n"
   508 proof
   509   note geometric_sums[of "1 / 2"]
   510   note sums_mult[OF this, of "1 / 2"]
   511   from sums_suminf_ereal[OF this]
   512   show "(\<integral>\<^sup>+ x. ereal (1 / 2 ^ Suc x) \<partial>count_space UNIV) = 1"
   513     by (simp add: nn_integral_count_space_nat field_simps)
   514 qed simp
   515 
   516 lemma pmf_geometric[simp]: "pmf geometric_pmf n = 1 / 2^Suc n"
   517   by transfer rule
   518 
   519 lemma set_pmf_geometric[simp]: "set_pmf geometric_pmf = UNIV"
   520   by (auto simp: set_pmf_iff)
   521 
   522 context
   523   fixes M :: "'a multiset" assumes M_not_empty: "M \<noteq> {#}"
   524 begin
   525 
   526 lift_definition pmf_of_multiset :: "'a pmf" is "\<lambda>x. count M x / size M"
   527 proof
   528   show "(\<integral>\<^sup>+ x. ereal (real (count M x) / real (size M)) \<partial>count_space UNIV) = 1"  
   529     using M_not_empty
   530     by (simp add: zero_less_divide_iff nn_integral_count_space nonempty_has_size
   531                   setsum_divide_distrib[symmetric])
   532        (auto simp: size_multiset_overloaded_eq intro!: setsum.cong)
   533 qed simp
   534 
   535 lemma pmf_of_multiset[simp]: "pmf pmf_of_multiset x = count M x / size M"
   536   by transfer rule
   537 
   538 lemma set_pmf_of_multiset[simp]: "set_pmf pmf_of_multiset = set_of M"
   539   by (auto simp: set_pmf_iff)
   540 
   541 end
   542 
   543 context
   544   fixes S :: "'a set" assumes S_not_empty: "S \<noteq> {}" and S_finite: "finite S"
   545 begin
   546 
   547 lift_definition pmf_of_set :: "'a pmf" is "\<lambda>x. indicator S x / card S"
   548 proof
   549   show "(\<integral>\<^sup>+ x. ereal (indicator S x / real (card S)) \<partial>count_space UNIV) = 1"  
   550     using S_not_empty S_finite by (subst nn_integral_count_space'[of S]) auto
   551 qed simp
   552 
   553 lemma pmf_of_set[simp]: "pmf pmf_of_set x = indicator S x / card S"
   554   by transfer rule
   555 
   556 lemma set_pmf_of_set[simp]: "set_pmf pmf_of_set = S"
   557   using S_finite S_not_empty by (auto simp: set_pmf_iff)
   558 
   559 lemma emeasure_pmf_of_set[simp]: "emeasure pmf_of_set S = 1"
   560   by (rule measure_pmf.emeasure_eq_1_AE) (auto simp: AE_measure_pmf_iff)
   561 
   562 end
   563 
   564 end
   565 
   566 subsection {* Monad interpretation *}
   567 
   568 lemma measurable_measure_pmf[measurable]:
   569   "(\<lambda>x. measure_pmf (M x)) \<in> measurable (count_space UNIV) (subprob_algebra (count_space UNIV))"
   570   by (auto simp: space_subprob_algebra intro!: prob_space_imp_subprob_space) unfold_locales
   571 
   572 lemma bind_pmf_cong:
   573   assumes "\<And>x. A x \<in> space (subprob_algebra N)" "\<And>x. B x \<in> space (subprob_algebra N)"
   574   assumes "\<And>i. i \<in> set_pmf x \<Longrightarrow> A i = B i"
   575   shows "bind (measure_pmf x) A = bind (measure_pmf x) B"
   576 proof (rule measure_eqI)
   577   show "sets (measure_pmf x \<guillemotright>= A) = sets (measure_pmf x \<guillemotright>= B)"
   578     using assms by (subst (1 2) sets_bind) (auto simp: space_subprob_algebra)
   579 next
   580   fix X assume "X \<in> sets (measure_pmf x \<guillemotright>= A)"
   581   then have X: "X \<in> sets N"
   582     using assms by (subst (asm) sets_bind) (auto simp: space_subprob_algebra)
   583   show "emeasure (measure_pmf x \<guillemotright>= A) X = emeasure (measure_pmf x \<guillemotright>= B) X"
   584     using assms
   585     by (subst (1 2) emeasure_bind[where N=N, OF _ _ X])
   586        (auto intro!: nn_integral_cong_AE simp: AE_measure_pmf_iff)
   587 qed
   588 
   589 context
   590 begin
   591 
   592 interpretation pmf_as_measure .
   593 
   594 lift_definition join_pmf :: "'a pmf pmf \<Rightarrow> 'a pmf" is "\<lambda>M. measure_pmf M \<guillemotright>= measure_pmf"
   595 proof (intro conjI)
   596   fix M :: "'a pmf pmf"
   597 
   598   interpret bind: prob_space "measure_pmf M \<guillemotright>= measure_pmf"
   599     apply (intro measure_pmf.prob_space_bind[where S="count_space UNIV"] AE_I2)
   600     apply (auto intro!: subprob_space_measure_pmf simp: space_subprob_algebra)
   601     apply unfold_locales
   602     done
   603   show "prob_space (measure_pmf M \<guillemotright>= measure_pmf)"
   604     by intro_locales
   605   show "sets (measure_pmf M \<guillemotright>= measure_pmf) = UNIV"
   606     by (subst sets_bind) auto
   607   have "AE x in measure_pmf M \<guillemotright>= measure_pmf. emeasure (measure_pmf M \<guillemotright>= measure_pmf) {x} \<noteq> 0"
   608     by (auto simp: AE_bind[where B="count_space UNIV"] measure_pmf_in_subprob_algebra
   609                    emeasure_bind[where N="count_space UNIV"] AE_measure_pmf_iff nn_integral_0_iff_AE
   610                    measure_pmf.emeasure_eq_measure measure_le_0_iff set_pmf_iff pmf.rep_eq)
   611   then show "AE x in measure_pmf M \<guillemotright>= measure_pmf. measure (measure_pmf M \<guillemotright>= measure_pmf) {x} \<noteq> 0"
   612     unfolding bind.emeasure_eq_measure by simp
   613 qed
   614 
   615 lemma pmf_join: "pmf (join_pmf N) i = (\<integral>M. pmf M i \<partial>measure_pmf N)"
   616 proof (transfer fixing: N i)
   617   have N: "subprob_space (measure_pmf N)"
   618     by (rule prob_space_imp_subprob_space) intro_locales
   619   show "measure (measure_pmf N \<guillemotright>= measure_pmf) {i} = integral\<^sup>L (measure_pmf N) (\<lambda>M. measure M {i})"
   620     using measurable_measure_pmf[of "\<lambda>x. x"]
   621     by (intro subprob_space.measure_bind[where N="count_space UNIV", OF N]) auto
   622 qed (auto simp: Transfer.Rel_def rel_fun_def cr_pmf_def)
   623 
   624 lemma set_pmf_join_pmf: "set_pmf (join_pmf f) = (\<Union>p\<in>set_pmf f. set_pmf p)"
   625 apply(simp add: set_eq_iff set_pmf_iff pmf_join)
   626 apply(subst integral_nonneg_eq_0_iff_AE)
   627 apply(auto simp add: pmf_le_1 pmf_nonneg AE_measure_pmf_iff intro!: measure_pmf.integrable_const_bound[where B=1])
   628 done
   629 
   630 lift_definition return_pmf :: "'a \<Rightarrow> 'a pmf" is "return (count_space UNIV)"
   631   by (auto intro!: prob_space_return simp: AE_return measure_return)
   632 
   633 lemma join_return_pmf: "join_pmf (return_pmf M) = M"
   634   by (simp add: integral_return pmf_eq_iff pmf_join return_pmf.rep_eq)
   635 
   636 lemma map_return_pmf: "map_pmf f (return_pmf x) = return_pmf (f x)"
   637   by transfer (simp add: distr_return)
   638 
   639 lemma map_pmf_const[simp]: "map_pmf (\<lambda>_. c) M = return_pmf c"
   640   by transfer (auto simp: prob_space.distr_const)
   641 
   642 lemma set_return_pmf: "set_pmf (return_pmf x) = {x}"
   643   by transfer (auto simp add: measure_return split: split_indicator)
   644 
   645 lemma pmf_return: "pmf (return_pmf x) y = indicator {y} x"
   646   by transfer (simp add: measure_return)
   647 
   648 lemma nn_integral_return_pmf[simp]: "0 \<le> f x \<Longrightarrow> (\<integral>\<^sup>+x. f x \<partial>return_pmf x) = f x"
   649   unfolding return_pmf.rep_eq by (intro nn_integral_return) auto
   650 
   651 lemma emeasure_return_pmf[simp]: "emeasure (return_pmf x) X = indicator X x"
   652   unfolding return_pmf.rep_eq by (intro emeasure_return) auto
   653 
   654 end
   655 
   656 definition "bind_pmf M f = join_pmf (map_pmf f M)"
   657 
   658 lemma (in pmf_as_measure) bind_transfer[transfer_rule]:
   659   "rel_fun pmf_as_measure.cr_pmf (rel_fun (rel_fun op = pmf_as_measure.cr_pmf) pmf_as_measure.cr_pmf) op \<guillemotright>= bind_pmf"
   660 proof (auto simp: pmf_as_measure.cr_pmf_def rel_fun_def bind_pmf_def join_pmf.rep_eq map_pmf.rep_eq)
   661   fix M f and g :: "'a \<Rightarrow> 'b pmf" assume "\<forall>x. f x = measure_pmf (g x)"
   662   then have f: "f = (\<lambda>x. measure_pmf (g x))"
   663     by auto
   664   show "measure_pmf M \<guillemotright>= f = distr (measure_pmf M) (count_space UNIV) g \<guillemotright>= measure_pmf"
   665     unfolding f by (subst bind_distr[OF _ measurable_measure_pmf]) auto
   666 qed
   667 
   668 lemma pmf_bind: "pmf (bind_pmf N f) i = (\<integral>x. pmf (f x) i \<partial>measure_pmf N)"
   669   by (auto intro!: integral_distr simp: bind_pmf_def pmf_join map_pmf.rep_eq)
   670 
   671 lemma bind_return_pmf: "bind_pmf (return_pmf x) f = f x"
   672   unfolding bind_pmf_def map_return_pmf join_return_pmf ..
   673 
   674 lemma join_eq_bind_pmf: "join_pmf M = bind_pmf M id"
   675   by (simp add: bind_pmf_def)
   676 
   677 lemma bind_pmf_const[simp]: "bind_pmf M (\<lambda>x. c) = c"
   678   unfolding bind_pmf_def map_pmf_const join_return_pmf ..
   679 
   680 lemma set_bind_pmf: "set_pmf (bind_pmf M N) = (\<Union>M\<in>set_pmf M. set_pmf (N M))"
   681   apply (simp add: set_eq_iff set_pmf_iff pmf_bind)
   682   apply (subst integral_nonneg_eq_0_iff_AE)
   683   apply (auto simp: pmf_nonneg pmf_le_1 AE_measure_pmf_iff
   684               intro!: measure_pmf.integrable_const_bound[where B=1])
   685   done
   686 
   687 lemma measurable_pair_restrict_pmf2:
   688   assumes "countable A"
   689   assumes "\<And>y. y \<in> A \<Longrightarrow> (\<lambda>x. f (x, y)) \<in> measurable M L"
   690   shows "f \<in> measurable (M \<Otimes>\<^sub>M restrict_space (measure_pmf N) A) L"
   691   apply (subst measurable_cong_sets)
   692   apply (rule sets_pair_measure_cong sets_restrict_space_cong sets_measure_pmf_count_space refl)+
   693   apply (simp_all add: restrict_count_space)
   694   apply (subst split_eta[symmetric])
   695   unfolding measurable_split_conv
   696   apply (rule measurable_compose_countable'[OF _ measurable_snd `countable A`])
   697   apply (rule measurable_compose[OF measurable_fst])
   698   apply fact
   699   done
   700 
   701 lemma measurable_pair_restrict_pmf1:
   702   assumes "countable A"
   703   assumes "\<And>x. x \<in> A \<Longrightarrow> (\<lambda>y. f (x, y)) \<in> measurable N L"
   704   shows "f \<in> measurable (restrict_space (measure_pmf M) A \<Otimes>\<^sub>M N) L"
   705   apply (subst measurable_cong_sets)
   706   apply (rule sets_pair_measure_cong sets_restrict_space_cong sets_measure_pmf_count_space refl)+
   707   apply (simp_all add: restrict_count_space)
   708   apply (subst split_eta[symmetric])
   709   unfolding measurable_split_conv
   710   apply (rule measurable_compose_countable'[OF _ measurable_fst `countable A`])
   711   apply (rule measurable_compose[OF measurable_snd])
   712   apply fact
   713   done
   714                                 
   715 lemma bind_commute_pmf: "bind_pmf A (\<lambda>x. bind_pmf B (C x)) = bind_pmf B (\<lambda>y. bind_pmf A (\<lambda>x. C x y))"
   716   unfolding pmf_eq_iff pmf_bind
   717 proof
   718   fix i
   719   interpret B: prob_space "restrict_space B B"
   720     by (intro prob_space_restrict_space measure_pmf.emeasure_eq_1_AE)
   721        (auto simp: AE_measure_pmf_iff)
   722   interpret A: prob_space "restrict_space A A"
   723     by (intro prob_space_restrict_space measure_pmf.emeasure_eq_1_AE)
   724        (auto simp: AE_measure_pmf_iff)
   725 
   726   interpret AB: pair_prob_space "restrict_space A A" "restrict_space B B"
   727     by unfold_locales
   728 
   729   have "(\<integral> x. \<integral> y. pmf (C x y) i \<partial>B \<partial>A) = (\<integral> x. (\<integral> y. pmf (C x y) i \<partial>restrict_space B B) \<partial>A)"
   730     by (rule integral_cong) (auto intro!: integral_pmf_restrict)
   731   also have "\<dots> = (\<integral> x. (\<integral> y. pmf (C x y) i \<partial>restrict_space B B) \<partial>restrict_space A A)"
   732     by (intro integral_pmf_restrict B.borel_measurable_lebesgue_integral measurable_pair_restrict_pmf2
   733               countable_set_pmf borel_measurable_count_space)
   734   also have "\<dots> = (\<integral> y. \<integral> x. pmf (C x y) i \<partial>restrict_space A A \<partial>restrict_space B B)"
   735     by (rule AB.Fubini_integral[symmetric])
   736        (auto intro!: AB.integrable_const_bound[where B=1] measurable_pair_restrict_pmf2
   737              simp: pmf_nonneg pmf_le_1 measurable_restrict_space1)
   738   also have "\<dots> = (\<integral> y. \<integral> x. pmf (C x y) i \<partial>restrict_space A A \<partial>B)"
   739     by (intro integral_pmf_restrict[symmetric] A.borel_measurable_lebesgue_integral measurable_pair_restrict_pmf2
   740               countable_set_pmf borel_measurable_count_space)
   741   also have "\<dots> = (\<integral> y. \<integral> x. pmf (C x y) i \<partial>A \<partial>B)"
   742     by (rule integral_cong) (auto intro!: integral_pmf_restrict[symmetric])
   743   finally show "(\<integral> x. \<integral> y. pmf (C x y) i \<partial>B \<partial>A) = (\<integral> y. \<integral> x. pmf (C x y) i \<partial>A \<partial>B)" .
   744 qed
   745 
   746 
   747 context
   748 begin
   749 
   750 interpretation pmf_as_measure .
   751 
   752 lemma measure_pmf_bind: "measure_pmf (bind_pmf M f) = (measure_pmf M \<guillemotright>= (\<lambda>x. measure_pmf (f x)))"
   753   by transfer simp
   754 
   755 lemma nn_integral_bind_pmf[simp]: "(\<integral>\<^sup>+x. f x \<partial>bind_pmf M N) = (\<integral>\<^sup>+x. \<integral>\<^sup>+y. f y \<partial>N x \<partial>M)"
   756   using measurable_measure_pmf[of N]
   757   unfolding measure_pmf_bind
   758   apply (subst (1 3) nn_integral_max_0[symmetric])
   759   apply (intro nn_integral_bind[where B="count_space UNIV"])
   760   apply auto
   761   done
   762 
   763 lemma emeasure_bind_pmf[simp]: "emeasure (bind_pmf M N) X = (\<integral>\<^sup>+x. emeasure (N x) X \<partial>M)"
   764   using measurable_measure_pmf[of N]
   765   unfolding measure_pmf_bind
   766   by (subst emeasure_bind[where N="count_space UNIV"]) auto
   767 
   768 lemma bind_return_pmf': "bind_pmf N return_pmf = N"
   769 proof (transfer, clarify)
   770   fix N :: "'a measure" assume "sets N = UNIV" then show "N \<guillemotright>= return (count_space UNIV) = N"
   771     by (subst return_sets_cong[where N=N]) (simp_all add: bind_return')
   772 qed
   773 
   774 lemma bind_return_pmf'': "bind_pmf N (\<lambda>x. return_pmf (f x)) = map_pmf f N"
   775 proof (transfer, clarify)
   776   fix N :: "'b measure" and f :: "'b \<Rightarrow> 'a" assume "prob_space N" "sets N = UNIV"
   777   then show "N \<guillemotright>= (\<lambda>x. return (count_space UNIV) (f x)) = distr N (count_space UNIV) f"
   778     by (subst bind_return_distr[symmetric])
   779        (auto simp: prob_space.not_empty measurable_def comp_def)
   780 qed
   781 
   782 lemma bind_assoc_pmf: "bind_pmf (bind_pmf A B) C = bind_pmf A (\<lambda>x. bind_pmf (B x) C)"
   783   by transfer
   784      (auto intro!: bind_assoc[where N="count_space UNIV" and R="count_space UNIV"]
   785            simp: measurable_def space_subprob_algebra prob_space_imp_subprob_space)
   786 
   787 end
   788 
   789 lemma map_join_pmf: "map_pmf f (join_pmf AA) = join_pmf (map_pmf (map_pmf f) AA)"
   790   unfolding bind_pmf_def[symmetric]
   791   unfolding bind_return_pmf''[symmetric] join_eq_bind_pmf bind_assoc_pmf
   792   by (simp add: bind_return_pmf'')
   793 
   794 definition "pair_pmf A B = bind_pmf A (\<lambda>x. bind_pmf B (\<lambda>y. return_pmf (x, y)))"
   795 
   796 lemma pmf_pair: "pmf (pair_pmf M N) (a, b) = pmf M a * pmf N b"
   797   unfolding pair_pmf_def pmf_bind pmf_return
   798   apply (subst integral_measure_pmf[where A="{b}"])
   799   apply (auto simp: indicator_eq_0_iff)
   800   apply (subst integral_measure_pmf[where A="{a}"])
   801   apply (auto simp: indicator_eq_0_iff setsum_nonneg_eq_0_iff pmf_nonneg)
   802   done
   803 
   804 lemma set_pair_pmf: "set_pmf (pair_pmf A B) = set_pmf A \<times> set_pmf B"
   805   unfolding pair_pmf_def set_bind_pmf set_return_pmf by auto
   806 
   807 lemma measure_pmf_in_subprob_space[measurable (raw)]:
   808   "measure_pmf M \<in> space (subprob_algebra (count_space UNIV))"
   809   by (simp add: space_subprob_algebra) intro_locales
   810 
   811 lemma bind_pair_pmf:
   812   assumes M[measurable]: "M \<in> measurable (count_space UNIV \<Otimes>\<^sub>M count_space UNIV) (subprob_algebra N)"
   813   shows "measure_pmf (pair_pmf A B) \<guillemotright>= M = (measure_pmf A \<guillemotright>= (\<lambda>x. measure_pmf B \<guillemotright>= (\<lambda>y. M (x, y))))"
   814     (is "?L = ?R")
   815 proof (rule measure_eqI)
   816   have M'[measurable]: "M \<in> measurable (pair_pmf A B) (subprob_algebra N)"
   817     using M[THEN measurable_space] by (simp_all add: space_pair_measure)
   818 
   819   note measurable_bind[where N="count_space UNIV", measurable]
   820   note measure_pmf_in_subprob_space[simp]
   821 
   822   have sets_eq_N: "sets ?L = N"
   823     by (subst sets_bind[OF sets_kernel[OF M']]) auto
   824   show "sets ?L = sets ?R"
   825     using measurable_space[OF M]
   826     by (simp add: sets_eq_N space_pair_measure space_subprob_algebra)
   827   fix X assume "X \<in> sets ?L"
   828   then have X[measurable]: "X \<in> sets N"
   829     unfolding sets_eq_N .
   830   then show "emeasure ?L X = emeasure ?R X"
   831     apply (simp add: emeasure_bind[OF _ M' X])
   832     apply (simp add: nn_integral_bind[where B="count_space UNIV"] pair_pmf_def measure_pmf_bind[of A]
   833       nn_integral_measure_pmf_finite set_return_pmf emeasure_nonneg pmf_return one_ereal_def[symmetric])
   834     apply (subst emeasure_bind[OF _ _ X])
   835     apply measurable
   836     apply (subst emeasure_bind[OF _ _ X])
   837     apply measurable
   838     done
   839 qed
   840 
   841 lemma join_map_return_pmf: "join_pmf (map_pmf return_pmf A) = A"
   842   unfolding bind_pmf_def[symmetric] bind_return_pmf' ..
   843 
   844 lemma map_fst_pair_pmf: "map_pmf fst (pair_pmf A B) = A"
   845   by (simp add: pair_pmf_def bind_return_pmf''[symmetric] bind_assoc_pmf bind_return_pmf bind_return_pmf')
   846 
   847 lemma map_snd_pair_pmf: "map_pmf snd (pair_pmf A B) = B"
   848   by (simp add: pair_pmf_def bind_return_pmf''[symmetric] bind_assoc_pmf bind_return_pmf bind_return_pmf')
   849 
   850 lemma nn_integral_pmf':
   851   "inj_on f A \<Longrightarrow> (\<integral>\<^sup>+x. pmf p (f x) \<partial>count_space A) = emeasure p (f ` A)"
   852   by (subst nn_integral_bij_count_space[where g=f and B="f`A"])
   853      (auto simp: bij_betw_def nn_integral_pmf)
   854 
   855 lemma pmf_le_0_iff[simp]: "pmf M p \<le> 0 \<longleftrightarrow> pmf M p = 0"
   856   using pmf_nonneg[of M p] by simp
   857 
   858 lemma min_pmf_0[simp]: "min (pmf M p) 0 = 0" "min 0 (pmf M p) = 0"
   859   using pmf_nonneg[of M p] by simp_all
   860 
   861 lemma pmf_eq_0_set_pmf: "pmf M p = 0 \<longleftrightarrow> p \<notin> set_pmf M"
   862   unfolding set_pmf_iff by simp
   863 
   864 lemma pmf_map_inj: "inj_on f (set_pmf M) \<Longrightarrow> x \<in> set_pmf M \<Longrightarrow> pmf (map_pmf f M) (f x) = pmf M x"
   865   by (auto simp: pmf.rep_eq map_pmf.rep_eq measure_distr AE_measure_pmf_iff inj_onD
   866            intro!: measure_pmf.finite_measure_eq_AE)
   867 
   868 inductive rel_pmf :: "('a \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> 'a pmf \<Rightarrow> 'b pmf \<Rightarrow> bool"
   869 for R p q
   870 where
   871   "\<lbrakk> \<And>x y. (x, y) \<in> set_pmf pq \<Longrightarrow> R x y; 
   872      map_pmf fst pq = p; map_pmf snd pq = q \<rbrakk>
   873   \<Longrightarrow> rel_pmf R p q"
   874 
   875 bnf pmf: "'a pmf" map: map_pmf sets: set_pmf bd : "natLeq" rel: rel_pmf
   876 proof -
   877   show "map_pmf id = id" by (rule map_pmf_id)
   878   show "\<And>f g. map_pmf (f \<circ> g) = map_pmf f \<circ> map_pmf g" by (rule map_pmf_compose) 
   879   show "\<And>f g::'a \<Rightarrow> 'b. \<And>p. (\<And>x. x \<in> set_pmf p \<Longrightarrow> f x = g x) \<Longrightarrow> map_pmf f p = map_pmf g p"
   880     by (intro map_pmf_cong refl)
   881 
   882   show "\<And>f::'a \<Rightarrow> 'b. set_pmf \<circ> map_pmf f = op ` f \<circ> set_pmf"
   883     by (rule pmf_set_map)
   884 
   885   { fix p :: "'s pmf"
   886     have "(card_of (set_pmf p), card_of (UNIV :: nat set)) \<in> ordLeq"
   887       by (rule card_of_ordLeqI[where f="to_nat_on (set_pmf p)"])
   888          (auto intro: countable_set_pmf)
   889     also have "(card_of (UNIV :: nat set), natLeq) \<in> ordLeq"
   890       by (metis Field_natLeq card_of_least natLeq_Well_order)
   891     finally show "(card_of (set_pmf p), natLeq) \<in> ordLeq" . }
   892 
   893   show "\<And>R. rel_pmf R =
   894          (BNF_Def.Grp {x. set_pmf x \<subseteq> {(x, y). R x y}} (map_pmf fst))\<inverse>\<inverse> OO
   895          BNF_Def.Grp {x. set_pmf x \<subseteq> {(x, y). R x y}} (map_pmf snd)"
   896      by (auto simp add: fun_eq_iff BNF_Def.Grp_def OO_def rel_pmf.simps)
   897 
   898   { fix p :: "'a pmf" and f :: "'a \<Rightarrow> 'b" and g x
   899     assume p: "\<And>z. z \<in> set_pmf p \<Longrightarrow> f z = g z"
   900       and x: "x \<in> set_pmf p"
   901     thus "f x = g x" by simp }
   902 
   903   fix R :: "'a => 'b \<Rightarrow> bool" and S :: "'b \<Rightarrow> 'c \<Rightarrow> bool"
   904   { fix p q r
   905     assume pq: "rel_pmf R p q"
   906       and qr:"rel_pmf S q r"
   907     from pq obtain pq where pq: "\<And>x y. (x, y) \<in> set_pmf pq \<Longrightarrow> R x y"
   908       and p: "p = map_pmf fst pq" and q: "q = map_pmf snd pq" by cases auto
   909     from qr obtain qr where qr: "\<And>y z. (y, z) \<in> set_pmf qr \<Longrightarrow> S y z"
   910       and q': "q = map_pmf fst qr" and r: "r = map_pmf snd qr" by cases auto
   911 
   912     note pmf_nonneg[intro, simp]
   913 
   914     def A \<equiv> "\<lambda>y. {x. (x, y) \<in> set_pmf pq}"
   915     then have "\<And>y. A y \<subseteq> set_pmf p" by (auto simp add: p set_map_pmf intro: rev_image_eqI)
   916     then have [simp]: "\<And>y. countable (A y)" by (rule countable_subset) simp
   917     have A: "\<And>x y. (x, y) \<in> set_pmf pq \<longleftrightarrow> x \<in> A y"
   918       by (simp add: A_def)
   919 
   920     let ?P = "\<lambda>y. to_nat_on (A y)"
   921     def pp \<equiv> "map_pmf (\<lambda>(x, y). (y, ?P y x)) pq"
   922     let ?pp = "\<lambda>y x. pmf pp (y, x)"
   923     { fix x y have "x \<in> A y \<Longrightarrow> pmf pp (y, ?P y x) = pmf pq (x, y)"
   924         unfolding pp_def
   925         by (intro pmf_map_inj[of "\<lambda>(x, y). (y, ?P y x)" pq "(x, y)", simplified])
   926            (auto simp: inj_on_def A) }
   927     note pmf_pp = this
   928 
   929     def B \<equiv> "\<lambda>y. {z. (y, z) \<in> set_pmf qr}"
   930     then have "\<And>y. B y \<subseteq> set_pmf r" by (auto simp add: r set_map_pmf intro: rev_image_eqI)
   931     then have [simp]: "\<And>y. countable (B y)" by (rule countable_subset) simp
   932     have B: "\<And>y z. (y, z) \<in> set_pmf qr \<longleftrightarrow> z \<in> B y"
   933       by (simp add: B_def)
   934 
   935     let ?R = "\<lambda>y. to_nat_on (B y)"
   936     def rr \<equiv> "map_pmf (\<lambda>(y, z). (y, ?R y z)) qr"
   937     let ?rr = "\<lambda>y z. pmf rr (y, z)"
   938     { fix y z have "z \<in> B y \<Longrightarrow> pmf rr (y, ?R y z) = pmf qr (y, z)"
   939         unfolding rr_def
   940         by (intro pmf_map_inj[of "\<lambda>(y, z). (y, ?R y z)" qr "(y, z)", simplified])
   941            (auto simp: inj_on_def B) }
   942     note pmf_rr = this
   943 
   944     have eq: "\<And>y. (\<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV) = (\<integral>\<^sup>+ z. ?rr y z \<partial>count_space UNIV)"
   945     proof -
   946       fix y
   947       have "(\<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV) = pmf q y"
   948         by (simp add: nn_integral_pmf' inj_on_def pp_def q)
   949            (auto simp add: ereal_pmf_map intro!: arg_cong2[where f=emeasure])
   950       also have "\<dots> = (\<integral>\<^sup>+ x. ?rr y x \<partial>count_space UNIV)"
   951         by (simp add: nn_integral_pmf' inj_on_def rr_def q')
   952            (auto simp add: ereal_pmf_map intro!: arg_cong2[where f=emeasure])
   953       finally show "?thesis y" .
   954     qed
   955 
   956     def assign_aux \<equiv> "\<lambda>y remainder start weight z.
   957        if z < start then 0
   958        else if z = start then min weight remainder
   959        else if remainder + setsum (?rr y) {Suc start ..<z} < weight then min (weight - remainder - setsum (?rr y) {Suc start..<z}) (?rr y z) else 0"
   960     hence assign_aux_alt_def: "\<And>y remainder start weight z. assign_aux y remainder start weight z = 
   961        (if z < start then 0
   962         else if z = start then min weight remainder
   963         else if remainder + setsum (?rr y) {Suc start ..<z} < weight then min (weight - remainder - setsum (?rr y) {Suc start..<z}) (?rr y z) else 0)"
   964        by simp
   965     { fix y and remainder :: real and start and weight :: real
   966       assume weight_nonneg: "0 \<le> weight"
   967       let ?assign_aux = "assign_aux y remainder start weight"
   968       { fix z
   969         have "setsum ?assign_aux {..<z} =
   970            (if z \<le> start then 0 else if remainder + setsum (?rr y) {Suc start..<z} < weight then remainder + setsum (?rr y) {Suc start..<z} else weight)"
   971         proof(induction z)
   972           case (Suc z) show ?case
   973             by (auto simp add: Suc.IH assign_aux_alt_def[where z=z] not_less)
   974                (metis add.commute add.left_commute add_increasing pmf_nonneg)
   975         qed(auto simp add: assign_aux_def) }
   976       note setsum_start_assign_aux = this
   977       moreover {
   978         assume remainder_nonneg: "0 \<le> remainder"
   979         have [simp]: "\<And>z. 0 \<le> ?assign_aux z"
   980           by(simp add: assign_aux_def weight_nonneg remainder_nonneg)
   981         moreover have "\<And>z. \<lbrakk> ?rr y z = 0; remainder \<le> ?rr y start \<rbrakk> \<Longrightarrow> ?assign_aux z = 0"
   982           using remainder_nonneg weight_nonneg
   983           by(auto simp add: assign_aux_def min_def)
   984         moreover have "(\<integral>\<^sup>+ z. ?assign_aux z \<partial>count_space UNIV) = 
   985           min weight (\<integral>\<^sup>+ z. (if z < start then 0 else if z = start then remainder else ?rr y z) \<partial>count_space UNIV)"
   986           (is "?lhs = ?rhs" is "_ = min _ (\<integral>\<^sup>+ y. ?f y \<partial>_)")
   987         proof -
   988           have "?lhs = (SUP n. \<Sum>z<n. ereal (?assign_aux z))"
   989             by(simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP)
   990           also have "\<dots> = (SUP n. min weight (\<Sum>z<n. ?f z))"
   991           proof(rule arg_cong2[where f=SUPREMUM] ext refl)+
   992             fix n
   993             have "(\<Sum>z<n. ereal (?assign_aux z)) = min weight ((if n > start then remainder else 0) + setsum ?f {Suc start..<n})"
   994               using weight_nonneg remainder_nonneg by(simp add: setsum_start_assign_aux min_def)
   995             also have "\<dots> = min weight (setsum ?f {start..<n})"
   996               by(simp add: setsum_head_upt_Suc)
   997             also have "\<dots> = min weight (setsum ?f {..<n})"
   998               by(intro arg_cong2[where f=min] setsum.mono_neutral_left) auto
   999             finally show "(\<Sum>z<n. ereal (?assign_aux z)) = \<dots>" .
  1000           qed
  1001           also have "\<dots> = min weight (SUP n. setsum ?f {..<n})"
  1002             unfolding inf_min[symmetric] by(subst inf_SUP) simp
  1003           also have "\<dots> = ?rhs"
  1004             by(simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP remainder_nonneg)
  1005           finally show ?thesis .
  1006         qed
  1007         moreover note calculation }
  1008       moreover note calculation }
  1009     note setsum_start_assign_aux = this(1)
  1010       and assign_aux_nonneg [simp] = this(2)
  1011       and assign_aux_eq_0_outside = this(3)
  1012       and nn_integral_assign_aux = this(4)
  1013     { fix y and remainder :: real and start target
  1014       have "setsum (?rr y) {Suc start..<target} \<ge> 0" by (simp add: setsum_nonneg)
  1015       moreover assume "0 \<le> remainder"
  1016       ultimately have "assign_aux y remainder start 0 target = 0"
  1017         by(auto simp add: assign_aux_def min_def) }
  1018     note assign_aux_weight_0 [simp] = this
  1019 
  1020     def find_start \<equiv> "\<lambda>y weight. if \<exists>n. weight \<le> setsum (?rr y)  {..n} then Some (LEAST n. weight \<le> setsum (?rr y) {..n}) else None"
  1021     have find_start_eq_Some_above:
  1022       "\<And>y weight n. find_start y weight = Some n \<Longrightarrow> weight \<le> setsum (?rr y) {..n}"
  1023       by(drule sym)(auto simp add: find_start_def split: split_if_asm intro: LeastI)
  1024     { fix y weight n
  1025       assume find_start: "find_start y weight = Some n"
  1026       and weight: "0 \<le> weight"
  1027       have "setsum (?rr y) {..n} \<le> ?rr y n + weight"
  1028       proof(rule ccontr)
  1029         assume "\<not> ?thesis"
  1030         hence "?rr y n + weight < setsum (?rr y) {..n}" by simp
  1031         moreover with weight obtain n' where "n = Suc n'" by(cases n) auto
  1032         ultimately have "weight \<le> setsum (?rr y) {..n'}" by simp
  1033         hence "(LEAST n. weight \<le> setsum (?rr y) {..n}) \<le> n'" by(rule Least_le)
  1034         moreover from find_start have "n = (LEAST n. weight \<le> setsum (?rr y) {..n})"
  1035           by(auto simp add: find_start_def split: split_if_asm)
  1036         ultimately show False using \<open>n = Suc n'\<close> by auto
  1037       qed }
  1038     note find_start_eq_Some_least = this
  1039     have find_start_0 [simp]: "\<And>y. find_start y 0 = Some 0"
  1040       by(auto simp add: find_start_def intro!: exI[where x=0])
  1041     { fix y and weight :: real
  1042       assume "weight < \<integral>\<^sup>+ z. ?rr y z \<partial>count_space UNIV"
  1043       also have "(\<integral>\<^sup>+ z. ?rr y z \<partial>count_space UNIV) = (SUP n. \<Sum>z<n. ereal (?rr y z))"
  1044         by(simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP)
  1045       finally obtain n where "weight < (\<Sum>z<n. ?rr y z)" by(auto simp add: less_SUP_iff)
  1046       hence "weight \<in> dom (find_start y)"
  1047         by(auto simp add: find_start_def)(meson atMost_iff finite_atMost lessThan_iff less_imp_le order_trans pmf_nonneg setsum_mono3 subsetI) }
  1048     note in_dom_find_startI = this
  1049     { fix y and w w' :: real and m
  1050       let ?m' = "LEAST m. w' \<le> setsum (?rr y) {..m}"
  1051       assume "w' \<le> w"
  1052       also  assume "find_start y w = Some m"
  1053       hence "w \<le> setsum (?rr y) {..m}" by(rule find_start_eq_Some_above)
  1054       finally have "find_start y w' = Some ?m'" by(auto simp add: find_start_def)
  1055       moreover from \<open>w' \<le> setsum (?rr y) {..m}\<close> have "?m' \<le> m" by(rule Least_le)
  1056       ultimately have "\<exists>m'. find_start y w' = Some m' \<and> m' \<le> m" by blast }
  1057     note find_start_mono = this[rotated]
  1058 
  1059     def assign \<equiv> "\<lambda>y x z. let used = setsum (?pp y) {..<x}
  1060       in case find_start y used of None \<Rightarrow> 0
  1061          | Some start \<Rightarrow> assign_aux y (setsum (?rr y) {..start} - used) start (?pp y x) z"
  1062     hence assign_alt_def: "\<And>y x z. assign y x z = 
  1063       (let used = setsum (?pp y) {..<x}
  1064        in case find_start y used of None \<Rightarrow> 0
  1065           | Some start \<Rightarrow> assign_aux y (setsum (?rr y) {..start} - used) start (?pp y x) z)"
  1066       by simp
  1067     have assign_nonneg [simp]: "\<And>y x z. 0 \<le> assign y x z"
  1068       by(simp add: assign_def diff_le_iff find_start_eq_Some_above Let_def split: option.split)
  1069     have assign_eq_0_outside: "\<And>y x z. \<lbrakk> ?pp y x = 0 \<or> ?rr y z = 0 \<rbrakk> \<Longrightarrow> assign y x z = 0"
  1070       by(auto simp add: assign_def assign_aux_eq_0_outside diff_le_iff find_start_eq_Some_above find_start_eq_Some_least setsum_nonneg Let_def split: option.split)
  1071 
  1072     { fix y x z
  1073       have "(\<Sum>n<Suc x. assign y n z) =
  1074             (case find_start y (setsum (?pp y) {..<x}) of None \<Rightarrow> ?rr y z
  1075              | Some m \<Rightarrow> if z < m then ?rr y z 
  1076                          else min (?rr y z) (max 0 (setsum (?pp y) {..<x} + ?pp y x - setsum (?rr y) {..<z})))"
  1077         (is "?lhs x = ?rhs x")
  1078       proof(induction x)
  1079         case 0 thus ?case 
  1080           by(auto simp add: assign_def assign_aux_def setsum_head_upt_Suc atLeast0LessThan[symmetric] not_less field_simps max_def)
  1081       next
  1082         case (Suc x)
  1083         have "?lhs (Suc x) = ?lhs x + assign y (Suc x) z" by simp
  1084         also have "?lhs x = ?rhs x" by(rule Suc.IH)
  1085         also have "?rhs x + assign y (Suc x) z = ?rhs (Suc x)"
  1086         proof(cases "find_start y (setsum (?pp y) {..<Suc x})")
  1087           case None
  1088           thus ?thesis
  1089             by(auto split: option.split simp add: assign_def min_def max_def diff_le_iff setsum_nonneg not_le field_simps)
  1090               (metis add.commute add_increasing find_start_def lessThan_Suc_atMost less_imp_le option.distinct(1) setsum_lessThan_Suc)+
  1091         next 
  1092           case (Some m)
  1093           have [simp]: "setsum (?rr y) {..m} = ?rr y m + setsum (?rr y) {..<m}"
  1094             by(simp add: ivl_disj_un(2)[symmetric])
  1095           from Some obtain m' where m': "find_start y (setsum (?pp y) {..<x}) = Some m'" "m' \<le> m"
  1096             by(auto dest: find_start_mono[where w'2="setsum (?pp y) {..<x}"])
  1097           moreover {
  1098             assume "z < m"
  1099             then have "setsum (?rr y) {..z} \<le> setsum (?rr y) {..<m}"
  1100               by(auto intro: setsum_mono3)
  1101             also have "\<dots> \<le> setsum (?pp y) {..<Suc x}" using find_start_eq_Some_least[OF Some]
  1102               by(simp add: ivl_disj_un(2)[symmetric] setsum_nonneg)
  1103             finally have "?rr y z \<le> max 0 (setsum (?pp y) {..<x} + ?pp y x - setsum (?rr y) {..<z})"
  1104               by(auto simp add: ivl_disj_un(2)[symmetric] max_def diff_le_iff simp del: pmf_le_0_iff)
  1105           } moreover {
  1106             assume "m \<le> z"
  1107             have "setsum (?pp y) {..<Suc x} \<le> setsum (?rr y) {..m}"
  1108               using Some by(rule find_start_eq_Some_above)
  1109             also have "\<dots> \<le> setsum (?rr y) {..<Suc z}" using \<open>m \<le> z\<close> by(intro setsum_mono3) auto
  1110             finally have "max 0 (setsum (?pp y) {..<x} + ?pp y x - setsum (?rr y) {..<z}) \<le> ?rr y z" by simp
  1111             moreover have "z \<noteq> m \<Longrightarrow> setsum (?rr y) {..m} + setsum (?rr y) {Suc m..<z} = setsum (?rr y) {..<z}"
  1112               using \<open>m \<le> z\<close>
  1113               by(subst ivl_disj_un(8)[where l="Suc m", symmetric])
  1114                 (simp_all add: setsum_Un ivl_disj_un(2)[symmetric] setsum.neutral)
  1115             moreover note calculation
  1116           } moreover {
  1117             assume "m < z"
  1118             have "setsum (?pp y) {..<Suc x} \<le> setsum (?rr y) {..m}"
  1119               using Some by(rule find_start_eq_Some_above)
  1120             also have "\<dots> \<le> setsum (?rr y) {..<z}" using \<open>m < z\<close> by(intro setsum_mono3) auto
  1121             finally have "max 0 (setsum (?pp y) {..<Suc x} - setsum (?rr y) {..<z}) = 0" by simp }
  1122           moreover have "setsum (?pp y) {..<Suc x} \<ge> setsum (?rr y) {..<m}"
  1123             using find_start_eq_Some_least[OF Some]
  1124             by(simp add: setsum_nonneg ivl_disj_un(2)[symmetric])
  1125           moreover hence "setsum (?pp y) {..<Suc (Suc x)} \<ge> setsum (?rr y) {..<m}"
  1126             by(fastforce intro: order_trans)
  1127           ultimately show ?thesis using Some
  1128             by(auto simp add: assign_def assign_aux_def Let_def field_simps max_def)
  1129         qed
  1130         finally show ?case .
  1131       qed }
  1132     note setsum_assign = this
  1133 
  1134     have nn_integral_assign1: "\<And>y z. (\<integral>\<^sup>+ x. assign y x z \<partial>count_space UNIV) = ?rr y z"
  1135     proof -
  1136       fix y z
  1137       have "(\<integral>\<^sup>+ x. assign y x z \<partial>count_space UNIV) = (SUP n. ereal (\<Sum>x<n. assign y x z))"
  1138         by(simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP)
  1139       also have "\<dots> = ?rr y z"
  1140       proof(rule antisym)
  1141         show "(SUP n. ereal (\<Sum>x<n. assign y x z)) \<le> ?rr y z"
  1142         proof(rule SUP_least)
  1143           fix n
  1144           show "ereal (\<Sum>x<n. (assign y x z)) \<le> ?rr y z"
  1145             using setsum_assign[of y z "n - 1"]
  1146             by(cases n)(simp_all split: option.split)
  1147         qed
  1148         show "?rr y z \<le> (SUP n. ereal (\<Sum>x<n. assign y x z))"
  1149         proof(cases "setsum (?rr y) {..z} < \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV")
  1150           case True
  1151           then obtain n where "setsum (?rr y) {..z} < setsum (?pp y) {..<n}"
  1152             by(auto simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP less_SUP_iff)
  1153           moreover have "\<And>k. k < z \<Longrightarrow> setsum (?rr y) {..k} \<le> setsum (?rr y) {..<z}"
  1154             by(auto intro: setsum_mono3)
  1155           ultimately have "?rr y z \<le> (\<Sum>x<Suc n. assign y x z)"
  1156             by(subst setsum_assign)(auto split: option.split dest!: find_start_eq_Some_above simp add: ivl_disj_un(2)[symmetric] add.commute add_increasing le_diff_eq le_max_iff_disj)
  1157           also have "\<dots> \<le> (SUP n. ereal (\<Sum>x<n. assign y x z))" 
  1158             by(rule SUP_upper) simp
  1159           finally show ?thesis by simp
  1160         next
  1161           case False
  1162           have "setsum (?rr y) {..z} = \<integral>\<^sup>+ z. ?rr y z \<partial>count_space {..z}"
  1163             by(simp add: nn_integral_count_space_finite max_def)
  1164           also have "\<dots> \<le> \<integral>\<^sup>+ z. ?rr y z \<partial>count_space UNIV"
  1165             by(auto simp add: nn_integral_count_space_indicator indicator_def intro: nn_integral_mono)
  1166           also have "\<dots> = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV" by(simp add: eq)
  1167           finally have *: "setsum (?rr y) {..z} = \<dots>" using False by simp
  1168           also have "\<dots> = (SUP n. ereal (\<Sum>x<n. ?pp y x))"
  1169             by(simp add: nn_integral_count_space_nat suminf_ereal_eq_SUP)
  1170           also have "\<dots> \<le> (SUP n. ereal (\<Sum>x<n. assign y x z)) + setsum (?rr y) {..<z}"
  1171           proof(rule SUP_least)
  1172             fix n
  1173             have "setsum (?pp y) {..<n} = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space {..<n}"
  1174               by(simp add: nn_integral_count_space_finite max_def)
  1175             also have "\<dots> \<le> \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV"
  1176               by(auto simp add: nn_integral_count_space_indicator indicator_def intro: nn_integral_mono)
  1177             also have "\<dots> = setsum (?rr y) {..z}" using * by simp
  1178             finally obtain k where k: "find_start y (setsum (?pp y) {..<n}) = Some k"
  1179               by(fastforce simp add: find_start_def)
  1180             with \<open>ereal (setsum (?pp y) {..<n}) \<le> setsum (?rr y) {..z}\<close>
  1181             have "k \<le> z" by(auto simp add: find_start_def split: split_if_asm intro: Least_le)
  1182             then have "setsum (?pp y) {..<n} - setsum (?rr y) {..<z} \<le> ereal (\<Sum>x<Suc n. assign y x z)"
  1183               using \<open>ereal (setsum (?pp y) {..<n}) \<le> setsum (?rr y) {..z}\<close>
  1184               apply (subst setsum_assign)
  1185               apply (auto simp add: field_simps max_def k ivl_disj_un(2)[symmetric])
  1186               apply (meson add_increasing le_cases pmf_nonneg)
  1187               done
  1188             also have "\<dots> \<le> (SUP n. ereal (\<Sum>x<n. assign y x z))"
  1189               by(rule SUP_upper) simp
  1190             finally show "ereal (\<Sum>x<n. ?pp y x) \<le> \<dots> + setsum (?rr y) {..<z}" 
  1191               by(simp add: ereal_minus(1)[symmetric] ereal_minus_le del: ereal_minus(1))
  1192           qed
  1193           finally show ?thesis
  1194             by(simp add: ivl_disj_un(2)[symmetric] plus_ereal.simps(1)[symmetric] ereal_add_le_add_iff2 del: plus_ereal.simps(1))
  1195         qed
  1196       qed
  1197       finally show "?thesis y z" .
  1198     qed
  1199 
  1200     { fix y x
  1201       have "(\<integral>\<^sup>+ z. assign y x z \<partial>count_space UNIV) = ?pp y x"
  1202       proof(cases "setsum (?pp y) {..<x} = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV")
  1203         case False
  1204         let ?used = "setsum (?pp y) {..<x}"
  1205         have "?used = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space {..<x}"
  1206           by(simp add: nn_integral_count_space_finite max_def)
  1207         also have "\<dots> \<le> \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV"
  1208           by(auto simp add: nn_integral_count_space_indicator indicator_def intro!: nn_integral_mono)
  1209         finally have "?used < \<dots>" using False by auto
  1210         also note eq finally have "?used \<in> dom (find_start y)" by(rule in_dom_find_startI)
  1211         then obtain k where k: "find_start y ?used = Some k" by auto
  1212         let ?f = "\<lambda>z. if z < k then 0 else if z = k then setsum (?rr y) {..k} - ?used else ?rr y z"
  1213         let ?g = "\<lambda>x'. if x' < x then 0 else ?pp y x'"
  1214         have "?pp y x = ?g x" by simp
  1215         also have "?g x \<le> \<integral>\<^sup>+ x'. ?g x' \<partial>count_space UNIV" by(rule nn_integral_ge_point) simp
  1216         also {
  1217           have "?used = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space {..<x}"
  1218             by(simp add: nn_integral_count_space_finite max_def)
  1219           also have "\<dots> = \<integral>\<^sup>+ x'. (if x' < x then ?pp y x' else 0) \<partial>count_space UNIV"
  1220             by(simp add: nn_integral_count_space_indicator indicator_def if_distrib zero_ereal_def cong del: if_cong)
  1221           also have "(\<integral>\<^sup>+ x'. ?g x' \<partial>count_space UNIV) + \<dots> = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV"
  1222             by(subst nn_integral_add[symmetric])(auto intro: nn_integral_cong)
  1223           also note calculation }
  1224         ultimately have "ereal (?pp y x) + ?used \<le> \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV"
  1225           by (metis (no_types, lifting) ereal_add_mono order_refl)
  1226         also note eq
  1227         also have "(\<integral>\<^sup>+ z. ?rr y z \<partial>count_space UNIV) = (\<integral>\<^sup>+ z. ?f z \<partial>count_space UNIV) + (\<integral>\<^sup>+ z. (if z < k then ?rr y z else if z = k then ?used - setsum (?rr y) {..<k} else 0) \<partial>count_space UNIV)"
  1228           using k by(subst nn_integral_add[symmetric])(auto intro!: nn_integral_cong simp add: ivl_disj_un(2)[symmetric] setsum_nonneg dest: find_start_eq_Some_least find_start_eq_Some_above)
  1229         also have "(\<integral>\<^sup>+ z. (if z < k then ?rr y z else if z = k then ?used - setsum (?rr y) {..<k} else 0) \<partial>count_space UNIV) =
  1230           (\<integral>\<^sup>+ z. (if z < k then ?rr y z else if z = k then ?used - setsum (?rr y) {..<k} else 0) \<partial>count_space {..k})"
  1231           by(auto simp add: nn_integral_count_space_indicator indicator_def intro: nn_integral_cong)
  1232         also have "\<dots> = ?used" 
  1233           using k by(auto simp add: nn_integral_count_space_finite max_def ivl_disj_un(2)[symmetric] diff_le_iff setsum_nonneg dest: find_start_eq_Some_least)
  1234         finally have "?pp y x \<le> (\<integral>\<^sup>+ z. ?f z \<partial>count_space UNIV)"
  1235           by(cases "\<integral>\<^sup>+ z. ?f z \<partial>count_space UNIV") simp_all
  1236         then show ?thesis using k
  1237           by(simp add: assign_def nn_integral_assign_aux diff_le_iff find_start_eq_Some_above min_def)
  1238       next
  1239         case True
  1240         have "setsum (?pp y) {..x} = \<integral>\<^sup>+ x. ?pp y x \<partial>count_space {..x}"
  1241           by(simp add: nn_integral_count_space_finite max_def)
  1242         also have "\<dots> \<le> \<integral>\<^sup>+ x. ?pp y x \<partial>count_space UNIV"
  1243           by(auto simp add: nn_integral_count_space_indicator indicator_def intro: nn_integral_mono)
  1244         also have "\<dots> = setsum (?pp y) {..<x}" by(simp add: True)
  1245         finally have "?pp y x = 0" by(simp add: ivl_disj_un(2)[symmetric] eq_iff del: pmf_le_0_iff)
  1246         thus ?thesis
  1247           by(cases "find_start y (setsum (?pp y) {..<x})")(simp_all add: assign_def diff_le_iff find_start_eq_Some_above)
  1248       qed }
  1249     note nn_integral_assign2 = this
  1250 
  1251     def a \<equiv> "embed_pmf (\<lambda>(y, x, z). assign y x z)"
  1252     { fix y x z
  1253       have "assign y x z = pmf a (y, x, z)"
  1254         unfolding a_def
  1255       proof (subst pmf_embed_pmf)
  1256         have "(\<integral>\<^sup>+ x. ereal ((\<lambda>(y, x, z). assign y x z) x) \<partial>count_space UNIV) =
  1257           (\<integral>\<^sup>+ x. ereal ((\<lambda>(y, x, z). assign y x z) x) \<partial>(count_space ((\<lambda>((y, x), z). (y, x, z)) ` (pp \<times> UNIV))))"
  1258           by (force simp add: nn_integral_count_space_indicator pmf_eq_0_set_pmf split: split_indicator
  1259                     intro!: nn_integral_cong assign_eq_0_outside)
  1260         also have "\<dots> = (\<integral>\<^sup>+ x. ereal ((\<lambda>((y, x), z). assign y x z) x) \<partial>(count_space (pp \<times> UNIV)))"
  1261           by (subst nn_integral_bij_count_space[OF inj_on_imp_bij_betw, symmetric])
  1262              (auto simp: inj_on_def intro!: nn_integral_cong)
  1263         also have "\<dots> = (\<integral>\<^sup>+ y. \<integral>\<^sup>+z. ereal ((\<lambda>((y, x), z). assign y x z) (y, z)) \<partial>count_space UNIV \<partial>count_space pp)"
  1264           by (subst sigma_finite_measure.nn_integral_fst)
  1265              (auto simp: pair_measure_countable sigma_finite_measure_count_space_countable)
  1266         also have "\<dots> = (\<integral>\<^sup>+ z. ?pp (fst z) (snd z) \<partial>count_space pp)"
  1267           by (subst nn_integral_assign2[symmetric]) (auto intro!: nn_integral_cong)
  1268         finally show "(\<integral>\<^sup>+ x. ereal ((\<lambda>(y, x, z). assign y x z) x) \<partial>count_space UNIV) = 1"
  1269           by (simp add: nn_integral_pmf emeasure_pmf)
  1270       qed auto }
  1271     note a = this
  1272 
  1273     def pr \<equiv> "map_pmf (\<lambda>(y, x, z). (from_nat_into (A y) x, from_nat_into (B y) z)) a"
  1274 
  1275     have "rel_pmf (R OO S) p r"
  1276     proof
  1277       have pp_eq: "pp = map_pmf (\<lambda>(y, x, z). (y, x)) a"
  1278       proof (rule pmf_eqI)
  1279         fix i
  1280         show "pmf pp i = pmf (map_pmf (\<lambda>(y, x, z). (y, x)) a) i"
  1281           using nn_integral_assign2[of "fst i" "snd i", symmetric]
  1282           by (auto simp add: a nn_integral_pmf' inj_on_def ereal.inject[symmetric] ereal_pmf_map 
  1283                    simp del: ereal.inject intro!: arg_cong2[where f=emeasure])
  1284       qed
  1285       moreover have pq_eq: "pq = map_pmf (\<lambda>(y, x). (from_nat_into (A y) x, y)) pp"
  1286         by (simp add: pp_def map_pmf_comp split_beta A[symmetric] cong: map_pmf_cong)
  1287       ultimately show "map_pmf fst pr = p"
  1288         unfolding p pr_def by (simp add: map_pmf_comp split_beta)
  1289 
  1290       have rr_eq: "rr = map_pmf (\<lambda>(y, x, z). (y, z)) a"
  1291       proof (rule pmf_eqI)
  1292         fix i show "pmf rr i = pmf (map_pmf (\<lambda>(y, x, z). (y, z)) a) i"
  1293           using nn_integral_assign1[of "fst i" "snd i", symmetric]
  1294           by (auto simp add: a nn_integral_pmf' inj_on_def ereal.inject[symmetric] ereal_pmf_map 
  1295                    simp del: ereal.inject intro!: arg_cong2[where f=emeasure])
  1296       qed
  1297       moreover have qr_eq: "qr = map_pmf (\<lambda>(y, z). (y, from_nat_into (B y) z)) rr"
  1298         by (simp add: rr_def map_pmf_comp split_beta B[symmetric] cong: map_pmf_cong)
  1299       ultimately show "map_pmf snd pr = r"
  1300         unfolding r pr_def by (simp add: map_pmf_comp split_beta)
  1301 
  1302       fix x z assume "(x, z) \<in> set_pmf pr"
  1303       then have "\<exists>y. (x, y) \<in> set_pmf pq \<and> (y, z) \<in> set_pmf qr"
  1304         by (force simp add: pp_eq pq_eq rr_eq qr_eq set_map_pmf pr_def image_image)
  1305       with pq qr show "(R OO S) x z"
  1306         by blast
  1307     qed }
  1308   then show "rel_pmf R OO rel_pmf S \<le> rel_pmf (R OO S)"
  1309     by(auto simp add: le_fun_def)
  1310 qed (fact natLeq_card_order natLeq_cinfinite)+
  1311 
  1312 end
  1313