merged
authorwenzelm
Thu, 06 Oct 2016 11:27:28 +0200
changeset 64064 f3ac9153bc0d
parent 64019 b8f8fe506585 (diff)
parent 64063 2c5039363ea3 (current diff)
child 64066 666c7475f4f7
child 64068 3a506cb576d3
merged
--- a/CONTRIBUTORS	Thu Oct 06 11:27:03 2016 +0200
+++ b/CONTRIBUTORS	Thu Oct 06 11:27:28 2016 +0200
@@ -6,13 +6,17 @@
 Contributions to this Isabelle version
 --------------------------------------
 
-* January 2016: Florian Haftmann
+* January 2016: Florian Haftmann, TUM
   Abolition of compound operators INFIMUM and SUPREMUM
   for complete lattices.
 
-* March 2016: Florian Haftmann
+* March 2016: Florian Haftmann, TUM
   Abstract factorial rings with unique factorization.
 
+* March 2016: Florian Haftmann, TUM
+  Reworking of the HOL char type as special case of a
+  finite numeral type.
+
 * March 2016: Andreas Lochbihler
   Reasoning support for monotonicity, continuity and
   admissibility in chain-complete partial orders.
@@ -23,6 +27,11 @@
 * June 2016: Andreas Lochbihler
   Formalisation of discrete subprobability distributions.
 
+* June 2016: Florian Haftmann, TUM
+  Improvements to code generation: optional timing measurements,
+  more succint closures for static evaluation, less ambiguities
+  concering Scala implicits.
+
 * July 2016: Daniel Stuewe
   Height-size proofs in HOL/Data_Structures
 
--- a/NEWS	Thu Oct 06 11:27:03 2016 +0200
+++ b/NEWS	Thu Oct 06 11:27:28 2016 +0200
@@ -60,6 +60,9 @@
     introduction and elimination rules after each split rule. As a
     result the subgoal may be split into several subgoals.
 
+* Solve direct: option 'solve_direct_strict_warnings' gives explicit
+  warnings for lemma statements with trivial proofs.
+
 
 *** Prover IDE -- Isabelle/Scala/jEdit ***
 
--- a/src/HOL/Analysis/Analysis.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Analysis.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -10,6 +10,7 @@
   Bounded_Continuous_Function
   Weierstrass_Theorems
   Polytope
+  FurtherTopology
   Poly_Roots
   Conformal_Mappings
   Generalised_Binomial_Theorem
--- a/src/HOL/Analysis/Binary_Product_Measure.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Binary_Product_Measure.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -686,6 +686,53 @@
   show "a \<in> A" and "b \<in> B" by auto
 qed
 
