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