tuned
authornipkow
Thu, 20 Oct 2016 19:39:27 +0200
changeset 64323 20d15328b248
parent 64321 95be866e49fc (diff)
parent 64322 72060e61ca9d (current diff)
child 64328 2284011c341a
tuned
NEWS
src/HOL/ROOT
--- a/Admin/Release/build_library	Tue Oct 18 16:04:44 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,93 +0,0 @@
-#!/usr/bin/env bash
-#
-# build Isabelle HTML library from platform bundle
-
-## diagnostics
-
-PRG=$(basename "$0")
-
-function usage()
-{
-  echo
-  echo "Usage: $PRG [OPTIONS] ARCHIVE"
-  echo
-  echo "  Options are:"
-  echo "    -j INT       maximum number of parallel jobs (default 1)"
-  echo
-  echo "  Build Isabelle HTML library from platform bundle."
-  echo
-  exit 1
-}
-
-function fail()
-{
-  echo "$1" >&2
-  exit 2
-}
-
-
-## process command line
-
-# options
-
-JOBS=""
-
-while getopts "j:" OPT
-do
-  case "$OPT" in
-    j)
-      JOBS="-j $OPTARG"
-      ;;
-    \?)
-      usage
-      ;;
-  esac
-done
-
-shift $(($OPTIND - 1))
-
-
-# args
-
-[ "$#" -ne 1 ] && usage
-
-ARCHIVE="$1"; shift
-
-[ ! -f "$ARCHIVE" ] && fail "Bad archive file $ARCHIVE"
-ARCHIVE_BASE="$(basename "$ARCHIVE")"
-ARCHIVE_DIR="$(cd "$(dirname "$ARCHIVE")"; echo "$PWD")"
-ARCHIVE_FULL="$ARCHIVE_DIR/$ARCHIVE_BASE"
-
-
-## main
-
-#GNU tar (notably on Mac OS X)
-type -p gnutar >/dev/null && function tar() { gnutar "$@"; }
-
-TMP="/var/tmp/isabelle-makedist$$"
-mkdir "$TMP" || fail "Cannot create directory: \"$TMP\""
-
-cd "$TMP"
-tar -x -z -f "$ARCHIVE_FULL"
-
-cd *
-ISABELLE_NAME="$(basename "$PWD")"
-
-env ISABELLE_IDENTIFIER="${ISABELLE_NAME}-build" \
-  ./bin/isabelle build $JOBS -s -c -a -d '~~/src/Benchmarks' -o browser_info \
-    -o "document=pdf" -o "document_variants=document:outline=/proof,/ML"
-RC="$?"
-
-cd ..
-
-if [ "$RC" = 0 ]; then
-  chmod -R a+r "$ISABELLE_NAME"
-  chmod -R g=o "$ISABELLE_NAME"
-  tar -c -z -f "$ARCHIVE_DIR/${ISABELLE_NAME}_library.tar.gz" "$ISABELLE_NAME/browser_info"
-fi
-
-# clean up
-cd /tmp
-rm -rf "$TMP"
-
-exit "$RC"
--- a/Admin/Windows/Cygwin/README	Tue Oct 18 16:04:44 2016 +0200
+++ b/Admin/Windows/Cygwin/README	Thu Oct 20 19:39:27 2016 +0200
@@ -16,3 +16,21 @@
   http://isabelle.in.tum.de/cygwin_2016  (Isabelle2016-1)
 
 * Quasi-component: "isabelle makedist_cygwin" (as administrator)
+
+* SSH server:
+
+  - run Cygwin terminal as Administrator
+
+  - run ssh-host-config
+
+    StrictMode: yes
+    privilege separation: yes
+    new local account 'sshd': yes
+    sshd as a service: yes
+    different name (than cyg_server): no
+    new privileged account cyg_server: yes
+
+  - mkpasswd -l > /etc/passwd
+    mkgroup -l > /etc/group
+
+    passwd -R USER
--- a/Admin/components/components.sha1	Tue Oct 18 16:04:44 2016 +0200
+++ b/Admin/components/components.sha1	Thu Oct 20 19:39:27 2016 +0200
@@ -65,6 +65,7 @@
 baa6de37bb6f7a104ce5fe6506bca3d2572d601a  jdk-7u80.tar.gz
 7d5b152ac70f720bb9e783fa45ecadcf95069584  jdk-7u9.tar.gz
 baf275a68d3f799a841932e4e9a95a1a604058ae  jdk-8u102.tar.gz
+741de6a4a805a0f9fb917d1845409e99346c2747  jdk-8u112.tar.gz
 5442f1015a0657259be0590b04572cd933431df7  jdk-8u11.tar.gz
 cfecb1383faaf027ffbabfcd77a0b6a6521e0969  jdk-8u20.tar.gz
 44ffeeae219782d40ce6822b580e608e72fd4c76  jdk-8u31.tar.gz
--- a/Admin/components/main	Tue Oct 18 16:04:44 2016 +0200
+++ b/Admin/components/main	Thu Oct 20 19:39:27 2016 +0200
@@ -5,7 +5,7 @@
 e-1.8
 Haskabelle-2015
 isabelle_fonts-20160830
-jdk-8u102
+jdk-8u112
 jedit_build-20160330
 jfreechart-1.0.14-1
 jortho-1.0-2
--- a/Admin/java/build	Tue Oct 18 16:04:44 2016 +0200
+++ b/Admin/java/build	Thu Oct 20 19:39:27 2016 +0200
@@ -14,8 +14,8 @@
 
 ## parameters
 
-VERSION="8u102"
-FULL_VERSION="1.8.0_102"
+VERSION="8u112"
+FULL_VERSION="1.8.0_112"
 
 ARCHIVE_LINUX32="jdk-${VERSION}-linux-i586.tar.gz"
 ARCHIVE_LINUX64="jdk-${VERSION}-linux-x64.tar.gz"
--- a/Admin/profiling_report	Tue Oct 18 16:04:44 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-#!/usr/bin/env perl
-#
-# Author: Makarius
-#
-# DESCRIPTION: Simple report generator for Poly/ML profiling output.
-
-use strict;
-
-my %log = ();
-my @output = ();
-
-while (<ARGV>) {
-    if (m,^([ 0-9]{10}) (\S+$|GARBAGE COLLECTION.*$),) {
-	my $count = $1;
-	my $fun = $2;
-	$fun =~ s,-?\(\d+\).*$,,g;
-	$fun =~ s,/\d+$,,g;
-	if ($count =~ m,^\s*(\d)+$,) {
-	    if (defined($log{$fun})) {
-		$log{$fun} += $count;
-	    } else {
-		$log{$fun} = $count;
-	    }
-	}
-    }
-}
-
-foreach my $fun (keys %log) {
-    push @output, (sprintf "%14u %s\n", $log{$fun}, $fun);
-}
-
-print (sort @output);
--- a/Admin/profiling_reports	Tue Oct 18 16:04:44 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-#!/usr/bin/env bash
-#
-# Author: Makarius
-#
-# DESCRIPTION: Cumulative reports for Poly/ML profiling output.
-
-THIS="$(cd $(dirname "$0"); pwd)"
-
-SRC="$1"
-DST="$2"
-
-mkdir -p "$DST"
-
-for FILE in "$SRC"/*.gz
-do
-  echo "$FILE"
-  NAME="$(basename "$FILE" .gz)"
-  gzip -dc "$FILE" | "$THIS/profiling_report" > "$DST/$NAME"
-done
--- a/NEWS	Tue Oct 18 16:04:44 2016 +0200
+++ b/NEWS	Thu Oct 20 19:39:27 2016 +0200
@@ -281,7 +281,12 @@
     mod_1 ~> mod_by_Suc_0
 INCOMPATIBILITY.
 
-* Renamed "setsum" ~> "sum" and "setprod" ~> "prod".
+* Renamed constants "setsum" ~> "sum" and "setprod" ~> "prod".
+  Corresponding renaming of theorems.
+
+* New type class "idom_abs_sgn" specifies algebraic properties
+of sign and absolute value functions.  Type class "sgn_if" has
+disappeared.  Slight INCOMPATIBILITY.
 
 * Dedicated syntax LENGTH('a) for length of types.
 
@@ -1035,6 +1040,9 @@
 exhaust the small 32-bit address space of the ML process (which is used
 by default).
 
+* System option "profiling" specifies the mode for global ML profiling
+in "isabelle build". Possible values are "time", "allocations".
+
 * System option "ML_process_policy" specifies an optional command prefix
 for the underlying ML process, e.g. to control CPU affinity on
 multiprocessor systems. The "isabelle jedit" tool allows to override the
--- a/etc/options	Tue Oct 18 16:04:44 2016 +0200
+++ b/etc/options	Thu Oct 20 19:39:27 2016 +0200
@@ -108,6 +108,9 @@
 option checkpoint : bool = false
   -- "checkpoint for theories during build process (heap compression)"
 
+option profiling : string = ""
+  -- "ML profiling (possible values: time, allocations)"
+
 
 section "ML System"
 
--- a/src/Doc/System/Sessions.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Doc/System/Sessions.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -215,6 +215,11 @@
     Isabelle/Scala. Thus it is relatively reliable in canceling processes that
     get out of control, even if there is a deadlock without CPU time usage.
 
+    \<^item> @{system_option_def "profiling"} specifies a mode for global ML
+    profiling. Possible values are the empty string (disabled), \<^verbatim>\<open>time\<close> for
+    @{ML profile_time} and \<^verbatim>\<open>allocations\<close> for @{ML profile_allocations}.
+    Results appear near the bottom of the session log file.
+
   The @{tool_def options} tool prints Isabelle system options. Its
   command-line usage is:
   @{verbatim [display]
--- a/src/HOL/Analysis/Analysis.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Analysis.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -8,9 +8,10 @@
   Determinants
   Homeomorphism
   Bounded_Continuous_Function
+  Function_Topology
   Weierstrass_Theorems
   Polytope
-  FurtherTopology
+  Further_Topology
   Poly_Roots
   Conformal_Mappings
   Generalised_Binomial_Theorem
--- a/src/HOL/Analysis/Bochner_Integration.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Bochner_Integration.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1157,7 +1157,7 @@
   let ?s = "\<lambda>n. simple_bochner_integral M (s n)"
 
   have "\<exists>x. ?s \<longlonglongrightarrow> x"
-    unfolding convergent_eq_cauchy
+    unfolding convergent_eq_Cauchy
   proof (rule metric_CauchyI)
     fix e :: real assume "0 < e"
     then have "0 < ennreal (e / 2)" by auto
--- a/src/HOL/Analysis/Borel_Space.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Borel_Space.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -345,6 +345,14 @@
   "A \<in> sets borel \<Longrightarrow> insert x A \<in> sets (borel :: 'a::t1_space measure)"
   unfolding insert_def by (rule sets.Un) auto
 
+lemma sets_borel_eq_count_space: "sets (borel :: 'a::{countable, t2_space} measure) = count_space UNIV"
+proof -
+  have "(\<Union>a\<in>A. {a}) \<in> sets borel" for A :: "'a set"
+    by (intro sets.countable_UN') auto
+  then show ?thesis
+    by auto
+qed
+
 lemma borel_comp[measurable]: "A \<in> sets borel \<Longrightarrow> - A \<in> sets borel"
   unfolding Compl_eq_Diff_UNIV by simp
 
@@ -1797,13 +1805,13 @@
 proof -
   define u' where "u' x = lim (\<lambda>i. if Cauchy (\<lambda>i. f i x) then f i x else 0)" for x
   then have *: "\<And>x. lim (\<lambda>i. f i x) = (if Cauchy (\<lambda>i. f i x) then u' x else (THE x. False))"
-    by (auto simp: lim_def convergent_eq_cauchy[symmetric])
+    by (auto simp: lim_def convergent_eq_Cauchy[symmetric])
   have "u' \<in> borel_measurable M"
   proof (rule borel_measurable_LIMSEQ_metric)
     fix x
     have "convergent (\<lambda>i. if Cauchy (\<lambda>i. f i x) then f i x else 0)"
       by (cases "Cauchy (\<lambda>i. f i x)")
-         (auto simp add: convergent_eq_cauchy[symmetric] convergent_def)
+         (auto simp add: convergent_eq_Cauchy[symmetric] convergent_def)
     then show "(\<lambda>i. if Cauchy (\<lambda>i. f i x) then f i x else 0) \<longlonglongrightarrow> u' x"
       unfolding u'_def
       by (rule convergent_LIMSEQ_iff[THEN iffD1])
--- a/src/HOL/Analysis/Complex_Transcendental.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Complex_Transcendental.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -236,6 +236,23 @@
   finally show ?thesis .
 qed
 
+lemma exp_plus_2pin [simp]: "exp (z + \<i> * (of_int n * (of_real pi * 2))) = exp z"
+  by (simp add: exp_eq)
+
+lemma inj_on_exp_pi:
+  fixes z::complex shows "inj_on exp (ball z pi)"
+proof (clarsimp simp: inj_on_def exp_eq)
+  fix y n
+  assume "dist z (y + 2 * of_int n * of_real pi * \<i>) < pi"
+         "dist z y < pi"
+  then have "dist y (y + 2 * of_int n * of_real pi * \<i>) < pi+pi"
+    using dist_commute_lessI dist_triangle_less_add by blast
+  then have "norm (2 * of_int n * of_real pi * \<i>) < 2*pi"
+    by (simp add: dist_norm)
+  then show "n = 0"
+    by (auto simp: norm_mult)
+qed
+
 lemma sin_cos_eq_iff: "sin y = sin x \<and> cos y = cos x \<longleftrightarrow> (\<exists>n::int. y = x + 2 * n * pi)"
 proof -
   { assume "sin y = sin x" "cos y = cos x"
--- a/src/HOL/Analysis/Convex_Euclidean_Space.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Convex_Euclidean_Space.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -4378,6 +4378,15 @@
 definition "rel_interior S =
   {x. \<exists>T. openin (subtopology euclidean (affine hull S)) T \<and> x \<in> T \<and> T \<subseteq> S}"
 
+lemma rel_interior_mono:
+   "\<lbrakk>S \<subseteq> T; affine hull S = affine hull T\<rbrakk>
+   \<Longrightarrow> (rel_interior S) \<subseteq> (rel_interior T)"
+  by (auto simp: rel_interior_def)
+
+lemma rel_interior_maximal:
+   "\<lbrakk>T \<subseteq> S; openin(subtopology euclidean (affine hull S)) T\<rbrakk> \<Longrightarrow> T \<subseteq> (rel_interior S)"
+  by (auto simp: rel_interior_def)
+
 lemma rel_interior:
   "rel_interior S = {x \<in> S. \<exists>T. open T \<and> x \<in> T \<and> T \<inter> affine hull S \<subseteq> S}"
   unfolding rel_interior_def[of S] openin_open[of "affine hull S"]
--- a/src/HOL/Analysis/Derivative.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Derivative.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1922,7 +1922,7 @@
     using assms(1,2,3) by (rule has_derivative_sequence_lipschitz)
   have "\<exists>g. \<forall>x\<in>s. ((\<lambda>n. f n x) \<longlongrightarrow> g x) sequentially"
     apply (rule bchoice)
-    unfolding convergent_eq_cauchy
+    unfolding convergent_eq_Cauchy
   proof
     fix x
     assume "x \<in> s"
--- a/src/HOL/Analysis/Extended_Real_Limits.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Extended_Real_Limits.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -56,6 +56,15 @@
     by simp
 qed
 
+instance enat :: second_countable_topology
+proof
+  show "\<exists>B::enat set set. countable B \<and> open = generate_topology B"
+  proof (intro exI conjI)
+    show "countable (range lessThan \<union> range greaterThan::enat set set)"
+      by auto
+  qed (simp add: open_enat_def)
+qed
+
 instance ereal :: second_countable_topology
 proof (standard, intro exI conjI)
   let ?B = "(\<Union>r\<in>\<rat>. {{..< r}, {r <..}} :: ereal set set)"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Analysis/Function_Topology.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,1392 @@
+(*  Author:  Sébastien Gouëzel   sebastien.gouezel@univ-rennes1.fr
+    License: BSD
+*)
+
+theory Function_Topology
+imports Topology_Euclidean_Space Bounded_Linear_Function Finite_Product_Measure
+begin
+
+
+section {*Product topology*}
+
+text {*We want to define the product topology.
+
+The product topology on a product of topological spaces is generated by
+the sets which are products of open sets along finitely many coordinates, and the whole
+space along the other coordinates. This is the coarsest topology for which the projection
+to each factor is continuous.
+
+To form a product of objects in Isabelle/HOL, all these objects should be subsets of a common type
+'a. The product is then @{term "PiE I X"}, the set of elements from 'i to 'a such that the $i$-th
+coordinate belongs to $X\;i$ for all $i \in I$.
+
+Hence, to form a product of topological spaces, all these spaces should be subsets of a common type.
+This means that type classes can not be used to define such a product if one wants to take the
+product of different topological spaces (as the type 'a can only be given one structure of
+topological space using type classes). On the other hand, one can define different topologies (as
+introduced in \verb+Topology_Euclidean_Space.thy+) on one type, and these topologies do not need to
+share the same maximal open set. Hence, one can form a product of topologies in this sense, and
+this works well. The big caveat is that it does not interact well with the main body of
+topology in Isabelle/HOL defined in terms of type classes... For instance, continuity of maps
+is not defined in this setting.
+
+As the product of different topological spaces is very important in several areas of
+mathematics (for instance adeles), I introduce below the product topology in terms of topologies,
+and reformulate afterwards the consequences in terms of type classes (which are of course very
+handy for applications).
+
+Given this limitation, it looks to me that it would be very beneficial to revamp the theory
+of topological spaces in Isabelle/HOL in terms of topologies, and keep the statements involving
+type classes as consequences of more general statements in terms of topologies (but I am
+probably too naive here).
+
+Here is an example of a reformulation using topologies. Let
+\begin{verbatim}
+continuous_on_topo T1 T2 f = ((\<forall> U. openin T2 U \<longrightarrow> openin T1 (f-`U \<inter> topspace(T1)))
+                                      \<and> (f`(topspace T1) \<subseteq> (topspace T2)))
+\end{verbatim}
+be the natural continuity definition of a map from the topology $T1$ to the topology $T2$. Then
+the current \verb+continuous_on+ (with type classes) can be redefined as
+\begin{verbatim}
+continuous_on s f = continuous_on_topo (subtopology euclidean s) (topology euclidean) f
+\end{verbatim}
+
+In fact, I need \verb+continuous_on_topo+ to express the continuity of the projection on subfactors
+for the product topology, in Lemma~\verb+continuous_on_restrict_product_topology+, and I show
+the above equivalence in Lemma~\verb+continuous_on_continuous_on_topo+.
+
+I only develop the basics of the product topology in this theory. The most important missing piece
+is Tychonov theorem, stating that a product of compact spaces is always compact for the product
+topology, even when the product is not finite (or even countable).
+
+I realized afterwards that this theory has a lot in common with \verb+Fin_Map.thy+.
+*}
+
+subsection {*Topology without type classes*}
+
+subsubsection {*The topology generated by some (open) subsets*}
+
+text {* In the definition below of a generated topology, the \<open>Empty\<close> case is not necessary,
+as it follows from \<open>UN\<close> taking for $K$ the empty set. However, it is convenient to have,
+and is never a problem in proofs, so I prefer to write it down explicitly.
+
+We do not require UNIV to be an open set, as this will not be the case in applications. (We are
+thinking of a topology on a subset of UNIV, the remaining part of UNIV being irrelevant.)*}
+
+inductive generate_topology_on for S where
+Empty: "generate_topology_on S {}"
+|Int: "generate_topology_on S a \<Longrightarrow> generate_topology_on S b \<Longrightarrow> generate_topology_on S (a \<inter> b)"
+| UN: "(\<And>k. k \<in> K \<Longrightarrow> generate_topology_on S k) \<Longrightarrow> generate_topology_on S (\<Union>K)"
+| Basis: "s \<in> S \<Longrightarrow> generate_topology_on S s"
+
+lemma istopology_generate_topology_on:
+  "istopology (generate_topology_on S)"
+unfolding istopology_def by (auto intro: generate_topology_on.intros)
+
+text {*The basic property of the topology generated by a set $S$ is that it is the
+smallest topology containing all the elements of $S$:*}
+
+lemma generate_topology_on_coarsest:
+  assumes "istopology T"
+          "\<And>s. s \<in> S \<Longrightarrow> T s"
+          "generate_topology_on S s0"
+  shows "T s0"
+using assms(3) apply (induct rule: generate_topology_on.induct)
+using assms(1) assms(2) unfolding istopology_def by auto
+
+definition topology_generated_by::"('a set set) \<Rightarrow> ('a topology)"
+  where "topology_generated_by S = topology (generate_topology_on S)"
+
+lemma openin_topology_generated_by_iff:
+  "openin (topology_generated_by S) s \<longleftrightarrow> generate_topology_on S s"
+using topology_inverse'[OF istopology_generate_topology_on[of S]]
+unfolding topology_generated_by_def by simp
+
+lemma openin_topology_generated_by:
+  "openin (topology_generated_by S) s \<Longrightarrow> generate_topology_on S s"
+using openin_topology_generated_by_iff by auto
+
+lemma topology_generated_by_topspace:
+  "topspace (topology_generated_by S) = (\<Union>S)"
+proof
+  {
+    fix s assume "openin (topology_generated_by S) s"
+    then have "generate_topology_on S s" by (rule openin_topology_generated_by)
+    then have "s \<subseteq> (\<Union>S)" by (induct, auto)
+  }
+  then show "topspace (topology_generated_by S) \<subseteq> (\<Union>S)"
+    unfolding topspace_def by auto
+next
+  have "generate_topology_on S (\<Union>S)"
+    using generate_topology_on.UN[OF generate_topology_on.Basis, of S S] by simp
+  then show "(\<Union>S) \<subseteq> topspace (topology_generated_by S)"
+    unfolding topspace_def using openin_topology_generated_by_iff by auto
+qed
+
+lemma topology_generated_by_Basis:
+  "s \<in> S \<Longrightarrow> openin (topology_generated_by S) s"
+by (simp only: openin_topology_generated_by_iff, auto simp: generate_topology_on.Basis)
+
+subsubsection {*Continuity*}
+
+text {*We will need to deal with continuous maps in terms of topologies and not in terms
+of type classes, as defined below.*}
+
+definition continuous_on_topo::"'a topology \<Rightarrow> 'b topology \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool"
+  where "continuous_on_topo T1 T2 f = ((\<forall> U. openin T2 U \<longrightarrow> openin T1 (f-`U \<inter> topspace(T1)))
+                                      \<and> (f`(topspace T1) \<subseteq> (topspace T2)))"
+
+lemma continuous_on_continuous_on_topo:
+  "continuous_on s f \<longleftrightarrow> continuous_on_topo (subtopology euclidean s) euclidean f"
+unfolding continuous_on_open_invariant openin_open vimage_def continuous_on_topo_def
+topspace_euclidean_subtopology open_openin topspace_euclidean by fast
+
+lemma continuous_on_topo_UNIV:
+  "continuous_on UNIV f \<longleftrightarrow> continuous_on_topo euclidean euclidean f"
+using continuous_on_continuous_on_topo[of UNIV f] subtopology_UNIV[of euclidean] by auto
+
+lemma continuous_on_topo_open [intro]:
+  "continuous_on_topo T1 T2 f \<Longrightarrow> openin T2 U \<Longrightarrow> openin T1 (f-`U \<inter> topspace(T1))"
+unfolding continuous_on_topo_def by auto
+
+lemma continuous_on_topo_topspace [intro]:
+  "continuous_on_topo T1 T2 f \<Longrightarrow> f`(topspace T1) \<subseteq> (topspace T2)"
+unfolding continuous_on_topo_def by auto
+
+lemma continuous_on_generated_topo_iff:
+  "continuous_on_topo T1 (topology_generated_by S) f \<longleftrightarrow>
+      ((\<forall>U. U \<in> S \<longrightarrow> openin T1 (f-`U \<inter> topspace(T1))) \<and> (f`(topspace T1) \<subseteq> (\<Union> S)))"
+unfolding continuous_on_topo_def topology_generated_by_topspace
+proof (auto simp add: topology_generated_by_Basis)
+  assume H: "\<forall>U. U \<in> S \<longrightarrow> openin T1 (f -` U \<inter> topspace T1)"
+  fix U assume "openin (topology_generated_by S) U"
+  then have "generate_topology_on S U" by (rule openin_topology_generated_by)
+  then show "openin T1 (f -` U \<inter> topspace T1)"
+  proof (induct)
+    fix a b
+    assume H: "openin T1 (f -` a \<inter> topspace T1)" "openin T1 (f -` b \<inter> topspace T1)"
+    have "f -` (a \<inter> b) \<inter> topspace T1 = (f-`a \<inter> topspace T1) \<inter> (f-`b \<inter> topspace T1)"
+      by auto
+    then show "openin T1 (f -` (a \<inter> b) \<inter> topspace T1)" using H by auto
+  next
+    fix K
+    assume H: "openin T1 (f -` k \<inter> topspace T1)" if "k\<in> K" for k
+    define L where "L = {f -` k \<inter> topspace T1|k. k \<in> K}"
+    have *: "openin T1 l" if "l \<in>L" for l using that H unfolding L_def by auto
+    have "openin T1 (\<Union>L)" using openin_Union[OF *] by simp
+    moreover have "(\<Union>L) = (f -` \<Union>K \<inter> topspace T1)" unfolding L_def by auto
+    ultimately show "openin T1 (f -` \<Union>K \<inter> topspace T1)" by simp
+  qed (auto simp add: H)
+qed
+
+lemma continuous_on_generated_topo:
+  assumes "\<And>U. U \<in>S \<Longrightarrow> openin T1 (f-`U \<inter> topspace(T1))"
+          "f`(topspace T1) \<subseteq> (\<Union> S)"
+  shows "continuous_on_topo T1 (topology_generated_by S) f"
+using assms continuous_on_generated_topo_iff by blast
+
+lemma continuous_on_topo_compose:
+  assumes "continuous_on_topo T1 T2 f" "continuous_on_topo T2 T3 g"
+  shows "continuous_on_topo T1 T3 (g o f)"
+using assms unfolding continuous_on_topo_def
+proof (auto)
+  fix U :: "'c set"
+  assume H: "openin T3 U"
+  have "openin T1 (f -` (g -` U \<inter> topspace T2) \<inter> topspace T1)"
+    using H assms by blast
+  moreover have "f -` (g -` U \<inter> topspace T2) \<inter> topspace T1 = (g \<circ> f) -` U \<inter> topspace T1"
+    using H assms continuous_on_topo_topspace by fastforce
+  ultimately show "openin T1 ((g \<circ> f) -` U \<inter> topspace T1)"
+    by simp
+qed (blast)
+
+lemma continuous_on_topo_preimage_topspace [intro]:
+  assumes "continuous_on_topo T1 T2 f"
+  shows "f-`(topspace T2) \<inter> topspace T1 = topspace T1"
+using assms unfolding continuous_on_topo_def by auto
+
+
+subsubsection {*Pullback topology*}
+
+text {*Pulling back a topology by map gives again a topology. \<open>subtopology\<close> is
+a special case of this notion, pulling back by the identity. We introduce the general notion as
+we will need it to define the strong operator topology on the space of continuous linear operators,
+by pulling back the product topology on the space of all functions.*}
+
+text {*\verb+pullback_topology A f T+ is the pullback of the topology $T$ by the map $f$ on
+the set $A$.*}
+
+definition pullback_topology::"('a set) \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> ('b topology) \<Rightarrow> ('a topology)"
+  where "pullback_topology A f T = topology (\<lambda>S. \<exists>U. openin T U \<and> S = f-`U \<inter> A)"
+
+lemma istopology_pullback_topology:
+  "istopology (\<lambda>S. \<exists>U. openin T U \<and> S = f-`U \<inter> A)"
+unfolding istopology_def proof (auto)
+  fix K assume "\<forall>S\<in>K. \<exists>U. openin T U \<and> S = f -` U \<inter> A"
+  then have "\<exists>U. \<forall>S\<in>K. openin T (U S) \<and> S = f-`(U S) \<inter> A"
+    by (rule bchoice)
+  then obtain U where U: "\<forall>S\<in>K. openin T (U S) \<and> S = f-`(U S) \<inter> A"
+    by blast
+  define V where "V = (\<Union>S\<in>K. U S)"
+  have "openin T V" "\<Union>K = f -` V \<inter> A" unfolding V_def using U by auto
+  then show "\<exists>V. openin T V \<and> \<Union>K = f -` V \<inter> A" by auto
+qed
+
+lemma openin_pullback_topology:
+  "openin (pullback_topology A f T) S \<longleftrightarrow> (\<exists>U. openin T U \<and> S = f-`U \<inter> A)"
+unfolding pullback_topology_def topology_inverse'[OF istopology_pullback_topology] by auto
+
+lemma topspace_pullback_topology:
+  "topspace (pullback_topology A f T) = f-`(topspace T) \<inter> A"
+by (auto simp add: topspace_def openin_pullback_topology)
+
+lemma continuous_on_topo_pullback [intro]:
+  assumes "continuous_on_topo T1 T2 g"
+  shows "continuous_on_topo (pullback_topology A f T1) T2 (g o f)"
+unfolding continuous_on_topo_def
+proof (auto)
+  fix U::"'b set" assume "openin T2 U"
+  then have "openin T1 (g-`U \<inter> topspace T1)"
+    using assms unfolding continuous_on_topo_def by auto
+  have "(g o f)-`U \<inter> topspace (pullback_topology A f T1) = (g o f)-`U \<inter> A \<inter> f-`(topspace T1)"
+    unfolding topspace_pullback_topology by auto
+  also have "... = f-`(g-`U \<inter> topspace T1) \<inter> A "
+    by auto
+  also have "openin (pullback_topology A f T1) (...)"
+    unfolding openin_pullback_topology using `openin T1 (g-\`U \<inter> topspace T1)` by auto
+  finally show "openin (pullback_topology A f T1) ((g \<circ> f) -` U \<inter> topspace (pullback_topology A f T1))"
+    by auto
+next
+  fix x assume "x \<in> topspace (pullback_topology A f T1)"
+  then have "f x \<in> topspace T1"
+    unfolding topspace_pullback_topology by auto
+  then show "g (f x) \<in> topspace T2"
+    using assms unfolding continuous_on_topo_def by auto
+qed
+
+lemma continuous_on_topo_pullback' [intro]:
+  assumes "continuous_on_topo T1 T2 (f o g)" "topspace T1 \<subseteq> g-`A"
+  shows "continuous_on_topo T1 (pullback_topology A f T2) g"
+unfolding continuous_on_topo_def
+proof (auto)
+  fix U assume "openin (pullback_topology A f T2) U"
+  then have "\<exists>V. openin T2 V \<and> U = f-`V \<inter> A"
+    unfolding openin_pullback_topology by auto
+  then obtain V where "openin T2 V" "U = f-`V \<inter> A"
+    by blast
+  then have "g -` U \<inter> topspace T1 = g-`(f-`V \<inter> A) \<inter> topspace T1"
+    by blast
+  also have "... = (f o g)-`V \<inter> (g-`A \<inter> topspace T1)"
+    by auto
+  also have "... = (f o g)-`V \<inter> topspace T1"
+    using assms(2) by auto
+  also have "openin T1 (...)"
+    using assms(1) `openin T2 V` by auto
+  finally show "openin T1 (g -` U \<inter> topspace T1)" by simp
+next
+  fix x assume "x \<in> topspace T1"
+  have "(f o g) x \<in> topspace T2"
+    using assms(1) `x \<in> topspace T1` unfolding continuous_on_topo_def by auto
+  then have "g x \<in> f-`(topspace T2)"
+    unfolding comp_def by blast
+  moreover have "g x \<in> A" using assms(2) `x \<in> topspace T1` by blast
+  ultimately show "g x \<in> topspace (pullback_topology A f T2)"
+    unfolding topspace_pullback_topology by blast
+qed
+
+subsubsection {*Miscellaneous*}
+
+text {*The following could belong to \verb+Topology_Euclidean_Spaces.thy+, and will be needed
+below.*}
+lemma openin_INT [intro]:
+  assumes "finite I"
+          "\<And>i. i \<in> I \<Longrightarrow> openin T (U i)"
+  shows "openin T ((\<Inter>i \<in> I. U i) \<inter> topspace T)"
+using assms by (induct, auto simp add: inf_sup_aci(2) openin_Int)
+
+lemma openin_INT2 [intro]:
+  assumes "finite I" "I \<noteq> {}"
+          "\<And>i. i \<in> I \<Longrightarrow> openin T (U i)"
+  shows "openin T (\<Inter>i \<in> I. U i)"
+proof -
+  have "(\<Inter>i \<in> I. U i) \<subseteq> topspace T"
+    using `I \<noteq> {}` openin_subset[OF assms(3)] by auto
+  then show ?thesis
+    using openin_INT[of _ _ U, OF assms(1) assms(3)] by (simp add: inf.absorb2 inf_commute)
+qed
+
+
+subsection {*The product topology*}
+
+text {*We can now define the product topology, as generated by
+the sets which are products of open sets along finitely many coordinates, and the whole
+space along the other coordinates. Equivalently, it is generated by sets which are one open
+set along one single coordinate, and the whole space along other coordinates. In fact, this is only
+equivalent for nonempty products, but for the empty product the first formulation is better
+(the second one gives an empty product space, while an empty product should have exactly one
+point, equal to \verb+undefined+ along all coordinates.
+
+So, we use the first formulation, which moreover seems to give rise to more straightforward proofs.
+*}
+
+definition product_topology::"('i \<Rightarrow> ('a topology)) \<Rightarrow> ('i set) \<Rightarrow> (('i \<Rightarrow> 'a) topology)"
+  where "product_topology T I =
+    topology_generated_by {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}}"
+
+text {*The total set of the product topology is the product of the total sets
+along each coordinate.*}
+
+lemma product_topology_topspace:
+  "topspace (product_topology T I) = (\<Pi>\<^sub>E i\<in>I. topspace(T i))"
+proof
+  show "topspace (product_topology T I) \<subseteq> (\<Pi>\<^sub>E i\<in>I. topspace (T i))"
+    unfolding product_topology_def apply (simp only: topology_generated_by_topspace)
+    unfolding topspace_def by auto
+  have "(\<Pi>\<^sub>E i\<in>I. topspace (T i)) \<in> {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}}"
+    using openin_topspace not_finite_existsD by auto
+  then show "(\<Pi>\<^sub>E i\<in>I. topspace (T i)) \<subseteq> topspace (product_topology T I)"
+    unfolding product_topology_def using PiE_def by (auto simp add: topology_generated_by_topspace)
+qed
+
+lemma product_topology_basis:
+  assumes "\<And>i. openin (T i) (X i)" "finite {i. X i \<noteq> topspace (T i)}"
+  shows "openin (product_topology T I) (\<Pi>\<^sub>E i\<in>I. X i)"
+unfolding product_topology_def apply (rule topology_generated_by_Basis) using assms by auto
+
+lemma product_topology_open_contains_basis:
+  assumes "openin (product_topology T I) U"
+          "x \<in> U"
+  shows "\<exists>X. x \<in> (\<Pi>\<^sub>E i\<in>I. X i) \<and> (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)} \<and> (\<Pi>\<^sub>E i\<in>I. X i) \<subseteq> U"
+proof -
+  have "generate_topology_on {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}} U"
+    using assms unfolding product_topology_def by (intro openin_topology_generated_by) auto
+  then have "\<And>x. x\<in>U \<Longrightarrow> \<exists>X. x \<in> (\<Pi>\<^sub>E i\<in>I. X i) \<and> (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)} \<and> (\<Pi>\<^sub>E i\<in>I. X i) \<subseteq> U"
+  proof induction
+    case (Int U V x)
+    then obtain XU XV where H:
+      "x \<in> Pi\<^sub>E I XU" "(\<forall>i. openin (T i) (XU i))" "finite {i. XU i \<noteq> topspace (T i)}" "Pi\<^sub>E I XU \<subseteq> U"
+      "x \<in> Pi\<^sub>E I XV" "(\<forall>i. openin (T i) (XV i))" "finite {i. XV i \<noteq> topspace (T i)}" "Pi\<^sub>E I XV \<subseteq> V"
+      by auto meson
+    define X where "X = (\<lambda>i. XU i \<inter> XV i)"
+    have "Pi\<^sub>E I X \<subseteq> Pi\<^sub>E I XU \<inter> Pi\<^sub>E I XV"
+      unfolding X_def by (auto simp add: PiE_iff)
+    then have "Pi\<^sub>E I X \<subseteq> U \<inter> V" using H by auto
+    moreover have "\<forall>i. openin (T i) (X i)"
+      unfolding X_def using H by auto
+    moreover have "finite {i. X i \<noteq> topspace (T i)}"
+      apply (rule rev_finite_subset[of "{i. XU i \<noteq> topspace (T i)} \<union> {i. XV i \<noteq> topspace (T i)}"])
+      unfolding X_def using H by auto
+    moreover have "x \<in> Pi\<^sub>E I X"
+      unfolding X_def using H by auto
+    ultimately show ?case
+      by auto
+  next
+    case (UN K x)
+    then obtain k where "k \<in> K" "x \<in> k" by auto
+    with UN have "\<exists>X. x \<in> Pi\<^sub>E I X \<and> (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)} \<and> Pi\<^sub>E I X \<subseteq> k"
+      by simp
+    then obtain X where "x \<in> Pi\<^sub>E I X \<and> (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)} \<and> Pi\<^sub>E I X \<subseteq> k"
+      by blast
+    then have "x \<in> Pi\<^sub>E I X \<and> (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)} \<and> Pi\<^sub>E I X \<subseteq> (\<Union>K)"
+      using `k \<in> K` by auto
+    then show ?case
+      by auto
+  qed auto
+  then show ?thesis using `x \<in> U` by auto
+qed
+
+
+text {*The basic property of the product topology is the continuity of projections:*}
+
+lemma continuous_on_topo_product_coordinates [simp]:
+  assumes "i \<in> I"
+  shows "continuous_on_topo (product_topology T I) (T i) (\<lambda>x. x i)"
+proof -
+  {
+    fix U assume "openin (T i) U"
+    define X where "X = (\<lambda>j. if j = i then U else topspace (T j))"
+    then have *: "(\<lambda>x. x i) -` U \<inter> (\<Pi>\<^sub>E i\<in>I. topspace (T i)) = (\<Pi>\<^sub>E j\<in>I. X j)"
+      unfolding X_def using assms openin_subset[OF `openin (T i) U`]
+      by (auto simp add: PiE_iff, auto, metis subsetCE)
+    have **: "(\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}"
+      unfolding X_def using `openin (T i) U` by auto
+    have "openin (product_topology T I) ((\<lambda>x. x i) -` U \<inter> (\<Pi>\<^sub>E i\<in>I. topspace (T i)))"
+      unfolding product_topology_def
+      apply (rule topology_generated_by_Basis)
+      apply (subst *)
+      using ** by auto
+  }
+  then show ?thesis unfolding continuous_on_topo_def
+    by (auto simp add: assms product_topology_topspace PiE_iff)
+qed
+
+lemma continuous_on_topo_coordinatewise_then_product [intro]:
+  assumes "\<And>i. i \<in> I \<Longrightarrow> continuous_on_topo T1 (T i) (\<lambda>x. f x i)"
+          "\<And>i x. i \<notin> I \<Longrightarrow> x \<in> topspace T1 \<Longrightarrow> f x i = undefined"
+  shows "continuous_on_topo T1 (product_topology T I) f"
+unfolding product_topology_def
+proof (rule continuous_on_generated_topo)
+  fix U assume "U \<in> {Pi\<^sub>E I X |X. (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}}"
+  then obtain X where H: "U = Pi\<^sub>E I X" "\<And>i. openin (T i) (X i)" "finite {i. X i \<noteq> topspace (T i)}"
+    by blast
+  define J where "J = {i \<in> I. X i \<noteq> topspace (T i)}"
+  have "finite J" "J \<subseteq> I" unfolding J_def using H(3) by auto
+  have "(\<lambda>x. f x i)-`(topspace(T i)) \<inter> topspace T1 = topspace T1" if "i \<in> I" for i
+    using that assms(1) by (simp add: continuous_on_topo_preimage_topspace)
+  then have *: "(\<lambda>x. f x i)-`(X i) \<inter> topspace T1 = topspace T1" if "i \<in> I-J" for i
+    using that unfolding J_def by auto
+  have "f-`U \<inter> topspace T1 = (\<Inter>i\<in>I. (\<lambda>x. f x i)-`(X i) \<inter> topspace T1) \<inter> (topspace T1)"
+    by (subst H(1), auto simp add: PiE_iff assms)
+  also have "... = (\<Inter>i\<in>J. (\<lambda>x. f x i)-`(X i) \<inter> topspace T1) \<inter> (topspace T1)"
+    using * `J \<subseteq> I` by auto
+  also have "openin T1 (...)"
+    apply (rule openin_INT)
+    apply (simp add: `finite J`)
+    using H(2) assms(1) `J \<subseteq> I` by auto
+  ultimately show "openin T1 (f-`U \<inter> topspace T1)" by simp
+next
+  show "f `topspace T1 \<subseteq> \<Union>{Pi\<^sub>E I X |X. (\<forall>i. openin (T i) (X i)) \<and> finite {i. X i \<noteq> topspace (T i)}}"
+    apply (subst topology_generated_by_topspace[symmetric])
+    apply (subst product_topology_def[symmetric])
+    apply (simp only: product_topology_topspace)
+    apply (auto simp add: PiE_iff)
+    using assms unfolding continuous_on_topo_def by auto
+qed
+
+lemma continuous_on_topo_product_then_coordinatewise [intro]:
+  assumes "continuous_on_topo T1 (product_topology T I) f"
+  shows "\<And>i. i \<in> I \<Longrightarrow> continuous_on_topo T1 (T i) (\<lambda>x. f x i)"
+        "\<And>i x. i \<notin> I \<Longrightarrow> x \<in> topspace T1 \<Longrightarrow> f x i = undefined"
+proof -
+  fix i assume "i \<in> I"
+  have "(\<lambda>x. f x i) = (\<lambda>y. y i) o f" by auto
+  also have "continuous_on_topo T1 (T i) (...)"
+    apply (rule continuous_on_topo_compose[of _ "product_topology T I"])
+    using assms `i \<in> I` by auto
+  ultimately show "continuous_on_topo T1 (T i) (\<lambda>x. f x i)"
+    by simp
+next
+  fix i x assume "i \<notin> I" "x \<in> topspace T1"
+  have "f x \<in> topspace (product_topology T I)"
+    using assms `x \<in> topspace T1` unfolding continuous_on_topo_def by auto
+  then have "f x \<in> (\<Pi>\<^sub>E i\<in>I. topspace (T i))"
+    using product_topology_topspace by metis
+  then show "f x i = undefined"
+    using `i \<notin> I` by (auto simp add: PiE_iff extensional_def)
+qed
+
+lemma continuous_on_restrict:
+  assumes "J \<subseteq> I"
+  shows "continuous_on_topo (product_topology T I) (product_topology T J) (\<lambda>x. restrict x J)"
+proof (rule continuous_on_topo_coordinatewise_then_product)
+  fix i assume "i \<in> J"
+  then have "(\<lambda>x. restrict x J i) = (\<lambda>x. x i)" unfolding restrict_def by auto
+  then show "continuous_on_topo (product_topology T I) (T i) (\<lambda>x. restrict x J i)"
+    using `i \<in> J` `J \<subseteq> I` by auto
+next
+  fix i assume "i \<notin> J"
+  then show "restrict x J i = undefined" for x::"'a \<Rightarrow> 'b"
+    unfolding restrict_def by auto
+qed
+
+
+subsubsection {*Powers of a single topological space as a topological space, using type classes*}
+
+instantiation "fun" :: (type, topological_space) topological_space
+begin
+
+definition open_fun_def:
+  "open U = openin (product_topology (\<lambda>i. euclidean) UNIV) U"
+
+instance proof
+  have "topspace (product_topology (\<lambda>(i::'a). euclidean::('b topology)) UNIV) = UNIV"
+    unfolding product_topology_topspace topspace_euclidean by auto
+  then show "open (UNIV::('a \<Rightarrow> 'b) set)"
+    unfolding open_fun_def by (metis openin_topspace)
+qed (auto simp add: open_fun_def)
+
+end
+
+lemma euclidean_product_topology:
+  "euclidean = product_topology (\<lambda>i. euclidean::('b::topological_space) topology) UNIV"
+by (metis open_openin topology_eq open_fun_def)
+
+lemma product_topology_basis':
+  fixes x::"'i \<Rightarrow> 'a" and U::"'i \<Rightarrow> ('b::topological_space) set"
+  assumes "finite I" "\<And>i. i \<in> I \<Longrightarrow> open (U i)"
+  shows "open {f. \<forall>i\<in>I. f (x i) \<in> U i}"
+proof -
+  define J where "J = x`I"
+  define V where "V = (\<lambda>y. if y \<in> J then \<Inter>{U i|i. i\<in>I \<and> x i = y} else UNIV)"
+  define X where "X = (\<lambda>y. if y \<in> J then V y else UNIV)"
+  have *: "open (X i)" for i
+    unfolding X_def V_def using assms by auto
+  have **: "finite {i. X i \<noteq> UNIV}"
+    unfolding X_def V_def J_def using assms(1) by auto
+  have "open (Pi\<^sub>E UNIV X)"
+    unfolding open_fun_def apply (rule product_topology_basis)
+    using * ** unfolding open_openin topspace_euclidean by auto
+  moreover have "Pi\<^sub>E UNIV X = {f. \<forall>i\<in>I. f (x i) \<in> U i}"
+    apply (auto simp add: PiE_iff) unfolding X_def V_def J_def
+    proof (auto)
+      fix f :: "'a \<Rightarrow> 'b" and i :: 'i
+      assume a1: "i \<in> I"
+      assume a2: "\<forall>i. f i \<in> (if i \<in> x`I then if i \<in> x`I then \<Inter>{U ia |ia. ia \<in> I \<and> x ia = i} else UNIV else UNIV)"
+      have f3: "x i \<in> x`I"
+        using a1 by blast
+      have "U i \<in> {U ia |ia. ia \<in> I \<and> x ia = x i}"
+        using a1 by blast
+      then show "f (x i) \<in> U i"
+        using f3 a2 by (meson Inter_iff)
+    qed
+  ultimately show ?thesis by simp
+qed
+
+text {*The results proved in the general situation of products of possibly different
+spaces have their counterparts in this simpler setting.*}
+
+lemma continuous_on_product_coordinates [simp]:
+  "continuous_on UNIV (\<lambda>x. x i::('b::topological_space))"
+unfolding continuous_on_topo_UNIV euclidean_product_topology
+by (rule continuous_on_topo_product_coordinates, simp)
+
+lemma continuous_on_coordinatewise_then_product [intro, continuous_intros]:
+  assumes "\<And>i. continuous_on UNIV (\<lambda>x. f x i)"
+  shows "continuous_on UNIV f"
+using assms unfolding continuous_on_topo_UNIV euclidean_product_topology
+by (rule continuous_on_topo_coordinatewise_then_product, simp)
+
+lemma continuous_on_product_then_coordinatewise:
+  assumes "continuous_on UNIV f"
+  shows "continuous_on UNIV (\<lambda>x. f x i)"
+using assms unfolding continuous_on_topo_UNIV euclidean_product_topology
+by (rule continuous_on_topo_product_then_coordinatewise(1), simp)
+
+lemma continuous_on_product_coordinatewise_iff:
+  "continuous_on UNIV f \<longleftrightarrow> (\<forall>i. continuous_on UNIV (\<lambda>x. f x i))"
+by (auto intro: continuous_on_product_then_coordinatewise)
+
+subsubsection {*Topological countability for product spaces*}
+
+text {*The next two lemmas are useful to prove first or second countability
+of product spaces, but they have more to do with countability and could
+be put in the corresponding theory.*}
+
+lemma countable_nat_product_event_const:
+  fixes F::"'a set" and a::'a
+  assumes "a \<in> F" "countable F"
+  shows "countable {x::(nat \<Rightarrow> 'a). (\<forall>i. x i \<in> F) \<and> finite {i. x i \<noteq> a}}"
+proof -
+  have *: "{x::(nat \<Rightarrow> 'a). (\<forall>i. x i \<in> F) \<and> finite {i. x i \<noteq> a}}
+                  \<subseteq> (\<Union>N. {x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)})"
+    using infinite_nat_iff_unbounded_le by fastforce
+  have "countable {x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)}" for N::nat
+  proof (induction N)
+    case 0
+    have "{x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>(0::nat). x i = a)} = {(\<lambda>i. a)}"
+      using `a \<in> F` by auto
+    then show ?case by auto
+  next
+    case (Suc N)
+    define f::"((nat \<Rightarrow> 'a) \<times> 'a) \<Rightarrow> (nat \<Rightarrow> 'a)"
+      where "f = (\<lambda>(x, b). (\<lambda>i. if i = N then b else x i))"
+    have "{x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>Suc N. x i = a)} \<subseteq> f`({x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)} \<times> F)"
+    proof (auto)
+      fix x assume H: "\<forall>i::nat. x i \<in> F" "\<forall>i\<ge>Suc N. x i = a"
+      define y where "y = (\<lambda>i. if i = N then a else x i)"
+      have "f (y, x N) = x"
+        unfolding f_def y_def by auto
+      moreover have "(y, x N) \<in> {x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)} \<times> F"
+        unfolding y_def using H `a \<in> F` by auto
+      ultimately show "x \<in> f`({x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)} \<times> F)"
+        by (metis (no_types, lifting) image_eqI)
+    qed
+    moreover have "countable ({x. (\<forall>i. x i \<in> F) \<and> (\<forall>i\<ge>N. x i = a)} \<times> F)"
+      using Suc.IH assms(2) by auto
+    ultimately show ?case
+      by (meson countable_image countable_subset)
+  qed
+  then show ?thesis using countable_subset[OF *] by auto
+qed
+
+lemma countable_product_event_const:
+  fixes F::"('a::countable) \<Rightarrow> 'b set" and b::'b
+  assumes "\<And>i. countable (F i)"
+  shows "countable {f::('a \<Rightarrow> 'b). (\<forall>i. f i \<in> F i) \<and> (finite {i. f i \<noteq> b})}"
+proof -
+  define G where "G = (\<Union>i. F i) \<union> {b}"
+  have "countable G" unfolding G_def using assms by auto
+  have "b \<in> G" unfolding G_def by auto
+  define pi where "pi = (\<lambda>(x::(nat \<Rightarrow> 'b)). (\<lambda> i::'a. x ((to_nat::('a \<Rightarrow> nat)) i)))"
+  have "{f::('a \<Rightarrow> 'b). (\<forall>i. f i \<in> F i) \<and> (finite {i. f i \<noteq> b})}
+        \<subseteq> pi`{g::(nat \<Rightarrow> 'b). (\<forall>j. g j \<in> G) \<and> (finite {j. g j \<noteq> b})}"
+  proof (auto)
+    fix f assume H: "\<forall>i. f i \<in> F i" "finite {i. f i \<noteq> b}"
+    define I where "I = {i. f i \<noteq> b}"
+    define g where "g = (\<lambda>j. if j \<in> to_nat`I then f (from_nat j) else b)"
+    have "{j. g j \<noteq> b} \<subseteq> to_nat`I" unfolding g_def by auto
+    then have "finite {j. g j \<noteq> b}"
+      unfolding I_def using H(2) using finite_surj by blast
+    moreover have "g j \<in> G" for j
+      unfolding g_def G_def using H by auto
+    ultimately have "g \<in> {g::(nat \<Rightarrow> 'b). (\<forall>j. g j \<in> G) \<and> (finite {j. g j \<noteq> b})}"
+      by auto
+    moreover have "f = pi g"
+      unfolding pi_def g_def I_def using H by fastforce
+    ultimately show "f \<in> pi`{g. (\<forall>j. g j \<in> G) \<and> finite {j. g j \<noteq> b}}"
+      by auto
+  qed
+  then show ?thesis
+    using countable_nat_product_event_const[OF `b \<in> G` `countable G`]
+    by (meson countable_image countable_subset)
+qed
+
+instance "fun" :: (countable, first_countable_topology) first_countable_topology
+proof
+  fix x::"'a \<Rightarrow> 'b"
+  have "\<exists>A::('b \<Rightarrow> nat \<Rightarrow> 'b set). \<forall>x. (\<forall>i. x \<in> A x i \<and> open (A x i)) \<and> (\<forall>S. open S \<and> x \<in> S \<longrightarrow> (\<exists>i. A x i \<subseteq> S))"
+    apply (rule choice) using first_countable_basis by auto
+  then obtain A::"('b \<Rightarrow> nat \<Rightarrow> 'b set)" where A: "\<And>x i. x \<in> A x i"
+                                                  "\<And>x i. open (A x i)"
+                                                  "\<And>x S. open S \<Longrightarrow> x \<in> S \<Longrightarrow> (\<exists>i. A x i \<subseteq> S)"
+    by metis
+  text {*$B i$ is a countable basis of neighborhoods of $x_i$.*}
+  define B where "B = (\<lambda>i. (A (x i))`UNIV \<union> {UNIV})"
+  have "countable (B i)" for i unfolding B_def by auto
+
+  define K where "K = {Pi\<^sub>E UNIV X | X. (\<forall>i. X i \<in> B i) \<and> finite {i. X i \<noteq> UNIV}}"
+  have "Pi\<^sub>E UNIV (\<lambda>i. UNIV) \<in> K"
+    unfolding K_def B_def by auto
+  then have "K \<noteq> {}" by auto
+  have "countable {X. (\<forall>i. X i \<in> B i) \<and> finite {i. X i \<noteq> UNIV}}"
+    apply (rule countable_product_event_const) using `\<And>i. countable (B i)` by auto
+  moreover have "K = (\<lambda>X. Pi\<^sub>E UNIV X)`{X. (\<forall>i. X i \<in> B i) \<and> finite {i. X i \<noteq> UNIV}}"
+    unfolding K_def by auto
+  ultimately have "countable K" by auto
+  have "x \<in> k" if "k \<in> K" for k
+    using that unfolding K_def B_def apply auto using A(1) by auto
+  have "open k" if "k \<in> K" for k
+    using that unfolding open_fun_def K_def B_def apply (auto)
+    apply (rule product_topology_basis)
+    unfolding topspace_euclidean by (auto, metis imageE open_UNIV A(2))
+
+  have Inc: "\<exists>k\<in>K. k \<subseteq> U" if "open U \<and> x \<in> U" for U
+  proof -
+    have "openin (product_topology (\<lambda>i. euclidean) UNIV) U" "x \<in> U"
+      using `open U \<and> x \<in> U` unfolding open_fun_def by auto
+    with product_topology_open_contains_basis[OF this]
+    have "\<exists>X. x \<in> (\<Pi>\<^sub>E i\<in>UNIV. X i) \<and> (\<forall>i. open (X i)) \<and> finite {i. X i \<noteq> UNIV} \<and> (\<Pi>\<^sub>E i\<in>UNIV. X i) \<subseteq> U"
+      unfolding topspace_euclidean open_openin by simp
+    then obtain X where H: "x \<in> (\<Pi>\<^sub>E i\<in>UNIV. X i)"
+                           "\<And>i. open (X i)"
+                           "finite {i. X i \<noteq> UNIV}"
+                           "(\<Pi>\<^sub>E i\<in>UNIV. X i) \<subseteq> U"
+      by auto
+    define I where "I = {i. X i \<noteq> UNIV}"
+    define Y where "Y = (\<lambda>i. if i \<in> I then (SOME y. y \<in> B i \<and> y \<subseteq> X i) else UNIV)"
+    have *: "\<exists>y. y \<in> B i \<and> y \<subseteq> X i" for i
+      unfolding B_def using A(3)[OF H(2)] H(1) by (metis PiE_E UNIV_I UnCI image_iff)
+    have **: "Y i \<in> B i \<and> Y i \<subseteq> X i" for i
+      apply (cases "i \<in> I")
+      unfolding Y_def using * that apply (auto)
+      apply (metis (no_types, lifting) someI, metis (no_types, lifting) someI_ex subset_iff)
+      unfolding B_def apply simp
+      unfolding I_def apply auto
+      done
+    have "{i. Y i \<noteq> UNIV} \<subseteq> I"
+      unfolding Y_def by auto
+    then have ***: "finite {i. Y i \<noteq> UNIV}"
+      unfolding I_def using H(3) rev_finite_subset by blast
+    have "(\<forall>i. Y i \<in> B i) \<and> finite {i. Y i \<noteq> UNIV}"
+      using ** *** by auto
+    then have "Pi\<^sub>E UNIV Y \<in> K"
+      unfolding K_def by auto
+
+    have "Y i \<subseteq> X i" for i
+      apply (cases "i \<in> I") using ** apply simp unfolding Y_def I_def by auto
+    then have "Pi\<^sub>E UNIV Y \<subseteq> Pi\<^sub>E UNIV X" by auto
+    then have "Pi\<^sub>E UNIV Y \<subseteq> U" using H(4) by auto
+    then show ?thesis using `Pi\<^sub>E UNIV Y \<in> K` by auto
+  qed
+
+  show "\<exists>L. (\<forall>(i::nat). x \<in> L i \<and> open (L i)) \<and> (\<forall>U. open U \<and> x \<in> U \<longrightarrow> (\<exists>i. L i \<subseteq> U))"
+    apply (rule first_countableI[of K])
+    using `countable K` `\<And>k. k \<in> K \<Longrightarrow> x \<in> k` `\<And>k. k \<in> K \<Longrightarrow> open k` Inc by auto
+qed
+
+lemma product_topology_countable_basis:
+  shows "\<exists>K::(('a::countable \<Rightarrow> 'b::second_countable_topology) set set).
+          topological_basis K \<and> countable K \<and>
+          (\<forall>k\<in>K. \<exists>X. (k = PiE UNIV X) \<and> (\<forall>i. open (X i)) \<and> finite {i. X i \<noteq> UNIV})"
+proof -
+  obtain B::"'b set set" where B: "countable B \<and> topological_basis B"
+    using ex_countable_basis by auto
+  then have "B \<noteq> {}" by (meson UNIV_I empty_iff open_UNIV topological_basisE)
+  define B2 where "B2 = B \<union> {UNIV}"
+  have "countable B2"
+    unfolding B2_def using B by auto
+  have "open U" if "U \<in> B2" for U
+    using that unfolding B2_def using B topological_basis_open by auto
+
+  define K where "K = {Pi\<^sub>E UNIV X | X. (\<forall>i::'a. X i \<in> B2) \<and> finite {i. X i \<noteq> UNIV}}"
+  have i: "\<forall>k\<in>K. \<exists>X. (k = PiE UNIV X) \<and> (\<forall>i. open (X i)) \<and> finite {i. X i \<noteq> UNIV}"
+    unfolding K_def using `\<And>U. U \<in> B2 \<Longrightarrow> open U` by auto
+
+  have "countable {X. (\<forall>(i::'a). X i \<in> B2) \<and> finite {i. X i \<noteq> UNIV}}"
+    apply (rule countable_product_event_const) using `countable B2` by auto
+  moreover have "K = (\<lambda>X. Pi\<^sub>E UNIV X)`{X. (\<forall>i. X i \<in> B2) \<and> finite {i. X i \<noteq> UNIV}}"
+    unfolding K_def by auto
+  ultimately have ii: "countable K" by auto
+
+  have iii: "topological_basis K"
+  proof (rule topological_basisI)
+    fix U and x::"'a\<Rightarrow>'b" assume "open U" "x \<in> U"
+    then have "openin (product_topology (\<lambda>i. euclidean) UNIV) U"
+      unfolding open_fun_def by auto
+    with product_topology_open_contains_basis[OF this `x \<in> U`]
+    have "\<exists>X. x \<in> (\<Pi>\<^sub>E i\<in>UNIV. X i) \<and> (\<forall>i. open (X i)) \<and> finite {i. X i \<noteq> UNIV} \<and> (\<Pi>\<^sub>E i\<in>UNIV. X i) \<subseteq> U"
+      unfolding topspace_euclidean open_openin by simp
+    then obtain X where H: "x \<in> (\<Pi>\<^sub>E i\<in>UNIV. X i)"
+                           "\<And>i. open (X i)"
+                           "finite {i. X i \<noteq> UNIV}"
+                           "(\<Pi>\<^sub>E i\<in>UNIV. X i) \<subseteq> U"
+      by auto
+    then have "x i \<in> X i" for i by auto
+    define I where "I = {i. X i \<noteq> UNIV}"
+    define Y where "Y = (\<lambda>i. if i \<in> I then (SOME y. y \<in> B2 \<and> y \<subseteq> X i \<and> x i \<in> y) else UNIV)"
+    have *: "\<exists>y. y \<in> B2 \<and> y \<subseteq> X i \<and> x i \<in> y" for i
+      unfolding B2_def using B `open (X i)` `x i \<in> X i` by (meson UnCI topological_basisE)
+    have **: "Y i \<in> B2 \<and> Y i \<subseteq> X i \<and> x i \<in> Y i" for i
+      using someI_ex[OF *]
+      apply (cases "i \<in> I")
+      unfolding Y_def using * apply (auto)
+      unfolding B2_def I_def by auto
+    have "{i. Y i \<noteq> UNIV} \<subseteq> I"
+      unfolding Y_def by auto
+    then have ***: "finite {i. Y i \<noteq> UNIV}"
+      unfolding I_def using H(3) rev_finite_subset by blast
+    have "(\<forall>i. Y i \<in> B2) \<and> finite {i. Y i \<noteq> UNIV}"
+      using ** *** by auto
+    then have "Pi\<^sub>E UNIV Y \<in> K"
+      unfolding K_def by auto
+
+    have "Y i \<subseteq> X i" for i
+      apply (cases "i \<in> I") using ** apply simp unfolding Y_def I_def by auto
+    then have "Pi\<^sub>E UNIV Y \<subseteq> Pi\<^sub>E UNIV X" by auto
+    then have "Pi\<^sub>E UNIV Y \<subseteq> U" using H(4) by auto
+
+    have "x \<in> Pi\<^sub>E UNIV Y"
+      using ** by auto
+
+    show "\<exists>V\<in>K. x \<in> V \<and> V \<subseteq> U"
+      using `Pi\<^sub>E UNIV Y \<in> K` `Pi\<^sub>E UNIV Y \<subseteq> U` `x \<in> Pi\<^sub>E UNIV Y` by auto
+  next
+    fix U assume "U \<in> K"
+    show "open U"
+      using `U \<in> K` unfolding open_fun_def K_def apply (auto)
+      apply (rule product_topology_basis)
+      using `\<And>V. V \<in> B2 \<Longrightarrow> open V` open_UNIV unfolding topspace_euclidean open_openin[symmetric]
+      by auto
+  qed
+
+  show ?thesis using i ii iii by auto
+qed
+
+instance "fun" :: (countable, second_countable_topology) second_countable_topology
+  apply standard
+  using product_topology_countable_basis topological_basis_imp_subbasis by auto
+
+
+subsection {*The strong operator topology on continuous linear operators*}
+
+text {*Let 'a and 'b be two normed real vector spaces. Then the space of linear continuous
+operators from 'a to 'b has a canonical norm, and therefore a canonical corresponding topology
+(the type classes instantiation are given in \verb+Bounded_Linear_Function.thy+).
+
+However, there is another topology on this space, the strong operator topology, where $T_n$ tends to
+$T$ iff, for all $x$ in 'a, then $T_n x$ tends to $T x$. This is precisely the product topology
+where the target space is endowed with the norm topology. It is especially useful when 'b is the set
+of real numbers, since then this topology is compact.
+
+We can not implement it using type classes as there is already a topology, but at least we
+can define it as a topology.
+
+Note that there is yet another (common and useful) topology on operator spaces, the weak operator
+topology, defined analogously using the product topology, but where the target space is given the
+weak-* topology, i.e., the pullback of the weak topology on the bidual of the space under the
+canonical embedding of a space into its bidual. We do not define it there, although it could also be
+defined analogously.
+*}
+
+definition strong_operator_topology::"('a::real_normed_vector \<Rightarrow>\<^sub>L'b::real_normed_vector) topology"
+where "strong_operator_topology = pullback_topology UNIV blinfun_apply euclidean"
+
+lemma strong_operator_topology_topspace:
+  "topspace strong_operator_topology = UNIV"
+unfolding strong_operator_topology_def topspace_pullback_topology topspace_euclidean by auto
+
+lemma strong_operator_topology_basis:
+  fixes f::"('a::real_normed_vector \<Rightarrow>\<^sub>L'b::real_normed_vector)" and U::"'i \<Rightarrow> 'b set" and x::"'i \<Rightarrow> 'a"
+  assumes "finite I" "\<And>i. i \<in> I \<Longrightarrow> open (U i)"
+  shows "openin strong_operator_topology {f. \<forall>i\<in>I. blinfun_apply f (x i) \<in> U i}"
+proof -
+  have "open {g::('a\<Rightarrow>'b). \<forall>i\<in>I. g (x i) \<in> U i}"
+    by (rule product_topology_basis'[OF assms])
+  moreover have "{f. \<forall>i\<in>I. blinfun_apply f (x i) \<in> U i}
+                = blinfun_apply-`{g::('a\<Rightarrow>'b). \<forall>i\<in>I. g (x i) \<in> U i} \<inter> UNIV"
+    by auto
+  ultimately show ?thesis
+    unfolding strong_operator_topology_def open_openin apply (subst openin_pullback_topology) by auto
+qed
+
+lemma strong_operator_topology_continuous_evaluation:
+  "continuous_on_topo strong_operator_topology euclidean (\<lambda>f. blinfun_apply f x)"
+proof -
+  have "continuous_on_topo strong_operator_topology euclidean ((\<lambda>f. f x) o blinfun_apply)"
+    unfolding strong_operator_topology_def apply (rule continuous_on_topo_pullback)
+    using continuous_on_topo_UNIV continuous_on_product_coordinates by fastforce
+  then show ?thesis unfolding comp_def by simp
+qed
+
+lemma continuous_on_strong_operator_topo_iff_coordinatewise:
+  "continuous_on_topo T strong_operator_topology f
+    \<longleftrightarrow> (\<forall>x. continuous_on_topo T euclidean (\<lambda>y. blinfun_apply (f y) x))"
+proof (auto)
+  fix x::"'b"
+  assume "continuous_on_topo T strong_operator_topology f"
+  with continuous_on_topo_compose[OF this strong_operator_topology_continuous_evaluation]
+  have "continuous_on_topo T euclidean ((\<lambda>z. blinfun_apply z x) o f)"
+    by simp
+  then show "continuous_on_topo T euclidean (\<lambda>y. blinfun_apply (f y) x)"
+    unfolding comp_def by auto
+next
+  assume *: "\<forall>x. continuous_on_topo T euclidean (\<lambda>y. blinfun_apply (f y) x)"
+  have "continuous_on_topo T euclidean (blinfun_apply o f)"
+    unfolding euclidean_product_topology
+    apply (rule continuous_on_topo_coordinatewise_then_product, auto)
+    using * unfolding comp_def by auto
+  show "continuous_on_topo T strong_operator_topology f"
+    unfolding strong_operator_topology_def
+    apply (rule continuous_on_topo_pullback')
+    by (auto simp add: `continuous_on_topo T euclidean (blinfun_apply o f)`)
+qed
+
+lemma strong_operator_topology_weaker_than_euclidean:
+  "continuous_on_topo euclidean strong_operator_topology (\<lambda>f. f)"
+by (subst continuous_on_strong_operator_topo_iff_coordinatewise,
+    auto simp add: continuous_on_topo_UNIV[symmetric] linear_continuous_on)
+
+
+subsection {*Metrics on product spaces*}
+
+
+text {*In general, the product topology is not metrizable, unless the index set is countable.
+When the index set is countable, essentially any (convergent) combination of the metrics on the
+factors will do. We use below the simplest one, based on $L^1$, but $L^2$ would also work,
+for instance.
+
+What is not completely trivial is that the distance thus defined induces the same topology
+as the product topology. This is what we have to prove to show that we have an instance
+of \verb+metric_space+.
+
+The proofs below would work verbatim for general countable products of metric spaces. However,
+since distances are only implemented in terms of type classes, we only develop the theory
+for countable products of the same space.*}
+
+instantiation "fun" :: (countable, metric_space) metric_space
+begin
+
+definition dist_fun_def:
+  "dist x y = (\<Sum>n. (1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+
+definition uniformity_fun_def:
+  "(uniformity::(('a \<Rightarrow> 'b) \<times> ('a \<Rightarrow> 'b)) filter) = (INF e:{0<..}. principal {(x, y). dist (x::('a\<Rightarrow>'b)) y < e})"
+
+text {*Except for the first one, the auxiliary lemmas below are only useful when proving the
+instance: once it is proved, they become trivial consequences of the general theory of metric
+spaces. It would thus be desirable to hide them once the instance is proved, but I do not know how
+to do this.*}
+
+lemma dist_fun_le_dist_first_terms:
+  "dist x y \<le> 2 * Max {dist (x (from_nat n)) (y (from_nat n))|n. n \<le> N} + (1/2)^N"
+proof -
+  have "(\<Sum>n. (1 / 2) ^ (n+Suc N) * min (dist (x (from_nat (n+Suc N))) (y (from_nat (n+Suc N)))) 1)
+          = (\<Sum>n. (1 / 2) ^ (Suc N) * ((1/2) ^ n * min (dist (x (from_nat (n+Suc N))) (y (from_nat (n+Suc N)))) 1))"
+    by (rule suminf_cong, simp add: power_add)
+  also have "... = (1/2)^(Suc N) * (\<Sum>n. (1 / 2) ^ n * min (dist (x (from_nat (n+Suc N))) (y (from_nat (n+Suc N)))) 1)"
+    apply (rule suminf_mult)
+    by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+  also have "... \<le> (1/2)^(Suc N) * (\<Sum>n. (1 / 2) ^ n)"
+    apply (simp, rule suminf_le, simp)
+    by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+  also have "... = (1/2)^(Suc N) * 2"
+    using suminf_geometric[of "1/2"] by auto
+  also have "... = (1/2)^N"
+    by auto
+  finally have *: "(\<Sum>n. (1 / 2) ^ (n+Suc N) * min (dist (x (from_nat (n+Suc N))) (y (from_nat (n+Suc N)))) 1) \<le> (1/2)^N"
+    by simp
+
+  define M where "M = Max {dist (x (from_nat n)) (y (from_nat n))|n. n \<le> N}"
+  have "dist (x (from_nat 0)) (y (from_nat 0)) \<le> M"
+    unfolding M_def by (rule Max_ge, auto)
+  then have [simp]: "M \<ge> 0" by (meson dual_order.trans zero_le_dist)
+  have "dist (x (from_nat n)) (y (from_nat n)) \<le> M" if "n\<le>N" for n
+    unfolding M_def apply (rule Max_ge) using that by auto
+  then have i: "min (dist (x (from_nat n)) (y (from_nat n))) 1 \<le> M" if "n\<le>N" for n
+    using that by force
+  have "(\<Sum>n< Suc N. (1 / 2) ^ n * min (dist (x (from_nat n)) (y (from_nat n))) 1) \<le>
+      (\<Sum>n< Suc N. M * (1 / 2) ^ n)"
+    by (rule sum_mono, simp add: i)
+  also have "... = M * (\<Sum>n<Suc N. (1 / 2) ^ n)"
+    by (rule sum_distrib_left[symmetric])
+  also have "... \<le> M * (\<Sum>n. (1 / 2) ^ n)"
+    by (rule mult_left_mono, rule sum_le_suminf, auto simp add: summable_geometric_iff)
+  also have "... = M * 2"
+    using suminf_geometric[of "1/2"] by auto
+  finally have **: "(\<Sum>n< Suc N. (1 / 2) ^ n * min (dist (x (from_nat n)) (y (from_nat n))) 1) \<le> 2 * M"
+    by simp
+
+  have "dist x y = (\<Sum>n. (1 / 2) ^ n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+    unfolding dist_fun_def by simp
+  also have "... = (\<Sum>n. (1 / 2) ^ (n+Suc N) * min (dist (x (from_nat (n+Suc N))) (y (from_nat (n+Suc N)))) 1)
+                  + (\<Sum>n<Suc N. (1 / 2) ^ n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+    apply (rule suminf_split_initial_segment)
+    by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+  also have "... \<le> 2 * M + (1/2)^N"
+    using * ** by auto
+  finally show ?thesis unfolding M_def by simp
+qed
+
+lemma open_fun_contains_ball_aux:
+  assumes "open (U::(('a \<Rightarrow> 'b) set))"
+          "x \<in> U"
+  shows "\<exists>e>0. {y. dist x y < e} \<subseteq> U"
+proof -
+  have *: "openin (product_topology (\<lambda>i. euclidean) UNIV) U"
+    using open_fun_def assms by auto
+  obtain X where H: "Pi\<^sub>E UNIV X \<subseteq> U"
+                    "\<And>i. openin euclidean (X i)"
+                    "finite {i. X i \<noteq> topspace euclidean}"
+                    "x \<in> Pi\<^sub>E UNIV X"
+    using product_topology_open_contains_basis[OF * `x \<in> U`] by auto
+  define I where "I = {i. X i \<noteq> topspace euclidean}"
+  have "finite I" unfolding I_def using H(3) by auto
+  {
+    fix i
+    have "x i \<in> X i" using `x \<in> U` H by auto
+    then have "\<exists>e. e>0 \<and> ball (x i) e \<subseteq> X i"
+      using `openin euclidean (X i)` open_openin open_contains_ball by blast
+    then obtain e where "e>0" "ball (x i) e \<subseteq> X i" by blast
+    define f where "f = min e (1/2)"
+    have "f>0" "f<1" unfolding f_def using `e>0` by auto
+    moreover have "ball (x i) f \<subseteq> X i" unfolding f_def using `ball (x i) e \<subseteq> X i` by auto
+    ultimately have "\<exists>f. f > 0 \<and> f < 1 \<and> ball (x i) f \<subseteq> X i" by auto
+  } note * = this
+  have "\<exists>e. \<forall>i. e i > 0 \<and> e i < 1 \<and> ball (x i) (e i) \<subseteq> X i"
+    by (rule choice, auto simp add: *)
+  then obtain e where "\<And>i. e i > 0" "\<And>i. e i < 1" "\<And>i. ball (x i) (e i) \<subseteq> X i"
+    by blast
+  define m where "m = Min {(1/2)^(to_nat i) * e i|i. i \<in> I}"
+  have "m > 0" if "I\<noteq>{}"
+    unfolding m_def apply (rule Min_grI) using `finite I` `I \<noteq> {}` `\<And>i. e i > 0` by auto
+  moreover have "{y. dist x y < m} \<subseteq> U"
+  proof (auto)
+    fix y assume "dist x y < m"
+    have "y i \<in> X i" if "i \<in> I" for i
+    proof -
+      have *: "summable (\<lambda>n. (1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+        by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+      define n where "n = to_nat i"
+      have "(1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1 < m"
+        using `dist x y < m` unfolding dist_fun_def using sum_le_suminf[OF *, of "{n}"] by auto
+      then have "(1/2)^(to_nat i) * min (dist (x i) (y i)) 1 < m"
+        using `n = to_nat i` by auto
+      also have "... \<le> (1/2)^(to_nat i) * e i"
+        unfolding m_def apply (rule Min_le) using `finite I` `i \<in> I` by auto
+      ultimately have "min (dist (x i) (y i)) 1 < e i"
+        by (auto simp add: divide_simps)
+      then have "dist (x i) (y i) < e i"
+        using `e i < 1` by auto
+      then show "y i \<in> X i" using `ball (x i) (e i) \<subseteq> X i` by auto
+    qed
+    then have "y \<in> Pi\<^sub>E UNIV X" using H(1) unfolding I_def topspace_euclidean by (auto simp add: PiE_iff)
+    then show "y \<in> U" using `Pi\<^sub>E UNIV X \<subseteq> U` by auto
+  qed
+  ultimately have *: "\<exists>m>0. {y. dist x y < m} \<subseteq> U" if "I \<noteq> {}" using that by auto
+
+  have "U = UNIV" if "I = {}"
+    using that H(1) unfolding I_def topspace_euclidean by (auto simp add: PiE_iff)
+  then have "\<exists>m>0. {y. dist x y < m} \<subseteq> U" if "I = {}" using that zero_less_one by blast
+  then show "\<exists>m>0. {y. dist x y < m} \<subseteq> U" using * by blast
+qed
+
+lemma ball_fun_contains_open_aux:
+  fixes x::"('a \<Rightarrow> 'b)" and e::real
+  assumes "e>0"
+  shows "\<exists>U. open U \<and> x \<in> U \<and> U \<subseteq> {y. dist x y < e}"
+proof -
+  have "\<exists>N::nat. 2^N > 8/e"
+    by (simp add: real_arch_pow)
+  then obtain N::nat where "2^N > 8/e" by auto
+  define f where "f = e/4"
+  have [simp]: "e>0" "f > 0" unfolding f_def using assms by auto
+  define X::"('a \<Rightarrow> 'b set)" where "X = (\<lambda>i. if (\<exists>n\<le>N. i = from_nat n) then {z. dist (x i) z < f} else UNIV)"
+  have "{i. X i \<noteq> UNIV} \<subseteq> from_nat`{0..N}"
+    unfolding X_def by auto
+  then have "finite {i. X i \<noteq> topspace euclidean}"
+    unfolding topspace_euclidean using finite_surj by blast
+  have "\<And>i. open (X i)"
+    unfolding X_def using metric_space_class.open_ball open_UNIV by auto
+  then have "\<And>i. openin euclidean (X i)"
+    using open_openin by auto
+  define U where "U = Pi\<^sub>E UNIV X"
+  have "open U"
+    unfolding open_fun_def product_topology_def apply (rule topology_generated_by_Basis)
+    unfolding U_def using `\<And>i. openin euclidean (X i)` `finite {i. X i \<noteq> topspace euclidean}`
+    by auto
+  moreover have "x \<in> U"
+    unfolding U_def X_def by (auto simp add: PiE_iff)
+  moreover have "dist x y < e" if "y \<in> U" for y
+  proof -
+    have *: "dist (x (from_nat n)) (y (from_nat n)) \<le> f" if "n \<le> N" for n
+      using `y \<in> U` unfolding U_def apply (auto simp add: PiE_iff)
+      unfolding X_def using that by (metis less_imp_le mem_Collect_eq)
+    have **: "Max {dist (x (from_nat n)) (y (from_nat n))|n. n \<le> N} \<le> f"
+      apply (rule Max.boundedI) using * by auto
+
+    have "dist x y \<le> 2 * Max {dist (x (from_nat n)) (y (from_nat n))|n. n \<le> N} + (1/2)^N"
+      by (rule dist_fun_le_dist_first_terms)
+    also have "... \<le> 2 * f + e / 8"
+      apply (rule add_mono) using ** `2^N > 8/e` by(auto simp add: algebra_simps divide_simps)
+    also have "... \<le> e/2 + e/8"
+      unfolding f_def by auto
+    also have "... < e"
+      by auto
+    finally show "dist x y < e" by simp
+  qed
+  ultimately show ?thesis by auto
+qed
+
+lemma fun_open_ball_aux:
+  fixes U::"('a \<Rightarrow> 'b) set"
+  shows "open U \<longleftrightarrow> (\<forall>x\<in>U. \<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> y \<in> U)"
+proof (auto)
+  assume "open U"
+  fix x assume "x \<in> U"
+  then show "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> y \<in> U"
+    using open_fun_contains_ball_aux[OF `open U` `x \<in> U`] by auto
+next
+  assume H: "\<forall>x\<in>U. \<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> y \<in> U"
+  define K where "K = {V. open V \<and> V \<subseteq> U}"
+  {
+    fix x assume "x \<in> U"
+    then obtain e where e: "e>0" "{y. dist x y < e} \<subseteq> U" using H by blast
+    then obtain V where V: "open V" "x \<in> V" "V \<subseteq> {y. dist x y < e}"
+      using ball_fun_contains_open_aux[OF `e>0`, of x] by auto
+    have "V \<in> K"
+      unfolding K_def using e(2) V(1) V(3) by auto
+    then have "x \<in> (\<Union>K)" using `x \<in> V` by auto
+  }
+  then have "(\<Union>K) = U"
+    unfolding K_def by auto
+  moreover have "open (\<Union>K)"
+    unfolding K_def by auto
+  ultimately show "open U" by simp
+qed
+
+instance proof
+  fix x y::"'a \<Rightarrow> 'b" show "(dist x y = 0) = (x = y)"
+  proof
+    assume "x = y"
+    then show "dist x y = 0" unfolding dist_fun_def using `x = y` by auto
+  next
+    assume "dist x y = 0"
+    have *: "summable (\<lambda>n. (1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+      by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+    have "(1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1 = 0" for n
+      using `dist x y = 0` unfolding dist_fun_def by (simp add: "*" suminf_eq_zero_iff)
+    then have "dist (x (from_nat n)) (y (from_nat n)) = 0" for n
+      by (metis div_0 min_def nonzero_mult_div_cancel_left power_eq_0_iff
+                zero_eq_1_divide_iff zero_neq_numeral)
+    then have "x (from_nat n) = y (from_nat n)" for n
+      by auto
+    then have "x i = y i" for i
+      by (metis from_nat_to_nat)
+    then show "x = y"
+      by auto
+  qed
+next
+  text{*The proof of the triangular inequality is trivial, modulo the fact that we are dealing
+        with infinite series, hence we should justify the convergence at each step. In this
+        respect, the following simplification rule is extremely handy.*}
+  have [simp]: "summable (\<lambda>n. (1/2)^n * min (dist (u (from_nat n)) (v (from_nat n))) 1)" for u v::"'a \<Rightarrow> 'b"
+    by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+  fix x y z::"'a \<Rightarrow> 'b"
+  {
+    fix n
+    have *: "dist (x (from_nat n)) (y (from_nat n)) \<le>
+            dist (x (from_nat n)) (z (from_nat n)) + dist (y (from_nat n)) (z (from_nat n))"
+      by (simp add: dist_triangle2)
+    have "0 \<le> dist (y (from_nat n)) (z (from_nat n))"
+      using zero_le_dist by blast
+    moreover
+    {
+      assume "min (dist (y (from_nat n)) (z (from_nat n))) 1 \<noteq> dist (y (from_nat n)) (z (from_nat n))"
+      then have "1 \<le> min (dist (x (from_nat n)) (z (from_nat n))) 1 + min (dist (y (from_nat n)) (z (from_nat n))) 1"
+        by (metis (no_types) diff_le_eq diff_self min_def zero_le_dist zero_le_one)
+    }
+    ultimately have "min (dist (x (from_nat n)) (y (from_nat n))) 1 \<le>
+            min (dist (x (from_nat n)) (z (from_nat n))) 1 + min (dist (y (from_nat n)) (z (from_nat n))) 1"
+      using * by linarith
+  } note ineq = this
+  have "dist x y = (\<Sum>n. (1/2)^n * min (dist (x (from_nat n)) (y (from_nat n))) 1)"
+    unfolding dist_fun_def by simp
+  also have "... \<le> (\<Sum>n. (1/2)^n * min (dist (x (from_nat n)) (z (from_nat n))) 1
+                        + (1/2)^n * min (dist (y (from_nat n)) (z (from_nat n))) 1)"
+    apply (rule suminf_le)
+    using ineq apply (metis (no_types, hide_lams) add.right_neutral distrib_left
+      le_divide_eq_numeral1(1) mult_2_right mult_left_mono zero_le_one zero_le_power)
+    by (auto simp add: summable_add)
+  also have "... = (\<Sum>n. (1/2)^n * min (dist (x (from_nat n)) (z (from_nat n))) 1)
+                  + (\<Sum>n. (1/2)^n * min (dist (y (from_nat n)) (z (from_nat n))) 1)"
+    by (rule suminf_add[symmetric], auto)
+  also have "... = dist x z + dist y z"
+    unfolding dist_fun_def by simp
+  finally show "dist x y \<le> dist x z + dist y z"
+    by simp
+next
+  text{*Finally, we show that the topology generated by the distance and the product
+        topology coincide. This is essentially contained in Lemma \verb+fun_open_ball_aux+,
+        except that the condition to prove is expressed with filters. To deal with this,
+        we copy some mumbo jumbo from Lemma \verb+eventually_uniformity_metric+ in
+        \verb+Real_Vector_Spaces.thy+*}
+  fix U::"('a \<Rightarrow> 'b) set"
+  have "eventually P uniformity \<longleftrightarrow> (\<exists>e>0. \<forall>x (y::('a \<Rightarrow> 'b)). dist x y < e \<longrightarrow> P (x, y))" for P
+  unfolding uniformity_fun_def apply (subst eventually_INF_base)
+    by (auto simp: eventually_principal subset_eq intro: bexI[of _ "min _ _"])
+  then show "open U = (\<forall>x\<in>U. \<forall>\<^sub>F (x', y) in uniformity. x' = x \<longrightarrow> y \<in> U)"
+    unfolding fun_open_ball_aux by simp
+qed (simp add: uniformity_fun_def)
+
+end
+
+text {*Nice properties of spaces are preserved under countable products. In addition
+to first countability, second countability and metrizability, as we have seen above,
+completeness is also preserved, and therefore being Polish.*}
+
+instance "fun" :: (countable, complete_space) complete_space
+proof
+  fix u::"nat \<Rightarrow> ('a \<Rightarrow> 'b)" assume "Cauchy u"
+  have "Cauchy (\<lambda>n. u n i)" for i
+  unfolding cauchy_def proof (intro impI allI)
+    fix e assume "e>(0::real)"
+    obtain k where "i = from_nat k"
+      using from_nat_to_nat[of i] by metis
+    have "(1/2)^k * min e 1 > 0" using `e>0` by auto
+    then have "\<exists>N. \<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (u m) (u n) < (1/2)^k * min e 1"
+      using `Cauchy u` unfolding cauchy_def by blast
+    then obtain N::nat where C: "\<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (u m) (u n) < (1/2)^k * min e 1"
+      by blast
+    have "\<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (u m i) (u n i) < e"
+    proof (auto)
+      fix m n::nat assume "m \<ge> N" "n \<ge> N"
+      have "(1/2)^k * min (dist (u m i) (u n i)) 1
+              = sum (\<lambda>p. (1/2)^p * min (dist (u m (from_nat p)) (u n (from_nat p))) 1) {k}"
+        using `i = from_nat k` by auto
+      also have "... \<le> (\<Sum>p. (1/2)^p * min (dist (u m (from_nat p)) (u n (from_nat p))) 1)"
+        apply (rule sum_le_suminf)
+        by (rule summable_comparison_test'[of "\<lambda>n. (1/2)^n"], auto simp add: summable_geometric_iff)
+      also have "... = dist (u m) (u n)"
+        unfolding dist_fun_def by auto
+      also have "... < (1/2)^k * min e 1"
+        using C `m \<ge> N` `n \<ge> N` by auto
+      finally have "min (dist (u m i) (u n i)) 1 < min e 1"
+        by (auto simp add: algebra_simps divide_simps)
+      then show "dist (u m i) (u n i) < e" by auto
+    qed
+    then show "\<exists>N. \<forall>m n. N \<le> m \<and> N \<le> n \<longrightarrow> dist (u m i) (u n i) < e"
+      by blast
+  qed
+  then have "\<exists>x. (\<lambda>n. u n i) \<longlonglongrightarrow> x" for i
+    using Cauchy_convergent convergent_def by auto
+  then have "\<exists>x. \<forall>i. (\<lambda>n. u n i) \<longlonglongrightarrow> x i"
+    using choice by force
+  then obtain x where *: "\<And>i. (\<lambda>n. u n i) \<longlonglongrightarrow> x i" by blast
+  have "u \<longlonglongrightarrow> x"
+  proof (rule metric_LIMSEQ_I)
+    fix e assume [simp]: "e>(0::real)"
+    have i: "\<exists>K. \<forall>n\<ge>K. dist (u n i) (x i) < e/4" for i
+      by (rule metric_LIMSEQ_D, auto simp add: *)
+    have "\<exists>K. \<forall>i. \<forall>n\<ge>K i. dist (u n i) (x i) < e/4"
+      apply (rule choice) using i by auto
+    then obtain K where K: "\<And>i n. n \<ge> K i \<Longrightarrow> dist (u n i) (x i) < e/4"
+      by blast
+
+    have "\<exists>N::nat. 2^N > 4/e"
+      by (simp add: real_arch_pow)
+    then obtain N::nat where "2^N > 4/e" by auto
+    define L where "L = Max {K (from_nat n)|n. n \<le> N}"
+    have "dist (u k) x < e" if "k \<ge> L" for k
+    proof -
+      have *: "dist (u k (from_nat n)) (x (from_nat n)) \<le> e / 4" if "n \<le> N" for n
+      proof -
+        have "K (from_nat n) \<le> L"
+          unfolding L_def apply (rule Max_ge) using `n \<le> N` by auto
+        then have "k \<ge> K (from_nat n)" using `k \<ge> L` by auto
+        then show ?thesis using K less_imp_le by auto
+      qed
+      have **: "Max {dist (u k (from_nat n)) (x (from_nat n)) |n. n \<le> N} \<le> e/4"
+        apply (rule Max.boundedI) using * by auto
+      have "dist (u k) x \<le> 2 * Max {dist (u k (from_nat n)) (x (from_nat n)) |n. n \<le> N} + (1/2)^N"
+        using dist_fun_le_dist_first_terms by auto
+      also have "... \<le> 2 * e/4 + e/4"
+        apply (rule add_mono)
+        using ** `2^N > 4/e` less_imp_le by (auto simp add: algebra_simps divide_simps)
+      also have "... < e" by auto
+      finally show ?thesis by simp
+    qed
+    then show "\<exists>L. \<forall>k\<ge>L. dist (u k) x < e" by blast
+  qed
+  then show "convergent u" using convergent_def by blast
+qed
+
+instance "fun" :: (countable, polish_space) polish_space
+by standard
+
+
+subsection {*Measurability*}
+
+text {*There are two natural sigma-algebras on a product space: the borel sigma algebra,
+generated by open sets in the product, and the product sigma algebra, countably generated by
+products of measurable sets along finitely many coordinates. The second one is defined and studied
+in \verb+Finite_Product_Measure.thy+.
+
+These sigma-algebra share a lot of natural properties (measurability of coordinates, for instance),
+but there is a fundamental difference: open sets are generated by arbitrary unions, not only
+countable ones, so typically many open sets will not be measurable with respect to the product sigma
+algebra (while all sets in the product sigma algebra are borel). The two sigma algebras coincide
+only when everything is countable (i.e., the product is countable, and the borel sigma algebra in
+the factor is countably generated).
+
+In this paragraph, we develop basic measurability properties for the borel sigma algebra, and
+compare it with the product sigma algebra as explained above.
+*}
+
+lemma measurable_product_coordinates [measurable (raw)]:
+  "(\<lambda>x. x i) \<in> measurable borel borel"
+by (rule borel_measurable_continuous_on1[OF continuous_on_product_coordinates])
+
+lemma measurable_product_then_coordinatewise:
+  fixes f::"'a \<Rightarrow> 'b \<Rightarrow> ('c::topological_space)"
+  assumes [measurable]: "f \<in> borel_measurable M"
+  shows "(\<lambda>x. f x i) \<in> borel_measurable M"
+proof -
+  have "(\<lambda>x. f x i) = (\<lambda>y. y i) o f"
+    unfolding comp_def by auto
+  then show ?thesis by simp
+qed
+
+text {*To compare the Borel sigma algebra with the product sigma algebra, we give a presentation
+of the product sigma algebra that is more similar to the one we used above for the product
+topology.*}
+
+lemma sets_PiM_finite:
+  "sets (Pi\<^sub>M I M) = sigma_sets (\<Pi>\<^sub>E i\<in>I. space (M i))
+        {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. X i \<in> sets (M i)) \<and> finite {i. X i \<noteq> space (M i)}}"
+proof
+  have "{(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. X i \<in> sets (M i)) \<and> finite {i. X i \<noteq> space (M i)}} \<subseteq> sets (Pi\<^sub>M I M)"
+  proof (auto)
+    fix X assume H: "\<forall>i. X i \<in> sets (M i)" "finite {i. X i \<noteq> space (M i)}"
+    then have *: "X i \<in> sets (M i)" for i by simp
+    define J where "J = {i \<in> I. X i \<noteq> space (M i)}"
+    have "finite J" "J \<subseteq> I" unfolding J_def using H by auto
+    define Y where "Y = (\<Pi>\<^sub>E j\<in>J. X j)"
+    have "prod_emb I M J Y \<in> sets (Pi\<^sub>M I M)"
+      unfolding Y_def apply (rule sets_PiM_I) using `finite J` `J \<subseteq> I` * by auto
+    moreover have "prod_emb I M J Y = (\<Pi>\<^sub>E i\<in>I. X i)"
+      unfolding prod_emb_def Y_def J_def using H sets.sets_into_space[OF *]
+      by (auto simp add: PiE_iff, blast)
+    ultimately show "Pi\<^sub>E I X \<in> sets (Pi\<^sub>M I M)" by simp
+  qed
+  then show "sigma_sets (\<Pi>\<^sub>E i\<in>I. space (M i)) {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. X i \<in> sets (M i)) \<and> finite {i. X i \<noteq> space (M i)}}
+              \<subseteq> sets (Pi\<^sub>M I M)"
+    by (metis (mono_tags, lifting) sets.sigma_sets_subset' sets.top space_PiM)
+
+  have *: "\<exists>X. {f. (\<forall>i\<in>I. f i \<in> space (M i)) \<and> f \<in> extensional I \<and> f i \<in> A} = Pi\<^sub>E I X \<and>
+                (\<forall>i. X i \<in> sets (M i)) \<and> finite {i. X i \<noteq> space (M i)}"
+    if "i \<in> I" "A \<in> sets (M i)" for i A
+  proof -
+    define X where "X = (\<lambda>j. if j = i then A else space (M j))"
+    have "{f. (\<forall>i\<in>I. f i \<in> space (M i)) \<and> f \<in> extensional I \<and> f i \<in> A} = Pi\<^sub>E I X"
+      unfolding X_def using sets.sets_into_space[OF `A \<in> sets (M i)`] `i \<in> I`
+      by (auto simp add: PiE_iff extensional_def, metis subsetCE, metis)
+    moreover have "X j \<in> sets (M j)" for j
+      unfolding X_def using `A \<in> sets (M i)` by auto
+    moreover have "finite {j. X j \<noteq> space (M j)}"
+      unfolding X_def by simp
+    ultimately show ?thesis by auto
+  qed
+  show "sets (Pi\<^sub>M I M) \<subseteq> sigma_sets (\<Pi>\<^sub>E i\<in>I. space (M i)) {(\<Pi>\<^sub>E i\<in>I. X i) |X. (\<forall>i. X i \<in> sets (M i)) \<and> finite {i. X i \<noteq> space (M i)}}"
+    unfolding sets_PiM_single
+    apply (rule sigma_sets_mono')
+    apply (auto simp add: PiE_iff *)
+    done
+qed
+
+lemma sets_PiM_subset_borel:
+  "sets (Pi\<^sub>M UNIV (\<lambda>_. borel)) \<subseteq> sets borel"
+proof -
+  have *: "Pi\<^sub>E UNIV X \<in> sets borel" if [measurable]: "\<And>i. X i \<in> sets borel" "finite {i. X i \<noteq> UNIV}" for X::"'a \<Rightarrow> 'b set"
+  proof -
+    define I where "I = {i. X i \<noteq> UNIV}"
+    have "finite I" unfolding I_def using that by simp
+    have "Pi\<^sub>E UNIV X = (\<Inter>i\<in>I. (\<lambda>x. x i)-`(X i) \<inter> space borel) \<inter> space borel"
+      unfolding I_def by auto
+    also have "... \<in> sets borel"
+      using that `finite I` by measurable
+    finally show ?thesis by simp
+  qed
+  then have "{(\<Pi>\<^sub>E i\<in>UNIV. X i) |X::('a \<Rightarrow> 'b set). (\<forall>i. X i \<in> sets borel) \<and> finite {i. X i \<noteq> space borel}} \<subseteq> sets borel"
+    by auto
+  then show ?thesis unfolding sets_PiM_finite space_borel
+    by (simp add: * sets.sigma_sets_subset')
+qed
+
+lemma sets_PiM_equal_borel:
+  "sets (Pi\<^sub>M UNIV (\<lambda>i::('a::countable). borel::('b::second_countable_topology measure))) = sets borel"
+proof
+  obtain K::"('a \<Rightarrow> 'b) set set" where K: "topological_basis K" "countable K"
+            "\<And>k. k \<in> K \<Longrightarrow> \<exists>X. (k = PiE UNIV X) \<and> (\<forall>i. open (X i)) \<and> finite {i. X i \<noteq> UNIV}"
+    using product_topology_countable_basis by fast
+  have *: "k \<in> sets (Pi\<^sub>M UNIV (\<lambda>_. borel))" if "k \<in> K" for k
+  proof -
+    obtain X where H: "k = PiE UNIV X" "\<And>i. open (X i)" "finite {i. X i \<noteq> UNIV}"
+      using K(3)[OF `k \<in> K`] by blast
+    show ?thesis unfolding H(1) sets_PiM_finite space_borel using borel_open[OF H(2)] H(3) by auto
+  qed
+  have **: "U \<in> sets (Pi\<^sub>M UNIV (\<lambda>_. borel))" if "open U" for U::"('a \<Rightarrow> 'b) set"
+  proof -
+    obtain B where "B \<subseteq> K" "U = (\<Union>B)"
+      using `open U` `topological_basis K` by (metis topological_basis_def)
+    have "countable B" using `B \<subseteq> K` `countable K` countable_subset by blast
+    moreover have "k \<in> sets (Pi\<^sub>M UNIV (\<lambda>_. borel))" if "k \<in> B" for k
+      using `B \<subseteq> K` * that by auto
+    ultimately show ?thesis unfolding `U = (\<Union>B)` by auto
+  qed
+  have "sigma_sets UNIV (Collect open) \<subseteq> sets (Pi\<^sub>M UNIV (\<lambda>i::'a. (borel::('b measure))))"
+    apply (rule sets.sigma_sets_subset') using ** by auto
+  then show "sets (borel::('a \<Rightarrow> 'b) measure) \<subseteq> sets (Pi\<^sub>M UNIV (\<lambda>_. borel))"
+    unfolding borel_def by auto
+qed (simp add: sets_PiM_subset_borel)
+
+lemma measurable_coordinatewise_then_product:
+  fixes f::"'a \<Rightarrow> ('b::countable) \<Rightarrow> ('c::second_countable_topology)"
+  assumes [measurable]: "\<And>i. (\<lambda>x. f x i) \<in> borel_measurable M"
+  shows "f \<in> borel_measurable M"
+proof -
+  have "f \<in> measurable M (Pi\<^sub>M UNIV (\<lambda>_. borel))"
+    by (rule measurable_PiM_single', auto simp add: assms)
+  then show ?thesis using sets_PiM_equal_borel measurable_cong_sets by blast
+qed
+
+end
--- a/src/HOL/Analysis/FurtherTopology.thy	Tue Oct 18 16:04:44 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2355 +0,0 @@
-section \<open>Extending Continous Maps, Invariance of Domain, 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
-
-subsection\<open> Invariance of domain and corollaries\<close>
-
-lemma invariance_of_domain_ball:
-  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
-  assumes contf: "continuous_on (cball a r) f" and "0 < r"
-     and inj: "inj_on f (cball a r)"
-   shows "open(f ` ball a r)"
-proof (cases "DIM('a) = 1")
-  case True
-  obtain h::"'a\<Rightarrow>real" and k
-        where "linear h" "linear k" "h ` UNIV = UNIV" "k ` UNIV = UNIV"
-              "\<And>x. norm(h x) = norm x" "\<And>x. norm(k x) = norm x"
-              "\<And>x. k(h x) = x" "\<And>x. h(k x) = x"
-    apply (rule isomorphisms_UNIV_UNIV [where 'M='a and 'N=real])
-      using True
-       apply force
-      by (metis UNIV_I UNIV_eq_I imageI)
-    have cont: "continuous_on S h"  "continuous_on T k" for S T
-      by (simp_all add: \<open>linear h\<close> \<open>linear k\<close> linear_continuous_on linear_linear)
-    have "continuous_on (h ` cball a r) (h \<circ> f \<circ> k)"
-      apply (intro continuous_on_compose cont continuous_on_subset [OF contf])
-      apply (auto simp: \<open>\<And>x. k (h x) = x\<close>)
-      done
-    moreover have "is_interval (h ` cball a r)"
-      by (simp add: is_interval_connected_1 \<open>linear h\<close> linear_continuous_on linear_linear connected_continuous_image)
-    moreover have "inj_on (h \<circ> f \<circ> k) (h ` cball a r)"
-      using inj by (simp add: inj_on_def) (metis \<open>\<And>x. k (h x) = x\<close>)
-    ultimately have *: "\<And>T. \<lbrakk>open T; T \<subseteq> h ` cball a r\<rbrakk> \<Longrightarrow> open ((h \<circ> f \<circ> k) ` T)"
-      using injective_eq_1d_open_map_UNIV by blast
-    have "open ((h \<circ> f \<circ> k) ` (h ` ball a r))"
-      by (rule *) (auto simp: \<open>linear h\<close> \<open>range h = UNIV\<close> open_surjective_linear_image)
-    then have "open ((h \<circ> f) ` ball a r)"
-      by (simp add: image_comp \<open>\<And>x. k (h x) = x\<close> cong: image_cong)
-    then show ?thesis
-      apply (simp add: image_comp [symmetric])
-      apply (metis open_bijective_linear_image_eq \<open>linear h\<close> \<open>\<And>x. k (h x) = x\<close> \<open>range h = UNIV\<close> bijI inj_on_def)
-      done
-next
-  case False
-  then have 2: "DIM('a) \<ge> 2"
-    by (metis DIM_ge_Suc0 One_nat_def Suc_1 antisym not_less_eq_eq)
-  have fimsub: "f ` ball a r \<subseteq> - f ` sphere a r"
-    using inj  by clarsimp (metis inj_onD less_eq_real_def mem_cball order_less_irrefl)
-  have hom: "f ` sphere a r homeomorphic sphere a r"
-    by (meson compact_sphere contf continuous_on_subset homeomorphic_compact homeomorphic_sym inj inj_on_subset sphere_cball)
-  then have nconn: "\<not> connected (- f ` sphere a r)"
-    by (rule Jordan_Brouwer_separation) (auto simp: \<open>0 < r\<close>)
-  obtain C where C: "C \<in> components (- f ` sphere a r)" and "bounded C"
-    apply (rule cobounded_has_bounded_component [OF _ nconn])
-      apply (simp_all add: 2)
-    by (meson compact_imp_bounded compact_continuous_image_eq compact_sphere contf inj sphere_cball)
-  moreover have "f ` (ball a r) = C"
-  proof
-    have "C \<noteq> {}"
-      by (rule in_components_nonempty [OF C])
-    show "C \<subseteq> f ` ball a r"
-    proof (rule ccontr)
-      assume nonsub: "\<not> C \<subseteq> f ` ball a r"
-      have "- f ` cball a r \<subseteq> C"
-      proof (rule components_maximal [OF C])
-        have "f ` cball a r homeomorphic cball a r"
-          using compact_cball contf homeomorphic_compact homeomorphic_sym inj by blast
-        then show "connected (- f ` cball a r)"
-          by (auto intro: connected_complement_homeomorphic_convex_compact 2)
-        show "- f ` cball a r \<subseteq> - f ` sphere a r"
-          by auto
-        then show "C \<inter> - f ` cball a r \<noteq> {}"
-          using \<open>C \<noteq> {}\<close> in_components_subset [OF C] nonsub
-          using image_iff by fastforce
-      qed
-      then have "bounded (- f ` cball a r)"
-        using bounded_subset \<open>bounded C\<close> by auto
-      then have "\<not> bounded (f ` cball a r)"
-        using cobounded_imp_unbounded by blast
-      then show "False"
-        using compact_continuous_image [OF contf] compact_cball compact_imp_bounded by blast
-    qed
-    with \<open>C \<noteq> {}\<close> have "C \<inter> f ` ball a r \<noteq> {}"
-      by (simp add: inf.absorb_iff1)
-    then show "f ` ball a r \<subseteq> C"
-      by (metis components_maximal [OF C _ fimsub] connected_continuous_image ball_subset_cball connected_ball contf continuous_on_subset)
-  qed
-  moreover have "open (- f ` sphere a r)"
-    using hom compact_eq_bounded_closed compact_sphere homeomorphic_compactness by blast
-  ultimately show ?thesis
-    using open_components by blast
-qed
-
-
-text\<open>Proved by L. E. J. Brouwer (1912)\<close>
-theorem invariance_of_domain:
-  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
-  assumes "continuous_on S f" "open S" "inj_on f S"
-    shows "open(f ` S)"
-  unfolding open_subopen [of "f`S"]
-proof clarify
-  fix a
-  assume "a \<in> S"
-  obtain \<delta> where "\<delta> > 0" and \<delta>: "cball a \<delta> \<subseteq> S"
-    using \<open>open S\<close> \<open>a \<in> S\<close> open_contains_cball_eq by blast
-  show "\<exists>T. open T \<and> f a \<in> T \<and> T \<subseteq> f ` S"
-  proof (intro exI conjI)
-    show "open (f ` (ball a \<delta>))"
-      by (meson \<delta> \<open>0 < \<delta>\<close> assms continuous_on_subset inj_on_subset invariance_of_domain_ball)
-    show "f a \<in> f ` ball a \<delta>"
-      by (simp add: \<open>0 < \<delta>\<close>)
-    show "f ` ball a \<delta> \<subseteq> f ` S"
-      using \<delta> ball_subset_cball by blast
-  qed
-qed
-
-lemma inv_of_domain_ss0:
-  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
-  assumes contf: "continuous_on U f" and injf: "inj_on f U" and fim: "f ` U \<subseteq> S"
-      and "subspace S" and dimS: "dim S = DIM('b::euclidean_space)"
-      and ope: "openin (subtopology euclidean S) U"
-    shows "openin (subtopology euclidean S) (f ` U)"
-proof -
-  have "U \<subseteq> S"
-    using ope openin_imp_subset by blast
-  have "(UNIV::'b set) homeomorphic S"
-    by (simp add: \<open>subspace S\<close> dimS dim_UNIV homeomorphic_subspaces)
-  then obtain h k where homhk: "homeomorphism (UNIV::'b set) S h k"
-    using homeomorphic_def by blast
-  have homkh: "homeomorphism S (k ` S) k h"
-    using homhk homeomorphism_image2 homeomorphism_sym by fastforce
-  have "open ((k \<circ> f \<circ> h) ` k ` U)"
-  proof (rule invariance_of_domain)
-    show "continuous_on (k ` U) (k \<circ> f \<circ> h)"
-    proof (intro continuous_intros)
-      show "continuous_on (k ` U) h"
-        by (meson continuous_on_subset [OF homeomorphism_cont1 [OF homhk]] top_greatest)
-      show "continuous_on (h ` k ` U) f"
-        apply (rule continuous_on_subset [OF contf], clarify)
-        apply (metis homhk homeomorphism_def ope openin_imp_subset rev_subsetD)
-        done
-      show "continuous_on (f ` h ` k ` U) k"
-        apply (rule continuous_on_subset [OF homeomorphism_cont2 [OF homhk]])
-        using fim homhk homeomorphism_apply2 ope openin_subset by fastforce
-    qed
-    have ope_iff: "\<And>T. open T \<longleftrightarrow> openin (subtopology euclidean (k ` S)) T"
-      using homhk homeomorphism_image2 open_openin by fastforce
-    show "open (k ` U)"
-      by (simp add: ope_iff homeomorphism_imp_open_map [OF homkh ope])
-    show "inj_on (k \<circ> f \<circ> h) (k ` U)"
-      apply (clarsimp simp: inj_on_def)
-      by (metis subsetD fim homeomorphism_apply2 [OF homhk] image_subset_iff inj_on_eq_iff injf \<open>U \<subseteq> S\<close>)
-  qed
-  moreover
-  have eq: "f ` U = h ` (k \<circ> f \<circ> h \<circ> k) ` U"
-    apply (auto simp: image_comp [symmetric])
-    apply (metis homkh \<open>U \<subseteq> S\<close> fim homeomorphism_image2 homeomorphism_of_subsets homhk imageI subset_UNIV)
-    by (metis \<open>U \<subseteq> S\<close> subsetD fim homeomorphism_def homhk image_eqI)
-  ultimately show ?thesis
-    by (metis (no_types, hide_lams) homeomorphism_imp_open_map homhk image_comp open_openin subtopology_UNIV)
-qed
-
-lemma inv_of_domain_ss1:
-  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
-  assumes contf: "continuous_on U f" and injf: "inj_on f U" and fim: "f ` U \<subseteq> S"
-      and "subspace S"
-      and ope: "openin (subtopology euclidean S) U"
-    shows "openin (subtopology euclidean S) (f ` U)"
-proof -
-  define S' where "S' \<equiv> {y. \<forall>x \<in> S. orthogonal x y}"
-  have "subspace S'"
-    by (simp add: S'_def subspace_orthogonal_to_vectors)
-  define g where "g \<equiv> \<lambda>z::'a*'a. ((f \<circ> fst)z, snd z)"
-  have "openin (subtopology euclidean (S \<times> S')) (g ` (U \<times> S'))"
-  proof (rule inv_of_domain_ss0)
-    show "continuous_on (U \<times> S') g"
-      apply (simp add: g_def)
-      apply (intro continuous_intros continuous_on_compose2 [OF contf continuous_on_fst], auto)
-      done
-    show "g ` (U \<times> S') \<subseteq> S \<times> S'"
-      using fim  by (auto simp: g_def)
-    show "inj_on g (U \<times> S')"
-      using injf by (auto simp: g_def inj_on_def)
-    show "subspace (S \<times> S')"
-      by (simp add: \<open>subspace S'\<close> \<open>subspace S\<close> subspace_Times)
-    show "openin (subtopology euclidean (S \<times> S')) (U \<times> S')"
-      by (simp add: openin_Times [OF ope])
-    have "dim (S \<times> S') = dim S + dim S'"
-      by (simp add: \<open>subspace S'\<close> \<open>subspace S\<close> dim_Times)
-    also have "... = DIM('a)"
-      using dim_subspace_orthogonal_to_vectors [OF \<open>subspace S\<close> subspace_UNIV]
-      by (simp add: add.commute S'_def)
-    finally show "dim (S \<times> S') = DIM('a)" .
-  qed
-  moreover have "g ` (U \<times> S') = f ` U \<times> S'"
-    by (auto simp: g_def image_iff)
-  moreover have "0 \<in> S'"
-    using \<open>subspace S'\<close> subspace_affine by blast
-  ultimately show ?thesis
-    by (auto simp: openin_Times_eq)
-qed
-
-
-corollary invariance_of_domain_subspaces:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes ope: "openin (subtopology euclidean U) S"
-      and "subspace U" "subspace V" and VU: "dim V \<le> dim U"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
-      and injf: "inj_on f S"
-    shows "openin (subtopology euclidean V) (f ` S)"
-proof -
-  obtain V' where "subspace V'" "V' \<subseteq> U" "dim V' = dim V"
-    using choose_subspace_of_subspace [OF VU]
-    by (metis span_eq \<open>subspace U\<close>)
-  then have "V homeomorphic V'"
-    by (simp add: \<open>subspace V\<close> homeomorphic_subspaces)
-  then obtain h k where homhk: "homeomorphism V V' h k"
-    using homeomorphic_def by blast
-  have eq: "f ` S = k ` (h \<circ> f) ` S"
-  proof -
-    have "k ` h ` f ` S = f ` S"
-      by (meson fim homeomorphism_def homeomorphism_of_subsets homhk subset_refl)
-    then show ?thesis
-      by (simp add: image_comp)
-  qed
-  show ?thesis
-    unfolding eq
-  proof (rule homeomorphism_imp_open_map)
-    show homkh: "homeomorphism V' V k h"
-      by (simp add: homeomorphism_symD homhk)
-    have hfV': "(h \<circ> f) ` S \<subseteq> V'"
-      using fim homeomorphism_image1 homhk by fastforce
-    moreover have "openin (subtopology euclidean U) ((h \<circ> f) ` S)"
-    proof (rule inv_of_domain_ss1)
-      show "continuous_on S (h \<circ> f)"
-        by (meson contf continuous_on_compose continuous_on_subset fim homeomorphism_cont1 homhk)
-      show "inj_on (h \<circ> f) S"
-        apply (clarsimp simp: inj_on_def)
-        by (metis fim homeomorphism_apply2 [OF homkh] image_subset_iff inj_onD injf)
-      show "(h \<circ> f) ` S \<subseteq> U"
-        using \<open>V' \<subseteq> U\<close> hfV' by auto
-      qed (auto simp: assms)
-    ultimately show "openin (subtopology euclidean V') ((h \<circ> f) ` S)"
-      using openin_subset_trans \<open>V' \<subseteq> U\<close> by force
-  qed
-qed
-
-corollary invariance_of_dimension_subspaces:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes ope: "openin (subtopology euclidean U) S"
-      and "subspace U" "subspace V"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
-      and injf: "inj_on f S" and "S \<noteq> {}"
-    shows "dim U \<le> dim V"
-proof -
-  have "False" if "dim V < dim U"
-  proof -
-    obtain T where "subspace T" "T \<subseteq> U" "dim T = dim V"
-      using choose_subspace_of_subspace [of "dim V" U]
-      by (metis span_eq \<open>subspace U\<close> \<open>dim V < dim U\<close> linear not_le)
-    then have "V homeomorphic T"
-      by (simp add: \<open>subspace V\<close> homeomorphic_subspaces)
-    then obtain h k where homhk: "homeomorphism V T h k"
-      using homeomorphic_def  by blast
-    have "continuous_on S (h \<circ> f)"
-      by (meson contf continuous_on_compose continuous_on_subset fim homeomorphism_cont1 homhk)
-    moreover have "(h \<circ> f) ` S \<subseteq> U"
-      using \<open>T \<subseteq> U\<close> fim homeomorphism_image1 homhk by fastforce
-    moreover have "inj_on (h \<circ> f) S"
-      apply (clarsimp simp: inj_on_def)
-      by (metis fim homeomorphism_apply1 homhk image_subset_iff inj_onD injf)
-    ultimately have ope_hf: "openin (subtopology euclidean U) ((h \<circ> f) ` S)"
-      using invariance_of_domain_subspaces [OF ope \<open>subspace U\<close> \<open>subspace U\<close>] by auto
-    have "(h \<circ> f) ` S \<subseteq> T"
-      using fim homeomorphism_image1 homhk by fastforce
-    then show ?thesis
-      by (metis dim_openin \<open>dim T = dim V\<close> ope_hf \<open>subspace U\<close> \<open>S \<noteq> {}\<close> dim_subset image_is_empty not_le that)
-  qed
-  then show ?thesis
-    using not_less by blast
-qed
-
-corollary invariance_of_domain_affine_sets:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes ope: "openin (subtopology euclidean U) S"
-      and aff: "affine U" "affine V" "aff_dim V \<le> aff_dim U"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
-      and injf: "inj_on f S"
-    shows "openin (subtopology euclidean V) (f ` S)"
-proof (cases "S = {}")
-  case True
-  then show ?thesis by auto
-next
-  case False
-  obtain a b where "a \<in> S" "a \<in> U" "b \<in> V"
-    using False fim ope openin_contains_cball by fastforce
-  have "openin (subtopology euclidean (op + (- b) ` V)) ((op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S)"
-  proof (rule invariance_of_domain_subspaces)
-    show "openin (subtopology euclidean (op + (- a) ` U)) (op + (- a) ` S)"
-      by (metis ope homeomorphism_imp_open_map homeomorphism_translation translation_galois)
-    show "subspace (op + (- a) ` U)"
-      by (simp add: \<open>a \<in> U\<close> affine_diffs_subspace \<open>affine U\<close>)
-    show "subspace (op + (- b) ` V)"
-      by (simp add: \<open>b \<in> V\<close> affine_diffs_subspace \<open>affine V\<close>)
-    show "dim (op + (- b) ` V) \<le> dim (op + (- a) ` U)"
-      by (metis \<open>a \<in> U\<close> \<open>b \<in> V\<close> aff_dim_eq_dim affine_hull_eq aff of_nat_le_iff)
-    show "continuous_on (op + (- a) ` S) (op + (- b) \<circ> f \<circ> op + a)"
-      by (metis contf continuous_on_compose homeomorphism_cont2 homeomorphism_translation translation_galois)
-    show "(op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S \<subseteq> op + (- b) ` V"
-      using fim by auto
-    show "inj_on (op + (- b) \<circ> f \<circ> op + a) (op + (- a) ` S)"
-      by (auto simp: inj_on_def) (meson inj_onD injf)
-  qed
-  then show ?thesis
-    by (metis (no_types, lifting) homeomorphism_imp_open_map homeomorphism_translation image_comp translation_galois)
-qed
-
-corollary invariance_of_dimension_affine_sets:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes ope: "openin (subtopology euclidean U) S"
-      and aff: "affine U" "affine V"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
-      and injf: "inj_on f S" and "S \<noteq> {}"
-    shows "aff_dim U \<le> aff_dim V"
-proof -
-  obtain a b where "a \<in> S" "a \<in> U" "b \<in> V"
-    using \<open>S \<noteq> {}\<close> fim ope openin_contains_cball by fastforce
-  have "dim (op + (- a) ` U) \<le> dim (op + (- b) ` V)"
-  proof (rule invariance_of_dimension_subspaces)
-    show "openin (subtopology euclidean (op + (- a) ` U)) (op + (- a) ` S)"
-      by (metis ope homeomorphism_imp_open_map homeomorphism_translation translation_galois)
-    show "subspace (op + (- a) ` U)"
-      by (simp add: \<open>a \<in> U\<close> affine_diffs_subspace \<open>affine U\<close>)
-    show "subspace (op + (- b) ` V)"
-      by (simp add: \<open>b \<in> V\<close> affine_diffs_subspace \<open>affine V\<close>)
-    show "continuous_on (op + (- a) ` S) (op + (- b) \<circ> f \<circ> op + a)"
-      by (metis contf continuous_on_compose homeomorphism_cont2 homeomorphism_translation translation_galois)
-    show "(op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S \<subseteq> op + (- b) ` V"
-      using fim by auto
-    show "inj_on (op + (- b) \<circ> f \<circ> op + a) (op + (- a) ` S)"
-      by (auto simp: inj_on_def) (meson inj_onD injf)
-  qed (use \<open>S \<noteq> {}\<close> in auto)
-  then show ?thesis
-    by (metis \<open>a \<in> U\<close> \<open>b \<in> V\<close> aff_dim_eq_dim affine_hull_eq aff of_nat_le_iff)
-qed
-
-corollary invariance_of_dimension:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes contf: "continuous_on S f" and "open S"
-      and injf: "inj_on f S" and "S \<noteq> {}"
-    shows "DIM('a) \<le> DIM('b)"
-  using invariance_of_dimension_subspaces [of UNIV S UNIV f] assms
-  by auto
-
-
-corollary continuous_injective_image_subspace_dim_le:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "subspace S" "subspace T"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> T"
-      and injf: "inj_on f S"
-    shows "dim S \<le> dim T"
-  apply (rule invariance_of_dimension_subspaces [of S S _ f])
-  using assms by (auto simp: subspace_affine)
-
-lemma invariance_of_dimension_convex_domain:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "convex S"
-      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> affine hull T"
-      and injf: "inj_on f S"
-    shows "aff_dim S \<le> aff_dim T"
-proof (cases "S = {}")
-  case True
-  then show ?thesis by (simp add: aff_dim_geq)
-next
-  case False
-  have "aff_dim (affine hull S) \<le> aff_dim (affine hull T)"
-  proof (rule invariance_of_dimension_affine_sets)
-    show "openin (subtopology euclidean (affine hull S)) (rel_interior S)"
-      by (simp add: openin_rel_interior)
-    show "continuous_on (rel_interior S) f"
-      using contf continuous_on_subset rel_interior_subset by blast
-    show "f ` rel_interior S \<subseteq> affine hull T"
-      using fim rel_interior_subset by blast
-    show "inj_on f (rel_interior S)"
-      using inj_on_subset injf rel_interior_subset by blast
-    show "rel_interior S \<noteq> {}"
-      by (simp add: False \<open>convex S\<close> rel_interior_eq_empty)
-  qed auto
-  then show ?thesis
-    by simp
-qed
-
-
-lemma homeomorphic_convex_sets_le:
-  assumes "convex S" "S homeomorphic T"
-  shows "aff_dim S \<le> aff_dim T"
-proof -
-  obtain h k where homhk: "homeomorphism S T h k"
-    using homeomorphic_def assms  by blast
-  show ?thesis
-  proof (rule invariance_of_dimension_convex_domain [OF \<open>convex S\<close>])
-    show "continuous_on S h"
-      using homeomorphism_def homhk by blast
-    show "h ` S \<subseteq> affine hull T"
-      by (metis homeomorphism_def homhk hull_subset)
-    show "inj_on h S"
-      by (meson homeomorphism_apply1 homhk inj_on_inverseI)
-  qed
-qed
-
-lemma homeomorphic_convex_sets:
-  assumes "convex S" "convex T" "S homeomorphic T"
-  shows "aff_dim S = aff_dim T"
-  by (meson assms dual_order.antisym homeomorphic_convex_sets_le homeomorphic_sym)
-
-lemma homeomorphic_convex_compact_sets_eq:
-  assumes "convex S" "compact S" "convex T" "compact T"
-  shows "S homeomorphic T \<longleftrightarrow> aff_dim S = aff_dim T"
-  by (meson assms homeomorphic_convex_compact_sets homeomorphic_convex_sets)
-
-lemma invariance_of_domain_gen:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "open S" "continuous_on S f" "inj_on f S" "DIM('b) \<le> DIM('a)"
-    shows "open(f ` S)"
-  using invariance_of_domain_subspaces [of UNIV S UNIV f] assms by auto
-
-lemma injective_into_1d_imp_open_map_UNIV:
-  fixes f :: "'a::euclidean_space \<Rightarrow> real"
-  assumes "open T" "continuous_on S f" "inj_on f S" "T \<subseteq> S"
-    shows "open (f ` T)"
-  apply (rule invariance_of_domain_gen [OF \<open>open T\<close>])
-  using assms apply (auto simp: elim: continuous_on_subset subset_inj_on)
-  done
-
-lemma continuous_on_inverse_open:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" and gf: "\<And>x. x \<in> S \<Longrightarrow> g(f x) = x"
-    shows "continuous_on (f ` S) g"
-proof (clarsimp simp add: continuous_openin_preimage_eq)
-  fix T :: "'a set"
-  assume "open T"
-  have eq: "{x. x \<in> f ` S \<and> g x \<in> T} = f ` (S \<inter> T)"
-    by (auto simp: gf)
-  show "openin (subtopology euclidean (f ` S)) {x \<in> f ` S. g x \<in> T}"
-    apply (subst eq)
-    apply (rule open_openin_trans)
-      apply (rule invariance_of_domain_gen)
-    using assms
-         apply auto
-    using inj_on_inverseI apply auto[1]
-    by (metis \<open>open T\<close> continuous_on_subset inj_onI inj_on_subset invariance_of_domain_gen openin_open openin_open_eq)
-qed
-
-lemma invariance_of_domain_homeomorphism:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" "inj_on f S"
-  obtains g where "homeomorphism S (f ` S) f g"
-proof
-  show "homeomorphism S (f ` S) f (inv_into S f)"
-    by (simp add: assms continuous_on_inverse_open homeomorphism_def)
-qed
-
-corollary invariance_of_domain_homeomorphic:
-  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
-  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" "inj_on f S"
-  shows "S homeomorphic (f ` S)"
-  using invariance_of_domain_homeomorphism [OF assms]
-  by (meson homeomorphic_def)
-
-end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Analysis/Further_Topology.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,3097 @@
+section \<open>Extending Continous Maps, Invariance of Domain, etc..\<close>
+
+text\<open>Ported from HOL Light (moretop.ml) by L C Paulson\<close>
+
+theory Further_Topology
+  imports Equivalence_Lebesgue_Henstock_Integration Weierstrass_Theorems Polytope Complex_Transcendental
+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
+
+subsection\<open> Invariance of domain and corollaries\<close>
+
+lemma invariance_of_domain_ball:
+  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
+  assumes contf: "continuous_on (cball a r) f" and "0 < r"
+     and inj: "inj_on f (cball a r)"
+   shows "open(f ` ball a r)"
+proof (cases "DIM('a) = 1")
+  case True
+  obtain h::"'a\<Rightarrow>real" and k
+        where "linear h" "linear k" "h ` UNIV = UNIV" "k ` UNIV = UNIV"
+              "\<And>x. norm(h x) = norm x" "\<And>x. norm(k x) = norm x"
+              "\<And>x. k(h x) = x" "\<And>x. h(k x) = x"
+    apply (rule isomorphisms_UNIV_UNIV [where 'M='a and 'N=real])
+      using True
+       apply force
+      by (metis UNIV_I UNIV_eq_I imageI)
+    have cont: "continuous_on S h"  "continuous_on T k" for S T
+      by (simp_all add: \<open>linear h\<close> \<open>linear k\<close> linear_continuous_on linear_linear)
+    have "continuous_on (h ` cball a r) (h \<circ> f \<circ> k)"
+      apply (intro continuous_on_compose cont continuous_on_subset [OF contf])
+      apply (auto simp: \<open>\<And>x. k (h x) = x\<close>)
+      done
+    moreover have "is_interval (h ` cball a r)"
+      by (simp add: is_interval_connected_1 \<open>linear h\<close> linear_continuous_on linear_linear connected_continuous_image)
+    moreover have "inj_on (h \<circ> f \<circ> k) (h ` cball a r)"
+      using inj by (simp add: inj_on_def) (metis \<open>\<And>x. k (h x) = x\<close>)
+    ultimately have *: "\<And>T. \<lbrakk>open T; T \<subseteq> h ` cball a r\<rbrakk> \<Longrightarrow> open ((h \<circ> f \<circ> k) ` T)"
+      using injective_eq_1d_open_map_UNIV by blast
+    have "open ((h \<circ> f \<circ> k) ` (h ` ball a r))"
+      by (rule *) (auto simp: \<open>linear h\<close> \<open>range h = UNIV\<close> open_surjective_linear_image)
+    then have "open ((h \<circ> f) ` ball a r)"
+      by (simp add: image_comp \<open>\<And>x. k (h x) = x\<close> cong: image_cong)
+    then show ?thesis
+      apply (simp add: image_comp [symmetric])
+      apply (metis open_bijective_linear_image_eq \<open>linear h\<close> \<open>\<And>x. k (h x) = x\<close> \<open>range h = UNIV\<close> bijI inj_on_def)
+      done
+next
+  case False
+  then have 2: "DIM('a) \<ge> 2"
+    by (metis DIM_ge_Suc0 One_nat_def Suc_1 antisym not_less_eq_eq)
+  have fimsub: "f ` ball a r \<subseteq> - f ` sphere a r"
+    using inj  by clarsimp (metis inj_onD less_eq_real_def mem_cball order_less_irrefl)
+  have hom: "f ` sphere a r homeomorphic sphere a r"
+    by (meson compact_sphere contf continuous_on_subset homeomorphic_compact homeomorphic_sym inj inj_on_subset sphere_cball)
+  then have nconn: "\<not> connected (- f ` sphere a r)"
+    by (rule Jordan_Brouwer_separation) (auto simp: \<open>0 < r\<close>)
+  obtain C where C: "C \<in> components (- f ` sphere a r)" and "bounded C"
+    apply (rule cobounded_has_bounded_component [OF _ nconn])
+      apply (simp_all add: 2)
+    by (meson compact_imp_bounded compact_continuous_image_eq compact_sphere contf inj sphere_cball)
+  moreover have "f ` (ball a r) = C"
+  proof
+    have "C \<noteq> {}"
+      by (rule in_components_nonempty [OF C])
+    show "C \<subseteq> f ` ball a r"
+    proof (rule ccontr)
+      assume nonsub: "\<not> C \<subseteq> f ` ball a r"
+      have "- f ` cball a r \<subseteq> C"
+      proof (rule components_maximal [OF C])
+        have "f ` cball a r homeomorphic cball a r"
+          using compact_cball contf homeomorphic_compact homeomorphic_sym inj by blast
+        then show "connected (- f ` cball a r)"
+          by (auto intro: connected_complement_homeomorphic_convex_compact 2)
+        show "- f ` cball a r \<subseteq> - f ` sphere a r"
+          by auto
+        then show "C \<inter> - f ` cball a r \<noteq> {}"
+          using \<open>C \<noteq> {}\<close> in_components_subset [OF C] nonsub
+          using image_iff by fastforce
+      qed
+      then have "bounded (- f ` cball a r)"
+        using bounded_subset \<open>bounded C\<close> by auto
+      then have "\<not> bounded (f ` cball a r)"
+        using cobounded_imp_unbounded by blast
+      then show "False"
+        using compact_continuous_image [OF contf] compact_cball compact_imp_bounded by blast
+    qed
+    with \<open>C \<noteq> {}\<close> have "C \<inter> f ` ball a r \<noteq> {}"
+      by (simp add: inf.absorb_iff1)
+    then show "f ` ball a r \<subseteq> C"
+      by (metis components_maximal [OF C _ fimsub] connected_continuous_image ball_subset_cball connected_ball contf continuous_on_subset)
+  qed
+  moreover have "open (- f ` sphere a r)"
+    using hom compact_eq_bounded_closed compact_sphere homeomorphic_compactness by blast
+  ultimately show ?thesis
+    using open_components by blast
+qed
+
+
+text\<open>Proved by L. E. J. Brouwer (1912)\<close>
+theorem invariance_of_domain:
+  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
+  assumes "continuous_on S f" "open S" "inj_on f S"
+    shows "open(f ` S)"
+  unfolding open_subopen [of "f`S"]
+proof clarify
+  fix a
+  assume "a \<in> S"
+  obtain \<delta> where "\<delta> > 0" and \<delta>: "cball a \<delta> \<subseteq> S"
+    using \<open>open S\<close> \<open>a \<in> S\<close> open_contains_cball_eq by blast
+  show "\<exists>T. open T \<and> f a \<in> T \<and> T \<subseteq> f ` S"
+  proof (intro exI conjI)
+    show "open (f ` (ball a \<delta>))"
+      by (meson \<delta> \<open>0 < \<delta>\<close> assms continuous_on_subset inj_on_subset invariance_of_domain_ball)
+    show "f a \<in> f ` ball a \<delta>"
+      by (simp add: \<open>0 < \<delta>\<close>)
+    show "f ` ball a \<delta> \<subseteq> f ` S"
+      using \<delta> ball_subset_cball by blast
+  qed
+qed
+
+lemma inv_of_domain_ss0:
+  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
+  assumes contf: "continuous_on U f" and injf: "inj_on f U" and fim: "f ` U \<subseteq> S"
+      and "subspace S" and dimS: "dim S = DIM('b::euclidean_space)"
+      and ope: "openin (subtopology euclidean S) U"
+    shows "openin (subtopology euclidean S) (f ` U)"
+proof -
+  have "U \<subseteq> S"
+    using ope openin_imp_subset by blast
+  have "(UNIV::'b set) homeomorphic S"
+    by (simp add: \<open>subspace S\<close> dimS dim_UNIV homeomorphic_subspaces)
+  then obtain h k where homhk: "homeomorphism (UNIV::'b set) S h k"
+    using homeomorphic_def by blast
+  have homkh: "homeomorphism S (k ` S) k h"
+    using homhk homeomorphism_image2 homeomorphism_sym by fastforce
+  have "open ((k \<circ> f \<circ> h) ` k ` U)"
+  proof (rule invariance_of_domain)
+    show "continuous_on (k ` U) (k \<circ> f \<circ> h)"
+    proof (intro continuous_intros)
+      show "continuous_on (k ` U) h"
+        by (meson continuous_on_subset [OF homeomorphism_cont1 [OF homhk]] top_greatest)
+      show "continuous_on (h ` k ` U) f"
+        apply (rule continuous_on_subset [OF contf], clarify)
+        apply (metis homhk homeomorphism_def ope openin_imp_subset rev_subsetD)
+        done
+      show "continuous_on (f ` h ` k ` U) k"
+        apply (rule continuous_on_subset [OF homeomorphism_cont2 [OF homhk]])
+        using fim homhk homeomorphism_apply2 ope openin_subset by fastforce
+    qed
+    have ope_iff: "\<And>T. open T \<longleftrightarrow> openin (subtopology euclidean (k ` S)) T"
+      using homhk homeomorphism_image2 open_openin by fastforce
+    show "open (k ` U)"
+      by (simp add: ope_iff homeomorphism_imp_open_map [OF homkh ope])
+    show "inj_on (k \<circ> f \<circ> h) (k ` U)"
+      apply (clarsimp simp: inj_on_def)
+      by (metis subsetD fim homeomorphism_apply2 [OF homhk] image_subset_iff inj_on_eq_iff injf \<open>U \<subseteq> S\<close>)
+  qed
+  moreover
+  have eq: "f ` U = h ` (k \<circ> f \<circ> h \<circ> k) ` U"
+    apply (auto simp: image_comp [symmetric])
+    apply (metis homkh \<open>U \<subseteq> S\<close> fim homeomorphism_image2 homeomorphism_of_subsets homhk imageI subset_UNIV)
+    by (metis \<open>U \<subseteq> S\<close> subsetD fim homeomorphism_def homhk image_eqI)
+  ultimately show ?thesis
+    by (metis (no_types, hide_lams) homeomorphism_imp_open_map homhk image_comp open_openin subtopology_UNIV)
+qed
+
+lemma inv_of_domain_ss1:
+  fixes f :: "'a \<Rightarrow> 'a::euclidean_space"
+  assumes contf: "continuous_on U f" and injf: "inj_on f U" and fim: "f ` U \<subseteq> S"
+      and "subspace S"
+      and ope: "openin (subtopology euclidean S) U"
+    shows "openin (subtopology euclidean S) (f ` U)"
+proof -
+  define S' where "S' \<equiv> {y. \<forall>x \<in> S. orthogonal x y}"
+  have "subspace S'"
+    by (simp add: S'_def subspace_orthogonal_to_vectors)
+  define g where "g \<equiv> \<lambda>z::'a*'a. ((f \<circ> fst)z, snd z)"
+  have "openin (subtopology euclidean (S \<times> S')) (g ` (U \<times> S'))"
+  proof (rule inv_of_domain_ss0)
+    show "continuous_on (U \<times> S') g"
+      apply (simp add: g_def)
+      apply (intro continuous_intros continuous_on_compose2 [OF contf continuous_on_fst], auto)
+      done
+    show "g ` (U \<times> S') \<subseteq> S \<times> S'"
+      using fim  by (auto simp: g_def)
+    show "inj_on g (U \<times> S')"
+      using injf by (auto simp: g_def inj_on_def)
+    show "subspace (S \<times> S')"
+      by (simp add: \<open>subspace S'\<close> \<open>subspace S\<close> subspace_Times)
+    show "openin (subtopology euclidean (S \<times> S')) (U \<times> S')"
+      by (simp add: openin_Times [OF ope])
+    have "dim (S \<times> S') = dim S + dim S'"
+      by (simp add: \<open>subspace S'\<close> \<open>subspace S\<close> dim_Times)
+    also have "... = DIM('a)"
+      using dim_subspace_orthogonal_to_vectors [OF \<open>subspace S\<close> subspace_UNIV]
+      by (simp add: add.commute S'_def)
+    finally show "dim (S \<times> S') = DIM('a)" .
+  qed
+  moreover have "g ` (U \<times> S') = f ` U \<times> S'"
+    by (auto simp: g_def image_iff)
+  moreover have "0 \<in> S'"
+    using \<open>subspace S'\<close> subspace_affine by blast
+  ultimately show ?thesis
+    by (auto simp: openin_Times_eq)
+qed
+
+
+corollary invariance_of_domain_subspaces:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes ope: "openin (subtopology euclidean U) S"
+      and "subspace U" "subspace V" and VU: "dim V \<le> dim U"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
+      and injf: "inj_on f S"
+    shows "openin (subtopology euclidean V) (f ` S)"
+proof -
+  obtain V' where "subspace V'" "V' \<subseteq> U" "dim V' = dim V"
+    using choose_subspace_of_subspace [OF VU]
+    by (metis span_eq \<open>subspace U\<close>)
+  then have "V homeomorphic V'"
+    by (simp add: \<open>subspace V\<close> homeomorphic_subspaces)
+  then obtain h k where homhk: "homeomorphism V V' h k"
+    using homeomorphic_def by blast
+  have eq: "f ` S = k ` (h \<circ> f) ` S"
+  proof -
+    have "k ` h ` f ` S = f ` S"
+      by (meson fim homeomorphism_def homeomorphism_of_subsets homhk subset_refl)
+    then show ?thesis
+      by (simp add: image_comp)
+  qed
+  show ?thesis
+    unfolding eq
+  proof (rule homeomorphism_imp_open_map)
+    show homkh: "homeomorphism V' V k h"
+      by (simp add: homeomorphism_symD homhk)
+    have hfV': "(h \<circ> f) ` S \<subseteq> V'"
+      using fim homeomorphism_image1 homhk by fastforce
+    moreover have "openin (subtopology euclidean U) ((h \<circ> f) ` S)"
+    proof (rule inv_of_domain_ss1)
+      show "continuous_on S (h \<circ> f)"
+        by (meson contf continuous_on_compose continuous_on_subset fim homeomorphism_cont1 homhk)
+      show "inj_on (h \<circ> f) S"
+        apply (clarsimp simp: inj_on_def)
+        by (metis fim homeomorphism_apply2 [OF homkh] image_subset_iff inj_onD injf)
+      show "(h \<circ> f) ` S \<subseteq> U"
+        using \<open>V' \<subseteq> U\<close> hfV' by auto
+      qed (auto simp: assms)
+    ultimately show "openin (subtopology euclidean V') ((h \<circ> f) ` S)"
+      using openin_subset_trans \<open>V' \<subseteq> U\<close> by force
+  qed
+qed
+
+corollary invariance_of_dimension_subspaces:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes ope: "openin (subtopology euclidean U) S"
+      and "subspace U" "subspace V"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
+      and injf: "inj_on f S" and "S \<noteq> {}"
+    shows "dim U \<le> dim V"
+proof -
+  have "False" if "dim V < dim U"
+  proof -
+    obtain T where "subspace T" "T \<subseteq> U" "dim T = dim V"
+      using choose_subspace_of_subspace [of "dim V" U]
+      by (metis span_eq \<open>subspace U\<close> \<open>dim V < dim U\<close> linear not_le)
+    then have "V homeomorphic T"
+      by (simp add: \<open>subspace V\<close> homeomorphic_subspaces)
+    then obtain h k where homhk: "homeomorphism V T h k"
+      using homeomorphic_def  by blast
+    have "continuous_on S (h \<circ> f)"
+      by (meson contf continuous_on_compose continuous_on_subset fim homeomorphism_cont1 homhk)
+    moreover have "(h \<circ> f) ` S \<subseteq> U"
+      using \<open>T \<subseteq> U\<close> fim homeomorphism_image1 homhk by fastforce
+    moreover have "inj_on (h \<circ> f) S"
+      apply (clarsimp simp: inj_on_def)
+      by (metis fim homeomorphism_apply1 homhk image_subset_iff inj_onD injf)
+    ultimately have ope_hf: "openin (subtopology euclidean U) ((h \<circ> f) ` S)"
+      using invariance_of_domain_subspaces [OF ope \<open>subspace U\<close> \<open>subspace U\<close>] by auto
+    have "(h \<circ> f) ` S \<subseteq> T"
+      using fim homeomorphism_image1 homhk by fastforce
+    then show ?thesis
+      by (metis dim_openin \<open>dim T = dim V\<close> ope_hf \<open>subspace U\<close> \<open>S \<noteq> {}\<close> dim_subset image_is_empty not_le that)
+  qed
+  then show ?thesis
+    using not_less by blast
+qed
+
+corollary invariance_of_domain_affine_sets:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes ope: "openin (subtopology euclidean U) S"
+      and aff: "affine U" "affine V" "aff_dim V \<le> aff_dim U"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
+      and injf: "inj_on f S"
+    shows "openin (subtopology euclidean V) (f ` S)"
+proof (cases "S = {}")
+  case True
+  then show ?thesis by auto
+next
+  case False
+  obtain a b where "a \<in> S" "a \<in> U" "b \<in> V"
+    using False fim ope openin_contains_cball by fastforce
+  have "openin (subtopology euclidean (op + (- b) ` V)) ((op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S)"
+  proof (rule invariance_of_domain_subspaces)
+    show "openin (subtopology euclidean (op + (- a) ` U)) (op + (- a) ` S)"
+      by (metis ope homeomorphism_imp_open_map homeomorphism_translation translation_galois)
+    show "subspace (op + (- a) ` U)"
+      by (simp add: \<open>a \<in> U\<close> affine_diffs_subspace \<open>affine U\<close>)
+    show "subspace (op + (- b) ` V)"
+      by (simp add: \<open>b \<in> V\<close> affine_diffs_subspace \<open>affine V\<close>)
+    show "dim (op + (- b) ` V) \<le> dim (op + (- a) ` U)"
+      by (metis \<open>a \<in> U\<close> \<open>b \<in> V\<close> aff_dim_eq_dim affine_hull_eq aff of_nat_le_iff)
+    show "continuous_on (op + (- a) ` S) (op + (- b) \<circ> f \<circ> op + a)"
+      by (metis contf continuous_on_compose homeomorphism_cont2 homeomorphism_translation translation_galois)
+    show "(op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S \<subseteq> op + (- b) ` V"
+      using fim by auto
+    show "inj_on (op + (- b) \<circ> f \<circ> op + a) (op + (- a) ` S)"
+      by (auto simp: inj_on_def) (meson inj_onD injf)
+  qed
+  then show ?thesis
+    by (metis (no_types, lifting) homeomorphism_imp_open_map homeomorphism_translation image_comp translation_galois)
+qed
+
+corollary invariance_of_dimension_affine_sets:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes ope: "openin (subtopology euclidean U) S"
+      and aff: "affine U" "affine V"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> V"
+      and injf: "inj_on f S" and "S \<noteq> {}"
+    shows "aff_dim U \<le> aff_dim V"
+proof -
+  obtain a b where "a \<in> S" "a \<in> U" "b \<in> V"
+    using \<open>S \<noteq> {}\<close> fim ope openin_contains_cball by fastforce
+  have "dim (op + (- a) ` U) \<le> dim (op + (- b) ` V)"
+  proof (rule invariance_of_dimension_subspaces)
+    show "openin (subtopology euclidean (op + (- a) ` U)) (op + (- a) ` S)"
+      by (metis ope homeomorphism_imp_open_map homeomorphism_translation translation_galois)
+    show "subspace (op + (- a) ` U)"
+      by (simp add: \<open>a \<in> U\<close> affine_diffs_subspace \<open>affine U\<close>)
+    show "subspace (op + (- b) ` V)"
+      by (simp add: \<open>b \<in> V\<close> affine_diffs_subspace \<open>affine V\<close>)
+    show "continuous_on (op + (- a) ` S) (op + (- b) \<circ> f \<circ> op + a)"
+      by (metis contf continuous_on_compose homeomorphism_cont2 homeomorphism_translation translation_galois)
+    show "(op + (- b) \<circ> f \<circ> op + a) ` op + (- a) ` S \<subseteq> op + (- b) ` V"
+      using fim by auto
+    show "inj_on (op + (- b) \<circ> f \<circ> op + a) (op + (- a) ` S)"
+      by (auto simp: inj_on_def) (meson inj_onD injf)
+  qed (use \<open>S \<noteq> {}\<close> in auto)
+  then show ?thesis
+    by (metis \<open>a \<in> U\<close> \<open>b \<in> V\<close> aff_dim_eq_dim affine_hull_eq aff of_nat_le_iff)
+qed
+
+corollary invariance_of_dimension:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes contf: "continuous_on S f" and "open S"
+      and injf: "inj_on f S" and "S \<noteq> {}"
+    shows "DIM('a) \<le> DIM('b)"
+  using invariance_of_dimension_subspaces [of UNIV S UNIV f] assms
+  by auto
+
+
+corollary continuous_injective_image_subspace_dim_le:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "subspace S" "subspace T"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> T"
+      and injf: "inj_on f S"
+    shows "dim S \<le> dim T"
+  apply (rule invariance_of_dimension_subspaces [of S S _ f])
+  using assms by (auto simp: subspace_affine)
+
+lemma invariance_of_dimension_convex_domain:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "convex S"
+      and contf: "continuous_on S f" and fim: "f ` S \<subseteq> affine hull T"
+      and injf: "inj_on f S"
+    shows "aff_dim S \<le> aff_dim T"
+proof (cases "S = {}")
+  case True
+  then show ?thesis by (simp add: aff_dim_geq)
+next
+  case False
+  have "aff_dim (affine hull S) \<le> aff_dim (affine hull T)"
+  proof (rule invariance_of_dimension_affine_sets)
+    show "openin (subtopology euclidean (affine hull S)) (rel_interior S)"
+      by (simp add: openin_rel_interior)
+    show "continuous_on (rel_interior S) f"
+      using contf continuous_on_subset rel_interior_subset by blast
+    show "f ` rel_interior S \<subseteq> affine hull T"
+      using fim rel_interior_subset by blast
+    show "inj_on f (rel_interior S)"
+      using inj_on_subset injf rel_interior_subset by blast
+    show "rel_interior S \<noteq> {}"
+      by (simp add: False \<open>convex S\<close> rel_interior_eq_empty)
+  qed auto
+  then show ?thesis
+    by simp
+qed
+
+
+lemma homeomorphic_convex_sets_le:
+  assumes "convex S" "S homeomorphic T"
+  shows "aff_dim S \<le> aff_dim T"
+proof -
+  obtain h k where homhk: "homeomorphism S T h k"
+    using homeomorphic_def assms  by blast
+  show ?thesis
+  proof (rule invariance_of_dimension_convex_domain [OF \<open>convex S\<close>])
+    show "continuous_on S h"
+      using homeomorphism_def homhk by blast
+    show "h ` S \<subseteq> affine hull T"
+      by (metis homeomorphism_def homhk hull_subset)
+    show "inj_on h S"
+      by (meson homeomorphism_apply1 homhk inj_on_inverseI)
+  qed
+qed
+
+lemma homeomorphic_convex_sets:
+  assumes "convex S" "convex T" "S homeomorphic T"
+  shows "aff_dim S = aff_dim T"
+  by (meson assms dual_order.antisym homeomorphic_convex_sets_le homeomorphic_sym)
+
+lemma homeomorphic_convex_compact_sets_eq:
+  assumes "convex S" "compact S" "convex T" "compact T"
+  shows "S homeomorphic T \<longleftrightarrow> aff_dim S = aff_dim T"
+  by (meson assms homeomorphic_convex_compact_sets homeomorphic_convex_sets)
+
+lemma invariance_of_domain_gen:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "open S" "continuous_on S f" "inj_on f S" "DIM('b) \<le> DIM('a)"
+    shows "open(f ` S)"
+  using invariance_of_domain_subspaces [of UNIV S UNIV f] assms by auto
+
+lemma injective_into_1d_imp_open_map_UNIV:
+  fixes f :: "'a::euclidean_space \<Rightarrow> real"
+  assumes "open T" "continuous_on S f" "inj_on f S" "T \<subseteq> S"
+    shows "open (f ` T)"
+  apply (rule invariance_of_domain_gen [OF \<open>open T\<close>])
+  using assms apply (auto simp: elim: continuous_on_subset subset_inj_on)
+  done
+
+lemma continuous_on_inverse_open:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" and gf: "\<And>x. x \<in> S \<Longrightarrow> g(f x) = x"
+    shows "continuous_on (f ` S) g"
+proof (clarsimp simp add: continuous_openin_preimage_eq)
+  fix T :: "'a set"
+  assume "open T"
+  have eq: "{x. x \<in> f ` S \<and> g x \<in> T} = f ` (S \<inter> T)"
+    by (auto simp: gf)
+  show "openin (subtopology euclidean (f ` S)) {x \<in> f ` S. g x \<in> T}"
+    apply (subst eq)
+    apply (rule open_openin_trans)
+      apply (rule invariance_of_domain_gen)
+    using assms
+         apply auto
+    using inj_on_inverseI apply auto[1]
+    by (metis \<open>open T\<close> continuous_on_subset inj_onI inj_on_subset invariance_of_domain_gen openin_open openin_open_eq)
+qed
+
+lemma invariance_of_domain_homeomorphism:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" "inj_on f S"
+  obtains g where "homeomorphism S (f ` S) f g"
+proof
+  show "homeomorphism S (f ` S) f (inv_into S f)"
+    by (simp add: assms continuous_on_inverse_open homeomorphism_def)
+qed
+
+corollary invariance_of_domain_homeomorphic:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "open S" "continuous_on S f" "DIM('b) \<le> DIM('a)" "inj_on f S"
+  shows "S homeomorphic (f ` S)"
+  using invariance_of_domain_homeomorphism [OF assms]
+  by (meson homeomorphic_def)
+
+lemma continuous_image_subset_interior:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes "continuous_on S f" "inj_on f S" "DIM('b) \<le> DIM('a)"
+  shows "f ` (interior S) \<subseteq> interior(f ` S)"
+  apply (rule interior_maximal)
+   apply (simp add: image_mono interior_subset)
+  apply (rule invariance_of_domain_gen)
+  using assms
+     apply (auto simp: subset_inj_on interior_subset continuous_on_subset)
+  done
+
+lemma homeomorphic_interiors_same_dimension:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" and dimeq: "DIM('a) = DIM('b)"
+  shows "(interior S) homeomorphic (interior T)"
+  using assms [unfolded homeomorphic_minimal]
+  unfolding homeomorphic_def
+proof (clarify elim!: ex_forward)
+  fix f g
+  assume S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+     and contf: "continuous_on S f" and contg: "continuous_on T g"
+  then have fST: "f ` S = T" and gTS: "g ` T = S" and "inj_on f S" "inj_on g T"
+    by (auto simp: inj_on_def intro: rev_image_eqI) metis+
+  have fim: "f ` interior S \<subseteq> interior T"
+    using continuous_image_subset_interior [OF contf \<open>inj_on f S\<close>] dimeq fST by simp
+  have gim: "g ` interior T \<subseteq> interior S"
+    using continuous_image_subset_interior [OF contg \<open>inj_on g T\<close>] dimeq gTS by simp
+  show "homeomorphism (interior S) (interior T) f g"
+    unfolding homeomorphism_def
+  proof (intro conjI ballI)
+    show "\<And>x. x \<in> interior S \<Longrightarrow> g (f x) = x"
+      by (meson \<open>\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x\<close> subsetD interior_subset)
+    have "interior T \<subseteq> f ` interior S"
+    proof
+      fix x assume "x \<in> interior T"
+      then have "g x \<in> interior S"
+        using gim by blast
+      then show "x \<in> f ` interior S"
+        by (metis T \<open>x \<in> interior T\<close> image_iff interior_subset subsetCE)
+    qed
+    then show "f ` interior S = interior T"
+      using fim by blast
+    show "continuous_on (interior S) f"
+      by (metis interior_subset continuous_on_subset contf)
+    show "\<And>y. y \<in> interior T \<Longrightarrow> f (g y) = y"
+      by (meson T subsetD interior_subset)
+    have "interior S \<subseteq> g ` interior T"
+    proof
+      fix x assume "x \<in> interior S"
+      then have "f x \<in> interior T"
+        using fim by blast
+      then show "x \<in> g ` interior T"
+        by (metis S \<open>x \<in> interior S\<close> image_iff interior_subset subsetCE)
+    qed
+    then show "g ` interior T = interior S"
+      using gim by blast
+    show "continuous_on (interior T) g"
+      by (metis interior_subset continuous_on_subset contg)
+  qed
+qed
+
+lemma homeomorphic_open_imp_same_dimension:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "open S" "S \<noteq> {}" "open T" "T \<noteq> {}"
+  shows "DIM('a) = DIM('b)"
+    using assms
+    apply (simp add: homeomorphic_minimal)
+    apply (rule order_antisym; metis inj_onI invariance_of_dimension)
+    done
+
+lemma homeomorphic_interiors:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "interior S = {} \<longleftrightarrow> interior T = {}"
+    shows "(interior S) homeomorphic (interior T)"
+proof (cases "interior T = {}")
+  case True
+  with assms show ?thesis by auto
+next
+  case False
+  then have "DIM('a) = DIM('b)"
+    using assms
+    apply (simp add: homeomorphic_minimal)
+    apply (rule order_antisym; metis continuous_on_subset inj_onI inj_on_subset interior_subset invariance_of_dimension open_interior)
+    done
+  then show ?thesis
+    by (rule homeomorphic_interiors_same_dimension [OF \<open>S homeomorphic T\<close>])
+qed
+
+lemma homeomorphic_frontiers_same_dimension:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "closed S" "closed T" and dimeq: "DIM('a) = DIM('b)"
+  shows "(frontier S) homeomorphic (frontier T)"
+  using assms [unfolded homeomorphic_minimal]
+  unfolding homeomorphic_def
+proof (clarify elim!: ex_forward)
+  fix f g
+  assume S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+     and contf: "continuous_on S f" and contg: "continuous_on T g"
+  then have fST: "f ` S = T" and gTS: "g ` T = S" and "inj_on f S" "inj_on g T"
+    by (auto simp: inj_on_def intro: rev_image_eqI) metis+
+  have "g ` interior T \<subseteq> interior S"
+    using continuous_image_subset_interior [OF contg \<open>inj_on g T\<close>] dimeq gTS by simp
+  then have fim: "f ` frontier S \<subseteq> frontier T"
+    apply (simp add: frontier_def)
+    using continuous_image_subset_interior assms(2) assms(3) S by auto
+  have "f ` interior S \<subseteq> interior T"
+    using continuous_image_subset_interior [OF contf \<open>inj_on f S\<close>] dimeq fST by simp
+  then have gim: "g ` frontier T \<subseteq> frontier S"
+    apply (simp add: frontier_def)
+    using continuous_image_subset_interior T assms(2) assms(3) by auto
+  show "homeomorphism (frontier S) (frontier T) f g"
+    unfolding homeomorphism_def
+  proof (intro conjI ballI)
+    show gf: "\<And>x. x \<in> frontier S \<Longrightarrow> g (f x) = x"
+      by (simp add: S assms(2) frontier_def)
+    show fg: "\<And>y. y \<in> frontier T \<Longrightarrow> f (g y) = y"
+      by (simp add: T assms(3) frontier_def)
+    have "frontier T \<subseteq> f ` frontier S"
+    proof
+      fix x assume "x \<in> frontier T"
+      then have "g x \<in> frontier S"
+        using gim by blast
+      then show "x \<in> f ` frontier S"
+        by (metis fg \<open>x \<in> frontier T\<close> imageI)
+    qed
+    then show "f ` frontier S = frontier T"
+      using fim by blast
+    show "continuous_on (frontier S) f"
+      by (metis Diff_subset assms(2) closure_eq contf continuous_on_subset frontier_def)
+    have "frontier S \<subseteq> g ` frontier T"
+    proof
+      fix x assume "x \<in> frontier S"
+      then have "f x \<in> frontier T"
+        using fim by blast
+      then show "x \<in> g ` frontier T"
+        by (metis gf \<open>x \<in> frontier S\<close> imageI)
+    qed
+    then show "g ` frontier T = frontier S"
+      using gim by blast
+    show "continuous_on (frontier T) g"
+      by (metis Diff_subset assms(3) closure_closed contg continuous_on_subset frontier_def)
+  qed
+qed
+
+lemma homeomorphic_frontiers:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "closed S" "closed T"
+          "interior S = {} \<longleftrightarrow> interior T = {}"
+    shows "(frontier S) homeomorphic (frontier T)"
+proof (cases "interior T = {}")
+  case True
+  then show ?thesis
+    by (metis Diff_empty assms closure_eq frontier_def)
+next
+  case False
+  show ?thesis
+    apply (rule homeomorphic_frontiers_same_dimension)
+       apply (simp_all add: assms)
+    using False assms homeomorphic_interiors homeomorphic_open_imp_same_dimension by blast
+qed
+
+lemma continuous_image_subset_rel_interior:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space"
+  assumes contf: "continuous_on S f" and injf: "inj_on f S" and fim: "f ` S \<subseteq> T"
+      and TS: "aff_dim T \<le> aff_dim S"
+  shows "f ` (rel_interior S) \<subseteq> rel_interior(f ` S)"
+proof (rule rel_interior_maximal)
+  show "f ` rel_interior S \<subseteq> f ` S"
+    by(simp add: image_mono rel_interior_subset)
+  show "openin (subtopology euclidean (affine hull f ` S)) (f ` rel_interior S)"
+  proof (rule invariance_of_domain_affine_sets)
+    show "openin (subtopology euclidean (affine hull S)) (rel_interior S)"
+      by (simp add: openin_rel_interior)
+    show "aff_dim (affine hull f ` S) \<le> aff_dim (affine hull S)"
+      by (metis aff_dim_affine_hull aff_dim_subset fim TS order_trans)
+    show "f ` rel_interior S \<subseteq> affine hull f ` S"
+      by (meson \<open>f ` rel_interior S \<subseteq> f ` S\<close> hull_subset order_trans)
+    show "continuous_on (rel_interior S) f"
+      using contf continuous_on_subset rel_interior_subset by blast
+    show "inj_on f (rel_interior S)"
+      using inj_on_subset injf rel_interior_subset by blast
+  qed auto
+qed
+
+lemma homeomorphic_rel_interiors_same_dimension:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" and aff: "aff_dim S = aff_dim T"
+  shows "(rel_interior S) homeomorphic (rel_interior T)"
+  using assms [unfolded homeomorphic_minimal]
+  unfolding homeomorphic_def
+proof (clarify elim!: ex_forward)
+  fix f g
+  assume S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+     and contf: "continuous_on S f" and contg: "continuous_on T g"
+  then have fST: "f ` S = T" and gTS: "g ` T = S" and "inj_on f S" "inj_on g T"
+    by (auto simp: inj_on_def intro: rev_image_eqI) metis+
+  have fim: "f ` rel_interior S \<subseteq> rel_interior T"
+    by (metis \<open>inj_on f S\<close> aff contf continuous_image_subset_rel_interior fST order_refl)
+  have gim: "g ` rel_interior T \<subseteq> rel_interior S"
+    by (metis \<open>inj_on g T\<close> aff contg continuous_image_subset_rel_interior gTS order_refl)
+  show "homeomorphism (rel_interior S) (rel_interior T) f g"
+    unfolding homeomorphism_def
+  proof (intro conjI ballI)
+    show gf: "\<And>x. x \<in> rel_interior S \<Longrightarrow> g (f x) = x"
+      using S rel_interior_subset by blast
+    show fg: "\<And>y. y \<in> rel_interior T \<Longrightarrow> f (g y) = y"
+      using T mem_rel_interior_ball by blast
+    have "rel_interior T \<subseteq> f ` rel_interior S"
+    proof
+      fix x assume "x \<in> rel_interior T"
+      then have "g x \<in> rel_interior S"
+        using gim by blast
+      then show "x \<in> f ` rel_interior S"
+        by (metis fg \<open>x \<in> rel_interior T\<close> imageI)
+    qed
+    moreover have "f ` rel_interior S \<subseteq> rel_interior T"
+      by (metis \<open>inj_on f S\<close> aff contf continuous_image_subset_rel_interior fST order_refl)
+    ultimately show "f ` rel_interior S = rel_interior T"
+      by blast
+    show "continuous_on (rel_interior S) f"
+      using contf continuous_on_subset rel_interior_subset by blast
+    have "rel_interior S \<subseteq> g ` rel_interior T"
+    proof
+      fix x assume "x \<in> rel_interior S"
+      then have "f x \<in> rel_interior T"
+        using fim by blast
+      then show "x \<in> g ` rel_interior T"
+        by (metis gf \<open>x \<in> rel_interior S\<close> imageI)
+    qed
+    then show "g ` rel_interior T = rel_interior S"
+      using gim by blast
+    show "continuous_on (rel_interior T) g"
+      using contg continuous_on_subset rel_interior_subset by blast
+  qed
+qed
+
+lemma homeomorphic_rel_interiors:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "rel_interior S = {} \<longleftrightarrow> rel_interior T = {}"
+    shows "(rel_interior S) homeomorphic (rel_interior T)"
+proof (cases "rel_interior T = {}")
+  case True
+  with assms show ?thesis by auto
+next
+  case False
+  obtain f g
+    where S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+      and contf: "continuous_on S f" and contg: "continuous_on T g"
+    using  assms [unfolded homeomorphic_minimal] by auto
+  have "aff_dim (affine hull S) \<le> aff_dim (affine hull T)"
+    apply (rule invariance_of_dimension_affine_sets [of _ "rel_interior S" _ f])
+          apply (simp_all add: openin_rel_interior False assms)
+    using contf continuous_on_subset rel_interior_subset apply blast
+      apply (meson S hull_subset image_subsetI rel_interior_subset rev_subsetD)
+    apply (metis S inj_on_inverseI inj_on_subset rel_interior_subset)
+    done
+  moreover have "aff_dim (affine hull T) \<le> aff_dim (affine hull S)"
+    apply (rule invariance_of_dimension_affine_sets [of _ "rel_interior T" _ g])
+          apply (simp_all add: openin_rel_interior False assms)
+    using contg continuous_on_subset rel_interior_subset apply blast
+      apply (meson T hull_subset image_subsetI rel_interior_subset rev_subsetD)
+    apply (metis T inj_on_inverseI inj_on_subset rel_interior_subset)
+    done
+  ultimately have "aff_dim S = aff_dim T" by force
+  then show ?thesis
+    by (rule homeomorphic_rel_interiors_same_dimension [OF \<open>S homeomorphic T\<close>])
+qed
+
+
+lemma homeomorphic_rel_boundaries_same_dimension:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" and aff: "aff_dim S = aff_dim T"
+  shows "(S - rel_interior S) homeomorphic (T - rel_interior T)"
+  using assms [unfolded homeomorphic_minimal]
+  unfolding homeomorphic_def
+proof (clarify elim!: ex_forward)
+  fix f g
+  assume S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+     and contf: "continuous_on S f" and contg: "continuous_on T g"
+  then have fST: "f ` S = T" and gTS: "g ` T = S" and "inj_on f S" "inj_on g T"
+    by (auto simp: inj_on_def intro: rev_image_eqI) metis+
+  have fim: "f ` rel_interior S \<subseteq> rel_interior T"
+    by (metis \<open>inj_on f S\<close> aff contf continuous_image_subset_rel_interior fST order_refl)
+  have gim: "g ` rel_interior T \<subseteq> rel_interior S"
+    by (metis \<open>inj_on g T\<close> aff contg continuous_image_subset_rel_interior gTS order_refl)
+  show "homeomorphism (S - rel_interior S) (T - rel_interior T) f g"
+    unfolding homeomorphism_def
+  proof (intro conjI ballI)
+    show gf: "\<And>x. x \<in> S - rel_interior S \<Longrightarrow> g (f x) = x"
+      using S rel_interior_subset by blast
+    show fg: "\<And>y. y \<in> T - rel_interior T \<Longrightarrow> f (g y) = y"
+      using T mem_rel_interior_ball by blast
+    show "f ` (S - rel_interior S) = T - rel_interior T"
+      using S fST fim gim by auto
+    show "continuous_on (S - rel_interior S) f"
+      using contf continuous_on_subset rel_interior_subset by blast
+    show "g ` (T - rel_interior T) = S - rel_interior S"
+      using T gTS gim fim by auto
+    show "continuous_on (T - rel_interior T) g"
+      using contg continuous_on_subset rel_interior_subset by blast
+  qed
+qed
+
+lemma homeomorphic_rel_boundaries:
+  fixes S :: "'a::euclidean_space set" and T :: "'b::euclidean_space set"
+  assumes "S homeomorphic T" "rel_interior S = {} \<longleftrightarrow> rel_interior T = {}"
+    shows "(S - rel_interior S) homeomorphic (T - rel_interior T)"
+proof (cases "rel_interior T = {}")
+  case True
+  with assms show ?thesis by auto
+next
+  case False
+  obtain f g
+    where S: "\<forall>x\<in>S. f x \<in> T \<and> g (f x) = x" and T: "\<forall>y\<in>T. g y \<in> S \<and> f (g y) = y"
+      and contf: "continuous_on S f" and contg: "continuous_on T g"
+    using  assms [unfolded homeomorphic_minimal] by auto
+  have "aff_dim (affine hull S) \<le> aff_dim (affine hull T)"
+    apply (rule invariance_of_dimension_affine_sets [of _ "rel_interior S" _ f])
+          apply (simp_all add: openin_rel_interior False assms)
+    using contf continuous_on_subset rel_interior_subset apply blast
+      apply (meson S hull_subset image_subsetI rel_interior_subset rev_subsetD)
+    apply (metis S inj_on_inverseI inj_on_subset rel_interior_subset)
+    done
+  moreover have "aff_dim (affine hull T) \<le> aff_dim (affine hull S)"
+    apply (rule invariance_of_dimension_affine_sets [of _ "rel_interior T" _ g])
+          apply (simp_all add: openin_rel_interior False assms)
+    using contg continuous_on_subset rel_interior_subset apply blast
+      apply (meson T hull_subset image_subsetI rel_interior_subset rev_subsetD)
+    apply (metis T inj_on_inverseI inj_on_subset rel_interior_subset)
+    done
+  ultimately have "aff_dim S = aff_dim T" by force
+  then show ?thesis
+    by (rule homeomorphic_rel_boundaries_same_dimension [OF \<open>S homeomorphic T\<close>])
+qed
+
+proposition uniformly_continuous_homeomorphism_UNIV_trivial:
+  fixes f :: "'a::euclidean_space \<Rightarrow> 'a"
+  assumes contf: "uniformly_continuous_on S f" and hom: "homeomorphism S UNIV f g"
+  shows "S = UNIV"
+proof (cases "S = {}")
+  case True
+  then show ?thesis
+    by (metis UNIV_I hom empty_iff homeomorphism_def image_eqI)
+next
+  case False
+  have "inj g"
+    by (metis UNIV_I hom homeomorphism_apply2 injI)
+  then have "open (g ` UNIV)"
+    by (blast intro: invariance_of_domain hom homeomorphism_cont2)
+  then have "open S"
+    using hom homeomorphism_image2 by blast
+  moreover have "complete S"
+    unfolding complete_def
+  proof clarify
+    fix \<sigma>
+    assume \<sigma>: "\<forall>n. \<sigma> n \<in> S" and "Cauchy \<sigma>"
+    have "Cauchy (f o \<sigma>)"
+      using uniformly_continuous_imp_Cauchy_continuous \<open>Cauchy \<sigma>\<close> \<sigma> contf by blast
+    then obtain l where "(f \<circ> \<sigma>) \<longlonglongrightarrow> l"
+      by (auto simp: convergent_eq_Cauchy [symmetric])
+    show "\<exists>l\<in>S. \<sigma> \<longlonglongrightarrow> l"
+    proof
+      show "g l \<in> S"
+        using hom homeomorphism_image2 by blast
+      have "(g \<circ> (f \<circ> \<sigma>)) \<longlonglongrightarrow> g l"
+        by (meson UNIV_I \<open>(f \<circ> \<sigma>) \<longlonglongrightarrow> l\<close> continuous_on_sequentially hom homeomorphism_cont2)
+      then show "\<sigma> \<longlonglongrightarrow> g l"
+      proof -
+        have "\<forall>n. \<sigma> n = (g \<circ> (f \<circ> \<sigma>)) n"
+          by (metis (no_types) \<sigma> comp_eq_dest_lhs hom homeomorphism_apply1)
+        then show ?thesis
+          by (metis (no_types) LIMSEQ_iff \<open>(g \<circ> (f \<circ> \<sigma>)) \<longlonglongrightarrow> g l\<close>)
+      qed
+    qed
+  qed
+  then have "closed S"
+    by (simp add: complete_eq_closed)
+  ultimately show ?thesis
+    using clopen [of S] False  by simp
+qed
+
+subsection\<open>The power, squaring and exponential functions as covering maps\<close>
+
+proposition covering_space_power_punctured_plane:
+  assumes "0 < n"
+    shows "covering_space (- {0}) (\<lambda>z::complex. z^n) (- {0})"
+proof -
+  consider "n = 1" | "2 \<le> n" using assms by linarith
+  then obtain e where "0 < e"
+                and e: "\<And>w z. cmod(w - z) < e * cmod z \<Longrightarrow> (w^n = z^n \<longleftrightarrow> w = z)"
+  proof cases
+    assume "n = 1" then show ?thesis
+      by (rule_tac e=1 in that) auto
+  next
+    assume "2 \<le> n"
+    have eq_if_pow_eq:
+         "w = z" if lt: "cmod (w - z) < 2 * sin (pi / real n) * cmod z"
+                 and eq: "w^n = z^n" for w z
+    proof (cases "z = 0")
+      case True with eq assms show ?thesis by (auto simp: power_0_left)
+    next
+      case False
+      then have "z \<noteq> 0" by auto
+      have "(w/z)^n = 1"
+        by (metis False divide_self_if eq power_divide power_one)
+      then obtain j where j: "w / z = exp (2 * of_real pi * \<i> * j / n)" and "j < n"
+        using Suc_leI assms \<open>2 \<le> n\<close> complex_roots_unity [THEN eqset_imp_iff, of n "w/z"]
+        by force
+      have "cmod (w/z - 1) < 2 * sin (pi / real n)"
+        using lt assms \<open>z \<noteq> 0\<close> by (simp add: divide_simps norm_divide)
+      then have "cmod (exp (\<i> * of_real (2 * pi * j / n)) - 1) < 2 * sin (pi / real n)"
+        by (simp add: j field_simps)
+      then have "2 * \<bar>sin((2 * pi * j / n) / 2)\<bar> < 2 * sin (pi / real n)"
+        by (simp only: dist_exp_ii_1)
+      then have sin_less: "sin((pi * j / n)) < sin (pi / real n)"
+        by (simp add: field_simps)
+      then have "w / z = 1"
+      proof (cases "j = 0")
+        case True then show ?thesis by (auto simp: j)
+      next
+        case False
+        then have "sin (pi / real n) \<le> sin((pi * j / n))"
+        proof (cases "j / n \<le> 1/2")
+          case True
+          show ?thesis
+            apply (rule sin_monotone_2pi_le)
+            using \<open>j \<noteq> 0 \<close> \<open>j < n\<close> True
+            apply (auto simp: field_simps intro: order_trans [of _ 0])
+            done
+        next
+          case False
+          then have seq: "sin(pi * j / n) = sin(pi * (n - j) / n)"
+            using \<open>j < n\<close> by (simp add: algebra_simps diff_divide_distrib of_nat_diff)
+          show ?thesis
+            apply (simp only: seq)
+            apply (rule sin_monotone_2pi_le)
+            using \<open>j < n\<close> False
+            apply (auto simp: field_simps intro: order_trans [of _ 0])
+            done
+        qed
+        with sin_less show ?thesis by force
+      qed
+      then show ?thesis by simp
+    qed
+    show ?thesis
+      apply (rule_tac e = "2 * sin(pi / n)" in that)
+       apply (force simp: \<open>2 \<le> n\<close> sin_pi_divide_n_gt_0)
+      apply (meson eq_if_pow_eq)
+      done
+  qed
+  have zn1: "continuous_on (- {0}) (\<lambda>z::complex. z^n)"
+    by (rule continuous_intros)+
+  have zn2: "(\<lambda>z::complex. z^n) ` (- {0}) = - {0}"
+    using assms by (auto simp: image_def elim: exists_complex_root_nonzero [where n = n])
+  have zn3: "\<exists>T. z^n \<in> T \<and> open T \<and> 0 \<notin> T \<and>
+               (\<exists>v. \<Union>v = {x. x \<noteq> 0 \<and> x^n \<in> T} \<and>
+                    (\<forall>u\<in>v. open u \<and> 0 \<notin> u) \<and>
+                    pairwise disjnt v \<and>
+                    (\<forall>u\<in>v. Ex (homeomorphism u T (\<lambda>z. z^n))))"
+           if "z \<noteq> 0" for z::complex
+  proof -
+    def d \<equiv> "min (1/2) (e/4) * norm z"
+    have "0 < d"
+      by (simp add: d_def \<open>0 < e\<close> \<open>z \<noteq> 0\<close>)
+    have iff_x_eq_y: "x^n = y^n \<longleftrightarrow> x = y"
+         if eq: "w^n = z^n" and x: "x \<in> ball w d" and y: "y \<in> ball w d" for w x y
+    proof -
+      have [simp]: "norm z = norm w" using that
+        by (simp add: assms power_eq_imp_eq_norm)
+      show ?thesis
+      proof (cases "w = 0")
+        case True with \<open>z \<noteq> 0\<close> assms eq
+        show ?thesis by (auto simp: power_0_left)
+      next
+        case False
+        have "cmod (x - y) < 2*d"
+          using x y
+          by (simp add: dist_norm [symmetric]) (metis dist_commute mult_2 dist_triangle_less_add)
+        also have "... \<le> 2 * e / 4 * norm w"
+          using \<open>e > 0\<close> by (simp add: d_def min_mult_distrib_right)
+        also have "... = e * (cmod w / 2)"
+          by simp
+        also have "... \<le> e * cmod y"
+          apply (rule mult_left_mono)
+          using \<open>e > 0\<close> y
+           apply (simp_all add: dist_norm d_def min_mult_distrib_right del: divide_const_simps)
+          apply (metis dist_0_norm dist_complex_def dist_triangle_half_l linorder_not_less order_less_irrefl)
+          done
+        finally have "cmod (x - y) < e * cmod y" .
+        then show ?thesis by (rule e)
+      qed
+    qed
+    then have inj: "inj_on (\<lambda>w. w^n) (ball z d)"
+      by (simp add: inj_on_def)
+    have cont: "continuous_on (ball z d) (\<lambda>w. w ^ n)"
+      by (intro continuous_intros)
+    have noncon: "\<not> (\<lambda>w::complex. w^n) constant_on UNIV"
+      by (metis UNIV_I assms constant_on_def power_one zero_neq_one zero_power)
+    have open_imball: "open ((\<lambda>w. w^n) ` ball z d)"
+      by (rule invariance_of_domain [OF cont open_ball inj])
+    have im_eq: "(\<lambda>w. w^n) ` ball z' d = (\<lambda>w. w^n) ` ball z d"
+                if z': "z'^n = z^n" for z'
+    proof -
+      have nz': "norm z' = norm z" using that assms power_eq_imp_eq_norm by blast
+      have "(w \<in> (\<lambda>w. w^n) ` ball z' d) = (w \<in> (\<lambda>w. w^n) ` ball z d)" for w
+      proof (cases "w=0")
+        case True with assms show ?thesis
+          by (simp add: image_def ball_def nz')
+      next
+        case False
+        have "z' \<noteq> 0" using \<open>z \<noteq> 0\<close> nz' by force
+        have [simp]: "(z*x / z')^n = x^n" if "x \<noteq> 0" for x
+          using z' that by (simp add: field_simps \<open>z \<noteq> 0\<close>)
+        have [simp]: "cmod (z - z * x / z') = cmod (z' - x)" if "x \<noteq> 0" for x
+        proof -
+          have "cmod (z - z * x / z') = cmod z * cmod (1 - x / z')"
+            by (metis (no_types) ab_semigroup_mult_class.mult_ac(1) complex_divide_def mult.right_neutral norm_mult right_diff_distrib')
+          also have "... = cmod z' * cmod (1 - x / z')"
+            by (simp add: nz')
+          also have "... = cmod (z' - x)"
+            by (simp add: \<open>z' \<noteq> 0\<close> diff_divide_eq_iff norm_divide)
+          finally show ?thesis .
+        qed
+        have [simp]: "(z'*x / z)^n = x^n" if "x \<noteq> 0" for x
+          using z' that by (simp add: field_simps \<open>z \<noteq> 0\<close>)
+        have [simp]: "cmod (z' - z' * x / z) = cmod (z - x)" if "x \<noteq> 0" for x
+        proof -
+          have "cmod (z * (1 - x * inverse z)) = cmod (z - x)"
+            by (metis \<open>z \<noteq> 0\<close> diff_divide_distrib divide_complex_def divide_self_if nonzero_eq_divide_eq semiring_normalization_rules(7))
+          then show ?thesis
+            by (metis (no_types) mult.assoc complex_divide_def mult.right_neutral norm_mult nz' right_diff_distrib')
+        qed
+        show ?thesis
+          unfolding image_def ball_def
+          apply safe
+          apply simp_all
+          apply (rule_tac x="z/z' * x" in exI)
+          using assms False apply (simp add: dist_norm)
+          apply (rule_tac x="z'/z * x" in exI)
+          using assms False apply (simp add: dist_norm)
+          done
+      qed
+      then show ?thesis by blast
+    qed
+    have ex_ball: "\<exists>B. (\<exists>z'. B = ball z' d \<and> z'^n = z^n) \<and> x \<in> B"
+                  if "x \<noteq> 0" and eq: "x^n = w^n" and dzw: "dist z w < d" for x w
+    proof -
+      have "w \<noteq> 0" by (metis assms power_eq_0_iff that(1) that(2))
+      have [simp]: "cmod x = cmod w"
+        using assms power_eq_imp_eq_norm eq by blast
+      have [simp]: "cmod (x * z / w - x) = cmod (z - w)"
+      proof -
+        have "cmod (x * z / w - x) = cmod x * cmod (z / w - 1)"
+          by (metis (no_types) mult.right_neutral norm_mult right_diff_distrib' times_divide_eq_right)
+        also have "... = cmod w * cmod (z / w - 1)"
+          by simp
+        also have "... = cmod (z - w)"
+          by (simp add: \<open>w \<noteq> 0\<close> divide_diff_eq_iff nonzero_norm_divide)
+        finally show ?thesis .
+      qed
+      show ?thesis
+        apply (rule_tac x="ball (z / w * x) d" in exI)
+        using \<open>d > 0\<close> that
+        apply (simp add: ball_eq_ball_iff)
+        apply (simp add: \<open>z \<noteq> 0\<close> \<open>w \<noteq> 0\<close> field_simps)
+        apply (simp add: dist_norm)
+        done
+    qed
+    have ball1: "\<Union>{ball z' d |z'. z'^n = z^n} = {x. x \<noteq> 0 \<and> x^n \<in> (\<lambda>w. w^n) ` ball z d}"
+      apply (rule equalityI)
+       prefer 2 apply (force simp: ex_ball, clarsimp)
+      apply (subst im_eq [symmetric], assumption)
+      using assms
+      apply (force simp: dist_norm d_def min_mult_distrib_right dest: power_eq_imp_eq_norm)
+      done
+    have ball2: "pairwise disjnt {ball z' d |z'. z'^n = z^n}"
+    proof (clarsimp simp add: pairwise_def disjnt_iff)
+      fix \<xi> \<zeta> x
+      assume "\<xi>^n = z^n" "\<zeta>^n = z^n" "ball \<xi> d \<noteq> ball \<zeta> d"
+         and "dist \<xi> x < d" "dist \<zeta> x < d"
+      then have "dist \<xi> \<zeta> < d+d"
+        using dist_triangle_less_add by blast
+      then have "cmod (\<xi> - \<zeta>) < 2*d"
+        by (simp add: dist_norm)
+      also have "... \<le> e * cmod z"
+        using mult_right_mono \<open>0 < e\<close> that by (auto simp: d_def)
+      finally have "cmod (\<xi> - \<zeta>) < e * cmod z" .
+      with e have "\<xi> = \<zeta>"
+        by (metis \<open>\<xi>^n = z^n\<close> \<open>\<zeta>^n = z^n\<close> assms power_eq_imp_eq_norm)
+      then show "False"
+        using \<open>ball \<xi> d \<noteq> ball \<zeta> d\<close> by blast
+    qed
+    have ball3: "Ex (homeomorphism (ball z' d) ((\<lambda>w. w^n) ` ball z d) (\<lambda>z. z^n))"
+            if zeq: "z'^n = z^n" for z'
+    proof -
+      have inj: "inj_on (\<lambda>z. z ^ n) (ball z' d)"
+        by (meson iff_x_eq_y inj_onI zeq)
+      show ?thesis
+        apply (rule invariance_of_domain_homeomorphism [of "ball z' d" "\<lambda>z. z^n"])
+          apply (rule open_ball continuous_intros order_refl inj)+
+        apply (force simp: im_eq [OF zeq])
+        done
+    qed
+    show ?thesis
+      apply (rule_tac x = "(\<lambda>w. w^n) ` (ball z d)" in exI)
+      apply (intro conjI open_imball)
+        using \<open>d > 0\<close> apply simp
+       using \<open>z \<noteq> 0\<close> assms apply (force simp: d_def)
+      apply (rule_tac x="{ ball z' d |z'. z'^n = z^n}" in exI)
+      apply (intro conjI ball1 ball2)
+       apply (force simp: assms d_def power_eq_imp_eq_norm that, clarify)
+      by (metis ball3)
+  qed
+  show ?thesis
+    using assms
+    apply (simp add: covering_space_def zn1 zn2)
+    apply (subst zn2 [symmetric])
+    apply (simp add: openin_open_eq open_Compl)
+    apply (blast intro: zn3)
+    done
+qed
+
+corollary covering_space_square_punctured_plane:
+  "covering_space (- {0}) (\<lambda>z::complex. z^2) (- {0})"
+  by (simp add: covering_space_power_punctured_plane)
+
+
+
+proposition covering_space_exp_punctured_plane:
+  "covering_space UNIV (\<lambda>z::complex. exp z) (- {0})"
+proof (simp add: covering_space_def, intro conjI ballI)
+  show "continuous_on UNIV (\<lambda>z::complex. exp z)"
+    by (rule continuous_on_exp [OF continuous_on_id])
+  show "range exp = - {0::complex}"
+    by auto (metis exp_Ln range_eqI)
+  show "\<exists>T. z \<in> T \<and> openin (subtopology euclidean (- {0})) T \<and>
+             (\<exists>v. \<Union>v = {z. exp z \<in> T} \<and> (\<forall>u\<in>v. open u) \<and> disjoint v \<and>
+                  (\<forall>u\<in>v. \<exists>q. homeomorphism u T exp q))"
+        if "z \<in> - {0::complex}" for z
+  proof -
+    have "z \<noteq> 0"
+      using that by auto
+    have inj_exp: "inj_on exp (ball (Ln z) 1)"
+      apply (rule inj_on_subset [OF inj_on_exp_pi [of "Ln z"]])
+      using pi_ge_two by (simp add: ball_subset_ball_iff)
+    define \<V> where "\<V> \<equiv> range (\<lambda>n. (\<lambda>x. x + of_real (2 * of_int n * pi) * ii) ` (ball(Ln z) 1))"
+    show ?thesis
+    proof (intro exI conjI)
+      show "z \<in> exp ` (ball(Ln z) 1)"
+        by (metis \<open>z \<noteq> 0\<close> centre_in_ball exp_Ln rev_image_eqI zero_less_one)
+      have "open (- {0::complex})"
+        by blast
+      moreover have "inj_on exp (ball (Ln z) 1)"
+        apply (rule inj_on_subset [OF inj_on_exp_pi [of "Ln z"]])
+        using pi_ge_two by (simp add: ball_subset_ball_iff)
+      ultimately show "openin (subtopology euclidean (- {0})) (exp ` ball (Ln z) 1)"
+        by (auto simp: openin_open_eq invariance_of_domain continuous_on_exp [OF continuous_on_id])
+      show "\<Union>\<V> = {w. exp w \<in> exp ` ball (Ln z) 1}"
+        by (auto simp: \<V>_def Complex_Transcendental.exp_eq image_iff)
+      show "\<forall>V\<in>\<V>. open V"
+        by (auto simp: \<V>_def inj_on_def continuous_intros invariance_of_domain)
+      have xy: "2 \<le> cmod (2 * of_int x * of_real pi * \<i> - 2 * of_int y * of_real pi * \<i>)"
+               if "x < y" for x y
+      proof -
+        have "1 \<le> abs (x - y)"
+          using that by linarith
+        then have "1 \<le> cmod (of_int x - of_int y) * 1"
+          by (metis mult.right_neutral norm_of_int of_int_1_le_iff of_int_abs of_int_diff)
+        also have "... \<le> cmod (of_int x - of_int y) * of_real pi"
+          apply (rule mult_left_mono)
+          using pi_ge_two by auto
+        also have "... \<le> cmod ((of_int x - of_int y) * of_real pi * \<i>)"
+          by (simp add: norm_mult)
+        also have "... \<le> cmod (of_int x * of_real pi * \<i> - of_int y * of_real pi * \<i>)"
+          by (simp add: algebra_simps)
+        finally have "1 \<le> cmod (of_int x * of_real pi * \<i> - of_int y * of_real pi * \<i>)" .
+        then have "2 * 1 \<le> cmod (2 * (of_int x * of_real pi * \<i> - of_int y * of_real pi * \<i>))"
+          by (metis mult_le_cancel_left_pos norm_mult_numeral1 zero_less_numeral)
+        then show ?thesis
+          by (simp add: algebra_simps)
+      qed
+      show "disjoint \<V>"
+        apply (clarsimp simp add: \<V>_def pairwise_def disjnt_def add.commute [of _ "x*y" for x y]
+                        image_add_ball ball_eq_ball_iff)
+        apply (rule disjoint_ballI)
+        apply (auto simp: dist_norm neq_iff)
+        by (metis norm_minus_commute xy)+
+      show "\<forall>u\<in>\<V>. \<exists>q. homeomorphism u (exp ` ball (Ln z) 1) exp q"
+      proof
+        fix u
+        assume "u \<in> \<V>"
+        then obtain n where n: "u = (\<lambda>x. x + of_real (2 * of_int n * pi) * ii) ` (ball(Ln z) 1)"
+          by (auto simp: \<V>_def)
+        have "compact (cball (Ln z) 1)"
+          by simp
+        moreover have "continuous_on (cball (Ln z) 1) exp"
+          by (rule continuous_on_exp [OF continuous_on_id])
+        moreover have "inj_on exp (cball (Ln z) 1)"
+          apply (rule inj_on_subset [OF inj_on_exp_pi [of "Ln z"]])
+          using pi_ge_two by (simp add: cball_subset_ball_iff)
+        ultimately obtain \<gamma> where hom: "homeomorphism (cball (Ln z) 1) (exp ` cball (Ln z) 1) exp \<gamma>"
+          using homeomorphism_compact  by blast
+        have eq1: "exp ` u = exp ` ball (Ln z) 1"
+          unfolding n
+          apply (auto simp: algebra_simps)
+          apply (rename_tac w)
+          apply (rule_tac x = "w + \<i> * (of_int n * (of_real pi * 2))" in image_eqI)
+          apply (auto simp: image_iff)
+          done
+        have \<gamma>exp: "\<gamma> (exp x) + 2 * of_int n * of_real pi * \<i> = x" if "x \<in> u" for x
+        proof -
+          have "exp x = exp (x - 2 * of_int n * of_real pi * \<i>)"
+            by (simp add: exp_eq)
+          then have "\<gamma> (exp x) = \<gamma> (exp (x - 2 * of_int n * of_real pi * \<i>))"
+            by simp
+          also have "... = x - 2 * of_int n * of_real pi * \<i>"
+            apply (rule homeomorphism_apply1 [OF hom])
+            using \<open>x \<in> u\<close> by (auto simp: n)
+          finally show ?thesis
+            by simp
+        qed
+        have exp2n: "exp (\<gamma> (exp x) + 2 * of_int n * complex_of_real pi * \<i>) = exp x"
+                if "dist (Ln z) x < 1" for x
+          using that by (auto simp: exp_eq homeomorphism_apply1 [OF hom])
+        have cont: "continuous_on (exp ` ball (Ln z) 1) (\<lambda>x. \<gamma> x + 2 * of_int n * complex_of_real pi * \<i>)"
+          apply (intro continuous_intros)
+          apply (rule continuous_on_subset [OF homeomorphism_cont2 [OF hom]])
+          apply (force simp:)
+          done
+        show "\<exists>q. homeomorphism u (exp ` ball (Ln z) 1) exp q"
+          apply (rule_tac x="(\<lambda>x. x + of_real(2 * n * pi) * ii) \<circ> \<gamma>" in exI)
+          unfolding homeomorphism_def
+          apply (intro conjI ballI eq1 continuous_on_exp [OF continuous_on_id])
+             apply (auto simp: \<gamma>exp exp2n cont n)
+           apply (simp add:  homeomorphism_apply1 [OF hom])
+          apply (simp add: image_comp [symmetric])
+          using hom homeomorphism_apply1  apply (force simp: image_iff)
+          done
+      qed
+    qed
+  qed
+qed
+
+end
--- a/src/HOL/Analysis/Henstock_Kurzweil_Integration.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Henstock_Kurzweil_Integration.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -960,7 +960,7 @@
         using dp p(1) mn d(2) by auto
     qed
   qed
-  then guess y unfolding convergent_eq_cauchy[symmetric] .. note y=this[THEN LIMSEQ_D]
+  then guess y unfolding convergent_eq_Cauchy[symmetric] .. note y=this[THEN LIMSEQ_D]
   show ?l
     unfolding integrable_on_def has_integral
   proof (rule_tac x=y in exI, clarify)
@@ -1798,7 +1798,7 @@
     qed
   qed
   then obtain s where s: "i \<longlonglongrightarrow> s"
-    using convergent_eq_cauchy[symmetric] by blast
+    using convergent_eq_Cauchy[symmetric] by blast
   show ?thesis
     unfolding integrable_on_def has_integral
   proof (rule_tac x=s in exI, clarify)
@@ -5437,7 +5437,7 @@
       apply auto
       done
   qed
-  from this[unfolded convergent_eq_cauchy[symmetric]] guess i ..
+  from this[unfolded convergent_eq_Cauchy[symmetric]] guess i ..
   note i = this[THEN LIMSEQ_D]
 
   show ?l unfolding integrable_on_def has_integral_alt'[of f]
--- a/src/HOL/Analysis/Measurable.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Measurable.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -646,6 +646,14 @@
   shows "liminf A \<in> sets M"
 by (subst liminf_SUP_INF, auto)
 
+lemma measurable_case_enat[measurable (raw)]:
+  assumes f: "f \<in> M \<rightarrow>\<^sub>M count_space UNIV" and g: "\<And>i. g i \<in> M \<rightarrow>\<^sub>M N" and h: "h \<in> M \<rightarrow>\<^sub>M N"
+  shows "(\<lambda>x. case f x of enat i \<Rightarrow> g i x | \<infinity> \<Rightarrow> h x) \<in> M \<rightarrow>\<^sub>M N"
+  apply (rule measurable_compose_countable[OF _ f])
+  subgoal for i
+    by (cases i) (auto intro: g h)
+  done
+
 hide_const (open) pred
 
 end
--- a/src/HOL/Analysis/Measure_Space.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Measure_Space.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1469,6 +1469,9 @@
 lemma distr_id[simp]: "distr N N (\<lambda>x. x) = N"
   by (rule measure_eqI) (auto simp: emeasure_distr)
 
+lemma distr_id2: "sets M = sets N \<Longrightarrow> distr N M (\<lambda>x. x) = N"
+  by (rule measure_eqI) (auto simp: emeasure_distr)
+
 lemma measure_distr:
   "f \<in> measurable M N \<Longrightarrow> S \<in> sets N \<Longrightarrow> measure (distr M N f) S = measure M (f -` S \<inter> space M)"
   by (simp add: emeasure_distr measure_def)
@@ -3516,6 +3519,11 @@
   finally show ?thesis .
 qed
 
+lemma measurable_SUP2:
+  "I \<noteq> {} \<Longrightarrow> (\<And>i. i \<in> I \<Longrightarrow> f \<in> measurable N (M i)) \<Longrightarrow>
+    (\<And>i j. i \<in> I \<Longrightarrow> j \<in> I \<Longrightarrow> space (M i) = space (M j)) \<Longrightarrow> f \<in> measurable N (SUP i:I. M i)"
+  by (auto intro!: measurable_Sup2)
+
 lemma sets_Sup_sigma:
   assumes [simp]: "M \<noteq> {}" and M: "\<And>m. m \<in> M \<Longrightarrow> m \<subseteq> Pow \<Omega>"
   shows "sets (SUP m:M. sigma \<Omega> m) = sets (sigma \<Omega> (\<Union>M))"
--- a/src/HOL/Analysis/Topology_Euclidean_Space.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Analysis/Topology_Euclidean_Space.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -458,6 +458,11 @@
        (fastforce simp: topological_space_class.topological_basis_def)+
 qed
 
+instance nat :: second_countable_topology
+proof
+  show "\<exists>B::nat set set. countable B \<and> open = generate_topology B"
+    by (intro exI[of _ "range lessThan \<union> range greaterThan"]) (auto simp: open_nat_def)
+qed
 
 lemma countable_separating_set_linorder1:
   shows "\<exists>B::('a::{linorder_topology, second_countable_topology} set). countable B \<and> (\<forall>x y. x < y \<longrightarrow> (\<exists>b \<in> B. x < b \<and> b \<le> y))"
@@ -1034,6 +1039,14 @@
   shows "x \<in> cball 0 e \<longleftrightarrow> norm x \<le> e"
   by (simp add: dist_norm)
 
+lemma disjoint_ballI:
+  shows "dist x y \<ge> r+s \<Longrightarrow> ball x r \<inter> ball y s = {}"
+  using dist_triangle_less_add not_le by fastforce
+
+lemma disjoint_cballI:
+  shows "dist x y > r+s \<Longrightarrow> cball x r \<inter> cball y s = {}"
+  by (metis add_mono disjoint_iff_not_equal dist_triangle2 dual_order.trans leD mem_cball)
+
 lemma mem_sphere_0 [simp]:
   fixes x :: "'a::real_normed_vector"
   shows "x \<in> sphere 0 e \<longleftrightarrow> norm x = e"
@@ -5435,62 +5448,62 @@
 qed
 
 lemma complete_imp_closed:
-  fixes s :: "'a::metric_space set"
-  assumes "complete s"
-  shows "closed s"
+  fixes S :: "'a::metric_space set"
+  assumes "complete S"
+  shows "closed S"
 proof (unfold closed_sequential_limits, clarify)
-  fix f x assume "\<forall>n. f n \<in> s" and "f \<longlonglongrightarrow> x"
+  fix f x assume "\<forall>n. f n \<in> S" and "f \<longlonglongrightarrow> x"
   from \<open>f \<longlonglongrightarrow> x\<close> have "Cauchy f"
     by (rule LIMSEQ_imp_Cauchy)
-  with \<open>complete s\<close> and \<open>\<forall>n. f n \<in> s\<close> obtain l where "l \<in> s" and "f \<longlonglongrightarrow> l"
+  with \<open>complete S\<close> and \<open>\<forall>n. f n \<in> S\<close> obtain l where "l \<in> S" and "f \<longlonglongrightarrow> l"
     by (rule completeE)
   from \<open>f \<longlonglongrightarrow> x\<close> and \<open>f \<longlonglongrightarrow> l\<close> have "x = l"
     by (rule LIMSEQ_unique)
-  with \<open>l \<in> s\<close> show "x \<in> s"
+  with \<open>l \<in> S\<close> show "x \<in> S"
     by simp
 qed
 
 lemma complete_Int_closed:
-  fixes s :: "'a::metric_space set"
-  assumes "complete s" and "closed t"
-  shows "complete (s \<inter> t)"
+  fixes S :: "'a::metric_space set"
+  assumes "complete S" and "closed t"
+  shows "complete (S \<inter> t)"
 proof (rule completeI)
-  fix f assume "\<forall>n. f n \<in> s \<inter> t" and "Cauchy f"
-  then have "\<forall>n. f n \<in> s" and "\<forall>n. f n \<in> t"
+  fix f assume "\<forall>n. f n \<in> S \<inter> t" and "Cauchy f"
+  then have "\<forall>n. f n \<in> S" and "\<forall>n. f n \<in> t"
     by simp_all
-  from \<open>complete s\<close> obtain l where "l \<in> s" and "f \<longlonglongrightarrow> l"
-    using \<open>\<forall>n. f n \<in> s\<close> and \<open>Cauchy f\<close> by (rule completeE)
+  from \<open>complete S\<close> obtain l where "l \<in> S" and "f \<longlonglongrightarrow> l"
+    using \<open>\<forall>n. f n \<in> S\<close> and \<open>Cauchy f\<close> by (rule completeE)
   from \<open>closed t\<close> and \<open>\<forall>n. f n \<in> t\<close> and \<open>f \<longlonglongrightarrow> l\<close> have "l \<in> t"
     by (rule closed_sequentially)
-  with \<open>l \<in> s\<close> and \<open>f \<longlonglongrightarrow> l\<close> show "\<exists>l\<in>s \<inter> t. f \<longlonglongrightarrow> l"
+  with \<open>l \<in> S\<close> and \<open>f \<longlonglongrightarrow> l\<close> show "\<exists>l\<in>S \<inter> t. f \<longlonglongrightarrow> l"
     by fast
 qed
 
 lemma complete_closed_subset:
-  fixes s :: "'a::metric_space set"
-  assumes "closed s" and "s \<subseteq> t" and "complete t"
-  shows "complete s"
-  using assms complete_Int_closed [of t s] by (simp add: Int_absorb1)
+  fixes S :: "'a::metric_space set"
+  assumes "closed S" and "S \<subseteq> t" and "complete t"
+  shows "complete S"
+  using assms complete_Int_closed [of t S] by (simp add: Int_absorb1)
 
 lemma complete_eq_closed:
-  fixes s :: "('a::complete_space) set"
-  shows "complete s \<longleftrightarrow> closed s"
+  fixes S :: "('a::complete_space) set"
+  shows "complete S \<longleftrightarrow> closed S"
 proof
-  assume "closed s" then show "complete s"
+  assume "closed S" then show "complete S"
     using subset_UNIV complete_UNIV by (rule complete_closed_subset)
 next
-  assume "complete s" then show "closed s"
+  assume "complete S" then show "closed S"
     by (rule complete_imp_closed)
 qed
 
-lemma convergent_eq_cauchy:
-  fixes s :: "nat \<Rightarrow> 'a::complete_space"
-  shows "(\<exists>l. (s \<longlongrightarrow> l) sequentially) \<longleftrightarrow> Cauchy s"
+lemma convergent_eq_Cauchy:
+  fixes S :: "nat \<Rightarrow> 'a::complete_space"
+  shows "(\<exists>l. (S \<longlongrightarrow> l) sequentially) \<longleftrightarrow> Cauchy S"
   unfolding Cauchy_convergent_iff convergent_def ..
 
 lemma convergent_imp_bounded:
-  fixes s :: "nat \<Rightarrow> 'a::metric_space"
-  shows "(s \<longlongrightarrow> l) sequentially \<Longrightarrow> bounded (range s)"
+  fixes S :: "nat \<Rightarrow> 'a::metric_space"
+  shows "(S \<longlongrightarrow> l) sequentially \<Longrightarrow> bounded (range S)"
   by (intro cauchy_imp_bounded LIMSEQ_imp_Cauchy)
 
 lemma compact_cball[simp]:
@@ -5500,15 +5513,15 @@
   by blast
 
 lemma compact_frontier_bounded[intro]:
-  fixes s :: "'a::heine_borel set"
-  shows "bounded s \<Longrightarrow> compact (frontier s)"
+  fixes S :: "'a::heine_borel set"
+  shows "bounded S \<Longrightarrow> compact (frontier S)"
   unfolding frontier_def
   using compact_eq_bounded_closed
   by blast
 
 lemma compact_frontier[intro]:
-  fixes s :: "'a::heine_borel set"
-  shows "compact s \<Longrightarrow> compact (frontier s)"
+  fixes S :: "'a::heine_borel set"
+  shows "compact S \<Longrightarrow> compact (frontier S)"
   using compact_eq_bounded_closed compact_frontier_bounded
   by blast
 
@@ -5528,8 +5541,8 @@
 by (simp add: compact_imp_closed)
 
 lemma frontier_subset_compact:
-  fixes s :: "'a::heine_borel set"
-  shows "compact s \<Longrightarrow> frontier s \<subseteq> s"
+  fixes S :: "'a::heine_borel set"
+  shows "compact S \<Longrightarrow> frontier S \<subseteq> S"
   using frontier_subset_closed compact_eq_bounded_closed
   by blast
 
@@ -5723,7 +5736,7 @@
     apply auto
     done
   then obtain l where l: "\<forall>x. P x \<longrightarrow> ((\<lambda>n. s n x) \<longlongrightarrow> l x) sequentially"
-    unfolding convergent_eq_cauchy[symmetric]
+    unfolding convergent_eq_Cauchy[symmetric]
     using choice[of "\<lambda>x l. P x \<longrightarrow> ((\<lambda>n. s n x) \<longlongrightarrow> l) sequentially"]
     by auto
   {
@@ -6081,6 +6094,11 @@
     unfolding uniformly_continuous_on_def by blast
 qed
 
+lemma continuous_closed_imp_Cauchy_continuous:
+  fixes S :: "('a::complete_space) set"
+  shows "\<lbrakk>continuous_on S f; closed S; Cauchy \<sigma>; \<And>n. (\<sigma> n) \<in> S\<rbrakk> \<Longrightarrow> Cauchy(f o \<sigma>)"
+  apply (simp add: complete_eq_closed [symmetric] continuous_on_sequentially)
+  by (meson LIMSEQ_imp_Cauchy complete_def)
 
 text\<open>The usual transformation theorems.\<close>
 
@@ -6630,7 +6648,7 @@
 
   from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF xs]
   obtain l where l: "(\<lambda>n. f (xs n)) \<longlonglongrightarrow> l"
-    by atomize_elim (simp only: convergent_eq_cauchy)
+    by atomize_elim (simp only: convergent_eq_Cauchy)
 
   have "(f \<longlongrightarrow> l) (at x within X)"
   proof (safe intro!: Lim_within_LIMSEQ)
@@ -6641,7 +6659,7 @@
 
     from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF \<open>xs' \<longlonglongrightarrow> x\<close> \<open>xs' _ \<in> X\<close>]
     obtain l' where l': "(\<lambda>n. f (xs' n)) \<longlonglongrightarrow> l'"
-      by atomize_elim (simp only: convergent_eq_cauchy)
+      by atomize_elim (simp only: convergent_eq_Cauchy)
 
     show "(\<lambda>n. f (xs' n)) \<longlonglongrightarrow> l"
     proof (rule tendstoI)
--- a/src/HOL/Archimedean_Field.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Archimedean_Field.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -736,6 +736,9 @@
     by simp
 qed
 
+lemma round_unique': "\<bar>x - of_int n\<bar> < 1/2 \<Longrightarrow> round x = n"
+  by (subst (asm) abs_less_iff, rule round_unique) (simp_all add: field_simps)
+
 lemma round_altdef: "round x = (if frac x \<ge> 1/2 then \<lceil>x\<rceil> else \<lfloor>x\<rfloor>)"
   by (cases "frac x \<ge> 1/2")
     (rule round_unique, ((simp add: frac_def field_simps ceiling_altdef; linarith)+)[2])+
--- a/src/HOL/Complex.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Complex.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -381,6 +381,23 @@
   by (simp add: complex_sgn_def divide_inverse)
 
 
+subsection \<open>Absolute value\<close>
+
+instantiation complex :: field_abs_sgn
+begin
+
+definition abs_complex :: "complex \<Rightarrow> complex"
+  where "abs_complex = of_real \<circ> norm"
+
+instance
+  apply standard
+         apply (auto simp add: abs_complex_def complex_sgn_def norm_mult)
+  apply (auto simp add: scaleR_conv_of_real field_simps)
+  done
+
+end
+
+
 subsection \<open>Completeness of the Complexes\<close>
 
 lemma bounded_linear_Re: "bounded_linear Re"
--- a/src/HOL/Data_Structures/document/root.tex	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Data_Structures/document/root.tex	Thu Oct 20 19:39:27 2016 +0200
@@ -1,6 +1,8 @@
 \documentclass[11pt,a4paper]{article}
 \usepackage{isabelle,isabellesym}
 \usepackage{latexsym}
+\usepackage{amssymb}
+\usepackage{amsmath}
 % this should be the last package used
 \usepackage{pdfsetup}
 
--- a/src/HOL/Enum.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Enum.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -580,7 +580,7 @@
 instantiation finite_1 :: 
   "{linordered_ring_strict, linordered_comm_semiring_strict, ordered_comm_ring,
     ordered_cancel_comm_monoid_diff, comm_monoid_mult, ordered_ring_abs,
-    one, modulo, sgn_if, inverse}"
+    one, modulo, sgn, inverse}"
 begin
 definition [simp]: "Groups.zero = a\<^sub>1"
 definition [simp]: "Groups.one = a\<^sub>1"
@@ -683,7 +683,7 @@
 
 instance finite_2 :: complete_linorder ..
 
-instantiation finite_2 :: "{field, abs_if, ring_div, sgn_if, semiring_div}" begin
+instantiation finite_2 :: "{field, ring_div, idom_abs_sgn}" begin
 definition [simp]: "0 = a\<^sub>1"
 definition [simp]: "1 = a\<^sub>2"
 definition "x + y = (case (x, y) of (a\<^sub>1, a\<^sub>1) \<Rightarrow> a\<^sub>1 | (a\<^sub>2, a\<^sub>2) \<Rightarrow> a\<^sub>1 | _ \<Rightarrow> a\<^sub>2)"
@@ -806,7 +806,7 @@
 
 instance finite_3 :: complete_linorder ..
 
-instantiation finite_3 :: "{field, abs_if, ring_div, semiring_div, sgn_if}" begin
+instantiation finite_3 :: "{field, ring_div, idom_abs_sgn}" begin
 definition [simp]: "0 = a\<^sub>1"
 definition [simp]: "1 = a\<^sub>2"
 definition
@@ -819,9 +819,9 @@
 definition "x * y = (case (x, y) of (a\<^sub>2, a\<^sub>2) \<Rightarrow> a\<^sub>2 | (a\<^sub>3, a\<^sub>3) \<Rightarrow> a\<^sub>2 | (a\<^sub>2, a\<^sub>3) \<Rightarrow> a\<^sub>3 | (a\<^sub>3, a\<^sub>2) \<Rightarrow> a\<^sub>3 | _ \<Rightarrow> a\<^sub>1)"
 definition "inverse = (\<lambda>x :: finite_3. x)" 
 definition "x div y = x * inverse (y :: finite_3)"
-definition "abs = (\<lambda>x :: finite_3. x)"
+definition "abs = (\<lambda>x. case x of a\<^sub>3 \<Rightarrow> a\<^sub>2 | _ \<Rightarrow> x)"
 definition "x mod y = (case (x, y) of (a\<^sub>2, a\<^sub>1) \<Rightarrow> a\<^sub>2 | (a\<^sub>3, a\<^sub>1) \<Rightarrow> a\<^sub>3 | _ \<Rightarrow> a\<^sub>1)"
-definition "sgn = (\<lambda>x. case x of a\<^sub>1 \<Rightarrow> a\<^sub>1 | _ \<Rightarrow> a\<^sub>2)"
+definition "sgn = (\<lambda>x :: finite_3. x)"
 instance
 by intro_classes
   (simp_all add: plus_finite_3_def uminus_finite_3_def minus_finite_3_def times_finite_3_def
--- a/src/HOL/Fields.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Fields.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -513,6 +513,48 @@
 
 subsection \<open>Ordered fields\<close>
 
+class field_abs_sgn = field + idom_abs_sgn
+begin
+
+lemma sgn_inverse [simp]:
+  "sgn (inverse a) = inverse (sgn a)"
+proof (cases "a = 0")
+  case True then show ?thesis by simp
+next
+  case False
+  then have "a * inverse a = 1"
+    by simp
+  then have "sgn (a * inverse a) = sgn 1"
+    by simp
+  then have "sgn a * sgn (inverse a) = 1"
+    by (simp add: sgn_mult)
+  then have "inverse (sgn a) * (sgn a * sgn (inverse a)) = inverse (sgn a) * 1"
+    by simp
+  then have "(inverse (sgn a) * sgn a) * sgn (inverse a) = inverse (sgn a)"
+    by (simp add: ac_simps)
+  with False show ?thesis
+    by (simp add: sgn_eq_0_iff)
+qed
+
+lemma abs_inverse [simp]:
+  "\<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
+proof -
+  from sgn_mult_abs [of "inverse a"] sgn_mult_abs [of a]
+  have "inverse (sgn a) * \<bar>inverse a\<bar> = inverse (sgn a * \<bar>a\<bar>)"
+    by simp
+  then show ?thesis by (auto simp add: sgn_eq_0_iff)
+qed
+    
+lemma sgn_divide [simp]:
+  "sgn (a / b) = sgn a / sgn b"
+  unfolding divide_inverse sgn_mult by simp
+
+lemma abs_divide [simp]:
+  "\<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
+  unfolding divide_inverse abs_mult by simp
+  
+end
+
 class linordered_field = field + linordered_idom
 begin
 
@@ -932,16 +974,15 @@
   show "x < y \<Longrightarrow> \<exists>z>x. z < y" by (blast intro!: less_half_sum gt_half_sum)
 qed
 
+subclass field_abs_sgn ..
+
 lemma nonzero_abs_inverse:
-     "a \<noteq> 0 ==> \<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
-apply (auto simp add: neq_iff abs_if nonzero_inverse_minus_eq
-                      negative_imp_inverse_negative)
-apply (blast intro: positive_imp_inverse_positive elim: less_asym)
-done
+  "a \<noteq> 0 ==> \<bar>inverse a\<bar> = inverse \<bar>a\<bar>"
+  by (rule abs_inverse)
 
 lemma nonzero_abs_divide:
-     "b \<noteq> 0 ==> \<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
-  by (simp add: divide_inverse abs_mult nonzero_abs_inverse)
+  "b \<noteq> 0 ==> \<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
+  by (rule abs_divide)
 
 lemma field_le_epsilon:
   assumes e: "\<And>e. 0 < e \<Longrightarrow> x \<le> y + e"
@@ -1147,19 +1188,6 @@
   "(b/a = 1) = ((a \<noteq> 0 & a = b))"
 by (auto simp add: divide_eq_eq)
 
-lemma abs_inverse [simp]:
-     "\<bar>inverse a\<bar> =
-      inverse \<bar>a\<bar>"
-apply (cases "a=0", simp)
-apply (simp add: nonzero_abs_inverse)
-done
-
-lemma abs_divide [simp]:
-     "\<bar>a / b\<bar> = \<bar>a\<bar> / \<bar>b\<bar>"
-apply (cases "b=0", simp)
-apply (simp add: nonzero_abs_divide)
-done
-
 lemma abs_div_pos: "0 < y ==>
     \<bar>x\<bar> / y = \<bar>x / y\<bar>"
   apply (subst abs_divide)
@@ -1174,7 +1202,7 @@
 
 lemma inverse_sgn:
   "sgn (inverse a) = inverse (sgn a)"
-  by (simp add: sgn_if)
+  by (fact sgn_inverse)
 
 lemma field_le_mult_one_interval:
   assumes *: "\<And>z. \<lbrakk> 0 < z ; z < 1 \<rbrakk> \<Longrightarrow> z * x \<le> y"
--- a/src/HOL/Groups.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Groups.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1148,18 +1148,6 @@
 class sgn =
   fixes sgn :: "'a \<Rightarrow> 'a"
 
-class abs_if = minus + uminus + ord + zero + abs +
-  assumes abs_if: "\<bar>a\<bar> = (if a < 0 then - a else a)"
-
-class sgn_if = minus + uminus + zero + one + ord + sgn +
-  assumes sgn_if: "sgn x = (if x = 0 then 0 else if 0 < x then 1 else - 1)"
-begin
-
-lemma sgn0 [simp]: "sgn 0 = 0"
-  by (simp add:sgn_if)
-
-end
-
 class ordered_ab_group_add_abs = ordered_ab_group_add + abs +
   assumes abs_ge_zero [simp]: "\<bar>a\<bar> \<ge> 0"
     and abs_ge_self: "a \<le> \<bar>a\<bar>"
--- a/src/HOL/Library/Extended_Nonnegative_Real.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Library/Extended_Nonnegative_Real.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1131,6 +1131,9 @@
 lemma enn2real_positive_iff: "0 < enn2real x \<longleftrightarrow> (0 < x \<and> x < top)"
   by (cases x rule: ennreal_cases) auto
 
+lemma enn2real_eq_1_iff[simp]: "enn2real x = 1 \<longleftrightarrow> x = 1"
+  by (cases x) auto
+
 subsection \<open>Coercion from @{typ enat} to @{typ ennreal}\<close>
 
 
--- a/src/HOL/Library/Fraction_Field.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Library/Fraction_Field.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -70,7 +70,7 @@
     and "\<And>a c. Fract 0 a = Fract 0 c"
 by(transfer; simp)+
 
-instantiation fract :: (idom) "{comm_ring_1,power}"
+instantiation fract :: (idom) comm_ring_1
 begin
 
 lift_definition zero_fract :: "'a fract" is "(0, 1)" by simp
@@ -353,31 +353,20 @@
 
 end
 
-instantiation fract :: (linordered_idom) "{distrib_lattice,abs_if,sgn_if}"
+instantiation fract :: (linordered_idom) linordered_field
 begin
 
-definition abs_fract_def2: "\<bar>q\<bar> = (if q < 0 then -q else (q::'a fract))"
+definition abs_fract_def2:
+  "\<bar>q\<bar> = (if q < 0 then -q else (q::'a fract))"
 
 definition sgn_fract_def:
   "sgn (q::'a fract) = (if q = 0 then 0 else if 0 < q then 1 else - 1)"
 
 theorem abs_fract [simp]: "\<bar>Fract a b\<bar> = Fract \<bar>a\<bar> \<bar>b\<bar>"
-unfolding abs_fract_def2 not_le[symmetric]
-by transfer(auto simp add: zero_less_mult_iff le_less)
-
-definition inf_fract_def:
-  "(inf :: 'a fract \<Rightarrow> 'a fract \<Rightarrow> 'a fract) = min"
+  unfolding abs_fract_def2 not_le [symmetric]
+  by transfer (auto simp add: zero_less_mult_iff le_less)
 
-definition sup_fract_def:
-  "(sup :: 'a fract \<Rightarrow> 'a fract \<Rightarrow> 'a fract) = max"
-
-instance
-by intro_classes (simp_all add: abs_fract_def2 sgn_fract_def inf_fract_def sup_fract_def max_min_distrib2)
-
-end
-
-instance fract :: (linordered_idom) linordered_field
-proof
+instance proof
   fix q r s :: "'a fract"
   assume "q \<le> r"
   then show "s + q \<le> s + r"
@@ -420,7 +409,23 @@
         by (simp add: ac_simps)
     qed
   qed
-qed
+qed (fact sgn_fract_def abs_fract_def2)+
+
+end
+
+instantiation fract :: (linordered_idom) distrib_lattice
+begin
+
+definition inf_fract_def:
+  "(inf :: 'a fract \<Rightarrow> 'a fract \<Rightarrow> 'a fract) = min"
+
+definition sup_fract_def:
+  "(sup :: 'a fract \<Rightarrow> 'a fract \<Rightarrow> 'a fract) = max"
+
+instance
+  by standard (simp_all add: inf_fract_def sup_fract_def max_min_distrib2)
+  
+end
 
 lemma fract_induct_pos [case_names Fract]:
   fixes P :: "'a::linordered_idom fract \<Rightarrow> bool"
--- a/src/HOL/Library/Linear_Temporal_Logic_on_Streams.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Library/Linear_Temporal_Logic_on_Streams.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -662,7 +662,7 @@
 lemma sfilter_not_P[simp]: "\<not> P (shd s) \<Longrightarrow> sfilter P s = sfilter P (stl s)"
   using sfilter_Stream[of P "shd s" "stl s"] by simp
 
-lemma sfilter_eq: 
+lemma sfilter_eq:
   assumes "ev (holds P) s"
   shows "sfilter P s = x ## s' \<longleftrightarrow>
     P x \<and> (not (holds P) suntil (HLD {x} aand nxt (\<lambda>s. sfilter P s = s'))) s"
@@ -685,7 +685,7 @@
 proof
   assume "alw Q (sfilter P s)" with * show "alw (\<lambda>x. Q (sfilter P x)) s"
   proof (coinduction arbitrary: s rule: alw_coinduct)
-    case (stl s) 
+    case (stl s)
     then have "ev (holds P) s"
       by blast
     from this stl show ?case
@@ -694,7 +694,7 @@
 next
   assume "alw (\<lambda>x. Q (sfilter P x)) s" with * show "alw Q (sfilter P s)"
   proof (coinduction arbitrary: s rule: alw_coinduct)
-    case (stl s) 
+    case (stl s)
     then have "ev (holds P) s"
       by blast
     from this stl show ?case
@@ -767,4 +767,22 @@
 lemma hld_smap': "HLD x (smap f s) = HLD (f -` x) s"
   by (simp add: HLD_def)
 
+lemma pigeonhole_stream:
+  assumes "alw (HLD s) \<omega>"
+  assumes "finite s"
+  shows "\<exists>x\<in>s. alw (ev (HLD {x})) \<omega>"
+proof -
+  have "\<forall>i\<in>UNIV. \<exists>x\<in>s. \<omega> !! i = x"
+    using `alw (HLD s) \<omega>` by (simp add: alw_iff_sdrop HLD_iff)
+  from pigeonhole_infinite_rel[OF infinite_UNIV_nat `finite s` this]
+  show ?thesis
+    by (simp add: HLD_iff infinite_iff_alw_ev[symmetric])
+qed
+
+lemma ev_eq_suntil: "ev P \<omega> \<longleftrightarrow> (not P suntil P) \<omega>"
+proof
+  assume "ev P \<omega>" then show "((\<lambda>xs. \<not> P xs) suntil P) \<omega>"
+    by (induction rule: ev_induct_strong) (auto intro: suntil.intros)
+qed (auto simp: ev_suntil)
+
 end
--- a/src/HOL/Library/Old_SMT/old_smt_solver.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Library/Old_SMT/old_smt_solver.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -53,7 +53,7 @@
 
 fun make_cmd command options problem_path proof_path =
   space_implode " "
-    ("(exec 2>&1;" :: map File.bash_string (command () @ options) @
+    ("(exec 2>&1;" :: map Bash.string (command () @ options) @
       [File.bash_path problem_path, ")", ">", File.bash_path proof_path])
 
 fun trace_and ctxt msg f x =
--- a/src/HOL/Library/Stream.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Library/Stream.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -242,7 +242,7 @@
 lemma sdrop_snth: "sdrop n s !! m = s !! (n + m)"
   by (induct n arbitrary: m s) auto
 
-partial_function (tailrec) sdrop_while :: "('a \<Rightarrow> bool) \<Rightarrow> 'a stream \<Rightarrow> 'a stream" where 
+partial_function (tailrec) sdrop_while :: "('a \<Rightarrow> bool) \<Rightarrow> 'a stream \<Rightarrow> 'a stream" where
   "sdrop_while P s = (if P (shd s) then sdrop_while P (stl s) else s)"
 
 lemma sdrop_while_SCons[code]:
@@ -342,7 +342,7 @@
   by (induct n arbitrary: u) (auto simp: rotate1_rotate_swap rotate1_hd_tl rotate_conv_mod[symmetric])
 
 lemma sset_cycle[simp]:
-  assumes "xs \<noteq> []" 
+  assumes "xs \<noteq> []"
   shows "sset (cycle xs) = set xs"
 proof (intro set_eqI iffI)
   fix x
@@ -408,6 +408,14 @@
 lemma sconst_streams: "x \<in> A \<Longrightarrow> sconst x \<in> streams A"
   by (simp add: streams_iff_sset)
 
+lemma streams_empty_iff: "streams S = {} \<longleftrightarrow> S = {}"
+proof safe
+  fix x assume "x \<in> S" "streams S = {}"
+  then have "sconst x \<in> streams S"
+    by (intro sconst_streams)
+  then show "x \<in> {}"
+    unfolding \<open>streams S = {}\<close> by simp
+qed (auto simp: streams_empty)
 
 subsection \<open>stream of natural numbers\<close>
 
@@ -442,11 +450,11 @@
 lemma flat_unfold: "shd ws \<noteq> [] \<Longrightarrow> flat ws = shd ws @- flat (stl ws)"
   by (cases ws) auto
 
-lemma flat_snth: "\<forall>xs \<in> sset s. xs \<noteq> [] \<Longrightarrow> flat s !! n = (if n < length (shd s) then 
+lemma flat_snth: "\<forall>xs \<in> sset s. xs \<noteq> [] \<Longrightarrow> flat s !! n = (if n < length (shd s) then
   shd s ! n else flat (stl s) !! (n - length (shd s)))"
   by (metis flat_unfold not_less shd_sset shift_snth_ge shift_snth_less)
 
-lemma sset_flat[simp]: "\<forall>xs \<in> sset s. xs \<noteq> [] \<Longrightarrow> 
+lemma sset_flat[simp]: "\<forall>xs \<in> sset s. xs \<noteq> [] \<Longrightarrow>
   sset (flat s) = (\<Union>xs \<in> sset s. set xs)" (is "?P \<Longrightarrow> ?L = ?R")
 proof safe
   fix x assume ?P "x : ?L"
--- a/src/HOL/Limits.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Limits.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -2340,6 +2340,11 @@
 
 lemma isUCont_Cauchy: "isUCont f \<Longrightarrow> Cauchy X \<Longrightarrow> Cauchy (\<lambda>n. f (X n))"
   by (rule uniformly_continuous_on_Cauchy[where S=UNIV and f=f]) simp_all
+  
+lemma uniformly_continuous_imp_Cauchy_continuous:
+  fixes f :: "'a::metric_space \<Rightarrow> 'b::metric_space"
+  shows "\<lbrakk>uniformly_continuous_on S f; Cauchy \<sigma>; \<And>n. (\<sigma> n) \<in> S\<rbrakk> \<Longrightarrow> Cauchy(f o \<sigma>)"
+  by (simp add: uniformly_continuous_on_def Cauchy_def) meson
 
 lemma (in bounded_linear) isUCont: "isUCont f"
   unfolding isUCont_def dist_norm
--- a/src/HOL/Nonstandard_Analysis/StarDef.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Nonstandard_Analysis/StarDef.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -898,19 +898,15 @@
 instance star :: (abs_if) abs_if
   by (intro_classes; transfer) (fact abs_if)
 
-instance star :: (sgn_if) sgn_if
-  by (intro_classes; transfer) (fact sgn_if)
-
 instance star :: (linordered_ring_strict) linordered_ring_strict ..
 instance star :: (ordered_comm_ring) ordered_comm_ring ..
 
 instance star :: (linordered_semidom) linordered_semidom
-  apply intro_classes
-  apply(transfer, fact zero_less_one)
-  apply(transfer, fact le_add_diff_inverse2)
-  done
+  by (intro_classes; transfer) (fact zero_less_one le_add_diff_inverse2)+
 
-instance star :: (linordered_idom) linordered_idom ..
+instance star :: (linordered_idom) linordered_idom
+  by (intro_classes; transfer) (fact sgn_if)
+
 instance star :: (linordered_field) linordered_field ..
 
 subsection \<open>Power\<close>
--- a/src/HOL/Number_Theory/Fib.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Number_Theory/Fib.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1,12 +1,13 @@
 (*  Title:      HOL/Number_Theory/Fib.thy
     Author:     Lawrence C. Paulson
     Author:     Jeremy Avigad
+    Author:     Manuel Eberl
 *)
 
 section \<open>The fibonacci function\<close>
 
 theory Fib
-imports Main GCD Binomial
+  imports Complex_Main
 begin
 
 
@@ -38,6 +39,34 @@
   by (induct n rule: fib.induct) (auto simp add: )
 
 
+subsection \<open>More efficient code\<close>
+
+text \<open>
+  The naive approach is very inefficient since the branching recursion leads to many
+  values of @{term fib} being computed multiple times. We can avoid this by ``remembering''
+  the last two values in the sequence, yielding a tail-recursive version.
+  This is far from optimal (it takes roughly $O(n\cdot M(n))$ time where $M(n)$ is the 
+  time required to multiply two $n$-bit integers), but much better than the naive version,
+  which is exponential.
+\<close>
+
+fun gen_fib :: "nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat" where
+  "gen_fib a b 0 = a"
+| "gen_fib a b (Suc 0) = b"
+| "gen_fib a b (Suc (Suc n)) = gen_fib b (a + b) (Suc n)"
+
+lemma gen_fib_recurrence: "gen_fib a b (Suc (Suc n)) = gen_fib a b n + gen_fib a b (Suc n)"
+  by (induction a b n rule: gen_fib.induct) simp_all
+  
+lemma gen_fib_fib: "gen_fib (fib n) (fib (Suc n)) m = fib (n + m)"
+  by (induction m rule: fib.induct) (simp_all del: gen_fib.simps(3) add: gen_fib_recurrence)
+
+lemma fib_conv_gen_fib: "fib n = gen_fib 0 1 n"
+  using gen_fib_fib[of 0 n] by simp
+
+declare fib_conv_gen_fib [code]
+
+
 subsection \<open>A Few Elementary Results\<close>
 
 text \<open>
@@ -104,6 +133,114 @@
   by (induct n rule: nat.induct) (auto simp add:  field_simps)
 
 
+subsection \<open>Closed form\<close>
+
+lemma fib_closed_form:
+  defines "\<phi> \<equiv> (1 + sqrt 5) / (2::real)" and "\<psi> \<equiv> (1 - sqrt 5) / (2::real)"
+  shows   "of_nat (fib n) = (\<phi> ^ n - \<psi> ^ n) / sqrt 5"
+proof (induction n rule: fib.induct)
+  fix n :: nat
+  assume IH1: "of_nat (fib n) = (\<phi> ^ n - \<psi> ^ n) / sqrt 5"
+  assume IH2: "of_nat (fib (Suc n)) = (\<phi> ^ Suc n - \<psi> ^ Suc n) / sqrt 5"
+  have "of_nat (fib (Suc (Suc n))) = of_nat (fib (Suc n)) + of_nat (fib n)" by simp
+  also have "... = (\<phi>^n*(\<phi> + 1) - \<psi>^n*(\<psi> + 1)) / sqrt 5"
+    by (simp add: IH1 IH2 field_simps)
+  also have "\<phi> + 1 = \<phi>\<^sup>2" by (simp add: \<phi>_def field_simps power2_eq_square)
+  also have "\<psi> + 1 = \<psi>\<^sup>2" by (simp add: \<psi>_def field_simps power2_eq_square)
+  also have "\<phi>^n * \<phi>\<^sup>2 - \<psi>^n * \<psi>\<^sup>2 = \<phi> ^ Suc (Suc n) - \<psi> ^ Suc (Suc n)"  
+    by (simp add: power2_eq_square)
+  finally show "of_nat (fib (Suc (Suc n))) = (\<phi> ^ Suc (Suc n) - \<psi> ^ Suc (Suc n)) / sqrt 5" .
+qed (simp_all add: \<phi>_def \<psi>_def field_simps)
+
+lemma fib_closed_form':
+  defines "\<phi> \<equiv> (1 + sqrt 5) / (2 :: real)" and "\<psi> \<equiv> (1 - sqrt 5) / (2 :: real)"
+  assumes "n > 0"
+  shows   "fib n = round (\<phi> ^ n / sqrt 5)"
+proof (rule sym, rule round_unique')
+  have "\<bar>\<phi> ^ n / sqrt 5 - of_int (int (fib n))\<bar> = \<bar>\<psi>\<bar> ^ n / sqrt 5"
+    by (simp add: fib_closed_form[folded \<phi>_def \<psi>_def] field_simps power_abs)
+  also {
+    from assms have "\<bar>\<psi>\<bar>^n \<le> \<bar>\<psi>\<bar>^1"
+      by (intro power_decreasing) (simp_all add: algebra_simps real_le_lsqrt)
+    also have "... < sqrt 5 / 2" by (simp add: \<psi>_def field_simps)
+    finally have "\<bar>\<psi>\<bar>^n / sqrt 5 < 1/2" by (simp add: field_simps)
+  }
+  finally show "\<bar>\<phi> ^ n / sqrt 5 - of_int (int (fib n))\<bar> < 1/2" .
+qed
+
+lemma fib_asymptotics:
+  defines "\<phi> \<equiv> (1 + sqrt 5) / (2 :: real)"
+  shows   "(\<lambda>n. real (fib n) / (\<phi> ^ n / sqrt 5)) \<longlonglongrightarrow> 1"
+proof -
+  define \<psi> where "\<psi> \<equiv> (1 - sqrt 5) / (2 :: real)"
+  have "\<phi> > 1" by (simp add: \<phi>_def)
+  hence A: "\<phi> \<noteq> 0" by auto
+  have "(\<lambda>n. (\<psi> / \<phi>) ^ n) \<longlonglongrightarrow> 0"
+    by (rule LIMSEQ_power_zero) (simp_all add: \<phi>_def \<psi>_def field_simps add_pos_pos)
+  hence "(\<lambda>n. 1 - (\<psi> / \<phi>) ^ n) \<longlonglongrightarrow> 1 - 0" by (intro tendsto_diff tendsto_const)
+  with A show ?thesis
+    by (simp add: divide_simps fib_closed_form [folded \<phi>_def \<psi>_def])
+qed
+
+
+subsection \<open>Divide-and-Conquer recurrence\<close>
+
+text \<open>
+  The following divide-and-conquer recurrence allows for a more efficient computation 
+  of Fibonacci numbers; however, it requires memoisation of values to be reasonably 
+  efficient, cutting the number of values to be computed to logarithmically many instead of
+  linearly many. The vast majority of the computation time is then actually spent on the 
+  multiplication, since the output number is exponential in the input number.
+\<close>
+
+lemma fib_rec_odd:
+  defines "\<phi> \<equiv> (1 + sqrt 5) / (2 :: real)" and "\<psi> \<equiv> (1 - sqrt 5) / (2 :: real)"
+  shows   "fib (Suc (2*n)) = fib n^2 + fib (Suc n)^2"
+proof -
+  have "of_nat (fib n^2 + fib (Suc n)^2) = ((\<phi> ^ n - \<psi> ^ n)\<^sup>2 + (\<phi> * \<phi> ^ n - \<psi> * \<psi> ^ n)\<^sup>2)/5"
+    by (simp add: fib_closed_form[folded \<phi>_def \<psi>_def] field_simps power2_eq_square)
+  also have "(\<phi> ^ n - \<psi> ^ n)\<^sup>2 + (\<phi> * \<phi> ^ n - \<psi> * \<psi> ^ n)\<^sup>2 = 
+    \<phi>^(2*n) + \<psi>^(2*n) - 2*(\<phi>*\<psi>)^n + \<phi>^(2*n+2) + \<psi>^(2*n+2) - 2*(\<phi>*\<psi>)^(n+1)" (is "_ = ?A")
+      by (simp add: power2_eq_square algebra_simps power_mult power_mult_distrib)
+  also have "\<phi> * \<psi> = -1" by (simp add: \<phi>_def \<psi>_def field_simps)
+  hence "?A = \<phi>^(2*n+1) * (\<phi> + inverse \<phi>) + \<psi>^(2*n+1) * (\<psi> + inverse \<psi>)" 
+    by (auto simp: field_simps power2_eq_square)
+  also have "1 + sqrt 5 > 0" by (auto intro: add_pos_pos)
+  hence "\<phi> + inverse \<phi> = sqrt 5" by (simp add: \<phi>_def field_simps)
+  also have "\<psi> + inverse \<psi> = -sqrt 5" by (simp add: \<psi>_def field_simps)
+  also have "(\<phi> ^ (2*n+1) * sqrt 5 + \<psi> ^ (2*n+1)* - sqrt 5) / 5 =
+               (\<phi> ^ (2*n+1) - \<psi> ^ (2*n+1)) * (sqrt 5 / 5)" by (simp add: field_simps)
+  also have "sqrt 5 / 5 = inverse (sqrt 5)" by (simp add: field_simps)
+  also have "(\<phi> ^ (2*n+1) - \<psi> ^ (2*n+1)) * ... = of_nat (fib (Suc (2*n)))"
+    by (simp add: fib_closed_form[folded \<phi>_def \<psi>_def] divide_inverse)
+  finally show ?thesis by (simp only: of_nat_eq_iff)
+qed
+
+lemma fib_rec_even: "fib (2*n) = (fib (n - 1) + fib (n + 1)) * fib n"
+proof (induction n)
+  case (Suc n)
+  let ?rfib = "\<lambda>x. real (fib x)"
+  have "2 * (Suc n) = Suc (Suc (2*n))" by simp
+  also have "real (fib ...) = ?rfib n^2 + ?rfib (Suc n)^2 + (?rfib (n - 1) + ?rfib (n + 1)) * ?rfib n" 
+    by (simp add: fib_rec_odd Suc)
+  also have "(?rfib (n - 1) + ?rfib (n + 1)) * ?rfib n = (2 * ?rfib (n + 1) - ?rfib n) * ?rfib n"
+    by (cases n) simp_all
+  also have "?rfib n^2 + ?rfib (Suc n)^2 + ... = (?rfib (Suc n) + 2 * ?rfib n) * ?rfib (Suc n)"
+    by (simp add: algebra_simps power2_eq_square)
+  also have "... = real ((fib (Suc n - 1) + fib (Suc n + 1)) * fib (Suc n))" by simp
+  finally show ?case by (simp only: of_nat_eq_iff)
+qed simp
+
+lemma fib_rec_even': "fib (2*n) = (2*fib (n - 1) + fib n) * fib n"
+  by (subst fib_rec_even, cases n) simp_all
+
+lemma fib_rec:
+  "fib n = (if n = 0 then 0 else if n = 1 then 1 else
+            if even n then let n' = n div 2; fn = fib n' in (2 * fib (n' - 1) + fn) * fn
+            else let n' = n div 2 in fib n' ^ 2 + fib (Suc n') ^ 2)"
+  by (auto elim: evenE oddE simp: fib_rec_odd fib_rec_even' Let_def)
+
+
 subsection \<open>Fibonacci and Binomial Coefficients\<close>
 
 lemma sum_drop_zero: "(\<Sum>k = 0..Suc n. if 0<k then (f (k - 1)) else 0) = (\<Sum>j = 0..n. f j)"
--- a/src/HOL/Number_Theory/Number_Theory.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Number_Theory/Number_Theory.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -2,7 +2,7 @@
 section \<open>Comprehensive number theory\<close>
 
 theory Number_Theory
-imports Fib Residues Eratosthenes QuadraticReciprocity Pocklington
+imports Fib Residues Eratosthenes Quadratic_Reciprocity Pocklington
 begin
 
 end
--- a/src/HOL/Number_Theory/QuadraticReciprocity.thy	Tue Oct 18 16:04:44 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,387 +0,0 @@
-(* Author: Jaime Mendizabal Roche *)
-
-theory QuadraticReciprocity
-imports Gauss
-begin
-
-text {* The proof is based on Gauss's fifth proof, which can be found at http://www.lehigh.edu/~shw2/q-recip/gauss5.pdf *}
-
-locale QR =
-  fixes p :: "nat"
-  fixes q :: "nat"
-
-  assumes p_prime: "prime p"
-  assumes p_ge_2: "2 < p"
-  assumes q_prime: "prime q"
-  assumes q_ge_2: "2 < q"
-  assumes pq_neq: "p \<noteq> q"
-begin
-
-lemma odd_p: "odd p" using p_ge_2 p_prime prime_odd_nat by blast
-
-lemma p_ge_0: "0 < int p"
-  using p_prime not_prime_0[where 'a = nat] by fastforce+
-
-lemma p_eq2: "int p = (2 * ((int p - 1) div 2)) + 1" using odd_p by simp
-
-lemma odd_q: "odd q" using q_ge_2 q_prime prime_odd_nat by blast
-
-lemma q_ge_0: "0 < int q" using q_prime not_prime_0[where 'a = nat] by fastforce+
-
-lemma q_eq2: "int q = (2 * ((int q - 1) div 2)) + 1" using odd_q by simp
-
-lemma pq_eq2: "int p * int q = (2 * ((int p * int q - 1) div 2)) + 1" using odd_p odd_q by simp
-
-lemma pq_coprime: "coprime p q"
-  using pq_neq p_prime primes_coprime_nat q_prime by blast
-
-lemma pq_coprime_int: "coprime (int p) (int q)"
-  using pq_coprime transfer_int_nat_gcd(1) by presburger
-
-lemma qp_ineq: "(int p * k \<le> (int p * int q - 1) div 2) = (k \<le> (int q - 1) div 2)"
-proof -
-  have "(2 * int p * k \<le> int p * int q - 1) = (2 * k \<le> int q - 1)" using p_ge_0 by auto
-  thus ?thesis by auto
-qed
-
-lemma QRqp: "QR q p" using QR_def QR_axioms by simp
-
-lemma pq_commute: "int p * int q = int q * int p" by simp
-
-lemma pq_ge_0: "int p * int q > 0" using p_ge_0 q_ge_0 mult_pos_pos by blast
-
-definition "r = ((p - 1) div 2)*((q - 1) div 2)"
-definition "m = card (GAUSS.E p q)"
-definition "n = card (GAUSS.E q p)"
-
-abbreviation "Res (k::int) \<equiv> {0 .. k - 1}"
-abbreviation "Res_ge_0 (k::int) \<equiv> {0 <.. k - 1}"
-abbreviation "Res_0 (k::int) \<equiv> {0::int}"
-abbreviation "Res_l (k::int) \<equiv> {0 <.. (k - 1) div 2}"
-abbreviation "Res_h (k::int) \<equiv> {(k - 1) div 2 <.. k - 1}"
-
-abbreviation "Sets_pq r0 r1 r2 \<equiv>
-  {(x::int). x \<in> r0 (int p * int q) \<and> x mod p \<in> r1 (int p) \<and> x mod q \<in> r2 (int q)}"
-
-definition "A = Sets_pq Res_l Res_l Res_h"
-definition "B = Sets_pq Res_l Res_h Res_l"
-definition "C = Sets_pq Res_h Res_h Res_l"
-definition "D = Sets_pq Res_l Res_h Res_h"
-definition "E = Sets_pq Res_l Res_0 Res_h"
-definition "F = Sets_pq Res_l Res_h Res_0"
-
-definition "a = card A"
-definition "b = card B"
-definition "c = card C"
-definition "d = card D"
-definition "e = card E"
-definition "f = card F"
-
-lemma Gpq: "GAUSS p q" unfolding GAUSS_def
-  using p_prime pq_neq p_ge_2 q_prime
-  by (auto simp: cong_altdef_int zdvd_int [symmetric] dest: primes_dvd_imp_eq) 
-
-lemma Gqp: "GAUSS q p" using QRqp QR.Gpq by simp
-
-lemma QR_lemma_01: "(\<lambda>x. x mod q) ` E = GAUSS.E q p"
-proof
-    {
-      fix x
-      assume a1: "x \<in> E"
-      then obtain k where k: "x = int p * k" unfolding E_def by blast
-      have "x \<in> Res_l (int p * int q)" using a1 E_def by blast
-      hence "k \<in> GAUSS.A q" using Gqp GAUSS.A_def k qp_ineq by (simp add: zero_less_mult_iff)
-      hence "x mod q \<in> GAUSS.E q p"
-        using GAUSS.C_def[of q p] Gqp k GAUSS.B_def[of q p] a1 GAUSS.E_def[of q p]
-        unfolding E_def by force
-      hence "x \<in> E \<longrightarrow> x mod int q \<in> GAUSS.E q p" by auto
-    }
-    thus "(\<lambda>x. x mod int q) ` E \<subseteq> GAUSS.E q p" by auto
-next
-  show "GAUSS.E q p \<subseteq> (\<lambda>x. x mod q) ` E"
-  proof
-    fix x
-    assume a1: "x \<in> GAUSS.E q p"
-    then obtain ka where ka: "ka \<in> GAUSS.A q" "x = (ka * p) mod q"
-      using Gqp GAUSS.B_def GAUSS.C_def GAUSS.E_def by auto
-    hence "ka * p \<in> Res_l (int p * int q)"
-      using GAUSS.A_def Gqp p_ge_0 qp_ineq by (simp add: Groups.mult_ac(2))
-    thus "x \<in> (\<lambda>x. x mod q) ` E" unfolding E_def using ka a1 Gqp GAUSS.E_def q_ge_0 by force
-  qed
-qed
-
-lemma QR_lemma_02: "e= n"
-proof -
-  {
-    fix x y
-    assume a: "x \<in> E" "y \<in> E" "x mod q = y mod q"
-    obtain p_inv where p_inv: "[int p * p_inv = 1] (mod int q)"
-      using pq_coprime_int cong_solve_coprime_int by blast
-    obtain kx ky where k: "x = int p * kx" "y = int p * ky" using a E_def dvd_def[of p x] by blast
-    hence "0 < x" "int p * kx \<le> (int p * int q - 1) div 2"
-        "0 < y" "int p * ky \<le> (int p * int q - 1) div 2"
-      using E_def a greaterThanAtMost_iff mem_Collect_eq by blast+
-    hence "0 \<le> kx" "kx < q" "0 \<le> ky" "ky < q" using qp_ineq k by (simp add: zero_less_mult_iff)+
-    moreover have "(p_inv * (p * kx)) mod q = (p_inv * (p * ky)) mod q"
-      using a(3) mod_mult_cong k by blast
-    hence "(p * p_inv * kx) mod q = (p * p_inv * ky) mod q" by (simp add:algebra_simps)
-    hence "kx mod q = ky mod q"
-      using p_inv mod_mult_cong[of "p * p_inv" "q" "1"] cong_int_def by auto
-    hence "[kx = ky] (mod q)" using cong_int_def by blast
-    ultimately have "x = y" using cong_less_imp_eq_int k by blast
-  }
-  hence "inj_on (\<lambda>x. x mod q) E" unfolding inj_on_def by auto
-  thus ?thesis using QR_lemma_01 card_image e_def n_def by fastforce
-qed
-
-lemma QR_lemma_03: "f = m"
-proof -
-  have "F = QR.E q p" unfolding F_def pq_commute using QRqp QR.E_def[of q p] by fastforce
-  hence "f = QR.e q p" unfolding f_def using QRqp QR.e_def[of q p] by presburger
-  thus ?thesis using QRqp QR.QR_lemma_02 m_def QRqp QR.n_def by presburger
-qed
-
-definition f_1 :: "int \<Rightarrow> int \<times> int" where
-  "f_1 x = ((x mod p), (x mod q))"
-
-definition P_1 :: "int \<times> int \<Rightarrow> int \<Rightarrow> bool" where
-  "P_1 res x \<longleftrightarrow> x mod p = fst res & x mod q = snd res & x \<in> Res (int p * int q)"
-
-definition g_1 :: "int \<times> int \<Rightarrow> int" where
-  "g_1 res = (THE x. P_1 res x)"
-
-lemma P_1_lemma: assumes "0 \<le> fst res" "fst res < p" "0 \<le> snd res" "snd res < q"
-  shows "\<exists>! x. P_1 res x"
-proof -
-  obtain y k1 k2 where yk: "y = nat (fst res) + k1 * p" "y = nat (snd res) + k2 * q"
-    using chinese_remainder[of p q] pq_coprime p_ge_0 q_ge_0 by fastforce
-  have h1: "[y = fst res] (mod p)" "[y = snd res] (mod q)"
-    using yk(1) assms(1) cong_iff_lin_int[of "fst res"] cong_sym_int apply simp
-    using yk(2) assms(3) cong_iff_lin_int[of "snd res"] cong_sym_int by simp
-  have "(y mod (int p * int q)) mod int p = fst res" "(y mod (int p * int q)) mod int q = snd res"
-    using h1(1) mod_mod_cancel[of "int p"] assms(1) assms(2) cong_int_def apply simp
-    using h1(2) mod_mod_cancel[of "int q"] assms(3) assms(4) cong_int_def by simp
-  then obtain x where "P_1 res x" unfolding P_1_def
-    using Divides.pos_mod_bound Divides.pos_mod_sign pq_ge_0 by fastforce
-  moreover {
-    fix a b
-    assume a: "P_1 res a" "P_1 res b"
-    hence "int p * int q dvd a - b"
-      using divides_mult[of "int p" "a - b" "int q"] pq_coprime_int zmod_eq_dvd_iff[of a _ b]
-      unfolding P_1_def by force
-    hence "a = b" using dvd_imp_le_int[of "a - b"] a unfolding P_1_def by fastforce
-  }
-  ultimately show ?thesis by auto
-qed
-
-lemma g_1_lemma: assumes "0 \<le> fst res" "fst res < p" "0 \<le> snd res" "snd res < q"
-  shows "P_1 res (g_1 res)" using assms P_1_lemma theI'[of "P_1 res"] g_1_def by presburger
-
-definition "BuC = Sets_pq Res_ge_0 Res_h Res_l"
-
-lemma QR_lemma_04: "card BuC = card ((Res_h p) \<times> (Res_l q))"
-  using card_bij_eq[of f_1 "BuC" "(Res_h p) \<times> (Res_l q)" g_1]
-proof
-  {
-    fix x y
-    assume a: "x \<in> BuC" "y \<in> BuC" "f_1 x = f_1 y"
-    hence "int p * int q dvd x - y"
-      using f_1_def pq_coprime_int divides_mult[of "int p" "x - y" "int q"] 
-            zmod_eq_dvd_iff[of x _ y] by auto
-    hence "x = y"
-      using dvd_imp_le_int[of "x - y" "int p * int q"] a unfolding BuC_def by force
-  }
-  thus "inj_on f_1 BuC" unfolding inj_on_def by auto
-next
-  {
-    fix x y
-    assume a: "x \<in> (Res_h p) \<times> (Res_l q)" "y \<in> (Res_h p) \<times> (Res_l q)" "g_1 x = g_1 y"
-    hence "0 \<le> fst x" "fst x < p" "0 \<le> snd x" "snd x < q"
-        "0 \<le> fst y" "fst y < p" "0 \<le> snd y" "snd y < q"
-      using mem_Sigma_iff prod.collapse by fastforce+
-    hence "x = y" using g_1_lemma[of x] g_1_lemma[of y] a P_1_def by fastforce
-  }
-  thus "inj_on g_1 ((Res_h p) \<times> (Res_l q))" unfolding inj_on_def by auto
-next
-  show "g_1 ` ((Res_h p) \<times> (Res_l q)) \<subseteq> BuC"
-  proof
-    fix y
-    assume "y \<in> g_1 ` ((Res_h p) \<times> (Res_l q))"
-    then obtain x where x: "y = g_1 x" "x \<in> ((Res_h p) \<times> (Res_l q))" by blast
-    hence "P_1 x y" using g_1_lemma by fastforce
-    thus "y \<in> BuC" unfolding P_1_def BuC_def mem_Collect_eq using x SigmaE prod.sel by fastforce
-  qed
-qed (auto simp: BuC_def finite_subset f_1_def)
-
-lemma QR_lemma_05: "card ((Res_h p) \<times> (Res_l q)) = r"
-proof -
-  have "card (Res_l q) = (q - 1) div 2" "card (Res_h p) = (p - 1) div 2" using p_eq2 by force+
-  thus ?thesis unfolding r_def using card_cartesian_product[of "Res_h p" "Res_l q"] by presburger
-qed
-
-lemma QR_lemma_06: "b + c = r"
-proof -
-  have "B \<inter> C = {}" "finite B" "finite C" "B \<union> C = BuC" unfolding B_def C_def BuC_def by fastforce+
-  thus ?thesis
-    unfolding b_def c_def using card_empty card_Un_Int QR_lemma_04 QR_lemma_05 by fastforce
-qed
-
-definition f_2:: "int \<Rightarrow> int" where
-  "f_2 x = (int p * int q) - x"
-
-lemma f_2_lemma_1: "\<And>x. f_2 (f_2 x) = x" unfolding f_2_def by simp
-
-lemma f_2_lemma_2: "[f_2 x = int p - x] (mod p)" unfolding f_2_def using cong_altdef_int by simp
-
-lemma f_2_lemma_3: "f_2 x \<in> S \<Longrightarrow> x \<in> f_2 ` S"
-  using f_2_lemma_1[of x] image_eqI[of x f_2 "f_2 x" S] by presburger
-
-lemma QR_lemma_07: "f_2 ` Res_l (int p * int q) = Res_h (int p * int q)"
-    "f_2 ` Res_h (int p * int q) = Res_l (int p * int q)"
-proof -
-  have h1: "f_2 ` Res_l (int p * int q) \<subseteq> Res_h (int p * int q)" using f_2_def by force
-  have h2: "f_2 ` Res_h (int p * int q) \<subseteq> Res_l (int p * int q)" using f_2_def pq_eq2 by fastforce
-  have h3: "Res_h (int p * int q) \<subseteq> f_2 ` Res_l (int p * int q)" using h2 f_2_lemma_3 by blast
-  have h4: "Res_l (int p * int q) \<subseteq> f_2 ` Res_h (int p * int q)" using h1 f_2_lemma_3 by blast
-  show "f_2 ` Res_l (int p * int q) = Res_h (int p * int q)" using h1 h3 by blast
-  show "f_2 ` Res_h (int p * int q) = Res_l (int p * int q)" using h2 h4 by blast
-qed
-
-lemma QR_lemma_08: "(f_2 x mod p \<in> Res_l p) = (x mod p \<in> Res_h p)"
-    "(f_2 x mod p \<in> Res_h p) = (x mod p \<in> Res_l p)"
-  using f_2_lemma_2[of x] cong_int_def[of "f_2 x" "p - x" p] minus_mod_self2[of x p]
-  zmod_zminus1_eq_if[of x p] p_eq2 by auto
-
-lemma QR_lemma_09: "(f_2 x mod q \<in> Res_l q) = (x mod q \<in> Res_h q)"
-    "(f_2 x mod q \<in> Res_h q) = (x mod q \<in> Res_l q)"
-  using QRqp QR.QR_lemma_08 f_2_def QR.f_2_def pq_commute by auto+
-
-lemma QR_lemma_10: "a = c" unfolding a_def c_def apply (rule card_bij_eq[of f_2 A C f_2])
-  unfolding A_def C_def
-  using QR_lemma_07 QR_lemma_08 QR_lemma_09 apply ((simp add: inj_on_def f_2_def),blast)+
-  by fastforce+
-
-definition "BuD = Sets_pq Res_l Res_h Res_ge_0"
-definition "BuDuF = Sets_pq Res_l Res_h Res"
-
-definition f_3 :: "int \<Rightarrow> int \<times> int" where
-  "f_3 x = (x mod p, x div p + 1)"
-
-definition g_3 :: "int \<times> int \<Rightarrow> int" where
-  "g_3 x = fst x + (snd x - 1) * p"
-
-lemma QR_lemma_11: "card BuDuF = card ((Res_h p) \<times> (Res_l q))"
-  using card_bij_eq[of f_3 BuDuF "(Res_h p) \<times> (Res_l q)" g_3]
-proof
-  show "f_3 ` BuDuF \<subseteq> (Res_h p) \<times> (Res_l q)"
-  proof
-    fix y
-    assume "y \<in> f_3 ` BuDuF"
-    then obtain x where x: "y = f_3 x" "x \<in> BuDuF" by blast
-    hence "x \<le> int p * (int q - 1) div 2 + (int p - 1) div 2"
-      unfolding BuDuF_def using p_eq2 int_distrib(4) by auto
-    moreover have "(int p - 1) div 2 \<le> - 1 + x mod p" using x BuDuF_def by auto
-    moreover have "int p * (int q - 1) div 2 = int p * ((int q - 1) div 2)"
-      using zdiv_zmult1_eq odd_q by auto
-    hence "p * (int q - 1) div 2 = p * ((int q + 1) div 2 - 1)" by fastforce
-    ultimately have "x \<le> p * ((int q + 1) div 2 - 1) - 1 + x mod p" by linarith
-    hence "x div p < (int q + 1) div 2 - 1"
-      using mult.commute[of "int p" "x div p"] p_ge_0 div_mult_mod_eq[of x p]
-        mult_less_cancel_left_pos[of p "x div p" "(int q + 1) div 2 - 1"] by linarith
-    moreover have "0 < x div p + 1"
-      using pos_imp_zdiv_neg_iff[of p x] p_ge_0 x mem_Collect_eq BuDuF_def by auto
-    ultimately show "y \<in> (Res_h p) \<times> (Res_l q)" using x BuDuF_def f_3_def by auto
-  qed
-next
-  have h1: "\<And>x. x \<in> ((Res_h p) \<times> (Res_l q)) \<Longrightarrow> f_3 (g_3 x) = x"
-  proof -
-    fix x
-    assume a: "x \<in> ((Res_h p) \<times> (Res_l q))"
-    moreover have h: "(fst x + (snd x - 1) * int p) mod int p = fst x" using a by force
-    ultimately have "(fst x + (snd x - 1) * int p) div int p + 1 = snd x"
-      by (auto simp: semiring_numeral_div_class.div_less)
-    with h show "f_3 (g_3 x) = x" unfolding f_3_def g_3_def by simp
-  qed
-  show "inj_on g_3 ((Res_h p) \<times> (Res_l q))" apply (rule inj_onI[of "(Res_h p) \<times> (Res_l q)" g_3])
-  proof -
-    fix x y
-    assume "x \<in> ((Res_h p) \<times> (Res_l q))" "y \<in> ((Res_h p) \<times> (Res_l q))" "g_3 x = g_3 y"
-    thus "x = y" using h1[of x] h1[of y] by presburger
-  qed
-next
-  show "g_3 ` ((Res_h p) \<times> (Res_l q)) \<subseteq> BuDuF"
-  proof
-    fix y
-    assume "y \<in> g_3 ` ((Res_h p) \<times> (Res_l q))"
-    then obtain x where x: "y = g_3 x" "x \<in> (Res_h p) \<times> (Res_l q)" by blast
-    hence "snd x \<le> (int q - 1) div 2" by force
-    moreover have "int p * ((int q - 1) div 2) = (int p * int q - int p) div 2"
-      using int_distrib(4) zdiv_zmult1_eq[of "int p" "int q - 1" 2] odd_q by fastforce
-    ultimately have "(snd x) * int p \<le> (int q * int p - int p) div 2"
-      using mult_right_mono[of "snd x" "(int q - 1) div 2" p] mult.commute[of "(int q - 1) div 2" p]
-        pq_commute by presburger
-    hence "(snd x - 1) * int p \<le> (int q * int p - 1) div 2 - int p"
-      using p_ge_0 int_distrib(3) by auto
-    moreover have "fst x \<le> int p - 1" using x by force
-    ultimately have "fst x + (snd x - 1) * int p \<le> (int p * int q - 1) div 2"
-      using pq_commute by linarith
-    moreover have "0 < fst x" "0 \<le> (snd x - 1) * p" using x(2) by fastforce+
-    ultimately show "y \<in> BuDuF" unfolding BuDuF_def using q_ge_0 x g_3_def x(1) by auto
-  qed
-next
-  show "finite BuDuF" unfolding BuDuF_def by fastforce
-qed (simp add: inj_on_inverseI[of BuDuF g_3] f_3_def g_3_def QR_lemma_05)+
-
-lemma QR_lemma_12: "b + d + m = r"
-proof -
-  have "B \<inter> D = {}" "finite B" "finite D" "B \<union> D = BuD" unfolding B_def D_def BuD_def by fastforce+
-  hence "b + d = card BuD" unfolding b_def d_def using card_Un_Int by fastforce
-  moreover have "BuD \<inter> F = {}" "finite BuD" "finite F" unfolding BuD_def F_def by fastforce+
-  moreover have "BuD \<union> F = BuDuF" unfolding BuD_def F_def BuDuF_def
-    using q_ge_0 ivl_disj_un_singleton(5)[of 0 "int q - 1"] by auto
-  ultimately show ?thesis using QR_lemma_03 QR_lemma_05 QR_lemma_11 card_Un_disjoint[of BuD F]
-    unfolding b_def d_def f_def by presburger
-qed
-
-lemma QR_lemma_13: "a + d + n = r"
-proof -
-  have "A = QR.B q p" unfolding A_def pq_commute using QRqp QR.B_def[of q p] by blast
-  hence "a = QR.b q p" using a_def QRqp QR.b_def[of q p] by presburger
-  moreover have "D = QR.D q p" unfolding D_def pq_commute using QRqp QR.D_def[of q p] by blast
-    hence "d = QR.d q p" using d_def  QRqp QR.d_def[of q p] by presburger
-  moreover have "n = QR.m q p" using n_def QRqp QR.m_def[of q p] by presburger
-  moreover have "r = QR.r q p" unfolding r_def using QRqp QR.r_def[of q p] by auto
-  ultimately show ?thesis using QRqp QR.QR_lemma_12 by presburger
-qed
-
-lemma QR_lemma_14: "(-1::int) ^ (m + n) = (-1) ^ r"
-proof -
-  have "m + n + 2 * d = r" using QR_lemma_06 QR_lemma_10 QR_lemma_12 QR_lemma_13 by auto
-  thus ?thesis using power_add[of "-1::int" "m + n" "2 * d"] by fastforce
-qed
-
-lemma Quadratic_Reciprocity:
-    "(Legendre p q) * (Legendre q p) = (-1::int) ^ ((p - 1) div 2 * ((q - 1) div 2))"
-  using Gpq Gqp GAUSS.gauss_lemma power_add[of "-1::int" m n] QR_lemma_14
-  unfolding r_def m_def n_def by auto
-
-end
-
-theorem Quadratic_Reciprocity: assumes "prime p" "2 < p" "prime q" "2 < q" "p \<noteq> q"
-  shows "(Legendre p q) * (Legendre q p) = (-1::int) ^ ((p - 1) div 2 * ((q - 1) div 2))"
-  using QR.Quadratic_Reciprocity QR_def assms by blast
-
-theorem Quadratic_Reciprocity_int: assumes "prime (nat p)" "2 < p" "prime (nat q)" "2 < q" "p \<noteq> q"
-  shows "(Legendre p q) * (Legendre q p) = (-1::int) ^ (nat ((p - 1) div 2 * ((q - 1) div 2)))"
-proof -
-  have "0 \<le> (p - 1) div 2" using assms by simp
-  moreover have "(nat p - 1) div 2 = nat ((p - 1) div 2)" "(nat q - 1) div 2 = nat ((q - 1) div 2)"
-    by fastforce+
-  ultimately have "(nat p - 1) div 2 * ((nat q - 1) div 2) = nat ((p - 1) div 2 * ((q - 1) div 2))"
-    using nat_mult_distrib by presburger
-  moreover have "2 < nat p" "2 < nat q" "nat p \<noteq> nat q" "int (nat p) = p" "int (nat q) = q"
-    using assms by linarith+
-  ultimately show ?thesis using Quadratic_Reciprocity[of "nat p" "nat q"] assms by presburger
-qed
-
-end
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Number_Theory/Quadratic_Reciprocity.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,387 @@
+(* Author: Jaime Mendizabal Roche *)
+
+theory Quadratic_Reciprocity
+imports Gauss
+begin
+
+text {* The proof is based on Gauss's fifth proof, which can be found at http://www.lehigh.edu/~shw2/q-recip/gauss5.pdf *}
+
+locale QR =
+  fixes p :: "nat"
+  fixes q :: "nat"
+
+  assumes p_prime: "prime p"
+  assumes p_ge_2: "2 < p"
+  assumes q_prime: "prime q"
+  assumes q_ge_2: "2 < q"
+  assumes pq_neq: "p \<noteq> q"
+begin
+
+lemma odd_p: "odd p" using p_ge_2 p_prime prime_odd_nat by blast
+
+lemma p_ge_0: "0 < int p"
+  using p_prime not_prime_0[where 'a = nat] by fastforce+
+
+lemma p_eq2: "int p = (2 * ((int p - 1) div 2)) + 1" using odd_p by simp
+
+lemma odd_q: "odd q" using q_ge_2 q_prime prime_odd_nat by blast
+
+lemma q_ge_0: "0 < int q" using q_prime not_prime_0[where 'a = nat] by fastforce+
+
+lemma q_eq2: "int q = (2 * ((int q - 1) div 2)) + 1" using odd_q by simp
+
+lemma pq_eq2: "int p * int q = (2 * ((int p * int q - 1) div 2)) + 1" using odd_p odd_q by simp
+
+lemma pq_coprime: "coprime p q"
+  using pq_neq p_prime primes_coprime_nat q_prime by blast
+
+lemma pq_coprime_int: "coprime (int p) (int q)"
+  using pq_coprime transfer_int_nat_gcd(1) by presburger
+
+lemma qp_ineq: "(int p * k \<le> (int p * int q - 1) div 2) = (k \<le> (int q - 1) div 2)"
+proof -
+  have "(2 * int p * k \<le> int p * int q - 1) = (2 * k \<le> int q - 1)" using p_ge_0 by auto
+  thus ?thesis by auto
+qed
+
+lemma QRqp: "QR q p" using QR_def QR_axioms by simp
+
+lemma pq_commute: "int p * int q = int q * int p" by simp
+
+lemma pq_ge_0: "int p * int q > 0" using p_ge_0 q_ge_0 mult_pos_pos by blast
+
+definition "r = ((p - 1) div 2)*((q - 1) div 2)"
+definition "m = card (GAUSS.E p q)"
+definition "n = card (GAUSS.E q p)"
+
+abbreviation "Res (k::int) \<equiv> {0 .. k - 1}"
+abbreviation "Res_ge_0 (k::int) \<equiv> {0 <.. k - 1}"
+abbreviation "Res_0 (k::int) \<equiv> {0::int}"
+abbreviation "Res_l (k::int) \<equiv> {0 <.. (k - 1) div 2}"
+abbreviation "Res_h (k::int) \<equiv> {(k - 1) div 2 <.. k - 1}"
+
+abbreviation "Sets_pq r0 r1 r2 \<equiv>
+  {(x::int). x \<in> r0 (int p * int q) \<and> x mod p \<in> r1 (int p) \<and> x mod q \<in> r2 (int q)}"
+
+definition "A = Sets_pq Res_l Res_l Res_h"
+definition "B = Sets_pq Res_l Res_h Res_l"
+definition "C = Sets_pq Res_h Res_h Res_l"
+definition "D = Sets_pq Res_l Res_h Res_h"
+definition "E = Sets_pq Res_l Res_0 Res_h"
+definition "F = Sets_pq Res_l Res_h Res_0"
+
+definition "a = card A"
+definition "b = card B"
+definition "c = card C"
+definition "d = card D"
+definition "e = card E"
+definition "f = card F"
+
+lemma Gpq: "GAUSS p q" unfolding GAUSS_def
+  using p_prime pq_neq p_ge_2 q_prime
+  by (auto simp: cong_altdef_int zdvd_int [symmetric] dest: primes_dvd_imp_eq) 
+
+lemma Gqp: "GAUSS q p" using QRqp QR.Gpq by simp
+
+lemma QR_lemma_01: "(\<lambda>x. x mod q) ` E = GAUSS.E q p"
+proof
+    {
+      fix x
+      assume a1: "x \<in> E"
+      then obtain k where k: "x = int p * k" unfolding E_def by blast
+      have "x \<in> Res_l (int p * int q)" using a1 E_def by blast
+      hence "k \<in> GAUSS.A q" using Gqp GAUSS.A_def k qp_ineq by (simp add: zero_less_mult_iff)
+      hence "x mod q \<in> GAUSS.E q p"
+        using GAUSS.C_def[of q p] Gqp k GAUSS.B_def[of q p] a1 GAUSS.E_def[of q p]
+        unfolding E_def by force
+      hence "x \<in> E \<longrightarrow> x mod int q \<in> GAUSS.E q p" by auto
+    }
+    thus "(\<lambda>x. x mod int q) ` E \<subseteq> GAUSS.E q p" by auto
+next
+  show "GAUSS.E q p \<subseteq> (\<lambda>x. x mod q) ` E"
+  proof
+    fix x
+    assume a1: "x \<in> GAUSS.E q p"
+    then obtain ka where ka: "ka \<in> GAUSS.A q" "x = (ka * p) mod q"
+      using Gqp GAUSS.B_def GAUSS.C_def GAUSS.E_def by auto
+    hence "ka * p \<in> Res_l (int p * int q)"
+      using GAUSS.A_def Gqp p_ge_0 qp_ineq by (simp add: Groups.mult_ac(2))
+    thus "x \<in> (\<lambda>x. x mod q) ` E" unfolding E_def using ka a1 Gqp GAUSS.E_def q_ge_0 by force
+  qed
+qed
+
+lemma QR_lemma_02: "e= n"
+proof -
+  {
+    fix x y
+    assume a: "x \<in> E" "y \<in> E" "x mod q = y mod q"
+    obtain p_inv where p_inv: "[int p * p_inv = 1] (mod int q)"
+      using pq_coprime_int cong_solve_coprime_int by blast
+    obtain kx ky where k: "x = int p * kx" "y = int p * ky" using a E_def dvd_def[of p x] by blast
+    hence "0 < x" "int p * kx \<le> (int p * int q - 1) div 2"
+        "0 < y" "int p * ky \<le> (int p * int q - 1) div 2"
+      using E_def a greaterThanAtMost_iff mem_Collect_eq by blast+
+    hence "0 \<le> kx" "kx < q" "0 \<le> ky" "ky < q" using qp_ineq k by (simp add: zero_less_mult_iff)+
+    moreover have "(p_inv * (p * kx)) mod q = (p_inv * (p * ky)) mod q"
+      using a(3) mod_mult_cong k by blast
+    hence "(p * p_inv * kx) mod q = (p * p_inv * ky) mod q" by (simp add:algebra_simps)
+    hence "kx mod q = ky mod q"
+      using p_inv mod_mult_cong[of "p * p_inv" "q" "1"] cong_int_def by auto
+    hence "[kx = ky] (mod q)" using cong_int_def by blast
+    ultimately have "x = y" using cong_less_imp_eq_int k by blast
+  }
+  hence "inj_on (\<lambda>x. x mod q) E" unfolding inj_on_def by auto
+  thus ?thesis using QR_lemma_01 card_image e_def n_def by fastforce
+qed
+
+lemma QR_lemma_03: "f = m"
+proof -
+  have "F = QR.E q p" unfolding F_def pq_commute using QRqp QR.E_def[of q p] by fastforce
+  hence "f = QR.e q p" unfolding f_def using QRqp QR.e_def[of q p] by presburger
+  thus ?thesis using QRqp QR.QR_lemma_02 m_def QRqp QR.n_def by presburger
+qed
+
+definition f_1 :: "int \<Rightarrow> int \<times> int" where
+  "f_1 x = ((x mod p), (x mod q))"
+
+definition P_1 :: "int \<times> int \<Rightarrow> int \<Rightarrow> bool" where
+  "P_1 res x \<longleftrightarrow> x mod p = fst res & x mod q = snd res & x \<in> Res (int p * int q)"
+
+definition g_1 :: "int \<times> int \<Rightarrow> int" where
+  "g_1 res = (THE x. P_1 res x)"
+
+lemma P_1_lemma: assumes "0 \<le> fst res" "fst res < p" "0 \<le> snd res" "snd res < q"
+  shows "\<exists>! x. P_1 res x"
+proof -
+  obtain y k1 k2 where yk: "y = nat (fst res) + k1 * p" "y = nat (snd res) + k2 * q"
+    using chinese_remainder[of p q] pq_coprime p_ge_0 q_ge_0 by fastforce
+  have h1: "[y = fst res] (mod p)" "[y = snd res] (mod q)"
+    using yk(1) assms(1) cong_iff_lin_int[of "fst res"] cong_sym_int apply simp
+    using yk(2) assms(3) cong_iff_lin_int[of "snd res"] cong_sym_int by simp
+  have "(y mod (int p * int q)) mod int p = fst res" "(y mod (int p * int q)) mod int q = snd res"
+    using h1(1) mod_mod_cancel[of "int p"] assms(1) assms(2) cong_int_def apply simp
+    using h1(2) mod_mod_cancel[of "int q"] assms(3) assms(4) cong_int_def by simp
+  then obtain x where "P_1 res x" unfolding P_1_def
+    using Divides.pos_mod_bound Divides.pos_mod_sign pq_ge_0 by fastforce
+  moreover {
+    fix a b
+    assume a: "P_1 res a" "P_1 res b"
+    hence "int p * int q dvd a - b"
+      using divides_mult[of "int p" "a - b" "int q"] pq_coprime_int zmod_eq_dvd_iff[of a _ b]
+      unfolding P_1_def by force
+    hence "a = b" using dvd_imp_le_int[of "a - b"] a unfolding P_1_def by fastforce
+  }
+  ultimately show ?thesis by auto
+qed
+
+lemma g_1_lemma: assumes "0 \<le> fst res" "fst res < p" "0 \<le> snd res" "snd res < q"
+  shows "P_1 res (g_1 res)" using assms P_1_lemma theI'[of "P_1 res"] g_1_def by presburger
+
+definition "BuC = Sets_pq Res_ge_0 Res_h Res_l"
+
+lemma QR_lemma_04: "card BuC = card ((Res_h p) \<times> (Res_l q))"
+  using card_bij_eq[of f_1 "BuC" "(Res_h p) \<times> (Res_l q)" g_1]
+proof
+  {
+    fix x y
+    assume a: "x \<in> BuC" "y \<in> BuC" "f_1 x = f_1 y"
+    hence "int p * int q dvd x - y"
+      using f_1_def pq_coprime_int divides_mult[of "int p" "x - y" "int q"] 
+            zmod_eq_dvd_iff[of x _ y] by auto
+    hence "x = y"
+      using dvd_imp_le_int[of "x - y" "int p * int q"] a unfolding BuC_def by force
+  }
+  thus "inj_on f_1 BuC" unfolding inj_on_def by auto
+next
+  {
+    fix x y
+    assume a: "x \<in> (Res_h p) \<times> (Res_l q)" "y \<in> (Res_h p) \<times> (Res_l q)" "g_1 x = g_1 y"
+    hence "0 \<le> fst x" "fst x < p" "0 \<le> snd x" "snd x < q"
+        "0 \<le> fst y" "fst y < p" "0 \<le> snd y" "snd y < q"
+      using mem_Sigma_iff prod.collapse by fastforce+
+    hence "x = y" using g_1_lemma[of x] g_1_lemma[of y] a P_1_def by fastforce
+  }
+  thus "inj_on g_1 ((Res_h p) \<times> (Res_l q))" unfolding inj_on_def by auto
+next
+  show "g_1 ` ((Res_h p) \<times> (Res_l q)) \<subseteq> BuC"
+  proof
+    fix y
+    assume "y \<in> g_1 ` ((Res_h p) \<times> (Res_l q))"
+    then obtain x where x: "y = g_1 x" "x \<in> ((Res_h p) \<times> (Res_l q))" by blast
+    hence "P_1 x y" using g_1_lemma by fastforce
+    thus "y \<in> BuC" unfolding P_1_def BuC_def mem_Collect_eq using x SigmaE prod.sel by fastforce
+  qed
+qed (auto simp: BuC_def finite_subset f_1_def)
+
+lemma QR_lemma_05: "card ((Res_h p) \<times> (Res_l q)) = r"
+proof -
+  have "card (Res_l q) = (q - 1) div 2" "card (Res_h p) = (p - 1) div 2" using p_eq2 by force+
+  thus ?thesis unfolding r_def using card_cartesian_product[of "Res_h p" "Res_l q"] by presburger
+qed
+
+lemma QR_lemma_06: "b + c = r"
+proof -
+  have "B \<inter> C = {}" "finite B" "finite C" "B \<union> C = BuC" unfolding B_def C_def BuC_def by fastforce+
+  thus ?thesis
+    unfolding b_def c_def using card_empty card_Un_Int QR_lemma_04 QR_lemma_05 by fastforce
+qed
+
+definition f_2:: "int \<Rightarrow> int" where
+  "f_2 x = (int p * int q) - x"
+
+lemma f_2_lemma_1: "\<And>x. f_2 (f_2 x) = x" unfolding f_2_def by simp
+
+lemma f_2_lemma_2: "[f_2 x = int p - x] (mod p)" unfolding f_2_def using cong_altdef_int by simp
+
+lemma f_2_lemma_3: "f_2 x \<in> S \<Longrightarrow> x \<in> f_2 ` S"
+  using f_2_lemma_1[of x] image_eqI[of x f_2 "f_2 x" S] by presburger
+
+lemma QR_lemma_07: "f_2 ` Res_l (int p * int q) = Res_h (int p * int q)"
+    "f_2 ` Res_h (int p * int q) = Res_l (int p * int q)"
+proof -
+  have h1: "f_2 ` Res_l (int p * int q) \<subseteq> Res_h (int p * int q)" using f_2_def by force
+  have h2: "f_2 ` Res_h (int p * int q) \<subseteq> Res_l (int p * int q)" using f_2_def pq_eq2 by fastforce
+  have h3: "Res_h (int p * int q) \<subseteq> f_2 ` Res_l (int p * int q)" using h2 f_2_lemma_3 by blast
+  have h4: "Res_l (int p * int q) \<subseteq> f_2 ` Res_h (int p * int q)" using h1 f_2_lemma_3 by blast
+  show "f_2 ` Res_l (int p * int q) = Res_h (int p * int q)" using h1 h3 by blast
+  show "f_2 ` Res_h (int p * int q) = Res_l (int p * int q)" using h2 h4 by blast
+qed
+
+lemma QR_lemma_08: "(f_2 x mod p \<in> Res_l p) = (x mod p \<in> Res_h p)"
+    "(f_2 x mod p \<in> Res_h p) = (x mod p \<in> Res_l p)"
+  using f_2_lemma_2[of x] cong_int_def[of "f_2 x" "p - x" p] minus_mod_self2[of x p]
+  zmod_zminus1_eq_if[of x p] p_eq2 by auto
+
+lemma QR_lemma_09: "(f_2 x mod q \<in> Res_l q) = (x mod q \<in> Res_h q)"
+    "(f_2 x mod q \<in> Res_h q) = (x mod q \<in> Res_l q)"
+  using QRqp QR.QR_lemma_08 f_2_def QR.f_2_def pq_commute by auto+
+
+lemma QR_lemma_10: "a = c" unfolding a_def c_def apply (rule card_bij_eq[of f_2 A C f_2])
+  unfolding A_def C_def
+  using QR_lemma_07 QR_lemma_08 QR_lemma_09 apply ((simp add: inj_on_def f_2_def),blast)+
+  by fastforce+
+
+definition "BuD = Sets_pq Res_l Res_h Res_ge_0"
+definition "BuDuF = Sets_pq Res_l Res_h Res"
+
+definition f_3 :: "int \<Rightarrow> int \<times> int" where
+  "f_3 x = (x mod p, x div p + 1)"
+
+definition g_3 :: "int \<times> int \<Rightarrow> int" where
+  "g_3 x = fst x + (snd x - 1) * p"
+
+lemma QR_lemma_11: "card BuDuF = card ((Res_h p) \<times> (Res_l q))"
+  using card_bij_eq[of f_3 BuDuF "(Res_h p) \<times> (Res_l q)" g_3]
+proof
+  show "f_3 ` BuDuF \<subseteq> (Res_h p) \<times> (Res_l q)"
+  proof
+    fix y
+    assume "y \<in> f_3 ` BuDuF"
+    then obtain x where x: "y = f_3 x" "x \<in> BuDuF" by blast
+    hence "x \<le> int p * (int q - 1) div 2 + (int p - 1) div 2"
+      unfolding BuDuF_def using p_eq2 int_distrib(4) by auto
+    moreover have "(int p - 1) div 2 \<le> - 1 + x mod p" using x BuDuF_def by auto
+    moreover have "int p * (int q - 1) div 2 = int p * ((int q - 1) div 2)"
+      using zdiv_zmult1_eq odd_q by auto
+    hence "p * (int q - 1) div 2 = p * ((int q + 1) div 2 - 1)" by fastforce
+    ultimately have "x \<le> p * ((int q + 1) div 2 - 1) - 1 + x mod p" by linarith
+    hence "x div p < (int q + 1) div 2 - 1"
+      using mult.commute[of "int p" "x div p"] p_ge_0 div_mult_mod_eq[of x p]
+        mult_less_cancel_left_pos[of p "x div p" "(int q + 1) div 2 - 1"] by linarith
+    moreover have "0 < x div p + 1"
+      using pos_imp_zdiv_neg_iff[of p x] p_ge_0 x mem_Collect_eq BuDuF_def by auto
+    ultimately show "y \<in> (Res_h p) \<times> (Res_l q)" using x BuDuF_def f_3_def by auto
+  qed
+next
+  have h1: "\<And>x. x \<in> ((Res_h p) \<times> (Res_l q)) \<Longrightarrow> f_3 (g_3 x) = x"
+  proof -
+    fix x
+    assume a: "x \<in> ((Res_h p) \<times> (Res_l q))"
+    moreover have h: "(fst x + (snd x - 1) * int p) mod int p = fst x" using a by force
+    ultimately have "(fst x + (snd x - 1) * int p) div int p + 1 = snd x"
+      by (auto simp: semiring_numeral_div_class.div_less)
+    with h show "f_3 (g_3 x) = x" unfolding f_3_def g_3_def by simp
+  qed
+  show "inj_on g_3 ((Res_h p) \<times> (Res_l q))" apply (rule inj_onI[of "(Res_h p) \<times> (Res_l q)" g_3])
+  proof -
+    fix x y
+    assume "x \<in> ((Res_h p) \<times> (Res_l q))" "y \<in> ((Res_h p) \<times> (Res_l q))" "g_3 x = g_3 y"
+    thus "x = y" using h1[of x] h1[of y] by presburger
+  qed
+next
+  show "g_3 ` ((Res_h p) \<times> (Res_l q)) \<subseteq> BuDuF"
+  proof
+    fix y
+    assume "y \<in> g_3 ` ((Res_h p) \<times> (Res_l q))"
+    then obtain x where x: "y = g_3 x" "x \<in> (Res_h p) \<times> (Res_l q)" by blast
+    hence "snd x \<le> (int q - 1) div 2" by force
+    moreover have "int p * ((int q - 1) div 2) = (int p * int q - int p) div 2"
+      using int_distrib(4) zdiv_zmult1_eq[of "int p" "int q - 1" 2] odd_q by fastforce
+    ultimately have "(snd x) * int p \<le> (int q * int p - int p) div 2"
+      using mult_right_mono[of "snd x" "(int q - 1) div 2" p] mult.commute[of "(int q - 1) div 2" p]
+        pq_commute by presburger
+    hence "(snd x - 1) * int p \<le> (int q * int p - 1) div 2 - int p"
+      using p_ge_0 int_distrib(3) by auto
+    moreover have "fst x \<le> int p - 1" using x by force
+    ultimately have "fst x + (snd x - 1) * int p \<le> (int p * int q - 1) div 2"
+      using pq_commute by linarith
+    moreover have "0 < fst x" "0 \<le> (snd x - 1) * p" using x(2) by fastforce+
+    ultimately show "y \<in> BuDuF" unfolding BuDuF_def using q_ge_0 x g_3_def x(1) by auto
+  qed
+next
+  show "finite BuDuF" unfolding BuDuF_def by fastforce
+qed (simp add: inj_on_inverseI[of BuDuF g_3] f_3_def g_3_def QR_lemma_05)+
+
+lemma QR_lemma_12: "b + d + m = r"
+proof -
+  have "B \<inter> D = {}" "finite B" "finite D" "B \<union> D = BuD" unfolding B_def D_def BuD_def by fastforce+
+  hence "b + d = card BuD" unfolding b_def d_def using card_Un_Int by fastforce
+  moreover have "BuD \<inter> F = {}" "finite BuD" "finite F" unfolding BuD_def F_def by fastforce+
+  moreover have "BuD \<union> F = BuDuF" unfolding BuD_def F_def BuDuF_def
+    using q_ge_0 ivl_disj_un_singleton(5)[of 0 "int q - 1"] by auto
+  ultimately show ?thesis using QR_lemma_03 QR_lemma_05 QR_lemma_11 card_Un_disjoint[of BuD F]
+    unfolding b_def d_def f_def by presburger
+qed
+
+lemma QR_lemma_13: "a + d + n = r"
+proof -
+  have "A = QR.B q p" unfolding A_def pq_commute using QRqp QR.B_def[of q p] by blast
+  hence "a = QR.b q p" using a_def QRqp QR.b_def[of q p] by presburger
+  moreover have "D = QR.D q p" unfolding D_def pq_commute using QRqp QR.D_def[of q p] by blast
+    hence "d = QR.d q p" using d_def  QRqp QR.d_def[of q p] by presburger
+  moreover have "n = QR.m q p" using n_def QRqp QR.m_def[of q p] by presburger
+  moreover have "r = QR.r q p" unfolding r_def using QRqp QR.r_def[of q p] by auto
+  ultimately show ?thesis using QRqp QR.QR_lemma_12 by presburger
+qed
+
+lemma QR_lemma_14: "(-1::int) ^ (m + n) = (-1) ^ r"
+proof -
+  have "m + n + 2 * d = r" using QR_lemma_06 QR_lemma_10 QR_lemma_12 QR_lemma_13 by auto
+  thus ?thesis using power_add[of "-1::int" "m + n" "2 * d"] by fastforce
+qed
+
+lemma Quadratic_Reciprocity:
+    "(Legendre p q) * (Legendre q p) = (-1::int) ^ ((p - 1) div 2 * ((q - 1) div 2))"
+  using Gpq Gqp GAUSS.gauss_lemma power_add[of "-1::int" m n] QR_lemma_14
+  unfolding r_def m_def n_def by auto
+
+end
+
+theorem Quadratic_Reciprocity: assumes "prime p" "2 < p" "prime q" "2 < q" "p \<noteq> q"
+  shows "(Legendre p q) * (Legendre q p) = (-1::int) ^ ((p - 1) div 2 * ((q - 1) div 2))"
+  using QR.Quadratic_Reciprocity QR_def assms by blast
+
+theorem Quadratic_Reciprocity_int: assumes "prime (nat p)" "2 < p" "prime (nat q)" "2 < q" "p \<noteq> q"
+  shows "(Legendre p q) * (Legendre q p) = (-1::int) ^ (nat ((p - 1) div 2 * ((q - 1) div 2)))"
+proof -
+  have "0 \<le> (p - 1) div 2" using assms by simp
+  moreover have "(nat p - 1) div 2 = nat ((p - 1) div 2)" "(nat q - 1) div 2 = nat ((q - 1) div 2)"
+    by fastforce+
+  ultimately have "(nat p - 1) div 2 * ((nat q - 1) div 2) = nat ((p - 1) div 2 * ((q - 1) div 2))"
+    using nat_mult_distrib by presburger
+  moreover have "2 < nat p" "2 < nat q" "nat p \<noteq> nat q" "int (nat p) = p" "int (nat q) = q"
+    using assms by linarith+
+  ultimately show ?thesis using Quadratic_Reciprocity[of "nat p" "nat q"] assms by presburger
+qed
+
+end
--- a/src/HOL/Number_Theory/document/root.tex	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Number_Theory/document/root.tex	Thu Oct 20 19:39:27 2016 +0200
@@ -1,6 +1,8 @@
 \documentclass[11pt,a4paper]{article}
 \usepackage{graphicx}
 \usepackage{isabelle,isabellesym}
+\usepackage{amssymb}
+\usepackage{amsmath}
 \usepackage{pdfsetup}
 
 \urlstyle{rm}
--- a/src/HOL/Orderings.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Orderings.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1437,6 +1437,17 @@
 apply (erule Least_le)
 done
 
+lemma exists_least_iff: "(\<exists>n. P n) \<longleftrightarrow> (\<exists>n. P n \<and> (\<forall>m < n. \<not> P m))" (is "?lhs \<longleftrightarrow> ?rhs")
+proof
+  assume ?rhs thus ?lhs by blast
+next
+  assume H: ?lhs then obtain n where n: "P n" by blast
+  let ?x = "Least P"
+  { fix m assume m: "m < ?x"
+    from not_less_Least[OF m] have "\<not> P m" . }
+  with LeastI_ex[OF H] show ?rhs by blast
+qed
+
 end
 
 
--- a/src/HOL/Probability/Distribution_Functions.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Probability/Distribution_Functions.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -36,11 +36,11 @@
   by (simp add: cdf_def)
 
 locale finite_borel_measure = finite_measure M for M :: "real measure" +
-  assumes M_super_borel: "sets borel \<subseteq> sets M"
+  assumes M_is_borel: "sets M = sets borel"
 begin
 
 lemma sets_M[intro]: "a \<in> sets borel \<Longrightarrow> a \<in> sets M"
-  using M_super_borel by auto
+  using M_is_borel by auto
 
 lemma cdf_diff_eq:
   assumes "x < y"
@@ -57,7 +57,7 @@
   unfolding cdf_def by (auto intro!: finite_measure_mono)
 
 lemma borel_UNIV: "space M = UNIV"
- by (metis in_mono sets.sets_into_space space_in_borel top_le M_super_borel)
+ by (metis in_mono sets.sets_into_space space_in_borel top_le M_is_borel)
 
 lemma cdf_nonneg: "cdf M x \<ge> 0"
   unfolding cdf_def by (rule measure_nonneg)
@@ -142,11 +142,17 @@
 end
 
 locale real_distribution = prob_space M for M :: "real measure" +
-  assumes events_eq_borel [simp, measurable_cong]: "sets M = sets borel" and space_eq_univ [simp]: "space M = UNIV"
+  assumes events_eq_borel [simp, measurable_cong]: "sets M = sets borel"
 begin
 
+lemma finite_borel_measure_M: "finite_borel_measure M"
+  by standard auto
+
 sublocale finite_borel_measure M
-  by standard auto
+  by (rule finite_borel_measure_M)
+
+lemma space_eq_univ [simp]: "space M = UNIV"
+  using events_eq_borel[THEN sets_eq_imp_space_eq] by simp
 
 lemma cdf_bounded_prob: "\<And>x. cdf M x \<le> 1"
   by (subst prob_space [symmetric], rule cdf_bounded)
@@ -167,20 +173,23 @@
   "random_variable borel X \<Longrightarrow> real_distribution (distr M borel X)"
   unfolding real_distribution_def real_distribution_axioms_def by (auto intro!: prob_space_distr)
 
-subsection \<open>uniqueness\<close>
+subsection \<open>Uniqueness\<close>
 
-lemma (in real_distribution) emeasure_Ioc:
+lemma (in finite_borel_measure) emeasure_Ioc:
   assumes "a \<le> b" shows "emeasure M {a <.. b} = cdf M b - cdf M a"
 proof -
   have "{a <.. b} = {..b} - {..a}"
     by auto
-  with \<open>a \<le> b\<close> show ?thesis
+  moreover have "{..x} \<in> sets M" for x
+    using atMost_borel[of x] M_is_borel by auto
+  moreover note \<open>a \<le> b\<close>
+  ultimately show ?thesis
     by (simp add: emeasure_eq_measure finite_measure_Diff cdf_def)
 qed
 
-lemma cdf_unique:
+lemma cdf_unique':
   fixes M1 M2
-  assumes "real_distribution M1" and "real_distribution M2"
+  assumes "finite_borel_measure M1" and "finite_borel_measure M2"
   assumes "cdf M1 = cdf M2"
   shows "M1 = M2"
 proof (rule measure_eqI_generator_eq[where \<Omega>=UNIV])
@@ -188,14 +197,56 @@
   then obtain a b where Xeq: "X = {a<..b}" by auto
   then show "emeasure M1 X = emeasure M2 X"
     by (cases "a \<le> b")
-       (simp_all add: assms(1,2)[THEN real_distribution.emeasure_Ioc] assms(3))
+       (simp_all add: assms(1,2)[THEN finite_borel_measure.emeasure_Ioc] assms(3))
 next
   show "(\<Union>i. {- real (i::nat)<..real i}) = UNIV"
     by (rule UN_Ioc_eq_UNIV)
-qed (auto simp: real_distribution.emeasure_Ioc[OF assms(1)]
-  assms(1,2)[THEN real_distribution.events_eq_borel] borel_sigma_sets_Ioc
+qed (auto simp: finite_borel_measure.emeasure_Ioc[OF assms(1)]
+  assms(1,2)[THEN finite_borel_measure.M_is_borel] borel_sigma_sets_Ioc
   Int_stable_def)
 
+lemma cdf_unique:
+  "real_distribution M1 \<Longrightarrow> real_distribution M2 \<Longrightarrow> cdf M1 = cdf M2 \<Longrightarrow> M1 = M2"
+  using cdf_unique'[of M1 M2] by (simp add: real_distribution.finite_borel_measure_M)
+
+lemma
+  fixes F :: "real \<Rightarrow> real"
+  assumes nondecF : "\<And> x y. x \<le> y \<Longrightarrow> F x \<le> F y"
+    and right_cont_F : "\<And>a. continuous (at_right a) F"
+    and lim_F_at_bot : "(F \<longlongrightarrow> 0) at_bot"
+    and lim_F_at_top : "(F \<longlongrightarrow> m) at_top"
+    and m: "0 \<le> m"
+  shows interval_measure_UNIV: "emeasure (interval_measure F) UNIV = m"
+    and finite_borel_measure_interval_measure: "finite_borel_measure (interval_measure F)"
+proof -
+  let ?F = "interval_measure F"
+  { have "ennreal (m - 0) = (SUP i::nat. ennreal (F (real i) - F (- real i)))"
+      by (intro LIMSEQ_unique[OF _ LIMSEQ_SUP] tendsto_ennrealI tendsto_intros
+                lim_F_at_bot[THEN filterlim_compose] lim_F_at_top[THEN filterlim_compose]
+                lim_F_at_bot[THEN filterlim_compose] filterlim_real_sequentially
+                filterlim_uminus_at_top[THEN iffD1])
+         (auto simp: incseq_def nondecF intro!: diff_mono)
+    also have "\<dots> = (SUP i::nat. emeasure ?F {- real i<..real i})"
+      by (subst emeasure_interval_measure_Ioc) (simp_all add: nondecF right_cont_F)
+    also have "\<dots> = emeasure ?F (\<Union>i::nat. {- real i<..real i})"
+      by (rule SUP_emeasure_incseq) (auto simp: incseq_def)
+    also have "(\<Union>i. {- real (i::nat)<..real i}) = space ?F"
+      by (simp add: UN_Ioc_eq_UNIV)
+    finally have "emeasure ?F (space ?F) = m"
+      by simp }
+  note * = this
+  then show "emeasure (interval_measure F) UNIV = m"
+    by simp
+
+  interpret finite_measure ?F
+  proof
+    show "emeasure ?F (space ?F) \<noteq> \<infinity>"
+      using * by simp
+  qed
+  show "finite_borel_measure (interval_measure F)"
+    proof qed simp_all
+qed
+
 lemma real_distribution_interval_measure:
   fixes F :: "real \<Rightarrow> real"
   assumes nondecF : "\<And> x y. x \<le> y \<Longrightarrow> F x \<le> F y" and
@@ -206,53 +257,47 @@
 proof -
   let ?F = "interval_measure F"
   interpret prob_space ?F
-  proof
-    have "ennreal (1 - 0) = (SUP i::nat. ennreal (F (real i) - F (- real i)))"
-      by (intro LIMSEQ_unique[OF _ LIMSEQ_SUP] tendsto_ennrealI tendsto_intros
-                lim_F_at_bot[THEN filterlim_compose] lim_F_at_top[THEN filterlim_compose]
-                lim_F_at_bot[THEN filterlim_compose] filterlim_real_sequentially
-                filterlim_uminus_at_top[THEN iffD1])
-         (auto simp: incseq_def nondecF intro!: diff_mono)
-    also have "\<dots> = (SUP i::nat. emeasure ?F {- real i<..real i})"
-      by (subst emeasure_interval_measure_Ioc) (simp_all add: nondecF right_cont_F)
-    also have "\<dots> = emeasure ?F (\<Union>i::nat. {- real i<..real i})"
-      by (rule SUP_emeasure_incseq) (auto simp: incseq_def)
-    also have "(\<Union>i. {- real (i::nat)<..real i}) = space ?F"
-      by (simp add: UN_Ioc_eq_UNIV)
-    finally show "emeasure ?F (space ?F) = 1"
-      by (simp add: one_ereal_def)
-  qed
+    proof qed (use interval_measure_UNIV[OF assms] in simp)
   show ?thesis
     proof qed simp_all
 qed
 
-lemma cdf_interval_measure:
+lemma
   fixes F :: "real \<Rightarrow> real"
   assumes nondecF : "\<And> x y. x \<le> y \<Longrightarrow> F x \<le> F y" and
     right_cont_F : "\<And>a. continuous (at_right a) F" and
-    lim_F_at_bot : "(F \<longlongrightarrow> 0) at_bot" and
-    lim_F_at_top : "(F \<longlongrightarrow> 1) at_top"
-  shows "cdf (interval_measure F) = F"
+    lim_F_at_bot : "(F \<longlongrightarrow> 0) at_bot"
+  shows emeasure_interval_measure_Iic: "emeasure (interval_measure F) {.. x} = F x"
+    and measure_interval_measure_Iic: "measure (interval_measure F) {.. x} = F x"
   unfolding cdf_def
-proof (intro ext)
-  interpret real_distribution "interval_measure F"
-    by (rule real_distribution_interval_measure) fact+
-  fix x
-  have "F x - 0 = measure (interval_measure F) (\<Union>i::nat. {-real i <.. x})"
-  proof (intro LIMSEQ_unique[OF _ finite_Lim_measure_incseq])
+proof -
+  have F_nonneg[simp]: "0 \<le> F y" for y
+    using lim_F_at_bot by (rule tendsto_upperbound) (auto simp: eventually_at_bot_linorder nondecF intro!: exI[of _ y])
+
+  have "emeasure (interval_measure F) (\<Union>i::nat. {-real i <.. x}) = F x - ennreal 0"
+  proof (intro LIMSEQ_unique[OF Lim_emeasure_incseq])
     have "(\<lambda>i. F x - F (- real i)) \<longlonglongrightarrow> F x - 0"
       by (intro tendsto_intros lim_F_at_bot[THEN filterlim_compose] filterlim_real_sequentially
                 filterlim_uminus_at_top[THEN iffD1])
-    then show "(\<lambda>i. measure (interval_measure F) {- real i<..x}) \<longlonglongrightarrow> F x - 0"
-      apply (rule filterlim_cong[OF refl refl, THEN iffD1, rotated])
+    from tendsto_ennrealI[OF this]
+    show "(\<lambda>i. emeasure (interval_measure F) {- real i<..x}) \<longlonglongrightarrow> F x - ennreal 0"
+      apply (rule filterlim_cong[THEN iffD1, rotated 3])
+        apply simp
+       apply simp
       apply (rule eventually_sequentiallyI[where c="nat (ceiling (- x))"])
-      apply (simp add: measure_interval_measure_Ioc right_cont_F nondecF)
+      apply (simp add: emeasure_interval_measure_Ioc right_cont_F nondecF)
       done
   qed (auto simp: incseq_def)
   also have "(\<Union>i::nat. {-real i <.. x}) = {..x}"
     by auto (metis minus_minus neg_less_iff_less reals_Archimedean2)
-  finally show "measure (interval_measure F) {..x} = F x"
+  finally show "emeasure (interval_measure F) {..x} = F x"
     by simp
+  then show "measure (interval_measure F) {..x} = F x"
+    by (simp add: measure_def)
 qed
 
+lemma cdf_interval_measure:
+  "(\<And> x y. x \<le> y \<Longrightarrow> F x \<le> F y) \<Longrightarrow> (\<And>a. continuous (at_right a) F) \<Longrightarrow> (F \<longlongrightarrow> 0) at_bot \<Longrightarrow> cdf (interval_measure F) = F"
+  by (simp add: cdf_def fun_eq_iff measure_interval_measure_Iic)
+
 end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Probability/Essential_Supremum.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,199 @@
+(*  Author:  Sébastien Gouëzel   sebastien.gouezel@univ-rennes1.fr
+    License: BSD
+*)
+
+theory Essential_Supremum
+imports "../Analysis/Analysis"
+begin
+
+section {*The essential supremum*}
+
+text {*In this paragraph, we define the essential supremum and give its basic properties. The
+essential supremum of a function is its maximum value if one is allowed to throw away a set
+of measure $0$. It is convenient to define it to be infinity for non-measurable functions, as
+it allows for neater statements in general. This is a prerequisiste to define the space $L^\infty$.*}
+
+definition esssup::"'a measure \<Rightarrow> ('a \<Rightarrow> 'b::{second_countable_topology, dense_linorder, linorder_topology, complete_linorder}) \<Rightarrow> 'b"
+  where "esssup M f = (if f \<in> borel_measurable M then Inf {z. emeasure M {x \<in> space M. f x > z} = 0} else top)"
+
+lemma esssup_zero_measure:
+  "emeasure M {x \<in> space M. f x > esssup M f} = 0"
+proof (cases "esssup M f = top")
+  case True
+  then show ?thesis by auto
+next
+  case False
+  then have [measurable]: "f \<in> borel_measurable M" unfolding esssup_def by meson
+  have "esssup M f < top" using False by (auto simp: less_top)
+  have *: "{x \<in> space M. f x > z} \<in> null_sets M" if "z > esssup M f" for z
+  proof -
+    have "\<exists>w. w < z \<and> emeasure M {x \<in> space M. f x > w} = 0"
+      using `z > esssup M f` unfolding esssup_def apply auto
+      by (metis (mono_tags, lifting) Inf_less_iff mem_Collect_eq)
+    then obtain w where "w < z" "emeasure M {x \<in> space M. f x > w} = 0" by auto
+    then have a: "{x \<in> space M. f x > w} \<in> null_sets M" by auto
+    have b: "{x \<in> space M. f x > z} \<subseteq> {x \<in> space M. f x > w}" using `w < z` by auto
+    show ?thesis using null_sets_subset[OF a _ b] by simp
+  qed
+  obtain u::"nat \<Rightarrow> 'b" where u: "\<And>n. u n > esssup M f" "u \<longlonglongrightarrow> esssup M f"
+    using approx_from_above_dense_linorder[OF `esssup M f < top`] by auto
+  have "{x \<in> space M. f x > esssup M f} = (\<Union>n. {x \<in> space M. f x > u n})"
+    using u apply auto
+    apply (metis (mono_tags, lifting) order_tendsto_iff eventually_mono LIMSEQ_unique)
+    using less_imp_le less_le_trans by blast
+  also have "... \<in> null_sets M"
+    using *[OF u(1)] by auto
+  finally show ?thesis by auto
+qed
+
+lemma esssup_AE:
+  "AE x in M. f x \<le> esssup M f"
+proof (cases "f \<in> borel_measurable M")
+  case True
+  show ?thesis
+    apply (rule AE_I[OF _ esssup_zero_measure[of _ f]]) using True by auto
+next
+  case False
+  then have "esssup M f = top" unfolding esssup_def by auto
+  then show ?thesis by auto
+qed
+
+lemma esssup_pos_measure:
+  assumes "f \<in> borel_measurable M" "z < esssup M f"
+  shows "emeasure M {x \<in> space M. f x > z} > 0"
+using assms Inf_less_iff mem_Collect_eq not_gr_zero unfolding esssup_def by force
+
+lemma esssup_non_measurable:
+  assumes "f \<notin> borel_measurable M"
+  shows "esssup M f = top"
+using assms unfolding esssup_def by auto
+
+lemma esssup_I [intro]:
+  assumes "f \<in> borel_measurable M" "AE x in M. f x \<le> c"
+  shows "esssup M f \<le> c"
+proof -
+  have "emeasure M {x \<in> space M. \<not> f x \<le> c} = 0"
+    apply (rule AE_E2[OF assms(2)]) using assms(1) by simp
+  then have *: "emeasure M {x \<in> space M. f x > c} = 0"
+    by (metis (mono_tags, lifting) Collect_cong not_less)
+  show ?thesis unfolding esssup_def using assms apply simp by (rule Inf_lower, simp add: *)
+qed
+
+lemma esssup_AE_mono:
+  assumes "f \<in> borel_measurable M" "AE x in M. f x \<le> g x"
+  shows "esssup M f \<le> esssup M g"
+proof (cases "g \<in> borel_measurable M")
+  case False
+  then show ?thesis unfolding esssup_def by auto
+next
+  case True
+  have "AE x in M. f x \<le> esssup M g"
+    using assms(2) esssup_AE[of g M] by auto
+  then show ?thesis using esssup_I assms(1) by auto
+qed
+
+lemma esssup_mono:
+  assumes "f \<in> borel_measurable M" "\<And>x. f x \<le> g x"
+  shows "esssup M f \<le> esssup M g"
+apply (rule esssup_AE_mono) using assms by auto
+
+lemma esssup_AE_cong:
+  assumes [measurable]: "f \<in> borel_measurable M" "g \<in> borel_measurable M"
+      and "AE x in M. f x = g x"
+  shows "esssup M f = esssup M g"
+proof -
+  have "esssup M f \<le> esssup M g"
+    using esssup_AE_mono[OF assms(1), of g] assms(3) by (simp add: eq_iff)
+  moreover have "esssup M g \<le> esssup M f"
+    using esssup_AE_mono[OF assms(2), of f] assms(3) by (simp add: eq_iff)
+  ultimately show ?thesis by simp
+qed
+
+lemma esssup_const:
+  assumes "emeasure M (space M) \<noteq> 0"
+  shows "esssup M (\<lambda>x. c) = c"
+proof -
+  have "emeasure M {x \<in> space M. (\<lambda>x. c) x > z} = (if c > z then emeasure M (space M) else 0)" for z
+    by auto
+  then have "{z. emeasure M {x \<in> space M. (\<lambda>x. c) x > z} = 0} = {c..}" using assms by auto
+  then have "esssup M (\<lambda>x. c) = Inf {c..}" unfolding esssup_def by auto
+  then show ?thesis by auto
+qed
+
+lemma esssup_cmult:
+  assumes "c > (0::real)"
+  shows "esssup M (\<lambda>x. c * f x::ereal) = c * esssup M f"
+proof (cases "f \<in> borel_measurable M")
+  case True
+  then have a [measurable]: "f \<in> borel_measurable M" by simp
+  then have b [measurable]: "(\<lambda>x. c * f x) \<in> borel_measurable M" by simp
+  have a: "{x \<in> space M. c * z < c * f x} = {x \<in> space M. z < f x}" for z::ereal
+    by (meson assms ereal_less(2) ereal_mult_left_mono ereal_mult_strict_left_mono less_ereal.simps(4) less_imp_le not_less)
+  have *: "{z::ereal. emeasure M {x \<in> space M. ereal c * f x > z} = 0} = {c * z| z::ereal. emeasure M {x \<in> space M. f x > z} = 0}"
+  proof (auto)
+    fix y assume *: "emeasure M {x \<in> space M. y < c * f x} = 0"
+    define z where "z = y / c"
+    have **: "y = c * z" unfolding z_def using assms by (simp add: ereal_mult_divide)
+    then have "y = c * z \<and> emeasure M {x \<in> space M. z < f x} = 0"
+      using * unfolding ** unfolding a by auto
+    then show "\<exists>z. y = ereal c * z \<and> emeasure M {x \<in> space M. z < f x} = 0"
+      by auto
+  next
+    fix z assume *: "emeasure M {x \<in> space M. z < f x} = 0"
+    then show "emeasure M {x \<in> space M. c * z < c * f x} = 0"
+        using a by auto
+  qed
+  have "esssup M (\<lambda>x. c * f x) = Inf {z::ereal. emeasure M {x \<in> space M. c * f x > z} = 0}"
+    unfolding esssup_def using b by auto
+  also have "... = Inf {c * z| z::ereal. emeasure M {x \<in> space M. f x > z} = 0}"
+    using * by auto
+  also have "... = ereal c * Inf {z. emeasure M {x \<in> space M. f x > z} = 0}"
+    apply (rule ereal_Inf_cmult) using assms by auto
+  also have "... = c * esssup M f"
+    unfolding esssup_def by auto
+  finally show ?thesis by simp
+next
+  case False
+  have "esssup M f = top" using False unfolding esssup_def by auto
+  then have *: "c * esssup M f = \<infinity>" using assms by (simp add: ennreal_mult_eq_top_iff top_ereal_def)
+  have "(\<lambda>x. c * f x) \<notin> borel_measurable M"
+  proof (rule ccontr)
+    assume "\<not> (\<lambda>x. c * f x) \<notin> borel_measurable M"
+    then have [measurable]: "(\<lambda>x. c * f x) \<in> borel_measurable M" by simp
+    then have "(\<lambda>x. (1/c) * (c * f x)) \<in> borel_measurable M" by measurable
+    moreover have "(1/c) * (c * f x) = f x" for x
+      by (metis "*" PInfty_neq_ereal(1) divide_inverse divide_self_if ereal_zero_mult mult.assoc mult.commute mult.left_neutral one_ereal_def times_ereal.simps(1) zero_ereal_def)
+    ultimately show False using False by auto
+  qed
+  then have "esssup M (\<lambda>x. c * f x) = \<infinity>" unfolding esssup_def by (simp add: top_ereal_def)
+  then show ?thesis using * by auto
+qed
+
+lemma esssup_add:
+  "esssup M (\<lambda>x. f x + g x::ereal) \<le> esssup M f + esssup M g"
+proof (cases "f \<in> borel_measurable M \<and> g \<in> borel_measurable M")
+  case True
+  then have [measurable]: "(\<lambda>x. f x + g x) \<in> borel_measurable M" by auto
+  have "f x + g x \<le> esssup M f + esssup M g" if "f x \<le> esssup M f" "g x \<le> esssup M g" for x
+    using that ereal_add_mono by auto
+  then have "AE x in M. f x + g x \<le> esssup M f + esssup M g"
+    using esssup_AE[of f M] esssup_AE[of g M] by auto
+  then show ?thesis using esssup_I by auto
+next
+  case False
+  then have "esssup M f + esssup M g = \<infinity>" unfolding esssup_def top_ereal_def by auto
+  then show ?thesis by auto
+qed
+
+lemma esssup_zero_space:
+  assumes "emeasure M (space M) = 0"
+          "f \<in> borel_measurable M"
+  shows "esssup M f = (- \<infinity>::ereal)"
+proof -
+  have "emeasure M {x \<in> space M. f x > - \<infinity>} = 0"
+    using assms(1) emeasure_mono emeasure_eq_0 by fastforce
+  then show ?thesis unfolding esssup_def using assms(2) Inf_eq_MInfty by auto
+qed
+
+end
+
--- a/src/HOL/Probability/Giry_Monad.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Probability/Giry_Monad.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -1778,4 +1778,10 @@
   shows "space (M \<bind> f) = space B"
   using M by (intro space_bind[OF sets_kernel[OF f]]) auto
 
+lemma bind_distr_return:
+  "f \<in> M \<rightarrow>\<^sub>M N \<Longrightarrow> g \<in> N \<rightarrow>\<^sub>M L \<Longrightarrow> space M \<noteq> {} \<Longrightarrow>
+    distr M N f \<bind> (\<lambda>x. return L (g x)) = distr M L (\<lambda>x. g (f x))"
+  by (subst bind_distr[OF _ measurable_compose[OF _ return_measurable]])
+     (auto intro!: bind_return_distr')
+
 end
--- a/src/HOL/Probability/Probability.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Probability/Probability.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -12,6 +12,8 @@
   SPMF
   Stream_Space
   Conditional_Expectation
+  Essential_Supremum
+  Stopping_Time
 begin
 
 end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Probability/Stopping_Time.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,262 @@
+(* Author: Johannes Hölzl <hoelzl@in.tum.de> *)
+
+section {* Stopping times *}
+
+theory Stopping_Time
+  imports "../Analysis/Analysis"
+begin
+
+subsection \<open>Stopping Time\<close>
+
+text \<open>This is also called strong stopping time. Then stopping time is T with alternative is
+  \<open>T x < t\<close> measurable.\<close>
+
+definition stopping_time :: "('t::linorder \<Rightarrow> 'a measure) \<Rightarrow> ('a \<Rightarrow> 't) \<Rightarrow> bool"
+where
+  "stopping_time F T = (\<forall>t. Measurable.pred (F t) (\<lambda>x. T x \<le> t))"
+
+lemma stopping_time_cong: "(\<And>t x. x \<in> space (F t) \<Longrightarrow> T x = S x) \<Longrightarrow> stopping_time F T = stopping_time F S"
+  unfolding stopping_time_def by (intro arg_cong[where f=All] ext measurable_cong) simp
+
+lemma stopping_timeD: "stopping_time F T \<Longrightarrow> Measurable.pred (F t) (\<lambda>x. T x \<le> t)"
+  by (auto simp: stopping_time_def)
+
+lemma stopping_timeD2: "stopping_time F T \<Longrightarrow> Measurable.pred (F t) (\<lambda>x. t < T x)"
+  unfolding not_le[symmetric] by (auto intro: stopping_timeD Measurable.pred_intros_logic)
+
+lemma stopping_timeI[intro?]: "(\<And>t. Measurable.pred (F t) (\<lambda>x. T x \<le> t)) \<Longrightarrow> stopping_time F T"
+  by (auto simp: stopping_time_def)
+
+lemma measurable_stopping_time:
+  fixes T :: "'a \<Rightarrow> 't::{linorder_topology, second_countable_topology}"
+  assumes T: "stopping_time F T"
+    and M: "\<And>t. sets (F t) \<subseteq> sets M" "\<And>t. space (F t) = space M"
+  shows "T \<in> M \<rightarrow>\<^sub>M borel"
+proof (rule borel_measurableI_le)
+  show "{x \<in> space M. T x \<le> t} \<in> sets M" for t
+    using stopping_timeD[OF T] M by (auto simp: Measurable.pred_def)
+qed
+
+lemma stopping_time_const: "stopping_time F (\<lambda>x. c)"
+  by (auto simp: stopping_time_def)
+
+lemma stopping_time_min:
+  "stopping_time F T \<Longrightarrow> stopping_time F S \<Longrightarrow> stopping_time F (\<lambda>x. min (T x) (S x))"
+  by (auto simp: stopping_time_def min_le_iff_disj intro!: pred_intros_logic)
+
+lemma stopping_time_max:
+  "stopping_time F T \<Longrightarrow> stopping_time F S \<Longrightarrow> stopping_time F (\<lambda>x. max (T x) (S x))"
+  by (auto simp: stopping_time_def intro!: pred_intros_logic)
+
+section \<open>Filtration\<close>
+
+locale filtration =
+  fixes \<Omega> :: "'a set" and F :: "'t::{linorder_topology, second_countable_topology} \<Rightarrow> 'a measure"
+  assumes space_F: "\<And>i. space (F i) = \<Omega>"
+  assumes sets_F_mono: "\<And>i j. i \<le> j \<Longrightarrow> sets (F i) \<le> sets (F j)"
+begin
+
+subsection \<open>$\sigma$-algebra of a Stopping Time\<close>
+
+definition pre_sigma :: "('a \<Rightarrow> 't) \<Rightarrow> 'a measure"
+where
+  "pre_sigma T = sigma \<Omega> {A. \<forall>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)}"
+
+lemma space_pre_sigma: "space (pre_sigma T) = \<Omega>"
+  unfolding pre_sigma_def using sets.space_closed[of "F _"]
+  by (intro space_measure_of) (auto simp: space_F)
+
+lemma measure_pre_sigma[simp]: "emeasure (pre_sigma T) = (\<lambda>_. 0)"
+  by (simp add: pre_sigma_def emeasure_sigma)
+
+lemma sigma_algebra_pre_sigma:
+  assumes T: "stopping_time F T"
+  shows "sigma_algebra \<Omega> {A. \<forall>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)}"
+  unfolding sigma_algebra_iff2
+proof (intro sigma_algebra_iff2[THEN iffD2] conjI ballI allI impI CollectI)
+  show "{A. \<forall>t. {\<omega> \<in> A. T \<omega> \<le> t} \<in> sets (F t)} \<subseteq> Pow \<Omega>"
+    using sets.space_closed[of "F _"] by (auto simp: space_F)
+next
+  fix A t assume "A \<in> {A. \<forall>t. {\<omega> \<in> A. T \<omega> \<le> t} \<in> sets (F t)}"
+  then have "{\<omega> \<in> space (F t). T \<omega> \<le> t} - {\<omega> \<in> A. T \<omega> \<le> t} \<in> sets (F t)"
+    using T stopping_timeD[measurable] by auto
+  also have "{\<omega> \<in> space (F t). T \<omega> \<le> t} - {\<omega> \<in> A. T \<omega> \<le> t} = {\<omega> \<in> \<Omega> - A. T \<omega> \<le> t}"
+    by (auto simp: space_F)
+  finally show "{\<omega> \<in> \<Omega> - A. T \<omega> \<le> t} \<in> sets (F t)" .
+next
+  fix AA :: "nat \<Rightarrow> 'a set" and t assume "range AA \<subseteq> {A. \<forall>t. {\<omega> \<in> A. T \<omega> \<le> t} \<in> sets (F t)}"
+  then have "(\<Union>i. {\<omega> \<in> AA i. T \<omega> \<le> t}) \<in> sets (F t)" for t
+    by auto
+  also have "(\<Union>i. {\<omega> \<in> AA i. T \<omega> \<le> t}) = {\<omega> \<in> UNION UNIV AA. T \<omega> \<le> t}"
+    by auto
+  finally show "{\<omega> \<in> UNION UNIV AA. T \<omega> \<le> t} \<in> sets (F t)" .
+qed auto
+
+lemma sets_pre_sigma: "stopping_time F T \<Longrightarrow> sets (pre_sigma T) = {A. \<forall>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)}"
+  unfolding pre_sigma_def by (rule sigma_algebra.sets_measure_of_eq[OF sigma_algebra_pre_sigma])
+
+lemma sets_pre_sigmaI: "stopping_time F T \<Longrightarrow> (\<And>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)) \<Longrightarrow> A \<in> sets (pre_sigma T)"
+  unfolding sets_pre_sigma by auto
+
+lemma pred_pre_sigmaI:
+  assumes T: "stopping_time F T"
+  shows "(\<And>t. Measurable.pred (F t) (\<lambda>\<omega>. P \<omega> \<and> T \<omega> \<le> t)) \<Longrightarrow> Measurable.pred (pre_sigma T) P"
+  unfolding pred_def space_F space_pre_sigma by (intro sets_pre_sigmaI[OF T]) simp
+
+lemma sets_pre_sigmaD: "stopping_time F T \<Longrightarrow> A \<in> sets (pre_sigma T) \<Longrightarrow> {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)"
+  unfolding sets_pre_sigma by auto
+
+lemma stopping_time_le_const: "stopping_time F T \<Longrightarrow> s \<le> t \<Longrightarrow> Measurable.pred (F t) (\<lambda>\<omega>. T \<omega> \<le> s)"
+  using stopping_timeD[of F T] sets_F_mono[of _ t] by (auto simp: pred_def space_F)
+
+lemma measurable_stopping_time_pre_sigma:
+  assumes T: "stopping_time F T" shows "T \<in> pre_sigma T \<rightarrow>\<^sub>M borel"
+proof (intro borel_measurableI_le sets_pre_sigmaI[OF T])
+  fix t t'
+  have "{\<omega>\<in>space (F (min t' t)). T \<omega> \<le> min t' t} \<in> sets (F (min t' t))"
+    using T unfolding pred_def[symmetric] by (rule stopping_timeD)
+  also have "\<dots> \<subseteq> sets (F t)"
+    by (rule sets_F_mono) simp
+  finally show "{\<omega> \<in> {x \<in> space (pre_sigma T). T x \<le> t'}. T \<omega> \<le> t} \<in> sets (F t)"
+    by (simp add: space_pre_sigma space_F)
+qed
+
+lemma mono_pre_sigma:
+  assumes T: "stopping_time F T" and S: "stopping_time F S"
+    and le: "\<And>\<omega>. \<omega> \<in> \<Omega> \<Longrightarrow> T \<omega> \<le> S \<omega>"
+  shows "sets (pre_sigma T) \<subseteq> sets (pre_sigma S)"
+  unfolding sets_pre_sigma[OF S] sets_pre_sigma[OF T]
+proof safe
+  interpret sigma_algebra \<Omega> "{A. \<forall>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)}"
+    using T by (rule sigma_algebra_pre_sigma)
+  fix A t assume A: "\<forall>t. {\<omega>\<in>A. T \<omega> \<le> t} \<in> sets (F t)"
+  then have "A \<subseteq> \<Omega>"
+    using sets_into_space by auto
+  from A have "{\<omega>\<in>A. T \<omega> \<le> t} \<inter> {\<omega>\<in>space (F t). S \<omega> \<le> t} \<in> sets (F t)"
+    using stopping_timeD[OF S] by (auto simp: pred_def)
+  also have "{\<omega>\<in>A. T \<omega> \<le> t} \<inter> {\<omega>\<in>space (F t). S \<omega> \<le> t} = {\<omega>\<in>A. S \<omega> \<le> t}"
+    using \<open>A \<subseteq> \<Omega>\<close> sets_into_space[of A] le by (auto simp: space_F intro: order_trans)
+  finally show "{\<omega>\<in>A. S \<omega> \<le> t} \<in> sets (F t)"
+    by auto
+qed
+
+lemma stopping_time_less_const:
+  assumes T: "stopping_time F T" shows "Measurable.pred (F t) (\<lambda>\<omega>. T \<omega> < t)"
+proof -
+  guess D :: "'t set" by (rule countable_dense_setE)
+  note D = this
+  show ?thesis
+  proof cases
+    assume *: "\<forall>t'<t. \<exists>t''. t' < t'' \<and> t'' < t"
+    { fix t' assume "t' < t"
+      with * have "{t' <..< t} \<noteq> {}"
+        by fastforce
+      with D(2)[OF _ this]
+      have "\<exists>d\<in>D. t'< d \<and> d < t"
+        by auto }
+    note ** = this
+
+    show ?thesis
+    proof (rule measurable_cong[THEN iffD2])
+      show "T \<omega> < t \<longleftrightarrow> (\<exists>r\<in>{r\<in>D. r < t}. T \<omega> \<le> r)" for \<omega>
+        by (auto dest: ** intro: less_imp_le)
+      show "Measurable.pred (F t) (\<lambda>w. \<exists>r\<in>{r \<in> D. r < t}. T w \<le> r)"
+        by (intro measurable_pred_countable stopping_time_le_const[OF T] countable_Collect D) auto
+    qed
+  next
+    assume "\<not> (\<forall>t'<t. \<exists>t''. t' < t'' \<and> t'' < t)"
+    then obtain t' where t': "t' < t" "\<And>t''. t'' < t \<Longrightarrow> t'' \<le> t'"
+      by (auto simp: not_less[symmetric])
+    show ?thesis
+    proof (rule measurable_cong[THEN iffD2])
+      show "T \<omega> < t \<longleftrightarrow> T \<omega> \<le> t'" for \<omega>
+        using t' by auto
+      show "Measurable.pred (F t) (\<lambda>w. T w \<le> t')"
+        using \<open>t'<t\<close> by (intro stopping_time_le_const[OF T]) auto
+    qed
+  qed
+qed
+
+lemma stopping_time_eq_const: "stopping_time F T \<Longrightarrow> Measurable.pred (F t) (\<lambda>\<omega>. T \<omega> = t)"
+  unfolding eq_iff using stopping_time_less_const[of T t]
+  by (intro pred_intros_logic stopping_time_le_const) (auto simp: not_less[symmetric] )
+
+lemma stopping_time_less:
+  assumes T: "stopping_time F T" and S: "stopping_time F S"
+  shows "Measurable.pred (pre_sigma T) (\<lambda>\<omega>. T \<omega> < S \<omega>)"
+proof (rule pred_pre_sigmaI[OF T])
+  fix t
+  obtain D :: "'t set"
+    where [simp]: "countable D" and semidense_D: "\<And>x y. x < y \<Longrightarrow> (\<exists>b\<in>D. x \<le> b \<and> b < y)"
+    using countable_separating_set_linorder2 by auto
+  show "Measurable.pred (F t) (\<lambda>\<omega>. T \<omega> < S \<omega> \<and> T \<omega> \<le> t)"
+  proof (rule measurable_cong[THEN iffD2])
+    let ?f = "\<lambda>\<omega>. if T \<omega> = t then \<not> S \<omega> \<le> t else \<exists>s\<in>{s\<in>D. s \<le> t}. T \<omega> \<le> s \<and> \<not> (S \<omega> \<le> s)"
+    { fix \<omega> assume "T \<omega> \<le> t" "T \<omega> \<noteq> t" "T \<omega> < S \<omega>"
+      then have "T \<omega> < min t (S \<omega>)"
+        by auto
+      then obtain r where "r \<in> D" "T \<omega> \<le> r" "r < min t (S \<omega>)"
+        by (metis semidense_D)
+      then have "\<exists>s\<in>{s\<in>D. s \<le> t}. T \<omega> \<le> s \<and> s < S \<omega>"
+        by auto }
+    then show "(T \<omega> < S \<omega> \<and> T \<omega> \<le> t) = ?f \<omega>" for \<omega>
+      by (auto simp: not_le)
+    show "Measurable.pred (F t) ?f"
+      by (intro pred_intros_logic measurable_If measurable_pred_countable countable_Collect
+                stopping_time_le_const predE stopping_time_eq_const T S)
+         auto
+  qed
+qed
+
+end
+
+lemma stopping_time_SUP_enat:
+  fixes T :: "nat \<Rightarrow> ('a \<Rightarrow> enat)"
+  shows "(\<And>i. stopping_time F (T i)) \<Longrightarrow> stopping_time F (SUP i. T i)"
+  unfolding stopping_time_def SUP_apply SUP_le_iff by (auto intro!: pred_intros_countable)
+
+lemma less_eSuc_iff: "a < eSuc b \<longleftrightarrow> (a \<le> b \<and> a \<noteq> \<infinity>)"
+  by (cases a) auto
+
+lemma stopping_time_Inf_enat:
+  fixes F :: "enat \<Rightarrow> 'a measure"
+  assumes F: "filtration \<Omega> F"
+  assumes P: "\<And>i. Measurable.pred (F i) (P i)"
+  shows "stopping_time F (\<lambda>\<omega>. Inf {i. P i \<omega>})"
+proof (rule stopping_timeI, cases)
+  fix t :: enat assume "t = \<infinity>" then show "Measurable.pred (F t) (\<lambda>\<omega>. Inf {i. P i \<omega>} \<le> t)"
+    by auto
+next
+  fix t :: enat assume "t \<noteq> \<infinity>"
+  moreover
+  { fix i \<omega> assume "Inf {i. P i \<omega>} \<le> t"
+    with \<open>t \<noteq> \<infinity>\<close> have "(\<exists>i\<le>t. P i \<omega>)"
+      unfolding Inf_le_iff by (cases t) (auto elim!: allE[of _ "eSuc t"] simp: less_eSuc_iff) }
+  ultimately have *: "\<And>\<omega>. Inf {i. P i \<omega>} \<le> t \<longleftrightarrow> (\<exists>i\<in>{..t}. P i \<omega>)"
+    by (auto intro!: Inf_lower2)
+  show "Measurable.pred (F t) (\<lambda>\<omega>. Inf {i. P i \<omega>} \<le> t)"
+    unfolding * using filtration.sets_F_mono[OF F, of _ t] P
+    by (intro pred_intros_countable_bounded) (auto simp: pred_def filtration.space_F[OF F])
+qed
+
+lemma stopping_time_Inf_nat:
+  fixes F :: "nat \<Rightarrow> 'a measure"
+  assumes F: "filtration \<Omega> F"
+  assumes P: "\<And>i. Measurable.pred (F i) (P i)" and wf: "\<And>i \<omega>. \<omega> \<in> \<Omega> \<Longrightarrow> \<exists>n. P n \<omega>"
+  shows "stopping_time F (\<lambda>\<omega>. Inf {i. P i \<omega>})"
+  unfolding stopping_time_def
+proof (intro allI, subst measurable_cong)
+  fix t \<omega> assume "\<omega> \<in> space (F t)"
+  then have "\<omega> \<in> \<Omega>"
+    using filtration.space_F[OF F] by auto
+  from wf[OF this] have "((LEAST n. P n \<omega>) \<le> t) = (\<exists>i\<le>t. P i \<omega>)"
+    by (rule LeastI2_wellorder_ex) auto
+  then show "(Inf {i. P i \<omega>} \<le> t) = (\<exists>i\<in>{..t}. P i \<omega>)"
+    by (simp add: Inf_nat_def Bex_def)
+next
+  fix t from P show "Measurable.pred (F t) (\<lambda>w. \<exists>i\<in>{..t}. P i w)"
+    using filtration.sets_F_mono[OF F, of _ t]
+    by (intro pred_intros_countable_bounded) (auto simp: pred_def filtration.space_F[OF F])
+qed
+
+end
--- a/src/HOL/Probability/Stream_Space.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Probability/Stream_Space.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -446,6 +446,17 @@
     by (cases "xs = []") (auto simp: * space_stream_space del: in_listsD)
 qed (auto simp: * ae sets_M del: in_listsD intro!: streams_sets)
 
+lemma sets_sstart[measurable]: "sstart \<Omega> xs \<in> sets (stream_space (count_space UNIV))"
+proof (induction xs)
+  case (Cons x xs)
+  note this[measurable]
+  have "sstart \<Omega> (x # xs) = {\<omega>\<in>space (stream_space (count_space UNIV)). \<omega> \<in> sstart \<Omega> (x # xs)}"
+    by (auto simp: space_stream_space)
+  also have "\<dots> \<in> sets (stream_space (count_space UNIV))"
+    unfolding in_sstart by measurable
+  finally show ?case .
+qed (auto intro!: streams_sets)
+
 primrec scylinder :: "'a set \<Rightarrow> 'a set list \<Rightarrow> 'a stream set"
 where
   "scylinder S [] = streams S"
--- a/src/HOL/Quotient_Examples/Quotient_Rat.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Quotient_Examples/Quotient_Rat.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -28,7 +28,7 @@
 quotient_type rat = "int \<times> int" / partial: ratrel
  using ratrel_equivp .
 
-instantiation rat :: "{zero, one, plus, uminus, minus, times, ord, abs_if, sgn_if}"
+instantiation rat :: "{zero, one, plus, uminus, minus, times, ord, abs, sgn}"
 begin
 
 quotient_definition
@@ -100,8 +100,7 @@
 definition
   sgn_rat_def: "sgn (i::rat) = (if i = 0 then 0 else if 0 < i then 1 else - 1)"
 
-instance by intro_classes
-  (auto simp add: rabs_rat_def sgn_rat_def)
+instance ..
 
 end
 
--- a/src/HOL/ROOT	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/ROOT	Thu Oct 20 19:39:27 2016 +0200
@@ -181,7 +181,7 @@
   theories [document = false]
     "Less_False"
     "~~/src/HOL/Library/Multiset"
-    "~~/src/HOL/Library/Float"
+    "~~/src/HOL/Number_Theory/Fib"
   theories
     Balance
     Tree_Map
--- a/src/HOL/Rings.thy	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Rings.thy	Thu Oct 20 19:39:27 2016 +0200
@@ -532,6 +532,100 @@
 
 end
 
+class idom_abs_sgn = idom + abs + sgn +
+  assumes sgn_mult_abs: "sgn a * \<bar>a\<bar> = a"
+    and sgn_sgn [simp]: "sgn (sgn a) = sgn a"
+    and abs_abs [simp]: "\<bar>\<bar>a\<bar>\<bar> = \<bar>a\<bar>"
+    and abs_0 [simp]: "\<bar>0\<bar> = 0"
+    and sgn_0 [simp]: "sgn 0 = 0"
+    and sgn_1 [simp]: "sgn 1 = 1"
+    and sgn_minus_1: "sgn (- 1) = - 1"
+    and sgn_mult: "sgn (a * b) = sgn a * sgn b"
+begin
+
+lemma sgn_eq_0_iff:
+  "sgn a = 0 \<longleftrightarrow> a = 0"
+proof -
+  { assume "sgn a = 0"
+    then have "sgn a * \<bar>a\<bar> = 0"
+      by simp
+    then have "a = 0"
+      by (simp add: sgn_mult_abs)
+  } then show ?thesis
+    by auto
+qed
+
+lemma abs_eq_0_iff:
+  "\<bar>a\<bar> = 0 \<longleftrightarrow> a = 0"
+proof -
+  { assume "\<bar>a\<bar> = 0"
+    then have "sgn a * \<bar>a\<bar> = 0"
+      by simp
+    then have "a = 0"
+      by (simp add: sgn_mult_abs)
+  } then show ?thesis
+    by auto
+qed
+
+lemma abs_mult_sgn:
+  "\<bar>a\<bar> * sgn a = a"
+  using sgn_mult_abs [of a] by (simp add: ac_simps)
+
+lemma abs_1 [simp]:
+  "\<bar>1\<bar> = 1"
+  using sgn_mult_abs [of 1] by simp
+
+lemma sgn_abs [simp]:
+  "\<bar>sgn a\<bar> = of_bool (a \<noteq> 0)"
+  using sgn_mult_abs [of "sgn a"] mult_cancel_left [of "sgn a" "\<bar>sgn a\<bar>" 1]
+  by (auto simp add: sgn_eq_0_iff)
+
+lemma abs_sgn [simp]:
+  "sgn \<bar>a\<bar> = of_bool (a \<noteq> 0)"
+  using sgn_mult_abs [of "\<bar>a\<bar>"] mult_cancel_right [of "sgn \<bar>a\<bar>" "\<bar>a\<bar>" 1]
+  by (auto simp add: abs_eq_0_iff)
+
+lemma abs_mult:
+  "\<bar>a * b\<bar> = \<bar>a\<bar> * \<bar>b\<bar>"
+proof (cases "a = 0 \<or> b = 0")
+  case True
+  then show ?thesis
+    by auto
+next
+  case False
+  then have *: "sgn (a * b) \<noteq> 0"
+    by (simp add: sgn_eq_0_iff)
+  from abs_mult_sgn [of "a * b"] abs_mult_sgn [of a] abs_mult_sgn [of b]
+  have "\<bar>a * b\<bar> * sgn (a * b) = \<bar>a\<bar> * sgn a * \<bar>b\<bar> * sgn b"
+    by (simp add: ac_simps)
+  then have "\<bar>a * b\<bar> * sgn (a * b) = \<bar>a\<bar> * \<bar>b\<bar> * sgn (a * b)"
+    by (simp add: sgn_mult ac_simps)
+  with * show ?thesis
+    by simp
+qed
+
+lemma sgn_minus [simp]:
+  "sgn (- a) = - sgn a"
+proof -
+  from sgn_minus_1 have "sgn (- 1 * a) = - 1 * sgn a"
+    by (simp only: sgn_mult)
+  then show ?thesis
+    by simp
+qed
+
+lemma abs_minus [simp]:
+  "\<bar>- a\<bar> = \<bar>a\<bar>"
+proof -
+  have [simp]: "\<bar>- 1\<bar> = 1"
+    using sgn_mult_abs [of "- 1"] by simp
+  then have "\<bar>- 1 * a\<bar> = 1 * \<bar>a\<bar>"
+    by (simp only: abs_mult)
+  then show ?thesis
+    by simp
+qed
+
+end
+
 text \<open>
   The theory of partially ordered rings is taken from the books:
     \<^item> \<^emph>\<open>Lattice Theory\<close> by Garret Birkhoff, American Mathematical Society, 1979
@@ -1599,6 +1693,9 @@
 
 end
 
+class abs_if = minus + uminus + ord + zero + abs +
+  assumes abs_if: "\<bar>a\<bar> = (if a < 0 then - a else a)"
+
 class linordered_ring = ring + linordered_semiring + linordered_ab_group_add + abs_if
 begin
 
@@ -1842,7 +1939,8 @@
 end
 
 class linordered_idom =
-  comm_ring_1 + linordered_comm_semiring_strict + ordered_ab_group_add + abs_if + sgn_if
+  comm_ring_1 + linordered_comm_semiring_strict + ordered_ab_group_add + abs_if + sgn +
+  assumes sgn_if: "sgn x = (if x = 0 then 0 else if 0 < x then 1 else - 1)"
 begin
 
 subclass linordered_semiring_1_strict ..
@@ -1857,6 +1955,10 @@
   show "b \<le> a \<Longrightarrow> a - b + b = a" for a b by simp
 qed
 
+subclass idom_abs_sgn
+  by standard
+    (auto simp add: sgn_if abs_if zero_less_mult_iff)
+
 lemma linorder_neqE_linordered_idom:
   assumes "x \<noteq> y"
   obtains "x < y" | "y < x"
@@ -1888,11 +1990,8 @@
 lemma mult_less_cancel_left2: "c * a < c \<longleftrightarrow> (0 \<le> c \<longrightarrow> a < 1) \<and> (c \<le> 0 \<longrightarrow> 1 < a)"
   using mult_less_cancel_left [of c a 1] by simp
 
-lemma sgn_sgn [simp]: "sgn (sgn a) = sgn a"
-  unfolding sgn_if by simp
-
 lemma sgn_0_0: "sgn a = 0 \<longleftrightarrow> a = 0"
-  unfolding sgn_if by simp
+  by (fact sgn_eq_0_iff)
 
 lemma sgn_1_pos: "sgn a = 1 \<longleftrightarrow> a > 0"
   unfolding sgn_if by simp
@@ -1906,9 +2005,6 @@
 lemma sgn_neg [simp]: "a < 0 \<Longrightarrow> sgn a = - 1"
   by (simp only: sgn_1_neg)
 
-lemma sgn_mult: "sgn (a * b) = sgn a * sgn b"
-  by (auto simp add: sgn_if zero_less_mult_iff)
-
 lemma abs_sgn: "\<bar>k\<bar> = k * sgn k"
   unfolding sgn_if abs_if by auto
 
@@ -1920,7 +2016,7 @@
 
 lemma abs_sgn_eq_1 [simp]:
   "a \<noteq> 0 \<Longrightarrow> \<bar>sgn a\<bar> = 1"
-  by (simp add: abs_if)
+  by simp
 
 lemma abs_sgn_eq: "\<bar>sgn a\<bar> = (if a = 0 then 0 else 1)"
   by (simp add: sgn_if)
@@ -2005,10 +2101,10 @@
 begin
 
 lemma mult_sgn_abs: "sgn x * \<bar>x\<bar> = x"
-  unfolding abs_if sgn_if by auto
+  by (fact sgn_mult_abs)
 
-lemma abs_one [simp]: "\<bar>1\<bar> = 1"
-  by (simp add: abs_if)
+lemma abs_one: "\<bar>1\<bar> = 1"
+  by (fact abs_1)
 
 end
 
@@ -2022,9 +2118,6 @@
 subclass ordered_ring_abs
   by standard (auto simp: abs_if not_less mult_less_0_iff)
 
-lemma abs_mult: "\<bar>a * b\<bar> = \<bar>a\<bar> * \<bar>b\<bar>"
-  by (rule abs_eq_mult) auto
-
 lemma abs_mult_self [simp]: "\<bar>a\<bar> * \<bar>a\<bar> = a * a"
   by (simp add: abs_if)
 
--- a/src/HOL/Tools/Nitpick/kodkod.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Tools/Nitpick/kodkod.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -1028,7 +1028,7 @@
           val outcome =
             let
               val code =
-                Isabelle_System.bash ("cd " ^ File.bash_string temp_dir ^ ";\n\
+                Isabelle_System.bash ("cd " ^ Bash.string temp_dir ^ ";\n\
                       \\"$KODKODI/bin/kodkodi\"" ^
                       (if ms >= 0 then " -max-msecs " ^ string_of_int ms
                        else "") ^
--- a/src/HOL/Tools/SMT/smt_solver.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/HOL/Tools/SMT/smt_solver.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -49,7 +49,7 @@
 local
 
 fun make_command command options problem_path proof_path =
-  "(exec 2>&1;" :: map File.bash_string (command () @ options) @
+  "(exec 2>&1;" :: map Bash.string (command () @ options) @
   [File.bash_path problem_path, ")", ">", File.bash_path proof_path]
   |> space_implode " "
 
--- a/src/Pure/Admin/build_doc.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/build_doc.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -78,7 +78,7 @@
 
       val getopts =
         Getopts("""
-Usage: isabelle build_doc [OPTIONS] [DOCS ...]"
+Usage: isabelle build_doc [OPTIONS] [DOCS ...]
 
   Options are:
     -a           select all documentation sessions
@@ -88,9 +88,9 @@
   Build Isabelle documentation from documentation sessions with
   suitable document_variants entry.
 """,
-        "a" -> (_ => all_docs = true),
-        "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
-        "s" -> (_ => system_mode = true))
+          "a" -> (_ => all_docs = true),
+          "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
+          "s" -> (_ => system_mode = true))
 
       val docs = getopts(args)
 
--- a/src/Pure/Admin/build_history.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/build_history.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -96,7 +96,7 @@
   /** build_history **/
 
   private val default_rev = "tip"
-  private val default_threads = 1
+  private val default_multicore = (1, 1)
   private val default_heap = 1000
   private val default_isabelle_identifier = "build_history"
 
@@ -109,12 +109,13 @@
     fresh: Boolean = false,
     nonfree: Boolean = false,
     multicore_base: Boolean = false,
-    threads_list: List[Int] = List(default_threads),
+    multicore_list: List[(Int, Int)] = List(default_multicore),
     arch_64: Boolean = false,
     heap: Int = default_heap,
     max_heap: Option[Int] = None,
     more_settings: List[String] = Nil,
     verbose: Boolean = false,
+    build_tags: List[String] = Nil,
     build_args: List[String] = Nil): List[(Process_Result, Path)] =
   {
     /* sanity checks */
@@ -122,7 +123,10 @@
     if (File.eq(Path.explode("~~"), hg.root))
       error("Repository coincides with ISABELLE_HOME=" + Path.explode("~~").expand)
 
-    for (threads <- threads_list if threads < 1) error("Bad threads value < 1: " + threads)
+    for ((threads, _) <- multicore_list if threads < 1)
+      error("Bad threads value < 1: " + threads)
+    for ((_, processes) <- multicore_list if processes < 1)
+      error("Bad processes value < 1: " + processes)
 
     if (heap < 100) error("Bad heap value < 100: " + heap)
 
@@ -146,11 +150,12 @@
 
     /* main */
 
+    val build_host = Isabelle_System.hostname()
     val build_history_date = Date.now()
-    val build_host = Isabelle_System.hostname()
+    val build_group_id = build_host + ":" + build_history_date.time.ms
 
     var first_build = true
-    for (threads <- threads_list) yield
+    for ((threads, processes) <- multicore_list) yield
     {
       /* init settings */
 
@@ -183,27 +188,34 @@
         Isabelle_System.copy_dir(isabelle_base_log, isabelle_output_log)
 
       val build_start = Date.now()
-      val res =
-        other_isabelle("build -v " + File.bash_args(build_args), redirect = true, echo = verbose)
+      val build_args1 = List("-v", "-j" + processes) ::: build_args
+      val build_result =
+        other_isabelle("build " + Bash.strings(build_args1), redirect = true, echo = verbose)
       val build_end = Date.now()
 
-
-      /* output log */
-
       val log_path =
         other_isabelle.isabelle_home_user +
           Build_Log.log_subdir(build_history_date) +
-          Build_Log.log_filename(
-            BUILD_HISTORY, build_history_date, build_host, ml_platform, "M" + threads)
+          Build_Log.log_filename(BUILD_HISTORY, build_history_date,
+            List(build_host, ml_platform, "M" + threads) ::: build_tags)
 
-      val build_info = Build_Log.Log_File(log_path.base.implode, res.out_lines).parse_build_info()
+      val build_info =
+        Build_Log.Log_File(log_path.base.implode, build_result.out_lines).parse_build_info()
+
+
+      /* output log */
 
       val meta_info =
-        List(Build_Log.Field.build_engine -> BUILD_HISTORY,
-          Build_Log.Field.build_host -> build_host,
-          Build_Log.Field.build_start -> Build_Log.print_date(build_start),
-          Build_Log.Field.build_end -> Build_Log.print_date(build_end),
-          Build_Log.Field.isabelle_version -> isabelle_version)
+        Build_Log.Prop.multiple(Build_Log.Prop.build_tags, build_tags) :::
+        Build_Log.Prop.multiple(Build_Log.Prop.build_args, build_args1) :::
+        List(
+          Build_Log.Prop.build_group_id -> build_group_id,
+          Build_Log.Prop.build_id -> (build_host + ":" + build_start.time.ms),
+          Build_Log.Prop.build_engine -> BUILD_HISTORY,
+          Build_Log.Prop.build_host -> build_host,
+          Build_Log.Prop.build_start -> Build_Log.print_date(build_start),
+          Build_Log.Prop.build_end -> Build_Log.print_date(build_end),
+          Build_Log.Prop.isabelle_version -> isabelle_version)
 
       val ml_statistics =
         build_info.finished_sessions.flatMap(session_name =>
@@ -228,7 +240,7 @@
       Isabelle_System.mkdirs(log_path.dir)
       File.write_xz(log_path.ext("xz"),
         terminate_lines(
-          Build_Log.Log_File.print_props(META_INFO_MARKER, meta_info) :: res.out_lines :::
+          Build_Log.Log_File.print_props(META_INFO_MARKER, meta_info) :: build_result.out_lines :::
           ml_statistics.map(Build_Log.Log_File.print_props(Build_Log.ML_STATISTICS_MARKER, _)) :::
           heap_sizes), XZ.options(6))
 
@@ -242,13 +254,26 @@
 
       first_build = false
 
-      (res, log_path.ext("xz"))
+      (build_result, log_path.ext("xz"))
     }
   }
 
 
   /* command line entry point */
 
+  private object Multicore
+  {
+    private val Pat1 = """^(\d+)$""".r
+    private val Pat2 = """^(\d+)x(\d+)$""".r
+
+    def parse(s: String): (Int, Int) =
+      s match {
+        case Pat1(Value.Int(x)) => (x, 1)
+        case Pat2(Value.Int(x), Value.Int(y)) => (x, y)
+        case _ => error("Bad multicore configuration: " + quote(s))
+      }
+  }
+
   def main(args: Array[String])
   {
     Command_Line.tool0 {
@@ -256,13 +281,14 @@
       var components_base = ""
       var heap: Option[Int] = None
       var max_heap: Option[Int] = None
-      var threads_list = List(default_threads)
+      var multicore_list = List(default_multicore)
       var isabelle_identifier = default_isabelle_identifier
       var more_settings: List[String] = Nil
       var fresh = false
       var arch_64 = false
       var nonfree = false
       var rev = default_rev
+      var build_tags = List.empty[String]
       var verbose = false
 
       val getopts = Getopts("""
@@ -272,7 +298,7 @@
     -B           first multicore build serves as base for scheduling information
     -C DIR       base directory for Isabelle components (default: $ISABELLE_HOME_USER/../contrib)
     -H SIZE      minimal ML heap in MB (default: """ + default_heap + """ for x86, """ + default_heap * 2 + """ for x86_64)
-    -M THREADS   multicore configurations (comma-separated list, default: """ + default_threads + """)
+    -M MULTICORE multicore configurations (see below)
     -N NAME      alternative ISABELLE_IDENTIFIER (default: """ + default_isabelle_identifier + """)
     -U SIZE      maximal ML heap in MB (default: unbounded)
     -e TEXT      additional text for generated etc/settings
@@ -280,15 +306,19 @@
     -m ARCH      processor architecture (32=x86, 64=x86_64, default: x86)
     -n           include nonfree components
     -r REV       update to revision (default: """ + default_rev + """)
+    -t TAG       free-form build tag (multiple occurrences possible)
     -v           verbose
 
   Build Isabelle sessions from the history of another REPOSITORY clone,
   passing ARGS directly to its isabelle build tool.
+
+  Each MULTICORE configuration consists of one or two numbers (default 1):
+  THREADS or THREADSxPROCESSES, e.g. -M 1,2,4 or -M 1x4,2x2,4.
 """,
         "B" -> (_ => multicore_base = true),
         "C:" -> (arg => components_base = arg),
         "H:" -> (arg => heap = Some(Value.Int.parse(arg))),
-        "M:" -> (arg => threads_list = space_explode(',', arg).map(Value.Int.parse(_))),
+        "M:" -> (arg => multicore_list = space_explode(',', arg).map(Multicore.parse(_))),
         "N:" -> (arg => isabelle_identifier = arg),
         "U:" -> (arg => max_heap = Some(Value.Int.parse(arg))),
         "e:" -> (arg => more_settings = more_settings ::: List(arg)),
@@ -301,6 +331,7 @@
           },
         "n" -> (_ => nonfree = true),
         "r:" -> (arg => rev = arg),
+        "t:" -> (arg => build_tags = build_tags ::: List(arg)),
         "v" -> (_ => verbose = true))
 
       val more_args = getopts(args)
@@ -315,10 +346,10 @@
       val results =
         build_history(hg, progress = progress, rev = rev, isabelle_identifier = isabelle_identifier,
           components_base = components_base, fresh = fresh, nonfree = nonfree,
-          multicore_base = multicore_base, threads_list = threads_list, arch_64 = arch_64,
+          multicore_base = multicore_base, multicore_list = multicore_list, arch_64 = arch_64,
           heap = heap.getOrElse(if (arch_64) default_heap * 2 else default_heap),
           max_heap = max_heap, more_settings = more_settings, verbose = verbose,
-          build_args = build_args)
+          build_tags = build_tags, build_args = build_args)
 
       for ((_, log_path) <- results)
         Output.writeln(log_path.implode, stdout = true)
@@ -342,7 +373,7 @@
     options: String = "",
     args: String = ""): List[(String, Bytes)] =
   {
-    val isabelle_admin = ssh.remote_path(isabelle_repos_self + Path.explode("Admin"))
+    val isabelle_admin = isabelle_repos_self + Path.explode("Admin")
 
 
     /* prepare repository clones */
@@ -353,19 +384,19 @@
     if (self_update) {
       isabelle_hg.pull()
       isabelle_hg.update(clean = true)
-      ssh.execute(File.bash_string(isabelle_admin + "/build") + " jars_fresh").check
+      ssh.execute(ssh.bash_path(isabelle_admin + Path.explode("build")) + " jars_fresh").check
     }
 
     Mercurial.setup_repository(
-      ssh.remote_path(isabelle_repos_self), isabelle_repos_other, ssh = Some(ssh))
+      ssh.bash_path(isabelle_repos_self), isabelle_repos_other, ssh = Some(ssh))
 
 
     /* Admin/build_history */
 
     val result =
       ssh.execute(
-        File.bash_string(isabelle_admin + "/build_history") + " " + options + " " +
-          File.bash_string(ssh.remote_path(isabelle_repos_other)) + " " + args,
+        ssh.bash_path(isabelle_admin + Path.explode("build_history")) + " " + options + " " +
+          ssh.bash_path(isabelle_repos_other) + " " + args,
         progress_stderr = progress.echo(_)).check
 
     for (line <- result.out_lines; log = Path.explode(line))
--- a/src/Pure/Admin/build_log.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/build_log.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -18,36 +18,32 @@
 
 object Build_Log
 {
-  /** directory content **/
+  /** content **/
+
+  /* properties */
 
-  /* file names */
+  object Prop
+  {
+    val separator = '\u000b'
+
+    def multiple(name: String, args: List[String]): Properties.T =
+      if (args.isEmpty) Nil
+      else List(name -> args.mkString(separator.toString))
 
-  def log_date(date: Date): String =
-    String.format(Locale.ROOT, "%s.%05d",
-      DateTimeFormatter.ofPattern("yyyy-MM-dd").format(date.rep),
-      new java.lang.Long((date.time - date.midnight.time).ms / 1000))
-
-  def log_subdir(date: Date): Path =
-    Path.explode("log") + Path.explode(date.rep.getYear.toString)
-
-  def log_filename(engine: String, date: Date, more: String*): Path =
-    Path.explode((engine :: log_date(date) :: more.toList).mkString("", "_", ".log"))
+    val build_tags = "build_tags"  // multiple
+    val build_args = "build_args"  // multiple
+    val build_group_id = "build_group_id"
+    val build_id = "build_id"
+    val build_engine = "build_engine"
+    val build_host = "build_host"
+    val build_start = "build_start"
+    val build_end = "build_end"
+    val isabelle_version = "isabelle_version"
+    val afp_version = "afp_version"
+  }
 
 
-  /* log file collections */
-
-  def is_log(file: JFile): Boolean =
-    List(".log", ".log.gz", ".log.xz").exists(ext => file.getName.endsWith(ext))
-
-  def isatest_files(dir: Path): List[JFile] =
-    File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("isatest-makeall-"))
-
-  def afp_test_files(dir: Path): List[JFile] =
-    File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("afp-test-devel-"))
-
-
-
-  /** settings **/
+  /* settings */
 
   object Settings
   {
@@ -78,6 +74,32 @@
   }
 
 
+  /* file names */
+
+  def log_date(date: Date): String =
+    String.format(Locale.ROOT, "%s.%05d",
+      DateTimeFormatter.ofPattern("yyyy-MM-dd").format(date.rep),
+      new java.lang.Long((date.time - date.midnight.time).ms / 1000))
+
+  def log_subdir(date: Date): Path =
+    Path.explode("log") + Path.explode(date.rep.getYear.toString)
+
+  def log_filename(engine: String, date: Date, more: List[String] = Nil): Path =
+    Path.explode((engine :: log_date(date) :: more).mkString("", "_", ".log"))
+
+
+  /* log file collections */
+
+  def is_log(file: JFile): Boolean =
+    List(".log", ".log.gz", ".log.xz").exists(ext => file.getName.endsWith(ext))
+
+  def isatest_files(dir: Path): List[JFile] =
+    File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("isatest-makeall-"))
+
+  def afp_test_files(dir: Path): List[JFile] =
+    File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("afp-test-devel-"))
+
+
 
   /** log file **/
 
@@ -245,16 +267,6 @@
 
   /** meta info **/
 
-  object Field
-  {
-    val build_engine = "build_engine"
-    val build_host = "build_host"
-    val build_start = "build_start"
-    val build_end = "build_end"
-    val isabelle_version = "isabelle_version"
-    val afp_version = "afp_version"
-  }
-
   object Meta_Info
   {
     val empty: Meta_Info = Meta_Info(Nil, Nil)
@@ -303,23 +315,28 @@
     def parse(engine: String, host: String, start: Date,
       End: Regex, Isabelle_Version: Regex, AFP_Version: Regex): Meta_Info =
     {
-      val build_engine = if (engine == "") Nil else List(Field.build_engine -> engine)
-      val build_host = if (host == "") Nil else List(Field.build_host -> host)
+      val build_id =
+      {
+        val prefix = if (host != "") host else if (engine != "") engine else ""
+        (if (prefix == "") "build" else prefix) + ":" + start.time.ms
+      }
+      val build_engine = if (engine == "") Nil else List(Prop.build_engine -> engine)
+      val build_host = if (host == "") Nil else List(Prop.build_host -> host)
 
-      val start_date = List(Field.build_start -> start.toString)
+      val start_date = List(Prop.build_start -> start.toString)
       val end_date =
         log_file.lines.last match {
           case End(log_file.Strict_Date(end_date)) =>
-            List(Field.build_end -> end_date.toString)
+            List(Prop.build_end -> end_date.toString)
           case _ => Nil
         }
 
       val isabelle_version =
-        log_file.find_match(Isabelle_Version).map(Field.isabelle_version -> _)
+        log_file.find_match(Isabelle_Version).map(Prop.isabelle_version -> _)
       val afp_version =
-        log_file.find_match(AFP_Version).map(Field.afp_version -> _)
+        log_file.find_match(AFP_Version).map(Prop.afp_version -> _)
 
-      Meta_Info(build_engine ::: build_host :::
+      Meta_Info((Prop.build_id -> build_id) :: build_engine ::: build_host :::
           start_date ::: end_date ::: isabelle_version.toList ::: afp_version.toList,
         log_file.get_settings(Settings.all_settings))
     }
--- a/src/Pure/Admin/build_release.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/build_release.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -76,8 +76,8 @@
         progress.bash(
           "isabelle makedist -d " + File.bash_path(base_dir) + jobs_option +
             (if (official_release) " -O" else "") +
-            (if (release_name != "") " -r " + File.bash_string(release_name) else "") +
-            (if (rev != "") " " + File.bash_string(rev) else ""),
+            (if (release_name != "") " -r " + Bash.string(release_name) else "") +
+            (if (rev != "") " " + Bash.string(rev) else ""),
           echo = true).check
       }
       Library.trim_line(File.read(isabelle_ident_file))
@@ -98,8 +98,8 @@
         progress.echo("\nApplication bundle for " + platform_family + ": " + bundle_archive.implode)
         progress.bash(
           "isabelle makedist_bundle " + File.bash_path(release_info.dist_archive) +
-            " " + File.bash_string(platform_family) +
-            (if (remote_mac == "") "" else " " + File.bash_string(remote_mac)),
+            " " + Bash.string(platform_family) +
+            (if (remote_mac == "") "" else " " + Bash.string(remote_mac)),
           echo = true).check
       }
     }
@@ -150,10 +150,29 @@
         progress.echo("### Library archive already exists: " +
           release_info.dist_library_archive.implode)
       else {
-        progress.bash("\"$ISABELLE_HOME/Admin/Release/build_library\"" + jobs_option + " " +
-          File.bash_path(release_info.dist_dir +
-            Path.explode(release_info.name + "_" +
-              Isabelle_System.getenv_strict("ISABELLE_PLATFORM_FAMILY") + ".tar.gz"))).check
+        Isabelle_System.with_tmp_dir("build_release")(tmp_dir =>
+          {
+            def execute(script: String): Unit =
+              Isabelle_System.bash(script, cwd = tmp_dir.file).check
+
+            val name = release_info.name
+            val platform = Isabelle_System.getenv_strict("ISABELLE_PLATFORM_FAMILY")
+            val bundle = release_info.dist_dir + Path.explode(name + "_" + platform + ".tar.gz")
+            execute("tar xzf " + File.bash_path(bundle))
+
+            val other_isabelle =
+              new Other_Isabelle(progress, tmp_dir + Path.explode(name), name + "-build")
+
+            other_isabelle.bash("bin/isabelle build" + jobs_option +
+                " -o browser_info -o document=pdf -o document_variants=document:outline=/proof,/ML" +
+                " -s -c -a -d '~~/src/Benchmarks'", echo = true).check
+            other_isabelle.isabelle_home_user.file.delete
+
+            execute("chmod -R a+r " + Bash.string(name))
+            execute("chmod -R g=o " + Bash.string(name))
+            execute("tar czf " + File.bash_path(release_info.dist_library_archive) +
+              " " + Bash.string(name + "/browser_info"))
+          })
       }
     }
 
@@ -198,7 +217,7 @@
         "R:" -> (arg => release_name = arg),
         "W:" -> (arg => website = Some(Path.explode(arg))),
         "j:" -> (arg => parallel_jobs = Value.Int.parse(arg)),
-        "l" -> (_ => build_library),
+        "l" -> (_ => build_library = true),
         "p:" -> (arg => platform_families = Library.space_explode(',', arg)),
         "r:" -> (arg => rev = arg))
 
--- a/src/Pure/Admin/ci_profile.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/ci_profile.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -27,7 +27,7 @@
         max_jobs = jobs,
         dirs = include,
         select_dirs = select,
-        system_mode = false,
+        system_mode = true,
         selection = select_sessions _)
     }
     val end_time = Time.now()
--- a/src/Pure/Admin/isabelle_cronjob.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/isabelle_cronjob.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -97,19 +97,21 @@
     host: String,
     user: String = "",
     port: Int = SSH.default_port,
-    shared_home: Boolean = false,
+    shared_home: Boolean = true,
     options: String = "",
     args: String = "-o timeout=10800 -a")
 
   private val remote_builds =
     List(
-      Remote_Build("lxbroy10", options = "-m32 -M4 -N", shared_home = true),
+      Remote_Build("lxbroy10", options = "-m32 -M4 -N"),
       Remote_Build("macbroy2", options = "-m32 -M4"),
       Remote_Build("macbroy30", options = "-m32 -M2"),
       Remote_Build("macbroy31", options = "-m32 -M2"))
 
   private def remote_build_history(rev: String, r: Remote_Build): Logger_Task =
-    Logger_Task("build_history-" + r.host, logger =>
+  {
+    val task_name = "build_history-" + r.host
+    Logger_Task(task_name, logger =>
       {
         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
           ssh =>
@@ -120,12 +122,14 @@
                   isabelle_repos.ext(r.host),
                   isabelle_repos_source = isabelle_dev_source,
                   self_update = !r.shared_home,
-                  options = r.options + " -f -r " + File.bash_string(rev),
+                  options =
+                    r.options + " -f -r " + Bash.string(rev) + " -N " + Bash.string(task_name),
                   args = r.args)
               for ((log, bytes) <- results)
                 Bytes.write(logger.log_dir + Path.explode(log), bytes)
             })
       })
+  }
 
 
 
@@ -167,7 +171,9 @@
       val err =
         res match {
           case Exn.Res(_) => None
-          case Exn.Exn(exn) => Some(Exn.message(exn))
+          case Exn.Exn(exn) =>
+            val first_line = Library.split_lines(Exn.message(exn)).headOption getOrElse "exception"
+            Some(first_line)
         }
       logger.log_end(end_date, err)
     }
--- a/src/Pure/Admin/other_isabelle.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/other_isabelle.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -7,7 +7,7 @@
 package isabelle
 
 
-private class Other_Isabelle(progress: Progress, isabelle_home: Path, isabelle_identifier: String)
+class Other_Isabelle(progress: Progress, val isabelle_home: Path, val isabelle_identifier: String)
 {
   other_isabelle =>
 
@@ -16,8 +16,8 @@
 
   def bash(script: String, redirect: Boolean = false, echo: Boolean = false): Process_Result =
     progress.bash(
-      "export ISABELLE_IDENTIFIER=" + File.bash_string(isabelle_identifier) + "\n" + script,
-      env = null, cwd = isabelle_home.file, redirect = redirect)
+      "export ISABELLE_IDENTIFIER=" + Bash.string(isabelle_identifier) + "\n" + script,
+      env = null, cwd = isabelle_home.file, redirect = redirect, echo = echo)
 
   def apply(cmdline: String, redirect: Boolean = false, echo: Boolean = false): Process_Result =
     bash("bin/isabelle " + cmdline, redirect, echo)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/Admin/profiling_report.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,55 @@
+/*  Title:      Pure/Admin/profiling_report.scala
+    Author:     Makarius
+
+Report Poly/ML profiling information from log files.
+*/
+
+package isabelle
+
+
+import java.util.Locale
+
+
+object Profiling_Report
+{
+  def profiling_report(log_file: Build_Log.Log_File): List[(Long, String)] =
+  {
+    val Line = """^(?:### )?([ 0-9]{10}) (\S+|GARBAGE COLLECTION.*)$""".r
+    val Count = """ *(\d+)""".r
+    val clean = """-?\(\d+\).*$""".r
+
+    var results = Map.empty[String, Long]
+    for (Line(Count(Value.Long(count)), raw_fun) <- log_file.lines) {
+      val fun = clean.replaceAllIn(raw_fun, "")
+      results += (fun -> (results.getOrElse(fun, 0L) + count))
+    }
+    for ((fun, count) <- results.toList.sortBy(_._2)) yield (count, fun)
+  }
+
+
+  /* Isabelle tool wrapper */
+
+  val isabelle_tool =
+    Isabelle_Tool("profiling_report", "report Poly/ML profiling information from log files", args =>
+    {
+      Command_Line.tool0 {
+        val getopts =
+          Getopts("""
+Usage: isabelle profiling_report [LOGS ...]
+
+  Report Poly/ML profiling output from log files (potentially compressed).
+""")
+        val log_names = getopts(args)
+        for (name <- log_names) {
+          val log_file = Build_Log.Log_File(Path.explode(name))
+          val results =
+            for ((count, fun) <- profiling_report(log_file))
+              yield
+                String.format(Locale.ROOT, "%14d %s",
+                  count.asInstanceOf[AnyRef], fun.asInstanceOf[AnyRef])
+          if (results.nonEmpty)
+            Output.writeln(cat_lines((log_file.name + ":") :: results))
+        }
+      }
+    })
+}
--- a/src/Pure/Admin/remote_dmg.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Admin/remote_dmg.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -13,13 +13,13 @@
   {
     ssh.with_tmp_dir(remote_dir =>
       {
-        val cd = "cd " + File.bash_string(ssh.remote_path(remote_dir)) + "; "
+        val cd = "cd " + ssh.bash_path(remote_dir) + "; "
 
         ssh.write_file(remote_dir + Path.explode("dmg.tar.gz"), tar_gz_file)
         ssh.execute(cd + "mkdir root && tar -C root -xzf dmg.tar.gz").check
         ssh.execute(
           cd + "hdiutil create -srcfolder root" +
-            (if (volume_name == "") "" else " -volname " + File.bash_string(volume_name)) +
+            (if (volume_name == "") "" else " -volname " + Bash.string(volume_name)) +
             " dmg.dmg").check
         ssh.read_file(remote_dir + Path.explode("dmg.dmg"), dmg_file)
       })
--- a/src/Pure/General/file.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/General/file.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -8,8 +8,6 @@
 sig
   val standard_path: Path.T -> string
   val platform_path: Path.T -> string
-  val bash_string: string -> string
-  val bash_args: string list -> string
   val bash_path: Path.T -> string
   val full_path: Path.T -> Path.T -> Path.T
   val tmp_path: Path.T -> Path.T
@@ -46,26 +44,7 @@
 val standard_path = Path.implode o Path.expand;
 val platform_path = ML_System.platform_path o standard_path;
 
-fun bash_string "" = "\"\""
-  | bash_string str =
-      str |> translate_string (fn ch =>
-        let val c = ord ch in
-          (case ch of
-            "\t" => "$'\\t'"
-          | "\n" => "$'\\n'"
-          | "\f" => "$'\\f'"
-          | "\r" => "$'\\r'"
-          | _ =>
-              if Symbol.is_ascii_letter ch orelse Symbol.is_ascii_digit ch orelse
-                exists_string (fn c => c = ch) "-./:_" then ch
-              else if c < 16 then "$'\\x0" ^ Int.fmt StringCvt.HEX c ^ "'"
-              else if c < 32 orelse c >= 127 then "$'\\x" ^ Int.fmt StringCvt.HEX c ^ "'"
-              else "\\" ^ ch)
-        end);
-
-val bash_args = space_implode " " o map bash_string;
-
-val bash_path = bash_string o standard_path;
+val bash_path = Bash_Syntax.string o standard_path;
 
 
 (* full_path *)
--- a/src/Pure/General/file.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/General/file.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -108,33 +108,8 @@
 
   /* bash path */
 
-  private def bash_chr(c: Byte): String =
-  {
-    val ch = c.toChar
-    ch match {
-      case '\t' => "$'\\t'"
-      case '\n' => "$'\\n'"
-      case '\f' => "$'\\f'"
-      case '\r' => "$'\\r'"
-      case _ =>
-        if (Symbol.is_ascii_letter(ch) || Symbol.is_ascii_digit(ch) || "-./:_".contains(ch))
-          Symbol.ascii(ch)
-        else if (c < 0) "$'\\x" + Integer.toHexString(256 + c) + "'"
-        else if (c < 16) "$'\\x0" + Integer.toHexString(c) + "'"
-        else if (c < 32 || c >= 127) "$'\\x" + Integer.toHexString(c) + "'"
-        else  "\\" + ch
-    }
-  }
-
-  def bash_string(s: String): String =
-    if (s == "") "\"\""
-    else UTF8.bytes(s).iterator.map(bash_chr(_)).mkString
-
-  def bash_args(args: List[String]): String =
-    args.iterator.map(bash_string(_)).mkString(" ")
-
-  def bash_path(path: Path): String = bash_string(standard_path(path))
-  def bash_path(file: JFile): String = bash_string(standard_path(file))
+  def bash_path(path: Path): String = Bash.string(standard_path(path))
+  def bash_path(file: JFile): String = Bash.string(standard_path(file))
 
 
   /* directory entries */
--- a/src/Pure/General/mercurial.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/General/mercurial.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -16,7 +16,7 @@
   /* command-line syntax */
 
   def optional(s: String, prefix: String = ""): String =
-    if (s == "") "" else " " + prefix + " " + File.bash_string(s)
+    if (s == "") "" else " " + prefix + " " + Bash.string(s)
 
   def opt_flag(flag: String, b: Boolean): String = if (b) " " + flag else ""
   def opt_rev(s: String): String = optional(s, "--rev")
@@ -40,7 +40,7 @@
       case None => Isabelle_System.mkdirs(hg.root.dir)
       case Some(ssh) => ssh.mkdirs(hg.root.dir)
     }
-    hg.command("clone", File.bash_string(source) + " " + File.bash_path(hg.root), options).check
+    hg.command("clone", Bash.string(source) + " " + File.bash_path(hg.root), options).check
     hg
   }
 
--- a/src/Pure/General/name_space.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/General/name_space.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -120,7 +120,7 @@
 
 (* internal names *)
 
-type internals = (string list * string list) Change_Table.T;
+type internals = (string list * string list) Change_Table.T;  (*xname -> visible, hidden*)
 
 fun map_internals f xname : internals -> internals =
   Change_Table.map_default (xname, ([], [])) f;
@@ -132,13 +132,15 @@
 fun hide_name name = map_internals (apsnd (update (op =) name)) name;
 
 
+(* external accesses *)
+
+type accesses = (xstring list * xstring list);  (*input / output fragments*)
+type entries = (accesses * entry) Change_Table.T;  (*name -> accesses, entry*)
+
+
 (* datatype T *)
 
-datatype T =
-  Name_Space of
-   {kind: string,
-    internals: internals,  (*xname -> visible, hidden*)
-    entries: (xstring list * entry) Change_Table.T};  (*name -> externals, entry*)
+datatype T = Name_Space of {kind: string, internals: internals, entries: entries};
 
 fun make_name_space (kind, internals, entries) =
   Name_Space {kind = kind, internals = internals, entries = entries};
@@ -200,12 +202,13 @@
 
 fun get_accesses (Name_Space {entries, ...}) name =
   (case Change_Table.lookup entries name of
-    NONE => []
-  | SOME (externals, _) => externals);
+    NONE => ([], [])
+  | SOME (accesses, _) => accesses);
 
-fun valid_accesses (Name_Space {internals, ...}) name =
-  Change_Table.fold (fn (xname, (names, _)) =>
-    if not (null names) andalso hd names = name then cons xname else I) internals [];
+fun is_valid_access (Name_Space {internals, ...}) name xname =
+  (case Change_Table.lookup internals xname of
+    SOME (name' :: _, _) => name = name'
+  | _ => false);
 
 
 (* extern *)
@@ -234,7 +237,7 @@
   in
     if names_long then name
     else if names_short then Long_Name.base_name name
-    else ext (get_accesses space name)
+    else ext (#2 (get_accesses space name))
   end;
 
 fun extern_ord ctxt space = string_ord o apply2 (extern ctxt space);
@@ -426,7 +429,7 @@
 
 fun mandatory_suffixes xs = map rev (mandatory_prefixes (rev xs));
 
-fun accesses naming binding =
+fun make_accesses naming binding =
   (case name_spec naming binding of
     {restriction = SOME true, ...} => ([], [])
   | {restriction, spec, ...} =>
@@ -443,12 +446,13 @@
   space |> map_name_space (fn (kind, internals, entries) =>
     let
       val _ = the_entry space name;
-      val names = valid_accesses space name;
+      val (accs, accs') = get_accesses space name;
+      val xnames = filter (is_valid_access space name) accs;
       val internals' = internals
         |> hide_name name
         |> fold (del_name name)
-          (if fully then names else inter (op =) [Long_Name.base_name name] names)
-        |> fold (del_name_extra name) (get_accesses space name);
+          (if fully then xnames else inter (op =) [Long_Name.base_name name] xnames)
+        |> fold (del_name_extra name) accs';
     in (kind, internals', entries) end);
 
 
@@ -458,10 +462,12 @@
   space |> map_name_space (fn (kind, internals, entries) =>
     let
       val _ = the_entry space name;
-      val (accs, accs') = accesses naming binding;
-      val internals' = internals |> fold (add_name name) accs;
+      val (more_accs, more_accs') = make_accesses naming binding;
+      val internals' = internals |> fold (add_name name) more_accs;
       val entries' = entries
-        |> Change_Table.map_entry name (apfst (fold_rev (update op =) accs'));
+        |> Change_Table.map_entry name (apfst (fn (accs, accs') =>
+            (fold_rev (update op =) more_accs accs,
+             fold_rev (update op =) more_accs' accs')))
     in (kind, internals', entries') end);
 
 
@@ -497,7 +503,7 @@
     val naming = naming_of context;
     val Naming {group, theory_name, ...} = naming;
     val {concealed, spec, ...} = name_spec naming binding;
-    val (accs, accs') = accesses naming binding;
+    val accesses = make_accesses naming binding;
 
     val name = Long_Name.implode (map fst spec);
     val _ = name = "" andalso error (Binding.bad binding);
@@ -512,10 +518,10 @@
     val space' =
       space |> map_name_space (fn (kind, internals, entries) =>
         let
-          val internals' = internals |> fold (add_name name) accs;
+          val internals' = internals |> fold (add_name name) (#1 accesses);
           val entries' =
             (if strict then Change_Table.update_new else Change_Table.update)
-              (name, (accs', entry)) entries
+              (name, (accesses, entry)) entries
             handle Change_Table.DUP dup =>
               err_dup kind (dup, #2 (the (Change_Table.lookup entries dup)))
                 (name, entry) (#pos entry);
--- a/src/Pure/General/ssh.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/General/ssh.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -243,6 +243,7 @@
     }
     def expand_path(path: Path): Path = path.expand_env(settings)
     def remote_path(path: Path): String = expand_path(path).implode
+    def bash_path(path: Path): String = Bash.string(remote_path(path))
 
     def chmod(permissions: Int, path: Path): Unit = sftp.chmod(permissions, remote_path(path))
     def mv(path1: Path, path2: Path): Unit = sftp.rename(remote_path(path1), remote_path(path2))
@@ -323,8 +324,10 @@
 
     /* tmp dirs */
 
+    def rm_tree(dir: Path): Unit = rm_tree(remote_path(dir))
+
     def rm_tree(remote_dir: String): Unit =
-      execute("rm -r -f " + File.bash_string(remote_dir)).check
+      execute("rm -r -f " + Bash.string(remote_dir)).check
 
     def tmp_dir(): String =
       execute("mktemp -d -t tmp.XXXXXXXXXX").check.out
--- a/src/Pure/ROOT	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/ROOT	Thu Oct 20 19:39:27 2016 +0200
@@ -4,6 +4,7 @@
   description {*
     The Pure logical framework
   *}
+  options [threads = 1]
   global_theories
     Pure
   theories
--- a/src/Pure/ROOT.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/ROOT.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -67,6 +67,7 @@
 ML_file "PIDE/xml.ML";
 ML_file "General/path.ML";
 ML_file "General/url.ML";
+ML_file "System/bash_syntax.ML";
 ML_file "General/file.ML";
 ML_file "General/long_name.ML";
 ML_file "General/binding.ML";
--- a/src/Pure/System/bash.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/System/bash.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -6,6 +6,8 @@
 
 signature BASH =
 sig
+  val string: string -> string
+  val strings: string list -> string
   val process: string -> {out: string, err: string, rc: int, terminate: unit -> unit}
 end;
 
@@ -14,6 +16,9 @@
 structure Bash: BASH =
 struct
 
+val string = Bash_Syntax.string;
+val strings = Bash_Syntax.strings;
+
 val process = Thread_Attributes.uninterruptible (fn restore_attributes => fn script =>
   let
     datatype result = Wait | Signal | Result of int;
@@ -105,6 +110,9 @@
 structure Bash: BASH =
 struct
 
+val string = Bash_Syntax.string;
+val strings = Bash_Syntax.strings;
+
 val process = Thread_Attributes.uninterruptible (fn restore_attributes => fn script =>
   let
     datatype result = Wait | Signal | Result of int;
--- a/src/Pure/System/bash.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/System/bash.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -13,6 +13,36 @@
 
 object Bash
 {
+  /* concrete syntax */
+
+  private def bash_chr(c: Byte): String =
+  {
+    val ch = c.toChar
+    ch match {
+      case '\t' => "$'\\t'"
+      case '\n' => "$'\\n'"
+      case '\f' => "$'\\f'"
+      case '\r' => "$'\\r'"
+      case _ =>
+        if (Symbol.is_ascii_letter(ch) || Symbol.is_ascii_digit(ch) || "-./:_".contains(ch))
+          Symbol.ascii(ch)
+        else if (c < 0) "$'\\x" + Integer.toHexString(256 + c) + "'"
+        else if (c < 16) "$'\\x0" + Integer.toHexString(c) + "'"
+        else if (c < 32 || c >= 127) "$'\\x" + Integer.toHexString(c) + "'"
+        else  "\\" + ch
+    }
+  }
+
+  def string(s: String): String =
+    if (s == "") "\"\""
+    else UTF8.bytes(s).iterator.map(bash_chr(_)).mkString
+
+  def strings(ss: List[String]): String =
+    ss.iterator.map(Bash.string(_)).mkString(" ")
+
+
+  /* process and result */
+
   private class Limited_Progress(proc: Process, progress_limit: Option[Long])
   {
     private var count = 0L
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/System/bash_syntax.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -0,0 +1,35 @@
+(*  Title:      Pure/System/bash_syntax.ML
+    Author:     Makarius
+
+Syntax for GNU bash (see also Pure/System/bash.ML).
+*)
+
+signature BASH_SYNTAX =
+sig
+  val string: string -> string
+  val strings: string list -> string
+end;
+
+structure Bash_Syntax: BASH_SYNTAX =
+struct
+
+fun string "" = "\"\""
+  | string str =
+      str |> translate_string (fn ch =>
+        let val c = ord ch in
+          (case ch of
+            "\t" => "$'\\t'"
+          | "\n" => "$'\\n'"
+          | "\f" => "$'\\f'"
+          | "\r" => "$'\\r'"
+          | _ =>
+              if Symbol.is_ascii_letter ch orelse Symbol.is_ascii_digit ch orelse
+                exists_string (fn c => c = ch) "-./:_" then ch
+              else if c < 16 then "$'\\x0" ^ Int.fmt StringCvt.HEX c ^ "'"
+              else if c < 32 orelse c >= 127 then "$'\\x" ^ Int.fmt StringCvt.HEX c ^ "'"
+              else "\\" ^ ch)
+        end);
+
+val strings = space_implode " " o map string;
+
+end;
--- a/src/Pure/System/isabelle_system.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/System/isabelle_system.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -318,7 +318,7 @@
   def hostname(): String = bash("hostname -s").check.out
 
   def open(arg: String): Unit =
-    bash("exec \"$ISABELLE_OPEN\" " + File.bash_string(arg) + " >/dev/null 2>/dev/null &")
+    bash("exec \"$ISABELLE_OPEN\" " + Bash.string(arg) + " >/dev/null 2>/dev/null &")
 
   def pdf_viewer(arg: Path): Unit =
     bash("exec \"$PDF_VIEWER\" " + File.bash_path(arg) + " >/dev/null 2>/dev/null &")
--- a/src/Pure/System/isabelle_tool.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/System/isabelle_tool.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -89,7 +89,7 @@
         (args: List[String]) =>
           {
             val tool = dir + Path.basic(name)
-            val result = Isabelle_System.bash(File.bash_path(tool) + " " + File.bash_args(args))
+            val result = Isabelle_System.bash(File.bash_path(tool) + " " + Bash.strings(args))
             sys.exit(result.print_stdout.rc)
           }
     })
@@ -106,6 +106,7 @@
       Doc.isabelle_tool,
       ML_Process.isabelle_tool,
       Options.isabelle_tool,
+      Profiling_Report.isabelle_tool,
       Remote_DMG.isabelle_tool,
       Update_Cartouches.isabelle_tool,
       Update_Header.isabelle_tool,
--- a/src/Pure/Tools/build.ML	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Tools/build.ML	Thu Oct 20 19:39:27 2016 +0200
@@ -114,6 +114,12 @@
           symbols = symbols,
           last_timing = last_timing,
           master_dir = master_dir}
+        |>
+          (case Options.string options "profiling" of
+            "" => I
+          | "time" => profile_time
+          | "allocations" => profile_allocations
+          | bad => error ("Bad profiling option: " ^ quote bad))
         |> Unsynchronized.setmp print_mode
             (space_explode "," (Options.string options "print_mode") @ print_mode_value ())) thys)
     else
--- a/src/Pure/Tools/ml_process.scala	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/Tools/ml_process.scala	Thu Oct 20 19:39:27 2016 +0200
@@ -107,7 +107,7 @@
 
     Bash.process(
       "exec " + options.string("ML_process_policy") + """ "$ML_HOME/poly" -q """ +
-        File.bash_args(bash_args),
+        Bash.strings(bash_args),
       cwd = cwd,
       env =
         Isabelle_System.library_path(env ++ env_options ++ env_tmp,
--- a/src/Pure/build-jars	Tue Oct 18 16:04:44 2016 +0200
+++ b/src/Pure/build-jars	Thu Oct 20 19:39:27 2016 +0200
@@ -19,6 +19,7 @@
   Admin/ci_profile.scala
   Admin/isabelle_cronjob.scala
   Admin/other_isabelle.scala
+  Admin/profiling_report.scala
   Admin/remote_dmg.scala
   Concurrent/consumer_thread.scala
   Concurrent/counter.scala