+lemma sets_pair_eq:
+  assumes Ea: "Ea \<subseteq> Pow (space A)" "sets A = sigma_sets (space A) Ea"
+    and Ca: "countable Ca" "Ca \<subseteq> Ea" "\<Union>Ca = space A"
+    and Eb: "Eb \<subseteq> Pow (space B)" "sets B = sigma_sets (space B) Eb"
+    and Cb: "countable Cb" "Cb \<subseteq> Eb" "\<Union>Cb = space B"
+  shows "sets (A \<Otimes>\<^sub>M B) = sets (sigma (space A \<times> space B) { a \<times> b | a b. a \<in> Ea \<and> b \<in> Eb })"
+    (is "_ = sets (sigma ?\<Omega> ?E)")
+proof
+  show "sets (sigma ?\<Omega> ?E) \<subseteq> sets (A \<Otimes>\<^sub>M B)"
+    using Ea(1) Eb(1) by (subst sigma_le_sets) (auto simp: Ea(2) Eb(2))
+  have "?E \<subseteq> Pow ?\<Omega>"
+    using Ea(1) Eb(1) by auto
+  then have E: "a \<in> Ea \<Longrightarrow> b \<in> Eb \<Longrightarrow> a \<times> b \<in> sets (sigma ?\<Omega> ?E)" for a b
+    by auto
+  have "sets (A \<Otimes>\<^sub>M B) \<subseteq> sets (Sup {vimage_algebra ?\<Omega> fst A, vimage_algebra ?\<Omega> snd B})"
+    unfolding sets_pair_eq_sets_fst_snd ..
+  also have "vimage_algebra ?\<Omega> fst A = vimage_algebra ?\<Omega> fst (sigma (space A) Ea)"
+    by (intro vimage_algebra_cong[OF refl refl]) (simp add: Ea)
+  also have "\<dots> = sigma ?\<Omega> {fst -` A \<inter> ?\<Omega> |A. A \<in> Ea}"
+    by (intro Ea vimage_algebra_sigma) auto
+  also have "vimage_algebra ?\<Omega> snd B = vimage_algebra ?\<Omega> snd (sigma (space B) Eb)"
+    by (intro vimage_algebra_cong[OF refl refl]) (simp add: Eb)
+  also have "\<dots> = sigma ?\<Omega> {snd -` A \<inter> ?\<Omega> |A. A \<in> Eb}"
+    by (intro Eb vimage_algebra_sigma) auto
+  also have "{sigma ?\<Omega> {fst -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Ea}, sigma ?\<Omega> {snd -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Eb}} =
+    sigma ?\<Omega> ` {{fst -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Ea}, {snd -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Eb}}"
+    by auto
+  also have "sets (SUP S:{{fst -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Ea}, {snd -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Eb}}. sigma ?\<Omega> S) =
+    sets (sigma ?\<Omega> (\<Union>{{fst -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Ea}, {snd -` Aa \<inter> ?\<Omega> |Aa. Aa \<in> Eb}}))"
+    using Ea(1) Eb(1) by (intro sets_Sup_sigma) auto
+  also have "\<dots> \<subseteq> sets (sigma ?\<Omega> ?E)"
+  proof (subst sigma_le_sets, safe intro!: space_in_measure_of)
+    fix a assume "a \<in> Ea"
+    then have "fst -` a \<inter> ?\<Omega> = (\<Union>b\<in>Cb. a \<times> b)"
+      using Cb(3)[symmetric] Ea(1) by auto
+    then show "fst -` a \<inter> ?\<Omega> \<in> sets (sigma ?\<Omega> ?E)"
+      using Cb \<open>a \<in> Ea\<close> by (auto intro!: sets.countable_UN' E)
+  next
+    fix b assume "b \<in> Eb"
+    then have "snd -` b \<inter> ?\<Omega> = (\<Union>a\<in>Ca. a \<times> b)"
+      using Ca(3)[symmetric] Eb(1) by auto
+    then show "snd -` b \<inter> ?\<Omega> \<in> sets (sigma ?\<Omega> ?E)"
+      using Ca \<open>b \<in> Eb\<close> by (auto intro!: sets.countable_UN' E)
+  qed
+  finally show "sets (A \<Otimes>\<^sub>M B) \<subseteq> sets (sigma ?\<Omega> ?E)" .
+qed
+
 lemma borel_prod:
   "(borel \<Otimes>\<^sub>M borel) = (borel :: ('a::second_countable_topology \<times> 'b::second_countable_topology) measure)"
   (is "?P = ?B")
--- a/src/HOL/Analysis/Bochner_Integration.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Bochner_Integration.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -951,6 +951,10 @@
   unfolding integrable.simps
   by (intro has_bochner_integral_cong_AE arg_cong[where f=Ex] ext)
 
+lemma integrable_cong_AE_imp:
+  "integrable M g \<Longrightarrow> f \<in> borel_measurable M \<Longrightarrow> (AE x in M. g x = f x) \<Longrightarrow> integrable M f"
+  using integrable_cong_AE[of f M g] by (auto simp: eq_commute)
+
 lemma integral_cong:
   "M = N \<Longrightarrow> (\<And>x. x \<in> space N \<Longrightarrow> f x = g x) \<Longrightarrow> integral\<^sup>L M f = integral\<^sup>L N g"
   by (simp cong: has_bochner_integral_cong cong del: if_weak_cong add: lebesgue_integral_def)
@@ -1682,6 +1686,16 @@
   finally show ?thesis .
 qed
 
+lemma nn_integral_eq_integrable:
+  assumes f: "f \<in> M \<rightarrow>\<^sub>M borel" "AE x in M. 0 \<le> f x" and "0 \<le> x"
+  shows "(\<integral>\<^sup>+x. f x \<partial>M) = ennreal x \<longleftrightarrow> (integrable M f \<and> integral\<^sup>L M f = x)"
+proof (safe intro!: nn_integral_eq_integral assms)
+  assume *: "(\<integral>\<^sup>+x. f x \<partial>M) = ennreal x"
+  with integrableI_nn_integral_finite[OF f this] nn_integral_eq_integral[of M f, OF _ f(2)]
+  show "integrable M f" "integral\<^sup>L M f = x"
+    by (simp_all add: * assms integral_nonneg_AE)
+qed
+
 lemma
   fixes f :: "_ \<Rightarrow> _ \<Rightarrow> 'a :: {banach, second_countable_topology}"
   assumes integrable[measurable]: "\<And>i. integrable M (f i)"
@@ -2227,6 +2241,27 @@
   shows "integrable (count_space UNIV) f \<Longrightarrow> integral\<^sup>L (count_space UNIV) f = (\<Sum>x. f x)"
   using sums_integral_count_space_nat by (rule sums_unique)
 
+lemma integrable_bij_count_space:
+  fixes f :: "'a \<Rightarrow> 'b::{banach, second_countable_topology}"
+  assumes g: "bij_betw g A B"
+  shows "integrable (count_space A) (\<lambda>x. f (g x)) \<longleftrightarrow> integrable (count_space B) f"
+  unfolding integrable_iff_bounded by (subst nn_integral_bij_count_space[OF g]) auto
+
+lemma integral_bij_count_space:
+  fixes f :: "'a \<Rightarrow> 'b::{banach, second_countable_topology}"
+  assumes g: "bij_betw g A B"
+  shows "integral\<^sup>L (count_space A) (\<lambda>x. f (g x)) = integral\<^sup>L (count_space B) f"
+  using g[THEN bij_betw_imp_funcset]
+  apply (subst distr_bij_count_space[OF g, symmetric])
+  apply (intro integral_distr[symmetric])
+  apply auto
+  done
+
+lemma has_bochner_integral_count_space_nat:
+  fixes f :: "nat \<Rightarrow> _::{banach,second_countable_topology}"
+  shows "has_bochner_integral (count_space UNIV) f x \<Longrightarrow> f sums x"
+  unfolding has_bochner_integral_iff by (auto intro!: sums_integral_count_space_nat)
+
 subsection \<open>Point measure\<close>
 
 lemma lebesgue_integral_point_measure_finite:
--- a/src/HOL/Analysis/Borel_Space.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Borel_Space.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1500,6 +1500,9 @@
   apply auto
   done
 
+lemma measurable_of_bool[measurable]: "of_bool \<in> count_space UNIV \<rightarrow>\<^sub>M borel"
+  by simp
+
 subsection "Borel space on the extended reals"
 
 lemma borel_measurable_ereal[measurable (raw)]:
@@ -1909,6 +1912,56 @@
   shows "mono f \<Longrightarrow> f \<in> borel_measurable borel"
   using borel_measurable_mono_on_fnc[of f UNIV] by (simp add: mono_def mono_on_def)
 
+lemma measurable_bdd_below_real[measurable (raw)]:
+  fixes F :: "'a \<Rightarrow> 'i \<Rightarrow> real"
+  assumes [simp]: "countable I" and [measurable]: "\<And>i. i \<in> I \<Longrightarrow> F i \<in> M \<rightarrow>\<^sub>M borel"
+  shows "Measurable.pred M (\<lambda>x. bdd_below ((\<lambda>i. F i x)`I))"
+proof (subst measurable_cong)
+  show "bdd_below ((\<lambda>i. F i x)`I) \<longleftrightarrow> (\<exists>q\<in>\<int>. \<forall>i\<in>I. q \<le> F i x)" for x
+    by (auto simp: bdd_below_def intro!: bexI[of _ "of_int (floor _)"] intro: order_trans of_int_floor_le)
+  show "Measurable.pred M (\<lambda>w. \<exists>q\<in>\<int>. \<forall>i\<in>I. q \<le> F i w)"
+    using countable_int by measurable
+qed
+
+lemma borel_measurable_cINF_real[measurable (raw)]:
+  fixes F :: "_ \<Rightarrow> _ \<Rightarrow> real"
+  assumes [simp]: "countable I"
+  assumes F[measurable]: "\<And>i. i \<in> I \<Longrightarrow> F i \<in> borel_measurable M"
+  shows "(\<lambda>x. INF i:I. F i x) \<in> borel_measurable M"
+proof (rule measurable_piecewise_restrict)
+  let ?\<Omega> = "{x\<in>space M. bdd_below ((\<lambda>i. F i x)`I)}"
+  show "countable {?\<Omega>, - ?\<Omega>}" "space M \<subseteq> \<Union>{?\<Omega>, - ?\<Omega>}" "\<And>X. X \<in> {?\<Omega>, - ?\<Omega>} \<Longrightarrow> X \<inter> space M \<in> sets M"
+    by auto
+  fix X assume "X \<in> {?\<Omega>, - ?\<Omega>}" then show "(\<lambda>x. INF i:I. F i x) \<in> borel_measurable (restrict_space M X)"
+  proof safe
+    show "(\<lambda>x. INF i:I. F i x) \<in> borel_measurable (restrict_space M ?\<Omega>)"
+      by (intro borel_measurable_cINF measurable_restrict_space1 F)
+         (auto simp: space_restrict_space)
+    show "(\<lambda>x. INF i:I. F i x) \<in> borel_measurable (restrict_space M (-?\<Omega>))"
+    proof (subst measurable_cong)
+      fix x assume "x \<in> space (restrict_space M (-?\<Omega>))"
+      then have "\<not> (\<forall>i\<in>I. - F i x \<le> y)" for y
+        by (auto simp: space_restrict_space bdd_above_def bdd_above_uminus[symmetric])
+      then show "(INF i:I. F i x) = - (THE x. False)"
+        by (auto simp: space_restrict_space Inf_real_def Sup_real_def Least_def simp del: Set.ball_simps(10))
+    qed simp
+  qed
+qed
+
+lemma borel_Ici: "borel = sigma UNIV (range (\<lambda>x::real. {x ..}))"
+proof (safe intro!: borel_eq_sigmaI1[OF borel_Iio])
+  fix x :: real
+  have eq: "{..<x} = space (sigma UNIV (range atLeast)) - {x ..}"
+    by auto
+  show "{..<x} \<in> sets (sigma UNIV (range atLeast))"
+    unfolding eq by (intro sets.compl_sets) auto
+qed auto
+
+lemma borel_measurable_pred_less[measurable (raw)]:
+  fixes f :: "'a \<Rightarrow> 'b::{second_countable_topology, linorder_topology}"
+  shows "f \<in> borel_measurable M \<Longrightarrow> g \<in> borel_measurable M \<Longrightarrow> Measurable.pred M (\<lambda>w. f w < g w)"
+  unfolding Measurable.pred_def by (rule borel_measurable_less)
+
 no_notation
   eucl_less (infix "<e" 50)
 
--- a/src/HOL/Analysis/Brouwer_Fixpoint.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Brouwer_Fixpoint.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1975,7 +1975,7 @@
 
 text \<open>So we get the no-retraction theorem.\<close>
 
-lemma no_retraction_cball:
+theorem no_retraction_cball:
   fixes a :: "'a::euclidean_space"
   assumes "e > 0"
   shows "\<not> (frontier (cball a e) retract_of (cball a e))"
@@ -2001,6 +2001,26 @@
     using x assms by auto
 qed
 
+corollary contractible_sphere:
+  fixes a :: "'a::euclidean_space"
+  shows "contractible(sphere a r) \<longleftrightarrow> r \<le> 0"
+proof (cases "0 < r")
+  case True
+  then show ?thesis
+    unfolding contractible_def nullhomotopic_from_sphere_extension
+    using no_retraction_cball [OF True, of a]
+    by (auto simp: retract_of_def retraction_def)
+next
+  case False
+  then show ?thesis
+    unfolding contractible_def nullhomotopic_from_sphere_extension
+    apply (simp add: not_less)
+    apply (rule_tac x=id in exI)
+    apply (auto simp: continuous_on_def)
+    apply (meson dist_not_less_zero le_less less_le_trans)
+    done
+qed
+
 subsection\<open>Retractions\<close>
 
 lemma retraction:
--- a/src/HOL/Analysis/Convex_Euclidean_Space.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Convex_Euclidean_Space.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -7495,6 +7495,11 @@
     by (auto simp: closed_segment_commute)
 qed
 
+lemma open_segment_eq_real_ivl:
+  fixes a b::real
+  shows "open_segment a b = (if a \<le> b then {a<..<b} else {b<..<a})"
+by (auto simp: closed_segment_eq_real_ivl open_segment_def split: if_split_asm)
+
 lemma closed_segment_real_eq:
   fixes u::real shows "closed_segment u v = (\<lambda>x. (v - u) * x + u) ` {0..1}"
   by (simp add: add.commute [of u] image_affinity_atLeastAtMost [where c=u] closed_segment_eq_real_ivl)
@@ -11353,6 +11358,81 @@
 by (metis connected_segment convex_contains_segment ends_in_segment imageI
            is_interval_connected_1 is_interval_convex connected_continuous_image [OF assms])
 
+lemma continuous_injective_image_segment_1:
+  fixes f :: "'a::euclidean_space \<Rightarrow> real"
+  assumes contf: "continuous_on (closed_segment a b) f"
+      and injf: "inj_on f (closed_segment a b)"
+  shows "f ` (closed_segment a b) = closed_segment (f a) (f b)"
+proof
+  show "closed_segment (f a) (f b) \<subseteq> f ` closed_segment a b"
+    by (metis subset_continuous_image_segment_1 contf)
+  show "f ` closed_segment a b \<subseteq> closed_segment (f a) (f b)"
+  proof (cases "a = b")
+    case True
+    then show ?thesis by auto
+  next
+    case False
+    then have fnot: "f a \<noteq> f b"
+      using inj_onD injf by fastforce
+    moreover
+    have "f a \<notin> open_segment (f c) (f b)" if c: "c \<in> closed_segment a b" for c
+    proof (clarsimp simp add: open_segment_def)
+      assume fa: "f a \<in> closed_segment (f c) (f b)"
+      moreover have "closed_segment (f c) (f b) \<subseteq> f ` closed_segment c b"
+        by (meson closed_segment_subset contf continuous_on_subset convex_closed_segment ends_in_segment(2) subset_continuous_image_segment_1 that)
+      ultimately have "f a \<in> f ` closed_segment c b"
+        by blast
+      then have a: "a \<in> closed_segment c b"
+        by (meson ends_in_segment inj_on_image_mem_iff_alt injf subset_closed_segment that)
+      have cb: "closed_segment c b \<subseteq> closed_segment a b"
+        by (simp add: closed_segment_subset that)
+      show "f a = f c"
+      proof (rule between_antisym)
+        show "between (f c, f b) (f a)"
+          by (simp add: between_mem_segment fa)
+        show "between (f a, f b) (f c)"
+          by (metis a cb between_antisym between_mem_segment between_triv1 subset_iff)
+      qed
+    qed
+    moreover
+    have "f b \<notin> open_segment (f a) (f c)" if c: "c \<in> closed_segment a b" for c
+    proof (clarsimp simp add: open_segment_def fnot eq_commute)
+      assume fb: "f b \<in> closed_segment (f a) (f c)"
+      moreover have "closed_segment (f a) (f c) \<subseteq> f ` closed_segment a c"
+        by (meson contf continuous_on_subset ends_in_segment(1) subset_closed_segment subset_continuous_image_segment_1 that)
+      ultimately have "f b \<in> f ` closed_segment a c"
+        by blast
+      then have b: "b \<in> closed_segment a c"
+        by (meson ends_in_segment inj_on_image_mem_iff_alt injf subset_closed_segment that)
+      have ca: "closed_segment a c \<subseteq> closed_segment a b"
+        by (simp add: closed_segment_subset that)
+      show "f b = f c"
+      proof (rule between_antisym)
+        show "between (f c, f a) (f b)"
+          by (simp add: between_commute between_mem_segment fb)
+        show "between (f b, f a) (f c)"
+          by (metis b between_antisym between_commute between_mem_segment between_triv2 that)
+      qed
+    qed
+    ultimately show ?thesis
+      by (force simp: closed_segment_eq_real_ivl open_segment_eq_real_ivl split: if_split_asm)
+  qed
+qed
+
+lemma continuous_injective_image_open_segment_1:
+  fixes f :: "'a::euclidean_space \<Rightarrow> real"
+  assumes contf: "continuous_on (closed_segment a b) f"
+      and injf: "inj_on f (closed_segment a b)"
+    shows "f ` (open_segment a b) = open_segment (f a) (f b)"
+proof -
+  have "f ` (open_segment a b) = f ` (closed_segment a b) - {f a, f b}"
+    by (metis (no_types, hide_lams) empty_subsetI ends_in_segment image_insert image_is_empty inj_on_image_set_diff injf insert_subset open_segment_def segment_open_subset_closed)
+  also have "... = open_segment (f a) (f b)"
+    using continuous_injective_image_segment_1 [OF assms]
+    by (simp add: open_segment_def inj_on_image_set_diff [OF injf])
+  finally show ?thesis .
+qed
+
 lemma collinear_imp_coplanar:
   "collinear s ==> coplanar s"
 by (metis collinear_affine_hull coplanar_def insert_absorb2)
--- a/src/HOL/Analysis/Derivative.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Derivative.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -2370,6 +2370,16 @@
   shows "(\<exists>c. (f has_real_derivative c) F) = (\<exists>D. (f has_derivative D) F)"
   by (metis has_field_derivative_def has_real_derivative)
 
+lemma has_vector_derivative_cong_ev:
+  assumes *: "eventually (\<lambda>x. x \<in> s \<longrightarrow> f x = g x) (nhds x)" "f x = g x"
+  shows "(f has_vector_derivative f') (at x within s) = (g has_vector_derivative f') (at x within s)"
+  unfolding has_vector_derivative_def has_derivative_def
+  using *
+  apply (cases "at x within s \<noteq> bot")
+  apply (intro refl conj_cong filterlim_cong)
+  apply (auto simp: netlimit_within eventually_at_filter elim: eventually_mono)
+  done
+
 definition deriv :: "('a \<Rightarrow> 'a::real_normed_field) \<Rightarrow> 'a \<Rightarrow> 'a" where
   "deriv f x \<equiv> SOME D. DERIV f x :> D"
 
--- a/src/HOL/Analysis/Finite_Product_Measure.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Finite_Product_Measure.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1196,4 +1196,14 @@
     by (subst emeasure_distr) (auto simp: measurable_pair_iff)
 qed simp
 
+lemma infprod_in_sets[intro]:
+  fixes E :: "nat \<Rightarrow> 'a set" assumes E: "\<And>i. E i \<in> sets (M i)"
+  shows "Pi UNIV E \<in> sets (\<Pi>\<^sub>M i\<in>UNIV::nat set. M i)"
+proof -
+  have "Pi UNIV E = (\<Inter>i. prod_emb UNIV M {..i} (\<Pi>\<^sub>E j\<in>{..i}. E j))"
+    using E E[THEN sets.sets_into_space]
+    by (auto simp: prod_emb_def Pi_iff extensional_def)
+  with E show ?thesis by auto
+qed
+
 end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Analysis/FurtherTopology.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -0,0 +1,1891 @@
+section \<open>Extending Continous Maps, etc..\<close>
+
+text\<open>Ported from HOL Light (moretop.ml) by L C Paulson\<close>
+
+theory "FurtherTopology"
+  imports Equivalence_Lebesgue_Henstock_Integration Weierstrass_Theorems Polytope
+
+begin
+
+subsection\<open>A map from a sphere to a higher dimensional sphere is nullhomotopic\<close>
+
+lemma spheremap_lemma1:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'a::euclidean_space"
+  assumes "subspace S" "subspace T" and dimST: "dim S < dim T"
+      and "S \<subseteq> T"
+      and diff_f: "f differentiable_on sphere 0 1 \<inter> S"
+    shows "f ` (sphere 0 1 \<inter> S) \<noteq> sphere 0 1 \<inter> T"
+proof
+  assume fim: "f ` (sphere 0 1 \<inter> S) = sphere 0 1 \<inter> T"
+  have inS: "\<And>x. \<lbrakk>x \<in> S; x \<noteq> 0\<rbrakk> \<Longrightarrow> (x /\<^sub>R norm x) \<in> S"
+    using subspace_mul \<open>subspace S\<close> by blast
+  have subS01: "(\<lambda>x. x /\<^sub>R norm x) ` (S - {0}) \<subseteq> sphere 0 1 \<inter> S"
+    using \<open>subspace S\<close> subspace_mul by fastforce
+  then have diff_f': "f differentiable_on (\<lambda>x. x /\<^sub>R norm x) ` (S - {0})"
+    by (rule differentiable_on_subset [OF diff_f])
+  define g where "g \<equiv> \<lambda>x. norm x *\<^sub>R f(inverse(norm x) *\<^sub>R x)"
+  have gdiff: "g differentiable_on S - {0}"
+    unfolding g_def
+    by (rule diff_f' derivative_intros differentiable_on_compose [where f=f] | force)+
+  have geq: "g ` (S - {0}) = T - {0}"
+  proof
+    have "g ` (S - {0}) \<subseteq> T"
+      apply (auto simp: g_def subspace_mul [OF \<open>subspace T\<close>])
+      apply (metis (mono_tags, lifting) DiffI subS01 subspace_mul [OF \<open>subspace T\<close>] fim image_subset_iff inf_le2 singletonD)
+      done
+    moreover have "g ` (S - {0}) \<subseteq> UNIV - {0}"
+    proof (clarsimp simp: g_def)
+      fix y
+      assume "y \<in> S" and f0: "f (y /\<^sub>R norm y) = 0"
+      then have "y \<noteq> 0 \<Longrightarrow> y /\<^sub>R norm y \<in> sphere 0 1 \<inter> S"
+        by (auto simp: subspace_mul [OF \<open>subspace S\<close>])
+      then show "y = 0"
+        by (metis fim f0 Int_iff image_iff mem_sphere_0 norm_eq_zero zero_neq_one)
+    qed
+    ultimately show "g ` (S - {0}) \<subseteq> T - {0}"
+      by auto
+  next
+    have *: "sphere 0 1 \<inter> T \<subseteq> f ` (sphere 0 1 \<inter> S)"
+      using fim by (simp add: image_subset_iff)
+    have "x \<in> (\<lambda>x. norm x *\<^sub>R f (x /\<^sub>R norm x)) ` (S - {0})"
+          if "x \<in> T" "x \<noteq> 0" for x
+    proof -
+      have "x /\<^sub>R norm x \<in> T"
+        using \<open>subspace T\<close> subspace_mul that by blast
+      then show ?thesis
+        using * [THEN subsetD, of "x /\<^sub>R norm x"] that apply clarsimp
+        apply (rule_tac x="norm x *\<^sub>R xa" in image_eqI, simp)
+        apply (metis norm_eq_zero right_inverse scaleR_one scaleR_scaleR)
+        using \<open>subspace S\<close> subspace_mul apply force
+        done
+    qed
+    then have "T - {0} \<subseteq> (\<lambda>x. norm x *\<^sub>R f (x /\<^sub>R norm x)) ` (S - {0})"
+      by force
+    then show "T - {0} \<subseteq> g ` (S - {0})"
+      by (simp add: g_def)
+  qed
+  define T' where "T' \<equiv> {y. \<forall>x \<in> T. orthogonal x y}"
+  have "subspace T'"
+    by (simp add: subspace_orthogonal_to_vectors T'_def)
+  have dim_eq: "dim T' + dim T = DIM('a)"
+    using dim_subspace_orthogonal_to_vectors [of T UNIV] \<open>subspace T\<close>
+    by (simp add: dim_UNIV T'_def)
+  have "\<exists>v1 v2. v1 \<in> span T \<and> (\<forall>w \<in> span T. orthogonal v2 w) \<and> x = v1 + v2" for x
+    by (force intro: orthogonal_subspace_decomp_exists [of T x])
+  then obtain p1 p2 where p1span: "p1 x \<in> span T"
+                      and "\<And>w. w \<in> span T \<Longrightarrow> orthogonal (p2 x) w"
+                      and eq: "p1 x + p2 x = x" for x
+    by metis
+  then have p1: "\<And>z. p1 z \<in> T" and ortho: "\<And>w. w \<in> T \<Longrightarrow> orthogonal (p2 x) w" for x
+    using span_eq \<open>subspace T\<close> by blast+
+  then have p2: "\<And>z. p2 z \<in> T'"
+    by (simp add: T'_def orthogonal_commute)
+  have p12_eq: "\<And>x y. \<lbrakk>x \<in> T; y \<in> T'\<rbrakk> \<Longrightarrow> p1(x + y) = x \<and> p2(x + y) = y"
+  proof (rule orthogonal_subspace_decomp_unique [OF eq p1span, where T=T'])
+    show "\<And>x y. \<lbrakk>x \<in> T; y \<in> T'\<rbrakk> \<Longrightarrow> p2 (x + y) \<in> span T'"
+      using span_eq p2 \<open>subspace T'\<close> by blast
+    show "\<And>a b. \<lbrakk>a \<in> T; b \<in> T'\<rbrakk> \<Longrightarrow> orthogonal a b"
+      using T'_def by blast
+  qed (auto simp: span_superset)
+  then have "\<And>c x. p1 (c *\<^sub>R x) = c *\<^sub>R p1 x \<and> p2 (c *\<^sub>R x) = c *\<^sub>R p2 x"
+    by (metis eq \<open>subspace T\<close> \<open>subspace T'\<close> p1 p2 scaleR_add_right subspace_mul)
+  moreover have lin_add: "\<And>x y. p1 (x + y) = p1 x + p1 y \<and> p2 (x + y) = p2 x + p2 y"
+  proof (rule orthogonal_subspace_decomp_unique [OF _ p1span, where T=T'])
+    show "\<And>x y. p1 (x + y) + p2 (x + y) = p1 x + p1 y + (p2 x + p2 y)"
+      by (simp add: add.assoc add.left_commute eq)
+    show  "\<And>a b. \<lbrakk>a \<in> T; b \<in> T'\<rbrakk> \<Longrightarrow> orthogonal a b"
+      using T'_def by blast
+  qed (auto simp: p1span p2 span_superset subspace_add)
+  ultimately have "linear p1" "linear p2"
+    by unfold_locales auto
+  have "(\<lambda>z. g (p1 z)) differentiable_on {x + y |x y. x \<in> S - {0} \<and> y \<in> T'}"
+    apply (rule differentiable_on_compose [where f=g])
+    apply (rule linear_imp_differentiable_on [OF \<open>linear p1\<close>])
+    apply (rule differentiable_on_subset [OF gdiff])
+    using p12_eq \<open>S \<subseteq> T\<close> apply auto
+    done
+  then have diff: "(\<lambda>x. g (p1 x) + p2 x) differentiable_on {x + y |x y. x \<in> S - {0} \<and> y \<in> T'}"
+    by (intro derivative_intros linear_imp_differentiable_on [OF \<open>linear p2\<close>])
+  have "dim {x + y |x y. x \<in> S - {0} \<and> y \<in> T'} \<le> dim {x + y |x y. x \<in> S  \<and> y \<in> T'}"
+    by (blast intro: dim_subset)
+  also have "... = dim S + dim T' - dim (S \<inter> T')"
+    using dim_sums_Int [OF \<open>subspace S\<close> \<open>subspace T'\<close>]
+    by (simp add: algebra_simps)
+  also have "... < DIM('a)"
+    using dimST dim_eq by auto
+  finally have neg: "negligible {x + y |x y. x \<in> S - {0} \<and> y \<in> T'}"
+    by (rule negligible_lowdim)
+  have "negligible ((\<lambda>x. g (p1 x) + p2 x) ` {x + y |x y. x \<in> S - {0} \<and> y \<in> T'})"
+    by (rule negligible_differentiable_image_negligible [OF order_refl neg diff])
+  then have "negligible {x + y |x y. x \<in> g ` (S - {0}) \<and> y \<in> T'}"
+  proof (rule negligible_subset)
+    have "\<lbrakk>t' \<in> T'; s \<in> S; s \<noteq> 0\<rbrakk>
+          \<Longrightarrow> g s + t' \<in> (\<lambda>x. g (p1 x) + p2 x) `
+                         {x + t' |x t'. x \<in> S \<and> x \<noteq> 0 \<and> t' \<in> T'}" for t' s
+      apply (rule_tac x="s + t'" in image_eqI)
+      using \<open>S \<subseteq> T\<close> p12_eq by auto
+    then show "{x + y |x y. x \<in> g ` (S - {0}) \<and> y \<in> T'}
+          \<subseteq> (\<lambda>x. g (p1 x) + p2 x) ` {x + y |x y. x \<in> S - {0} \<and> y \<in> T'}"
+      by auto
+  qed
+  moreover have "- T' \<subseteq> {x + y |x y. x \<in> g ` (S - {0}) \<and> y \<in> T'}"
+  proof clarsimp
+    fix z assume "z \<notin> T'"
+    show "\<exists>x y. z = x + y \<and> x \<in> g ` (S - {0}) \<and> y \<in> T'"
+      apply (rule_tac x="p1 z" in exI)
+      apply (rule_tac x="p2 z" in exI)
+      apply (simp add: p1 eq p2 geq)
+      by (metis \<open>z \<notin> T'\<close> add.left_neutral eq p2)
+  qed
+  ultimately have "negligible (-T')"
+    using negligible_subset by blast
+  moreover have "negligible T'"
+    using negligible_lowdim
+    by (metis add.commute assms(3) diff_add_inverse2 diff_self_eq_0 dim_eq le_add1 le_antisym linordered_semidom_class.add_diff_inverse not_less0)
+  ultimately have  "negligible (-T' \<union> T')"
+    by (metis negligible_Un_eq)
+  then show False
+    using negligible_Un_eq non_negligible_UNIV by simp
+qed
+
+
+lemma spheremap_lemma2:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'a::euclidean_space"
+  assumes ST: "subspace S" "subspace T" "dim S < dim T"
+      and "S \<subseteq> T"
+      and contf: "continuous_on (sphere 0 1 \<inter> S) f"
+      and fim: "f ` (sphere 0 1 \<inter> S) \<subseteq> sphere 0 1 \<inter> T"
+    shows "\<exists>c. homotopic_with (\<lambda>x. True) (sphere 0 1 \<inter> S) (sphere 0 1 \<inter> T) f (\<lambda>x. c)"
+proof -
+  have [simp]: "\<And>x. \<lbrakk>norm x = 1; x \<in> S\<rbrakk> \<Longrightarrow> norm (f x) = 1"
+    using fim by (simp add: image_subset_iff)
+  have "compact (sphere 0 1 \<inter> S)"
+    by (simp add: \<open>subspace S\<close> closed_subspace compact_Int_closed)
+  then obtain g where pfg: "polynomial_function g" and gim: "g ` (sphere 0 1 \<inter> S) \<subseteq> T"
+                and g12: "\<And>x. x \<in> sphere 0 1 \<inter> S \<Longrightarrow> norm(f x - g x) < 1/2"
+    apply (rule Stone_Weierstrass_polynomial_function_subspace [OF _ contf _ \<open>subspace T\<close>, of "1/2"])
+    using fim apply auto
+    done
+  have gnz: "g x \<noteq> 0" if "x \<in> sphere 0 1 \<inter> S" for x
+  proof -
+    have "norm (f x) = 1"
+      using fim that by (simp add: image_subset_iff)
+    then show ?thesis
+      using g12 [OF that] by auto
+  qed
+  have diffg: "g differentiable_on sphere 0 1 \<inter> S"
+    by (metis pfg differentiable_on_polynomial_function)
+  define h where "h \<equiv> \<lambda>x. inverse(norm(g x)) *\<^sub>R g x"
+  have h: "x \<in> sphere 0 1 \<inter> S \<Longrightarrow> h x \<in> sphere 0 1 \<inter> T" for x
+    unfolding h_def
+    using gnz [of x]
+    by (auto simp: subspace_mul [OF \<open>subspace T\<close>] subsetD [OF gim])
+  have diffh: "h differentiable_on sphere 0 1 \<inter> S"
+    unfolding h_def
+    apply (intro derivative_intros diffg differentiable_on_compose [OF diffg])
+    using gnz apply auto
+    done
+  have homfg: "homotopic_with (\<lambda>z. True) (sphere 0 1 \<inter> S) (T - {0}) f g"
+  proof (rule homotopic_with_linear [OF contf])
+    show "continuous_on (sphere 0 1 \<inter> S) g"
+      using pfg by (simp add: differentiable_imp_continuous_on diffg)
+  next
+    have non0fg: "0 \<notin> closed_segment (f x) (g x)" if "norm x = 1" "x \<in> S" for x
+    proof -
+      have "f x \<in> sphere 0 1"
+        using fim that by (simp add: image_subset_iff)
+      moreover have "norm(f x - g x) < 1/2"
+        apply (rule g12)
+        using that by force
+      ultimately show ?thesis
+        by (auto simp: norm_minus_commute dest: segment_bound)
+    qed
+    show "\<And>x. x \<in> sphere 0 1 \<inter> S \<Longrightarrow> closed_segment (f x) (g x) \<subseteq> T - {0}"
+      apply (simp add: subset_Diff_insert non0fg)
+      apply (simp add: segment_convex_hull)
+      apply (rule hull_minimal)
+       using fim image_eqI gim apply force
+      apply (rule subspace_imp_convex [OF \<open>subspace T\<close>])
+      done
+  qed
+  obtain d where d: "d \<in> (sphere 0 1 \<inter> T) - h ` (sphere 0 1 \<inter> S)"
+    using h spheremap_lemma1 [OF ST \<open>S \<subseteq> T\<close> diffh] by force
+  then have non0hd: "0 \<notin> closed_segment (h x) (- d)" if "norm x = 1" "x \<in> S" for x
+    using midpoint_between [of 0 "h x" "-d"] that h [of x]
+    by (auto simp: between_mem_segment midpoint_def)
+  have conth: "continuous_on (sphere 0 1 \<inter> S) h"
+    using differentiable_imp_continuous_on diffh by blast
+  have hom_hd: "homotopic_with (\<lambda>z. True) (sphere 0 1 \<inter> S) (T - {0}) h (\<lambda>x. -d)"
+    apply (rule homotopic_with_linear [OF conth continuous_on_const])
+    apply (simp add: subset_Diff_insert non0hd)
+    apply (simp add: segment_convex_hull)
+    apply (rule hull_minimal)
+     using h d apply (force simp: subspace_neg [OF \<open>subspace T\<close>])
+    apply (rule subspace_imp_convex [OF \<open>subspace T\<close>])
+    done
+  have conT0: "continuous_on (T - {0}) (\<lambda>y. inverse(norm y) *\<^sub>R y)"
+    by (intro continuous_intros) auto
+  have sub0T: "(\<lambda>y. y /\<^sub>R norm y) ` (T - {0}) \<subseteq> sphere 0 1 \<inter> T"
+    by (fastforce simp: assms(2) subspace_mul)
+  obtain c where homhc: "homotopic_with (\<lambda>z. True) (sphere 0 1 \<inter> S) (sphere 0 1 \<inter> T) h (\<lambda>x. c)"
+    apply (rule_tac c="-d" in that)
+    apply (rule homotopic_with_eq)
+       apply (rule homotopic_compose_continuous_left [OF hom_hd conT0 sub0T])
+    using d apply (auto simp: h_def)
+    done
+  show ?thesis
+    apply (rule_tac x=c in exI)
+    apply (rule homotopic_with_trans [OF _ homhc])
+    apply (rule homotopic_with_eq)
+       apply (rule homotopic_compose_continuous_left [OF homfg conT0 sub0T])
+      apply (auto simp: h_def)
+    done
+qed
+
+
+lemma spheremap_lemma3:
+  assumes "bounded S" "convex S" "subspace U" and affSU: "aff_dim S \<le> dim U"
+  obtains T where "subspace T" "T \<subseteq> U" "S \<noteq> {} \<Longrightarrow> aff_dim T = aff_dim S"
+                  "(rel_frontier S) homeomorphic (sphere 0 1 \<inter> T)"
+proof (cases "S = {}")
+  case True
+  with \<open>subspace U\<close> subspace_0 show ?thesis
+    by (rule_tac T = "{0}" in that) auto
+next
+  case False
+  then obtain a where "a \<in> S"
+    by auto
+  then have affS: "aff_dim S = int (dim ((\<lambda>x. -a+x) ` S))"
+    by (metis hull_inc aff_dim_eq_dim)
+  with affSU have "dim ((\<lambda>x. -a+x) ` S) \<le> dim U"
+    by linarith
+  with choose_subspace_of_subspace
+  obtain T where "subspace T" "T \<subseteq> span U" and dimT: "dim T = dim ((\<lambda>x. -a+x) ` S)" .
+  show ?thesis
+  proof (rule that [OF \<open>subspace T\<close>])
+    show "T \<subseteq> U"
+      using span_eq \<open>subspace U\<close> \<open>T \<subseteq> span U\<close> by blast
+    show "aff_dim T = aff_dim S"
+      using dimT \<open>subspace T\<close> affS aff_dim_subspace by fastforce
+    show "rel_frontier S homeomorphic sphere 0 1 \<inter> T"
+    proof -
+      have "aff_dim (ball 0 1 \<inter> T) = aff_dim (T)"
+        by (metis IntI interior_ball \<open>subspace T\<close> aff_dim_convex_Int_nonempty_interior centre_in_ball empty_iff inf_commute subspace_0 subspace_imp_convex zero_less_one)
+      then have affS_eq: "aff_dim S = aff_dim (ball 0 1 \<inter> T)"
+        using \<open>aff_dim T = aff_dim S\<close> by simp
+      have "rel_frontier S homeomorphic rel_frontier(ball 0 1 \<inter> T)"
+        apply (rule homeomorphic_rel_frontiers_convex_bounded_sets [OF \<open>convex S\<close> \<open>bounded S\<close>])
+          apply (simp add: \<open>subspace T\<close> convex_Int subspace_imp_convex)
+         apply (simp add: bounded_Int)
+        apply (rule affS_eq)
+        done
+      also have "... = frontier (ball 0 1) \<inter> T"
+        apply (rule convex_affine_rel_frontier_Int [OF convex_ball])
+         apply (simp add: \<open>subspace T\<close> subspace_imp_affine)
+        using \<open>subspace T\<close> subspace_0 by force
+      also have "... = sphere 0 1 \<inter> T"
+        by auto
+      finally show ?thesis .
+    qed
+  qed
+qed
+
+
+proposition inessential_spheremap_lowdim_gen:
+  fixes f :: "'M::euclidean_space \<Rightarrow> 'a::euclidean_space"
+  assumes "convex S" "bounded S" "convex T" "bounded T"
+      and affST: "aff_dim S < aff_dim T"
+      and contf: "continuous_on (rel_frontier S) f"
+      and fim: "f ` (rel_frontier S) \<subseteq> rel_frontier T"
+  obtains c where "homotopic_with (\<lambda>z. True) (rel_frontier S) (rel_frontier T) f (\<lambda>x. c)"
+proof (cases "S = {}")
+  case True
+  then show ?thesis
+    by (simp add: that)
+next
+  case False
+  then show ?thesis
+  proof (cases "T = {}")
+    case True
+    then show ?thesis
+      using fim that by auto
+  next
+    case False
+    obtain T':: "'a set"
+      where "subspace T'" and affT': "aff_dim T' = aff_dim T"
+        and homT: "rel_frontier T homeomorphic sphere 0 1 \<inter> T'"
+      apply (rule spheremap_lemma3 [OF \<open>bounded T\<close> \<open>convex T\<close> subspace_UNIV, where 'b='a])
+       apply (simp add: dim_UNIV aff_dim_le_DIM)
+      using \<open>T \<noteq> {}\<close> by blast
+    with homeomorphic_imp_homotopy_eqv
+    have relT: "sphere 0 1 \<inter> T'  homotopy_eqv rel_frontier T"
+      using homotopy_eqv_sym by blast
+    have "aff_dim S \<le> int (dim T')"
+      using affT' \<open>subspace T'\<close> affST aff_dim_subspace by force
+    with spheremap_lemma3 [OF \<open>bounded S\<close> \<open>convex S\<close> \<open>subspace T'\<close>] \<open>S \<noteq> {}\<close>
+    obtain S':: "'a set" where "subspace S'" "S' \<subseteq> T'"
+       and affS': "aff_dim S' = aff_dim S"
+       and homT: "rel_frontier S homeomorphic sphere 0 1 \<inter> S'"
+        by metis
+    with homeomorphic_imp_homotopy_eqv
+    have relS: "sphere 0 1 \<inter> S'  homotopy_eqv rel_frontier S"
+      using homotopy_eqv_sym by blast
+    have dimST': "dim S' < dim T'"
+      by (metis \<open>S' \<subseteq> T'\<close> \<open>subspace S'\<close> \<open>subspace T'\<close> affS' affST affT' less_irrefl not_le subspace_dim_equal)
+    have "\<exists>c. homotopic_with (\<lambda>z. True) (rel_frontier S) (rel_frontier T) f (\<lambda>x. c)"
+      apply (rule homotopy_eqv_homotopic_triviality_null_imp [OF relT contf fim])
+      apply (rule homotopy_eqv_cohomotopic_triviality_null[OF relS, THEN iffD1, rule_format])
+       apply (metis dimST' \<open>subspace S'\<close>  \<open>subspace T'\<close>  \<open>S' \<subseteq> T'\<close> spheremap_lemma2, blast)
+      done
+    with that show ?thesis by blast
+  qed
+qed
+
+lemma inessential_spheremap_lowdim:
+  fixes f :: "'M::euclidean_space \<Rightarrow> 'a::euclidean_space"
+  assumes
+   "DIM('M) < DIM('a)" and f: "continuous_on (sphere a r) f" "f ` (sphere a r) \<subseteq> (sphere b s)"
+   obtains c where "homotopic_with (\<lambda>z. True) (sphere a r) (sphere b s) f (\<lambda>x. c)"
+proof (cases "s \<le> 0")
+  case True then show ?thesis
+    by (meson nullhomotopic_into_contractible f contractible_sphere that)
+next
+  case False
+  show ?thesis
+  proof (cases "r \<le> 0")
+    case True then show ?thesis
+      by (meson f nullhomotopic_from_contractible contractible_sphere that)
+  next
+    case False
+    with \<open>~ s \<le> 0\<close> have "r > 0" "s > 0" by auto
+    show ?thesis
+      apply (rule inessential_spheremap_lowdim_gen [of "cball a r" "cball b s" f])
+      using  \<open>0 < r\<close> \<open>0 < s\<close> assms(1)
+             apply (simp_all add: f aff_dim_cball)
+      using that by blast
+  qed
+qed
+
+
+
+subsection\<open> Some technical lemmas about extending maps from cell complexes.\<close>
+
+lemma extending_maps_Union_aux:
+  assumes fin: "finite \<F>"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> closed S"
+      and "\<And>S T. \<lbrakk>S \<in> \<F>; T \<in> \<F>; S \<noteq> T\<rbrakk> \<Longrightarrow> S \<inter> T \<subseteq> K"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> \<exists>g. continuous_on S g \<and> g ` S \<subseteq> T \<and> (\<forall>x \<in> S \<inter> K. g x = h x)"
+   shows "\<exists>g. continuous_on (\<Union>\<F>) g \<and> g ` (\<Union>\<F>) \<subseteq> T \<and> (\<forall>x \<in> \<Union>\<F> \<inter> K. g x = h x)"
+using assms
+proof (induction \<F>)
+  case empty show ?case by simp
+next
+  case (insert S \<F>)
+  then obtain f where contf: "continuous_on (S) f" and fim: "f ` S \<subseteq> T" and feq: "\<forall>x \<in> S \<inter> K. f x = h x"
+    by (meson insertI1)
+  obtain g where contg: "continuous_on (\<Union>\<F>) g" and gim: "g ` \<Union>\<F> \<subseteq> T" and geq: "\<forall>x \<in> \<Union>\<F> \<inter> K. g x = h x"
+    using insert by auto
+  have fg: "f x = g x" if "x \<in> T" "T \<in> \<F>" "x \<in> S" for x T
+  proof -
+    have "T \<inter> S \<subseteq> K \<or> S = T"
+      using that by (metis (no_types) insert.prems(2) insertCI)
+    then show ?thesis
+      using UnionI feq geq \<open>S \<notin> \<F>\<close> subsetD that by fastforce
+  qed
+  show ?case
+    apply (rule_tac x="\<lambda>x. if x \<in> S then f x else g x" in exI, simp)
+    apply (intro conjI continuous_on_cases)
+    apply (simp_all add: insert closed_Union contf contg)
+    using fim gim feq geq
+    apply (force simp: insert closed_Union contf contg inf_commute intro: fg)+
+    done
+qed
+
+lemma extending_maps_Union:
+  assumes fin: "finite \<F>"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> \<exists>g. continuous_on S g \<and> g ` S \<subseteq> T \<and> (\<forall>x \<in> S \<inter> K. g x = h x)"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> closed S"
+      and K: "\<And>X Y. \<lbrakk>X \<in> \<F>; Y \<in> \<F>; ~ X \<subseteq> Y; ~ Y \<subseteq> X\<rbrakk> \<Longrightarrow> X \<inter> Y \<subseteq> K"
+    shows "\<exists>g. continuous_on (\<Union>\<F>) g \<and> g ` (\<Union>\<F>) \<subseteq> T \<and> (\<forall>x \<in> \<Union>\<F> \<inter> K. g x = h x)"
+apply (simp add: Union_maximal_sets [OF fin, symmetric])
+apply (rule extending_maps_Union_aux)
+apply (simp_all add: Union_maximal_sets [OF fin] assms)
+by (metis K psubsetI)
+
+
+lemma extend_map_lemma:
+  assumes "finite \<F>" "\<G> \<subseteq> \<F>" "convex T" "bounded T"
+      and poly: "\<And>X. X \<in> \<F> \<Longrightarrow> polytope X"
+      and aff: "\<And>X. X \<in> \<F> - \<G> \<Longrightarrow> aff_dim X < aff_dim T"
+      and face: "\<And>S T. \<lbrakk>S \<in> \<F>; T \<in> \<F>\<rbrakk> \<Longrightarrow> (S \<inter> T) face_of S \<and> (S \<inter> T) face_of T"
+      and contf: "continuous_on (\<Union>\<G>) f" and fim: "f ` (\<Union>\<G>) \<subseteq> rel_frontier T"
+  obtains g where "continuous_on (\<Union>\<F>) g" "g ` (\<Union>\<F>) \<subseteq> rel_frontier T" "\<And>x. x \<in> \<Union>\<G> \<Longrightarrow> g x = f x"
+proof (cases "\<F> - \<G> = {}")
+  case True
+  then have "\<Union>\<F> \<subseteq> \<Union>\<G>"
+    by (simp add: Union_mono)
+  then show ?thesis
+    apply (rule_tac g=f in that)
+      using contf continuous_on_subset apply blast
+     using fim apply blast
+    by simp
+next
+  case False
+  then have "0 \<le> aff_dim T"
+    by (metis aff aff_dim_empty aff_dim_geq aff_dim_negative_iff all_not_in_conv not_less)
+  then obtain i::nat where i: "int i = aff_dim T"
+    by (metis nonneg_eq_int)
+  have Union_empty_eq: "\<Union>{D. D = {} \<and> P D} = {}" for P :: "'a set \<Rightarrow> bool"
+    by auto
+  have extendf: "\<exists>g. continuous_on (\<Union>(\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < i})) g \<and>
+                     g ` (\<Union> (\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < i})) \<subseteq> rel_frontier T \<and>
+                     (\<forall>x \<in> \<Union>\<G>. g x = f x)"
+       if "i \<le> aff_dim T" for i::nat
+  using that
+  proof (induction i)
+    case 0 then show ?case
+      apply (simp add: Union_empty_eq)
+      apply (rule_tac x=f in exI)
+      apply (intro conjI)
+      using contf continuous_on_subset apply blast
+      using fim apply blast
+      by simp
+  next
+    case (Suc p)
+    with \<open>bounded T\<close> have "rel_frontier T \<noteq> {}"
+      by (auto simp: rel_frontier_eq_empty affine_bounded_eq_lowdim [of T])
+    then obtain t where t: "t \<in> rel_frontier T" by auto
+    have ple: "int p \<le> aff_dim T" using Suc.prems by force
+    obtain h where conth: "continuous_on (\<Union>(\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p})) h"
+               and him: "h ` (\<Union> (\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p}))
+                         \<subseteq> rel_frontier T"
+               and heq: "\<And>x. x \<in> \<Union>\<G> \<Longrightarrow> h x = f x"
+      using Suc.IH [OF ple] by auto
+    let ?Faces = "{D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D \<le> p}"
+    have extendh: "\<exists>g. continuous_on D g \<and>
+                       g ` D \<subseteq> rel_frontier T \<and>
+                       (\<forall>x \<in> D \<inter> \<Union>(\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p}). g x = h x)"
+      if D: "D \<in> \<G> \<union> ?Faces" for D
+    proof (cases "D \<subseteq> \<Union>(\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p})")
+      case True
+      then show ?thesis
+        apply (rule_tac x=h in exI)
+        apply (intro conjI)
+        apply (blast intro: continuous_on_subset [OF conth])
+        using him apply blast
+        by simp
+    next
+      case False
+      note notDsub = False
+      show ?thesis
+      proof (cases "\<exists>a. D = {a}")
+        case True
+        then obtain a where "D = {a}" by auto
+        with notDsub t show ?thesis
+          by (rule_tac x="\<lambda>x. t" in exI) simp
+      next
+        case False
+        have "D \<noteq> {}" using notDsub by auto
+        have Dnotin: "D \<notin> \<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p}"
+          using notDsub by auto
+        then have "D \<notin> \<G>" by simp
+        have "D \<in> ?Faces - {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < p}"
+          using Dnotin that by auto
+        then obtain C where "C \<in> \<F>" "D face_of C" and affD: "aff_dim D = int p"
+          by auto
+        then have "bounded D"
+          using face_of_polytope_polytope poly polytope_imp_bounded by blast
+        then have [simp]: "\<not> affine D"
+          using affine_bounded_eq_trivial False \<open>D \<noteq> {}\<close> \<open>bounded D\<close> by blast
+        have "{F. F facet_of D} \<subseteq> {E. E face_of C \<and> aff_dim E < int p}"
+          apply clarify
+          apply (metis \<open>D face_of C\<close> affD eq_iff face_of_trans facet_of_def zle_diff1_eq)
+          done
+        moreover have "polyhedron D"
+          using \<open>C \<in> \<F>\<close> \<open>D face_of C\<close> face_of_polytope_polytope poly polytope_imp_polyhedron by auto
+        ultimately have relf_sub: "rel_frontier D \<subseteq> \<Union> {E. E face_of C \<and> aff_dim E < p}"
+          by (simp add: rel_frontier_of_polyhedron Union_mono)
+        then have him_relf: "h ` rel_frontier D \<subseteq> rel_frontier T"
+          using \<open>C \<in> \<F>\<close> him by blast
+        have "convex D"
+          by (simp add: \<open>polyhedron D\<close> polyhedron_imp_convex)
+        have affD_lessT: "aff_dim D < aff_dim T"
+          using Suc.prems affD by linarith
+        have contDh: "continuous_on (rel_frontier D) h"
+          using \<open>C \<in> \<F>\<close> relf_sub by (blast intro: continuous_on_subset [OF conth])
+        then have *: "(\<exists>c. homotopic_with (\<lambda>x. True) (rel_frontier D) (rel_frontier T) h (\<lambda>x. c)) =
+                      (\<exists>g. continuous_on UNIV g \<and>  range g \<subseteq> rel_frontier T \<and>
+                           (\<forall>x\<in>rel_frontier D. g x = h x))"
+          apply (rule nullhomotopic_into_rel_frontier_extension [OF closed_rel_frontier])
+          apply (simp_all add: assms rel_frontier_eq_empty him_relf)
+          done
+        have "(\<exists>c. homotopic_with (\<lambda>x. True) (rel_frontier D)
+              (rel_frontier T) h (\<lambda>x. c))"
+          by (metis inessential_spheremap_lowdim_gen
+                 [OF \<open>convex D\<close> \<open>bounded D\<close> \<open>convex T\<close> \<open>bounded T\<close> affD_lessT contDh him_relf])
+        then obtain g where contg: "continuous_on UNIV g"
+                        and gim: "range g \<subseteq> rel_frontier T"
+                        and gh: "\<And>x. x \<in> rel_frontier D \<Longrightarrow> g x = h x"
+          by (metis *)
+        have "D \<inter> E \<subseteq> rel_frontier D"
+             if "E \<in> \<G> \<union> {D. Bex \<F> (op face_of D) \<and> aff_dim D < int p}" for E
+        proof (rule face_of_subset_rel_frontier)
+          show "D \<inter> E face_of D"
+            using that \<open>C \<in> \<F>\<close> \<open>D face_of C\<close> face
+            apply auto
+            apply (meson face_of_Int_subface \<open>\<G> \<subseteq> \<F>\<close> face_of_refl_eq poly polytope_imp_convex subsetD)
+            using face_of_Int_subface apply blast
+            done
+          show "D \<inter> E \<noteq> D"
+            using that notDsub by auto
+        qed
+        then show ?thesis
+          apply (rule_tac x=g in exI)
+          apply (intro conjI ballI)
+            using continuous_on_subset contg apply blast
+           using gim apply blast
+          using gh by fastforce
+      qed
+    qed
+    have intle: "i < 1 + int j \<longleftrightarrow> i \<le> int j" for i j
+      by auto
+    have "finite \<G>"
+      using \<open>finite \<F>\<close> \<open>\<G> \<subseteq> \<F>\<close> rev_finite_subset by blast
+    then have fin: "finite (\<G> \<union> ?Faces)"
+      apply simp
+      apply (rule_tac B = "\<Union>{{D. D face_of C}| C. C \<in> \<F>}" in finite_subset)
+       by (auto simp: \<open>finite \<F>\<close> finite_polytope_faces poly)
+    have clo: "closed S" if "S \<in> \<G> \<union> ?Faces" for S
+      using that \<open>\<G> \<subseteq> \<F>\<close> face_of_polytope_polytope poly polytope_imp_closed by blast
+    have K: "X \<inter> Y \<subseteq> \<Union>(\<G> \<union> {D. \<exists>C\<in>\<F>. D face_of C \<and> aff_dim D < int p})"
+                if "X \<in> \<G> \<union> ?Faces" "Y \<in> \<G> \<union> ?Faces" "~ Y \<subseteq> X" for X Y
+    proof -
+      have ff: "X \<inter> Y face_of X \<and> X \<inter> Y face_of Y"
+        if XY: "X face_of D" "Y face_of E" and DE: "D \<in> \<F>" "E \<in> \<F>" for D E
+        apply (rule face_of_Int_subface [OF _ _ XY])
+        apply (auto simp: face DE)
+        done
+      show ?thesis
+        using that
+        apply auto
+        apply (drule_tac x="X \<inter> Y" in spec, safe)
+        using ff face_of_imp_convex [of X] face_of_imp_convex [of Y]
+        apply (fastforce dest: face_of_aff_dim_lt)
+        by (meson face_of_trans ff)
+    qed
+    obtain g where "continuous_on (\<Union>(\<G> \<union> ?Faces)) g"
+                   "g ` \<Union>(\<G> \<union> ?Faces) \<subseteq> rel_frontier T"
+                   "(\<forall>x \<in> \<Union>(\<G> \<union> ?Faces) \<inter>
+                          \<Union>(\<G> \<union> {D. \<exists>C\<in>\<F>. D face_of C \<and> aff_dim D < p}). g x = h x)"
+      apply (rule exE [OF extending_maps_Union [OF fin extendh clo K]], blast+)
+      done
+    then show ?case
+      apply (simp add: intle local.heq [symmetric], blast)
+      done
+  qed
+  have eq: "\<Union>(\<G> \<union> {D. \<exists>C \<in> \<F>. D face_of C \<and> aff_dim D < i}) = \<Union>\<F>"
+  proof
+    show "\<Union>(\<G> \<union> {D. \<exists>C\<in>\<F>. D face_of C \<and> aff_dim D < int i}) \<subseteq> \<Union>\<F>"
+      apply (rule Union_subsetI)
+      using \<open>\<G> \<subseteq> \<F>\<close> face_of_imp_subset  apply force
+      done
+    show "\<Union>\<F> \<subseteq> \<Union>(\<G> \<union> {D. \<exists>C\<in>\<F>. D face_of C \<and> aff_dim D < i})"
+      apply (rule Union_mono)
+      using face  apply (fastforce simp: aff i)
+      done
+  qed
+  have "int i \<le> aff_dim T" by (simp add: i)
+  then show ?thesis
+    using extendf [of i] unfolding eq by (metis that)
+qed
+
+lemma extend_map_lemma_cofinite0:
+  assumes "finite \<F>"
+      and "pairwise (\<lambda>S T. S \<inter> T \<subseteq> K) \<F>"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> \<exists>a g. a \<notin> U \<and> continuous_on (S - {a}) g \<and> g ` (S - {a}) \<subseteq> T \<and> (\<forall>x \<in> S \<inter> K. g x = h x)"
+      and "\<And>S. S \<in> \<F> \<Longrightarrow> closed S"
+    shows "\<exists>C g. finite C \<and> disjnt C U \<and> card C \<le> card \<F> \<and>
+                 continuous_on (\<Union>\<F> - C) g \<and> g ` (\<Union>\<F> - C) \<subseteq> T
+                  \<and> (\<forall>x \<in> (\<Union>\<F> - C) \<inter> K. g x = h x)"
+  using assms
+proof induction
+  case empty then show ?case
+    by force
+next
+  case (insert X \<F>)
+  then have "closed X" and clo: "\<And>X. X \<in> \<F> \<Longrightarrow> closed X"
+        and \<F>: "\<And>S. S \<in> \<F> \<Longrightarrow> \<exists>a g. a \<notin> U \<and> continuous_on (S - {a}) g \<and> g ` (S - {a}) \<subseteq> T \<and> (\<forall>x \<in> S \<inter> K. g x = h x)"
+        and pwX: "\<And>Y. Y \<in> \<F> \<and> Y \<noteq> X \<longrightarrow> X \<inter> Y \<subseteq> K \<and> Y \<inter> X \<subseteq> K"
+        and pwF: "pairwise (\<lambda> S T. S \<inter> T \<subseteq> K) \<F>"
+    by (simp_all add: pairwise_insert)
+  obtain C g where C: "finite C" "disjnt C U" "card C \<le> card \<F>"
+               and contg: "continuous_on (\<Union>\<F> - C) g"
+               and gim: "g ` (\<Union>\<F> - C) \<subseteq> T"
+               and gh:  "\<And>x. x \<in> (\<Union>\<F> - C) \<inter> K \<Longrightarrow> g x = h x"
+    using insert.IH [OF pwF \<F> clo] by auto
+  obtain a f where "a \<notin> U"
+               and contf: "continuous_on (X - {a}) f"
+               and fim: "f ` (X - {a}) \<subseteq> T"
+               and fh: "(\<forall>x \<in> X \<inter> K. f x = h x)"
+    using insert.prems by (meson insertI1)
+  show ?case
+  proof (intro exI conjI)
+    show "finite (insert a C)"
+      by (simp add: C)
+    show "disjnt (insert a C) U"
+      using C \<open>a \<notin> U\<close> by simp
+    show "card (insert a C) \<le> card (insert X \<F>)"
+      by (simp add: C card_insert_if insert.hyps le_SucI)
+    have "closed (\<Union>\<F>)"
+      using clo insert.hyps by blast
+    have "continuous_on (X - insert a C \<union> (\<Union>\<F> - insert a C)) (\<lambda>x. if x \<in> X then f x else g x)"
+       apply (rule continuous_on_cases_local)
+          apply (simp_all add: closedin_closed)
+        using \<open>closed X\<close> apply blast
+        using \<open>closed (\<Union>\<F>)\<close> apply blast
+        using contf apply (force simp: elim: continuous_on_subset)
+        using contg apply (force simp: elim: continuous_on_subset)
+        using fh gh insert.hyps pwX by fastforce
+    then show "continuous_on (\<Union>insert X \<F> - insert a C) (\<lambda>a. if a \<in> X then f a else g a)"
+      by (blast intro: continuous_on_subset)
+    show "\<forall>x\<in>(\<Union>insert X \<F> - insert a C) \<inter> K. (if x \<in> X then f x else g x) = h x"
+      using gh by (auto simp: fh)
+    show "(\<lambda>a. if a \<in> X then f a else g a) ` (\<Union>insert X \<F> - insert a C) \<subseteq> T"
+      using fim gim by auto force
+  qed
+qed
+
+
+lemma extend_map_lemma_cofinite1:
+assumes "finite \<F>"
+    and \<F>: "\<And>X. X \<in> \<F> \<Longrightarrow> \<exists>a g. a \<notin> U \<and> continuous_on (X - {a}) g \<and> g ` (X - {a}) \<subseteq> T \<and> (\<forall>x \<in> X \<inter> K. g x = h x)"
+    and clo: "\<And>X. X \<in> \<F> \<Longrightarrow> closed X"
+    and K: "\<And>X Y. \<lbrakk>X \<in> \<F>; Y \<in> \<F>; ~(X \<subseteq> Y); ~(Y \<subseteq> X)\<rbrakk> \<Longrightarrow> X \<inter> Y \<subseteq> K"
+  obtains C g where "finite C" "disjnt C U" "card C \<le> card \<F>" "continuous_on (\<Union>\<F> - C) g"
+                    "g ` (\<Union>\<F> - C) \<subseteq> T"
+                    "\<And>x. x \<in> (\<Union>\<F> - C) \<inter> K \<Longrightarrow> g x = h x"
+proof -
+  let ?\<F> = "{X \<in> \<F>. \<forall>Y\<in>\<F>. \<not> X \<subset> Y}"
+  have [simp]: "\<Union>?\<F> = \<Union>\<F>"
+    by (simp add: Union_maximal_sets assms)
+  have fin: "finite ?\<F>"
+    by (force intro: finite_subset [OF _ \<open>finite \<F>\<close>])
+  have pw: "pairwise (\<lambda> S T. S \<inter> T \<subseteq> K) ?\<F>"
+    by (simp add: pairwise_def) (metis K psubsetI)
+  have "card {X \<in> \<F>. \<forall>Y\<in>\<F>. \<not> X \<subset> Y} \<le> card \<F>"
+    by (simp add: \<open>finite \<F>\<close> card_mono)
+  moreover
+  obtain C g where "finite C \<and> disjnt C U \<and> card C \<le> card ?\<F> \<and>
+                 continuous_on (\<Union>?\<F> - C) g \<and> g ` (\<Union>?\<F> - C) \<subseteq> T
+                  \<and> (\<forall>x \<in> (\<Union>?\<F> - C) \<inter> K. g x = h x)"
+    apply (rule exE [OF extend_map_lemma_cofinite0 [OF fin pw, of U T h]])
+      apply (fastforce intro!:  clo \<F>)+
+    done
+  ultimately show ?thesis
+    by (rule_tac C=C and g=g in that) auto
+qed
+
+
+lemma extend_map_lemma_cofinite:
+  assumes "finite \<F>" "\<G> \<subseteq> \<F>" and T: "convex T" "bounded T"
+      and poly: "\<And>X. X \<in> \<F> \<Longrightarrow> polytope X"
+      and contf: "continuous_on (\<Union>\<G>) f" and fim: "f ` (\<Union>\<G>) \<subseteq> rel_frontier T"
+      and face: "\<And>X Y. \<lbrakk>X \<in> \<F>; Y \<in> \<F>\<rbrakk> \<Longrightarrow> (X \<inter> Y) face_of X \<and> (X \<inter> Y) face_of Y"
+      and aff: "\<And>X. X \<in> \<F> - \<G> \<Longrightarrow> aff_dim X \<le> aff_dim T"
+  obtains C g where
+     "finite C" "disjnt C (\<Union>\<G>)" "card C \<le> card \<F>" "continuous_on (\<Union>\<F> - C) g"
+     "g ` (\<Union> \<F> - C) \<subseteq> rel_frontier T" "\<And>x. x \<in> \<Union>\<G> \<Longrightarrow> g x = f x"
+proof -
+  define \<H> where "\<H> \<equiv> \<G> \<union> {D. \<exists>C \<in> \<F> - \<G>. D face_of C \<and> aff_dim D < aff_dim T}"
+  have "finite \<G>"
+    using assms finite_subset by blast
+  moreover have "finite (\<Union>{{D. D face_of C} |C. C \<in> \<F>})"
+    apply (rule finite_Union)
+     apply (simp add: \<open>finite \<F>\<close>)
+    using finite_polytope_faces poly by auto
+  ultimately have "finite \<H>"
+    apply (simp add: \<H>_def)
+    apply (rule finite_subset [of _ "\<Union> {{D. D face_of C} | C. C \<in> \<F>}"], auto)
+    done
+  have *: "\<And>X Y. \<lbrakk>X \<in> \<H>; Y \<in> \<H>\<rbrakk> \<Longrightarrow> X \<inter> Y face_of X \<and> X \<inter> Y face_of Y"
+    unfolding \<H>_def
+    apply (elim UnE bexE CollectE DiffE)
+    using subsetD [OF \<open>\<G> \<subseteq> \<F>\<close>] apply (simp_all add: face)
+      apply (meson subsetD [OF \<open>\<G> \<subseteq> \<F>\<close>] face face_of_Int_subface face_of_imp_subset face_of_refl poly polytope_imp_convex)+
+    done
+  obtain h where conth: "continuous_on (\<Union>\<H>) h" and him: "h ` (\<Union>\<H>) \<subseteq> rel_frontier T"
+             and hf: "\<And>x. x \<in> \<Union>\<G> \<Longrightarrow> h x = f x"
+    using \<open>finite \<H>\<close>
+    unfolding \<H>_def
+    apply (rule extend_map_lemma [OF _ Un_upper1 T _ _ _ contf fim])
+    using \<open>\<G> \<subseteq> \<F>\<close> face_of_polytope_polytope poly apply fastforce
+    using * apply (auto simp: \<H>_def)
+    done
+  have "bounded (\<Union>\<G>)"
+    using \<open>finite \<G>\<close> \<open>\<G> \<subseteq> \<F>\<close> poly polytope_imp_bounded by blast
+  then have "\<Union>\<G> \<noteq> UNIV"
+    by auto
+  then obtain a where a: "a \<notin> \<Union>\<G>"
+    by blast
+  have \<F>: "\<exists>a g. a \<notin> \<Union>\<G> \<and> continuous_on (D - {a}) g \<and>
+                  g ` (D - {a}) \<subseteq> rel_frontier T \<and> (\<forall>x \<in> D \<inter> \<Union>\<H>. g x = h x)"
+       if "D \<in> \<F>" for D
+  proof (cases "D \<subseteq> \<Union>\<H>")
+    case True
+    then show ?thesis
+      apply (rule_tac x=a in exI)
+      apply (rule_tac x=h in exI)
+      using him apply (blast intro!: \<open>a \<notin> \<Union>\<G>\<close> continuous_on_subset [OF conth]) +
+      done
+  next
+    case False
+    note D_not_subset = False
+    show ?thesis
+    proof (cases "D \<in> \<G>")
+      case True
+      with D_not_subset show ?thesis
+        by (auto simp: \<H>_def)
+    next
+      case False
+      then have affD: "aff_dim D \<le> aff_dim T"
+        by (simp add: \<open>D \<in> \<F>\<close> aff)
+      show ?thesis
+      proof (cases "rel_interior D = {}")
+        case True
+        with \<open>D \<in> \<F>\<close> poly a show ?thesis
+          by (force simp: rel_interior_eq_empty polytope_imp_convex)
+      next
+        case False
+        then obtain b where brelD: "b \<in> rel_interior D"
+          by blast
+        have "polyhedron D"
+          by (simp add: poly polytope_imp_polyhedron that)
+        have "rel_frontier D retract_of affine hull D - {b}"
+          by (simp add: rel_frontier_retract_of_punctured_affine_hull poly polytope_imp_bounded polytope_imp_convex that brelD)
+        then obtain r where relfD: "rel_frontier D \<subseteq> affine hull D - {b}"
+                        and contr: "continuous_on (affine hull D - {b}) r"
+                        and rim: "r ` (affine hull D - {b}) \<subseteq> rel_frontier D"
+                        and rid: "\<And>x. x \<in> rel_frontier D \<Longrightarrow> r x = x"
+          by (auto simp: retract_of_def retraction_def)
+        show ?thesis
+        proof (intro exI conjI ballI)
+          show "b \<notin> \<Union>\<G>"
+          proof clarify
+            fix E
+            assume "b \<in> E" "E \<in> \<G>"
+            then have "E \<inter> D face_of E \<and> E \<inter> D face_of D"
+              using \<open>\<G> \<subseteq> \<F>\<close> face that by auto
+            with face_of_subset_rel_frontier \<open>E \<in> \<G>\<close> \<open>b \<in> E\<close> brelD rel_interior_subset [of D]
+                 D_not_subset rel_frontier_def \<H>_def
+            show False
+              by blast
+          qed
+          have "r ` (D - {b}) \<subseteq> r ` (affine hull D - {b})"
+            by (simp add: Diff_mono hull_subset image_mono)
+          also have "... \<subseteq> rel_frontier D"
+            by (rule rim)
+          also have "... \<subseteq> \<Union>{E. E face_of D \<and> aff_dim E < aff_dim T}"
+            using affD
+            by (force simp: rel_frontier_of_polyhedron [OF \<open>polyhedron D\<close>] facet_of_def)
+          also have "... \<subseteq> \<Union>(\<H>)"
+            using D_not_subset \<H>_def that by fastforce
+          finally have rsub: "r ` (D - {b}) \<subseteq> \<Union>(\<H>)" .
+          show "continuous_on (D - {b}) (h \<circ> r)"
+            apply (intro conjI \<open>b \<notin> \<Union>\<G>\<close> continuous_on_compose)
+               apply (rule continuous_on_subset [OF contr])
+            apply (simp add: Diff_mono hull_subset)
+            apply (rule continuous_on_subset [OF conth rsub])
+            done
+          show "(h \<circ> r) ` (D - {b}) \<subseteq> rel_frontier T"
+            using brelD him rsub by fastforce
+          show "(h \<circ> r) x = h x" if x: "x \<in> D \<inter> \<Union>\<H>" for x
+          proof -
+            consider A where "x \<in> D" "A \<in> \<G>" "x \<in> A"
+                 | A B where "x \<in> D" "A face_of B" "B \<in> \<F>" "B \<notin> \<G>" "aff_dim A < aff_dim T" "x \<in> A"
+              using x by (auto simp: \<H>_def)
+            then have xrel: "x \<in> rel_frontier D"
+            proof cases
+              case 1 show ?thesis
+              proof (rule face_of_subset_rel_frontier [THEN subsetD])
+                show "D \<inter> A face_of D"
+                  using \<open>A \<in> \<G>\<close> \<open>\<G> \<subseteq> \<F>\<close> face \<open>D \<in> \<F>\<close> by blast
+                show "D \<inter> A \<noteq> D"
+                  using \<open>A \<in> \<G>\<close> D_not_subset \<H>_def by blast
+              qed (auto simp: 1)
+            next
+              case 2 show ?thesis
+              proof (rule face_of_subset_rel_frontier [THEN subsetD])
+                show "D \<inter> A face_of D"
+                  apply (rule face_of_Int_subface [of D B _ A, THEN conjunct1])
+                     apply (simp_all add: 2 \<open>D \<in> \<F>\<close> face)
+                   apply (simp add: \<open>polyhedron D\<close> polyhedron_imp_convex face_of_refl)
+                  done
+                show "D \<inter> A \<noteq> D"
+                  using "2" D_not_subset \<H>_def by blast
+              qed (auto simp: 2)
+            qed
+            show ?thesis
+              by (simp add: rid xrel)
+          qed
+        qed
+      qed
+    qed
+  qed
+  have clo: "\<And>S. S \<in> \<F> \<Longrightarrow> closed S"
+    by (simp add: poly polytope_imp_closed)
+  obtain C g where "finite C" "disjnt C (\<Union>\<G>)" "card C \<le> card \<F>" "continuous_on (\<Union>\<F> - C) g"
+                   "g ` (\<Union>\<F> - C) \<subseteq> rel_frontier T"
+               and gh: "\<And>x. x \<in> (\<Union>\<F> - C) \<inter> \<Union>\<H> \<Longrightarrow> g x = h x"
+  proof (rule extend_map_lemma_cofinite1 [OF \<open>finite \<F>\<close> \<F> clo])
+    show "X \<inter> Y \<subseteq> \<Union>\<H>" if XY: "X \<in> \<F>" "Y \<in> \<F>" and "\<not> X \<subseteq> Y" "\<not> Y \<subseteq> X" for X Y
+    proof (cases "X \<in> \<G>")
+      case True
+      then show ?thesis
+        by (auto simp: \<H>_def)
+    next
+      case False
+      have "X \<inter> Y \<noteq> X"
+        using \<open>\<not> X \<subseteq> Y\<close> by blast
+      with XY
+      show ?thesis
+        by (clarsimp simp: \<H>_def)
+           (metis Diff_iff Int_iff aff antisym_conv face face_of_aff_dim_lt face_of_refl
+                  not_le poly polytope_imp_convex)
+    qed
+  qed (blast)+
+  with \<open>\<G> \<subseteq> \<F>\<close> show ?thesis
+    apply (rule_tac C=C and g=g in that)
+     apply (auto simp: disjnt_def hf [symmetric] \<H>_def intro!: gh)
+    done
+qed
+
+text\<open>The next two proofs are similar\<close>
+theorem extend_map_cell_complex_to_sphere:
+  assumes "finite \<F>" and S: "S \<subseteq> \<Union>\<F>" "closed S" and T: "convex T" "bounded T"
+      and poly: "\<And>X. X \<in> \<F> \<Longrightarrow> polytope X"
+      and aff: "\<And>X. X \<in> \<F> \<Longrightarrow> aff_dim X < aff_dim T"
+      and face: "\<And>X Y. \<lbrakk>X \<in> \<F>; Y \<in> \<F>\<rbrakk> \<Longrightarrow> (X \<inter> Y) face_of X \<and> (X \<inter> Y) face_of Y"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> rel_frontier T"
+  obtains g where "continuous_on (\<Union>\<F>) g"
+     "g ` (\<Union>\<F>) \<subseteq> rel_frontier T" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof -
+  obtain V g where "S \<subseteq> V" "open V" "continuous_on V g" and gim: "g ` V \<subseteq> rel_frontier T" and gf: "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+    using neighbourhood_extension_into_ANR [OF contf fim _ \<open>closed S\<close>] ANR_rel_frontier_convex T by blast
+  have "compact S"
+    by (meson assms compact_Union poly polytope_imp_compact seq_compact_closed_subset seq_compact_eq_compact)
+  then obtain d where "d > 0" and d: "\<And>x y. \<lbrakk>x \<in> S; y \<in> - V\<rbrakk> \<Longrightarrow> d \<le> dist x y"
+    using separate_compact_closed [of S "-V"] \<open>open V\<close> \<open>S \<subseteq> V\<close> by force
+  obtain \<G> where "finite \<G>" "\<Union>\<G> = \<Union>\<F>"
+             and diaG: "\<And>X. X \<in> \<G> \<Longrightarrow> diameter X < d"
+             and polyG: "\<And>X. X \<in> \<G> \<Longrightarrow> polytope X"
+             and affG: "\<And>X. X \<in> \<G> \<Longrightarrow> aff_dim X \<le> aff_dim T - 1"
+             and faceG: "\<And>X Y. \<lbrakk>X \<in> \<G>; Y \<in> \<G>\<rbrakk> \<Longrightarrow> X \<inter> Y face_of X \<and> X \<inter> Y face_of Y"
+  proof (rule cell_complex_subdivision_exists [OF \<open>d>0\<close> \<open>finite \<F>\<close> poly _ face])
+    show "\<And>X. X \<in> \<F> \<Longrightarrow> aff_dim X \<le> aff_dim T - 1"
+      by (simp add: aff)
+  qed auto
+  obtain h where conth: "continuous_on (\<Union>\<G>) h" and him: "h ` \<Union>\<G> \<subseteq> rel_frontier T" and hg: "\<And>x. x \<in> \<Union>(\<G> \<inter> Pow V) \<Longrightarrow> h x = g x"
+  proof (rule extend_map_lemma [of \<G> "\<G> \<inter> Pow V" T g])
+    show "continuous_on (\<Union>(\<G> \<inter> Pow V)) g"
+      by (metis Union_Int_subset Union_Pow_eq \<open>continuous_on V g\<close> continuous_on_subset le_inf_iff)
+  qed (use \<open>finite \<G>\<close> T polyG affG faceG gim in fastforce)+
+  show ?thesis
+  proof
+    show "continuous_on (\<Union>\<F>) h"
+      using \<open>\<Union>\<G> = \<Union>\<F>\<close> conth by auto
+    show "h ` \<Union>\<F> \<subseteq> rel_frontier T"
+      using \<open>\<Union>\<G> = \<Union>\<F>\<close> him by auto
+    show "h x = f x" if "x \<in> S" for x
+    proof -
+      have "x \<in> \<Union>\<G>"
+        using \<open>\<Union>\<G> = \<Union>\<F>\<close> \<open>S \<subseteq> \<Union>\<F>\<close> that by auto
+      then obtain X where "x \<in> X" "X \<in> \<G>" by blast
+      then have "diameter X < d" "bounded X"
+        by (auto simp: diaG \<open>X \<in> \<G>\<close> polyG polytope_imp_bounded)
+      then have "X \<subseteq> V" using d [OF \<open>x \<in> S\<close>] diameter_bounded_bound [OF \<open>bounded X\<close> \<open>x \<in> X\<close>]
+        by fastforce
+      have "h x = g x"
+        apply (rule hg)
+        using \<open>X \<in> \<G>\<close> \<open>X \<subseteq> V\<close> \<open>x \<in> X\<close> by blast
+      also have "... = f x"
+        by (simp add: gf that)
+      finally show "h x = f x" .
+    qed
+  qed
+qed
+
+
+theorem extend_map_cell_complex_to_sphere_cofinite:
+  assumes "finite \<F>" and S: "S \<subseteq> \<Union>\<F>" "closed S" and T: "convex T" "bounded T"
+      and poly: "\<And>X. X \<in> \<F> \<Longrightarrow> polytope X"
+      and aff: "\<And>X. X \<in> \<F> \<Longrightarrow> aff_dim X \<le> aff_dim T"
+      and face: "\<And>X Y. \<lbrakk>X \<in> \<F>; Y \<in> \<F>\<rbrakk> \<Longrightarrow> (X \<inter> Y) face_of X \<and> (X \<inter> Y) face_of Y"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> rel_frontier T"
+  obtains C g where "finite C" "disjnt C S" "continuous_on (\<Union>\<F> - C) g"
+     "g ` (\<Union>\<F> - C) \<subseteq> rel_frontier T" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof -
+  obtain V g where "S \<subseteq> V" "open V" "continuous_on V g" and gim: "g ` V \<subseteq> rel_frontier T" and gf: "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+    using neighbourhood_extension_into_ANR [OF contf fim _ \<open>closed S\<close>] ANR_rel_frontier_convex T by blast
+  have "compact S"
+    by (meson assms compact_Union poly polytope_imp_compact seq_compact_closed_subset seq_compact_eq_compact)
+  then obtain d where "d > 0" and d: "\<And>x y. \<lbrakk>x \<in> S; y \<in> - V\<rbrakk> \<Longrightarrow> d \<le> dist x y"
+    using separate_compact_closed [of S "-V"] \<open>open V\<close> \<open>S \<subseteq> V\<close> by force
+  obtain \<G> where "finite \<G>" "\<Union>\<G> = \<Union>\<F>"
+             and diaG: "\<And>X. X \<in> \<G> \<Longrightarrow> diameter X < d"
+             and polyG: "\<And>X. X \<in> \<G> \<Longrightarrow> polytope X"
+             and affG: "\<And>X. X \<in> \<G> \<Longrightarrow> aff_dim X \<le> aff_dim T"
+             and faceG: "\<And>X Y. \<lbrakk>X \<in> \<G>; Y \<in> \<G>\<rbrakk> \<Longrightarrow> X \<inter> Y face_of X \<and> X \<inter> Y face_of Y"
+    by (rule cell_complex_subdivision_exists [OF \<open>d>0\<close> \<open>finite \<F>\<close> poly aff face]) auto
+  obtain C h where "finite C" and dis: "disjnt C (\<Union>(\<G> \<inter> Pow V))"
+               and card: "card C \<le> card \<G>" and conth: "continuous_on (\<Union>\<G> - C) h"
+               and him: "h ` (\<Union>\<G> - C) \<subseteq> rel_frontier T"
+               and hg: "\<And>x. x \<in> \<Union>(\<G> \<inter> Pow V) \<Longrightarrow> h x = g x"
+  proof (rule extend_map_lemma_cofinite [of \<G> "\<G> \<inter> Pow V" T g])
+    show "continuous_on (\<Union>(\<G> \<inter> Pow V)) g"
+      by (metis Union_Int_subset Union_Pow_eq \<open>continuous_on V g\<close> continuous_on_subset le_inf_iff)
+    show "g ` \<Union>(\<G> \<inter> Pow V) \<subseteq> rel_frontier T"
+      using gim by force
+  qed (auto intro: \<open>finite \<G>\<close> T polyG affG dest: faceG)
+  have Ssub: "S \<subseteq> \<Union>(\<G> \<inter> Pow V)"
+  proof
+    fix x
+    assume "x \<in> S"
+    then have "x \<in> \<Union>\<G>"
+      using \<open>\<Union>\<G> = \<Union>\<F>\<close> \<open>S \<subseteq> \<Union>\<F>\<close> by auto
+    then obtain X where "x \<in> X" "X \<in> \<G>" by blast
+    then have "diameter X < d" "bounded X"
+      by (auto simp: diaG \<open>X \<in> \<G>\<close> polyG polytope_imp_bounded)
+    then have "X \<subseteq> V" using d [OF \<open>x \<in> S\<close>] diameter_bounded_bound [OF \<open>bounded X\<close> \<open>x \<in> X\<close>]
+      by fastforce
+    then show "x \<in> \<Union>(\<G> \<inter> Pow V)"
+      using \<open>X \<in> \<G>\<close> \<open>x \<in> X\<close> by blast
+  qed
+  show ?thesis
+  proof
+    show "continuous_on (\<Union>\<F>-C) h"
+      using \<open>\<Union>\<G> = \<Union>\<F>\<close> conth by auto
+    show "h ` (\<Union>\<F> - C) \<subseteq> rel_frontier T"
+      using \<open>\<Union>\<G> = \<Union>\<F>\<close> him by auto
+    show "h x = f x" if "x \<in> S" for x
+    proof -
+      have "h x = g x"
+        apply (rule hg)
+        using Ssub that by blast
+      also have "... = f x"
+        by (simp add: gf that)
+      finally show "h x = f x" .
+    qed
+    show "disjnt C S"
+      using dis Ssub  by (meson disjnt_iff subset_eq)
+  qed (intro \<open>finite C\<close>)
+qed
+
+
+
+subsection\<open> Special cases and corollaries involving spheres.\<close>
+
+lemma disjnt_Diff1: "X \<subseteq> Y' \<Longrightarrow> disjnt (X - Y) (X' - Y')"
+  by (auto simp: disjnt_def)
+
+proposition extend_map_affine_to_sphere_cofinite_simple:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "compact S" "convex U" "bounded U"
+      and aff: "aff_dim T \<le> aff_dim U"
+      and "S \<subseteq> T" and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> rel_frontier U"
+ obtains K g where "finite K" "K \<subseteq> T" "disjnt K S" "continuous_on (T - K) g"
+                   "g ` (T - K) \<subseteq> rel_frontier U"
+                   "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof -
+  have "\<exists>K g. finite K \<and> disjnt K S \<and> continuous_on (T - K) g \<and>
+              g ` (T - K) \<subseteq> rel_frontier U \<and> (\<forall>x \<in> S. g x = f x)"
+       if "affine T" "S \<subseteq> T" and aff: "aff_dim T \<le> aff_dim U"  for T
+  proof (cases "S = {}")
+    case True
+    show ?thesis
+    proof (cases "rel_frontier U = {}")
+      case True
+      with \<open>bounded U\<close> have "aff_dim U \<le> 0"
+        using affine_bounded_eq_lowdim rel_frontier_eq_empty by auto
+      with aff have "aff_dim T \<le> 0" by auto
+      then obtain a where "T \<subseteq> {a}"
+        using \<open>affine T\<close> affine_bounded_eq_lowdim affine_bounded_eq_trivial by auto
+      then show ?thesis
+        using \<open>S = {}\<close> fim
+        by (metis Diff_cancel contf disjnt_empty2 finite.emptyI finite_insert finite_subset)
+    next
+      case False
+      then obtain a where "a \<in> rel_frontier U"
+        by auto
+      then show ?thesis
+        using continuous_on_const [of _ a] \<open>S = {}\<close> by force
+    qed
+  next
+    case False
+    have "bounded S"
+      by (simp add: \<open>compact S\<close> compact_imp_bounded)
+    then obtain b where b: "S \<subseteq> cbox (-b) b"
+      using bounded_subset_cbox_symmetric by blast
+    define bbox where "bbox \<equiv> cbox (-(b+One)) (b+One)"
+    have "cbox (-b) b \<subseteq> bbox"
+      by (auto simp: bbox_def algebra_simps intro!: subset_box_imp)
+    with b \<open>S \<subseteq> T\<close> have "S \<subseteq> bbox \<inter> T"
+      by auto
+    then have Ssub: "S \<subseteq> \<Union>{bbox \<inter> T}"
+      by auto
+    then have "aff_dim (bbox \<inter> T) \<le> aff_dim U"
+      by (metis aff aff_dim_subset inf_commute inf_le1 order_trans)
+    obtain K g where K: "finite K" "disjnt K S"
+                 and contg: "continuous_on (\<Union>{bbox \<inter> T} - K) g"
+                 and gim: "g ` (\<Union>{bbox \<inter> T} - K) \<subseteq> rel_frontier U"
+                 and gf: "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+    proof (rule extend_map_cell_complex_to_sphere_cofinite
+              [OF _ Ssub _ \<open>convex U\<close> \<open>bounded U\<close> _ _ _ contf fim])
+      show "closed S"
+        using \<open>compact S\<close> compact_eq_bounded_closed by auto
+      show poly: "\<And>X. X \<in> {bbox \<inter> T} \<Longrightarrow> polytope X"
+        by (simp add: polytope_Int_polyhedron bbox_def polytope_interval affine_imp_polyhedron \<open>affine T\<close>)
+      show "\<And>X Y. \<lbrakk>X \<in> {bbox \<inter> T}; Y \<in> {bbox \<inter> T}\<rbrakk> \<Longrightarrow> X \<inter> Y face_of X \<and> X \<inter> Y face_of Y"
+        by (simp add:poly face_of_refl polytope_imp_convex)
+      show "\<And>X. X \<in> {bbox \<inter> T} \<Longrightarrow> aff_dim X \<le> aff_dim U"
+        by (simp add: \<open>aff_dim (bbox \<inter> T) \<le> aff_dim U\<close>)
+    qed auto
+    define fro where "fro \<equiv> \<lambda>d. frontier(cbox (-(b + d *\<^sub>R One)) (b + d *\<^sub>R One))"
+    obtain d where d12: "1/2 \<le> d" "d \<le> 1" and dd: "disjnt K (fro d)"
+    proof (rule disjoint_family_elem_disjnt [OF _ \<open>finite K\<close>])
+      show "infinite {1/2..1::real}"
+        by (simp add: infinite_Icc)
+      have dis1: "disjnt (fro x) (fro y)" if "x<y" for x y
+        by (auto simp: algebra_simps that subset_box_imp disjnt_Diff1 frontier_def fro_def)
+      then show "disjoint_family_on fro {1/2..1}"
+        by (auto simp: disjoint_family_on_def disjnt_def neq_iff)
+    qed auto
+    define c where "c \<equiv> b + d *\<^sub>R One"
+    have cbsub: "cbox (-b) b \<subseteq> box (-c) c"  "cbox (-b) b \<subseteq> cbox (-c) c"  "cbox (-c) c \<subseteq> bbox"
+      using d12 by (auto simp: algebra_simps subset_box_imp c_def bbox_def)
+    have clo_cbT: "closed (cbox (- c) c \<inter> T)"
+      by (simp add: affine_closed closed_Int closed_cbox \<open>affine T\<close>)
+    have cpT_ne: "cbox (- c) c \<inter> T \<noteq> {}"
+      using \<open>S \<noteq> {}\<close> b cbsub(2) \<open>S \<subseteq> T\<close> by fastforce
+    have "closest_point (cbox (- c) c \<inter> T) x \<notin> K" if "x \<in> T" "x \<notin> K" for x
+    proof (cases "x \<in> cbox (-c) c")
+      case True with that show ?thesis
+        by (simp add: closest_point_self)
+    next
+      case False
+      have int_ne: "interior (cbox (-c) c) \<inter> T \<noteq> {}"
+        using \<open>S \<noteq> {}\<close> \<open>S \<subseteq> T\<close> b \<open>cbox (- b) b \<subseteq> box (- c) c\<close> by force
+      have "convex T"
+        by (meson \<open>affine T\<close> affine_imp_convex)
+      then have "x \<in> affine hull (cbox (- c) c \<inter> T)"
+          by (metis Int_commute Int_iff \<open>S \<noteq> {}\<close> \<open>S \<subseteq> T\<close> cbsub(1) \<open>x \<in> T\<close> affine_hull_convex_Int_nonempty_interior all_not_in_conv b hull_inc inf.orderE interior_cbox)
+      then have "x \<in> affine hull (cbox (- c) c \<inter> T) - rel_interior (cbox (- c) c \<inter> T)"
+        by (meson DiffI False Int_iff rel_interior_subset subsetCE)
+      then have "closest_point (cbox (- c) c \<inter> T) x \<in> rel_frontier (cbox (- c) c \<inter> T)"
+        by (rule closest_point_in_rel_frontier [OF clo_cbT cpT_ne])
+      moreover have "(rel_frontier (cbox (- c) c \<inter> T)) \<subseteq> fro d"
+        apply (subst convex_affine_rel_frontier_Int [OF _  \<open>affine T\<close> int_ne])
+         apply (auto simp: fro_def c_def)
+        done
+      ultimately show ?thesis
+        using dd  by (force simp: disjnt_def)
+    qed
+    then have cpt_subset: "closest_point (cbox (- c) c \<inter> T) ` (T - K) \<subseteq> \<Union>{bbox \<inter> T} - K"
+      using closest_point_in_set [OF clo_cbT cpT_ne] cbsub(3) by force
+    show ?thesis
+    proof (intro conjI ballI exI)
+      have "continuous_on (T - K) (closest_point (cbox (- c) c \<inter> T))"
+        apply (rule continuous_on_closest_point)
+        using \<open>S \<noteq> {}\<close> cbsub(2) b that
+        by (auto simp: affine_imp_convex convex_Int affine_closed closed_Int closed_cbox \<open>affine T\<close>)
+      then show "continuous_on (T - K) (g \<circ> closest_point (cbox (- c) c \<inter> T))"
+        by (metis continuous_on_compose continuous_on_subset [OF contg cpt_subset])
+      have "(g \<circ> closest_point (cbox (- c) c \<inter> T)) ` (T - K) \<subseteq> g ` (\<Union>{bbox \<inter> T} - K)"
+        by (metis image_comp image_mono cpt_subset)
+      also have "... \<subseteq> rel_frontier U"
+        by (rule gim)
+      finally show "(g \<circ> closest_point (cbox (- c) c \<inter> T)) ` (T - K) \<subseteq> rel_frontier U" .
+      show "(g \<circ> closest_point (cbox (- c) c \<inter> T)) x = f x" if "x \<in> S" for x
+      proof -
+        have "(g \<circ> closest_point (cbox (- c) c \<inter> T)) x = g x"
+          unfolding o_def
+          by (metis IntI \<open>S \<subseteq> T\<close> b cbsub(2) closest_point_self subset_eq that)
+        also have "... = f x"
+          by (simp add: that gf)
+        finally show ?thesis .
+      qed
+    qed (auto simp: K)
+  qed
+  then obtain K g where "finite K" "disjnt K S"
+               and contg: "continuous_on (affine hull T - K) g"
+               and gim:  "g ` (affine hull T - K) \<subseteq> rel_frontier U"
+               and gf:   "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+    by (metis aff affine_affine_hull aff_dim_affine_hull
+              order_trans [OF \<open>S \<subseteq> T\<close> hull_subset [of T affine]])
+  then obtain K g where "finite K" "disjnt K S"
+               and contg: "continuous_on (T - K) g"
+               and gim:  "g ` (T - K) \<subseteq> rel_frontier U"
+               and gf:   "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+    by (rule_tac K=K and g=g in that) (auto simp: hull_inc elim: continuous_on_subset)
+  then show ?thesis
+    by (rule_tac K="K \<inter> T" and g=g in that) (auto simp: disjnt_iff Diff_Int contg)
+qed
+
+subsection\<open>Extending maps to spheres\<close>
+
+(*Up to extend_map_affine_to_sphere_cofinite_gen*)
+
+lemma closedin_closed_subset:
+ "\<lbrakk>closedin (subtopology euclidean U) V; T \<subseteq> U; S = V \<inter> T\<rbrakk>
+             \<Longrightarrow> closedin (subtopology euclidean T) S"
+  by (metis (no_types, lifting) Int_assoc Int_commute closedin_closed inf.orderE)
+
+lemma extend_map_affine_to_sphere1:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::topological_space"
+  assumes "finite K" "affine U" and contf: "continuous_on (U - K) f"
+      and fim: "f ` (U - K) \<subseteq> T"
+      and comps: "\<And>C. \<lbrakk>C \<in> components(U - S); C \<inter> K \<noteq> {}\<rbrakk> \<Longrightarrow> C \<inter> L \<noteq> {}"
+      and clo: "closedin (subtopology euclidean U) S" and K: "disjnt K S" "K \<subseteq> U"
+  obtains g where "continuous_on (U - L) g" "g ` (U - L) \<subseteq> T" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof (cases "K = {}")
+  case True
+  then show ?thesis
+    by (metis Diff_empty Diff_subset contf fim continuous_on_subset image_subsetI rev_image_eqI subset_iff that)
+next
+  case False
+  have "S \<subseteq> U"
+    using clo closedin_limpt by blast
+  then have "(U - S) \<inter> K \<noteq> {}"
+    by (metis Diff_triv False Int_Diff K disjnt_def inf.absorb_iff2 inf_commute)
+  then have "\<Union>(components (U - S)) \<inter> K \<noteq> {}"
+    using Union_components by simp
+  then obtain C0 where C0: "C0 \<in> components (U - S)" "C0 \<inter> K \<noteq> {}"
+    by blast
+  have "convex U"
+    by (simp add: affine_imp_convex \<open>affine U\<close>)
+  then have "locally connected U"
+    by (rule convex_imp_locally_connected)
+  have "\<exists>a g. a \<in> C \<and> a \<in> L \<and> continuous_on (S \<union> (C - {a})) g \<and>
+              g ` (S \<union> (C - {a})) \<subseteq> T \<and> (\<forall>x \<in> S. g x = f x)"
+       if C: "C \<in> components (U - S)" and CK: "C \<inter> K \<noteq> {}" for C
+  proof -
+    have "C \<subseteq> U-S" "C \<inter> L \<noteq> {}"
+      by (simp_all add: in_components_subset comps that)
+    then obtain a where a: "a \<in> C" "a \<in> L" by auto
+    have opeUC: "openin (subtopology euclidean U) C"
+    proof (rule openin_trans)
+      show "openin (subtopology euclidean (U-S)) C"
+        by (simp add: \<open>locally connected U\<close> clo locally_diff_closed openin_components_locally_connected [OF _ C])
+      show "openin (subtopology euclidean U) (U - S)"
+        by (simp add: clo openin_diff)
+    qed
+    then obtain d where "C \<subseteq> U" "0 < d" and d: "cball a d \<inter> U \<subseteq> C"
+      using openin_contains_cball by (metis \<open>a \<in> C\<close>)
+    then have "ball a d \<inter> U \<subseteq> C"
+      by auto
+    obtain h k where homhk: "homeomorphism (S \<union> C) (S \<union> C) h k"
+                 and subC: "{x. (~ (h x = x \<and> k x = x))} \<subseteq> C"
+                 and bou: "bounded {x. (~ (h x = x \<and> k x = x))}"
+                 and hin: "\<And>x. x \<in> C \<inter> K \<Longrightarrow> h x \<in> ball a d \<inter> U"
+    proof (rule homeomorphism_grouping_points_exists_gen [of C "ball a d \<inter> U" "C \<inter> K" "S \<union> C"])
+      show "openin (subtopology euclidean C) (ball a d \<inter> U)"
+        by (metis Topology_Euclidean_Space.open_ball \<open>C \<subseteq> U\<close> \<open>ball a d \<inter> U \<subseteq> C\<close> inf.absorb_iff2 inf.orderE inf_assoc open_openin openin_subtopology)
+      show "openin (subtopology euclidean (affine hull C)) C"
+        by (metis \<open>a \<in> C\<close> \<open>openin (subtopology euclidean U) C\<close> affine_hull_eq affine_hull_openin all_not_in_conv \<open>affine U\<close>)
+      show "ball a d \<inter> U \<noteq> {}"
+        using \<open>0 < d\<close> \<open>C \<subseteq> U\<close> \<open>a \<in> C\<close> by force
+      show "finite (C \<inter> K)"
+        by (simp add: \<open>finite K\<close>)
+      show "S \<union> C \<subseteq> affine hull C"
+        by (metis \<open>C \<subseteq> U\<close> \<open>S \<subseteq> U\<close> \<open>a \<in> C\<close> opeUC affine_hull_eq affine_hull_openin all_not_in_conv assms(2) sup.bounded_iff)
+      show "connected C"
+        by (metis C in_components_connected)
+    qed auto
+    have a_BU: "a \<in> ball a d \<inter> U"
+      using \<open>0 < d\<close> \<open>C \<subseteq> U\<close> \<open>a \<in> C\<close> by auto
+    have "rel_frontier (cball a d \<inter> U) retract_of (affine hull (cball a d \<inter> U) - {a})"
+      apply (rule rel_frontier_retract_of_punctured_affine_hull)
+        apply (auto simp: \<open>convex U\<close> convex_Int)
+      by (metis \<open>affine U\<close> convex_cball empty_iff interior_cball a_BU rel_interior_convex_Int_affine)
+    moreover have "rel_frontier (cball a d \<inter> U) = frontier (cball a d) \<inter> U"
+      apply (rule convex_affine_rel_frontier_Int)
+      using a_BU by (force simp: \<open>affine U\<close>)+
+    moreover have "affine hull (cball a d \<inter> U) = U"
+      by (metis \<open>convex U\<close> a_BU affine_hull_convex_Int_nonempty_interior affine_hull_eq \<open>affine U\<close> equals0D inf.commute interior_cball)
+    ultimately have "frontier (cball a d) \<inter> U retract_of (U - {a})"
+      by metis
+    then obtain r where contr: "continuous_on (U - {a}) r"
+                    and rim: "r ` (U - {a}) \<subseteq> sphere a d"  "r ` (U - {a}) \<subseteq> U"
+                    and req: "\<And>x. x \<in> sphere a d \<inter> U \<Longrightarrow> r x = x"
+      using \<open>affine U\<close> by (auto simp: retract_of_def retraction_def hull_same)
+    define j where "j \<equiv> \<lambda>x. if x \<in> ball a d then r x else x"
+    have kj: "\<And>x. x \<in> S \<Longrightarrow> k (j x) = x"
+      using \<open>C \<subseteq> U - S\<close> \<open>S \<subseteq> U\<close> \<open>ball a d \<inter> U \<subseteq> C\<close> j_def subC by auto
+    have Uaeq: "U - {a} = (cball a d - {a}) \<inter> U \<union> (U - ball a d)"
+      using \<open>0 < d\<close> by auto
+    have jim: "j ` (S \<union> (C - {a})) \<subseteq> (S \<union> C) - ball a d"
+    proof clarify
+      fix y  assume "y \<in> S \<union> (C - {a})"
+      then have "y \<in> U - {a}"
+        using \<open>C \<subseteq> U - S\<close> \<open>S \<subseteq> U\<close> \<open>a \<in> C\<close> by auto
+      then have "r y \<in> sphere a d"
+        using rim by auto
+      then show "j y \<in> S \<union> C - ball a d"
+        apply (simp add: j_def)
+        using \<open>r y \<in> sphere a d\<close> \<open>y \<in> U - {a}\<close> \<open>y \<in> S \<union> (C - {a})\<close> d rim by fastforce
+    qed
+    have contj: "continuous_on (U - {a}) j"
+      unfolding j_def Uaeq
+    proof (intro continuous_on_cases_local continuous_on_id, simp_all add: req closedin_closed Uaeq [symmetric])
+      show "\<exists>T. closed T \<and> (cball a d - {a}) \<inter> U = (U - {a}) \<inter> T"
+          apply (rule_tac x="(cball a d) \<inter> U" in exI)
+        using affine_closed \<open>affine U\<close> by blast
+      show "\<exists>T. closed T \<and> U - ball a d = (U - {a}) \<inter> T"
+         apply (rule_tac x="U - ball a d" in exI)
+        using \<open>0 < d\<close>  by (force simp: affine_closed \<open>affine U\<close> closed_Diff)
+      show "continuous_on ((cball a d - {a}) \<inter> U) r"
+        by (force intro: continuous_on_subset [OF contr])
+    qed
+    have fT: "x \<in> U - K \<Longrightarrow> f x \<in> T" for x
+      using fim by blast
+    show ?thesis
+    proof (intro conjI exI)
+      show "continuous_on (S \<union> (C - {a})) (f \<circ> k \<circ> j)"
+      proof (intro continuous_on_compose)
+        show "continuous_on (S \<union> (C - {a})) j"
+          apply (rule continuous_on_subset [OF contj])
+          using \<open>C \<subseteq> U - S\<close> \<open>S \<subseteq> U\<close> \<open>a \<in> C\<close> by force
+        show "continuous_on (j ` (S \<union> (C - {a}))) k"
+          apply (rule continuous_on_subset [OF homeomorphism_cont2 [OF homhk]])
+          using jim \<open>C \<subseteq> U - S\<close> \<open>S \<subseteq> U\<close> \<open>ball a d \<inter> U \<subseteq> C\<close> j_def by fastforce
+        show "continuous_on (k ` j ` (S \<union> (C - {a}))) f"
+        proof (clarify intro!: continuous_on_subset [OF contf])
+          fix y  assume "y \<in> S \<union> (C - {a})"
+          have ky: "k y \<in> S \<union> C"
+            using homeomorphism_image2 [OF homhk] \<open>y \<in> S \<union> (C - {a})\<close> by blast
+          have jy: "j y \<in> S \<union> C - ball a d"
+            using Un_iff \<open>y \<in> S \<union> (C - {a})\<close> jim by auto
+          show "k (j y) \<in> U - K"
+            apply safe
+            using \<open>C \<subseteq> U\<close> \<open>S \<subseteq> U\<close>  homeomorphism_image2 [OF homhk] jy apply blast
+            by (metis DiffD1 DiffD2 Int_iff Un_iff \<open>disjnt K S\<close> disjnt_def empty_iff hin homeomorphism_apply2 homeomorphism_image2 homhk imageI jy)
+        qed
+      qed
+      have ST: "\<And>x. x \<in> S \<Longrightarrow> (f \<circ> k \<circ> j) x \<in> T"
+        apply (simp add: kj)
+        apply (metis DiffI \<open>S \<subseteq> U\<close> \<open>disjnt K S\<close> subsetD disjnt_iff fim image_subset_iff)
+        done
+      moreover have "(f \<circ> k \<circ> j) x \<in> T" if "x \<in> C" "x \<noteq> a" "x \<notin> S" for x
+      proof -
+        have rx: "r x \<in> sphere a d"
+          using \<open>C \<subseteq> U\<close> rim that by fastforce
+        have jj: "j x \<in> S \<union> C - ball a d"
+          using jim that by blast
+        have "k (j x) = j x \<longrightarrow> k (j x) \<in> C \<or> j x \<in> C"
+          by (metis Diff_iff Int_iff Un_iff \<open>S \<subseteq> U\<close> subsetD d j_def jj rx sphere_cball that(1))
+        then have "k (j x) \<in> C"
+          using homeomorphism_apply2 [OF homhk, of "j x"]   \<open>C \<subseteq> U\<close> \<open>S \<subseteq> U\<close> a rx
+          by (metis (mono_tags, lifting) Diff_iff subsetD jj mem_Collect_eq subC)
+        with jj \<open>C \<subseteq> U\<close> show ?thesis
+          apply safe
+          using ST j_def apply fastforce
+          apply (auto simp: not_less intro!: fT)
+          by (metis DiffD1 DiffD2 Int_iff hin homeomorphism_apply2 [OF homhk] jj)
+      qed
+      ultimately show "(f \<circ> k \<circ> j) ` (S \<union> (C - {a})) \<subseteq> T"
+        by force
+      show "\<forall>x\<in>S. (f \<circ> k \<circ> j) x = f x" using kj by simp
+    qed (auto simp: a)
+  qed
+  then obtain a h where
+    ah: "\<And>C. \<lbrakk>C \<in> components (U - S); C \<inter> K \<noteq> {}\<rbrakk>
+           \<Longrightarrow> a C \<in> C \<and> a C \<in> L \<and> continuous_on (S \<union> (C - {a C})) (h C) \<and>
+               h C ` (S \<union> (C - {a C})) \<subseteq> T \<and> (\<forall>x \<in> S. h C x = f x)"
+    using that by metis
+  define F where "F \<equiv> {C \<in> components (U - S). C \<inter> K \<noteq> {}}"
+  define G where "G \<equiv> {C \<in> components (U - S). C \<inter> K = {}}"
+  define UF where "UF \<equiv> (\<Union>C\<in>F. C - {a C})"
+  have "C0 \<in> F"
+    by (auto simp: F_def C0)
+  have "finite F"
+  proof (subst finite_image_iff [of "\<lambda>C. C \<inter> K" F, symmetric])
+    show "inj_on (\<lambda>C. C \<inter> K) F"
+      unfolding F_def inj_on_def
+      using components_nonoverlap by blast
+    show "finite ((\<lambda>C. C \<inter> K) ` F)"
+      unfolding F_def
+      by (rule finite_subset [of _ "Pow K"]) (auto simp: \<open>finite K\<close>)
+  qed
+  obtain g where contg: "continuous_on (S \<union> UF) g"
+             and gh: "\<And>x i. \<lbrakk>i \<in> F; x \<in> (S \<union> UF) \<inter> (S \<union> (i - {a i}))\<rbrakk>
+                            \<Longrightarrow> g x = h i x"
+  proof (rule pasting_lemma_exists_closed [OF \<open>finite F\<close>, of "S \<union> UF" "\<lambda>C. S \<union> (C - {a C})" h])
+    show "S \<union> UF \<subseteq> (\<Union>C\<in>F. S \<union> (C - {a C}))"
+      using \<open>C0 \<in> F\<close> by (force simp: UF_def)
+    show "closedin (subtopology euclidean (S \<union> UF)) (S \<union> (C - {a C}))"
+         if "C \<in> F" for C
+    proof (rule closedin_closed_subset [of U "S \<union> C"])
+      show "closedin (subtopology euclidean U) (S \<union> C)"
+        apply (rule closedin_Un_complement_component [OF \<open>locally connected U\<close> clo])
+        using F_def that by blast
+    next
+      have "x = a C'" if "C' \<in> F"  "x \<in> C'" "x \<notin> U" for x C'
+      proof -
+        have "\<forall>A. x \<in> \<Union>A \<or> C' \<notin> A"
+          using \<open>x \<in> C'\<close> by blast
+        with that show "x = a C'"
+          by (metis (lifting) DiffD1 F_def Union_components mem_Collect_eq)
+      qed
+      then show "S \<union> UF \<subseteq> U"
+        using \<open>S \<subseteq> U\<close> by (force simp: UF_def)
+    next
+      show "S \<union> (C - {a C}) = (S \<union> C) \<inter> (S \<union> UF)"
+        using F_def UF_def components_nonoverlap that by auto
+    qed
+  next
+    show "continuous_on (S \<union> (C' - {a C'})) (h C')" if "C' \<in> F" for C'
+      using ah F_def that by blast
+    show "\<And>i j x. \<lbrakk>i \<in> F; j \<in> F;
+                   x \<in> (S \<union> UF) \<inter> (S \<union> (i - {a i})) \<inter> (S \<union> (j - {a j}))\<rbrakk>
+                  \<Longrightarrow> h i x = h j x"
+      using components_eq by (fastforce simp: components_eq F_def ah)
+  qed blast
+  have SU': "S \<union> \<Union>G \<union> (S \<union> UF) \<subseteq> U"
+    using \<open>S \<subseteq> U\<close> in_components_subset by (auto simp: F_def G_def UF_def)
+  have clo1: "closedin (subtopology euclidean (S \<union> \<Union>G \<union> (S \<union> UF))) (S \<union> \<Union>G)"
+  proof (rule closedin_closed_subset [OF _ SU'])
+    have *: "\<And>C. C \<in> F \<Longrightarrow> openin (subtopology euclidean U) C"
+      unfolding F_def
+      by clarify (metis (no_types, lifting) \<open>locally connected U\<close> clo closedin_def locally_diff_closed openin_components_locally_connected openin_trans topspace_euclidean_subtopology)
+    show "closedin (subtopology euclidean U) (U - UF)"
+      unfolding UF_def
+      by (force intro: openin_delete *)
+    show "S \<union> \<Union>G = (U - UF) \<inter> (S \<union> \<Union>G \<union> (S \<union> UF))"
+      using \<open>S \<subseteq> U\<close> apply (auto simp: F_def G_def UF_def)
+        apply (metis Diff_iff UnionI Union_components)
+       apply (metis DiffD1 UnionI Union_components)
+      by (metis (no_types, lifting) IntI components_nonoverlap empty_iff)
+  qed
+  have clo2: "closedin (subtopology euclidean (S \<union> \<Union>G \<union> (S \<union> UF))) (S \<union> UF)"
+  proof (rule closedin_closed_subset [OF _ SU'])
+    show "closedin (subtopology euclidean U) (\<Union>C\<in>F. S \<union> C)"
+      apply (rule closedin_Union)
+       apply (simp add: \<open>finite F\<close>)
+      using F_def \<open>locally connected U\<close> clo closedin_Un_complement_component by blast
+    show "S \<union> UF = (\<Union>C\<in>F. S \<union> C) \<inter> (S \<union> \<Union>G \<union> (S \<union> UF))"
+      using \<open>S \<subseteq> U\<close> apply (auto simp: F_def G_def UF_def)
+      using C0 apply blast
+      by (metis components_nonoverlap disjnt_def disjnt_iff)
+  qed
+  have SUG: "S \<union> \<Union>G \<subseteq> U - K"
+    using \<open>S \<subseteq> U\<close> K apply (auto simp: G_def disjnt_iff)
+    by (meson Diff_iff subsetD in_components_subset)
+  then have contf': "continuous_on (S \<union> \<Union>G) f"
+    by (rule continuous_on_subset [OF contf])
+  have contg': "continuous_on (S \<union> UF) g"
+    apply (rule continuous_on_subset [OF contg])
+    using \<open>S \<subseteq> U\<close> by (auto simp: F_def G_def)
+  have  "\<And>x. \<lbrakk>S \<subseteq> U; x \<in> S\<rbrakk> \<Longrightarrow> f x = g x"
+    by (subst gh) (auto simp: ah C0 intro: \<open>C0 \<in> F\<close>)
+  then have f_eq_g: "\<And>x. x \<in> S \<union> UF \<and> x \<in> S \<union> \<Union>G \<Longrightarrow> f x = g x"
+    using \<open>S \<subseteq> U\<close> apply (auto simp: F_def G_def UF_def dest: in_components_subset)
+    using components_eq by blast
+  have cont: "continuous_on (S \<union> \<Union>G \<union> (S \<union> UF)) (\<lambda>x. if x \<in> S \<union> \<Union>G then f x else g x)"
+    by (blast intro: continuous_on_cases_local [OF clo1 clo2 contf' contg' f_eq_g, of "\<lambda>x. x \<in> S \<union> \<Union>G"])
+  show ?thesis
+  proof
+    have UF: "\<Union>F - L \<subseteq> UF"
+      unfolding F_def UF_def using ah by blast
+    have "U - S - L = \<Union>(components (U - S)) - L"
+      by simp
+    also have "... = \<Union>F \<union> \<Union>G - L"
+      unfolding F_def G_def by blast
+    also have "... \<subseteq> UF \<union> \<Union>G"
+      using UF by blast
+    finally have "U - L \<subseteq> S \<union> \<Union>G \<union> (S \<union> UF)"
+      by blast
+    then show "continuous_on (U - L) (\<lambda>x. if x \<in> S \<union> \<Union>G then f x else g x)"
+      by (rule continuous_on_subset [OF cont])
+    have "((U - L) \<inter> {x. x \<notin> S \<and> (\<forall>xa\<in>G. x \<notin> xa)}) \<subseteq>  ((U - L) \<inter> (-S \<inter> UF))"
+      using \<open>U - L \<subseteq> S \<union> \<Union>G \<union> (S \<union> UF)\<close> by auto
+    moreover have "g ` ((U - L) \<inter> (-S \<inter> UF)) \<subseteq> T"
+    proof -
+      have "g x \<in> T" if "x \<in> U" "x \<notin> L" "x \<notin> S" "C \<in> F" "x \<in> C" "x \<noteq> a C" for x C
+      proof (subst gh)
+        show "x \<in> (S \<union> UF) \<inter> (S \<union> (C - {a C}))"
+          using that by (auto simp: UF_def)
+        show "h C x \<in> T"
+          using ah that by (fastforce simp add: F_def)
+      qed (rule that)
+      then show ?thesis
+        by (force simp: UF_def)
+    qed
+    ultimately have "g ` ((U - L) \<inter> {x. x \<notin> S \<and> (\<forall>xa\<in>G. x \<notin> xa)}) \<subseteq> T"
+      using image_mono order_trans by blast
+    moreover have "f ` ((U - L) \<inter> (S \<union> \<Union>G)) \<subseteq> T"
+      using fim SUG by blast
+    ultimately show "(\<lambda>x. if x \<in> S \<union> \<Union>G then f x else g x) ` (U - L) \<subseteq> T"
+       by force
+    show "\<And>x. x \<in> S \<Longrightarrow> (if x \<in> S \<union> \<Union>G then f x else g x) = f x"
+      by (simp add: F_def G_def)
+  qed
+qed
+
+
+lemma extend_map_affine_to_sphere2:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "compact S" "convex U" "bounded U" "affine T" "S \<subseteq> T"
+      and affTU: "aff_dim T \<le> aff_dim U"
+      and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> rel_frontier U"
+      and ovlap: "\<And>C. C \<in> components(T - S) \<Longrightarrow> C \<inter> L \<noteq> {}"
+    obtains K g where "finite K" "K \<subseteq> L" "K \<subseteq> T" "disjnt K S"
+                      "continuous_on (T - K) g" "g ` (T - K) \<subseteq> rel_frontier U"
+                      "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof -
+  obtain K g where K: "finite K" "K \<subseteq> T" "disjnt K S"
+               and contg: "continuous_on (T - K) g"
+               and gim: "g ` (T - K) \<subseteq> rel_frontier U"
+               and gf: "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+     using assms extend_map_affine_to_sphere_cofinite_simple by metis
+  have "(\<exists>y C. C \<in> components (T - S) \<and> x \<in> C \<and> y \<in> C \<and> y \<in> L)" if "x \<in> K" for x
+  proof -
+    have "x \<in> T-S"
+      using \<open>K \<subseteq> T\<close> \<open>disjnt K S\<close> disjnt_def that by fastforce
+    then obtain C where "C \<in> components(T - S)" "x \<in> C"
+      by (metis UnionE Union_components)
+    with ovlap [of C] show ?thesis
+      by blast
+  qed
+  then obtain \<xi> where \<xi>: "\<And>x. x \<in> K \<Longrightarrow> \<exists>C. C \<in> components (T - S) \<and> x \<in> C \<and> \<xi> x \<in> C \<and> \<xi> x \<in> L"
+    by metis
+  obtain h where conth: "continuous_on (T - \<xi> ` K) h"
+             and him: "h ` (T - \<xi> ` K) \<subseteq> rel_frontier U"
+             and hg: "\<And>x. x \<in> S \<Longrightarrow> h x = g x"
+  proof (rule extend_map_affine_to_sphere1 [OF \<open>finite K\<close> \<open>affine T\<close> contg gim, of S "\<xi> ` K"])
+    show cloTS: "closedin (subtopology euclidean T) S"
+      by (simp add: \<open>compact S\<close> \<open>S \<subseteq> T\<close> closed_subset compact_imp_closed)
+    show "\<And>C. \<lbrakk>C \<in> components (T - S); C \<inter> K \<noteq> {}\<rbrakk> \<Longrightarrow> C \<inter> \<xi> ` K \<noteq> {}"
+      using \<xi> components_eq by blast
+  qed (use K in auto)
+  show ?thesis
+  proof
+    show *: "\<xi> ` K \<subseteq> L"
+      using \<xi> by blast
+    show "finite (\<xi> ` K)"
+      by (simp add: K)
+    show "\<xi> ` K \<subseteq> T"
+      by clarify (meson \<xi> Diff_iff contra_subsetD in_components_subset)
+    show "continuous_on (T - \<xi> ` K) h"
+      by (rule conth)
+    show "disjnt (\<xi> ` K) S"
+      using K
+      apply (auto simp: disjnt_def)
+      by (metis \<xi> DiffD2 UnionI Union_components)
+  qed (simp_all add: him hg gf)
+qed
+
+
+proposition extend_map_affine_to_sphere_cofinite_gen:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes SUT: "compact S" "convex U" "bounded U" "affine T" "S \<subseteq> T"
+      and aff: "aff_dim T \<le> aff_dim U"
+      and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> rel_frontier U"
+      and dis: "\<And>C. \<lbrakk>C \<in> components(T - S); bounded C\<rbrakk> \<Longrightarrow> C \<inter> L \<noteq> {}"
+ obtains K g where "finite K" "K \<subseteq> L" "K \<subseteq> T" "disjnt K S" "continuous_on (T - K) g"
+                   "g ` (T - K) \<subseteq> rel_frontier U"
+                   "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof (cases "S = {}")
+  case True
+  show ?thesis
+  proof (cases "rel_frontier U = {}")
+    case True
+    with aff have "aff_dim T \<le> 0"
+      apply (simp add: rel_frontier_eq_empty)
+      using affine_bounded_eq_lowdim \<open>bounded U\<close> order_trans by auto
+    with aff_dim_geq [of T] consider "aff_dim T = -1" |  "aff_dim T = 0"
+      by linarith
+    then show ?thesis
+    proof cases
+      assume "aff_dim T = -1"
+      then have "T = {}"
+        by (simp add: aff_dim_empty)
+      then show ?thesis
+        by (rule_tac K="{}" in that) auto
+    next
+      assume "aff_dim T = 0"
+      then obtain a where "T = {a}"
+        using aff_dim_eq_0 by blast
+      then have "a \<in> L"
+        using dis [of "{a}"] \<open>S = {}\<close> by (auto simp: in_components_self)
+      with \<open>S = {}\<close> \<open>T = {a}\<close> show ?thesis
+        by (rule_tac K="{a}" and g=f in that) auto
+    qed
+  next
+    case False
+    then obtain y where "y \<in> rel_frontier U"
+      by auto
+    with \<open>S = {}\<close> show ?thesis
+      by (rule_tac K="{}" and g="\<lambda>x. y" in that)  (auto simp: continuous_on_const)
+  qed
+next
+  case False
+  have "bounded S"
+    by (simp add: assms compact_imp_bounded)
+  then obtain b where b: "S \<subseteq> cbox (-b) b"
+    using bounded_subset_cbox_symmetric by blast
+  define LU where "LU \<equiv> L \<union> (\<Union> {C \<in> components (T - S). ~bounded C} - cbox (-(b+One)) (b+One))"
+  obtain K g where "finite K" "K \<subseteq> LU" "K \<subseteq> T" "disjnt K S"
+               and contg: "continuous_on (T - K) g"
+               and gim: "g ` (T - K) \<subseteq> rel_frontier U"
+               and gf:  "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+  proof (rule extend_map_affine_to_sphere2 [OF SUT aff contf fim])
+    show "C \<inter> LU \<noteq> {}" if "C \<in> components (T - S)" for C
+    proof (cases "bounded C")
+      case True
+      with dis that show ?thesis
+        unfolding LU_def by fastforce
+    next
+      case False
+      then have "\<not> bounded (\<Union>{C \<in> components (T - S). \<not> bounded C})"
+        by (metis (no_types, lifting) Sup_upper bounded_subset mem_Collect_eq that)
+      then show ?thesis
+        apply (clarsimp simp: LU_def Int_Un_distrib Diff_Int_distrib Int_UN_distrib)
+        by (metis (no_types, lifting) False Sup_upper bounded_cbox bounded_subset inf.orderE mem_Collect_eq that)
+    qed
+  qed blast
+  have *: False if "x \<in> cbox (- b - m *\<^sub>R One) (b + m *\<^sub>R One)"
+                   "x \<notin> box (- b - n *\<^sub>R One) (b + n *\<^sub>R One)"
+                   "0 \<le> m" "m < n" "n \<le> 1" for m n x
+    using that by (auto simp: mem_box algebra_simps)
+  have "disjoint_family_on (\<lambda>d. frontier (cbox (- b - d *\<^sub>R One) (b + d *\<^sub>R One))) {1 / 2..1}"
+    by (auto simp: disjoint_family_on_def neq_iff frontier_def dest: *)
+  then obtain d where d12: "1/2 \<le> d" "d \<le> 1"
+                  and ddis: "disjnt K (frontier (cbox (-(b + d *\<^sub>R One)) (b + d *\<^sub>R One)))"
+    using disjoint_family_elem_disjnt [of "{1/2..1::real}" K "\<lambda>d. frontier (cbox (-(b + d *\<^sub>R One)) (b + d *\<^sub>R One))"]
+    by (auto simp: \<open>finite K\<close>)
+  define c where "c \<equiv> b + d *\<^sub>R One"
+  have cbsub: "cbox (-b) b \<subseteq> box (-c) c"
+              "cbox (-b) b \<subseteq> cbox (-c) c"
+              "cbox (-c) c \<subseteq> cbox (-(b+One)) (b+One)"
+    using d12 by (simp_all add: subset_box c_def inner_diff_left inner_left_distrib)
+  have clo_cT: "closed (cbox (- c) c \<inter> T)"
+    using affine_closed \<open>affine T\<close> by blast
+  have cT_ne: "cbox (- c) c \<inter> T \<noteq> {}"
+    using \<open>S \<noteq> {}\<close> \<open>S \<subseteq> T\<close> b cbsub by fastforce
+  have S_sub_cc: "S \<subseteq> cbox (- c) c"
+    using \<open>cbox (- b) b \<subseteq> cbox (- c) c\<close> b by auto
+  show ?thesis
+  proof
+    show "finite (K \<inter> cbox (-(b+One)) (b+One))"
+      using \<open>finite K\<close> by blast
+    show "K \<inter> cbox (- (b + One)) (b + One) \<subseteq> L"
+      using \<open>K \<subseteq> LU\<close> by (auto simp: LU_def)
+    show "K \<inter> cbox (- (b + One)) (b + One) \<subseteq> T"
+      using \<open>K \<subseteq> T\<close> by auto
+    show "disjnt (K \<inter> cbox (- (b + One)) (b + One)) S"
+      using \<open>disjnt K S\<close>  by (simp add: disjnt_def disjoint_eq_subset_Compl inf.coboundedI1)
+    have cloTK: "closest_point (cbox (- c) c \<inter> T) x \<in> T - K"
+                if "x \<in> T" and Knot: "x \<in> K \<longrightarrow> x \<notin> cbox (- b - One) (b + One)" for x
+    proof (cases "x \<in> cbox (- c) c")
+      case True
+      with \<open>x \<in> T\<close> show ?thesis
+        using cbsub(3) Knot  by (force simp: closest_point_self)
+    next
+      case False
+      have clo_in_rf: "closest_point (cbox (- c) c \<inter> T) x \<in> rel_frontier (cbox (- c) c \<inter> T)"
+      proof (intro closest_point_in_rel_frontier [OF clo_cT cT_ne] DiffI notI)
+        have "T \<inter> interior (cbox (- c) c) \<noteq> {}"
+          using \<open>S \<noteq> {}\<close> \<open>S \<subseteq> T\<close> b cbsub(1) by fastforce
+        then show "x \<in> affine hull (cbox (- c) c \<inter> T)"
+          by (simp add: Int_commute affine_hull_affine_Int_nonempty_interior \<open>affine T\<close> hull_inc that(1))
+      next
+        show "False" if "x \<in> rel_interior (cbox (- c) c \<inter> T)"
+        proof -
+          have "interior (cbox (- c) c) \<inter> T \<noteq> {}"
+            using \<open>S \<noteq> {}\<close> \<open>S \<subseteq> T\<close> b cbsub(1) by fastforce
+          then have "affine hull (T \<inter> cbox (- c) c) = T"
+            using affine_hull_convex_Int_nonempty_interior [of T "cbox (- c) c"]
+            by (simp add: affine_imp_convex \<open>affine T\<close> inf_commute)
+          then show ?thesis
+            by (meson subsetD le_inf_iff rel_interior_subset that False)
+        qed
+      qed
+      have "closest_point (cbox (- c) c \<inter> T) x \<notin> K"
+      proof
+        assume inK: "closest_point (cbox (- c) c \<inter> T) x \<in> K"
+        have "\<And>x. x \<in> K \<Longrightarrow> x \<notin> frontier (cbox (- (b + d *\<^sub>R One)) (b + d *\<^sub>R One))"
+          by (metis ddis disjnt_iff)
+        then show False
+          by (metis DiffI Int_iff \<open>affine T\<close> cT_ne c_def clo_cT clo_in_rf closest_point_in_set
+                    convex_affine_rel_frontier_Int convex_box(1) empty_iff frontier_cbox inK interior_cbox)
+      qed
+      then show ?thesis
+        using cT_ne clo_cT closest_point_in_set by blast
+    qed
+    show "continuous_on (T - K \<inter> cbox (- (b + One)) (b + One)) (g \<circ> closest_point (cbox (-c) c \<inter> T))"
+      apply (intro continuous_on_compose continuous_on_closest_point continuous_on_subset [OF contg])
+         apply (simp_all add: clo_cT affine_imp_convex \<open>affine T\<close> convex_Int cT_ne)
+      using cloTK by blast
+    have "g (closest_point (cbox (- c) c \<inter> T) x) \<in> rel_frontier U"
+         if "x \<in> T" "x \<in> K \<longrightarrow> x \<notin> cbox (- b - One) (b + One)" for x
+      apply (rule gim [THEN subsetD])
+      using that cloTK by blast
+    then show "(g \<circ> closest_point (cbox (- c) c \<inter> T)) ` (T - K \<inter> cbox (- (b + One)) (b + One))
+               \<subseteq> rel_frontier U"
+      by force
+    show "\<And>x. x \<in> S \<Longrightarrow> (g \<circ> closest_point (cbox (- c) c \<inter> T)) x = f x"
+      by simp (metis (mono_tags, lifting) IntI \<open>S \<subseteq> T\<close> cT_ne clo_cT closest_point_refl gf subsetD S_sub_cc)
+  qed
+qed
+
+
+corollary extend_map_affine_to_sphere_cofinite:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes SUT: "compact S" "affine T" "S \<subseteq> T"
+      and aff: "aff_dim T \<le> DIM('b)" and "0 \<le> r"
+      and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> sphere a r"
+      and dis: "\<And>C. \<lbrakk>C \<in> components(T - S); bounded C\<rbrakk> \<Longrightarrow> C \<inter> L \<noteq> {}"
+  obtains K g where "finite K" "K \<subseteq> L" "K \<subseteq> T" "disjnt K S" "continuous_on (T - K) g"
+                    "g ` (T - K) \<subseteq> sphere a r" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+proof (cases "r = 0")
+  case True
+  with fim show ?thesis
+    by (rule_tac K="{}" and g = "\<lambda>x. a" in that) (auto simp: continuous_on_const)
+next
+  case False
+  with assms have "0 < r" by auto
+  then have "aff_dim T \<le> aff_dim (cball a r)"
+    by (simp add: aff aff_dim_cball)
+  then show ?thesis
+    apply (rule extend_map_affine_to_sphere_cofinite_gen
+            [OF \<open>compact S\<close> convex_cball bounded_cball \<open>affine T\<close> \<open>S \<subseteq> T\<close> _ contf])
+    using fim apply (auto simp: assms False that dest: dis)
+    done
+qed
+
+corollary extend_map_UNIV_to_sphere_cofinite:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes aff: "DIM('a) \<le> DIM('b)" and "0 \<le> r"
+      and SUT: "compact S"
+      and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> sphere a r"
+      and dis: "\<And>C. \<lbrakk>C \<in> components(- S); bounded C\<rbrakk> \<Longrightarrow> C \<inter> L \<noteq> {}"
+  obtains K g where "finite K" "K \<subseteq> L" "disjnt K S" "continuous_on (- K) g"
+                    "g ` (- K) \<subseteq> sphere a r" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+apply (rule extend_map_affine_to_sphere_cofinite
+        [OF \<open>compact S\<close> affine_UNIV subset_UNIV _ \<open>0 \<le> r\<close> contf fim dis])
+ apply (auto simp: assms that Compl_eq_Diff_UNIV [symmetric])
+done
+
+corollary extend_map_UNIV_to_sphere_no_bounded_component:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes aff: "DIM('a) \<le> DIM('b)" and "0 \<le> r"
+      and SUT: "compact S"
+      and contf: "continuous_on S f"
+      and fim: "f ` S \<subseteq> sphere a r"
+      and dis: "\<And>C. C \<in> components(- S) \<Longrightarrow> \<not> bounded C"
+  obtains g where "continuous_on UNIV g" "g ` UNIV \<subseteq> sphere a r" "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+apply (rule extend_map_UNIV_to_sphere_cofinite [OF aff \<open>0 \<le> r\<close> \<open>compact S\<close> contf fim, of "{}"])
+   apply (auto simp: that dest: dis)
+done
+
+theorem Borsuk_separation_theorem_gen:
+  fixes S :: "'a::euclidean_space set"
+  assumes "compact S"
+    shows "(\<forall>c \<in> components(- S). ~bounded c) \<longleftrightarrow>
+           (\<forall>f. continuous_on S f \<and> f ` S \<subseteq> sphere (0::'a) 1
+                \<longrightarrow> (\<exists>c. homotopic_with (\<lambda>x. True) S (sphere 0 1) f (\<lambda>x. c)))"
+       (is "?lhs = ?rhs")
+proof
+  assume L [rule_format]: ?lhs
+  show ?rhs
+  proof clarify
+    fix f :: "'a \<Rightarrow> 'a"
+    assume contf: "continuous_on S f" and fim: "f ` S \<subseteq> sphere 0 1"
+    obtain g where contg: "continuous_on UNIV g" and gim: "range g \<subseteq> sphere 0 1"
+               and gf: "\<And>x. x \<in> S \<Longrightarrow> g x = f x"
+      by (rule extend_map_UNIV_to_sphere_no_bounded_component [OF _ _ \<open>compact S\<close> contf fim L]) auto
+    then show "\<exists>c. homotopic_with (\<lambda>x. True) S (sphere 0 1) f (\<lambda>x. c)"
+      using nullhomotopic_from_contractible [OF contg gim]
+      by (metis assms compact_imp_closed contf empty_iff fim homotopic_with_equal nullhomotopic_into_sphere_extension)
+  qed
+next
+  assume R [rule_format]: ?rhs
+  show ?lhs
+    unfolding components_def
+  proof clarify
+    fix a
+    assume "a \<notin> S" and a: "bounded (connected_component_set (- S) a)"
+    have cont: "continuous_on S (\<lambda>x. inverse(norm(x - a)) *\<^sub>R (x - a))"
+      apply (intro continuous_intros)
+      using \<open>a \<notin> S\<close> by auto
+    have im: "(\<lambda>x. inverse(norm(x - a)) *\<^sub>R (x - a)) ` S \<subseteq> sphere 0 1"
+      by clarsimp (metis \<open>a \<notin> S\<close> eq_iff_diff_eq_0 left_inverse norm_eq_zero)
+    show False
+      using R cont im Borsuk_map_essential_bounded_component [OF \<open>compact S\<close> \<open>a \<notin> S\<close>] a by blast
+  qed
+qed
+
+
+corollary Borsuk_separation_theorem:
+  fixes S :: "'a::euclidean_space set"
+  assumes "compact S" and 2: "2 \<le> DIM('a)"
+    shows "connected(- S) \<longleftrightarrow>
+           (\<forall>f. continuous_on S f \<and> f ` S \<subseteq> sphere (0::'a) 1
+                \<longrightarrow> (\<exists>c. homotopic_with (\<lambda>x. True) S (sphere 0 1) f (\<lambda>x. c)))"
+       (is "?lhs = ?rhs")
+proof
+  assume L: ?lhs
+  show ?rhs
+  proof (cases "S = {}")
+    case True
+    then show ?thesis by auto
+  next
+    case False
+    then have "(\<forall>c\<in>components (- S). \<not> bounded c)"
+      by (metis L assms(1) bounded_empty cobounded_imp_unbounded compact_imp_bounded in_components_maximal order_refl)
+    then show ?thesis
+      by (simp add: Borsuk_separation_theorem_gen [OF \<open>compact S\<close>])
+  qed
+next
+  assume R: ?rhs
+  then show ?lhs
+    apply (simp add: Borsuk_separation_theorem_gen [OF \<open>compact S\<close>, symmetric])
+    apply (auto simp: components_def connected_iff_eq_connected_component_set)
+    using connected_component_in apply fastforce
+    using cobounded_unique_unbounded_component [OF _ 2, of "-S"] \<open>compact S\<close> compact_eq_bounded_closed by fastforce
+qed
+
+
+lemma homotopy_eqv_separation:
+  fixes S :: "'a::euclidean_space set" and T :: "'a set"
+  assumes "S homotopy_eqv T" and "compact S" and "compact T"
+  shows "connected(- S) \<longleftrightarrow> connected(- T)"
+proof -
+  consider "DIM('a) = 1" | "2 \<le> DIM('a)"
+    by (metis DIM_ge_Suc0 One_nat_def Suc_1 dual_order.antisym not_less_eq_eq)
+  then show ?thesis
+  proof cases
+    case 1
+    then show ?thesis
+      using bounded_connected_Compl_1 compact_imp_bounded homotopy_eqv_empty1 homotopy_eqv_empty2 assms by metis
+  next
+    case 2
+    with assms show ?thesis
+      by (simp add: Borsuk_separation_theorem homotopy_eqv_cohomotopic_triviality_null)
+  qed
+qed
+
+lemma Jordan_Brouwer_separation:
+  fixes S :: "'a::euclidean_space set" and a::'a
+  assumes hom: "S homeomorphic sphere a r" and "0 < r"
+    shows "\<not> connected(- S)"
+proof -
+  have "- sphere a r \<inter> ball a r \<noteq> {}"
+    using \<open>0 < r\<close> by (simp add: Int_absorb1 subset_eq)
+  moreover
+  have eq: "- sphere a r - ball a r = - cball a r"
+    by auto
+  have "- cball a r \<noteq> {}"
+  proof -
+    have "frontier (cball a r) \<noteq> {}"
+      using \<open>0 < r\<close> by auto
+    then show ?thesis
+      by (metis frontier_complement frontier_empty)
+  qed
+  with eq have "- sphere a r - ball a r \<noteq> {}"
+    by auto
+  moreover
+  have "connected (- S) = connected (- sphere a r)"
+  proof (rule homotopy_eqv_separation)
+    show "S homotopy_eqv sphere a r"
+      using hom homeomorphic_imp_homotopy_eqv by blast
+    show "compact (sphere a r)"
+      by simp
+    then show " compact S"
+      using hom homeomorphic_compactness by blast
+  qed
+  ultimately show ?thesis
+    using connected_Int_frontier [of "- sphere a r" "ball a r"] by (auto simp: \<open>0 < r\<close>)
+qed
+
+
+lemma Jordan_Brouwer_frontier:
+  fixes S :: "'a::euclidean_space set" and a::'a
+  assumes S: "S homeomorphic sphere a r" and T: "T \<in> components(- S)" and 2: "2 \<le> DIM('a)"
+    shows "frontier T = S"
+proof (cases r rule: linorder_cases)
+  assume "r < 0"
+  with S T show ?thesis by auto
+next
+  assume "r = 0"
+  with S T card_eq_SucD obtain b where "S = {b}"
+    by (auto simp: homeomorphic_finite [of "{a}" S])
+  have "components (- {b}) = { -{b}}"
+    using T \<open>S = {b}\<close> by (auto simp: components_eq_sing_iff connected_punctured_universe 2)
+  with T show ?thesis
+    by (metis \<open>S = {b}\<close> cball_trivial frontier_cball frontier_complement singletonD sphere_trivial)
+next
+  assume "r > 0"
+  have "compact S"
+    using homeomorphic_compactness compact_sphere S by blast
+  show ?thesis
+  proof (rule frontier_minimal_separating_closed)
+    show "closed S"
+      using \<open>compact S\<close> compact_eq_bounded_closed by blast
+    show "\<not> connected (- S)"
+      using Jordan_Brouwer_separation S \<open>0 < r\<close> by blast
+    obtain f g where hom: "homeomorphism S (sphere a r) f g"
+      using S by (auto simp: homeomorphic_def)
+    show "connected (- T)" if "closed T" "T \<subset> S" for T
+    proof -
+      have "f ` T \<subseteq> sphere a r"
+        using \<open>T \<subset> S\<close> hom homeomorphism_image1 by blast
+      moreover have "f ` T \<noteq> sphere a r"
+        using \<open>T \<subset> S\<close> hom
+        by (metis homeomorphism_image2 homeomorphism_of_subsets order_refl psubsetE)
+      ultimately have "f ` T \<subset> sphere a r" by blast
+      then have "connected (- f ` T)"
+        by (rule psubset_sphere_Compl_connected [OF _ \<open>0 < r\<close> 2])
+      moreover have "compact T"
+        using \<open>compact S\<close> bounded_subset compact_eq_bounded_closed that by blast
+      moreover then have "compact (f ` T)"
+        by (meson compact_continuous_image continuous_on_subset hom homeomorphism_def psubsetE \<open>T \<subset> S\<close>)
+      moreover have "T homotopy_eqv f ` T"
+        by (meson \<open>f ` T \<subseteq> sphere a r\<close> dual_order.strict_implies_order hom homeomorphic_def homeomorphic_imp_homotopy_eqv homeomorphism_of_subsets \<open>T \<subset> S\<close>)
+      ultimately show ?thesis
+        using homotopy_eqv_separation [of T "f`T"] by blast
+    qed
+  qed (rule T)
+qed
+
+lemma Jordan_Brouwer_nonseparation:
+  fixes S :: "'a::euclidean_space set" and a::'a
+  assumes S: "S homeomorphic sphere a r" and "T \<subset> S" and 2: "2 \<le> DIM('a)"
+    shows "connected(- T)"
+proof -
+  have *: "connected(C \<union> (S - T))" if "C \<in> components(- S)" for C
+  proof (rule connected_intermediate_closure)
+    show "connected C"
+      using in_components_connected that by auto
+    have "S = frontier C"
+      using "2" Jordan_Brouwer_frontier S that by blast
+    with closure_subset show "C \<union> (S - T) \<subseteq> closure C"
+      by (auto simp: frontier_def)
+  qed auto
+  have "components(- S) \<noteq> {}"
+    by (metis S bounded_empty cobounded_imp_unbounded compact_eq_bounded_closed compact_sphere
+              components_eq_empty homeomorphic_compactness)
+  then have "- T = (\<Union>C \<in> components(- S). C \<union> (S - T))"
+    using Union_components [of "-S"] \<open>T \<subset> S\<close> by auto
+  then show ?thesis
+    apply (rule ssubst)
+    apply (rule connected_Union)
+    using \<open>T \<subset> S\<close> apply (auto simp: *)
+    done
+qed
+
+end
--- a/src/HOL/Analysis/Lebesgue_Measure.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Lebesgue_Measure.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -11,6 +11,24 @@
   imports Finite_Product_Measure Bochner_Integration Caratheodory Complete_Measure Summation_Tests Regularity
 begin
 
+lemma measure_eqI_lessThan:
+  fixes M N :: "real measure"
+  assumes sets: "sets M = sets borel" "sets N = sets borel"
+  assumes fin: "\<And>x. emeasure M {x <..} < \<infinity>"
+  assumes "\<And>x. emeasure M {x <..} = emeasure N {x <..}"
+  shows "M = N"
+proof (rule measure_eqI_generator_eq_countable)
+  let ?LT = "\<lambda>a::real. {a <..}" let ?E = "range ?LT"
+  show "Int_stable ?E"
+    by (auto simp: Int_stable_def lessThan_Int_lessThan)
+
+  show "?E \<subseteq> Pow UNIV" "sets M = sigma_sets UNIV ?E" "sets N = sigma_sets UNIV ?E"
+    unfolding sets borel_Ioi by auto
+
+  show "?LT`Rats \<subseteq> ?E" "(\<Union>i\<in>Rats. ?LT i) = UNIV" "\<And>a. a \<in> ?LT`Rats \<Longrightarrow> emeasure M a \<noteq> \<infinity>"
+    using fin by (auto intro: Rats_no_bot_less simp: less_top)
+qed (auto intro: assms countable_rat)
+
 subsection \<open>Every right continuous and nondecreasing function gives rise to a measure\<close>
 
 definition interval_measure :: "(real \<Rightarrow> real) \<Rightarrow> real measure" where
--- a/src/HOL/Analysis/Measurable.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Measurable.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -618,6 +618,24 @@
   shows "Measurable.pred M ((R ^^ n) T)"
   by (induct n) (auto intro: assms)
 
+lemma measurable_compose_countable_restrict:
+  assumes P: "countable {i. P i}"
+    and f: "f \<in> M \<rightarrow>\<^sub>M count_space UNIV"
+    and Q: "\<And>i. P i \<Longrightarrow> pred M (Q i)"
+  shows "pred M (\<lambda>x. P (f x) \<and> Q (f x) x)"
+proof -
+  have P_f: "{x \<in> space M. P (f x)} \<in> sets M"
+    unfolding pred_def[symmetric] by (rule measurable_compose[OF f]) simp
+  have "pred (restrict_space M {x\<in>space M. P (f x)}) (\<lambda>x. Q (f x) x)"
+  proof (rule measurable_compose_countable'[where g=f, OF _ _ P])
+    show "f \<in> restrict_space M {x\<in>space M. P (f x)} \<rightarrow>\<^sub>M count_space {i. P i}"
+      by (rule measurable_count_space_extend[OF subset_UNIV])
+         (auto simp: space_restrict_space intro!: measurable_restrict_space1 f)
+  qed (auto intro!: measurable_restrict_space1 Q)
+  then show ?thesis
+    unfolding pred_restrict_space[OF P_f] by (simp cong: measurable_cong)
+qed
+
 hide_const (open) pred
 
 end
--- a/src/HOL/Analysis/Measure_Space.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Measure_Space.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -838,6 +838,38 @@
   qed
 qed
 
+lemma space_empty: "space M = {} \<Longrightarrow> M = count_space {}"
+  by (rule measure_eqI) (simp_all add: space_empty_iff)
+
+lemma measure_eqI_generator_eq_countable:
+  fixes M N :: "'a measure" and E :: "'a set set" and A :: "'a set set"
+  assumes E: "Int_stable E" "E \<subseteq> Pow \<Omega>" "\<And>X. X \<in> E \<Longrightarrow> emeasure M X = emeasure N X"
+    and sets: "sets M = sigma_sets \<Omega> E" "sets N = sigma_sets \<Omega> E"
+  and A: "A \<subseteq> E" "(\<Union>A) = \<Omega>" "countable A" "\<And>a. a \<in> A \<Longrightarrow> emeasure M a \<noteq> \<infinity>"
+  shows "M = N"
+proof cases
+  assume "\<Omega> = {}"
+  have *: "sigma_sets \<Omega> E = sets (sigma \<Omega> E)"
+    using E(2) by simp
+  have "space M = \<Omega>" "space N = \<Omega>"
+    using sets E(2) unfolding * by (auto dest: sets_eq_imp_space_eq simp del: sets_measure_of)
+  then show "M = N"
+    unfolding \<open>\<Omega> = {}\<close> by (auto dest: space_empty)
+next
+  assume "\<Omega> \<noteq> {}" with \<open>\<Union>A = \<Omega>\<close> have "A \<noteq> {}" by auto
+  from this \<open>countable A\<close> have rng: "range (from_nat_into A) = A"
+    by (rule range_from_nat_into)
+  show "M = N"
+  proof (rule measure_eqI_generator_eq[OF E sets])
+    show "range (from_nat_into A) \<subseteq> E"
+      unfolding rng using \<open>A \<subseteq> E\<close> .
+    show "(\<Union>i. from_nat_into A i) = \<Omega>"
+      unfolding rng using \<open>\<Union>A = \<Omega>\<close> .
+    show "emeasure M (from_nat_into A i) \<noteq> \<infinity>" for i
+      using rng by (intro A) auto
+  qed
+qed
+
 lemma measure_of_of_measure: "measure_of (space M) (sets M) (emeasure M) = M"
 proof (intro measure_eqI emeasure_measure_of_sigma)
   show "sigma_algebra (space M) (sets M)" ..
@@ -1097,6 +1129,9 @@
   "(\<And>x. x \<in> space M \<Longrightarrow> P x \<longleftrightarrow> Q x) \<Longrightarrow> (AE x in M. P x) \<longleftrightarrow> (AE x in M. Q x)"
   by auto
 
+lemma AE_cong_strong: "M = N \<Longrightarrow> (\<And>x. x \<in> space N =simp=> P x = Q x) \<Longrightarrow> (AE x in M. P x) \<longleftrightarrow> (AE x in N. Q x)"
+  by (auto simp: simp_implies_def)
+
 lemma AE_all_countable:
   "(AE x in M. \<forall>i. P i x) \<longleftrightarrow> (\<forall>i::'i::countable. AE x in M. P i x)"
 proof
@@ -2135,9 +2170,6 @@
   qed simp
 qed (simp add: emeasure_notin_sets)
 
-lemma space_empty: "space M = {} \<Longrightarrow> M = count_space {}"
-  by (rule measure_eqI) (simp_all add: space_empty_iff)
-
 lemma null_sets_count_space: "null_sets (count_space A) = { {} }"
   unfolding null_sets_def by (auto simp add: emeasure_count_space_eq_0)
 
--- a/src/HOL/Analysis/Nonnegative_Lebesgue_Integration.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Nonnegative_Lebesgue_Integration.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1692,6 +1692,16 @@
     by (simp add: ** nn_integral_suminf from_nat_into)
 qed
 
+lemma of_bool_Bex_eq_nn_integral:
+  assumes unique: "\<And>x y. x \<in> X \<Longrightarrow> y \<in> X \<Longrightarrow> P x \<Longrightarrow> P y \<Longrightarrow> x = y"
+  shows "of_bool (\<exists>y\<in>X. P y) = (\<integral>\<^sup>+y. of_bool (P y) \<partial>count_space X)"
+proof cases
+  assume "\<exists>y\<in>X. P y"
+  then obtain y where "P y" "y \<in> X" by auto
+  then show ?thesis
+    by (subst nn_integral_count_space'[where A="{y}"]) (auto dest: unique)
+qed (auto cong: nn_integral_cong_simp)
+
 lemma emeasure_UN_countable:
   assumes sets[measurable]: "\<And>i. i \<in> I \<Longrightarrow> X i \<in> sets M" and I[simp]: "countable I"
   assumes disj: "disjoint_family_on X I"
--- a/src/HOL/Analysis/Path_Connected.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Path_Connected.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1883,6 +1883,10 @@
   finally show ?thesis .
 qed
 
+corollary connected_punctured_universe:
+  "2 \<le> DIM('N::euclidean_space) \<Longrightarrow> connected(- {a::'N})"
+  by (simp add: path_connected_punctured_universe path_connected_imp_connected)
+
 lemma path_connected_sphere:
   assumes "2 \<le> DIM('a::euclidean_space)"
   shows "path_connected {x::'a. norm (x - a) = r}"
@@ -2104,6 +2108,32 @@
   thus ?case by (metis Diff_insert)
 qed
 
+lemma psubset_sphere_Compl_connected:
+  fixes S :: "'a::euclidean_space set"
+  assumes S: "S \<subset> sphere a r" and "0 < r" and 2: "2 \<le> DIM('a)"
+  shows "connected(- S)"
+proof -
+  have "S \<subseteq> sphere a r"
+    using S by blast
+  obtain b where "dist a b = r" and "b \<notin> S"
+    using S mem_sphere by blast
+  have CS: "- S = {x. dist a x \<le> r \<and> (x \<notin> S)} \<union> {x. r \<le> dist a x \<and> (x \<notin> S)}"
+    by (auto simp: )
+  have "{x. dist a x \<le> r \<and> x \<notin> S} \<inter> {x. r \<le> dist a x \<and> x \<notin> S} \<noteq> {}"
+    using \<open>b \<notin> S\<close> \<open>dist a b = r\<close> by blast
+  moreover have "connected {x. dist a x \<le> r \<and> x \<notin> S}"
+    apply (rule connected_intermediate_closure [of "ball a r"])
+    using assms by auto
+  moreover
+  have "connected {x. r \<le> dist a x \<and> x \<notin> S}"
+    apply (rule connected_intermediate_closure [of "- cball a r"])
+    using assms apply (auto intro: connected_complement_bounded_convex)
+    apply (metis ComplI interior_cball interior_closure mem_ball not_less)
+    done
+  ultimately show ?thesis
+    by (simp add: CS connected_Un)
+qed
+
 subsection\<open>Relations between components and path components\<close>
 
 lemma open_connected_component:
@@ -2505,9 +2535,9 @@
   { fix y
     assume y1: "y \<in> closure (connected_component_set S x)"
        and y2: "y \<notin> interior (connected_component_set S x)"
-    have 1: "y \<in> closure S"
+    have "y \<in> closure S"
       using y1 closure_mono connected_component_subset by blast
-    have "z \<in> interior (connected_component_set S x)"
+    moreover have "z \<in> interior (connected_component_set S x)"
           if "0 < e" "ball y e \<subseteq> interior S" "dist y z < e" for e z
     proof -
       have "ball y e \<subseteq> connected_component_set S y"
@@ -2516,12 +2546,12 @@
         done
       then show ?thesis
         using y1 apply (simp add: closure_approachable open_contains_ball_eq [OF open_interior])
-        by (metis (no_types, hide_lams) connected_component_eq_eq connected_component_in subsetD
-                       dist_commute mem_Collect_eq mem_ball mem_interior \<open>0 < e\<close> y2)
+        by (metis connected_component_eq dist_commute mem_Collect_eq mem_ball mem_interior subsetD \<open>0 < e\<close> y2)
     qed
-    then have 2: "y \<notin> interior S"
+    then have "y \<notin> interior S"
       using y2 by (force simp: open_contains_ball_eq [OF open_interior])
-    note 1 2
+    ultimately have "y \<in> frontier S"
+      by (auto simp: frontier_def)
   }
   then show ?thesis by (auto simp: frontier_def)
 qed
@@ -2565,6 +2595,49 @@
 by (rule order_trans [OF frontier_Union_subset_closure])
    (auto simp: closure_subset_eq)
 
+lemma frontier_of_components_subset:
+  fixes S :: "'a::real_normed_vector set"
+  shows "C \<in> components S \<Longrightarrow> frontier C \<subseteq> frontier S"
+  by (metis Path_Connected.frontier_of_connected_component_subset components_iff)
+
+lemma frontier_of_components_closed_complement:
+  fixes S :: "'a::real_normed_vector set"
+  shows "\<lbrakk>closed S; C \<in> components (- S)\<rbrakk> \<Longrightarrow> frontier C \<subseteq> S"
+  using frontier_complement frontier_of_components_subset frontier_subset_eq by blast
+
+lemma frontier_minimal_separating_closed:
+  fixes S :: "'a::real_normed_vector set"
+  assumes "closed S"
+      and nconn: "~ connected(- S)"
+      and C: "C \<in> components (- S)"
+      and conn: "\<And>T. \<lbrakk>closed T; T \<subset> S\<rbrakk> \<Longrightarrow> connected(- T)"
+    shows "frontier C = S"
+proof (rule ccontr)
+  assume "frontier C \<noteq> S"
+  then have "frontier C \<subset> S"
+    using frontier_of_components_closed_complement [OF \<open>closed S\<close> C] by blast
+  then have "connected(- (frontier C))"
+    by (simp add: conn)
+  have "\<not> connected(- (frontier C))"
+    unfolding connected_def not_not
+  proof (intro exI conjI)
+    show "open C"
+      using C \<open>closed S\<close> open_components by blast
+    show "open (- closure C)"
+      by blast
+    show "C \<inter> - closure C \<inter> - frontier C = {}"
+      using closure_subset by blast
+    show "C \<inter> - frontier C \<noteq> {}"
+      using C \<open>open C\<close> components_eq frontier_disjoint_eq by fastforce
+    show "- frontier C \<subseteq> C \<union> - closure C"
+      by (simp add: \<open>open C\<close> closed_Compl frontier_closures)
+    then show "- closure C \<inter> - frontier C \<noteq> {}"
+      by (metis (no_types, lifting) C Compl_subset_Compl_iff \<open>frontier C \<subset> S\<close> compl_sup frontier_closures in_components_subset psubsetE sup.absorb_iff2 sup.boundedE sup_bot.right_neutral sup_inf_absorb)
+  qed
+  then show False
+    using \<open>connected (- frontier C)\<close> by blast
+qed
+
 lemma connected_component_UNIV [simp]:
     fixes x :: "'a::real_normed_vector"
     shows "connected_component_set UNIV x = UNIV"
@@ -6140,6 +6213,51 @@
 apply (metis assms homotopy_eqv_cohomotopic_triviality_null_imp)
 by (metis assms homotopy_eqv_cohomotopic_triviality_null_imp homotopy_eqv_sym)
 
+lemma homotopy_eqv_homotopic_triviality_null_imp:
+  fixes S :: "'a::real_normed_vector set"
+    and T :: "'b::real_normed_vector set"
+    and U :: "'c::real_normed_vector set"
+  assumes "S homotopy_eqv T"
+      and f: "continuous_on U f" "f ` U \<subseteq> T"
+      and homSU: "\<And>f. \<lbrakk>continuous_on U f; f ` U \<subseteq> S\<rbrakk>
+                      \<Longrightarrow> \<exists>c. homotopic_with (\<lambda>x. True) U S f (\<lambda>x. c)"
+    shows "\<exists>c. homotopic_with (\<lambda>x. True) U T f (\<lambda>x. c)"
+proof -
+  obtain h k where h: "continuous_on S h" "h ` S \<subseteq> T"
+               and k: "continuous_on T k" "k ` T \<subseteq> S"
+               and hom: "homotopic_with (\<lambda>x. True) S S (k \<circ> h) id"
+                        "homotopic_with (\<lambda>x. True) T T (h \<circ> k) id"
+    using assms by (auto simp: homotopy_eqv_def)
+  obtain c::'a where "homotopic_with (\<lambda>x. True) U S (k \<circ> f) (\<lambda>x. c)"
+    apply (rule exE [OF homSU [of "k \<circ> f"]])
+    apply (intro continuous_on_compose h)
+    using k f  apply (force elim!: continuous_on_subset)+
+    done
+  then have "homotopic_with (\<lambda>x. True) U T (h \<circ> (k \<circ> f)) (h \<circ> (\<lambda>x. c))"
+    apply (rule homotopic_with_compose_continuous_left [where Y=S])
+    using h by auto
+  moreover have "homotopic_with (\<lambda>x. True) U T (id \<circ> f) ((h \<circ> k) \<circ> f)"
+    apply (rule homotopic_with_compose_continuous_right [where X=T])
+      apply (simp add: hom homotopic_with_symD)
+     using f apply auto
+    done
+  ultimately show ?thesis
+    using homotopic_with_trans by (fastforce simp add: o_def)
+qed
+
+lemma homotopy_eqv_homotopic_triviality_null:
+  fixes S :: "'a::real_normed_vector set"
+    and T :: "'b::real_normed_vector set"
+    and U :: "'c::real_normed_vector set"
+  assumes "S homotopy_eqv T"
+    shows "(\<forall>f. continuous_on U f \<and> f ` U \<subseteq> S
+                  \<longrightarrow> (\<exists>c. homotopic_with (\<lambda>x. True) U S f (\<lambda>x. c))) \<longleftrightarrow>
+           (\<forall>f. continuous_on U f \<and> f ` U \<subseteq> T
+                  \<longrightarrow> (\<exists>c. homotopic_with (\<lambda>x. True) U T f (\<lambda>x. c)))"
+apply (rule iffI)
+apply (metis assms homotopy_eqv_homotopic_triviality_null_imp)
+by (metis assms homotopy_eqv_homotopic_triviality_null_imp homotopy_eqv_sym)
+
 lemma homotopy_eqv_contractible_sets:
   fixes S :: "'a::real_normed_vector set"
     and T :: "'b::real_normed_vector set"
--- a/src/HOL/Analysis/Sigma_Algebra.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Analysis/Sigma_Algebra.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1244,6 +1244,10 @@
 lemma (in algebra) Int_stable: "Int_stable M"
   unfolding Int_stable_def by auto
 
+lemma Int_stableI_image:
+  "(\<And>i j. i \<in> I \<Longrightarrow> j \<in> I \<Longrightarrow> \<exists>k\<in>I. A i \<inter> A j = A k) \<Longrightarrow> Int_stable (A ` I)"
+  by (auto simp: Int_stable_def image_def)
+
 lemma Int_stableI:
   "(\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> a \<inter> b \<in> A) \<Longrightarrow> Int_stable A"
   unfolding Int_stable_def by auto
@@ -1574,6 +1578,9 @@
 using assms
 by(simp_all add: sets_measure_of_conv space_measure_of_conv)
 
+lemma space_in_measure_of[simp]: "\<Omega> \<in> sets (measure_of \<Omega> M \<mu>)"
+  by (subst sets_measure_of_conv) (auto simp: sigma_sets_top)
+
 lemma (in sigma_algebra) sets_measure_of_eq[simp]: "sets (measure_of \<Omega> M \<mu>) = M"
   using space_closed by (auto intro!: sigma_sets_eq)
 
@@ -2259,4 +2266,7 @@
   by (rule measurable_restrict_countable[OF X])
      (auto simp: eq[symmetric] space_restrict_space cong: measurable_cong' intro: f measurable_restrict_space1)
 
+lemma measurable_count_space_extend: "A \<subseteq> B \<Longrightarrow> f \<in> space M \<rightarrow> A \<Longrightarrow> f \<in> M \<rightarrow>\<^sub>M count_space B \<Longrightarrow> f \<in> M \<rightarrow>\<^sub>M count_space A"
+  by (auto simp: measurable_def)
+
 end
--- a/src/HOL/Cardinals/Ordinal_Arithmetic.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Cardinals/Ordinal_Arithmetic.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -1660,7 +1660,7 @@
     thus "((x, y), (s.max_fun_diff (rev_curr f m) (rev_curr g m), m)) \<in> s *o t"
       using rst.max_fun_diff_in[OF diff1] rs.max_fun_diff_in[OF diff2] diff1 diff2
         rst.max_fun_diff_max[OF diff1, of y] rs.max_fun_diff_le_eq[OF _ diff2, of x]
-      unfolding oprod_def m_def rev_curr_def fun_eq_iff by auto (metis s.in_notinI)
+      unfolding oprod_def m_def rev_curr_def fun_eq_iff by (auto intro: s.in_notinI)
   qed
 qed
 
--- a/src/HOL/Data_Structures/Balance.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Data_Structures/Balance.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -4,10 +4,138 @@
 
 theory Balance
 imports
+  Complex_Main
   "~~/src/HOL/Library/Tree"
-  "~~/src/HOL/Library/Log_Nat"
 begin
 
+(* mv *)
+
+text \<open>The lemmas about \<open>floor\<close> and \<open>ceiling\<close> of \<open>log 2\<close> should be generalized
+from 2 to \<open>n\<close> and should be made executable. \<close>
+
+lemma floor_log_nat: fixes b n k :: nat
+assumes "b \<ge> 2" "b^n \<le> k" "k < b^(n+1)"
+shows "floor (log b (real k)) = int(n)"
+proof -
+  have "k \<ge> 1"
+    using assms(1,2) one_le_power[of b n] by linarith
+  show ?thesis
+  proof(rule floor_eq2)
+    show "int n \<le> log b k"
+      using assms(1,2) \<open>k \<ge> 1\<close>
+      by(simp add: powr_realpow le_log_iff of_nat_power[symmetric] del: of_nat_power)
+  next
+    have "real k < b powr (real(n + 1))" using assms(1,3)
+      by (simp only: powr_realpow) (metis of_nat_less_iff of_nat_power)
+    thus "log b k < real_of_int (int n) + 1"
+      using assms(1) \<open>k \<ge> 1\<close> by(simp add: log_less_iff add_ac)
+  qed
+qed
+
+lemma ceil_log_nat: fixes b n k :: nat
+assumes "b \<ge> 2" "b^n < k" "k \<le> b^(n+1)"
+shows "ceiling (log b (real k)) = int(n)+1"
+proof(rule ceiling_eq)
+  show "int n < log b k"
+    using assms(1,2)
+    by(simp add: powr_realpow less_log_iff of_nat_power[symmetric] del: of_nat_power)
+next
+  have "real k \<le> b powr (real(n + 1))"
+    using assms(1,3)
+    by (simp only: powr_realpow) (metis of_nat_le_iff of_nat_power)
+  thus "log b k \<le> real_of_int (int n) + 1"
+    using assms(1,2) by(simp add: log_le_iff add_ac)
+qed
+
+lemma ex_power_ivl1: fixes b k :: nat assumes "b \<ge> 2"
+shows "k \<ge> 1 \<Longrightarrow> \<exists>n. b^n \<le> k \<and> k < b^(n+1)" (is "_ \<Longrightarrow> \<exists>n. ?P k n")
+proof(induction k)
+  case 0 thus ?case by simp
+next
+  case (Suc k)
+  show ?case
+  proof cases
+    assume "k=0"
+    hence "?P (Suc k) 0"
+      using assms by simp
+    thus ?case ..
+  next
+    assume "k\<noteq>0"
+    with Suc obtain n where IH: "?P k n" by auto
+    show ?case
+    proof (cases "k = b^(n+1) - 1")
+      case True
+      hence "?P (Suc k) (n+1)" using assms
+        by (simp add: not_less_eq_eq[symmetric])
+      thus ?thesis ..
+    next
+      case False
+      hence "?P (Suc k) n" using IH by auto
+      thus ?thesis ..
+    qed
+  qed
+qed
+
+lemma ex_power_ivl2: fixes b k :: nat assumes "b \<ge> 2" "(k::nat) \<ge> 2"
+shows "\<exists>n. b^n < k \<and> k \<le> b^(n+1)"
+proof -
+  have "1 \<le> k - 1"
+    using assms(2) by arith
+  from ex_power_ivl1[OF assms(1) this]
+  obtain n where "b ^ n \<le> k - 1 \<and> k - 1 < b ^ (n + 1)" ..
+  hence "b^n < k \<and> k \<le> b^(n+1)"
+    using assms by auto
+  thus ?thesis ..
+qed
+
+lemma ceil_log2_div2: assumes "n \<ge> 2"
+shows "ceiling(log 2 (real n)) = ceiling(log 2 ((n-1) div 2 + 1)) + 1"
+proof cases
+  assume "n=2"
+  thus ?thesis by simp
+next
+  let ?m = "(n-1) div 2 + 1"
+  assume "n\<noteq>2"
+  hence "2 \<le> ?m"
+    using assms by arith
+  then obtain i where i: "2 ^ i < ?m" "?m \<le> 2 ^ (i + 1)"
+    using ex_power_ivl2[of 2 ?m] by auto
+  have "n \<le> 2*?m"
+    by arith
+  also have "2*?m \<le> 2 ^ ((i+1)+1)"
+    using i(2) by simp
+  finally have *: "n \<le> \<dots>" .
+  have "2^(i+1) < n"
+    using i(1) by (auto simp add: less_Suc_eq_0_disj)
+  from ceil_log_nat[OF _ this *] ceil_log_nat[OF _ i]
+  show ?thesis by simp
+qed
+
+lemma floor_log2_div2: fixes n :: nat assumes "n \<ge> 2"
+shows "floor(log 2 n) = floor(log 2 (n div 2)) + 1"
+proof cases
+  assume "n=2"
+  thus ?thesis by simp
+next
+  let ?m = "n div 2"
+  assume "n\<noteq>2"
+  hence "1 \<le> ?m"
+    using assms by arith
+  then obtain i where i: "2 ^ i \<le> ?m" "?m < 2 ^ (i + 1)"
+    using ex_power_ivl1[of 2 ?m] by auto
+  have "2^(i+1) \<le> 2*?m"
+    using i(1) by simp
+  also have "2*?m \<le> n"
+    by arith
+  finally have *: "2^(i+1) \<le> \<dots>" .
+  have "n < 2^(i+1+1)"
+    using i(2) by simp
+  from floor_log_nat[OF _ * this] floor_log_nat[OF _ i]
+  show ?thesis by simp
+qed
+
+(* end of mv *)
+
 fun bal :: "'a list \<Rightarrow> nat \<Rightarrow> 'a tree * 'a list" where
 "bal xs n = (if n=0 then (Leaf,xs) else
  (let m = n div 2;
@@ -28,8 +156,8 @@
   "n > 0 \<Longrightarrow>
    bal xs n =
   (let m = n div 2;
-      (l, ys) = Balance.bal xs m;
-      (r, zs) = Balance.bal (tl ys) (n-1-m)
+      (l, ys) = bal xs m;
+      (r, zs) = bal (tl ys) (n-1-m)
   in (Node l (hd ys) r, zs))"
 by(simp_all add: bal.simps)
 
@@ -78,39 +206,22 @@
 using bal_inorder[of xs "length xs"]
 by (metis balance_list_def order_refl prod.collapse take_all)
 
-lemma bal_height: "bal xs n = (t,ys) \<Longrightarrow> height t = floorlog 2 n"
+corollary inorder_balance_tree[simp]: "inorder(balance_tree t) = inorder t"
+by(simp add: balance_tree_def inorder_balance_list)
+
+corollary size_balance_list[simp]: "size(balance_list xs) = length xs"
+by (metis inorder_balance_list length_inorder)
+
+corollary size_balance_tree[simp]: "size(balance_tree t) = size t"
+by(simp add: balance_tree_def inorder_balance_list)
+
+lemma min_height_bal:
+  "bal xs n = (t,ys) \<Longrightarrow> min_height t = nat(floor(log 2 (n + 1)))"
 proof(induction xs n arbitrary: t ys rule: bal.induct)
   case (1 xs n) show ?case
   proof cases
     assume "n = 0" thus ?thesis
-      using "1.prems" by (simp add: floorlog_def bal_simps)
-  next
-    assume [arith]: "n \<noteq> 0"
-    from "1.prems" obtain l r xs' where
-      b1: "bal xs (n div 2) = (l,xs')" and
-      b2: "bal (tl xs') (n - 1 - n div 2) = (r,ys)" and
-      t: "t = \<langle>l, hd xs', r\<rangle>"
-      by(auto simp: bal_simps Let_def split: prod.splits)
-    let ?log1 = "floorlog 2 (n div 2)"
-    let ?log2 = "floorlog 2 (n - 1 - n div 2)"
-    have IH1: "height l = ?log1" using "1.IH"(1) b1 by simp
-    have IH2: "height r = ?log2" using "1.IH"(2) b1 b2 by simp
-    have "n div 2 \<ge> n - 1 - n div 2" by arith
-    hence le: "?log2 \<le> ?log1" by(simp add:floorlog_mono)
-    have "height t = max ?log1 ?log2 + 1" by (simp add: t IH1 IH2)
-    also have "\<dots> = ?log1 + 1" using le by (simp add: max_absorb1)
-    also have "\<dots> = floorlog 2 n" by (simp add: compute_floorlog)
-    finally show ?thesis .
-  qed
-qed
-
-lemma bal_min_height:
-  "bal xs n = (t,ys) \<Longrightarrow> min_height t = floorlog 2 (n + 1) - 1"
-proof(induction xs n arbitrary: t ys rule: bal.induct)
-  case (1 xs n) show ?case
-  proof cases
-    assume "n = 0" thus ?thesis
-      using "1.prems" by (simp add: floorlog_def bal_simps)
+      using "1.prems" by (simp add: bal_simps)
   next
     assume [arith]: "n \<noteq> 0"
     from "1.prems" obtain l r xs' where
@@ -118,54 +229,78 @@
       b2: "bal (tl xs') (n - 1 - n div 2) = (r,ys)" and
       t: "t = \<langle>l, hd xs', r\<rangle>"
       by(auto simp: bal_simps Let_def split: prod.splits)
-    let ?log1 = "floorlog 2 (n div 2 + 1) - 1"
-    let ?log2 = "floorlog 2 (n - 1 - n div 2 + 1) - 1"
-    let ?log2' = "floorlog 2 (n - n div 2) - 1"
-    have "n - 1 - n div 2 + 1 = n - n div 2" by arith
-    hence IH2: "min_height r = ?log2'" using "1.IH"(2) b1 b2 by simp
+    let ?log1 = "nat (floor(log 2 (n div 2 + 1)))"
+    let ?log2 = "nat (floor(log 2 (n - 1 - n div 2 + 1)))"
     have IH1: "min_height l = ?log1" using "1.IH"(1) b1 by simp
-    have *: "floorlog 2 (n - n div 2) \<ge> 1" by (simp add: floorlog_def)
-    have "n div 2 + 1 \<ge> n - n div 2" by arith
-    with * have le: "?log2' \<le> ?log1" by(simp add: floorlog_mono diff_le_mono)
-    have "min_height t = min ?log1 ?log2' + 1" by (simp add: t IH1 IH2)
-    also have "\<dots> = ?log2' + 1" using le by (simp add: min_absorb2)
-    also have "\<dots> = floorlog 2 (n - n div 2)" by(simp add: floorlog_def)
-    also have "n - n div 2 = (n+1) div 2" by arith
-    also have "floorlog 2 \<dots> = floorlog 2 (n+1) - 1"
-      by (simp add: compute_floorlog)
+    have IH2: "min_height r = ?log2" using "1.IH"(2) b1 b2 by simp
+    have "(n+1) div 2 \<ge> 1" by arith
+    hence 0: "log 2 ((n+1) div 2) \<ge> 0" by simp
+    have "n - 1 - n div 2 + 1 \<le> n div 2 + 1" by arith
+    hence le: "?log2 \<le> ?log1"
+      by(simp add: nat_mono floor_mono)
+    have "min_height t = min ?log1 ?log2 + 1" by (simp add: t IH1 IH2)
+    also have "\<dots> = ?log2 + 1" using le by (simp add: min_absorb2)
+    also have "n - 1 - n div 2 + 1 = (n+1) div 2" by linarith
+    also have "nat (floor(log 2 ((n+1) div 2))) + 1
+       = nat (floor(log 2 ((n+1) div 2) + 1))"
+      using 0 by linarith
+    also have "\<dots> = nat (floor(log 2 (n + 1)))"
+      using floor_log2_div2[of "n+1"] by (simp add: log_mult)
+    finally show ?thesis .
+  qed
+qed
+
+lemma height_bal:
+  "bal xs n = (t,ys) \<Longrightarrow> height t = nat \<lceil>log 2 (n + 1)\<rceil>"
+proof(induction xs n arbitrary: t ys rule: bal.induct)
+  case (1 xs n) show ?case
+  proof cases
+    assume "n = 0" thus ?thesis
+      using "1.prems" by (simp add: bal_simps)
+  next
+    assume [arith]: "n \<noteq> 0"
+    from "1.prems" obtain l r xs' where
+      b1: "bal xs (n div 2) = (l,xs')" and
+      b2: "bal (tl xs') (n - 1 - n div 2) = (r,ys)" and
+      t: "t = \<langle>l, hd xs', r\<rangle>"
+      by(auto simp: bal_simps Let_def split: prod.splits)
+    let ?log1 = "nat \<lceil>log 2 (n div 2 + 1)\<rceil>"
+    let ?log2 = "nat \<lceil>log 2 (n - 1 - n div 2 + 1)\<rceil>"
+    have IH1: "height l = ?log1" using "1.IH"(1) b1 by simp
+    have IH2: "height r = ?log2" using "1.IH"(2) b1 b2 by simp
+    have 0: "log 2 (n div 2 + 1) \<ge> 0" by auto
+    have "n - 1 - n div 2 + 1 \<le> n div 2 + 1" by arith
+    hence le: "?log2 \<le> ?log1"
+      by(simp add: nat_mono ceiling_mono del: nat_ceiling_le_eq)
+    have "height t = max ?log1 ?log2 + 1" by (simp add: t IH1 IH2)
+    also have "\<dots> = ?log1 + 1" using le by (simp add: max_absorb1)
+    also have "\<dots> = nat \<lceil>log 2 (n div 2 + 1) + 1\<rceil>" using 0 by linarith
+    also have "\<dots> = nat \<lceil>log 2 (n + 1)\<rceil>"
+      using ceil_log2_div2[of "n+1"] by (simp)
     finally show ?thesis .
   qed
 qed
 
 lemma balanced_bal:
   assumes "bal xs n = (t,ys)" shows "balanced t"
-proof -
-  have "floorlog 2 n \<le> floorlog 2 (n+1)" by (rule floorlog_mono) auto
-  thus ?thesis unfolding balanced_def
-    using bal_height[OF assms] bal_min_height[OF assms] by linarith
-qed
+unfolding balanced_def
+using height_bal[OF assms] min_height_bal[OF assms]
+by linarith
 
-corollary size_balance_list[simp]: "size(balance_list xs) = length xs"
-by (metis inorder_balance_list length_inorder)
+lemma height_balance_list:
+  "height (balance_list xs) = nat \<lceil>log 2 (length xs + 1)\<rceil>"
+by (metis balance_list_def height_bal prod.collapse)
+
+corollary height_balance_tree:
+  "height (balance_tree t) = nat(ceiling(log 2 (size t + 1)))"
+by(simp add: balance_tree_def height_balance_list)
 
 corollary balanced_balance_list[simp]: "balanced (balance_list xs)"
 by (metis balance_list_def balanced_bal prod.collapse)
 
-lemma height_balance_list: "height(balance_list xs) = floorlog 2 (length xs)"
-by (metis bal_height balance_list_def prod.collapse)
-
-lemma inorder_balance_tree[simp]: "inorder(balance_tree t) = inorder t"
-by(simp add: balance_tree_def inorder_balance_list)
-
-lemma size_balance_tree[simp]: "size(balance_tree t) = size t"
-by(simp add: balance_tree_def inorder_balance_list)
-
 corollary balanced_balance_tree[simp]: "balanced (balance_tree t)"
 by (simp add: balance_tree_def)
 
-lemma height_balance_tree: "height(balance_tree t) = floorlog 2 (size t)"
-by(simp add: balance_tree_def height_balance_list)
-
 lemma wbalanced_bal: "bal xs n = (t,ys) \<Longrightarrow> wbalanced t"
 proof(induction xs n arbitrary: t ys rule: bal.induct)
   case (1 xs n)
--- a/src/HOL/Divides.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Divides.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -542,6 +542,10 @@
   "even a \<longleftrightarrow> a mod 2 = 0"
   by (fact dvd_eq_mod_eq_0)
 
+lemma odd_iff_mod_2_eq_one:
+  "odd a \<longleftrightarrow> a mod 2 = 1"
+  by (auto simp add: even_iff_mod_2_eq_zero)
+
 lemma even_succ_div_two [simp]:
   "even a \<Longrightarrow> (a + 1) div 2 = a div 2"
   by (cases "a = 0") (auto elim!: evenE dest: mult_not_zero)
--- a/src/HOL/Int.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Int.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -983,6 +983,20 @@
 
 end
 
+lemma transfer_rule_of_int:
+  fixes R :: "'a::ring_1 \<Rightarrow> 'b::ring_1 \<Rightarrow> bool"
+  assumes [transfer_rule]: "R 0 0" "R 1 1"
+    "rel_fun R (rel_fun R R) plus plus"
+    "rel_fun R R uminus uminus"
+  shows "rel_fun HOL.eq R of_int of_int"
+proof -
+  note transfer_rule_of_nat [transfer_rule]
+  have [transfer_rule]: "rel_fun HOL.eq R of_nat of_nat"
+    by transfer_prover
+  show ?thesis
+    by (unfold of_int_of_nat [abs_def]) transfer_prover
+qed
+
 lemma nat_mult_distrib:
   fixes z z' :: int
   assumes "0 \<le> z"
--- a/src/HOL/Library/Countable_Set.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Library/Countable_Set.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -284,6 +284,9 @@
 lemma countable_Collect_finite: "countable (Collect (finite::'a::countable set\<Rightarrow>bool))"
   by (simp add: Collect_finite_eq_lists)
 
+lemma countable_int: "countable \<int>"
+  unfolding Ints_def by auto
+
 lemma countable_rat: "countable \<rat>"
   unfolding Rats_def by auto
 
--- a/src/HOL/Library/Extended_Nonnegative_Real.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Library/Extended_Nonnegative_Real.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -220,6 +220,11 @@
   shows "summable f \<Longrightarrow> finite I \<Longrightarrow> \<forall>m\<in>- I. 0 \<le> f m \<Longrightarrow> setsum f I \<le> suminf f"
   by (rule sums_le[OF _ sums_If_finite_set summable_sums]) auto
 
+lemma suminf_eq_SUP_real:
+  assumes X: "summable X" "\<And>i. 0 \<le> X i" shows "suminf X = (SUP i. \<Sum>n<i. X n::real)"
+  by (intro LIMSEQ_unique[OF summable_LIMSEQ] X LIMSEQ_incseq_SUP)
+     (auto intro!: bdd_aboveI2[where M="\<Sum>i. X i"] setsum_le_suminf X monoI setsum_mono3)
+
 subsection \<open>Defining the extended non-negative reals\<close>
 
 text \<open>Basic definitions and type class setup\<close>
--- a/src/HOL/Library/Multiset.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Library/Multiset.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -545,6 +545,8 @@
 interpretation subset_mset: ordered_cancel_comm_monoid_diff "op +" 0 "op \<le>#" "op <#" "op -"
   by standard (simp, fact mset_subset_eq_exists_conv)
 
+declare subset_mset.add_diff_assoc[simp] subset_mset.add_diff_assoc2[simp]
+
 lemma mset_subset_eq_mono_add_right_cancel: "(A::'a multiset) + C \<subseteq># B + C \<longleftrightarrow> A \<subseteq># B"
    by (fact subset_mset.add_le_cancel_right)
 
@@ -2649,7 +2651,7 @@
       using K N trans True by (meson that transE)
     ultimately show ?thesis
       by (rule_tac x = I in exI, rule_tac x = J in exI, rule_tac x = "(K - {#a#}) + K'" in exI)
-        (use z y N in \<open>auto simp: subset_mset.add_diff_assoc dest: in_diffD\<close>)
+        (use z y N in \<open>auto simp del: subset_mset.add_diff_assoc2 dest: in_diffD\<close>)
   next
     case False
     then have "a \<in># I" by (metis N(2) union_iff union_single_eq_member z)
@@ -2658,7 +2660,7 @@
     ultimately show ?thesis
       by (rule_tac x = "I - {#a#}" in exI, rule_tac x = "add_mset a J" in exI,
           rule_tac x = "K + K'" in exI)
-        (use z y N False K in \<open>auto simp: subset_mset.diff_add_assoc2\<close>)
+        (use z y N False K in \<open>auto simp: add.assoc\<close>)
   qed
 qed
 
--- a/src/HOL/Probability/Central_Limit_Theorem.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Central_Limit_Theorem.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -8,7 +8,7 @@
   imports Levy
 begin
 
-theorem (in prob_space) central_limit_theorem:
+theorem (in prob_space) central_limit_theorem_zero_mean:
   fixes X :: "nat \<Rightarrow> 'a \<Rightarrow> real"
     and \<mu> :: "real measure"
     and \<sigma> :: real
@@ -114,4 +114,31 @@
   qed (auto intro!: real_dist_normal_dist simp: S_def)
 qed
 
+theorem (in prob_space) central_limit_theorem:
+  fixes X :: "nat \<Rightarrow> 'a \<Rightarrow> real"
+    and \<mu> :: "real measure"
+    and \<sigma> :: real
+    and S :: "nat \<Rightarrow> 'a \<Rightarrow> real"
+  assumes X_indep: "indep_vars (\<lambda>i. borel) X UNIV"
+    and X_integrable: "\<And>n. integrable M (X n)"
+    and X_mean: "\<And>n. expectation (X n) = m"
+    and \<sigma>_pos: "\<sigma> > 0"
+    and X_square_integrable: "\<And>n. integrable M (\<lambda>x. (X n x)\<^sup>2)"
+    and X_variance: "\<And>n. variance (X n) = \<sigma>\<^sup>2"
+    and X_distrib: "\<And>n. distr M borel (X n) = \<mu>"
+  defines "X' i x \<equiv> X i x - m"
+  shows "weak_conv_m (\<lambda>n. distr M borel (\<lambda>x. (\<Sum>i<n. X' i x) / sqrt (n*\<sigma>\<^sup>2))) std_normal_distribution"
+proof (intro central_limit_theorem_zero_mean)
+  show "indep_vars (\<lambda>i. borel) X' UNIV"
+    unfolding X'_def[abs_def] using X_indep by (rule indep_vars_compose2) auto
+  show "integrable M (X' n)" "expectation (X' n) = 0" for n
+    using X_integrable X_mean by (auto simp: X'_def[abs_def] prob_space)
+  show "\<sigma> > 0" "integrable M (\<lambda>x. (X' n x)\<^sup>2)" "variance (X' n) = \<sigma>\<^sup>2" for n
+    using \<open>0 < \<sigma>\<close> X_integrable X_mean X_square_integrable X_variance unfolding X'_def
+    by (auto simp: prob_space power2_diff)
+  show "distr M borel (X' n) = distr \<mu> borel (\<lambda>x. x - m)" for n
+    unfolding X_distrib[of n, symmetric] using X_integrable
+    by (subst distr_distr) (auto simp: X'_def[abs_def] comp_def)
+qed
+
 end
--- a/src/HOL/Probability/Giry_Monad.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Giry_Monad.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -28,6 +28,9 @@
   show "subprob_space M" by standard fact+
 qed
 
+lemma (in subprob_space) emeasure_subprob_space_less_top: "emeasure M A \<noteq> top"
+  using emeasure_finite[of A] .
+
 lemma prob_space_imp_subprob_space:
   "prob_space M \<Longrightarrow> subprob_space M"
   by (rule subprob_spaceI) (simp_all add: prob_space.emeasure_space_1 prob_space.not_empty)
@@ -245,6 +248,43 @@
     by (auto dest: subprob_space_kernel sets_kernel)
 qed
 
+lemma measurable_subprob_algebra_generated:
+  assumes eq: "sets N = sigma_sets \<Omega> G" and "Int_stable G" "G \<subseteq> Pow \<Omega>"
+  assumes subsp: "\<And>a. a \<in> space M \<Longrightarrow> subprob_space (K a)"
+  assumes sets: "\<And>a. a \<in> space M \<Longrightarrow> sets (K a) = sets N"
+  assumes "\<And>A. A \<in> G \<Longrightarrow> (\<lambda>a. emeasure (K a) A) \<in> borel_measurable M"
+  assumes \<Omega>: "(\<lambda>a. emeasure (K a) \<Omega>) \<in> borel_measurable M"
+  shows "K \<in> measurable M (subprob_algebra N)"
+proof (rule measurable_subprob_algebra)
+  fix a assume "a \<in> space M" then show "subprob_space (K a)" "sets (K a) = sets N" by fact+
+next
+  interpret G: sigma_algebra \<Omega> "sigma_sets \<Omega> G"
+    using \<open>G \<subseteq> Pow \<Omega>\<close> by (rule sigma_algebra_sigma_sets)
+  fix A assume "A \<in> sets N" with assms(2,3) show "(\<lambda>a. emeasure (K a) A) \<in> borel_measurable M"
+    unfolding \<open>sets N = sigma_sets \<Omega> G\<close>
+  proof (induction rule: sigma_sets_induct_disjoint)
+    case (basic A) then show ?case by fact
+  next
+    case empty then show ?case by simp
+  next
+    case (compl A)
+    have "(\<lambda>a. emeasure (K a) (\<Omega> - A)) \<in> borel_measurable M \<longleftrightarrow>
+      (\<lambda>a. emeasure (K a) \<Omega> - emeasure (K a) A) \<in> borel_measurable M"
+      using G.top G.sets_into_space sets eq compl subprob_space.emeasure_subprob_space_less_top[OF subsp]
+      by (intro measurable_cong emeasure_Diff) auto
+    with compl \<Omega> show ?case
+      by simp
+  next
+    case (union F)
+    moreover have "(\<lambda>a. emeasure (K a) (\<Union>i. F i)) \<in> borel_measurable M \<longleftrightarrow>
+        (\<lambda>a. \<Sum>i. emeasure (K a) (F i)) \<in> borel_measurable M"
+      using sets union eq
+      by (intro measurable_cong suminf_emeasure[symmetric]) auto
+    ultimately show ?case
+      by auto
+  qed
+qed
+
 lemma space_subprob_algebra_empty_iff:
   "space (subprob_algebra N) = {} \<longleftrightarrow> space N = {}"
 proof
@@ -1080,7 +1120,7 @@
   shows "space (bind M f) = space N"
   using assms by (intro sets_eq_imp_space_eq sets_bind)
 
-lemma bind_cong:
+lemma bind_cong_All:
   assumes "\<forall>x \<in> space M. f x = g x"
   shows "bind M f = bind M g"
 proof (cases "space M = {}")
@@ -1090,6 +1130,10 @@
   with \<open>space M \<noteq> {}\<close> and assms show ?thesis by (simp add: bind_nonempty cong: distr_cong)
 qed (simp add: bind_empty)
 
+lemma bind_cong:
+  "M = N \<Longrightarrow> (\<And>x. x \<in> space M \<Longrightarrow> f x = g x) \<Longrightarrow> bind M f = bind N g"
+  using bind_cong_All[of M f g] by auto
+
 lemma bind_nonempty':
   assumes "f \<in> measurable M (subprob_algebra N)" "x \<in> space M"
   shows "bind M f = join (distr M (subprob_algebra N) f)"
@@ -1121,8 +1165,8 @@
 qed (simp add: bind_empty space_empty[of M] nn_integral_count_space)
 
 lemma AE_bind:
+  assumes N[measurable]: "N \<in> measurable M (subprob_algebra B)"
   assumes P[measurable]: "Measurable.pred B P"
-  assumes N[measurable]: "N \<in> measurable M (subprob_algebra B)"
   shows "(AE x in M \<bind> N. P x) \<longleftrightarrow> (AE x in M. AE y in N x. P y)"
 proof cases
   assume M: "space M = {}" show ?thesis
@@ -1454,7 +1498,7 @@
   also from Mh have "\<And>x. x \<in> space M \<Longrightarrow> h x \<in> measurable M' N" by measurable
   hence "do {x \<leftarrow> M; do {y \<leftarrow> f x; return N (h x y)} \<bind> g} =
             do {x \<leftarrow> M; y \<leftarrow> f x; return N (h x y) \<bind> g}"
-    apply (intro ballI bind_cong bind_assoc)
+    apply (intro ballI bind_cong refl bind_assoc)
     apply (subst measurable_cong_sets[OF sets_kernel[OF Mf] refl], simp)
     apply (rule measurable_compose[OF _ return_measurable], auto intro: Mg)
     done
@@ -1522,4 +1566,216 @@
   "null_measure M \<in> space (subprob_algebra M) \<longleftrightarrow> space M \<noteq> {}"
 by(simp add: space_subprob_algebra subprob_space_null_measure_iff)
 
+subsection \<open>Giry monad on probability spaces\<close>
+
+definition prob_algebra :: "'a measure \<Rightarrow> 'a measure measure" where
+  "prob_algebra K = restrict_space (subprob_algebra K) {M. prob_space M}"
+
+lemma space_prob_algebra: "space (prob_algebra M) = {N. sets N = sets M \<and> prob_space N}"
+  unfolding prob_algebra_def by (auto simp: space_subprob_algebra space_restrict_space prob_space_imp_subprob_space)
+
+lemma measurable_measure_prob_algebra[measurable]:
+  "a \<in> sets A \<Longrightarrow> (\<lambda>M. Sigma_Algebra.measure M a) \<in> prob_algebra A \<rightarrow>\<^sub>M borel"
+  unfolding prob_algebra_def by (intro measurable_restrict_space1 measurable_measure_subprob_algebra)
+
+lemma measurable_prob_algebraD:
+  "f \<in> N \<rightarrow>\<^sub>M prob_algebra M \<Longrightarrow> f \<in> N \<rightarrow>\<^sub>M subprob_algebra M"
+  unfolding prob_algebra_def measurable_restrict_space2_iff by auto
+
+lemma measure_measurable_prob_algebra2:
+  "Sigma (space M) A \<in> sets (M \<Otimes>\<^sub>M N) \<Longrightarrow> L \<in> M \<rightarrow>\<^sub>M prob_algebra N \<Longrightarrow>
+    (\<lambda>x. Sigma_Algebra.measure (L x) (A x)) \<in> borel_measurable M"
+  using measure_measurable_subprob_algebra2[of M A N L] by (auto intro: measurable_prob_algebraD)
+
+lemma measurable_prob_algebraI:
+  "(\<And>x. x \<in> space N \<Longrightarrow> prob_space (f x)) \<Longrightarrow> f \<in> N \<rightarrow>\<^sub>M subprob_algebra M \<Longrightarrow> f \<in> N \<rightarrow>\<^sub>M prob_algebra M"
+  unfolding prob_algebra_def by (intro measurable_restrict_space2) auto
+
+lemma measurable_distr_prob_space:
+  assumes f: "f \<in> M \<rightarrow>\<^sub>M N"
+  shows "(\<lambda>M'. distr M' N f) \<in> prob_algebra M \<rightarrow>\<^sub>M prob_algebra N"
+  unfolding prob_algebra_def measurable_restrict_space2_iff
+proof (intro conjI measurable_restrict_space1 measurable_distr f)
+  show "(\<lambda>M'. distr M' N f) \<in> space (restrict_space (subprob_algebra M) (Collect prob_space)) \<rightarrow> Collect prob_space"
+    using f by (auto simp: space_restrict_space space_subprob_algebra intro!: prob_space.prob_space_distr)
+qed
+
+lemma measurable_return_prob_space[measurable]: "return N \<in> N \<rightarrow>\<^sub>M prob_algebra N"
+  by (rule measurable_prob_algebraI) (auto simp: prob_space_return)
+
+lemma measurable_distr_prob_space2[measurable (raw)]:
+  assumes f: "g \<in> L \<rightarrow>\<^sub>M prob_algebra M" "(\<lambda>(x, y). f x y) \<in> L \<Otimes>\<^sub>M M \<rightarrow>\<^sub>M N"
+  shows "(\<lambda>x. distr (g x) N (f x)) \<in> L \<rightarrow>\<^sub>M prob_algebra N"
+  unfolding prob_algebra_def measurable_restrict_space2_iff
+proof (intro conjI measurable_restrict_space1 measurable_distr2[where M=M] f measurable_prob_algebraD)
+  show "(\<lambda>x. distr (g x) N (f x)) \<in> space L \<rightarrow> Collect prob_space"
+    using f subprob_measurableD[OF measurable_prob_algebraD[OF f(1)]]
+    by (auto simp: measurable_restrict_space2_iff prob_algebra_def
+             intro!: prob_space.prob_space_distr)
+qed
+
+lemma measurable_bind_prob_space:
+  assumes f: "f \<in> M \<rightarrow>\<^sub>M prob_algebra N" and g: "g \<in> N \<rightarrow>\<^sub>M prob_algebra R"
+  shows "(\<lambda>x. bind (f x) g) \<in> M \<rightarrow>\<^sub>M prob_algebra R"
+  unfolding prob_algebra_def measurable_restrict_space2_iff
+proof (intro conjI measurable_restrict_space1 measurable_bind2[where N=N] f g measurable_prob_algebraD)
+  show "(\<lambda>x. f x \<bind> g) \<in> space M \<rightarrow> Collect prob_space"
+    using g f subprob_measurableD[OF measurable_prob_algebraD[OF f]]
+    by (auto simp: measurable_restrict_space2_iff prob_algebra_def
+                intro!: prob_space.prob_space_bind[where S=R] AE_I2)
+qed
+
+lemma measurable_bind_prob_space2[measurable (raw)]:
+  assumes f: "f \<in> M \<rightarrow>\<^sub>M prob_algebra N" and g: "(\<lambda>(x, y). g x y) \<in> (M \<Otimes>\<^sub>M N) \<rightarrow>\<^sub>M prob_algebra R"
+  shows "(\<lambda>x. bind (f x) (g x)) \<in> M \<rightarrow>\<^sub>M prob_algebra R"
+  unfolding prob_algebra_def measurable_restrict_space2_iff
+proof (intro conjI measurable_restrict_space1 measurable_bind[where N=N] f g measurable_prob_algebraD)
+  show "(\<lambda>x. f x \<bind> g x) \<in> space M \<rightarrow> Collect prob_space"
+    using g f subprob_measurableD[OF measurable_prob_algebraD[OF f]]
+      using measurable_space[OF g]
+    by (auto simp: measurable_restrict_space2_iff prob_algebra_def space_pair_measure Pi_iff
+                intro!: prob_space.prob_space_bind[where S=R] AE_I2)
+qed (insert g, simp)
+
+
+lemma measurable_prob_algebra_generated:
+  assumes eq: "sets N = sigma_sets \<Omega> G" and "Int_stable G" "G \<subseteq> Pow \<Omega>"
+  assumes subsp: "\<And>a. a \<in> space M \<Longrightarrow> prob_space (K a)"
+  assumes sets: "\<And>a. a \<in> space M \<Longrightarrow> sets (K a) = sets N"
+  assumes "\<And>A. A \<in> G \<Longrightarrow> (\<lambda>a. emeasure (K a) A) \<in> borel_measurable M"
+  shows "K \<in> measurable M (prob_algebra N)"
+  unfolding measurable_restrict_space2_iff prob_algebra_def
+proof
+  show "K \<in> M \<rightarrow>\<^sub>M subprob_algebra N"
+  proof (rule measurable_subprob_algebra_generated[OF assms(1,2,3) _ assms(5,6)])
+    fix a assume "a \<in> space M" then show "subprob_space (K a)"
+      using subsp[of a] by (intro prob_space_imp_subprob_space)
+  next
+    have "(\<lambda>a. emeasure (K a) \<Omega>) \<in> borel_measurable M \<longleftrightarrow> (\<lambda>a. 1::ennreal) \<in> borel_measurable M"
+      using sets_eq_imp_space_eq[of "sigma \<Omega> G" N] \<open>G \<subseteq> Pow \<Omega>\<close> eq sets_eq_imp_space_eq[OF sets]
+        prob_space.emeasure_space_1[OF subsp]
+      by (intro measurable_cong) auto
+    then show "(\<lambda>a. emeasure (K a) \<Omega>) \<in> borel_measurable M" by simp
+  qed
+qed (insert subsp, auto)
+
+lemma in_space_prob_algebra:
+  "x \<in> space (prob_algebra M) \<Longrightarrow> emeasure x (space M) = 1"
+  unfolding prob_algebra_def space_restrict_space space_subprob_algebra
+  by (auto dest!: prob_space.emeasure_space_1 sets_eq_imp_space_eq)
+
+lemma prob_space_pair:
+  assumes "prob_space M" "prob_space N" shows "prob_space (M \<Otimes>\<^sub>M N)"
+proof -
+  interpret M: prob_space M by fact
+  interpret N: prob_space N by fact
+  interpret P: pair_prob_space M N proof qed
+  show ?thesis
+    by unfold_locales
+qed
+
+lemma measurable_pair_prob[measurable]:
+  "f \<in> M \<rightarrow>\<^sub>M prob_algebra N \<Longrightarrow> g \<in> M \<rightarrow>\<^sub>M prob_algebra L \<Longrightarrow> (\<lambda>x. f x \<Otimes>\<^sub>M g x) \<in> M \<rightarrow>\<^sub>M prob_algebra (N \<Otimes>\<^sub>M L)"
+  unfolding prob_algebra_def measurable_restrict_space2_iff
+  by (auto intro!: measurable_pair_measure prob_space_pair)
+
+lemma emeasure_bind_prob_algebra:
+  assumes A: "A \<in> space (prob_algebra N)"
+  assumes B: "B \<in> N \<rightarrow>\<^sub>M prob_algebra L"
+  assumes X: "X \<in> sets L"
+  shows "emeasure (bind A B) X = (\<integral>\<^sup>+x. emeasure (B x) X \<partial>A)"
+  using A B
+  by (intro emeasure_bind[OF _ _ X])
+     (auto simp: space_prob_algebra measurable_prob_algebraD cong: measurable_cong_sets intro!: prob_space.not_empty)
+
+lemma prob_space_bind':
+  assumes A: "A \<in> space (prob_algebra M)" and B: "B \<in> M \<rightarrow>\<^sub>M prob_algebra N" shows "prob_space (A \<bind> B)"
+  using measurable_bind_prob_space[OF measurable_const, OF A B, THEN measurable_space, of undefined "count_space UNIV"]
+  by (simp add: space_prob_algebra)
+
+lemma sets_bind':
+  assumes A: "A \<in> space (prob_algebra M)" and B: "B \<in> M \<rightarrow>\<^sub>M prob_algebra N" shows "sets (A \<bind> B) = sets N"
+  using measurable_bind_prob_space[OF measurable_const, OF A B, THEN measurable_space, of undefined "count_space UNIV"]
+  by (simp add: space_prob_algebra)
+
+lemma bind_cong_AE':
+  assumes M: "M \<in> space (prob_algebra L)"
+    and f: "f \<in> L \<rightarrow>\<^sub>M prob_algebra N" and g: "g \<in> L \<rightarrow>\<^sub>M prob_algebra N"
+    and ae: "AE x in M. f x = g x"
+  shows "bind M f = bind M g"
+proof (rule measure_eqI)
+  show "sets (M \<bind> f) = sets (M \<bind> g)"
+    unfolding sets_bind'[OF M f] sets_bind'[OF M g] ..
+  show "A \<in> sets (M \<bind> f) \<Longrightarrow> emeasure (M \<bind> f) A = emeasure (M \<bind> g) A" for A
+    unfolding sets_bind'[OF M f]
+    using emeasure_bind_prob_algebra[OF M f, of A] emeasure_bind_prob_algebra[OF M g, of A] ae
+    by (auto intro: nn_integral_cong_AE)
+qed
+
+lemma density_discrete:
+  "countable A \<Longrightarrow> sets N = Set.Pow A \<Longrightarrow> (\<And>x. f x \<ge> 0) \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> f x = emeasure N {x}) \<Longrightarrow>
+    density (count_space A) f = N"
+  by (rule measure_eqI_countable[of _ A]) (auto simp: emeasure_density)
+
+lemma distr_density_discrete:
+  fixes f'
+  assumes "countable A"
+  assumes "f' \<in> borel_measurable M"
+  assumes "g \<in> measurable M (count_space A)"
+  defines "f \<equiv> \<lambda>x. \<integral>\<^sup>+t. (if g t = x then 1 else 0) * f' t \<partial>M"
+  assumes "\<And>x.  x \<in> space M \<Longrightarrow> g x \<in> A"
+  shows "density (count_space A) (\<lambda>x. f x) = distr (density M f') (count_space A) g"
+proof (rule density_discrete)
+  fix x assume x: "x \<in> A"
+  have "f x = \<integral>\<^sup>+t. indicator (g -` {x} \<inter> space M) t * f' t \<partial>M" (is "_ = ?I") unfolding f_def
+    by (intro nn_integral_cong) (simp split: split_indicator)
+  also from x have in_sets: "g -` {x} \<inter> space M \<in> sets M"
+    by (intro measurable_sets[OF assms(3)]) simp
+  have "?I = emeasure (density M f') (g -` {x} \<inter> space M)" unfolding f_def
+    by (subst emeasure_density[OF assms(2) in_sets], subst mult.commute) (rule refl)
+  also from assms(3) x have "... = emeasure (distr (density M f') (count_space A) g) {x}"
+    by (subst emeasure_distr) simp_all
+  finally show "f x = emeasure (distr (density M f') (count_space A) g) {x}" .
+qed (insert assms, auto)
+
+lemma bind_cong_AE:
+  assumes "M = N"
+  assumes f: "f \<in> measurable N (subprob_algebra B)"
+  assumes g: "g \<in> measurable N (subprob_algebra B)"
+  assumes ae: "AE x in N. f x = g x"
+  shows "bind M f = bind N g"
+proof cases
+  assume "space N = {}" then show ?thesis
+    using `M = N` by (simp add: bind_empty)
+next
+  assume "space N \<noteq> {}"
+  show ?thesis unfolding `M = N`
+  proof (rule measure_eqI)
+    have *: "sets (N \<bind> f) = sets B"
+      using sets_bind[OF sets_kernel[OF f] `space N \<noteq> {}`] by simp
+    then show "sets (N \<bind> f) = sets (N \<bind> g)"
+      using sets_bind[OF sets_kernel[OF g] `space N \<noteq> {}`] by auto
+    fix A assume "A \<in> sets (N \<bind> f)"
+    then have "A \<in> sets B"
+      unfolding * .
+    with ae f g `space N \<noteq> {}` show "emeasure (N \<bind> f) A = emeasure (N \<bind> g) A"
+      by (subst (1 2) emeasure_bind[where N=B]) (auto intro!: nn_integral_cong_AE)
+  qed
+qed
+
+lemma bind_cong_strong: "M = N \<Longrightarrow> (\<And>x. x\<in>space M =simp=> f x = g x) \<Longrightarrow> bind M f = bind N g"
+  by (auto simp: simp_implies_def intro!: bind_cong)
+
+lemma sets_bind_measurable:
+  assumes f: "f \<in> measurable M (subprob_algebra B)"
+  assumes M: "space M \<noteq> {}"
+  shows "sets (M \<bind> f) = sets B"
+  using M by (intro sets_bind[OF sets_kernel[OF f]]) auto
+
+lemma space_bind_measurable:
+  assumes f: "f \<in> measurable M (subprob_algebra B)"
+  assumes M: "space M \<noteq> {}"
+  shows "space (M \<bind> f) = space B"
+  using M by (intro space_bind[OF sets_kernel[OF f]]) auto
+
 end
--- a/src/HOL/Probability/Infinite_Product_Measure.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Infinite_Product_Measure.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -63,6 +63,21 @@
     using emeasure_PiM_emb[of "{}" "\<lambda>_. {}"] by (simp add: *)
 qed
 
+lemma prob_space_PiM:
+  assumes M: "\<And>i. i \<in> I \<Longrightarrow> prob_space (M i)" shows "prob_space (PiM I M)"
+proof -
+  let ?M = "\<lambda>i. if i \<in> I then M i else count_space {undefined}"
+  interpret M': prob_space "?M i" for i
+    using M by (cases "i \<in> I") (auto intro!: prob_spaceI)
+  interpret product_prob_space ?M I
+    by unfold_locales
+  have "prob_space (\<Pi>\<^sub>M i\<in>I. ?M i)"
+    by unfold_locales
+  also have "(\<Pi>\<^sub>M i\<in>I. ?M i) = (\<Pi>\<^sub>M i\<in>I. M i)"
+    by (intro PiM_cong) auto
+  finally show ?thesis .
+qed
+
 lemma (in product_prob_space) emeasure_PiM_Collect:
   assumes X: "J \<subseteq> I" "finite J" "\<And>i. i \<in> J \<Longrightarrow> X i \<in> sets (M i)"
   shows "emeasure (Pi\<^sub>M I M) {x\<in>space (Pi\<^sub>M I M). \<forall>i\<in>J. x i \<in> X i} = (\<Prod> i\<in>J. emeasure (M i) (X i))"
@@ -123,6 +138,107 @@
   apply simp_all
   done
 
+lemma emeasure_PiM_emb:
+  assumes M: "\<And>i. i \<in> I \<Longrightarrow> prob_space (M i)"
+  assumes J: "J \<subseteq> I" "finite J" and A: "\<And>i. i \<in> J \<Longrightarrow> A i \<in> sets (M i)"
+  shows "emeasure (Pi\<^sub>M I M) (prod_emb I M J (Pi\<^sub>E J A)) = (\<Prod>i\<in>J. emeasure (M i) (A i))"
+proof -
+  let ?M = "\<lambda>i. if i \<in> I then M i else count_space {undefined}"
+  interpret M': prob_space "?M i" for i
+    using M by (cases "i \<in> I") (auto intro!: prob_spaceI)
+  interpret P: product_prob_space ?M I
+    by unfold_locales
+  have "emeasure (Pi\<^sub>M I M) (prod_emb I M J (Pi\<^sub>E J A)) = emeasure (Pi\<^sub>M I ?M) (P.emb I J (Pi\<^sub>E J A))"
+    by (auto simp: prod_emb_def PiE_iff intro!: arg_cong2[where f=emeasure] PiM_cong)
+  also have "\<dots> = (\<Prod>i\<in>J. emeasure (M i) (A i))"
+    using J A by (subst P.emeasure_PiM_emb[OF J]) (auto intro!: setprod.cong)
+  finally show ?thesis .
+qed
+
+lemma distr_pair_PiM_eq_PiM:
+  fixes i' :: "'i" and I :: "'i set" and M :: "'i \<Rightarrow> 'a measure"
+  assumes M: "\<And>i. i \<in> I \<Longrightarrow> prob_space (M i)" "prob_space (M i')"
+  shows "distr (M i' \<Otimes>\<^sub>M (\<Pi>\<^sub>M i\<in>I. M i)) (\<Pi>\<^sub>M i\<in>insert i' I. M i) (\<lambda>(x, X). X(i' := x)) =
+    (\<Pi>\<^sub>M i\<in>insert i' I. M i)" (is "?L = _")
+proof (rule measure_eqI_PiM_infinite[symmetric, OF refl])
+  interpret M': prob_space "M i'" by fact
+  interpret I: prob_space "(\<Pi>\<^sub>M i\<in>I. M i)"
+    using M by (intro prob_space_PiM) auto
+  interpret I': prob_space "(\<Pi>\<^sub>M i\<in>insert i' I. M i)"
+    using M by (intro prob_space_PiM) auto
+  show "finite_measure (\<Pi>\<^sub>M i\<in>insert i' I. M i)"
+    by unfold_locales
+  fix J A assume J: "finite J" "J \<subseteq> insert i' I" and A: "\<And>i. i \<in> J \<Longrightarrow> A i \<in> sets (M i)"
+  let ?X = "prod_emb (insert i' I) M J (Pi\<^sub>E J A)"
+  have "Pi\<^sub>M (insert i' I) M ?X = (\<Prod>i\<in>J. M i (A i))"
+    using M J A by (intro emeasure_PiM_emb) auto
+  also have "\<dots> = M i' (if i' \<in> J then (A i') else space (M i')) * (\<Prod>i\<in>J-{i'}. M i (A i))"
+    using setprod.insert_remove[of J "\<lambda>i. M i (A i)" i'] J M'.emeasure_space_1
+    by (cases "i' \<in> J") (auto simp: insert_absorb)
+  also have "(\<Prod>i\<in>J-{i'}. M i (A i)) = Pi\<^sub>M I M (prod_emb I M (J - {i'}) (Pi\<^sub>E (J - {i'}) A))"
+    using M J A by (intro emeasure_PiM_emb[symmetric]) auto
+  also have "M i' (if i' \<in> J then (A i') else space (M i')) * \<dots> =
+    (M i' \<Otimes>\<^sub>M Pi\<^sub>M I M) ((if i' \<in> J then (A i') else space (M i')) \<times> prod_emb I M (J - {i'}) (Pi\<^sub>E (J - {i'}) A))"
+    using J A by (intro I.emeasure_pair_measure_Times[symmetric] sets_PiM_I) auto
+  also have "((if i' \<in> J then (A i') else space (M i')) \<times> prod_emb I M (J - {i'}) (Pi\<^sub>E (J - {i'}) A)) =
+    (\<lambda>(x, X). X(i' := x)) -` ?X \<inter> space (M i' \<Otimes>\<^sub>M Pi\<^sub>M I M)"
+    using A[of i', THEN sets.sets_into_space] unfolding set_eq_iff
+    by (simp add: prod_emb_def space_pair_measure space_PiM PiE_fun_upd ac_simps cong: conj_cong)
+       (auto simp add: Pi_iff Ball_def all_conj_distrib)
+  finally show "Pi\<^sub>M (insert i' I) M ?X = ?L ?X"
+    using J A by (simp add: emeasure_distr)
+qed simp
+
+lemma distr_PiM_reindex:
+  assumes M: "\<And>i. i \<in> K \<Longrightarrow> prob_space (M i)"
+  assumes f: "inj_on f I" "f \<in> I \<rightarrow> K"
+  shows "distr (Pi\<^sub>M K M) (\<Pi>\<^sub>M i\<in>I. M (f i)) (\<lambda>\<omega>. \<lambda>n\<in>I. \<omega> (f n)) = (\<Pi>\<^sub>M i\<in>I. M (f i))"
+    (is "distr ?K ?I ?t = ?I")
+proof (rule measure_eqI_PiM_infinite[symmetric, OF refl])
+  interpret prob_space ?I
+    using f M by (intro prob_space_PiM) auto
+  show "finite_measure ?I"
+    by unfold_locales
+  fix A J assume J: "finite J" "J \<subseteq> I" and A: "\<And>i. i \<in> J \<Longrightarrow> A i \<in> sets (M (f i))"
+  have [simp]: "i \<in> J \<Longrightarrow> the_inv_into I f (f i) = i" for i
+    using J f by (intro the_inv_into_f_f) auto
+  have "?I (prod_emb I (\<lambda>i. M (f i)) J (Pi\<^sub>E J A)) = (\<Prod>j\<in>J. M (f j) (A j))"
+    using f J A by (intro emeasure_PiM_emb M) auto
+  also have "\<dots> = (\<Prod>j\<in>f`J. M j (A (the_inv_into I f j)))"
+    using f J by (subst setprod.reindex) (auto intro!: setprod.cong intro: inj_on_subset simp: the_inv_into_f_f)
+  also have "\<dots> = ?K (prod_emb K M (f`J) (\<Pi>\<^sub>E j\<in>f`J. A (the_inv_into I f j)))"
+    using f J A by (intro emeasure_PiM_emb[symmetric] M) (auto simp: the_inv_into_f_f)
+  also have "prod_emb K M (f`J) (\<Pi>\<^sub>E j\<in>f`J. A (the_inv_into I f j)) = ?t -` prod_emb I (\<lambda>i. M (f i)) J (Pi\<^sub>E J A) \<inter> space ?K"
+    using f J A by (auto simp: prod_emb_def space_PiM Pi_iff PiE_iff Int_absorb1)
+  also have "?K \<dots> = distr ?K ?I ?t (prod_emb I (\<lambda>i. M (f i)) J (Pi\<^sub>E J A))"
+    using f J A by (intro emeasure_distr[symmetric] sets_PiM_I) (auto simp: Pi_iff)
+  finally show "?I (prod_emb I (\<lambda>i. M (f i)) J (Pi\<^sub>E J A)) = distr ?K ?I ?t (prod_emb I (\<lambda>i. M (f i)) J (Pi\<^sub>E J A))" .
+qed simp
+
+lemma distr_PiM_component:
+  assumes M: "\<And>i. i \<in> I \<Longrightarrow> prob_space (M i)"
+  assumes "i \<in> I"
+  shows "distr (Pi\<^sub>M I M) (M i) (\<lambda>\<omega>. \<omega> i) = M i"
+proof -
+  have *: "(\<lambda>\<omega>. \<omega> i) -` A \<inter> space (Pi\<^sub>M I M) = prod_emb I M {i} (\<Pi>\<^sub>E i'\<in>{i}. A)" for A
+    by (auto simp: prod_emb_def space_PiM)
+  show ?thesis
+    apply (intro measure_eqI)
+    apply (auto simp add: emeasure_distr \<open>i\<in>I\<close> * emeasure_PiM_emb M)
+    apply (subst emeasure_PiM_emb)
+    apply (simp_all add: M \<open>i\<in>I\<close>)
+    done
+qed
+
+lemma AE_PiM_component:
+  "(\<And>i. i \<in> I \<Longrightarrow> prob_space (M i)) \<Longrightarrow> i \<in> I \<Longrightarrow> AE x in M i. P x \<Longrightarrow> AE x in PiM I M. P (x i)"
+  using AE_distrD[of "\<lambda>x. x i" "PiM I M" "M i"]
+  by (subst (asm) distr_PiM_component[of I _ i]) (auto intro: AE_distrD[of "\<lambda>x. x i" _ _ P])
+
+lemma decseq_emb_PiE:
+  "incseq J \<Longrightarrow> decseq (\<lambda>i. prod_emb I M (J i) (\<Pi>\<^sub>E j\<in>J i. X j))"
+  by (fastforce simp: decseq_def prod_emb_def incseq_def Pi_iff)
+
 subsection \<open>Sequence space\<close>
 
 definition comb_seq :: "nat \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> (nat \<Rightarrow> 'a)" where
--- a/src/HOL/Probability/Information.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Information.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -389,10 +389,6 @@
     done
 qed
 
-lemma integrable_cong_AE_imp:
-  "integrable M g \<Longrightarrow> f \<in> borel_measurable M \<Longrightarrow> (AE x in M. g x = f x) \<Longrightarrow> integrable M f"
-  using integrable_cong_AE[of f M g] by (auto simp: eq_commute)
-
 lemma (in information_space) finite_entropy_integrable:
   "finite_entropy S X Px \<Longrightarrow> integrable S (\<lambda>x. Px x * log b (Px x))"
   unfolding finite_entropy_def by auto
--- a/src/HOL/Probability/Probability_Mass_Function.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Probability_Mass_Function.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -246,7 +246,7 @@
   shows "finite (set_pmf M) \<Longrightarrow> integrable M f"
   by (auto intro!: integrableI_bounded simp: nn_integral_measure_pmf_finite ennreal_mult_less_top)
 
-lemma integral_measure_pmf:
+lemma integral_measure_pmf_real:
   assumes [simp]: "finite A" and "\<And>a. a \<in> set_pmf M \<Longrightarrow> f a \<noteq> 0 \<Longrightarrow> a \<in> A"
   shows "(\<integral>x. f x \<partial>measure_pmf M) = (\<Sum>a\<in>A. f a * pmf M a)"
 proof -
@@ -572,9 +572,9 @@
 
 lemma pmf_pair: "pmf (pair_pmf M N) (a, b) = pmf M a * pmf N b"
   unfolding pair_pmf_def pmf_bind pmf_return
-  apply (subst integral_measure_pmf[where A="{b}"])
+  apply (subst integral_measure_pmf_real[where A="{b}"])
   apply (auto simp: indicator_eq_0_iff)
-  apply (subst integral_measure_pmf[where A="{a}"])
+  apply (subst integral_measure_pmf_real[where A="{a}"])
   apply (auto simp: indicator_eq_0_iff setsum_nonneg_eq_0_iff pmf_nonneg)
   done
 
@@ -658,7 +658,10 @@
 done
 
 lemma pmf_map_outside: "x \<notin> f ` set_pmf M \<Longrightarrow> pmf (map_pmf f M) x = 0"
-unfolding pmf_eq_0_set_pmf by simp
+  unfolding pmf_eq_0_set_pmf by simp
+
+lemma measurable_set_pmf[measurable]: "Measurable.pred (count_space UNIV) (\<lambda>x. x \<in> set_pmf M)"
+  by simp
 
 subsection \<open> PMFs as function \<close>
 
@@ -742,6 +745,107 @@
 lemma nn_integral_measure_pmf: "(\<integral>\<^sup>+ x. f x \<partial>measure_pmf p) = \<integral>\<^sup>+ x. ennreal (pmf p x) * f x \<partial>count_space UNIV"
 by(simp add: measure_pmf_eq_density nn_integral_density pmf_nonneg)
 
+lemma integral_measure_pmf:
+  fixes f :: "'a \<Rightarrow> 'b::{banach, second_countable_topology}"
+  assumes A: "finite A"
+  shows "(\<And>a. a \<in> set_pmf M \<Longrightarrow> f a \<noteq> 0 \<Longrightarrow> a \<in> A) \<Longrightarrow> (LINT x|M. f x) = (\<Sum>a\<in>A. pmf M a *\<^sub>R f a)"
+  unfolding measure_pmf_eq_density
+  apply (simp add: integral_density)
+  apply (subst lebesgue_integral_count_space_finite_support)
+  apply (auto intro!: finite_subset[OF _ \<open>finite A\<close>] setsum.mono_neutral_left simp: pmf_eq_0_set_pmf)
+  done
+
+lemma continuous_on_LINT_pmf: -- \<open>This is dominated convergence!?\<close>
+  fixes f :: "'i \<Rightarrow> 'a::topological_space \<Rightarrow> 'b::{banach, second_countable_topology}"
+  assumes f: "\<And>i. i \<in> set_pmf M \<Longrightarrow> continuous_on A (f i)"
+    and bnd: "\<And>a i. a \<in> A \<Longrightarrow> i \<in> set_pmf M \<Longrightarrow> norm (f i a) \<le> B"
+  shows "continuous_on A (\<lambda>a. LINT i|M. f i a)"
+proof cases
+  assume "finite M" with f show ?thesis
+    using integral_measure_pmf[OF \<open>finite M\<close>]
+    by (subst integral_measure_pmf[OF \<open>finite M\<close>])
+       (auto intro!: continuous_on_setsum continuous_on_scaleR continuous_on_const)
+next
+  assume "infinite M"
+  let ?f = "\<lambda>i x. pmf (map_pmf (to_nat_on M) M) i *\<^sub>R f (from_nat_into M i) x"
+
+  show ?thesis
+  proof (rule uniform_limit_theorem)
+    show "\<forall>\<^sub>F n in sequentially. continuous_on A (\<lambda>a. \<Sum>i<n. ?f i a)"
+      by (intro always_eventually allI continuous_on_setsum continuous_on_scaleR continuous_on_const f
+                from_nat_into set_pmf_not_empty)
+    show "uniform_limit A (\<lambda>n a. \<Sum>i<n. ?f i a) (\<lambda>a. LINT i|M. f i a) sequentially"
+    proof (subst uniform_limit_cong[where g="\<lambda>n a. \<Sum>i<n. ?f i a"])
+      fix a assume "a \<in> A"
+      have 1: "(LINT i|M. f i a) = (LINT i|map_pmf (to_nat_on M) M. f (from_nat_into M i) a)"
+        by (auto intro!: integral_cong_AE AE_pmfI)
+      have 2: "\<dots> = (LINT i|count_space UNIV. pmf (map_pmf (to_nat_on M) M) i *\<^sub>R f (from_nat_into M i) a)"
+        by (simp add: measure_pmf_eq_density integral_density)
+      have "(\<lambda>n. ?f n a) sums (LINT i|M. f i a)"
+        unfolding 1 2
+      proof (intro sums_integral_count_space_nat)
+        have A: "integrable M (\<lambda>i. f i a)"
+          using \<open>a\<in>A\<close> by (auto intro!: measure_pmf.integrable_const_bound AE_pmfI bnd)
+        have "integrable (map_pmf (to_nat_on M) M) (\<lambda>i. f (from_nat_into M i) a)"
+          by (auto simp add: map_pmf_rep_eq integrable_distr_eq intro!: AE_pmfI integrable_cong_AE_imp[OF A])
+        then show "integrable (count_space UNIV) (\<lambda>n. ?f n a)"
+          by (simp add: measure_pmf_eq_density integrable_density)
+      qed
+      then show "(LINT i|M. f i a) = (\<Sum> n. ?f n a)"
+        by (simp add: sums_unique)
+    next
+      show "uniform_limit A (\<lambda>n a. \<Sum>i<n. ?f i a) (\<lambda>a. (\<Sum> n. ?f n a)) sequentially"
+      proof (rule weierstrass_m_test)
+        fix n a assume "a\<in>A"
+        then show "norm (?f n a) \<le> pmf (map_pmf (to_nat_on M) M) n * B"
+          using bnd by (auto intro!: mult_mono simp: from_nat_into set_pmf_not_empty)
+      next
+        have "integrable (map_pmf (to_nat_on M) M) (\<lambda>n. B)"
+          by auto
+        then show "summable (\<lambda>n. pmf (map_pmf (to_nat_on (set_pmf M)) M) n * B)"
+          by (simp add: measure_pmf_eq_density integrable_density integrable_count_space_nat_iff summable_rabs_cancel)
+      qed
+    qed simp
+  qed simp
+qed
+
+lemma continuous_on_LBINT:
+  fixes f :: "real \<Rightarrow> real"
+  assumes f: "\<And>b. a \<le> b \<Longrightarrow> set_integrable lborel {a..b} f"
+  shows "continuous_on UNIV (\<lambda>b. LBINT x:{a..b}. f x)"
+proof (subst set_borel_integral_eq_integral)
+  { fix b :: real assume "a \<le> b"
+    from f[OF this] have "continuous_on {a..b} (\<lambda>b. integral {a..b} f)"
+      by (intro indefinite_integral_continuous set_borel_integral_eq_integral) }
+  note * = this
+
+  have "continuous_on (\<Union>b\<in>{a..}. {a <..< b}) (\<lambda>b. integral {a..b} f)"
+  proof (intro continuous_on_open_UN)
+    show "b \<in> {a..} \<Longrightarrow> continuous_on {a<..<b} (\<lambda>b. integral {a..b} f)" for b
+      using *[of b] by (rule continuous_on_subset) auto
+  qed simp
+  also have "(\<Union>b\<in>{a..}. {a <..< b}) = {a <..}"
+    by (auto simp: lt_ex gt_ex less_imp_le) (simp add: Bex_def less_imp_le gt_ex cong: rev_conj_cong)
+  finally have "continuous_on {a+1 ..} (\<lambda>b. integral {a..b} f)"
+    by (rule continuous_on_subset) auto
+  moreover have "continuous_on {a..a+1} (\<lambda>b. integral {a..b} f)"
+    by (rule *) simp
+  moreover
+  have "x \<le> a \<Longrightarrow> {a..x} = (if a = x then {a} else {})" for x
+    by auto
+  then have "continuous_on {..a} (\<lambda>b. integral {a..b} f)"
+    by (subst continuous_on_cong[OF refl, where g="\<lambda>x. 0"]) (auto intro!: continuous_on_const)
+  ultimately have "continuous_on ({..a} \<union> {a..a+1} \<union> {a+1 ..}) (\<lambda>b. integral {a..b} f)"
+    by (intro continuous_on_closed_Un) auto
+  also have "{..a} \<union> {a..a+1} \<union> {a+1 ..} = UNIV"
+    by auto
+  finally show "continuous_on UNIV (\<lambda>b. integral {a..b} f)"
+    by auto
+next
+  show "set_integrable lborel {a..b} f" for b
+    using f by (cases "a \<le> b") auto
+qed
+
 locale pmf_as_function
 begin
 
--- a/src/HOL/Probability/Probability_Measure.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Probability_Measure.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -508,8 +508,6 @@
   "distributed M N X f \<longleftrightarrow>
   distr M N X = density N f \<and> f \<in> borel_measurable N \<and> X \<in> measurable M N"
 
-term distributed
-
 lemma
   assumes "distributed M N X f"
   shows distributed_distr_eq_density: "distr M N X = density N f"
--- a/src/HOL/Probability/Stream_Space.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Probability/Stream_Space.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -109,6 +109,10 @@
   shows "(\<lambda>x. stake n (f x) @- g x) \<in> measurable N (stream_space M)"
   using f by (induction n arbitrary: f) simp_all
 
+lemma measurable_case_stream_replace[measurable (raw)]:
+  "(\<lambda>x. f x (shd (g x)) (stl (g x))) \<in> measurable M N \<Longrightarrow> (\<lambda>x. case_stream (f x) (g x)) \<in> measurable M N"
+  unfolding stream.case_eq_if .
+
 lemma measurable_ev_at[measurable]:
   assumes [measurable]: "Measurable.pred (stream_space M) P"
   shows "Measurable.pred (stream_space M) (ev_at P n)"
@@ -442,4 +446,212 @@
     by (cases "xs = []") (auto simp: * space_stream_space del: in_listsD)
 qed (auto simp: * ae sets_M del: in_listsD intro!: streams_sets)
 
+primrec scylinder :: "'a set \<Rightarrow> 'a set list \<Rightarrow> 'a stream set"
+where
+  "scylinder S [] = streams S"
+| "scylinder S (A # As) = {\<omega>\<in>streams S. shd \<omega> \<in> A \<and> stl \<omega> \<in> scylinder S As}"
+
+lemma scylinder_streams: "scylinder S xs \<subseteq> streams S"
+  by (induction xs) auto
+
+lemma sets_scylinder: "(\<forall>x\<in>set xs. x \<in> sets S) \<Longrightarrow> scylinder (space S) xs \<in> sets (stream_space S)"
+  by (induction xs) (auto simp: space_stream_space[symmetric])
+
+lemma stream_space_eq_scylinder:
+  assumes P: "prob_space M" "prob_space N"
+  assumes "Int_stable G" and S: "sets S = sets (sigma (space S) G)"
+    and C: "countable C" "C \<subseteq> G" "\<Union>C = space S" and G: "G \<subseteq> Pow (space S)"
+  assumes sets_M: "sets M = sets (stream_space S)"
+  assumes sets_N: "sets N = sets (stream_space S)"
+  assumes *: "\<And>xs. xs \<noteq> [] \<Longrightarrow> xs \<in> lists G \<Longrightarrow> emeasure M (scylinder (space S) xs) = emeasure N (scylinder (space S) xs)"
+  shows "M = N"
+proof (rule measure_eqI_generator_eq)
+  interpret M: prob_space M by fact
+  interpret N: prob_space N by fact
+
+  let ?G = "scylinder (space S) ` lists G"
+  show sc_Pow: "?G \<subseteq> Pow (streams (space S))"
+    using scylinder_streams by auto
+
+  have "sets (stream_space S) = sets (sigma (streams (space S)) ?G)"
+    (is "?S = sets ?R")
+  proof (rule antisym)
+    let ?V = "\<lambda>i. vimage_algebra (streams (space S)) (\<lambda>s. s !! i) S"
+    show "?S \<subseteq> sets ?R"
+      unfolding sets_stream_space_eq
+    proof (safe intro!: sets_Sup_in_sets del: subsetI equalityI)
+      fix i :: nat
+      show "space (?V i) = space ?R"
+        using scylinder_streams by (subst space_measure_of) (auto simp: )
+      { fix A assume "A \<in> G"
+        then have "scylinder (space S) (replicate i (space S) @ [A]) = (\<lambda>s. s !! i) -` A \<inter> streams (space S)"
+          by (induction i) (auto simp add: streams_shd streams_stl cong: conj_cong)
+        also have "scylinder (space S) (replicate i (space S) @ [A]) = (\<Union>xs\<in>{xs\<in>lists C. length xs = i}. scylinder (space S) (xs @ [A]))"
+          apply (induction i)
+          apply auto []
+          apply (simp add: length_Suc_conv set_eq_iff ex_simps(1,2)[symmetric] cong: conj_cong del: ex_simps(1,2))
+          apply rule
+          subgoal for i x
+            apply (cases x)
+            apply (subst (2) C(3)[symmetric])
+            apply (simp del: ex_simps(1,2) add: ex_simps(1,2)[symmetric] ac_simps Bex_def)
+            apply auto
+            done
+          done
+        finally have "(\<lambda>s. s !! i) -` A \<inter> streams (space S) = (\<Union>xs\<in>{xs\<in>lists C. length xs = i}. scylinder (space S) (xs @ [A]))"
+          ..
+        also have "\<dots> \<in> ?R"
+          using C(2) \<open>A\<in>G\<close>
+          by (intro sets.countable_UN' countable_Collect countable_lists C)
+             (auto intro!: in_measure_of[OF sc_Pow] imageI)
+        finally have "(\<lambda>s. s !! i) -` A \<inter> streams (space S) \<in> ?R" . }
+      then show "sets (?V i) \<subseteq> ?R"
+        apply (subst vimage_algebra_cong[OF refl refl S])
+        apply (subst vimage_algebra_sigma[OF G])
+        apply (simp add: streams_iff_snth) []
+        apply (subst sigma_le_sets)
+        apply auto
+        done
+    qed
+    have "G \<subseteq> sets S"
+      unfolding S using G by auto
+    with C(2) show "sets ?R \<subseteq> ?S"
+      unfolding sigma_le_sets[OF sc_Pow] by (auto intro!: sets_scylinder)
+  qed
+  then show "sets M = sigma_sets (streams (space S)) (scylinder (space S) ` lists G)"
+    "sets N = sigma_sets (streams (space S)) (scylinder (space S) ` lists G)"
+    unfolding sets_M sets_N by (simp_all add: sc_Pow)
+
+  show "Int_stable ?G"
+  proof (rule Int_stableI_image)
+    fix xs ys assume "xs \<in> lists G" "ys \<in> lists G"
+    then show "\<exists>zs\<in>lists G. scylinder (space S) xs \<inter> scylinder (space S) ys = scylinder (space S) zs"
+    proof (induction xs arbitrary: ys)
+      case Nil then show ?case
+        by (auto simp add: Int_absorb1 scylinder_streams)
+    next
+      case xs: (Cons x xs)
+      show ?case
+      proof (cases ys)
+        case Nil with xs.hyps show ?thesis
+          by (auto simp add: Int_absorb2 scylinder_streams intro!: bexI[of _ "x#xs"])
+      next
+        case ys: (Cons y ys')
+        with xs.IH[of ys'] xs.prems obtain zs where
+          "zs \<in> lists G" and eq: "scylinder (space S) xs \<inter> scylinder (space S) ys' = scylinder (space S) zs"
+          by auto
+        show ?thesis
+        proof (intro bexI[of _ "(x \<inter> y)#zs"])
+          show "x \<inter> y # zs \<in> lists G"
+            using \<open>zs\<in>lists G\<close> \<open>x\<in>G\<close> \<open>ys\<in>lists G\<close> ys \<open>Int_stable G\<close>[THEN Int_stableD, of x y] by auto
+          show "scylinder (space S) (x # xs) \<inter> scylinder (space S) ys = scylinder (space S) (x \<inter> y # zs)"
+            by (auto simp add: eq[symmetric] ys)
+        qed
+      qed
+    qed
+  qed
+
+  show "range (\<lambda>_::nat. streams (space S)) \<subseteq> scylinder (space S) ` lists G"
+    "(\<Union>i. streams (space S)) = streams (space S)"
+    "emeasure M (streams (space S)) \<noteq> \<infinity>"
+    by (auto intro!: image_eqI[of _ _ "[]"])
+
+  fix X assume "X \<in> scylinder (space S) ` lists G"
+  then obtain xs where xs: "xs \<in> lists G" and eq: "X = scylinder (space S) xs"
+    by auto
+  then show "emeasure M X = emeasure N X"
+  proof (cases "xs = []")
+    assume "xs = []" then show ?thesis
+      unfolding eq
+      using sets_M[THEN sets_eq_imp_space_eq] sets_N[THEN sets_eq_imp_space_eq]
+         M.emeasure_space_1 N.emeasure_space_1
+      by (simp add: space_stream_space[symmetric])
+  next
+    assume "xs \<noteq> []" with xs show ?thesis
+      unfolding eq by (intro *)
+  qed
+qed
+
+lemma stream_space_coinduct:
+  fixes R :: "'a stream measure \<Rightarrow> 'a stream measure \<Rightarrow> bool"
+  assumes "R A B"
+  assumes R: "\<And>A B. R A B \<Longrightarrow> \<exists>K\<in>space (prob_algebra M).
+    \<exists>A'\<in>M \<rightarrow>\<^sub>M prob_algebra (stream_space M). \<exists>B'\<in>M \<rightarrow>\<^sub>M prob_algebra (stream_space M).
+    (AE y in K. R (A' y) (B' y) \<or> A' y = B' y) \<and>
+    A = do { y \<leftarrow> K; \<omega> \<leftarrow> A' y; return (stream_space M) (y ## \<omega>) } \<and>
+    B = do { y \<leftarrow> K; \<omega> \<leftarrow> B' y; return (stream_space M) (y ## \<omega>) }"
+  shows "A = B"
+proof (rule stream_space_eq_scylinder)
+  let ?step = "\<lambda>K L. do { y \<leftarrow> K; \<omega> \<leftarrow> L y; return (stream_space M) (y ## \<omega>) }"
+  { fix K A A' assume K: "K \<in> space (prob_algebra M)"
+      and A'[measurable]: "A' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)" and A_eq: "A = ?step K A'"
+    have ps: "prob_space A"
+      unfolding A_eq by (rule prob_space_bind'[OF K]) measurable
+    have "sets A = sets (stream_space M)"
+      unfolding A_eq by (rule sets_bind'[OF K]) measurable
+    note ps this }
+  note ** = this
+
+  { fix A B assume "R A B"
+    obtain K A' B' where K: "K \<in> space (prob_algebra M)"
+      and A': "A' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)" "A = ?step K A'"
+      and B': "B' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)" "B = ?step K B'"
+      using R[OF \<open>R A B\<close>] by blast
+    have "prob_space A" "prob_space B" "sets A = sets (stream_space M)" "sets B = sets (stream_space M)"
+      using **[OF K A'] **[OF K B'] by auto }
+  note R_D = this
+
+  show "prob_space A" "prob_space B" "sets A = sets (stream_space M)" "sets B = sets (stream_space M)"
+    using R_D[OF \<open>R A B\<close>] by auto
+
+  show "Int_stable (sets M)" "sets M = sets (sigma (space M) (sets M))" "countable {space M}"
+    "{space M} \<subseteq> sets M" "\<Union>{space M} = space M" "sets M \<subseteq> Pow (space M)"
+    using sets.space_closed[of M] by (auto simp: Int_stable_def)
+
+  { fix A As L K assume K[measurable]: "K \<in> space (prob_algebra M)" and A: "A \<in> sets M" "As \<in> lists (sets M)"
+      and L[measurable]: "L \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)"
+    from A have [measurable]: "\<forall>x\<in>set (A # As). x \<in> sets M" "\<forall>x\<in>set As. x \<in> sets M"
+      by auto
+    have [simp]: "space K = space M" "sets K = sets M"
+      using K by (auto simp: space_prob_algebra intro!: sets_eq_imp_space_eq)
+    have [simp]: "x \<in> space M \<Longrightarrow> sets (L x) = sets (stream_space M)" for x
+      using measurable_space[OF L] by (auto simp: space_prob_algebra)
+    note sets_scylinder[measurable]
+    have *: "indicator (scylinder (space M) (A # As)) (x ## \<omega>) =
+        (indicator A x * indicator (scylinder (space M) As) \<omega> :: ennreal)" for \<omega> x
+      using scylinder_streams[of "space M" As] \<open>A \<in> sets M\<close>[THEN sets.sets_into_space]
+      by (auto split: split_indicator)
+    have "emeasure (?step K L) (scylinder (space M) (A # As)) = (\<integral>\<^sup>+y. L y (scylinder (space M) As) * indicator A y \<partial>K)"
+      apply (subst emeasure_bind_prob_algebra[OF K])
+      apply measurable
+      apply (rule nn_integral_cong)
+      apply (subst emeasure_bind_prob_algebra[OF L[THEN measurable_space]])
+      apply (simp_all add: ac_simps * nn_integral_cmult_indicator del: scylinder.simps)
+      apply measurable
+      done }
+  note emeasure_step = this
+
+  fix Xs assume "Xs \<in> lists (sets M)"
+  from this \<open>R A B\<close> show "emeasure A (scylinder (space M) Xs) = emeasure B (scylinder (space M) Xs)"
+  proof (induction Xs arbitrary: A B)
+    case (Cons X Xs)
+    obtain K A' B' where K: "K \<in> space (prob_algebra M)"
+      and A'[measurable]: "A' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)" and A: "A = ?step K A'"
+      and B'[measurable]: "B' \<in> M \<rightarrow>\<^sub>M prob_algebra (stream_space M)" and B: "B = ?step K B'"
+      and AE_R: "AE x in K. R (A' x) (B' x) \<or> A' x = B' x"
+      using R[OF \<open>R A B\<close>] by blast
+
+    show ?case
+      unfolding A B emeasure_step[OF K Cons.hyps A'] emeasure_step[OF K Cons.hyps B']
+      apply (rule nn_integral_cong_AE)
+      using AE_R by eventually_elim (auto simp add: Cons.IH)
+  next
+    case Nil
+    note R_D[OF this]
+    from this(1,2)[THEN prob_space.emeasure_space_1] this(3,4)[THEN sets_eq_imp_space_eq]
+    show ?case
+      by (simp add: space_stream_space)
+  qed
+qed
+
 end
--- a/src/HOL/ROOT	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/ROOT	Thu Oct 06 11:27:28 2016 +0200
@@ -627,6 +627,7 @@
     Code_Timing
     Perm_Fragments
     Argo_Examples
+    Word_Type
   theories [skip_proofs = false]
     Meson_Test
   document_files "root.bib" "root.tex"
--- a/src/HOL/Topological_Spaces.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Topological_Spaces.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -699,7 +699,7 @@
   assumes "filterlim f (nhds c) F"
   assumes "eventually (\<lambda>x. f x \<in> A - {c}) F"
   shows   "filterlim f (at c within A) F"
-  using assms by (simp add: filterlim_at) 
+  using assms by (simp add: filterlim_at)
 
 lemma filterlim_atI:
   assumes "filterlim f (nhds c) F"
@@ -1644,6 +1644,10 @@
   unfolding continuous_on_def
   by (intro ball_cong filterlim_cong) (auto simp: eventually_at_filter)
 
+lemma continuous_on_strong_cong:
+  "s = t \<Longrightarrow> (\<And>x. x \<in> t =simp=> f x = g x) \<Longrightarrow> continuous_on s f \<longleftrightarrow> continuous_on t g"
+  unfolding simp_implies_def by (rule continuous_on_cong)
+
 lemma continuous_on_topological:
   "continuous_on s f \<longleftrightarrow>
     (\<forall>x\<in>s. \<forall>B. open B \<longrightarrow> f x \<in> B \<longrightarrow> (\<exists>A. open A \<and> x \<in> A \<and> (\<forall>y\<in>s. y \<in> A \<longrightarrow> f y \<in> B)))"
--- a/src/HOL/Transfer.thy	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/HOL/Transfer.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -602,4 +602,14 @@
 
 end
 
+
+subsection \<open>@{const of_nat}\<close>
+
+lemma transfer_rule_of_nat:
+  fixes R :: "'a::semiring_1 \<Rightarrow> 'b::semiring_1 \<Rightarrow> bool"
+  assumes [transfer_rule]: "R 0 0" "R 1 1"
+    "rel_fun R (rel_fun R R) plus plus"
+  shows "rel_fun HOL.eq R of_nat of_nat"
+  by (unfold of_nat_def [abs_def]) transfer_prover
+
 end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/ex/Word_Type.thy	Thu Oct 06 11:27:28 2016 +0200
@@ -0,0 +1,354 @@
+(*  Author:  Florian Haftmann, TUM
+*)
+
+section \<open>Proof of concept for algebraically founded bit word types\<close>
+
+theory Word_Type
+  imports
+    Main
+    "~~/src/HOL/Library/Type_Length"
+begin
+
+subsection \<open>Compact syntax for types with a length\<close>
+
+syntax "_type_length" :: "type \<Rightarrow> nat" ("(1LENGTH/(1'(_')))")
+
+translations "LENGTH('a)" \<rightharpoonup>
+  "CONST len_of (CONST Pure.type :: 'a itself)"
+
+print_translation \<open>
+  let
+    fun len_of_itself_tr' ctxt [Const (@{const_syntax Pure.type}, Type (_, [T]))] =
+      Syntax.const @{syntax_const "_type_length"} $ Syntax_Phases.term_of_typ ctxt T
+  in [(@{const_syntax len_of}, len_of_itself_tr')] end
+\<close>
+
+
+subsection \<open>Truncating bit representations of numeric types\<close>
+
+class semiring_bits = semiring_div_parity +
+  assumes semiring_bits: "(1 + 2 * a) mod of_nat (2 * n) = 1 + 2 * (a mod of_nat n)"
+
+context semiring_bits
+begin
+
+definition bits :: "nat \<Rightarrow> 'a \<Rightarrow> 'a"
+  where bits_eq_mod: "bits n a = a mod of_nat (2 ^ n)"
+
+lemma bits_bits [simp]:
+  "bits n (bits n a) = bits n a"
+  by (simp add: bits_eq_mod)
+  
+lemma bits_0 [simp]:
+  "bits 0 a = 0"
+  by (simp add: bits_eq_mod)
+
+lemma bits_Suc [simp]:
+  "bits (Suc n) a = bits n (a div 2) * 2 + a mod 2"
+proof -
+  define b and c
+    where "b = a div 2" and "c = a mod 2"
+  then have a: "a = b * 2 + c" 
+    and "c = 0 \<or> c = 1"
+    by (simp_all add: mod_div_equality parity)
+  from \<open>c = 0 \<or> c = 1\<close>
+  have "bits (Suc n) (b * 2 + c) = bits n b * 2 + c"
+  proof
+    assume "c = 0"
+    moreover have "(2 * b) mod (2 * 2 ^ n) = 2 * (b mod 2 ^ n)"
+      by (simp add: mod_mult_mult1)
+    ultimately show ?thesis
+      by (simp add: bits_eq_mod ac_simps)
+  next
+    assume "c = 1"
+    with semiring_bits [of b "2 ^ n"] show ?thesis
+      by (simp add: bits_eq_mod ac_simps)
+  qed
+  with a show ?thesis
+    by (simp add: b_def c_def)
+qed
+
+lemma bits_of_0 [simp]:
+  "bits n 0 = 0"
+  by (simp add: bits_eq_mod)
+
+lemma bits_plus:
+  "bits n (bits n a + bits n b) = bits n (a + b)"
+  by (simp add: bits_eq_mod mod_add_eq [symmetric])
+
+lemma bits_of_1_eq_0_iff [simp]:
+  "bits n 1 = 0 \<longleftrightarrow> n = 0"
+  by (induct n) simp_all
+
+end
+
+instance nat :: semiring_bits
+  by standard (simp add: mod_Suc Suc_double_not_eq_double)
+
+instance int :: semiring_bits
+  by standard (simp add: pos_zmod_mult_2)
+
+lemma bits_uminus:
+  fixes k :: int
+  shows "bits n (- (bits n k)) = bits n (- k)"
+  by (simp add: bits_eq_mod mod_minus_eq [symmetric])
+
+lemma bits_minus:
+  fixes k l :: int
+  shows "bits n (bits n k - bits n l) = bits n (k - l)"
+  by (simp add: bits_eq_mod mod_diff_eq [symmetric])
+
+lemma bits_nonnegative [simp]:
+  fixes k :: int
+  shows "bits n k \<ge> 0"
+  by (simp add: bits_eq_mod)
+
+definition signed_bits :: "nat \<Rightarrow> int \<Rightarrow> int"
+  where signed_bits_eq_bits:
+    "signed_bits n k = bits (Suc n) (k + 2 ^ n) - 2 ^ n"
+
+lemma signed_bits_eq_bits':
+  assumes "n > 0"
+  shows "signed_bits (n - Suc 0) k = bits n (k + 2 ^ (n - 1)) - 2 ^ (n - 1)"
+  using assms by (simp add: signed_bits_eq_bits)
+  
+lemma signed_bits_0 [simp]:
+  "signed_bits 0 k = - (k mod 2)"
+proof (cases "even k")
+  case True
+  then have "odd (k + 1)"
+    by simp
+  then have "(k + 1) mod 2 = 1"
+    by (simp add: even_iff_mod_2_eq_zero)
+  with True show ?thesis
+    by (simp add: signed_bits_eq_bits)
+next
+  case False
+  then show ?thesis
+    by (simp add: signed_bits_eq_bits odd_iff_mod_2_eq_one)
+qed
+
+lemma signed_bits_Suc [simp]:
+  "signed_bits (Suc n) k = signed_bits n (k div 2) * 2 + k mod 2"
+  using zero_not_eq_two by (simp add: signed_bits_eq_bits algebra_simps)
+
+lemma signed_bits_of_0 [simp]:
+  "signed_bits n 0 = 0"
+  by (simp add: signed_bits_eq_bits bits_eq_mod)
+
+lemma signed_bits_of_minus_1 [simp]:
+  "signed_bits n (- 1) = - 1"
+  by (induct n) simp_all
+
+lemma signed_bits_eq_iff_bits_eq:
+  assumes "n > 0"
+  shows "signed_bits (n - Suc 0) k = signed_bits (n - Suc 0) l \<longleftrightarrow> bits n k = bits n l" (is "?P \<longleftrightarrow> ?Q")
+proof -
+  from assms obtain m where m: "n = Suc m"
+    by (cases n) auto
+  show ?thesis
+  proof 
+    assume ?Q
+    have "bits (Suc m) (k + 2 ^ m) =
+      bits (Suc m) (bits (Suc m) k + bits (Suc m) (2 ^ m))"
+      by (simp only: bits_plus)
+    also have "\<dots> =
+      bits (Suc m) (bits (Suc m) l + bits (Suc m) (2 ^ m))"
+      by (simp only: \<open>?Q\<close> m [symmetric])
+    also have "\<dots> = bits (Suc m) (l + 2 ^ m)"
+      by (simp only: bits_plus)
+    finally show ?P
+      by (simp only: signed_bits_eq_bits m) simp
+  next
+    assume ?P
+    with assms have "(k + 2 ^ (n - Suc 0)) mod 2 ^ n = (l + 2 ^ (n - Suc 0)) mod 2 ^ n"
+      by (simp add: signed_bits_eq_bits' bits_eq_mod)
+    then have "(i + (k + 2 ^ (n - Suc 0))) mod 2 ^ n = (i + (l + 2 ^ (n - Suc 0))) mod 2 ^ n" for i
+      by (metis mod_add_eq)
+    then have "k mod 2 ^ n = l mod 2 ^ n"
+      by (metis add_diff_cancel_right' uminus_add_conv_diff)
+    then show ?Q
+      by (simp add: bits_eq_mod)
+  qed
+qed 
+
+
+subsection \<open>Bit strings as quotient type\<close>
+
+subsubsection \<open>Basic properties\<close>
+
+quotient_type (overloaded) 'a word = int / "\<lambda>k l. bits LENGTH('a) k = bits LENGTH('a::len0) l"
+  by (auto intro!: equivpI reflpI sympI transpI)
+
+instantiation word :: (len0) "{semiring_numeral, comm_semiring_0, comm_ring}"
+begin
+
+lift_definition zero_word :: "'a word"
+  is 0
+  .
+
+lift_definition one_word :: "'a word"
+  is 1
+  .
+
+lift_definition plus_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> 'a word"
+  is plus
+  by (subst bits_plus [symmetric]) (simp add: bits_plus)
+
+lift_definition uminus_word :: "'a word \<Rightarrow> 'a word"
+  is uminus
+  by (subst bits_uminus [symmetric]) (simp add: bits_uminus)
+
+lift_definition minus_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> 'a word"
+  is minus
+  by (subst bits_minus [symmetric]) (simp add: bits_minus)
+
+lift_definition times_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> 'a word"
+  is times
+  by (auto simp add: bits_eq_mod intro: mod_mult_cong)
+
+instance
+  by standard (transfer; simp add: algebra_simps)+
+
+end
+
+instance word :: (len) comm_ring_1
+  by standard (transfer; simp)+
+
+
+subsubsection \<open>Conversions\<close>
+
+lemma [transfer_rule]:
+  "rel_fun HOL.eq pcr_word int of_nat"
+proof -
+  note transfer_rule_of_nat [transfer_rule]
+  show ?thesis by transfer_prover
+qed
+  
+lemma [transfer_rule]:
+  "rel_fun HOL.eq pcr_word (\<lambda>k. k) of_int"
+proof -
+  note transfer_rule_of_int [transfer_rule]
+  have "rel_fun HOL.eq pcr_word (of_int :: int \<Rightarrow> int) (of_int :: int \<Rightarrow> 'a word)"
+    by transfer_prover
+  then show ?thesis by (simp add: id_def)
+qed
+
+context semiring_1
+begin
+
+lift_definition unsigned :: "'b::len0 word \<Rightarrow> 'a"
+  is "of_nat \<circ> nat \<circ> bits LENGTH('b)"
+  by simp
+
+lemma unsigned_0 [simp]:
+  "unsigned 0 = 0"
+  by transfer simp
+
+end
+
+context semiring_char_0
+begin
+
+lemma word_eq_iff_unsigned:
+  "a = b \<longleftrightarrow> unsigned a = unsigned b"
+  by safe (transfer; simp add: eq_nat_nat_iff)
+
+end
+
+context ring_1
+begin
+
+lift_definition signed :: "'b::len word \<Rightarrow> 'a"
+  is "of_int \<circ> signed_bits (LENGTH('b) - 1)"
+  by (simp add: signed_bits_eq_iff_bits_eq [symmetric])
+
+lemma signed_0 [simp]:
+  "signed 0 = 0"
+  by transfer simp
+
+end
+
+lemma unsigned_of_nat [simp]:
+  "unsigned (of_nat n :: 'a word) = bits LENGTH('a::len) n"
+  by transfer (simp add: nat_eq_iff bits_eq_mod zmod_int)
+
+lemma of_nat_unsigned [simp]:
+  "of_nat (unsigned a) = a"
+  by transfer simp
+
+lemma of_int_unsigned [simp]:
+  "of_int (unsigned a) = a"
+  by transfer simp
+
+context ring_char_0
+begin
+
+lemma word_eq_iff_signed:
+  "a = b \<longleftrightarrow> signed a = signed b"
+  by safe (transfer; auto simp add: signed_bits_eq_iff_bits_eq)
+
+end
+
+lemma signed_of_int [simp]:
+  "signed (of_int k :: 'a word) = signed_bits (LENGTH('a::len) - 1) k"
+  by transfer simp
+
+lemma of_int_signed [simp]:
+  "of_int (signed a) = a"
+  by transfer (simp add: signed_bits_eq_bits bits_eq_mod zdiff_zmod_left)
+
+
+subsubsection \<open>Properties\<close>
+
+
+subsubsection \<open>Division\<close>
+
+instantiation word :: (len0) modulo
+begin
+
+lift_definition divide_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> 'a word"
+  is "\<lambda>a b. bits LENGTH('a) a div bits LENGTH('a) b"
+  by simp
+
+lift_definition modulo_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> 'a word"
+  is "\<lambda>a b. bits LENGTH('a) a mod bits LENGTH('a) b"
+  by simp
+
+instance ..
+
+end
+
+
+subsubsection \<open>Orderings\<close>
+
+instantiation word :: (len0) linorder
+begin
+
+lift_definition less_eq_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> bool"
+  is "\<lambda>a b. bits LENGTH('a) a \<le> bits LENGTH('a) b"
+  by simp
+
+lift_definition less_word :: "'a word \<Rightarrow> 'a word \<Rightarrow> bool"
+  is "\<lambda>a b. bits LENGTH('a) a < bits LENGTH('a) b"
+  by simp
+
+instance
+  by standard (transfer; auto)+
+
+end
+
+context linordered_semidom
+begin
+
+lemma word_less_eq_iff_unsigned:
+  "a \<le> b \<longleftrightarrow> unsigned a \<le> unsigned b"
+  by (transfer fixing: less_eq) (simp add: nat_le_eq_zle)
+
+lemma word_less_iff_unsigned:
+  "a < b \<longleftrightarrow> unsigned a < unsigned b"
+  by (transfer fixing: less) (auto dest: preorder_class.le_less_trans [OF bits_nonnegative])
+
+end
+
+end
--- a/src/Tools/solve_direct.ML	Thu Oct 06 11:27:03 2016 +0200
+++ b/src/Tools/solve_direct.ML	Thu Oct 06 11:27:28 2016 +0200
@@ -14,7 +14,8 @@
   val someN: string
   val noneN: string
   val unknownN: string
-  val max_solutions: int Unsynchronized.ref
+  val max_solutions: int Config.T
+  val strict_warnings: bool Config.T
   val solve_direct: Proof.state -> bool * (string * string list)
 end;
 
@@ -32,7 +33,8 @@
 
 (* preferences *)
 
-val max_solutions = Unsynchronized.ref 5;
+val max_solutions = Attrib.setup_config_int @{binding solve_direct_max_solutions} (K 5);
+val strict_warnings = Attrib.setup_config_bool @{binding solve_direct_strict_warnings} (K false);
 
 
 (* solve_direct command *)
@@ -44,7 +46,8 @@
 
     val crits = [(true, Find_Theorems.Solves)];
     fun find g =
-      snd (Find_Theorems.find_theorems find_ctxt (SOME g) (SOME (! max_solutions)) false crits);
+      snd (Find_Theorems.find_theorems find_ctxt (SOME g)
+        (SOME (Config.get find_ctxt max_solutions)) false crits);
 
     fun prt_result (goal, results) =
       let
@@ -76,8 +79,15 @@
     (case try seek_against_goal () of
       SOME (SOME results) =>
         (someN,
-          let val msg = Pretty.string_of (Pretty.chunks (message results))
-          in if mode = Auto_Try then [msg] else (writeln msg; []) end)
+          let
+            val msg = Pretty.string_of (Pretty.chunks (message results))
+          in
+            if Config.get ctxt strict_warnings
+            then (warning msg; [])
+            else if mode = Auto_Try
+              then [msg]
+              else (writeln msg; [])
+          end)
     | SOME NONE =>
         (if mode = Normal then writeln "No proof found"
          else ();