Theory Topology_Euclidean_Space

theory Topology_Euclidean_Space
imports Indicator_Function Countable_Set FuncSet Linear_Algebra Norm_Arith
(*  Author:     L C Paulson, University of Cambridge
    Author:     Amine Chaieb, University of Cambridge
    Author:     Robert Himmelmann, TU Muenchen
    Author:     Brian Huffman, Portland State University
*)

section ‹Elementary topology in Euclidean space.›

theory Topology_Euclidean_Space
imports
  "HOL-Library.Indicator_Function"
  "HOL-Library.Countable_Set"
  "HOL-Library.FuncSet"
  Linear_Algebra
  Norm_Arith
begin

(* FIXME: move elsewhere *)

lemma Times_eq_image_sum:
  fixes S :: "'a :: comm_monoid_add set" and T :: "'b :: comm_monoid_add set"
  shows "S × T = {u + v |u v. u ∈ (λx. (x, 0)) ` S ∧ v ∈ Pair 0 ` T}"
  by force

lemma halfspace_Int_eq:
     "{x. a ∙ x ≤ b} ∩ {x. b ≤ a ∙ x} = {x. a ∙ x = b}"
     "{x. b ≤ a ∙ x} ∩ {x. a ∙ x ≤ b} = {x. a ∙ x = b}"
  by auto

definition (in monoid_add) support_on :: "'b set ⇒ ('b ⇒ 'a) ⇒ 'b set"
  where "support_on s f = {x∈s. f x ≠ 0}"

lemma in_support_on: "x ∈ support_on s f ⟷ x ∈ s ∧ f x ≠ 0"
  by (simp add: support_on_def)

lemma support_on_simps[simp]:
  "support_on {} f = {}"
  "support_on (insert x s) f =
    (if f x = 0 then support_on s f else insert x (support_on s f))"
  "support_on (s ∪ t) f = support_on s f ∪ support_on t f"
  "support_on (s ∩ t) f = support_on s f ∩ support_on t f"
  "support_on (s - t) f = support_on s f - support_on t f"
  "support_on (f ` s) g = f ` (support_on s (g ∘ f))"
  unfolding support_on_def by auto

lemma support_on_cong:
  "(⋀x. x ∈ s ⟹ f x = 0 ⟷ g x = 0) ⟹ support_on s f = support_on s g"
  by (auto simp: support_on_def)

lemma support_on_if: "a ≠ 0 ⟹ support_on A (λx. if P x then a else 0) = {x∈A. P x}"
  by (auto simp: support_on_def)

lemma support_on_if_subset: "support_on A (λx. if P x then a else 0) ⊆ {x ∈ A. P x}"
  by (auto simp: support_on_def)

lemma finite_support[intro]: "finite s ⟹ finite (support_on s f)"
  unfolding support_on_def by auto

(* TODO: is supp_sum really needed? TODO: Generalize to Finite_Set.fold *)
definition (in comm_monoid_add) supp_sum :: "('b ⇒ 'a) ⇒ 'b set ⇒ 'a"
  where "supp_sum f s = (∑x∈support_on s f. f x)"

lemma supp_sum_empty[simp]: "supp_sum f {} = 0"
  unfolding supp_sum_def by auto

lemma supp_sum_insert[simp]:
  "finite (support_on s f) ⟹
    supp_sum f (insert x s) = (if x ∈ s then supp_sum f s else f x + supp_sum f s)"
  by (simp add: supp_sum_def in_support_on insert_absorb)

lemma supp_sum_divide_distrib: "supp_sum f A / (r::'a::field) = supp_sum (λn. f n / r) A"
  by (cases "r = 0")
     (auto simp: supp_sum_def sum_divide_distrib intro!: sum.cong support_on_cong)

(*END OF SUPPORT, ETC.*)

lemma image_affinity_interval:
  fixes c :: "'a::ordered_real_vector"
  shows "((λx. m *R x + c) ` {a..b}) = (if {a..b}={} then {}
            else if 0 <= m then {m *R a + c .. m  *R b + c}
            else {m *R b + c .. m *R a + c})"
  apply (case_tac "m=0", force)
  apply (auto simp: scaleR_left_mono)
  apply (rule_tac x="inverse m *R (x-c)" in rev_image_eqI, auto simp: pos_le_divideR_eq le_diff_eq scaleR_left_mono_neg)
  apply (metis diff_le_eq inverse_inverse_eq order.not_eq_order_implies_strict pos_le_divideR_eq positive_imp_inverse_positive)
  apply (rule_tac x="inverse m *R (x-c)" in rev_image_eqI, auto simp: not_le neg_le_divideR_eq diff_le_eq)
  using le_diff_eq scaleR_le_cancel_left_neg
  apply fastforce
  done

lemma countable_PiE:
  "finite I ⟹ (⋀i. i ∈ I ⟹ countable (F i)) ⟹ countable (PiE I F)"
  by (induct I arbitrary: F rule: finite_induct) (auto simp: PiE_insert_eq)

lemma open_sums:
  fixes T :: "('b::real_normed_vector) set"
  assumes "open S ∨ open T"
  shows "open (⋃x∈ S. ⋃y ∈ T. {x + y})"
  using assms
proof
  assume S: "open S"
  show ?thesis
  proof (clarsimp simp: open_dist)
    fix x y
    assume "x ∈ S" "y ∈ T"
    with S obtain e where "e > 0" and e: "⋀x'. dist x' x < e ⟹ x' ∈ S"
      by (auto simp: open_dist)
    then have "⋀z. dist z (x + y) < e ⟹ ∃x∈S. ∃y∈T. z = x + y"
      by (metis ‹y ∈ T› diff_add_cancel dist_add_cancel2)
    then show "∃e>0. ∀z. dist z (x + y) < e ⟶ (∃x∈S. ∃y∈T. z = x + y)"
      using ‹0 < e› ‹x ∈ S› by blast
  qed
next
  assume T: "open T"
  show ?thesis
  proof (clarsimp simp: open_dist)
    fix x y
    assume "x ∈ S" "y ∈ T"
    with T obtain e where "e > 0" and e: "⋀x'. dist x' y < e ⟹ x' ∈ T"
      by (auto simp: open_dist)
    then have "⋀z. dist z (x + y) < e ⟹ ∃x∈S. ∃y∈T. z = x + y"
      by (metis ‹x ∈ S› add_diff_cancel_left' add_diff_eq diff_diff_add dist_norm)
    then show "∃e>0. ∀z. dist z (x + y) < e ⟶ (∃x∈S. ∃y∈T. z = x + y)"
      using ‹0 < e› ‹y ∈ T› by blast
  qed
qed


subsection ‹Topological Basis›

context topological_space
begin

definition "topological_basis B ⟷
  (∀b∈B. open b) ∧ (∀x. open x ⟶ (∃B'. B' ⊆ B ∧ ⋃B' = x))"

lemma topological_basis:
  "topological_basis B ⟷ (∀x. open x ⟷ (∃B'. B' ⊆ B ∧ ⋃B' = x))"
  unfolding topological_basis_def
  apply safe
     apply fastforce
    apply fastforce
   apply (erule_tac x=x in allE, simp)
   apply (rule_tac x="{x}" in exI, auto)
  done

lemma topological_basis_iff:
  assumes "⋀B'. B' ∈ B ⟹ open B'"
  shows "topological_basis B ⟷ (∀O'. open O' ⟶ (∀x∈O'. ∃B'∈B. x ∈ B' ∧ B' ⊆ O'))"
    (is "_ ⟷ ?rhs")
proof safe
  fix O' and x::'a
  assume H: "topological_basis B" "open O'" "x ∈ O'"
  then have "(∃B'⊆B. ⋃B' = O')" by (simp add: topological_basis_def)
  then obtain B' where "B' ⊆ B" "O' = ⋃B'" by auto
  then show "∃B'∈B. x ∈ B' ∧ B' ⊆ O'" using H by auto
next
  assume H: ?rhs
  show "topological_basis B"
    using assms unfolding topological_basis_def
  proof safe
    fix O' :: "'a set"
    assume "open O'"
    with H obtain f where "∀x∈O'. f x ∈ B ∧ x ∈ f x ∧ f x ⊆ O'"
      by (force intro: bchoice simp: Bex_def)
    then show "∃B'⊆B. ⋃B' = O'"
      by (auto intro: exI[where x="{f x |x. x ∈ O'}"])
  qed
qed

lemma topological_basisI:
  assumes "⋀B'. B' ∈ B ⟹ open B'"
    and "⋀O' x. open O' ⟹ x ∈ O' ⟹ ∃B'∈B. x ∈ B' ∧ B' ⊆ O'"
  shows "topological_basis B"
  using assms by (subst topological_basis_iff) auto

lemma topological_basisE:
  fixes O'
  assumes "topological_basis B"
    and "open O'"
    and "x ∈ O'"
  obtains B' where "B' ∈ B" "x ∈ B'" "B' ⊆ O'"
proof atomize_elim
  from assms have "⋀B'. B'∈B ⟹ open B'"
    by (simp add: topological_basis_def)
  with topological_basis_iff assms
  show  "∃B'. B' ∈ B ∧ x ∈ B' ∧ B' ⊆ O'"
    using assms by (simp add: Bex_def)
qed

lemma topological_basis_open:
  assumes "topological_basis B"
    and "X ∈ B"
  shows "open X"
  using assms by (simp add: topological_basis_def)

lemma topological_basis_imp_subbasis:
  assumes B: "topological_basis B"
  shows "open = generate_topology B"
proof (intro ext iffI)
  fix S :: "'a set"
  assume "open S"
  with B obtain B' where "B' ⊆ B" "S = ⋃B'"
    unfolding topological_basis_def by blast
  then show "generate_topology B S"
    by (auto intro: generate_topology.intros dest: topological_basis_open)
next
  fix S :: "'a set"
  assume "generate_topology B S"
  then show "open S"
    by induct (auto dest: topological_basis_open[OF B])
qed

lemma basis_dense:
  fixes B :: "'a set set"
    and f :: "'a set ⇒ 'a"
  assumes "topological_basis B"
    and choosefrom_basis: "⋀B'. B' ≠ {} ⟹ f B' ∈ B'"
  shows "∀X. open X ⟶ X ≠ {} ⟶ (∃B' ∈ B. f B' ∈ X)"
proof (intro allI impI)
  fix X :: "'a set"
  assume "open X" and "X ≠ {}"
  from topological_basisE[OF ‹topological_basis B› ‹open X› choosefrom_basis[OF ‹X ≠ {}›]]
  obtain B' where "B' ∈ B" "f X ∈ B'" "B' ⊆ X" .
  then show "∃B'∈B. f B' ∈ X"
    by (auto intro!: choosefrom_basis)
qed

end

lemma topological_basis_prod:
  assumes A: "topological_basis A"
    and B: "topological_basis B"
  shows "topological_basis ((λ(a, b). a × b) ` (A × B))"
  unfolding topological_basis_def
proof (safe, simp_all del: ex_simps add: subset_image_iff ex_simps(1)[symmetric])
  fix S :: "('a × 'b) set"
  assume "open S"
  then show "∃X⊆A × B. (⋃(a,b)∈X. a × b) = S"
  proof (safe intro!: exI[of _ "{x∈A × B. fst x × snd x ⊆ S}"])
    fix x y
    assume "(x, y) ∈ S"
    from open_prod_elim[OF ‹open S› this]
    obtain a b where a: "open a""x ∈ a" and b: "open b" "y ∈ b" and "a × b ⊆ S"
      by (metis mem_Sigma_iff)
    moreover
    from A a obtain A0 where "A0 ∈ A" "x ∈ A0" "A0 ⊆ a"
      by (rule topological_basisE)
    moreover
    from B b obtain B0 where "B0 ∈ B" "y ∈ B0" "B0 ⊆ b"
      by (rule topological_basisE)
    ultimately show "(x, y) ∈ (⋃(a, b)∈{X ∈ A × B. fst X × snd X ⊆ S}. a × b)"
      by (intro UN_I[of "(A0, B0)"]) auto
  qed auto
qed (metis A B topological_basis_open open_Times)


subsection ‹Countable Basis›

locale countable_basis =
  fixes B :: "'a::topological_space set set"
  assumes is_basis: "topological_basis B"
    and countable_basis: "countable B"
begin

lemma open_countable_basis_ex:
  assumes "open X"
  shows "∃B' ⊆ B. X = ⋃B'"
  using assms countable_basis is_basis
  unfolding topological_basis_def by blast

lemma open_countable_basisE:
  assumes "open X"
  obtains B' where "B' ⊆ B" "X = ⋃B'"
  using assms open_countable_basis_ex
  by atomize_elim simp

lemma countable_dense_exists:
  "∃D::'a set. countable D ∧ (∀X. open X ⟶ X ≠ {} ⟶ (∃d ∈ D. d ∈ X))"
proof -
  let ?f = "(λB'. SOME x. x ∈ B')"
  have "countable (?f ` B)" using countable_basis by simp
  with basis_dense[OF is_basis, of ?f] show ?thesis
    by (intro exI[where x="?f ` B"]) (metis (mono_tags) all_not_in_conv imageI someI)
qed

lemma countable_dense_setE:
  obtains D :: "'a set"
  where "countable D" "⋀X. open X ⟹ X ≠ {} ⟹ ∃d ∈ D. d ∈ X"
  using countable_dense_exists by blast

end

lemma (in first_countable_topology) first_countable_basisE:
  obtains A where "countable A" "⋀a. a ∈ A ⟹ x ∈ a" "⋀a. a ∈ A ⟹ open a"
    "⋀S. open S ⟹ x ∈ S ⟹ (∃a∈A. a ⊆ S)"
  using first_countable_basis[of x]
  apply atomize_elim
  apply (elim exE)
  apply (rule_tac x="range A" in exI, auto)
  done

lemma (in first_countable_topology) first_countable_basis_Int_stableE:
  obtains A where "countable A" "⋀a. a ∈ A ⟹ x ∈ a" "⋀a. a ∈ A ⟹ open a"
    "⋀S. open S ⟹ x ∈ S ⟹ (∃a∈A. a ⊆ S)"
    "⋀a b. a ∈ A ⟹ b ∈ A ⟹ a ∩ b ∈ A"
proof atomize_elim
  obtain A' where A':
    "countable A'"
    "⋀a. a ∈ A' ⟹ x ∈ a"
    "⋀a. a ∈ A' ⟹ open a"
    "⋀S. open S ⟹ x ∈ S ⟹ ∃a∈A'. a ⊆ S"
    by (rule first_countable_basisE) blast
  define A where [abs_def]:
    "A = (λN. ⋂((λn. from_nat_into A' n) ` N)) ` (Collect finite::nat set set)"
  then show "∃A. countable A ∧ (∀a. a ∈ A ⟶ x ∈ a) ∧ (∀a. a ∈ A ⟶ open a) ∧
        (∀S. open S ⟶ x ∈ S ⟶ (∃a∈A. a ⊆ S)) ∧ (∀a b. a ∈ A ⟶ b ∈ A ⟶ a ∩ b ∈ A)"
  proof (safe intro!: exI[where x=A])
    show "countable A"
      unfolding A_def by (intro countable_image countable_Collect_finite)
    fix a
    assume "a ∈ A"
    then show "x ∈ a" "open a"
      using A'(4)[OF open_UNIV] by (auto simp: A_def intro: A' from_nat_into)
  next
    let ?int = "λN. ⋂(from_nat_into A' ` N)"
    fix a b
    assume "a ∈ A" "b ∈ A"
    then obtain N M where "a = ?int N" "b = ?int M" "finite (N ∪ M)"
      by (auto simp: A_def)
    then show "a ∩ b ∈ A"
      by (auto simp: A_def intro!: image_eqI[where x="N ∪ M"])
  next
    fix S
    assume "open S" "x ∈ S"
    then obtain a where a: "a∈A'" "a ⊆ S" using A' by blast
    then show "∃a∈A. a ⊆ S" using a A'
      by (intro bexI[where x=a]) (auto simp: A_def intro: image_eqI[where x="{to_nat_on A' a}"])
  qed
qed

lemma (in topological_space) first_countableI:
  assumes "countable A"
    and 1: "⋀a. a ∈ A ⟹ x ∈ a" "⋀a. a ∈ A ⟹ open a"
    and 2: "⋀S. open S ⟹ x ∈ S ⟹ ∃a∈A. a ⊆ S"
  shows "∃A::nat ⇒ 'a set. (∀i. x ∈ A i ∧ open (A i)) ∧ (∀S. open S ∧ x ∈ S ⟶ (∃i. A i ⊆ S))"
proof (safe intro!: exI[of _ "from_nat_into A"])
  fix i
  have "A ≠ {}" using 2[of UNIV] by auto
  show "x ∈ from_nat_into A i" "open (from_nat_into A i)"
    using range_from_nat_into_subset[OF ‹A ≠ {}›] 1 by auto
next
  fix S
  assume "open S" "x∈S" from 2[OF this]
  show "∃i. from_nat_into A i ⊆ S"
    using subset_range_from_nat_into[OF ‹countable A›] by auto
qed

instance prod :: (first_countable_topology, first_countable_topology) first_countable_topology
proof
  fix x :: "'a × 'b"
  obtain A where A:
      "countable A"
      "⋀a. a ∈ A ⟹ fst x ∈ a"
      "⋀a. a ∈ A ⟹ open a"
      "⋀S. open S ⟹ fst x ∈ S ⟹ ∃a∈A. a ⊆ S"
    by (rule first_countable_basisE[of "fst x"]) blast
  obtain B where B:
      "countable B"
      "⋀a. a ∈ B ⟹ snd x ∈ a"
      "⋀a. a ∈ B ⟹ open a"
      "⋀S. open S ⟹ snd x ∈ S ⟹ ∃a∈B. a ⊆ S"
    by (rule first_countable_basisE[of "snd x"]) blast
  show "∃A::nat ⇒ ('a × 'b) set.
    (∀i. x ∈ A i ∧ open (A i)) ∧ (∀S. open S ∧ x ∈ S ⟶ (∃i. A i ⊆ S))"
  proof (rule first_countableI[of "(λ(a, b). a × b) ` (A × B)"], safe)
    fix a b
    assume x: "a ∈ A" "b ∈ B"
    with A(2, 3)[of a] B(2, 3)[of b] show "x ∈ a × b" and "open (a × b)"
      unfolding mem_Times_iff
      by (auto intro: open_Times)
  next
    fix S
    assume "open S" "x ∈ S"
    then obtain a' b' where a'b': "open a'" "open b'" "x ∈ a' × b'" "a' × b' ⊆ S"
      by (rule open_prod_elim)
    moreover
    from a'b' A(4)[of a'] B(4)[of b']
    obtain a b where "a ∈ A" "a ⊆ a'" "b ∈ B" "b ⊆ b'"
      by auto
    ultimately
    show "∃a∈(λ(a, b). a × b) ` (A × B). a ⊆ S"
      by (auto intro!: bexI[of _ "a × b"] bexI[of _ a] bexI[of _ b])
  qed (simp add: A B)
qed

class second_countable_topology = topological_space +
  assumes ex_countable_subbasis:
    "∃B::'a::topological_space set set. countable B ∧ open = generate_topology B"
begin

lemma ex_countable_basis: "∃B::'a set set. countable B ∧ topological_basis B"
proof -
  from ex_countable_subbasis obtain B where B: "countable B" "open = generate_topology B"
    by blast
  let ?B = "Inter ` {b. finite b ∧ b ⊆ B }"

  show ?thesis
  proof (intro exI conjI)
    show "countable ?B"
      by (intro countable_image countable_Collect_finite_subset B)
    {
      fix S
      assume "open S"
      then have "∃B'⊆{b. finite b ∧ b ⊆ B}. (⋃b∈B'. ⋂b) = S"
        unfolding B
      proof induct
        case UNIV
        show ?case by (intro exI[of _ "{{}}"]) simp
      next
        case (Int a b)
        then obtain x y where x: "a = UNION x Inter" "⋀i. i ∈ x ⟹ finite i ∧ i ⊆ B"
          and y: "b = UNION y Inter" "⋀i. i ∈ y ⟹ finite i ∧ i ⊆ B"
          by blast
        show ?case
          unfolding x y Int_UN_distrib2
          by (intro exI[of _ "{i ∪ j| i j.  i ∈ x ∧ j ∈ y}"]) (auto dest: x(2) y(2))
      next
        case (UN K)
        then have "∀k∈K. ∃B'⊆{b. finite b ∧ b ⊆ B}. UNION B' Inter = k" by auto
        then obtain k where
            "∀ka∈K. k ka ⊆ {b. finite b ∧ b ⊆ B} ∧ UNION (k ka) Inter = ka"
          unfolding bchoice_iff ..
        then show "∃B'⊆{b. finite b ∧ b ⊆ B}. UNION B' Inter = ⋃K"
          by (intro exI[of _ "UNION K k"]) auto
      next
        case (Basis S)
        then show ?case
          by (intro exI[of _ "{{S}}"]) auto
      qed
      then have "(∃B'⊆Inter ` {b. finite b ∧ b ⊆ B}. ⋃B' = S)"
        unfolding subset_image_iff by blast }
    then show "topological_basis ?B"
      unfolding topological_space_class.topological_basis_def
      by (safe intro!: topological_space_class.open_Inter)
         (simp_all add: B generate_topology.Basis subset_eq)
  qed
qed

end

sublocale second_countable_topology <
  countable_basis "SOME B. countable B ∧ topological_basis B"
  using someI_ex[OF ex_countable_basis]
  by unfold_locales safe

instance prod :: (second_countable_topology, second_countable_topology) second_countable_topology
proof
  obtain A :: "'a set set" where "countable A" "topological_basis A"
    using ex_countable_basis by auto
  moreover
  obtain B :: "'b set set" where "countable B" "topological_basis B"
    using ex_countable_basis by auto
  ultimately show "∃B::('a × 'b) set set. countable B ∧ open = generate_topology B"
    by (auto intro!: exI[of _ "(λ(a, b). a × b) ` (A × B)"] topological_basis_prod
      topological_basis_imp_subbasis)
qed

instance second_countable_topology  first_countable_topology
proof
  fix x :: 'a
  define B :: "'a set set" where "B = (SOME B. countable B ∧ topological_basis B)"
  then have B: "countable B" "topological_basis B"
    using countable_basis is_basis
    by (auto simp: countable_basis is_basis)
  then show "∃A::nat ⇒ 'a set.
    (∀i. x ∈ A i ∧ open (A i)) ∧ (∀S. open S ∧ x ∈ S ⟶ (∃i. A i ⊆ S))"
    by (intro first_countableI[of "{b∈B. x ∈ b}"])
       (fastforce simp: topological_space_class.topological_basis_def)+
qed

instance nat :: second_countable_topology
proof
  show "∃B::nat set set. countable B ∧ open = generate_topology B"
    by (intro exI[of _ "range lessThan ∪ range greaterThan"]) (auto simp: open_nat_def)
qed

lemma countable_separating_set_linorder1:
  shows "∃B::('a::{linorder_topology, second_countable_topology} set). countable B ∧ (∀x y. x < y ⟶ (∃b ∈ B. x < b ∧ b ≤ y))"
proof -
  obtain A::"'a set set" where "countable A" "topological_basis A" using ex_countable_basis by auto
  define B1 where "B1 = {(LEAST x. x ∈ U)| U. U ∈ A}"
  then have "countable B1" using ‹countable A› by (simp add: Setcompr_eq_image)
  define B2 where "B2 = {(SOME x. x ∈ U)| U. U ∈ A}"
  then have "countable B2" using ‹countable A› by (simp add: Setcompr_eq_image)
  have "∃b ∈ B1 ∪ B2. x < b ∧ b ≤ y" if "x < y" for x y
  proof (cases)
    assume "∃z. x < z ∧ z < y"
    then obtain z where z: "x < z ∧ z < y" by auto
    define U where "U = {x<..<y}"
    then have "open U" by simp
    moreover have "z ∈ U" using z U_def by simp
    ultimately obtain V where "V ∈ A" "z ∈ V" "V ⊆ U" using topological_basisE[OF ‹topological_basis A›] by auto
    define w where "w = (SOME x. x ∈ V)"
    then have "w ∈ V" using ‹z ∈ V› by (metis someI2)
    then have "x < w ∧ w ≤ y" using ‹w ∈ V› ‹V ⊆ U› U_def by fastforce
    moreover have "w ∈ B1 ∪ B2" using w_def B2_def ‹V ∈ A› by auto
    ultimately show ?thesis by auto
  next
    assume "¬(∃z. x < z ∧ z < y)"
    then have *: "⋀z. z > x ⟹ z ≥ y" by auto
    define U where "U = {x<..}"
    then have "open U" by simp
    moreover have "y ∈ U" using ‹x < y› U_def by simp
    ultimately obtain "V" where "V ∈ A" "y ∈ V" "V ⊆ U" using topological_basisE[OF ‹topological_basis A›] by auto
    have "U = {y..}" unfolding U_def using * ‹x < y› by auto
    then have "V ⊆ {y..}" using ‹V ⊆ U› by simp
    then have "(LEAST w. w ∈ V) = y" using ‹y ∈ V› by (meson Least_equality atLeast_iff subsetCE)
    then have "y ∈ B1 ∪ B2" using ‹V ∈ A› B1_def by auto
    moreover have "x < y ∧ y ≤ y" using ‹x < y› by simp
    ultimately show ?thesis by auto
  qed
  moreover have "countable (B1 ∪ B2)" using ‹countable B1› ‹countable B2› by simp
  ultimately show ?thesis by auto
qed

lemma countable_separating_set_linorder2:
  shows "∃B::('a::{linorder_topology, second_countable_topology} set). countable B ∧ (∀x y. x < y ⟶ (∃b ∈ B. x ≤ b ∧ b < y))"
proof -
  obtain A::"'a set set" where "countable A" "topological_basis A" using ex_countable_basis by auto
  define B1 where "B1 = {(GREATEST x. x ∈ U) | U. U ∈ A}"
  then have "countable B1" using ‹countable A› by (simp add: Setcompr_eq_image)
  define B2 where "B2 = {(SOME x. x ∈ U)| U. U ∈ A}"
  then have "countable B2" using ‹countable A› by (simp add: Setcompr_eq_image)
  have "∃b ∈ B1 ∪ B2. x ≤ b ∧ b < y" if "x < y" for x y
  proof (cases)
    assume "∃z. x < z ∧ z < y"
    then obtain z where z: "x < z ∧ z < y" by auto
    define U where "U = {x<..<y}"
    then have "open U" by simp
    moreover have "z ∈ U" using z U_def by simp
    ultimately obtain "V" where "V ∈ A" "z ∈ V" "V ⊆ U" using topological_basisE[OF ‹topological_basis A›] by auto
    define w where "w = (SOME x. x ∈ V)"
    then have "w ∈ V" using ‹z ∈ V› by (metis someI2)
    then have "x ≤ w ∧ w < y" using ‹w ∈ V› ‹V ⊆ U› U_def by fastforce
    moreover have "w ∈ B1 ∪ B2" using w_def B2_def ‹V ∈ A› by auto
    ultimately show ?thesis by auto
  next
    assume "¬(∃z. x < z ∧ z < y)"
    then have *: "⋀z. z < y ⟹ z ≤ x" using leI by blast
    define U where "U = {..<y}"
    then have "open U" by simp
    moreover have "x ∈ U" using ‹x < y› U_def by simp
    ultimately obtain "V" where "V ∈ A" "x ∈ V" "V ⊆ U" using topological_basisE[OF ‹topological_basis A›] by auto
    have "U = {..x}" unfolding U_def using * ‹x < y› by auto
    then have "V ⊆ {..x}" using ‹V ⊆ U› by simp
    then have "(GREATEST x. x ∈ V) = x" using ‹x ∈ V› by (meson Greatest_equality atMost_iff subsetCE)
    then have "x ∈ B1 ∪ B2" using ‹V ∈ A› B1_def by auto
    moreover have "x ≤ x ∧ x < y" using ‹x < y› by simp
    ultimately show ?thesis by auto
  qed
  moreover have "countable (B1 ∪ B2)" using ‹countable B1› ‹countable B2› by simp
  ultimately show ?thesis by auto
qed

lemma countable_separating_set_dense_linorder:
  shows "∃B::('a::{linorder_topology, dense_linorder, second_countable_topology} set). countable B ∧ (∀x y. x < y ⟶ (∃b ∈ B. x < b ∧ b < y))"
proof -
  obtain B::"'a set" where B: "countable B" "⋀x y. x < y ⟹ (∃b ∈ B. x < b ∧ b ≤ y)"
    using countable_separating_set_linorder1 by auto
  have "∃b ∈ B. x < b ∧ b < y" if "x < y" for x y
  proof -
    obtain z where "x < z" "z < y" using ‹x < y› dense by blast
    then obtain b where "b ∈ B" "x < b ∧ b ≤ z" using B(2) by auto
    then have "x < b ∧ b < y" using ‹z < y› by auto
    then show ?thesis using ‹b ∈ B› by auto
  qed
  then show ?thesis using B(1) by auto
qed

subsection ‹Polish spaces›

text ‹Textbooks define Polish spaces as completely metrizable.
  We assume the topology to be complete for a given metric.›

class polish_space = complete_space + second_countable_topology

subsection ‹General notion of a topology as a value›

definition "istopology L ⟷
  L {} ∧ (∀S T. L S ⟶ L T ⟶ L (S ∩ T)) ∧ (∀K. Ball K L ⟶ L (⋃K))"

typedef 'a topology = "{L::('a set) ⇒ bool. istopology L}"
  morphisms "openin" "topology"
  unfolding istopology_def by blast

lemma istopology_openin[intro]: "istopology(openin U)"
  using openin[of U] by blast

lemma topology_inverse': "istopology U ⟹ openin (topology U) = U"
  using topology_inverse[unfolded mem_Collect_eq] .

lemma topology_inverse_iff: "istopology U ⟷ openin (topology U) = U"
  using topology_inverse[of U] istopology_openin[of "topology U"] by auto

lemma topology_eq: "T1 = T2 ⟷ (∀S. openin T1 S ⟷ openin T2 S)"
proof
  assume "T1 = T2"
  then show "∀S. openin T1 S ⟷ openin T2 S" by simp
next
  assume H: "∀S. openin T1 S ⟷ openin T2 S"
  then have "openin T1 = openin T2" by (simp add: fun_eq_iff)
  then have "topology (openin T1) = topology (openin T2)" by simp
  then show "T1 = T2" unfolding openin_inverse .
qed

text‹Infer the "universe" from union of all sets in the topology.›

definition "topspace T = ⋃{S. openin T S}"

subsubsection ‹Main properties of open sets›

lemma openin_clauses:
  fixes U :: "'a topology"
  shows
    "openin U {}"
    "⋀S T. openin U S ⟹ openin U T ⟹ openin U (S∩T)"
    "⋀K. (∀S ∈ K. openin U S) ⟹ openin U (⋃K)"
  using openin[of U] unfolding istopology_def mem_Collect_eq by fast+

lemma openin_subset[intro]: "openin U S ⟹ S ⊆ topspace U"
  unfolding topspace_def by blast

lemma openin_empty[simp]: "openin U {}"
  by (rule openin_clauses)

lemma openin_Int[intro]: "openin U S ⟹ openin U T ⟹ openin U (S ∩ T)"
  by (rule openin_clauses)

lemma openin_Union[intro]: "(⋀S. S ∈ K ⟹ openin U S) ⟹ openin U (⋃K)"
  using openin_clauses by blast

lemma openin_Un[intro]: "openin U S ⟹ openin U T ⟹ openin U (S ∪ T)"
  using openin_Union[of "{S,T}" U] by auto

lemma openin_topspace[intro, simp]: "openin U (topspace U)"
  by (force simp: openin_Union topspace_def)

lemma openin_subopen: "openin U S ⟷ (∀x ∈ S. ∃T. openin U T ∧ x ∈ T ∧ T ⊆ S)"
  (is "?lhs ⟷ ?rhs")
proof
  assume ?lhs
  then show ?rhs by auto
next
  assume H: ?rhs
  let ?t = "⋃{T. openin U T ∧ T ⊆ S}"
  have "openin U ?t" by (force simp: openin_Union)
  also have "?t = S" using H by auto
  finally show "openin U S" .
qed

lemma openin_INT [intro]:
  assumes "finite I"
          "⋀i. i ∈ I ⟹ openin T (U i)"
  shows "openin T ((⋂i ∈ I. U i) ∩ topspace T)"
using assms by (induct, auto simp: inf_sup_aci(2) openin_Int)

lemma openin_INT2 [intro]:
  assumes "finite I" "I ≠ {}"
          "⋀i. i ∈ I ⟹ openin T (U i)"
  shows "openin T (⋂i ∈ I. U i)"
proof -
  have "(⋂i ∈ I. U i) ⊆ topspace T"
    using ‹I ≠ {}› 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


subsubsection ‹Closed sets›

definition "closedin U S ⟷ S ⊆ topspace U ∧ openin U (topspace U - S)"

lemma closedin_subset: "closedin U S ⟹ S ⊆ topspace U"
  by (metis closedin_def)

lemma closedin_empty[simp]: "closedin U {}"
  by (simp add: closedin_def)

lemma closedin_topspace[intro, simp]: "closedin U (topspace U)"
  by (simp add: closedin_def)

lemma closedin_Un[intro]: "closedin U S ⟹ closedin U T ⟹ closedin U (S ∪ T)"
  by (auto simp: Diff_Un closedin_def)

lemma Diff_Inter[intro]: "A - ⋂S = ⋃{A - s|s. s∈S}"
  by auto

lemma closedin_Union:
  assumes "finite S" "⋀T. T ∈ S ⟹ closedin U T"
    shows "closedin U (⋃S)"
  using assms by induction auto

lemma closedin_Inter[intro]:
  assumes Ke: "K ≠ {}"
    and Kc: "⋀S. S ∈K ⟹ closedin U S"
  shows "closedin U (⋂K)"
  using Ke Kc unfolding closedin_def Diff_Inter by auto

lemma closedin_INT[intro]:
  assumes "A ≠ {}" "⋀x. x ∈ A ⟹ closedin U (B x)"
  shows "closedin U (⋂x∈A. B x)"
  apply (rule closedin_Inter)
  using assms
  apply auto
  done

lemma closedin_Int[intro]: "closedin U S ⟹ closedin U T ⟹ closedin U (S ∩ T)"
  using closedin_Inter[of "{S,T}" U] by auto

lemma openin_closedin_eq: "openin U S ⟷ S ⊆ topspace U ∧ closedin U (topspace U - S)"
  apply (auto simp: closedin_def Diff_Diff_Int inf_absorb2)
  apply (metis openin_subset subset_eq)
  done

lemma openin_closedin: "S ⊆ topspace U ⟹ (openin U S ⟷ closedin U (topspace U - S))"
  by (simp add: openin_closedin_eq)

lemma openin_diff[intro]:
  assumes oS: "openin U S"
    and cT: "closedin U T"
  shows "openin U (S - T)"
proof -
  have "S - T = S ∩ (topspace U - T)" using openin_subset[of U S]  oS cT
    by (auto simp: topspace_def openin_subset)
  then show ?thesis using oS cT
    by (auto simp: closedin_def)
qed

lemma closedin_diff[intro]:
  assumes oS: "closedin U S"
    and cT: "openin U T"
  shows "closedin U (S - T)"
proof -
  have "S - T = S ∩ (topspace U - T)"
    using closedin_subset[of U S] oS cT by (auto simp: topspace_def)
  then show ?thesis
    using oS cT by (auto simp: openin_closedin_eq)
qed


subsubsection ‹Subspace topology›

definition "subtopology U V = topology (λT. ∃S. T = S ∩ V ∧ openin U S)"

lemma istopology_subtopology: "istopology (λT. ∃S. T = S ∩ V ∧ openin U S)"
  (is "istopology ?L")
proof -
  have "?L {}" by blast
  {
    fix A B
    assume A: "?L A" and B: "?L B"
    from A B obtain Sa and Sb where Sa: "openin U Sa" "A = Sa ∩ V" and Sb: "openin U Sb" "B = Sb ∩ V"
      by blast
    have "A ∩ B = (Sa ∩ Sb) ∩ V" "openin U (Sa ∩ Sb)"
      using Sa Sb by blast+
    then have "?L (A ∩ B)" by blast
  }
  moreover
  {
    fix K
    assume K: "K ⊆ Collect ?L"
    have th0: "Collect ?L = (λS. S ∩ V) ` Collect (openin U)"
      by blast
    from K[unfolded th0 subset_image_iff]
    obtain Sk where Sk: "Sk ⊆ Collect (openin U)" "K = (λS. S ∩ V) ` Sk"
      by blast
    have "⋃K = (⋃Sk) ∩ V"
      using Sk by auto
    moreover have "openin U (⋃Sk)"
      using Sk by (auto simp: subset_eq)
    ultimately have "?L (⋃K)" by blast
  }
  ultimately show ?thesis
    unfolding subset_eq mem_Collect_eq istopology_def by auto
qed

lemma openin_subtopology: "openin (subtopology U V) S ⟷ (∃T. openin U T ∧ S = T ∩ V)"
  unfolding subtopology_def topology_inverse'[OF istopology_subtopology]
  by auto

lemma topspace_subtopology: "topspace (subtopology U V) = topspace U ∩ V"
  by (auto simp: topspace_def openin_subtopology)

lemma closedin_subtopology: "closedin (subtopology U V) S ⟷ (∃T. closedin U T ∧ S = T ∩ V)"
  unfolding closedin_def topspace_subtopology
  by (auto simp: openin_subtopology)

lemma openin_subtopology_refl: "openin (subtopology U V) V ⟷ V ⊆ topspace U"
  unfolding openin_subtopology
  by auto (metis IntD1 in_mono openin_subset)

lemma subtopology_superset:
  assumes UV: "topspace U ⊆ V"
  shows "subtopology U V = U"
proof -
  {
    fix S
    {
      fix T
      assume T: "openin U T" "S = T ∩ V"
      from T openin_subset[OF T(1)] UV have eq: "S = T"
        by blast
      have "openin U S"
        unfolding eq using T by blast
    }
    moreover
    {
      assume S: "openin U S"
      then have "∃T. openin U T ∧ S = T ∩ V"
        using openin_subset[OF S] UV by auto
    }
    ultimately have "(∃T. openin U T ∧ S = T ∩ V) ⟷ openin U S"
      by blast
  }
  then show ?thesis
    unfolding topology_eq openin_subtopology by blast
qed

lemma subtopology_topspace[simp]: "subtopology U (topspace U) = U"
  by (simp add: subtopology_superset)

lemma subtopology_UNIV[simp]: "subtopology U UNIV = U"
  by (simp add: subtopology_superset)

lemma openin_subtopology_empty:
   "openin (subtopology U {}) S ⟷ S = {}"
by (metis Int_empty_right openin_empty openin_subtopology)

lemma closedin_subtopology_empty:
   "closedin (subtopology U {}) S ⟷ S = {}"
by (metis Int_empty_right closedin_empty closedin_subtopology)

lemma closedin_subtopology_refl [simp]:
   "closedin (subtopology U X) X ⟷ X ⊆ topspace U"
by (metis closedin_def closedin_topspace inf.absorb_iff2 le_inf_iff topspace_subtopology)

lemma openin_imp_subset:
   "openin (subtopology U S) T ⟹ T ⊆ S"
by (metis Int_iff openin_subtopology subsetI)

lemma closedin_imp_subset:
   "closedin (subtopology U S) T ⟹ T ⊆ S"
by (simp add: closedin_def topspace_subtopology)

lemma openin_subtopology_Un:
    "openin (subtopology U T) S ∧ openin (subtopology U u) S
     ⟹ openin (subtopology U (T ∪ u)) S"
by (simp add: openin_subtopology) blast


subsubsection ‹The standard Euclidean topology›

definition euclidean :: "'a::topological_space topology"
  where "euclidean = topology open"

lemma open_openin: "open S ⟷ openin euclidean S"
  unfolding euclidean_def
  apply (rule cong[where x=S and y=S])
  apply (rule topology_inverse[symmetric])
  apply (auto simp: istopology_def)
  done

declare open_openin [symmetric, simp]

lemma topspace_euclidean [simp]: "topspace euclidean = UNIV"
  by (force simp: topspace_def)

lemma topspace_euclidean_subtopology[simp]: "topspace (subtopology euclidean S) = S"
  by (simp add: topspace_subtopology)

lemma closed_closedin: "closed S ⟷ closedin euclidean S"
  by (simp add: closed_def closedin_def Compl_eq_Diff_UNIV)

lemma open_subopen: "open S ⟷ (∀x∈S. ∃T. open T ∧ x ∈ T ∧ T ⊆ S)"
  using openI by auto

lemma openin_subtopology_self [simp]: "openin (subtopology euclidean S) S"
  by (metis openin_topspace topspace_euclidean_subtopology)

text ‹Basic "localization" results are handy for connectedness.›

lemma openin_open: "openin (subtopology euclidean U) S ⟷ (∃T. open T ∧ (S = U ∩ T))"
  by (auto simp: openin_subtopology)

lemma openin_Int_open:
   "⟦openin (subtopology euclidean U) S; open T⟧
        ⟹ openin (subtopology euclidean U) (S ∩ T)"
by (metis open_Int Int_assoc openin_open)

lemma openin_open_Int[intro]: "open S ⟹ openin (subtopology euclidean U) (U ∩ S)"
  by (auto simp: openin_open)

lemma open_openin_trans[trans]:
  "open S ⟹ open T ⟹ T ⊆ S ⟹ openin (subtopology euclidean S) T"
  by (metis Int_absorb1  openin_open_Int)

lemma open_subset: "S ⊆ T ⟹ open S ⟹ openin (subtopology euclidean T) S"
  by (auto simp: openin_open)

lemma closedin_closed: "closedin (subtopology euclidean U) S ⟷ (∃T. closed T ∧ S = U ∩ T)"
  by (simp add: closedin_subtopology closed_closedin Int_ac)

lemma closedin_closed_Int: "closed S ⟹ closedin (subtopology euclidean U) (U ∩ S)"
  by (metis closedin_closed)

lemma closed_subset: "S ⊆ T ⟹ closed S ⟹ closedin (subtopology euclidean T) S"
  by (auto simp: closedin_closed)

lemma closedin_closed_subset:
 "⟦closedin (subtopology euclidean U) V; T ⊆ U; S = V ∩ T⟧
             ⟹ closedin (subtopology euclidean T) S"
  by (metis (no_types, lifting) Int_assoc Int_commute closedin_closed inf.orderE)

lemma finite_imp_closedin:
  fixes S :: "'a::t1_space set"
  shows "⟦finite S; S ⊆ T⟧ ⟹ closedin (subtopology euclidean T) S"
    by (simp add: finite_imp_closed closed_subset)

lemma closedin_singleton [simp]:
  fixes a :: "'a::t1_space"
  shows "closedin (subtopology euclidean U) {a} ⟷ a ∈ U"
using closedin_subset  by (force intro: closed_subset)

lemma openin_euclidean_subtopology_iff:
  fixes S U :: "'a::metric_space set"
  shows "openin (subtopology euclidean U) S ⟷
    S ⊆ U ∧ (∀x∈S. ∃e>0. ∀x'∈U. dist x' x < e ⟶ x'∈ S)"
  (is "?lhs ⟷ ?rhs")
proof
  assume ?lhs
  then show ?rhs
    unfolding openin_open open_dist by blast
next
  define T where "T = {x. ∃a∈S. ∃d>0. (∀y∈U. dist y a < d ⟶ y ∈ S) ∧ dist x a < d}"
  have 1: "∀x∈T. ∃e>0. ∀y. dist y x < e ⟶ y ∈ T"
    unfolding T_def
    apply clarsimp
    apply (rule_tac x="d - dist x a" in exI)
    apply (clarsimp simp add: less_diff_eq)
    by (metis dist_commute dist_triangle_lt)
  assume ?rhs then have 2: "S = U ∩ T"
    unfolding T_def
    by auto (metis dist_self)
  from 1 2 show ?lhs
    unfolding openin_open open_dist by fast
qed

lemma connected_openin:
      "connected s ⟷
       ~(∃e1 e2. openin (subtopology euclidean s) e1 ∧
                 openin (subtopology euclidean s) e2 ∧
                 s ⊆ e1 ∪ e2 ∧ e1 ∩ e2 = {} ∧ e1 ≠ {} ∧ e2 ≠ {})"
  apply (simp add: connected_def openin_open, safe)
  apply (simp_all, blast+)  (* SLOW *)
  done

lemma connected_openin_eq:
      "connected s ⟷
       ~(∃e1 e2. openin (subtopology euclidean s) e1 ∧
                 openin (subtopology euclidean s) e2 ∧
                 e1 ∪ e2 = s ∧ e1 ∩ e2 = {} ∧
                 e1 ≠ {} ∧ e2 ≠ {})"
  apply (simp add: connected_openin, safe, blast)
  by (metis Int_lower1 Un_subset_iff openin_open subset_antisym)

lemma connected_closedin:
      "connected s ⟷
       ~(∃e1 e2.
             closedin (subtopology euclidean s) e1 ∧
             closedin (subtopology euclidean s) e2 ∧
             s ⊆ e1 ∪ e2 ∧ e1 ∩ e2 = {} ∧
             e1 ≠ {} ∧ e2 ≠ {})"
proof -
  { fix A B x x'
    assume s_sub: "s ⊆ A ∪ B"
       and disj: "A ∩ B ∩ s = {}"
       and x: "x ∈ s" "x ∈ B" and x': "x' ∈ s" "x' ∈ A"
       and cl: "closed A" "closed B"
    assume "∀e1. (∀T. closed T ⟶ e1 ≠ s ∩ T) ∨ (∀e2. e1 ∩ e2 = {} ⟶ s ⊆ e1 ∪ e2 ⟶ (∀T. closed T ⟶ e2 ≠ s ∩ T) ∨ e1 = {} ∨ e2 = {})"
    then have "⋀C D. s ∩ C = {} ∨ s ∩ D = {} ∨ s ∩ (C ∩ (s ∩ D)) ≠ {} ∨ ¬ s ⊆ s ∩ (C ∪ D) ∨ ¬ closed C ∨ ¬ closed D"
      by (metis (no_types) Int_Un_distrib Int_assoc)
    moreover have "s ∩ (A ∩ B) = {}" "s ∩ (A ∪ B) = s" "s ∩ B ≠ {}"
      using disj s_sub x by blast+
    ultimately have "s ∩ A = {}"
      using cl by (metis inf.left_commute inf_bot_right order_refl)
    then have False
      using x' by blast
  } note * = this
  show ?thesis
    apply (simp add: connected_closed closedin_closed)
    apply (safe; simp)
    apply blast
    apply (blast intro: *)
    done
qed

lemma connected_closedin_eq:
      "connected s ⟷
           ~(∃e1 e2.
                 closedin (subtopology euclidean s) e1 ∧
                 closedin (subtopology euclidean s) e2 ∧
                 e1 ∪ e2 = s ∧ e1 ∩ e2 = {} ∧
                 e1 ≠ {} ∧ e2 ≠ {})"
  apply (simp add: connected_closedin, safe, blast)
  by (metis Int_lower1 Un_subset_iff closedin_closed subset_antisym)

text ‹These "transitivity" results are handy too›

lemma openin_trans[trans]:
  "openin (subtopology euclidean T) S ⟹ openin (subtopology euclidean U) T ⟹
    openin (subtopology euclidean U) S"
  unfolding open_openin openin_open by blast

lemma openin_open_trans: "openin (subtopology euclidean T) S ⟹ open T ⟹ open S"
  by (auto simp: openin_open intro: openin_trans)

lemma closedin_trans[trans]:
  "closedin (subtopology euclidean T) S ⟹ closedin (subtopology euclidean U) T ⟹
    closedin (subtopology euclidean U) S"
  by (auto simp: closedin_closed closed_closedin closed_Inter Int_assoc)

lemma closedin_closed_trans: "closedin (subtopology euclidean T) S ⟹ closed T ⟹ closed S"
  by (auto simp: closedin_closed intro: closedin_trans)

lemma openin_subtopology_Int_subset:
   "⟦openin (subtopology euclidean u) (u ∩ S); v ⊆ u⟧ ⟹ openin (subtopology euclidean v) (v ∩ S)"
  by (auto simp: openin_subtopology)

lemma openin_open_eq: "open s ⟹ (openin (subtopology euclidean s) t ⟷ open t ∧ t ⊆ s)"
  using open_subset openin_open_trans openin_subset by fastforce


subsection ‹Open and closed balls›

definition ball :: "'a::metric_space ⇒ real ⇒ 'a set"
  where "ball x e = {y. dist x y < e}"

definition cball :: "'a::metric_space ⇒ real ⇒ 'a set"
  where "cball x e = {y. dist x y ≤ e}"

definition sphere :: "'a::metric_space ⇒ real ⇒ 'a set"
  where "sphere x e = {y. dist x y = e}"

lemma mem_ball [simp]: "y ∈ ball x e ⟷ dist x y < e"
  by (simp add: ball_def)

lemma mem_cball [simp]: "y ∈ cball x e ⟷ dist x y ≤ e"
  by (simp add: cball_def)

lemma mem_sphere [simp]: "y ∈ sphere x e ⟷ dist x y = e"
  by (simp add: sphere_def)

lemma ball_trivial [simp]: "ball x 0 = {}"
  by (simp add: ball_def)

lemma cball_trivial [simp]: "cball x 0 = {x}"
  by (simp add: cball_def)

lemma sphere_trivial [simp]: "sphere x 0 = {x}"
  by (simp add: sphere_def)

lemma mem_ball_0 [simp]: "x ∈ ball 0 e ⟷ norm x < e"
  for x :: "'a::real_normed_vector"
  by (simp add: dist_norm)

lemma mem_cball_0 [simp]: "x ∈ cball 0 e ⟷ norm x ≤ e"
  for x :: "'a::real_normed_vector"
  by (simp add: dist_norm)

lemma disjoint_ballI: "dist x y ≥ r+s ⟹ ball x r ∩ ball y s = {}"
  using dist_triangle_less_add not_le by fastforce

lemma disjoint_cballI: "dist x y > r + s ⟹ cball x r ∩ cball y s = {}"
  by (metis add_mono disjoint_iff_not_equal dist_triangle2 dual_order.trans leD mem_cball)

lemma mem_sphere_0 [simp]: "x ∈ sphere 0 e ⟷ norm x = e"
  for x :: "'a::real_normed_vector"
  by (simp add: dist_norm)

lemma sphere_empty [simp]: "r < 0 ⟹ sphere a r = {}"
  for a :: "'a::metric_space"
  by auto

lemma centre_in_ball [simp]: "x ∈ ball x e ⟷ 0 < e"
  by simp

lemma centre_in_cball [simp]: "x ∈ cball x e ⟷ 0 ≤ e"
  by simp

lemma ball_subset_cball [simp, intro]: "ball x e ⊆ cball x e"
  by (simp add: subset_eq)

lemma sphere_cball [simp,intro]: "sphere z r ⊆ cball z r"
  by force

lemma cball_diff_sphere: "cball a r - sphere a r = ball a r"
  by auto

lemma subset_ball[intro]: "d ≤ e ⟹ ball x d ⊆ ball x e"
  by (simp add: subset_eq)

lemma subset_cball[intro]: "d ≤ e ⟹ cball x d ⊆ cball x e"
  by (simp add: subset_eq)

lemma ball_max_Un: "ball a (max r s) = ball a r ∪ ball a s"
  by (simp add: set_eq_iff) arith

lemma ball_min_Int: "ball a (min r s) = ball a r ∩ ball a s"
  by (simp add: set_eq_iff)

lemma cball_max_Un: "cball a (max r s) = cball a r ∪ cball a s"
  by (simp add: set_eq_iff) arith

lemma cball_min_Int: "cball a (min r s) = cball a r ∩ cball a s"
  by (simp add: set_eq_iff)

lemma cball_diff_eq_sphere: "cball a r - ball a r =  sphere a r"
  by (auto simp: cball_def ball_def dist_commute)

lemma image_add_ball [simp]:
  fixes a :: "'a::real_normed_vector"
  shows "op + b ` ball a r = ball (a+b) r"
apply (intro equalityI subsetI)
apply (force simp: dist_norm)
apply (rule_tac x="x-b" in image_eqI)
apply (auto simp: dist_norm algebra_simps)
done

lemma image_add_cball [simp]:
  fixes a :: "'a::real_normed_vector"
  shows "op + b ` cball a r = cball (a+b) r"
apply (intro equalityI subsetI)
apply (force simp: dist_norm)
apply (rule_tac x="x-b" in image_eqI)
apply (auto simp: dist_norm algebra_simps)
done

lemma open_ball [intro, simp]: "open (ball x e)"
proof -
  have "open (dist x -` {..<e})"
    by (intro open_vimage open_lessThan continuous_intros)
  also have "dist x -` {..<e} = ball x e"
    by auto
  finally show ?thesis .
qed

lemma open_contains_ball: "open S ⟷ (∀x∈S. ∃e>0. ball x e ⊆ S)"
  by (simp add: open_dist subset_eq mem_ball Ball_def dist_commute)

lemma openI [intro?]: "(⋀x. x∈S ⟹ ∃e>0. ball x e ⊆ S) ⟹ open S"
  by (auto simp: open_contains_ball)

lemma openE[elim?]:
  assumes "open S" "x∈S"
  obtains e where "e>0" "ball x e ⊆ S"
  using assms unfolding open_contains_ball by auto

lemma open_contains_ball_eq: "open S ⟹ x∈S ⟷ (∃e>0. ball x e ⊆ S)"
  by (metis open_contains_ball subset_eq centre_in_ball)

lemma openin_contains_ball:
    "openin (subtopology euclidean t) s ⟷
     s ⊆ t ∧ (∀x ∈ s. ∃e. 0 < e ∧ ball x e ∩ t ⊆ s)"
    (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    apply (simp add: openin_open)
    apply (metis Int_commute Int_mono inf.cobounded2 open_contains_ball order_refl subsetCE)
    done
next
  assume ?rhs
  then show ?lhs
    apply (simp add: openin_euclidean_subtopology_iff)
    by (metis (no_types) Int_iff dist_commute inf.absorb_iff2 mem_ball)
qed

lemma openin_contains_cball:
   "openin (subtopology euclidean t) s ⟷
        s ⊆ t ∧
        (∀x ∈ s. ∃e. 0 < e ∧ cball x e ∩ t ⊆ s)"
apply (simp add: openin_contains_ball)
apply (rule iffI)
apply (auto dest!: bspec)
apply (rule_tac x="e/2" in exI, force+)
done

lemma ball_eq_empty[simp]: "ball x e = {} ⟷ e ≤ 0"
  unfolding mem_ball set_eq_iff
  apply (simp add: not_less)
  apply (metis zero_le_dist order_trans dist_self)
  done

lemma ball_empty: "e ≤ 0 ⟹ ball x e = {}" by simp

lemma euclidean_dist_l2:
  fixes x y :: "'a :: euclidean_space"
  shows "dist x y = setL2 (λi. dist (x ∙ i) (y ∙ i)) Basis"
  unfolding dist_norm norm_eq_sqrt_inner setL2_def
  by (subst euclidean_inner) (simp add: power2_eq_square inner_diff_left)

lemma eventually_nhds_ball: "d > 0 ⟹ eventually (λx. x ∈ ball z d) (nhds z)"
  by (rule eventually_nhds_in_open) simp_all

lemma eventually_at_ball: "d > 0 ⟹ eventually (λt. t ∈ ball z d ∧ t ∈ A) (at z within A)"
  unfolding eventually_at by (intro exI[of _ d]) (simp_all add: dist_commute)

lemma eventually_at_ball': "d > 0 ⟹ eventually (λt. t ∈ ball z d ∧ t ≠ z ∧ t ∈ A) (at z within A)"
  unfolding eventually_at by (intro exI[of _ d]) (simp_all add: dist_commute)


subsection ‹Boxes›

abbreviation One :: "'a::euclidean_space"
  where "One ≡ ∑Basis"

lemma One_non_0: assumes "One = (0::'a::euclidean_space)" shows False
proof -
  have "dependent (Basis :: 'a set)"
    apply (simp add: dependent_finite)
    apply (rule_tac x="λi. 1" in exI)
    using SOME_Basis apply (auto simp: assms)
    done
  with independent_Basis show False by force
qed

corollary One_neq_0[iff]: "One ≠ 0"
  by (metis One_non_0)

corollary Zero_neq_One[iff]: "0 ≠ One"
  by (metis One_non_0)

definition (in euclidean_space) eucl_less (infix "<e" 50)
  where "eucl_less a b ⟷ (∀i∈Basis. a ∙ i < b ∙ i)"

definition box_eucl_less: "box a b = {x. a <e x ∧ x <e b}"
definition "cbox a b = {x. ∀i∈Basis. a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i}"

lemma box_def: "box a b = {x. ∀i∈Basis. a ∙ i < x ∙ i ∧ x ∙ i < b ∙ i}"
  and in_box_eucl_less: "x ∈ box a b ⟷ a <e x ∧ x <e b"
  and mem_box: "x ∈ box a b ⟷ (∀i∈Basis. a ∙ i < x ∙ i ∧ x ∙ i < b ∙ i)"
    "x ∈ cbox a b ⟷ (∀i∈Basis. a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i)"
  by (auto simp: box_eucl_less eucl_less_def cbox_def)

lemma cbox_Pair_eq: "cbox (a, c) (b, d) = cbox a b × cbox c d"
  by (force simp: cbox_def Basis_prod_def)

lemma cbox_Pair_iff [iff]: "(x, y) ∈ cbox (a, c) (b, d) ⟷ x ∈ cbox a b ∧ y ∈ cbox c d"
  by (force simp: cbox_Pair_eq)

lemma cbox_Complex_eq: "cbox (Complex a c) (Complex b d) = (λ(x,y). Complex x y) ` (cbox a b × cbox c d)"
  apply (auto simp: cbox_def Basis_complex_def)
  apply (rule_tac x = "(Re x, Im x)" in image_eqI)
  using complex_eq by auto

lemma cbox_Pair_eq_0: "cbox (a, c) (b, d) = {} ⟷ cbox a b = {} ∨ cbox c d = {}"
  by (force simp: cbox_Pair_eq)

lemma swap_cbox_Pair [simp]: "prod.swap ` cbox (c, a) (d, b) = cbox (a,c) (b,d)"
  by auto

lemma mem_box_real[simp]:
  "(x::real) ∈ box a b ⟷ a < x ∧ x < b"
  "(x::real) ∈ cbox a b ⟷ a ≤ x ∧ x ≤ b"
  by (auto simp: mem_box)

lemma box_real[simp]:
  fixes a b:: real
  shows "box a b = {a <..< b}" "cbox a b = {a .. b}"
  by auto

lemma box_Int_box:
  fixes a :: "'a::euclidean_space"
  shows "box a b ∩ box c d =
    box (∑i∈Basis. max (a∙i) (c∙i) *R i) (∑i∈Basis. min (b∙i) (d∙i) *R i)"
  unfolding set_eq_iff and Int_iff and mem_box by auto

lemma rational_boxes:
  fixes x :: "'a::euclidean_space"
  assumes "e > 0"
  shows "∃a b. (∀i∈Basis. a ∙ i ∈ ℚ ∧ b ∙ i ∈ ℚ) ∧ x ∈ box a b ∧ box a b ⊆ ball x e"
proof -
  define e' where "e' = e / (2 * sqrt (real (DIM ('a))))"
  then have e: "e' > 0"
    using assms by (auto simp: DIM_positive)
  have "∀i. ∃y. y ∈ ℚ ∧ y < x ∙ i ∧ x ∙ i - y < e'" (is "∀i. ?th i")
  proof
    fix i
    from Rats_dense_in_real[of "x ∙ i - e'" "x ∙ i"] e
    show "?th i" by auto
  qed
  from choice[OF this] obtain a where
    a: "∀xa. a xa ∈ ℚ ∧ a xa < x ∙ xa ∧ x ∙ xa - a xa < e'" ..
  have "∀i. ∃y. y ∈ ℚ ∧ x ∙ i < y ∧ y - x ∙ i < e'" (is "∀i. ?th i")
  proof
    fix i
    from Rats_dense_in_real[of "x ∙ i" "x ∙ i + e'"] e
    show "?th i" by auto
  qed
  from choice[OF this] obtain b where
    b: "∀xa. b xa ∈ ℚ ∧ x ∙ xa < b xa ∧ b xa - x ∙ xa < e'" ..
  let ?a = "∑i∈Basis. a i *R i" and ?b = "∑i∈Basis. b i *R i"
  show ?thesis
  proof (rule exI[of _ ?a], rule exI[of _ ?b], safe)
    fix y :: 'a
    assume *: "y ∈ box ?a ?b"
    have "dist x y = sqrt (∑i∈Basis. (dist (x ∙ i) (y ∙ i))2)"
      unfolding setL2_def[symmetric] by (rule euclidean_dist_l2)
    also have "… < sqrt (∑(i::'a)∈Basis. e^2 / real (DIM('a)))"
    proof (rule real_sqrt_less_mono, rule sum_strict_mono)
      fix i :: "'a"
      assume i: "i ∈ Basis"
      have "a i < y∙i ∧ y∙i < b i"
        using * i by (auto simp: box_def)
      moreover have "a i < x∙i" "x∙i - a i < e'"
        using a by auto
      moreover have "x∙i < b i" "b i - x∙i < e'"
        using b by auto
      ultimately have "¦x∙i - y∙i¦ < 2 * e'"
        by auto
      then have "dist (x ∙ i) (y ∙ i) < e/sqrt (real (DIM('a)))"
        unfolding e'_def by (auto simp: dist_real_def)
      then have "(dist (x ∙ i) (y ∙ i))2 < (e/sqrt (real (DIM('a))))2"
        by (rule power_strict_mono) auto
      then show "(dist (x ∙ i) (y ∙ i))2 < e2 / real DIM('a)"
        by (simp add: power_divide)
    qed auto
    also have "… = e"
      using ‹0 < e› by simp
    finally show "y ∈ ball x e"
      by (auto simp: ball_def)
  qed (insert a b, auto simp: box_def)
qed

lemma open_UNION_box:
  fixes M :: "'a::euclidean_space set"
  assumes "open M"
  defines "a' ≡ λf :: 'a ⇒ real × real. (∑(i::'a)∈Basis. fst (f i) *R i)"
  defines "b' ≡ λf :: 'a ⇒ real × real. (∑(i::'a)∈Basis. snd (f i) *R i)"
  defines "I ≡ {f∈Basis →E ℚ × ℚ. box (a' f) (b' f) ⊆ M}"
  shows "M = (⋃f∈I. box (a' f) (b' f))"
proof -
  have "x ∈ (⋃f∈I. box (a' f) (b' f))" if "x ∈ M" for x
  proof -
    obtain e where e: "e > 0" "ball x e ⊆ M"
      using openE[OF ‹open M› ‹x ∈ M›] by auto
    moreover obtain a b where ab:
      "x ∈ box a b"
      "∀i ∈ Basis. a ∙ i ∈ ℚ"
      "∀i∈Basis. b ∙ i ∈ ℚ"
      "box a b ⊆ ball x e"
      using rational_boxes[OF e(1)] by metis
    ultimately show ?thesis
       by (intro UN_I[of "λi∈Basis. (a ∙ i, b ∙ i)"])
          (auto simp: euclidean_representation I_def a'_def b'_def)
  qed
  then show ?thesis by (auto simp: I_def)
qed

corollary open_countable_Union_open_box:
  fixes S :: "'a :: euclidean_space set"
  assumes "open S"
  obtains 𝒟 where "countable 𝒟" "𝒟 ⊆ Pow S" "⋀X. X ∈ 𝒟 ⟹ ∃a b. X = box a b" "⋃𝒟 = S"
proof -
  let ?a = "λf. (∑(i::'a)∈Basis. fst (f i) *R i)"
  let ?b = "λf. (∑(i::'a)∈Basis. snd (f i) *R i)"
  let ?I = "{f∈Basis →E ℚ × ℚ. box (?a f) (?b f) ⊆ S}"
  let ?𝒟 = "(λf. box (?a f) (?b f)) ` ?I"
  show ?thesis
  proof
    have "countable ?I"
      by (simp add: countable_PiE countable_rat)
    then show "countable ?𝒟"
      by blast
    show "⋃?𝒟 = S"
      using open_UNION_box [OF assms] by metis
  qed auto
qed

lemma rational_cboxes:
  fixes x :: "'a::euclidean_space"
  assumes "e > 0"
  shows "∃a b. (∀i∈Basis. a ∙ i ∈ ℚ ∧ b ∙ i ∈ ℚ) ∧ x ∈ cbox a b ∧ cbox a b ⊆ ball x e"
proof -
  define e' where "e' = e / (2 * sqrt (real (DIM ('a))))"
  then have e: "e' > 0"
    using assms by auto
  have "∀i. ∃y. y ∈ ℚ ∧ y < x ∙ i ∧ x ∙ i - y < e'" (is "∀i. ?th i")
  proof
    fix i
    from Rats_dense_in_real[of "x ∙ i - e'" "x ∙ i"] e
    show "?th i" by auto
  qed
  from choice[OF this] obtain a where
    a: "∀u. a u ∈ ℚ ∧ a u < x ∙ u ∧ x ∙ u - a u < e'" ..
  have "∀i. ∃y. y ∈ ℚ ∧ x ∙ i < y ∧ y - x ∙ i < e'" (is "∀i. ?th i")
  proof
    fix i
    from Rats_dense_in_real[of "x ∙ i" "x ∙ i + e'"] e
    show "?th i" by auto
  qed
  from choice[OF this] obtain b where
    b: "∀u. b u ∈ ℚ ∧ x ∙ u < b u ∧ b u - x ∙ u < e'" ..
  let ?a = "∑i∈Basis. a i *R i" and ?b = "∑i∈Basis. b i *R i"
  show ?thesis
  proof (rule exI[of _ ?a], rule exI[of _ ?b], safe)
    fix y :: 'a
    assume *: "y ∈ cbox ?a ?b"
    have "dist x y = sqrt (∑i∈Basis. (dist (x ∙ i) (y ∙ i))2)"
      unfolding setL2_def[symmetric] by (rule euclidean_dist_l2)
    also have "… < sqrt (∑(i::'a)∈Basis. e^2 / real (DIM('a)))"
    proof (rule real_sqrt_less_mono, rule sum_strict_mono)
      fix i :: "'a"
      assume i: "i ∈ Basis"
      have "a i ≤ y∙i ∧ y∙i ≤ b i"
        using * i by (auto simp: cbox_def)
      moreover have "a i < x∙i" "x∙i - a i < e'"
        using a by auto
      moreover have "x∙i < b i" "b i - x∙i < e'"
        using b by auto
      ultimately have "¦x∙i - y∙i¦ < 2 * e'"
        by auto
      then have "dist (x ∙ i) (y ∙ i) < e/sqrt (real (DIM('a)))"
        unfolding e'_def by (auto simp: dist_real_def)
      then have "(dist (x ∙ i) (y ∙ i))2 < (e/sqrt (real (DIM('a))))2"
        by (rule power_strict_mono) auto
      then show "(dist (x ∙ i) (y ∙ i))2 < e2 / real DIM('a)"
        by (simp add: power_divide)
    qed auto
    also have "… = e"
      using ‹0 < e› by simp
    finally show "y ∈ ball x e"
      by (auto simp: ball_def)
  next
    show "x ∈ cbox (∑i∈Basis. a i *R i) (∑i∈Basis. b i *R i)"
      using a b less_imp_le by (auto simp: cbox_def)
  qed (use a b cbox_def in auto)
qed

lemma open_UNION_cbox:
  fixes M :: "'a::euclidean_space set"
  assumes "open M"
  defines "a' ≡ λf. (∑(i::'a)∈Basis. fst (f i) *R i)"
  defines "b' ≡ λf. (∑(i::'a)∈Basis. snd (f i) *R i)"
  defines "I ≡ {f∈Basis →E ℚ × ℚ. cbox (a' f) (b' f) ⊆ M}"
  shows "M = (⋃f∈I. cbox (a' f) (b' f))"
proof -
  have "x ∈ (⋃f∈I. cbox (a' f) (b' f))" if "x ∈ M" for x
  proof -
    obtain e where e: "e > 0" "ball x e ⊆ M"
      using openE[OF ‹open M› ‹x ∈ M›] by auto
    moreover obtain a b where ab: "x ∈ cbox a b" "∀i ∈ Basis. a ∙ i ∈ ℚ"
                                  "∀i ∈ Basis. b ∙ i ∈ ℚ" "cbox a b ⊆ ball x e"
      using rational_cboxes[OF e(1)] by metis
    ultimately show ?thesis
       by (intro UN_I[of "λi∈Basis. (a ∙ i, b ∙ i)"])
          (auto simp: euclidean_representation I_def a'_def b'_def)
  qed
  then show ?thesis by (auto simp: I_def)
qed

corollary open_countable_Union_open_cbox:
  fixes S :: "'a :: euclidean_space set"
  assumes "open S"
  obtains 𝒟 where "countable 𝒟" "𝒟 ⊆ Pow S" "⋀X. X ∈ 𝒟 ⟹ ∃a b. X = cbox a b" "⋃𝒟 = S"
proof -
  let ?a = "λf. (∑(i::'a)∈Basis. fst (f i) *R i)"
  let ?b = "λf. (∑(i::'a)∈Basis. snd (f i) *R i)"
  let ?I = "{f∈Basis →E ℚ × ℚ. cbox (?a f) (?b f) ⊆ S}"
  let ?𝒟 = "(λf. cbox (?a f) (?b f)) ` ?I"
  show ?thesis
  proof
    have "countable ?I"
      by (simp add: countable_PiE countable_rat)
    then show "countable ?𝒟"
      by blast
    show "⋃?𝒟 = S"
      using open_UNION_cbox [OF assms] by metis
  qed auto
qed

lemma box_eq_empty:
  fixes a :: "'a::euclidean_space"
  shows "(box a b = {} ⟷ (∃i∈Basis. b∙i ≤ a∙i))" (is ?th1)
    and "(cbox a b = {} ⟷ (∃i∈Basis. b∙i < a∙i))" (is ?th2)
proof -
  {
    fix i x
    assume i: "i∈Basis" and as:"b∙i ≤ a∙i" and x:"x∈box a b"
    then have "a ∙ i < x ∙ i ∧ x ∙ i < b ∙ i"
      unfolding mem_box by (auto simp: box_def)
    then have "a∙i < b∙i" by auto
    then have False using as by auto
  }
  moreover
  {
    assume as: "∀i∈Basis. ¬ (b∙i ≤ a∙i)"
    let ?x = "(1/2) *R (a + b)"
    {
      fix i :: 'a
      assume i: "i ∈ Basis"
      have "a∙i < b∙i"
        using as[THEN bspec[where x=i]] i by auto
      then have "a∙i < ((1/2) *R (a+b)) ∙ i" "((1/2) *R (a+b)) ∙ i < b∙i"
        by (auto simp: inner_add_left)
    }
    then have "box a b ≠ {}"
      using mem_box(1)[of "?x" a b] by auto
  }
  ultimately show ?th1 by blast

  {
    fix i x
    assume i: "i ∈ Basis" and as:"b∙i < a∙i" and x:"x∈cbox a b"
    then have "a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i"
      unfolding mem_box by auto
    then have "a∙i ≤ b∙i" by auto
    then have False using as by auto
  }
  moreover
  {
    assume as:"∀i∈Basis. ¬ (b∙i < a∙i)"
    let ?x = "(1/2) *R (a + b)"
    {
      fix i :: 'a
      assume i:"i ∈ Basis"
      have "a∙i ≤ b∙i"
        using as[THEN bspec[where x=i]] i by auto
      then have "a∙i ≤ ((1/2) *R (a+b)) ∙ i" "((1/2) *R (a+b)) ∙ i ≤ b∙i"
        by (auto simp: inner_add_left)
    }
    then have "cbox a b ≠ {}"
      using mem_box(2)[of "?x" a b] by auto
  }
  ultimately show ?th2 by blast
qed

lemma box_ne_empty:
  fixes a :: "'a::euclidean_space"
  shows "cbox a b ≠ {} ⟷ (∀i∈Basis. a∙i ≤ b∙i)"
  and "box a b ≠ {} ⟷ (∀i∈Basis. a∙i < b∙i)"
  unfolding box_eq_empty[of a b] by fastforce+

lemma
  fixes a :: "'a::euclidean_space"
  shows cbox_sing [simp]: "cbox a a = {a}"
    and box_sing [simp]: "box a a = {}"
  unfolding set_eq_iff mem_box eq_iff [symmetric]
  by (auto intro!: euclidean_eqI[where 'a='a])
     (metis all_not_in_conv nonempty_Basis)

lemma subset_box_imp:
  fixes a :: "'a::euclidean_space"
  shows "(∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i) ⟹ cbox c d ⊆ cbox a b"
    and "(∀i∈Basis. a∙i < c∙i ∧ d∙i < b∙i) ⟹ cbox c d ⊆ box a b"
    and "(∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i) ⟹ box c d ⊆ cbox a b"
     and "(∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i) ⟹ box c d ⊆ box a b"
  unfolding subset_eq[unfolded Ball_def] unfolding mem_box
  by (best intro: order_trans less_le_trans le_less_trans less_imp_le)+

lemma box_subset_cbox:
  fixes a :: "'a::euclidean_space"
  shows "box a b ⊆ cbox a b"
  unfolding subset_eq [unfolded Ball_def] mem_box
  by (fast intro: less_imp_le)

lemma subset_box:
  fixes a :: "'a::euclidean_space"
  shows "cbox c d ⊆ cbox a b ⟷ (∀i∈Basis. c∙i ≤ d∙i) ⟶ (∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i)" (is ?th1)
    and "cbox c d ⊆ box a b ⟷ (∀i∈Basis. c∙i ≤ d∙i) ⟶ (∀i∈Basis. a∙i < c∙i ∧ d∙i < b∙i)" (is ?th2)
    and "box c d ⊆ cbox a b ⟷ (∀i∈Basis. c∙i < d∙i) ⟶ (∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i)" (is ?th3)
    and "box c d ⊆ box a b ⟷ (∀i∈Basis. c∙i < d∙i) ⟶ (∀i∈Basis. a∙i ≤ c∙i ∧ d∙i ≤ b∙i)" (is ?th4)
proof -
  show ?th1
    unfolding subset_eq and Ball_def and mem_box
    by (auto intro: order_trans)
  show ?th2
    unfolding subset_eq and Ball_def and mem_box
    by (auto intro: le_less_trans less_le_trans order_trans less_imp_le)
  {
    assume as: "box c d ⊆ cbox a b" "∀i∈Basis. c∙i < d∙i"
    then have "box c d ≠ {}"
      unfolding box_eq_empty by auto
    fix i :: 'a
    assume i: "i ∈ Basis"
    (** TODO combine the following two parts as done in the HOL_light version. **)
    {
      let ?x = "(∑j∈Basis. (if j=i then ((min (a∙j) (d∙j))+c∙j)/2 else (c∙j+d∙j)/2) *R j)::'a"
      assume as2: "a∙i > c∙i"
      {
        fix j :: 'a
        assume j: "j ∈ Basis"
        then have "c ∙ j < ?x ∙ j ∧ ?x ∙ j < d ∙ j"
          apply (cases "j = i")
          using as(2)[THEN bspec[where x=j]] i
          apply (auto simp: as2)
          done
      }
      then have "?x∈box c d"
        using i unfolding mem_box by auto
      moreover
      have "?x ∉ cbox a b"
        unfolding mem_box
        apply auto
        apply (rule_tac x=i in bexI)
        using as(2)[THEN bspec[where x=i]] and as2 i
        apply auto
        done
      ultimately have False using as by auto
    }
    then have "a∙i ≤ c∙i" by (rule ccontr) auto
    moreover
    {
      let ?x = "(∑j∈Basis. (if j=i then ((max (b∙j) (c∙j))+d∙j)/2 else (c∙j+d∙j)/2) *R j)::'a"
      assume as2: "b∙i < d∙i"
      {
        fix j :: 'a
        assume "j∈Basis"
        then have "d ∙ j > ?x ∙ j ∧ ?x ∙ j > c ∙ j"
          apply (cases "j = i")
          using as(2)[THEN bspec[where x=j]]
          apply (auto simp: as2)
          done
      }
      then have "?x∈box c d"
        unfolding mem_box by auto
      moreover
      have "?x∉cbox a b"
        unfolding mem_box
        apply auto
        apply (rule_tac x=i in bexI)
        using as(2)[THEN bspec[where x=i]] and as2 using i
        apply auto
        done
      ultimately have False using as by auto
    }
    then have "b∙i ≥ d∙i" by (rule ccontr) auto
    ultimately
    have "a∙i ≤ c∙i ∧ d∙i ≤ b∙i" by auto
  } note part1 = this
  show ?th3
    unfolding subset_eq and Ball_def and mem_box
    apply (rule, rule, rule, rule)
    apply (rule part1)
    unfolding subset_eq and Ball_def and mem_box
    prefer 4
    apply auto
    apply (erule_tac x=xa in allE, erule_tac x=xa in allE, fastforce)+
    done
  {
    assume as: "box c d ⊆ box a b" "∀i∈Basis. c∙i < d∙i"
    fix i :: 'a
    assume i:"i∈Basis"
    from as(1) have "box c d ⊆ cbox a b"
      using box_subset_cbox[of a b] by auto
    then have "a∙i ≤ c∙i ∧ d∙i ≤ b∙i"
      using part1 and as(2) using i by auto
  } note * = this
  show ?th4
    unfolding subset_eq and Ball_def and mem_box
    apply (rule, rule, rule, rule)
    apply (rule *)
    unfolding subset_eq and Ball_def and mem_box
    prefer 4
    apply auto
    apply (erule_tac x=xa in allE, simp)+
    done
qed

lemma eq_cbox: "cbox a b = cbox c d ⟷ cbox a b = {} ∧ cbox c d = {} ∨ a = c ∧ b = d"
      (is "?lhs = ?rhs")
proof
  assume ?lhs
  then have "cbox a b ⊆ cbox c d" "cbox c d ⊆ cbox a b"
    by auto
  then show ?rhs
    by (force simp: subset_box box_eq_empty intro: antisym euclidean_eqI)
next
  assume ?rhs
  then show ?lhs
    by force
qed

lemma eq_cbox_box [simp]: "cbox a b = box c d ⟷ cbox a b = {} ∧ box c d = {}"
  (is "?lhs ⟷ ?rhs")
proof
  assume ?lhs
  then have "cbox a b ⊆ box c d" "box c d ⊆cbox a b"
    by auto
  then show ?rhs
    apply (simp add: subset_box)
    using ‹cbox a b = box c d› box_ne_empty box_sing
    apply (fastforce simp add:)
    done
next
  assume ?rhs
  then show ?lhs
    by force
qed

lemma eq_box_cbox [simp]: "box a b = cbox c d ⟷ box a b = {} ∧ cbox c d = {}"
  by (metis eq_cbox_box)

lemma eq_box: "box a b = box c d ⟷ box a b = {} ∧ box c d = {} ∨ a = c ∧ b = d"
  (is "?lhs ⟷ ?rhs")
proof
  assume ?lhs
  then have "box a b ⊆ box c d" "box c d ⊆ box a b"
    by auto
  then show ?rhs
    apply (simp add: subset_box)
    using box_ne_empty(2) ‹box a b = box c d›
    apply auto
     apply (meson euclidean_eqI less_eq_real_def not_less)+
    done
next
  assume ?rhs
  then show ?lhs
    by force
qed

lemma subset_box_complex:
   "cbox a b ⊆ cbox c d ⟷
      (Re a ≤ Re b ∧ Im a ≤ Im b) ⟶ Re a ≥ Re c ∧ Im a ≥ Im c ∧ Re b ≤ Re d ∧ Im b ≤ Im d"
   "cbox a b ⊆ box c d ⟷
      (Re a ≤ Re b ∧ Im a ≤ Im b) ⟶ Re a > Re c ∧ Im a > Im c ∧ Re b < Re d ∧ Im b < Im d"
   "box a b ⊆ cbox c d ⟷
      (Re a < Re b ∧ Im a < Im b) ⟶ Re a ≥ Re c ∧ Im a ≥ Im c ∧ Re b ≤ Re d ∧ Im b ≤ Im d"
   "box a b ⊆ box c d ⟷
      (Re a < Re b ∧ Im a < Im b) ⟶ Re a ≥ Re c ∧ Im a ≥ Im c ∧ Re b ≤ Re d ∧ Im b ≤ Im d"
  by (subst subset_box; force simp: Basis_complex_def)+

lemma Int_interval:
  fixes a :: "'a::euclidean_space"
  shows "cbox a b ∩ cbox c d =
    cbox (∑i∈Basis. max (a∙i) (c∙i) *R i) (∑i∈Basis. min (b∙i) (d∙i) *R i)"
  unfolding set_eq_iff and Int_iff and mem_box
  by auto

lemma disjoint_interval:
  fixes a::"'a::euclidean_space"
  shows "cbox a b ∩ cbox c d = {} ⟷ (∃i∈Basis. (b∙i < a∙i ∨ d∙i < c∙i ∨ b∙i < c∙i ∨ d∙i < a∙i))" (is ?th1)
    and "cbox a b ∩ box c d = {} ⟷ (∃i∈Basis. (b∙i < a∙i ∨ d∙i ≤ c∙i ∨ b∙i ≤ c∙i ∨ d∙i ≤ a∙i))" (is ?th2)
    and "box a b ∩ cbox c d = {} ⟷ (∃i∈Basis. (b∙i ≤ a∙i ∨ d∙i < c∙i ∨ b∙i ≤ c∙i ∨ d∙i ≤ a∙i))" (is ?th3)
    and "box a b ∩ box c d = {} ⟷ (∃i∈Basis. (b∙i ≤ a∙i ∨ d∙i ≤ c∙i ∨ b∙i ≤ c∙i ∨ d∙i ≤ a∙i))" (is ?th4)
proof -
  let ?z = "(∑i∈Basis. (((max (a∙i) (c∙i)) + (min (b∙i) (d∙i))) / 2) *R i)::'a"
  have **: "⋀P Q. (⋀i :: 'a. i ∈ Basis ⟹ Q ?z i ⟹ P i) ⟹
      (⋀i x :: 'a. i ∈ Basis ⟹ P i ⟹ Q x i) ⟹ (∀x. ∃i∈Basis. Q x i) ⟷ (∃i∈Basis. P i)"
    by blast
  note * = set_eq_iff Int_iff empty_iff mem_box ball_conj_distrib[symmetric] eq_False ball_simps(10)
  show ?th1 unfolding * by (intro **) auto
  show ?th2 unfolding * by (intro **) auto
  show ?th3 unfolding * by (intro **) auto
  show ?th4 unfolding * by (intro **) auto
qed

lemma UN_box_eq_UNIV: "(⋃i::nat. box (- (real i *R One)) (real i *R One)) = UNIV"
proof -
  have "¦x ∙ b¦ < real_of_int (⌈Max ((λb. ¦x ∙ b¦)`Basis)⌉ + 1)"
    if [simp]: "b ∈ Basis" for x b :: 'a
  proof -
    have "¦x ∙ b¦ ≤ real_of_int ⌈¦x ∙ b¦⌉"
      by (rule le_of_int_ceiling)
    also have "… ≤ real_of_int ⌈Max ((λb. ¦x ∙ b¦)`Basis)⌉"
      by (auto intro!: ceiling_mono)
    also have "… < real_of_int (⌈Max ((λb. ¦x ∙ b¦)`Basis)⌉ + 1)"
      by simp
    finally show ?thesis .
  qed
  then have "∃n::nat. ∀b∈Basis. ¦x ∙ b¦ < real n" for x :: 'a
    by (metis order.strict_trans reals_Archimedean2)
  moreover have "⋀x b::'a. ⋀n::nat.  ¦x ∙ b¦ < real n ⟷ - real n < x ∙ b ∧ x ∙ b < real n"
    by auto
  ultimately show ?thesis
    by (auto simp: box_def inner_sum_left inner_Basis sum.If_cases)
qed

text ‹Intervals in general, including infinite and mixtures of open and closed.›

definition "is_interval (s::('a::euclidean_space) set) ⟷
  (∀a∈s. ∀b∈s. ∀x. (∀i∈Basis. ((a∙i ≤ x∙i ∧ x∙i ≤ b∙i) ∨ (b∙i ≤ x∙i ∧ x∙i ≤ a∙i))) ⟶ x ∈ s)"

lemma is_interval_cbox [simp]: "is_interval (cbox a (b::'a::euclidean_space))" (is ?th1)
  and is_interval_box [simp]: "is_interval (box a b)" (is ?th2)
  unfolding is_interval_def mem_box Ball_def atLeastAtMost_iff
  by (meson order_trans le_less_trans less_le_trans less_trans)+

lemma is_interval_empty [iff]: "is_interval {}"
  unfolding is_interval_def  by simp

lemma is_interval_univ [iff]: "is_interval UNIV"
  unfolding is_interval_def  by simp

lemma mem_is_intervalI:
  assumes "is_interval s"
    and "a ∈ s" "b ∈ s"
    and "⋀i. i ∈ Basis ⟹ a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i ∨ b ∙ i ≤ x ∙ i ∧ x ∙ i ≤ a ∙ i"
  shows "x ∈ s"
  by (rule assms(1)[simplified is_interval_def, rule_format, OF assms(2,3,4)])

lemma interval_subst:
  fixes S::"'a::euclidean_space set"
  assumes "is_interval S"
    and "x ∈ S" "y j ∈ S"
    and "j ∈ Basis"
  shows "(∑i∈Basis. (if i = j then y i ∙ i else x ∙ i) *R i) ∈ S"
  by (rule mem_is_intervalI[OF assms(1,2)]) (auto simp: assms)

lemma mem_box_componentwiseI:
  fixes S::"'a::euclidean_space set"
  assumes "is_interval S"
  assumes "⋀i. i ∈ Basis ⟹ x ∙ i ∈ ((λx. x ∙ i) ` S)"
  shows "x ∈ S"
proof -
  from assms have "∀i ∈ Basis. ∃s ∈ S. x ∙ i = s ∙ i"
    by auto
  with finite_Basis obtain s and bs::"'a list"
    where s: "⋀i. i ∈ Basis ⟹ x ∙ i = s i ∙ i" "⋀i. i ∈ Basis ⟹ s i ∈ S"
      and bs: "set bs = Basis" "distinct bs"
    by (metis finite_distinct_list)
  from nonempty_Basis s obtain j where j: "j ∈ Basis" "s j ∈ S"
    by blast
  define y where
    "y = rec_list (s j) (λj _ Y. (∑i∈Basis. (if i = j then s i ∙ i else Y ∙ i) *R i))"
  have "x = (∑i∈Basis. (if i ∈ set bs then s i ∙ i else s j ∙ i) *R i)"
    using bs by (auto simp: s(1)[symmetric] euclidean_representation)
  also have [symmetric]: "y bs = …"
    using bs(2) bs(1)[THEN equalityD1]
    by (induct bs) (auto simp: y_def euclidean_representation intro!: euclidean_eqI[where 'a='a])
  also have "y bs ∈ S"
    using bs(1)[THEN equalityD1]
    apply (induct bs)
     apply (auto simp: y_def j)
    apply (rule interval_subst[OF assms(1)])
      apply (auto simp: s)
    done
  finally show ?thesis .
qed

lemma cbox01_nonempty [simp]: "cbox 0 One ≠ {}"
  by (simp add: box_ne_empty inner_Basis inner_sum_left sum_nonneg)

lemma box01_nonempty [simp]: "box 0 One ≠ {}"
  by (simp add: box_ne_empty inner_Basis inner_sum_left)

lemma empty_as_interval: "{} = cbox One (0::'a::euclidean_space)"
  using nonempty_Basis box01_nonempty box_eq_empty(1) box_ne_empty(1) by blast

lemma interval_subset_is_interval:
  assumes "is_interval S"
  shows "cbox a b ⊆ S ⟷ cbox a b = {} ∨ a ∈ S ∧ b ∈ S" (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs  using box_ne_empty(1) mem_box(2) by fastforce
next
  assume ?rhs
  have "cbox a b ⊆ S" if "a ∈ S" "b ∈ S"
    using assms unfolding is_interval_def
    apply (clarsimp simp add: mem_box)
    using that by blast
  with ‹?rhs› show ?lhs
    by blast
qed


subsection ‹Connectedness›

lemma connected_local:
 "connected S ⟷
  ¬ (∃e1 e2.
      openin (subtopology euclidean S) e1 ∧
      openin (subtopology euclidean S) e2 ∧
      S ⊆ e1 ∪ e2 ∧
      e1 ∩ e2 = {} ∧
      e1 ≠ {} ∧
      e2 ≠ {})"
  unfolding connected_def openin_open
  by safe blast+

lemma exists_diff:
  fixes P :: "'a set ⇒ bool"
  shows "(∃S. P (- S)) ⟷ (∃S. P S)"
    (is "?lhs ⟷ ?rhs")
proof -
  have ?rhs if ?lhs
    using that by blast
  moreover have "P (- (- S))" if "P S" for S
  proof -
    have "S = - (- S)" by simp
    with that show ?thesis by metis
  qed
  ultimately show ?thesis by metis
qed

lemma connected_clopen: "connected S ⟷
  (∀T. openin (subtopology euclidean S) T ∧
     closedin (subtopology euclidean S) T ⟶ T = {} ∨ T = S)" (is "?lhs ⟷ ?rhs")
proof -
  have "¬ connected S ⟷
    (∃e1 e2. open e1 ∧ open (- e2) ∧ S ⊆ e1 ∪ (- e2) ∧ e1 ∩ (- e2) ∩ S = {} ∧ e1 ∩ S ≠ {} ∧ (- e2) ∩ S ≠ {})"
    unfolding connected_def openin_open closedin_closed
    by (metis double_complement)
  then have th0: "connected S ⟷
    ¬ (∃e2 e1. closed e2 ∧ open e1 ∧ S ⊆ e1 ∪ (- e2) ∧ e1 ∩ (- e2) ∩ S = {} ∧ e1 ∩ S ≠ {} ∧ (- e2) ∩ S ≠ {})"
    (is " _ ⟷ ¬ (∃e2 e1. ?P e2 e1)")
    by (simp add: closed_def) metis
  have th1: "?rhs ⟷ ¬ (∃t' t. closed t'∧t = S∩t' ∧ t≠{} ∧ t≠S ∧ (∃t'. open t' ∧ t = S ∩ t'))"
    (is "_ ⟷ ¬ (∃t' t. ?Q t' t)")
    unfolding connected_def openin_open closedin_closed by auto
  have "(∃e1. ?P e2 e1) ⟷ (∃t. ?Q e2 t)" for e2
  proof -
    have "?P e2 e1 ⟷ (∃t. closed e2 ∧ t = S∩e2 ∧ open e1 ∧ t = S∩e1 ∧ t≠{} ∧ t ≠ S)" for e1
      by auto
    then show ?thesis
      by metis
  qed
  then have "∀e2. (∃e1. ?P e2 e1) ⟷ (∃t. ?Q e2 t)"
    by blast
  then show ?thesis
    by (simp add: th0 th1)
qed


subsection ‹Limit points›

definition (in topological_space) islimpt:: "'a ⇒ 'a set ⇒ bool"  (infixr "islimpt" 60)
  where "x islimpt S ⟷ (∀T. x∈T ⟶ open T ⟶ (∃y∈S. y∈T ∧ y≠x))"

lemma islimptI:
  assumes "⋀T. x ∈ T ⟹ open T ⟹ ∃y∈S. y ∈ T ∧ y ≠ x"
  shows "x islimpt S"
  using assms unfolding islimpt_def by auto

lemma islimptE:
  assumes "x islimpt S" and "x ∈ T" and "open T"
  obtains y where "y ∈ S" and "y ∈ T" and "y ≠ x"
  using assms unfolding islimpt_def by auto

lemma islimpt_iff_eventually: "x islimpt S ⟷ ¬ eventually (λy. y ∉ S) (at x)"
  unfolding islimpt_def eventually_at_topological by auto

lemma islimpt_subset: "x islimpt S ⟹ S ⊆ T ⟹ x islimpt T"
  unfolding islimpt_def by fast

lemma islimpt_approachable:
  fixes x :: "'a::metric_space"
  shows "x islimpt S ⟷ (∀e>0. ∃x'∈S. x' ≠ x ∧ dist x' x < e)"
  unfolding islimpt_iff_eventually eventually_at by fast

lemma islimpt_approachable_le: "x islimpt S ⟷ (∀e>0. ∃x'∈ S. x' ≠ x ∧ dist x' x ≤ e)"
  for x :: "'a::metric_space"
  unfolding islimpt_approachable
  using approachable_lt_le [where f="λy. dist y x" and P="λy. y ∉ S ∨ y = x",
    THEN arg_cong [where f=Not]]
  by (simp add: Bex_def conj_commute conj_left_commute)

lemma islimpt_UNIV_iff: "x islimpt UNIV ⟷ ¬ open {x}"
  unfolding islimpt_def by (safe, fast, case_tac "T = {x}", fast, fast)

lemma islimpt_punctured: "x islimpt S = x islimpt (S-{x})"
  unfolding islimpt_def by blast

text ‹A perfect space has no isolated points.›

lemma islimpt_UNIV [simp, intro]: "x islimpt UNIV"
  for x :: "'a::perfect_space"
  unfolding islimpt_UNIV_iff by (rule not_open_singleton)

lemma perfect_choose_dist: "0 < r ⟹ ∃a. a ≠ x ∧ dist a x < r"
  for x :: "'a::{perfect_space,metric_space}"
  using islimpt_UNIV [of x] by (simp add: islimpt_approachable)

lemma closed_limpt: "closed S ⟷ (∀x. x islimpt S ⟶ x ∈ S)"
  unfolding closed_def
  apply (subst open_subopen)
  apply (simp add: islimpt_def subset_eq)
  apply (metis ComplE ComplI)
  done

lemma islimpt_EMPTY[simp]: "¬ x islimpt {}"
  by (auto simp: islimpt_def)

lemma finite_set_avoid:
  fixes a :: "'a::metric_space"
  assumes fS: "finite S"
  shows "∃d>0. ∀x∈S. x ≠ a ⟶ d ≤ dist a x"
proof (induct rule: finite_induct[OF fS])
  case 1
  then show ?case by (auto intro: zero_less_one)
next
  case (2 x F)
  from 2 obtain d where d: "d > 0" "∀x∈F. x ≠ a ⟶ d ≤ dist a x"
    by blast
  show ?case
  proof (cases "x = a")
    case True
    with d show ?thesis by auto
  next
    case False
    let ?d = "min d (dist a x)"
    from False d(1) have dp: "?d > 0"
      by auto
    from d have d': "∀x∈F. x ≠ a ⟶ ?d ≤ dist a x"
      by auto
    with dp False show ?thesis
      by (auto intro!: exI[where x="?d"])
  qed
qed

lemma islimpt_Un: "x islimpt (S ∪ T) ⟷ x islimpt S ∨ x islimpt T"
  by (simp add: islimpt_iff_eventually eventually_conj_iff)

lemma discrete_imp_closed:
  fixes S :: "'a::metric_space set"
  assumes e: "0 < e"
    and d: "∀x ∈ S. ∀y ∈ S. dist y x < e ⟶ y = x"
  shows "closed S"
proof -
  have False if C: "∀e>0. ∃x'∈S. x' ≠ x ∧ dist x' x < e" for x
  proof -
    from e have e2: "e/2 > 0" by arith
    from C[rule_format, OF e2] obtain y where y: "y ∈ S" "y ≠ x" "dist y x < e/2"
      by blast
    let ?m = "min (e/2) (dist x y) "
    from e2 y(2) have mp: "?m > 0"
      by simp
    from C[rule_format, OF mp] obtain z where z: "z ∈ S" "z ≠ x" "dist z x < ?m"
      by blast
    from z y have "dist z y < e"
      by (intro dist_triangle_lt [where z=x]) simp
    from d[rule_format, OF y(1) z(1) this] y z show ?thesis
      by (auto simp: dist_commute)
  qed
  then show ?thesis
    by (metis islimpt_approachable closed_limpt [where 'a='a])
qed

lemma closed_of_nat_image: "closed (of_nat ` A :: 'a::real_normed_algebra_1 set)"
  by (rule discrete_imp_closed[of 1]) (auto simp: dist_of_nat)

lemma closed_of_int_image: "closed (of_int ` A :: 'a::real_normed_algebra_1 set)"
  by (rule discrete_imp_closed[of 1]) (auto simp: dist_of_int)

lemma closed_Nats [simp]: "closed (ℕ :: 'a :: real_normed_algebra_1 set)"
  unfolding Nats_def by (rule closed_of_nat_image)

lemma closed_Ints [simp]: "closed (ℤ :: 'a :: real_normed_algebra_1 set)"
  unfolding Ints_def by (rule closed_of_int_image)

lemma closed_subset_Ints:
  fixes A :: "'a :: real_normed_algebra_1 set"
  assumes "A ⊆ ℤ"
  shows   "closed A"
proof (intro discrete_imp_closed[OF zero_less_one] ballI impI, goal_cases)
  case (1 x y)
  with assms have "x ∈ ℤ" and "y ∈ ℤ" by auto
  with ‹dist y x < 1› show "y = x"
    by (auto elim!: Ints_cases simp: dist_of_int)
qed


subsection ‹Interior of a Set›

definition "interior S = ⋃{T. open T ∧ T ⊆ S}"

lemma interiorI [intro?]:
  assumes "open T" and "x ∈ T" and "T ⊆ S"
  shows "x ∈ interior S"
  using assms unfolding interior_def by fast

lemma interiorE [elim?]:
  assumes "x ∈ interior S"
  obtains T where "open T" and "x ∈ T" and "T ⊆ S"
  using assms unfolding interior_def by fast

lemma open_interior [simp, intro]: "open (interior S)"
  by (simp add: interior_def open_Union)

lemma interior_subset: "interior S ⊆ S"
  by (auto simp: interior_def)

lemma interior_maximal: "T ⊆ S ⟹ open T ⟹ T ⊆ interior S"
  by (auto simp: interior_def)

lemma interior_open: "open S ⟹ interior S = S"
  by (intro equalityI interior_subset interior_maximal subset_refl)

lemma interior_eq: "interior S = S ⟷ open S"
  by (metis open_interior interior_open)

lemma open_subset_interior: "open S ⟹ S ⊆ interior T ⟷ S ⊆ T"
  by (metis interior_maximal interior_subset subset_trans)

lemma interior_empty [simp]: "interior {} = {}"
  using open_empty by (rule interior_open)

lemma interior_UNIV [simp]: "interior UNIV = UNIV"
  using open_UNIV by (rule interior_open)

lemma interior_interior [simp]: "interior (interior S) = interior S"
  using open_interior by (rule interior_open)

lemma interior_mono: "S ⊆ T ⟹ interior S ⊆ interior T"
  by (auto simp: interior_def)

lemma interior_unique:
  assumes "T ⊆ S" and "open T"
  assumes "⋀T'. T' ⊆ S ⟹ open T' ⟹ T' ⊆ T"
  shows "interior S = T"
  by (intro equalityI assms interior_subset open_interior interior_maximal)

lemma interior_singleton [simp]: "interior {a} = {}"
  for a :: "'a::perfect_space"
  apply (rule interior_unique, simp_all)
  using not_open_singleton subset_singletonD
  apply fastforce
  done

lemma interior_Int [simp]: "interior (S ∩ T) = interior S ∩ interior T"
  by (intro equalityI Int_mono Int_greatest interior_mono Int_lower1
    Int_lower2 interior_maximal interior_subset open_Int open_interior)

lemma mem_interior: "x ∈ interior S ⟷ (∃e>0. ball x e ⊆ S)"
  using open_contains_ball_eq [where S="interior S"]
  by (simp add: open_subset_interior)

lemma eventually_nhds_in_nhd: "x ∈ interior s ⟹ eventually (λy. y ∈ s) (nhds x)"
  using interior_subset[of s] by (subst eventually_nhds) blast

lemma interior_limit_point [intro]:
  fixes x :: "'a::perfect_space"
  assumes x: "x ∈ interior S"
  shows "x islimpt S"
  using x islimpt_UNIV [of x]
  unfolding interior_def islimpt_def
  apply (clarsimp, rename_tac T T')
  apply (drule_tac x="T ∩ T'" in spec)
  apply (auto simp: open_Int)
  done

lemma interior_closed_Un_empty_interior:
  assumes cS: "closed S"
    and iT: "interior T = {}"
  shows "interior (S ∪ T) = interior S"
proof
  show "interior S ⊆ interior (S ∪ T)"
    by (rule interior_mono) (rule Un_upper1)
  show "interior (S ∪ T) ⊆ interior S"
  proof
    fix x
    assume "x ∈ interior (S ∪ T)"
    then obtain R where "open R" "x ∈ R" "R ⊆ S ∪ T" ..
    show "x ∈ interior S"
    proof (rule ccontr)
      assume "x ∉ interior S"
      with ‹x ∈ R› ‹open R› obtain y where "y ∈ R - S"
        unfolding interior_def by fast
      from ‹open R› ‹closed S› have "open (R - S)"
        by (rule open_Diff)
      from ‹R ⊆ S ∪ T› have "R - S ⊆ T"
        by fast
      from ‹y ∈ R - S› ‹open (R - S)› ‹R - S ⊆ T› ‹interior T = {}› show False
        unfolding interior_def by fast
    qed
  qed
qed

lemma interior_Times: "interior (A × B) = interior A × interior B"
proof (rule interior_unique)
  show "interior A × interior B ⊆ A × B"
    by (intro Sigma_mono interior_subset)
  show "open (interior A × interior B)"
    by (intro open_Times open_interior)
  fix T
  assume "T ⊆ A × B" and "open T"
  then show "T ⊆ interior A × interior B"
  proof safe
    fix x y
    assume "(x, y) ∈ T"
    then obtain C D where "open C" "open D" "C × D ⊆ T" "x ∈ C" "y ∈ D"
      using ‹open T› unfolding open_prod_def by fast
    then have "open C" "open D" "C ⊆ A" "D ⊆ B" "x ∈ C" "y ∈ D"
      using ‹T ⊆ A × B› by auto
    then show "x ∈ interior A" and "y ∈ interior B"
      by (auto intro: interiorI)
  qed
qed

lemma interior_Ici:
  fixes x :: "'a :: {dense_linorder,linorder_topology}"
  assumes "b < x"
  shows "interior {x ..} = {x <..}"
proof (rule interior_unique)
  fix T
  assume "T ⊆ {x ..}" "open T"
  moreover have "x ∉ T"
  proof
    assume "x ∈ T"
    obtain y where "y < x" "{y <.. x} ⊆ T"
      using open_left[OF ‹open T› ‹x ∈ T› ‹b < x›] by auto
    with dense[OF ‹y < x›] obtain z where "z ∈ T" "z < x"
      by (auto simp: subset_eq Ball_def)
    with ‹T ⊆ {x ..}› show False by auto
  qed
  ultimately show "T ⊆ {x <..}"
    by (auto simp: subset_eq less_le)
qed auto

lemma interior_Iic:
  fixes x :: "'a ::{dense_linorder,linorder_topology}"
  assumes "x < b"
  shows "interior {.. x} = {..< x}"
proof (rule interior_unique)
  fix T
  assume "T ⊆ {.. x}" "open T"
  moreover have "x ∉ T"
  proof
    assume "x ∈ T"
    obtain y where "x < y" "{x ..< y} ⊆ T"
      using open_right[OF ‹open T› ‹x ∈ T› ‹x < b›] by auto
    with dense[OF ‹x < y›] obtain z where "z ∈ T" "x < z"
      by (auto simp: subset_eq Ball_def less_le)
    with ‹T ⊆ {.. x}› show False by auto
  qed
  ultimately show "T ⊆ {..< x}"
    by (auto simp: subset_eq less_le)
qed auto


subsection ‹Closure of a Set›

definition "closure S = S ∪ {x | x. x islimpt S}"

lemma interior_closure: "interior S = - (closure (- S))"
  by (auto simp: interior_def closure_def islimpt_def)

lemma closure_interior: "closure S = - interior (- S)"
  by (simp add: interior_closure)

lemma closed_closure[simp, intro]: "closed (closure S)"
  by (simp add: closure_interior closed_Compl)

lemma closure_subset: "S ⊆ closure S"
  by (simp add: closure_def)

lemma closure_hull: "closure S = closed hull S"
  by (auto simp: hull_def closure_interior interior_def)

lemma closure_eq: "closure S = S ⟷ closed S"
  unfolding closure_hull using closed_Inter by (rule hull_eq)

lemma closure_closed [simp]: "closed S ⟹ closure S = S"
  by (simp only: closure_eq)

lemma closure_closure [simp]: "closure (closure S) = closure S"
  unfolding closure_hull by (rule hull_hull)

lemma closure_mono: "S ⊆ T ⟹ closure S ⊆ closure T"
  unfolding closure_hull by (rule hull_mono)

lemma closure_minimal: "S ⊆ T ⟹ closed T ⟹ closure S ⊆ T"
  unfolding closure_hull by (rule hull_minimal)

lemma closure_unique:
  assumes "S ⊆ T"
    and "closed T"
    and "⋀T'. S ⊆ T' ⟹ closed T' ⟹ T ⊆ T'"
  shows "closure S = T"
  using assms unfolding closure_hull by (rule hull_unique)

lemma closure_empty [simp]: "closure {} = {}"
  using closed_empty by (rule closure_closed)

lemma closure_UNIV [simp]: "closure UNIV = UNIV"
  using closed_UNIV by (rule closure_closed)

lemma closure_Un [simp]: "closure (S ∪ T) = closure S ∪ closure T"
  by (simp add: closure_interior)

lemma closure_eq_empty [iff]: "closure S = {} ⟷ S = {}"
  using closure_empty closure_subset[of S] by blast

lemma closure_subset_eq: "closure S ⊆ S ⟷ closed S"
  using closure_eq[of S] closure_subset[of S] by simp

lemma open_Int_closure_eq_empty: "open S ⟹ (S ∩ closure T) = {} ⟷ S ∩ T = {}"
  using open_subset_interior[of S "- T"]
  using interior_subset[of "- T"]
  by (auto simp: closure_interior)

lemma open_Int_closure_subset: "open S ⟹ S ∩ closure T ⊆ closure (S ∩ T)"
proof
  fix x
  assume *: "open S" "x ∈ S ∩ closure T"
  have "x islimpt (S ∩ T)" if **: "x islimpt T"
  proof (rule islimptI)
    fix A
    assume "x ∈ A" "open A"
    with * have "x ∈ A ∩ S" "open (A ∩ S)"
      by (simp_all add: open_Int)
    with ** obtain y where "y ∈ T" "y ∈ A ∩ S" "y ≠ x"
      by (rule islimptE)
    then have "y ∈ S ∩ T" "y ∈ A ∧ y ≠ x"
      by simp_all
    then show "∃y∈(S ∩ T). y ∈ A ∧ y ≠ x" ..
  qed
  with * show "x ∈ closure (S ∩ T)"
    unfolding closure_def by blast
qed

lemma closure_complement: "closure (- S) = - interior S"
  by (simp add: closure_interior)

lemma interior_complement: "interior (- S) = - closure S"
  by (simp add: closure_interior)

lemma interior_diff: "interior(S - T) = interior S - closure T"
  by (simp add: Diff_eq interior_complement)

lemma closure_Times: "closure (A × B) = closure A × closure B"
proof (rule closure_unique)
  show "A × B ⊆ closure A × closure B"
    by (intro Sigma_mono closure_subset)
  show "closed (closure A × closure B)"
    by (intro closed_Times closed_closure)
  fix T
  assume "A × B ⊆ T" and "closed T"
  then show "closure A × closure B ⊆ T"
    apply (simp add: closed_def open_prod_def, clarify)
    apply (rule ccontr)
    apply (drule_tac x="(a, b)" in bspec, simp, clarify, rename_tac C D)
    apply (simp add: closure_interior interior_def)
    apply (drule_tac x=C in spec)
    apply (drule_tac x=D in spec, auto)
    done
qed

lemma closure_openin_Int_closure:
  assumes ope: "openin (subtopology euclidean U) S" and "T ⊆ U"
  shows "closure(S ∩ closure T) = closure(S ∩ T)"
proof
  obtain V where "open V" and S: "S = U ∩ V"
    using ope using openin_open by metis
  show "closure (S ∩ closure T) ⊆ closure (S ∩ T)"
    proof (clarsimp simp: S)
      fix x
      assume  "x ∈ closure (U ∩ V ∩ closure T)"
      then have "V ∩ closure T ⊆ A ⟹ x ∈ closure A" for A
          by (metis closure_mono subsetD inf.coboundedI2 inf_assoc)
      then have "x ∈ closure (T ∩ V)"
         by (metis ‹open V› closure_closure inf_commute open_Int_closure_subset)
      then show "x ∈ closure (U ∩ V ∩ T)"
        by (metis ‹T ⊆ U› inf.absorb_iff2 inf_assoc inf_commute)
    qed
next
  show "closure (S ∩ T) ⊆ closure (S ∩ closure T)"
    by (meson Int_mono closure_mono closure_subset order_refl)
qed

lemma islimpt_in_closure: "(x islimpt S) = (x:closure(S-{x}))"
  unfolding closure_def using islimpt_punctured by blast

lemma connected_imp_connected_closure: "connected S ⟹ connected (closure S)"
  by (rule connectedI) (meson closure_subset open_Int open_Int_closure_eq_empty subset_trans connectedD)

lemma limpt_of_limpts: "x islimpt {y. y islimpt S} ⟹ x islimpt S"
  for x :: "'a::metric_space"
  apply (clarsimp simp add: islimpt_approachable)
  apply (drule_tac x="e/2" in spec)
  apply (auto simp: simp del: less_divide_eq_numeral1)
  apply (drule_tac x="dist x' x" in spec)
  apply (auto simp: zero_less_dist_iff simp del: less_divide_eq_numeral1)
  apply (erule rev_bexI)
  apply (metis dist_commute dist_triangle_half_r less_trans less_irrefl)
  done

lemma closed_limpts:  "closed {x::'a::metric_space. x islimpt S}"
  using closed_limpt limpt_of_limpts by blast

lemma limpt_of_closure: "x islimpt closure S ⟷ x islimpt S"
  for x :: "'a::metric_space"
  by (auto simp: closure_def islimpt_Un dest: limpt_of_limpts)

lemma closedin_limpt:
  "closedin (subtopology euclidean T) S ⟷ S ⊆ T ∧ (∀x. x islimpt S ∧ x ∈ T ⟶ x ∈ S)"
  apply (simp add: closedin_closed, safe)
   apply (simp add: closed_limpt islimpt_subset)
  apply (rule_tac x="closure S" in exI, simp)
  apply (force simp: closure_def)
  done

lemma closedin_closed_eq: "closed S ⟹ closedin (subtopology euclidean S) T ⟷ closed T ∧ T ⊆ S"
  by (meson closedin_limpt closed_subset closedin_closed_trans)

lemma closedin_subset_trans:
  "closedin (subtopology euclidean U) S ⟹ S ⊆ T ⟹ T ⊆ U ⟹
    closedin (subtopology euclidean T) S"
  by (meson closedin_limpt subset_iff)

lemma openin_subset_trans:
  "openin (subtopology euclidean U) S ⟹ S ⊆ T ⟹ T ⊆ U ⟹
    openin (subtopology euclidean T) S"
  by (auto simp: openin_open)

lemma openin_Times:
  "openin (subtopology euclidean S) S' ⟹ openin (subtopology euclidean T) T' ⟹
    openin (subtopology euclidean (S × T)) (S' × T')"
  unfolding openin_open using open_Times by blast

lemma Times_in_interior_subtopology:
  fixes U :: "('a::metric_space × 'b::metric_space) set"
  assumes "(x, y) ∈ U" "openin (subtopology euclidean (S × T)) U"
  obtains V W where "openin (subtopology euclidean S) V" "x ∈ V"
                    "openin (subtopology euclidean T) W" "y ∈ W" "(V × W) ⊆ U"
proof -
  from assms obtain e where "e > 0" and "U ⊆ S × T"
    and e: "⋀x' y'. ⟦x'∈S; y'∈T; dist (x', y') (x, y) < e⟧ ⟹ (x', y') ∈ U"
    by (force simp: openin_euclidean_subtopology_iff)
  with assms have "x ∈ S" "y ∈ T"
    by auto
  show ?thesis
  proof
    show "openin (subtopology euclidean S) (ball x (e/2) ∩ S)"
      by (simp add: Int_commute openin_open_Int)
    show "x ∈ ball x (e / 2) ∩ S"
      by (simp add: ‹0 < e› ‹x ∈ S›)
    show "openin (subtopology euclidean T) (ball y (e/2) ∩ T)"
      by (simp add: Int_commute openin_open_Int)
    show "y ∈ ball y (e / 2) ∩ T"
      by (simp add: ‹0 < e› ‹y ∈ T›)
    show "(ball x (e / 2) ∩ S) × (ball y (e / 2) ∩ T) ⊆ U"
      by clarify (simp add: e dist_Pair_Pair ‹0 < e› dist_commute sqrt_sum_squares_half_less)
  qed
qed

lemma openin_Times_eq:
  fixes S :: "'a::metric_space set" and T :: "'b::metric_space set"
  shows
    "openin (subtopology euclidean (S × T)) (S' × T') ⟷
      S' = {} ∨ T' = {} ∨ openin (subtopology euclidean S) S' ∧ openin (subtopology euclidean T) T'"
    (is "?lhs = ?rhs")
proof (cases "S' = {} ∨ T' = {}")
  case True
  then show ?thesis by auto
next
  case False
  then obtain x y where "x ∈ S'" "y ∈ T'"
    by blast
  show ?thesis
  proof
    assume ?lhs
    have "openin (subtopology euclidean S) S'"
      apply (subst openin_subopen, clarify)
      apply (rule Times_in_interior_subtopology [OF _ ‹?lhs›])
      using ‹y ∈ T'›
       apply auto
      done
    moreover have "openin (subtopology euclidean T) T'"
      apply (subst openin_subopen, clarify)
      apply (rule Times_in_interior_subtopology [OF _ ‹?lhs›])
      using ‹x ∈ S'›
       apply auto
      done
    ultimately show ?rhs
      by simp
  next
    assume ?rhs
    with False show ?lhs
      by (simp add: openin_Times)
  qed
qed

lemma closedin_Times:
  "closedin (subtopology euclidean S) S' ⟹ closedin (subtopology euclidean T) T' ⟹
    closedin (subtopology euclidean (S × T)) (S' × T')"
  unfolding closedin_closed using closed_Times by blast

lemma bdd_below_closure:
  fixes A :: "real set"
  assumes "bdd_below A"
  shows "bdd_below (closure A)"
proof -
  from assms obtain m where "⋀x. x ∈ A ⟹ m ≤ x"
    by (auto simp: bdd_below_def)
  then have "A ⊆ {m..}" by auto
  then have "closure A ⊆ {m..}"
    using closed_real_atLeast by (rule closure_minimal)
  then show ?thesis
    by (auto simp: bdd_below_def)
qed


subsection ‹Connected components, considered as a connectedness relation or a set›

definition "connected_component s x y ≡ ∃t. connected t ∧ t ⊆ s ∧ x ∈ t ∧ y ∈ t"

abbreviation "connected_component_set s x ≡ Collect (connected_component s x)"

lemma connected_componentI:
  "connected t ⟹ t ⊆ s ⟹ x ∈ t ⟹ y ∈ t ⟹ connected_component s x y"
  by (auto simp: connected_component_def)

lemma connected_component_in: "connected_component s x y ⟹ x ∈ s ∧ y ∈ s"
  by (auto simp: connected_component_def)

lemma connected_component_refl: "x ∈ s ⟹ connected_component s x x"
  by (auto simp: connected_component_def) (use connected_sing in blast)

lemma connected_component_refl_eq [simp]: "connected_component s x x ⟷ x ∈ s"
  by (auto simp: connected_component_refl) (auto simp: connected_component_def)

lemma connected_component_sym: "connected_component s x y ⟹ connected_component s y x"
  by (auto simp: connected_component_def)

lemma connected_component_trans:
  "connected_component s x y ⟹ connected_component s y z ⟹ connected_component s x z"
  unfolding connected_component_def
  by (metis Int_iff Un_iff Un_subset_iff equals0D connected_Un)

lemma connected_component_of_subset:
  "connected_component s x y ⟹ s ⊆ t ⟹ connected_component t x y"
  by (auto simp: connected_component_def)

lemma connected_component_Union: "connected_component_set s x = ⋃{t. connected t ∧ x ∈ t ∧ t ⊆ s}"
  by (auto simp: connected_component_def)

lemma connected_connected_component [iff]: "connected (connected_component_set s x)"
  by (auto simp: connected_component_Union intro: connected_Union)

lemma connected_iff_eq_connected_component_set:
  "connected s ⟷ (∀x ∈ s. connected_component_set s x = s)"
proof (cases "s = {}")
  case True
  then show ?thesis by simp
next
  case False
  then obtain x where "x ∈ s" by auto
  show ?thesis
  proof
    assume "connected s"
    then show "∀x ∈ s. connected_component_set s x = s"
      by (force simp: connected_component_def)
  next
    assume "∀x ∈ s. connected_component_set s x = s"
    then show "connected s"
      by (metis ‹x ∈ s› connected_connected_component)
  qed
qed

lemma connected_component_subset: "connected_component_set s x ⊆ s"
  using connected_component_in by blast

lemma connected_component_eq_self: "connected s ⟹ x ∈ s ⟹ connected_component_set s x = s"
  by (simp add: connected_iff_eq_connected_component_set)

lemma connected_iff_connected_component:
  "connected s ⟷ (∀x ∈ s. ∀y ∈ s. connected_component s x y)"
  using connected_component_in by (auto simp: connected_iff_eq_connected_component_set)

lemma connected_component_maximal:
  "x ∈ t ⟹ connected t ⟹ t ⊆ s ⟹ t ⊆ (connected_component_set s x)"
  using connected_component_eq_self connected_component_of_subset by blast

lemma connected_component_mono:
  "s ⊆ t ⟹ connected_component_set s x ⊆ connected_component_set t x"
  by (simp add: Collect_mono connected_component_of_subset)

lemma connected_component_eq_empty [simp]: "connected_component_set s x = {} ⟷ x ∉ s"
  using connected_component_refl by (fastforce simp: connected_component_in)

lemma connected_component_set_empty [simp]: "connected_component_set {} x = {}"
  using connected_component_eq_empty by blast

lemma connected_component_eq:
  "y ∈ connected_component_set s x ⟹ (connected_component_set s y = connected_component_set s x)"
  by (metis (no_types, lifting)
      Collect_cong connected_component_sym connected_component_trans mem_Collect_eq)

lemma closed_connected_component:
  assumes s: "closed s"
  shows "closed (connected_component_set s x)"
proof (cases "x ∈ s")
  case False
  then show ?thesis
    by (metis connected_component_eq_empty closed_empty)
next
  case True
  show ?thesis
    unfolding closure_eq [symmetric]
  proof
    show "closure (connected_component_set s x) ⊆ connected_component_set s x"
      apply (rule connected_component_maximal)
        apply (simp add: closure_def True)
       apply (simp add: connected_imp_connected_closure)
      apply (simp add: s closure_minimal connected_component_subset)
      done
  next
    show "connected_component_set s x ⊆ closure (connected_component_set s x)"
      by (simp add: closure_subset)
  qed
qed

lemma connected_component_disjoint:
  "connected_component_set s a ∩ connected_component_set s b = {} ⟷
    a ∉ connected_component_set s b"
  apply (auto simp: connected_component_eq)
  using connected_component_eq connected_component_sym
  apply blast
  done

lemma connected_component_nonoverlap:
  "connected_component_set s a ∩ connected_component_set s b = {} ⟷
    a ∉ s ∨ b ∉ s ∨ connected_component_set s a ≠ connected_component_set s b"
  apply (auto simp: connected_component_in)
  using connected_component_refl_eq
    apply blast
   apply (metis connected_component_eq mem_Collect_eq)
  apply (metis connected_component_eq mem_Collect_eq)
  done

lemma connected_component_overlap:
  "connected_component_set s a ∩ connected_component_set s b ≠ {} ⟷
    a ∈ s ∧ b ∈ s ∧ connected_component_set s a = connected_component_set s b"
  by (auto simp: connected_component_nonoverlap)

lemma connected_component_sym_eq: "connected_component s x y ⟷ connected_component s y x"
  using connected_component_sym by blast

lemma connected_component_eq_eq:
  "connected_component_set s x = connected_component_set s y ⟷
    x ∉ s ∧ y ∉ s ∨ x ∈ s ∧ y ∈ s ∧ connected_component s x y"
  apply (cases "y ∈ s", simp)
   apply (metis connected_component_eq connected_component_eq_empty connected_component_refl_eq mem_Collect_eq)
  apply (cases "x ∈ s", simp)
   apply (metis connected_component_eq_empty)
  using connected_component_eq_empty
  apply blast
  done

lemma connected_iff_connected_component_eq:
  "connected s ⟷ (∀x ∈ s. ∀y ∈ s. connected_component_set s x = connected_component_set s y)"
  by (simp add: connected_component_eq_eq connected_iff_connected_component)

lemma connected_component_idemp:
  "connected_component_set (connected_component_set s x) x = connected_component_set s x"
  apply (rule subset_antisym)
   apply (simp add: connected_component_subset)
  apply (metis connected_component_eq_empty connected_component_maximal
      connected_component_refl_eq connected_connected_component mem_Collect_eq set_eq_subset)
  done

lemma connected_component_unique:
  "⟦x ∈ c; c ⊆ s; connected c;
    ⋀c'. x ∈ c' ∧ c' ⊆ s ∧ connected c'
              ⟹ c' ⊆ c⟧
        ⟹ connected_component_set s x = c"
apply (rule subset_antisym)
apply (meson connected_component_maximal connected_component_subset connected_connected_component contra_subsetD)
by (simp add: connected_component_maximal)

lemma joinable_connected_component_eq:
  "⟦connected t; t ⊆ s;
    connected_component_set s x ∩ t ≠ {};
    connected_component_set s y ∩ t ≠ {}⟧
    ⟹ connected_component_set s x = connected_component_set s y"
apply (simp add: ex_in_conv [symmetric])
apply (rule connected_component_eq)
by (metis (no_types, hide_lams) connected_component_eq_eq connected_component_in connected_component_maximal subsetD mem_Collect_eq)


lemma Union_connected_component: "⋃(connected_component_set s ` s) = s"
  apply (rule subset_antisym)
  apply (simp add: SUP_least connected_component_subset)
  using connected_component_refl_eq
  by force


lemma complement_connected_component_unions:
    "s - connected_component_set s x =
     ⋃(connected_component_set s ` s - {connected_component_set s x})"
  apply (subst Union_connected_component [symmetric], auto)
  apply (metis connected_component_eq_eq connected_component_in)
  by (metis connected_component_eq mem_Collect_eq)

lemma connected_component_intermediate_subset:
        "⟦connected_component_set u a ⊆ t; t ⊆ u⟧
        ⟹ connected_component_set t a = connected_component_set u a"
  apply (case_tac "a ∈ u")
  apply (simp add: connected_component_maximal connected_component_mono subset_antisym)
  using connected_component_eq_empty by blast

proposition connected_Times:
  assumes S: "connected S" and T: "connected T"
  shows "connected (S × T)"
proof (clarsimp simp add: connected_iff_connected_component)
  fix x y x' y'
  assume xy: "x ∈ S" "y ∈ T" "x' ∈ S" "y' ∈ T"
  with xy obtain U V where U: "connected U" "U ⊆ S" "x ∈ U" "x' ∈ U"
                       and V: "connected V" "V ⊆ T" "y ∈ V" "y' ∈ V"
    using S T ‹x ∈ S› ‹x' ∈ S› by blast+
  show "connected_component (S × T) (x, y) (x', y')"
    unfolding connected_component_def
  proof (intro exI conjI)
    show "connected ((λx. (x, y)) ` U ∪ Pair x' ` V)"
    proof (rule connected_Un)
      have "continuous_on U (λx. (x, y))"
        by (intro continuous_intros)
      then show "connected ((λx. (x, y)) ` U)"
        by (rule connected_continuous_image) (rule ‹connected U›)
      have "continuous_on V (Pair x')"
        by (intro continuous_intros)
      then show "connected (Pair x' ` V)"
        by (rule connected_continuous_image) (rule ‹connected V›)
    qed (use U V in auto)
  qed (use U V in auto)
qed

corollary connected_Times_eq [simp]:
   "connected (S × T) ⟷ S = {} ∨ T = {} ∨ connected S ∧ connected T"  (is "?lhs = ?rhs")
proof
  assume L: ?lhs
  show ?rhs
  proof (cases "S = {} ∨ T = {}")
    case True
    then show ?thesis by auto
  next
    case False
    have "connected (fst ` (S × T))" "connected (snd ` (S × T))"
      using continuous_on_fst continuous_on_snd continuous_on_id
      by (blast intro: connected_continuous_image [OF _ L])+
    with False show ?thesis
      by auto
  qed
next
  assume ?rhs
  then show ?lhs
    by (auto simp: connected_Times)
qed


subsection ‹The set of connected components of a set›

definition components:: "'a::topological_space set ⇒ 'a set set"
  where "components s ≡ connected_component_set s ` s"

lemma components_iff: "s ∈ components u ⟷ (∃x. x ∈ u ∧ s = connected_component_set u x)"
  by (auto simp: components_def)

lemma componentsI: "x ∈ u ⟹ connected_component_set u x ∈ components u"
  by (auto simp: components_def)

lemma componentsE:
  assumes "s ∈ components u"
  obtains x where "x ∈ u" "s = connected_component_set u x"
  using assms by (auto simp: components_def)

lemma Union_components [simp]: "⋃(components u) = u"
  apply (rule subset_antisym)
  using Union_connected_component components_def apply fastforce
  apply (metis Union_connected_component components_def set_eq_subset)
  done

lemma pairwise_disjoint_components: "pairwise (λX Y. X ∩ Y = {}) (components u)"
  apply (simp add: pairwise_def)
  apply (auto simp: components_iff)
  apply (metis connected_component_eq_eq connected_component_in)+
  done

lemma in_components_nonempty: "c ∈ components s ⟹ c ≠ {}"
    by (metis components_iff connected_component_eq_empty)

lemma in_components_subset: "c ∈ components s ⟹ c ⊆ s"
  using Union_components by blast

lemma in_components_connected: "c ∈ components s ⟹ connected c"
  by (metis components_iff connected_connected_component)

lemma in_components_maximal:
  "c ∈ components s ⟷
    c ≠ {} ∧ c ⊆ s ∧ connected c ∧ (∀d. d ≠ {} ∧ c ⊆ d ∧ d ⊆ s ∧ connected d ⟶ d = c)"
  apply (rule iffI)
   apply (simp add: in_components_nonempty in_components_connected)
   apply (metis (full_types) components_iff connected_component_eq_self connected_component_intermediate_subset connected_component_refl in_components_subset mem_Collect_eq rev_subsetD)
  apply (metis bot.extremum_uniqueI components_iff connected_component_eq_empty connected_component_maximal connected_component_subset connected_connected_component subset_emptyI)
  done

lemma joinable_components_eq:
  "connected t ∧ t ⊆ s ∧ c1 ∈ components s ∧ c2 ∈ components s ∧ c1 ∩ t ≠ {} ∧ c2 ∩ t ≠ {} ⟹ c1 = c2"
  by (metis (full_types) components_iff joinable_connected_component_eq)

lemma closed_components: "⟦closed s; c ∈ components s⟧ ⟹ closed c"
  by (metis closed_connected_component components_iff)

lemma components_nonoverlap:
    "⟦c ∈ components s; c' ∈ components s⟧ ⟹ (c ∩ c' = {}) ⟷ (c ≠ c')"
  apply (auto simp: in_components_nonempty components_iff)
    using connected_component_refl apply blast
   apply (metis connected_component_eq_eq connected_component_in)
  by (metis connected_component_eq mem_Collect_eq)

lemma components_eq: "⟦c ∈ components s; c' ∈ components s⟧ ⟹ (c = c' ⟷ c ∩ c' ≠ {})"
  by (metis components_nonoverlap)

lemma components_eq_empty [simp]: "components s = {} ⟷ s = {}"
  by (simp add: components_def)

lemma components_empty [simp]: "components {} = {}"
  by simp

lemma connected_eq_connected_components_eq: "connected s ⟷ (∀c ∈ components s. ∀c' ∈ components s. c = c')"
  by (metis (no_types, hide_lams) components_iff connected_component_eq_eq connected_iff_connected_component)

lemma components_eq_sing_iff: "components s = {s} ⟷ connected s ∧ s ≠ {}"
  apply (rule iffI)
  using in_components_connected apply fastforce
  apply safe
  using Union_components apply fastforce
   apply (metis components_iff connected_component_eq_self)
  using in_components_maximal
  apply auto
  done

lemma components_eq_sing_exists: "(∃a. components s = {a}) ⟷ connected s ∧ s ≠ {}"
  apply (rule iffI)
  using connected_eq_connected_components_eq apply fastforce
  apply (metis components_eq_sing_iff)
  done

lemma connected_eq_components_subset_sing: "connected s ⟷ components s ⊆ {s}"
  by (metis Union_components components_empty components_eq_sing_iff connected_empty insert_subset order_refl subset_singletonD)

lemma connected_eq_components_subset_sing_exists: "connected s ⟷ (∃a. components s ⊆ {a})"
  by (metis components_eq_sing_exists connected_eq_components_subset_sing empty_iff subset_iff subset_singletonD)

lemma in_components_self: "s ∈ components s ⟷ connected s ∧ s ≠ {}"
  by (metis components_empty components_eq_sing_iff empty_iff in_components_connected insertI1)

lemma components_maximal: "⟦c ∈ components s; connected t; t ⊆ s; c ∩ t ≠ {}⟧ ⟹ t ⊆ c"
  apply (simp add: components_def ex_in_conv [symmetric], clarify)
  by (meson connected_component_def connected_component_trans)

lemma exists_component_superset: "⟦t ⊆ s; s ≠ {}; connected t⟧ ⟹ ∃c. c ∈ components s ∧ t ⊆ c"
  apply (cases "t = {}", force)
  apply (metis components_def ex_in_conv connected_component_maximal contra_subsetD image_eqI)
  done

lemma components_intermediate_subset: "⟦s ∈ components u; s ⊆ t; t ⊆ u⟧ ⟹ s ∈ components t"
  apply (auto simp: components_iff)
  apply (metis connected_component_eq_empty connected_component_intermediate_subset)
  done

lemma in_components_unions_complement: "c ∈ components s ⟹ s - c = ⋃(components s - {c})"
  by (metis complement_connected_component_unions components_def components_iff)

lemma connected_intermediate_closure:
  assumes cs: "connected s" and st: "s ⊆ t" and ts: "t ⊆ closure s"
  shows "connected t"
proof (rule connectedI)
  fix A B
  assume A: "open A" and B: "open B" and Alap: "A ∩ t ≠ {}" and Blap: "B ∩ t ≠ {}"
    and disj: "A ∩ B ∩ t = {}" and cover: "t ⊆ A ∪ B"
  have disjs: "A ∩ B ∩ s = {}"
    using disj st by auto
  have "A ∩ closure s ≠ {}"
    using Alap Int_absorb1 ts by blast
  then have Alaps: "A ∩ s ≠ {}"
    by (simp add: A open_Int_closure_eq_empty)
  have "B ∩ closure s ≠ {}"
    using Blap Int_absorb1 ts by blast
  then have Blaps: "B ∩ s ≠ {}"
    by (simp add: B open_Int_closure_eq_empty)
  then show False
    using cs [unfolded connected_def] A B disjs Alaps Blaps cover st
    by blast
qed

lemma closedin_connected_component: "closedin (subtopology euclidean s) (connected_component_set s x)"
proof (cases "connected_component_set s x = {}")
  case True
  then show ?thesis
    by (metis closedin_empty)
next
  case False
  then obtain y where y: "connected_component s x y"
    by blast
  have *: "connected_component_set s x ⊆ s ∩ closure (connected_component_set s x)"
    by (auto simp: closure_def connected_component_in)
  have "connected_component s x y ⟹ s ∩ closure (connected_component_set s x) ⊆ connected_component_set s x"
    apply (rule connected_component_maximal, simp)
    using closure_subset connected_component_in apply fastforce
    using * connected_intermediate_closure apply blast+
    done
  with y * show ?thesis
    by (auto simp: Topology_Euclidean_Space.closedin_closed)
qed


subsection ‹Frontier (also known as boundary)›

definition "frontier S = closure S - interior S"

lemma frontier_closed [iff]: "closed (frontier S)"
  by (simp add: frontier_def closed_Diff)

lemma frontier_closures: "frontier S = closure S ∩ closure (- S)"
  by (auto simp: frontier_def interior_closure)

lemma frontier_straddle:
  fixes a :: "'a::metric_space"
  shows "a ∈ frontier S ⟷ (∀e>0. (∃x∈S. dist a x < e) ∧ (∃x. x ∉ S ∧ dist a x < e))"
  unfolding frontier_def closure_interior
  by (auto simp: mem_interior subset_eq ball_def)

lemma frontier_subset_closed: "closed S ⟹ frontier S ⊆ S"
  by (metis frontier_def closure_closed Diff_subset)

lemma frontier_empty [simp]: "frontier {} = {}"
  by (simp add: frontier_def)

lemma frontier_subset_eq: "frontier S ⊆ S ⟷ closed S"
proof -
  {
    assume "frontier S ⊆ S"
    then have "closure S ⊆ S"
      using interior_subset unfolding frontier_def by auto
    then have "closed S"
      using closure_subset_eq by auto
  }
  then show ?thesis using frontier_subset_closed[of S] ..
qed

lemma frontier_complement [simp]: "frontier (- S) = frontier S"
  by (auto simp: frontier_def closure_complement interior_complement)

lemma frontier_disjoint_eq: "frontier S ∩ S = {} ⟷ open S"
  using frontier_complement frontier_subset_eq[of "- S"]
  unfolding open_closed by auto

lemma frontier_UNIV [simp]: "frontier UNIV = {}"
  using frontier_complement frontier_empty by fastforce

lemma frontier_interiors: "frontier s = - interior(s) - interior(-s)"
  by (simp add: Int_commute frontier_def interior_closure)

lemma frontier_interior_subset: "frontier(interior S) ⊆ frontier S"
  by (simp add: Diff_mono frontier_interiors interior_mono interior_subset)

lemma connected_Int_frontier:
     "⟦connected s; s ∩ t ≠ {}; s - t ≠ {}⟧ ⟹ (s ∩ frontier t ≠ {})"
  apply (simp add: frontier_interiors connected_openin, safe)
  apply (drule_tac x="s ∩ interior t" in spec, safe)
   apply (drule_tac [2] x="s ∩ interior (-t)" in spec)
   apply (auto simp: disjoint_eq_subset_Compl dest: interior_subset [THEN subsetD])
  done

lemma closure_Un_frontier: "closure S = S ∪ frontier S"
proof -
  have "S ∪ interior S = S"
    using interior_subset by auto
  then show ?thesis
    using closure_subset by (auto simp: frontier_def)
qed


subsection ‹Filters and the ``eventually true'' quantifier›

definition indirection :: "'a::real_normed_vector ⇒ 'a ⇒ 'a filter"  (infixr "indirection" 70)
  where "a indirection v = at a within {b. ∃c≥0. b - a = scaleR c v}"

text ‹Identify Trivial limits, where we can't approach arbitrarily closely.›

lemma trivial_limit_within: "trivial_limit (at a within S) ⟷ ¬ a islimpt S"
proof
  assume "trivial_limit (at a within S)"
  then show "¬ a islimpt S"
    unfolding trivial_limit_def
    unfolding eventually_at_topological
    unfolding islimpt_def
    apply (clarsimp simp add: set_eq_iff)
    apply (rename_tac T, rule_tac x=T in exI)
    apply (clarsimp, drule_tac x=y in bspec, simp_all)
    done
next
  assume "¬ a islimpt S"
  then show "trivial_limit (at a within S)"
    unfolding trivial_limit_def eventually_at_topological islimpt_def
    by metis
qed

lemma trivial_limit_at_iff: "trivial_limit (at a) ⟷ ¬ a islimpt UNIV"
  using trivial_limit_within [of a UNIV] by simp

lemma trivial_limit_at: "¬ trivial_limit (at a)"
  for a :: "'a::perfect_space"
  by (rule at_neq_bot)

lemma trivial_limit_at_infinity:
  "¬ trivial_limit (at_infinity :: ('a::{real_normed_vector,perfect_space}) filter)"
  unfolding trivial_limit_def eventually_at_infinity
  apply clarsimp
  apply (subgoal_tac "∃x::'a. x ≠ 0", clarify)
   apply (rule_tac x="scaleR (b / norm x) x" in exI, simp)
  apply (cut_tac islimpt_UNIV [of "0::'a", unfolded islimpt_def])
  apply (drule_tac x=UNIV in spec, simp)
  done

lemma not_trivial_limit_within: "¬ trivial_limit (at x within S) = (x ∈ closure (S - {x}))"
  using islimpt_in_closure by (metis trivial_limit_within)

lemma at_within_eq_bot_iff: "at c within A = bot ⟷ c ∉ closure (A - {c})"
  using not_trivial_limit_within[of c A] by blast

text ‹Some property holds "sufficiently close" to the limit point.›

lemma trivial_limit_eventually: "trivial_limit net ⟹ eventually P net"
  by simp

lemma trivial_limit_eq: "trivial_limit net ⟷ (∀P. eventually P net)"
  by (simp add: filter_eq_iff)


subsection ‹Limits›

lemma Lim: "(f ⤏ l) net ⟷ trivial_limit net ∨ (∀e>0. eventually (λx. dist (f x) l < e) net)"
  by (auto simp: tendsto_iff trivial_limit_eq)

text ‹Show that they yield usual definitions in the various cases.›

lemma Lim_within_le: "(f ⤏ l)(at a within S) ⟷
    (∀e>0. ∃d>0. ∀x∈S. 0 < dist x a ∧ dist x a ≤ d ⟶ dist (f x) l < e)"
  by (auto simp: tendsto_iff eventually_at_le)

lemma Lim_within: "(f ⤏ l) (at a within S) ⟷
    (∀e >0. ∃d>0. ∀x ∈ S. 0 < dist x a ∧ dist x a  < d ⟶ dist (f x) l < e)"
  by (auto simp: tendsto_iff eventually_at)

corollary Lim_withinI [intro?]:
  assumes "⋀e. e > 0 ⟹ ∃d>0. ∀x ∈ S. 0 < dist x a ∧ dist x a < d ⟶ dist (f x) l ≤ e"
  shows "(f ⤏ l) (at a within S)"
  apply (simp add: Lim_within, clarify)
  apply (rule ex_forward [OF assms [OF half_gt_zero]], auto)
  done

lemma Lim_at: "(f ⤏ l) (at a) ⟷
    (∀e >0. ∃d>0. ∀x. 0 < dist x a ∧ dist x a < d  ⟶ dist (f x) l < e)"
  by (auto simp: tendsto_iff eventually_at)

lemma Lim_at_infinity: "(f ⤏ l) at_infinity ⟷ (∀e>0. ∃b. ∀x. norm x ≥ b ⟶ dist (f x) l < e)"
  by (auto simp: tendsto_iff eventually_at_infinity)

corollary Lim_at_infinityI [intro?]:
  assumes "⋀e. e > 0 ⟹ ∃B. ∀x. norm x ≥ B ⟶ dist (f x) l ≤ e"
  shows "(f ⤏ l) at_infinity"
  apply (simp add: Lim_at_infinity, clarify)
  apply (rule ex_forward [OF assms [OF half_gt_zero]], auto)
  done

lemma Lim_eventually: "eventually (λx. f x = l) net ⟹ (f ⤏ l) net"
  by (rule topological_tendstoI) (auto elim: eventually_mono)

lemma Lim_transform_within_set:
  fixes a :: "'a::metric_space" and l :: "'b::metric_space"
  shows "⟦(f ⤏ l) (at a within S); eventually (λx. x ∈ S ⟷ x ∈ T) (at a)⟧
         ⟹ (f ⤏ l) (at a within T)"
apply (clarsimp simp: eventually_at Lim_within)
apply (drule_tac x=e in spec, clarify)
apply (rename_tac k)
apply (rule_tac x="min d k" in exI, simp)
done

lemma Lim_transform_within_set_eq:
  fixes a l :: "'a::real_normed_vector"
  shows "eventually (λx. x ∈ s ⟷ x ∈ t) (at a)
         ⟹ ((f ⤏ l) (at a within s) ⟷ (f ⤏ l) (at a within t))"
  by (force intro: Lim_transform_within_set elim: eventually_mono)

lemma Lim_transform_within_openin:
  fixes a :: "'a::metric_space"
  assumes f: "(f ⤏ l) (at a within T)"
    and "openin (subtopology euclidean T) S" "a ∈ S"
    and eq: "⋀x. ⟦x ∈ S; x ≠ a⟧ ⟹ f x = g x"
  shows "(g ⤏ l) (at a within T)"
proof -
  obtain ε where "0 < ε" and ε: "ball a ε ∩ T ⊆ S"
    using assms by (force simp: openin_contains_ball)
  then have "a ∈ ball a ε"
    by simp
  show ?thesis
    by (rule Lim_transform_within [OF f ‹0 < ε› eq]) (use ε in ‹auto simp: dist_commute subset_iff›)
qed

lemma continuous_transform_within_openin:
  fixes a :: "'a::metric_space"
  assumes "continuous (at a within T) f"
    and "openin (subtopology euclidean T) S" "a ∈ S"
    and eq: "⋀x. x ∈ S ⟹ f x = g x"
  shows "continuous (at a within T) g"
  using assms by (simp add: Lim_transform_within_openin continuous_within)

text ‹The expected monotonicity property.›

lemma Lim_Un:
  assumes "(f ⤏ l) (at x within S)" "(f ⤏ l) (at x within T)"
  shows "(f ⤏ l) (at x within (S ∪ T))"
  using assms unfolding at_within_union by (rule filterlim_sup)

lemma Lim_Un_univ:
  "(f ⤏ l) (at x within S) ⟹ (f ⤏ l) (at x within T) ⟹
    S ∪ T = UNIV ⟹ (f ⤏ l) (at x)"
  by (metis Lim_Un)

text ‹Interrelations between restricted and unrestricted limits.›

lemma Lim_at_imp_Lim_at_within: "(f ⤏ l) (at x) ⟹ (f ⤏ l) (at x within S)"
  by (metis order_refl filterlim_mono subset_UNIV at_le)

lemma eventually_within_interior:
  assumes "x ∈ interior S"
  shows "eventually P (at x within S) ⟷ eventually P (at x)"
  (is "?lhs = ?rhs")
proof
  from assms obtain T where T: "open T" "x ∈ T" "T ⊆ S" ..
  {
    assume ?lhs
    then obtain A where "open A" and "x ∈ A" and "∀y∈A. y ≠ x ⟶ y ∈ S ⟶ P y"
      by (auto simp: eventually_at_topological)
    with T have "open (A ∩ T)" and "x ∈ A ∩ T" and "∀y ∈ A ∩ T. y ≠ x ⟶ P y"
      by auto
    then show ?rhs
      by (auto simp: eventually_at_topological)
  next
    assume ?rhs
    then show ?lhs
      by (auto elim: eventually_mono simp: eventually_at_filter)
  }
qed

lemma at_within_interior: "x ∈ interior S ⟹ at x within S = at x"
  unfolding filter_eq_iff by (intro allI eventually_within_interior)

lemma Lim_within_LIMSEQ:
  fixes a :: "'a::first_countable_topology"
  assumes "∀S. (∀n. S n ≠ a ∧ S n ∈ T) ∧ S ⇢ a ⟶ (λn. X (S n)) ⇢ L"
  shows "(X ⤏ L) (at a within T)"
  using assms unfolding tendsto_def [where l=L]
  by (simp add: sequentially_imp_eventually_within)

lemma Lim_right_bound:
  fixes f :: "'a :: {linorder_topology, conditionally_complete_linorder, no_top} ⇒
    'b::{linorder_topology, conditionally_complete_linorder}"
  assumes mono: "⋀a b. a ∈ I ⟹ b ∈ I ⟹ x < a ⟹ a ≤ b ⟹ f a ≤ f b"
    and bnd: "⋀a. a ∈ I ⟹ x < a ⟹ K ≤ f a"
  shows "(f ⤏ Inf (f ` ({x<..} ∩ I))) (at x within ({x<..} ∩ I))"
proof (cases "{x<..} ∩ I = {}")
  case True
  then show ?thesis by simp
next
  case False
  show ?thesis
  proof (rule order_tendstoI)
    fix a
    assume a: "a < Inf (f ` ({x<..} ∩ I))"
    {
      fix y
      assume "y ∈ {x<..} ∩ I"
      with False bnd have "Inf (f ` ({x<..} ∩ I)) ≤ f y"
        by (auto intro!: cInf_lower bdd_belowI2)
      with a have "a < f y"
        by (blast intro: less_le_trans)
    }
    then show "eventually (λx. a < f x) (at x within ({x<..} ∩ I))"
      by (auto simp: eventually_at_filter intro: exI[of _ 1] zero_less_one)
  next
    fix a
    assume "Inf (f ` ({x<..} ∩ I)) < a"
    from cInf_lessD[OF _ this] False obtain y where y: "x < y" "y ∈ I" "f y < a"
      by auto
    then have "eventually (λx. x ∈ I ⟶ f x < a) (at_right x)"
      unfolding eventually_at_right[OF ‹x < y›] by (metis less_imp_le le_less_trans mono)
    then show "eventually (λx. f x < a) (at x within ({x<..} ∩ I))"
      unfolding eventually_at_filter by eventually_elim simp
  qed
qed

text ‹Another limit point characterization.›

lemma limpt_sequential_inj:
  fixes x :: "'a::metric_space"
  shows "x islimpt S ⟷
         (∃f. (∀n::nat. f n ∈ S - {x}) ∧ inj f ∧ (f ⤏ x) sequentially)"
         (is "?lhs = ?rhs")
proof
  assume ?lhs
  then have "∀e>0. ∃x'∈S. x' ≠ x ∧ dist x' x < e"
    by (force simp: islimpt_approachable)
  then obtain y where y: "⋀e. e>0 ⟹ y e ∈ S ∧ y e ≠ x ∧ dist (y e) x < e"
    by metis
  define f where "f ≡ rec_nat (y 1) (λn fn. y (min (inverse(2 ^ (Suc n))) (dist fn x)))"
  have [simp]: "f 0 = y 1"
               "f(Suc n) = y (min (inverse(2 ^ (Suc n))) (dist (f n) x))" for n
    by (simp_all add: f_def)
  have f: "f n ∈ S ∧ (f n ≠ x) ∧ dist (f n) x < inverse(2 ^ n)" for n
  proof (induction n)
    case 0 show ?case
      by (simp add: y)
  next
    case (Suc n) then show ?case
      apply (auto simp: y)
      by (metis half_gt_zero_iff inverse_positive_iff_positive less_divide_eq_numeral1(1) min_less_iff_conj y zero_less_dist_iff zero_less_numeral zero_less_power)
  qed
  show ?rhs
  proof (rule_tac x=f in exI, intro conjI allI)
    show "⋀n. f n ∈ S - {x}"
      using f by blast
    have "dist (f n) x < dist (f m) x" if "m < n" for m n
    using that
    proof (induction n)
      case 0 then show ?case by simp
    next
      case (Suc n)
      then consider "m < n" | "m = n" using less_Suc_eq by blast
      then show ?case
      proof cases
        assume "m < n"
        have "dist (f(Suc n)) x = dist (y (min (inverse(2 ^ (Suc n))) (dist (f n) x))) x"
          by simp
        also have "... < dist (f n) x"
          by (metis dist_pos_lt f min.strict_order_iff min_less_iff_conj y)
        also have "... < dist (f m) x"
          using Suc.IH ‹m < n› by blast
        finally show ?thesis .
      next
        assume "m = n" then show ?case
          by simp (metis dist_pos_lt f half_gt_zero_iff inverse_positive_iff_positive min_less_iff_conj y zero_less_numeral zero_less_power)
      qed
    qed
    then show "inj f"
      by (metis less_irrefl linorder_injI)
    show "f ⇢ x"
      apply (rule tendstoI)
      apply (rule_tac c="nat (ceiling(1/e))" in eventually_sequentiallyI)
      apply (rule less_trans [OF f [THEN conjunct2, THEN conjunct2]])
      apply (simp add: field_simps)
      by (meson le_less_trans mult_less_cancel_left not_le of_nat_less_two_power)
  qed
next
  assume ?rhs
  then show ?lhs
    by (fastforce simp add: islimpt_approachable lim_sequentially)
qed

(*could prove directly from islimpt_sequential_inj, but only for metric spaces*)
lemma islimpt_sequential:
  fixes x :: "'a::first_countable_topology"
  shows "x islimpt S ⟷ (∃f. (∀n::nat. f n ∈ S - {x}) ∧ (f ⤏ x) sequentially)"
    (is "?lhs = ?rhs")
proof
  assume ?lhs
  from countable_basis_at_decseq[of x] obtain A where A:
      "⋀i. open (A i)"
      "⋀i. x ∈ A i"
      "⋀S. open S ⟹ x ∈ S ⟹ eventually (λi. A i ⊆ S) sequentially"
    by blast
  define f where "f n = (SOME y. y ∈ S ∧ y ∈ A n ∧ x ≠ y)" for n
  {
    fix n
    from ‹?lhs› have "∃y. y ∈ S ∧ y ∈ A n ∧ x ≠ y"
      unfolding islimpt_def using A(1,2)[of n] by auto
    then have "f n ∈ S ∧ f n ∈ A n ∧ x ≠ f n"
      unfolding f_def by (rule someI_ex)
    then have "f n ∈ S" "f n ∈ A n" "x ≠ f n" by auto
  }
  then have "∀n. f n ∈ S - {x}" by auto
  moreover have "(λn. f n) ⇢ x"
  proof (rule topological_tendstoI)
    fix S
    assume "open S" "x ∈ S"
    from A(3)[OF this] ‹⋀n. f n ∈ A n›
    show "eventually (λx. f x ∈ S) sequentially"
      by (auto elim!: eventually_mono)
  qed
  ultimately show ?rhs by fast
next
  assume ?rhs
  then obtain f :: "nat ⇒ 'a" where f: "⋀n. f n ∈ S - {x}" and lim: "f ⇢ x"
    by auto
  show ?lhs
    unfolding islimpt_def
  proof safe
    fix T
    assume "open T" "x ∈ T"
    from lim[THEN topological_tendstoD, OF this] f
    show "∃y∈S. y ∈ T ∧ y ≠ x"
      unfolding eventually_sequentially by auto
  qed
qed

lemma Lim_null:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  shows "(f ⤏ l) net ⟷ ((λx. f(x) - l) ⤏ 0) net"
  by (simp add: Lim dist_norm)

lemma Lim_null_comparison:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  assumes "eventually (λx. norm (f x) ≤ g x) net" "(g ⤏ 0) net"
  shows "(f ⤏ 0) net"
  using assms(2)
proof (rule metric_tendsto_imp_tendsto)
  show "eventually (λx. dist (f x) 0 ≤ dist (g x) 0) net"
    using assms(1) by (rule eventually_mono) (simp add: dist_norm)
qed

lemma Lim_transform_bound:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
    and g :: "'a ⇒ 'c::real_normed_vector"
  assumes "eventually (λn. norm (f n) ≤ norm (g n)) net"
    and "(g ⤏ 0) net"
  shows "(f ⤏ 0) net"
  using assms(1) tendsto_norm_zero [OF assms(2)]
  by (rule Lim_null_comparison)

lemma lim_null_mult_right_bounded:
  fixes f :: "'a ⇒ 'b::real_normed_div_algebra"
  assumes f: "(f ⤏ 0) F" and g: "eventually (λx. norm(g x) ≤ B) F"
    shows "((λz. f z * g z) ⤏ 0) F"
proof -
  have *: "((λx. norm (f x) * B) ⤏ 0) F"
    by (simp add: f tendsto_mult_left_zero tendsto_norm_zero)
  have "((λx. norm (f x) * norm (g x)) ⤏ 0) F"
    apply (rule Lim_null_comparison [OF _ *])
    apply (simp add: eventually_mono [OF g] mult_left_mono)
    done
  then show ?thesis
    by (subst tendsto_norm_zero_iff [symmetric]) (simp add: norm_mult)
qed

lemma lim_null_mult_left_bounded:
  fixes f :: "'a ⇒ 'b::real_normed_div_algebra"
  assumes g: "eventually (λx. norm(g x) ≤ B) F" and f: "(f ⤏ 0) F"
    shows "((λz. g z * f z) ⤏ 0) F"
proof -
  have *: "((λx. B * norm (f x)) ⤏ 0) F"
    by (simp add: f tendsto_mult_right_zero tendsto_norm_zero)
  have "((λx. norm (g x) * norm (f x)) ⤏ 0) F"
    apply (rule Lim_null_comparison [OF _ *])
    apply (simp add: eventually_mono [OF g] mult_right_mono)
    done
  then show ?thesis
    by (subst tendsto_norm_zero_iff [symmetric]) (simp add: norm_mult)
qed

lemma lim_null_scaleR_bounded:
  assumes f: "(f ⤏ 0) net" and gB: "eventually (λa. f a = 0 ∨ norm(g a) ≤ B) net"
    shows "((λn. f n *R g n) ⤏ 0) net"
proof
  fix ε::real
  assume "0 < ε"
  then have B: "0 < ε / (abs B + 1)" by simp
  have *: "¦f x¦ * norm (g x) < ε" if f: "¦f x¦ * (¦B¦ + 1) < ε" and g: "norm (g x) ≤ B" for x
  proof -
    have "¦f x¦ * norm (g x) ≤ ¦f x¦ * B"
      by (simp add: mult_left_mono g)
    also have "... ≤ ¦f x¦ * (¦B¦ + 1)"
      by (simp add: mult_left_mono)
    also have "... < ε"
      by (rule f)
    finally show ?thesis .
  qed
  show "∀F x in net. dist (f x *R g x) 0 < ε"
    apply (rule eventually_mono [OF eventually_conj [OF tendstoD [OF f B] gB] ])
    apply (auto simp: ‹0 < ε› divide_simps * split: if_split_asm)
    done
qed

text‹Deducing things about the limit from the elements.›

lemma Lim_in_closed_set:
  assumes "closed S"
    and "eventually (λx. f(x) ∈ S) net"
    and "¬ trivial_limit net" "(f ⤏ l) net"
  shows "l ∈ S"
proof (rule ccontr)
  assume "l ∉ S"
  with ‹closed S› have "open (- S)" "l ∈ - S"
    by (simp_all add: open_Compl)
  with assms(4) have "eventually (λx. f x ∈ - S) net"
    by (rule topological_tendstoD)
  with assms(2) have "eventually (λx. False) net"
    by (rule eventually_elim2) simp
  with assms(3) show "False"
    by (simp add: eventually_False)
qed

text‹Need to prove closed(cball(x,e)) before deducing this as a corollary.›

lemma Lim_dist_ubound:
  assumes "¬(trivial_limit net)"
    and "(f ⤏ l) net"
    and "eventually (λx. dist a (f x) ≤ e) net"
  shows "dist a l ≤ e"
  using assms by (fast intro: tendsto_le tendsto_intros)

lemma Lim_norm_ubound:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  assumes "¬(trivial_limit net)" "(f ⤏ l) net" "eventually (λx. norm(f x) ≤ e) net"
  shows "norm(l) ≤ e"
  using assms by (fast intro: tendsto_le tendsto_intros)

lemma Lim_norm_lbound:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  assumes "¬ trivial_limit net"
    and "(f ⤏ l) net"
    and "eventually (λx. e ≤ norm (f x)) net"
  shows "e ≤ norm l"
  using assms by (fast intro: tendsto_le tendsto_intros)

text‹Limit under bilinear function›

lemma Lim_bilinear:
  assumes "(f ⤏ l) net"
    and "(g ⤏ m) net"
    and "bounded_bilinear h"
  shows "((λx. h (f x) (g x)) ⤏ (h l m)) net"
  using ‹bounded_bilinear h› ‹(f ⤏ l) net› ‹(g ⤏ m) net›
  by (rule bounded_bilinear.tendsto)

text‹These are special for limits out of the same vector space.›

lemma Lim_within_id: "(id ⤏ a) (at a within s)"
  unfolding id_def by (rule tendsto_ident_at)

lemma Lim_at_id: "(id ⤏ a) (at a)"
  unfolding id_def by (rule tendsto_ident_at)

lemma Lim_at_zero:
  fixes a :: "'a::real_normed_vector"
    and l :: "'b::topological_space"
  shows "(f ⤏ l) (at a) ⟷ ((λx. f(a + x)) ⤏ l) (at 0)"
  using LIM_offset_zero LIM_offset_zero_cancel ..

text‹It's also sometimes useful to extract the limit point from the filter.›

abbreviation netlimit :: "'a::t2_space filter ⇒ 'a"
  where "netlimit F ≡ Lim F (λx. x)"

lemma netlimit_within: "¬ trivial_limit (at a within S) ⟹ netlimit (at a within S) = a"
  by (rule tendsto_Lim) (auto intro: tendsto_intros)

lemma netlimit_at:
  fixes a :: "'a::{perfect_space,t2_space}"
  shows "netlimit (at a) = a"
  using netlimit_within [of a UNIV] by simp

lemma lim_within_interior:
  "x ∈ interior S ⟹ (f ⤏ l) (at x within S) ⟷ (f ⤏ l) (at x)"
  by (metis at_within_interior)

lemma netlimit_within_interior:
  fixes x :: "'a::{t2_space,perfect_space}"
  assumes "x ∈ interior S"
  shows "netlimit (at x within S) = x"
  using assms by (metis at_within_interior netlimit_at)

lemma netlimit_at_vector:
  fixes a :: "'a::real_normed_vector"
  shows "netlimit (at a) = a"
proof (cases "∃x. x ≠ a")
  case True then obtain x where x: "x ≠ a" ..
  have "¬ trivial_limit (at a)"
    unfolding trivial_limit_def eventually_at dist_norm
    apply clarsimp
    apply (rule_tac x="a + scaleR (d / 2) (sgn (x - a))" in exI)
    apply (simp add: norm_sgn sgn_zero_iff x)
    done
  then show ?thesis
    by (rule netlimit_within [of a UNIV])
qed simp


text‹Useful lemmas on closure and set of possible sequential limits.›

lemma closure_sequential:
  fixes l :: "'a::first_countable_topology"
  shows "l ∈ closure S ⟷ (∃x. (∀n. x n ∈ S) ∧ (x ⤏ l) sequentially)"
  (is "?lhs = ?rhs")
proof
  assume "?lhs"
  moreover
  {
    assume "l ∈ S"
    then have "?rhs" using tendsto_const[of l sequentially] by auto
  }
  moreover
  {
    assume "l islimpt S"
    then have "?rhs" unfolding islimpt_sequential by auto
  }
  ultimately show "?rhs"
    unfolding closure_def by auto
next
  assume "?rhs"
  then show "?lhs" unfolding closure_def islimpt_sequential by auto
qed

lemma closed_sequential_limits:
  fixes S :: "'a::first_countable_topology set"
  shows "closed S ⟷ (∀x l. (∀n. x n ∈ S) ∧ (x ⤏ l) sequentially ⟶ l ∈ S)"
by (metis closure_sequential closure_subset_eq subset_iff)

lemma closure_approachable:
  fixes S :: "'a::metric_space set"
  shows "x ∈ closure S ⟷ (∀e>0. ∃y∈S. dist y x < e)"
  apply (auto simp: closure_def islimpt_approachable)
  apply (metis dist_self)
  done

lemma closure_approachable_le:
  fixes S :: "'a::metric_space set"
  shows "x ∈ closure S ⟷ (∀e>0. ∃y∈S. dist y x ≤ e)"
  unfolding closure_approachable
  using dense by force

lemma closed_approachable:
  fixes S :: "'a::metric_space set"
  shows "closed S ⟹ (∀e>0. ∃y∈S. dist y x < e) ⟷ x ∈ S"
  by (metis closure_closed closure_approachable)

lemma closure_contains_Inf:
  fixes S :: "real set"
  assumes "S ≠ {}" "bdd_below S"
  shows "Inf S ∈ closure S"
proof -
  have *: "∀x∈S. Inf S ≤ x"
    using cInf_lower[of _ S] assms by metis
  {
    fix e :: real
    assume "e > 0"
    then have "Inf S < Inf S + e" by simp
    with assms obtain x where "x ∈ S" "x < Inf S + e"
      by (subst (asm) cInf_less_iff) auto
    with * have "∃x∈S. dist x (Inf S) < e"
      by (intro bexI[of _ x]) (auto simp: dist_real_def)
  }
  then show ?thesis unfolding closure_approachable by auto
qed

lemma closure_Int_ballI:
  fixes S :: "'a :: metric_space set"
  assumes "⋀U. ⟦openin (subtopology euclidean S) U; U ≠ {}⟧ ⟹ T ∩ U ≠ {}"
 shows "S ⊆ closure T"
proof (clarsimp simp: closure_approachable dist_commute)
  fix x and e::real
  assume "x ∈ S" "0 < e"
  with assms [of "S ∩ ball x e"] show "∃y∈T. dist x y < e"
    by force
qed

lemma closed_contains_Inf:
  fixes S :: "real set"
  shows "S ≠ {} ⟹ bdd_below S ⟹ closed S ⟹ Inf S ∈ S"
  by (metis closure_contains_Inf closure_closed)

lemma closed_subset_contains_Inf:
  fixes A C :: "real set"
  shows "closed C ⟹ A ⊆ C ⟹ A ≠ {} ⟹ bdd_below A ⟹ Inf A ∈ C"
  by (metis closure_contains_Inf closure_minimal subset_eq)

lemma atLeastAtMost_subset_contains_Inf:
  fixes A :: "real set" and a b :: real
  shows "A ≠ {} ⟹ a ≤ b ⟹ A ⊆ {a..b} ⟹ Inf A ∈ {a..b}"
  by (rule closed_subset_contains_Inf)
     (auto intro: closed_real_atLeastAtMost intro!: bdd_belowI[of A a])

lemma not_trivial_limit_within_ball:
  "¬ trivial_limit (at x within S) ⟷ (∀e>0. S ∩ ball x e - {x} ≠ {})"
  (is "?lhs ⟷ ?rhs")
proof
  show ?rhs if ?lhs
  proof -
    {
      fix e :: real
      assume "e > 0"
      then obtain y where "y ∈ S - {x}" and "dist y x < e"
        using ‹?lhs› not_trivial_limit_within[of x S] closure_approachable[of x "S - {x}"]
        by auto
      then have "y ∈ S ∩ ball x e - {x}"
        unfolding ball_def by (simp add: dist_commute)
      then have "S ∩ ball x e - {x} ≠ {}" by blast
    }
    then show ?thesis by auto
  qed
  show ?lhs if ?rhs
  proof -
    {
      fix e :: real
      assume "e > 0"
      then obtain y where "y ∈ S ∩ ball x e - {x}"
        using ‹?rhs› by blast
      then have "y ∈ S - {x}" and "dist y x < e"
        unfolding ball_def by (simp_all add: dist_commute)
      then have "∃y ∈ S - {x}. dist y x < e"
        by auto
    }
    then show ?thesis
      using not_trivial_limit_within[of x S] closure_approachable[of x "S - {x}"]
      by auto
  qed
qed


subsection ‹Infimum Distance›

definition "infdist x A = (if A = {} then 0 else INF a:A. dist x a)"

lemma bdd_below_infdist[intro, simp]: "bdd_below (dist x`A)"
  by (auto intro!: zero_le_dist)

lemma infdist_notempty: "A ≠ {} ⟹ infdist x A = (INF a:A. dist x a)"
  by (simp add: infdist_def)

lemma infdist_nonneg: "0 ≤ infdist x A"
  by (auto simp: infdist_def intro: cINF_greatest)

lemma infdist_le: "a ∈ A ⟹ infdist x A ≤ dist x a"
  by (auto intro: cINF_lower simp add: infdist_def)

lemma infdist_le2: "a ∈ A ⟹ dist x a ≤ d ⟹ infdist x A ≤ d"
  by (auto intro!: cINF_lower2 simp add: infdist_def)

lemma infdist_zero[simp]: "a ∈ A ⟹ infdist a A = 0"
  by (auto intro!: antisym infdist_nonneg infdist_le2)

lemma infdist_triangle: "infdist x A ≤ infdist y A + dist x y"
proof (cases "A = {}")
  case True
  then show ?thesis by (simp add: infdist_def)
next
  case False
  then obtain a where "a ∈ A" by auto
  have "infdist x A ≤ Inf {dist x y + dist y a |a. a ∈ A}"
  proof (rule cInf_greatest)
    from ‹A ≠ {}› show "{dist x y + dist y a |a. a ∈ A} ≠ {}"
      by simp
    fix d
    assume "d ∈ {dist x y + dist y a |a. a ∈ A}"
    then obtain a where d: "d = dist x y + dist y a" "a ∈ A"
      by auto
    show "infdist x A ≤ d"
      unfolding infdist_notempty[OF ‹A ≠ {}›]
    proof (rule cINF_lower2)
      show "a ∈ A" by fact
      show "dist x a ≤ d"
        unfolding d by (rule dist_triangle)
    qed simp
  qed
  also have "… = dist x y + infdist y A"
  proof (rule cInf_eq, safe)
    fix a
    assume "a ∈ A"
    then show "dist x y + infdist y A ≤ dist x y + dist y a"
      by (auto intro: infdist_le)
  next
    fix i
    assume inf: "⋀d. d ∈ {dist x y + dist y a |a. a ∈ A} ⟹ i ≤ d"
    then have "i - dist x y ≤ infdist y A"
      unfolding infdist_notempty[OF ‹A ≠ {}›] using ‹a ∈ A›
      by (intro cINF_greatest) (auto simp: field_simps)
    then show "i ≤ dist x y + infdist y A"
      by simp
  qed
  finally show ?thesis by simp
qed

lemma in_closure_iff_infdist_zero:
  assumes "A ≠ {}"
  shows "x ∈ closure A ⟷ infdist x A = 0"
proof
  assume "x ∈ closure A"
  show "infdist x A = 0"
  proof (rule ccontr)
    assume "infdist x A ≠ 0"
    with infdist_nonneg[of x A] have "infdist x A > 0"
      by auto
    then have "ball x (infdist x A) ∩ closure A = {}"
      apply auto
      apply (metis ‹x ∈ closure A› closure_approachable dist_commute infdist_le not_less)
      done
    then have "x ∉ closure A"
      by (metis ‹0 < infdist x A› centre_in_ball disjoint_iff_not_equal)
    then show False using ‹x ∈ closure A› by simp
  qed
next
  assume x: "infdist x A = 0"
  then obtain a where "a ∈ A"
    by atomize_elim (metis all_not_in_conv assms)
  show "x ∈ closure A"
    unfolding closure_approachable
    apply safe
  proof (rule ccontr)
    fix e :: real
    assume "e > 0"
    assume "¬ (∃y∈A. dist y x < e)"
    then have "infdist x A ≥ e" using ‹a ∈ A›
      unfolding infdist_def
      by (force simp: dist_commute intro: cINF_greatest)
    with x ‹e > 0› show False by auto
  qed
qed

lemma in_closed_iff_infdist_zero:
  assumes "closed A" "A ≠ {}"
  shows "x ∈ A ⟷ infdist x A = 0"
proof -
  have "x ∈ closure A ⟷ infdist x A = 0"
    by (rule in_closure_iff_infdist_zero) fact
  with assms show ?thesis by simp
qed

lemma tendsto_infdist [tendsto_intros]:
  assumes f: "(f ⤏ l) F"
  shows "((λx. infdist (f x) A) ⤏ infdist l A) F"
proof (rule tendstoI)
  fix e ::real
  assume "e > 0"
  from tendstoD[OF f this]
  show "eventually (λx. dist (infdist (f x) A) (infdist l A) < e) F"
  proof (eventually_elim)
    fix x
    from infdist_triangle[of l A "f x"] infdist_triangle[of "f x" A l]
    have "dist (infdist (f x) A) (infdist l A) ≤ dist (f x) l"
      by (simp add: dist_commute dist_real_def)
    also assume "dist (f x) l < e"
    finally show "dist (infdist (f x) A) (infdist l A) < e" .
  qed
qed

text‹Some other lemmas about sequences.›

lemma sequentially_offset: (* TODO: move to Topological_Spaces.thy *)
  assumes "eventually (λi. P i) sequentially"
  shows "eventually (λi. P (i + k)) sequentially"
  using assms by (rule eventually_sequentially_seg [THEN iffD2])

lemma seq_offset_neg: (* TODO: move to Topological_Spaces.thy *)
  "(f ⤏ l) sequentially ⟹ ((λi. f(i - k)) ⤏ l) sequentially"
  apply (erule filterlim_compose)
  apply (simp add: filterlim_def le_sequentially eventually_filtermap eventually_sequentially, arith)
  done

lemma seq_harmonic: "((λn. inverse (real n)) ⤏ 0) sequentially"
  using LIMSEQ_inverse_real_of_nat by (rule LIMSEQ_imp_Suc) (* TODO: move to Limits.thy *)

subsection ‹More properties of closed balls›

lemma closed_cball [iff]: "closed (cball x e)"
proof -
  have "closed (dist x -` {..e})"
    by (intro closed_vimage closed_atMost continuous_intros)
  also have "dist x -` {..e} = cball x e"
    by auto
  finally show ?thesis .
qed

lemma open_contains_cball: "open S ⟷ (∀x∈S. ∃e>0.  cball x e ⊆ S)"
proof -
  {
    fix x and e::real
    assume "x∈S" "e>0" "ball x e ⊆ S"
    then have "∃d>0. cball x d ⊆ S" unfolding subset_eq by (rule_tac x="e/2" in exI, auto)
  }
  moreover
  {
    fix x and e::real
    assume "x∈S" "e>0" "cball x e ⊆ S"
    then have "∃d>0. ball x d ⊆ S"
      unfolding subset_eq
      apply (rule_tac x="e/2" in exI, auto)
      done
  }
  ultimately show ?thesis
    unfolding open_contains_ball by auto
qed

lemma open_contains_cball_eq: "open S ⟹ (∀x. x ∈ S ⟷ (∃e>0. cball x e ⊆ S))"
  by (metis open_contains_cball subset_eq order_less_imp_le centre_in_cball)

lemma mem_interior_cball: "x ∈ interior S ⟷ (∃e>0. cball x e ⊆ S)"
  apply (simp add: interior_def, safe)
  apply (force simp: open_contains_cball)
  apply (rule_tac x="ball x e" in exI)
  apply (simp add: subset_trans [OF ball_subset_cball])
  done

lemma islimpt_ball:
  fixes x y :: "'a::{real_normed_vector,perfect_space}"
  shows "y islimpt ball x e ⟷ 0 < e ∧ y ∈ cball x e"
  (is "?lhs ⟷ ?rhs")
proof
  show ?rhs if ?lhs
  proof
    {
      assume "e ≤ 0"
      then have *: "ball x e = {}"
        using ball_eq_empty[of x e] by auto
      have False using ‹?lhs›
        unfolding * using islimpt_EMPTY[of y] by auto
    }
    then show "e > 0" by (metis not_less)
    show "y ∈ cball x e"
      using closed_cball[of x e] islimpt_subset[of y "ball x e" "cball x e"]
        ball_subset_cball[of x e] ‹?lhs›
      unfolding closed_limpt by auto
  qed
  show ?lhs if ?rhs
  proof -
    from that have "e > 0" by auto
    {
      fix d :: real
      assume "d > 0"
      have "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
      proof (cases "d ≤ dist x y")
        case True
        then show "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
        proof (cases "x = y")
          case True
          then have False
            using ‹d ≤ dist x y› ‹d>0› by auto
          then show "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
            by auto
        next
          case False
          have "dist x (y - (d / (2 * dist y x)) *R (y - x)) =
            norm (x - y + (d / (2 * norm (y - x))) *R (y - x))"
            unfolding mem_cball mem_ball dist_norm diff_diff_eq2 diff_add_eq[symmetric]
            by auto
          also have "… = ¦- 1 + d / (2 * norm (x - y))¦ * norm (x - y)"
            using scaleR_left_distrib[of "- 1" "d / (2 * norm (y - x))", symmetric, of "y - x"]
            unfolding scaleR_minus_left scaleR_one
            by (auto simp: norm_minus_commute)
          also have "… = ¦- norm (x - y) + d / 2¦"
            unfolding abs_mult_pos[of "norm (x - y)", OF norm_ge_zero[of "x - y"]]
            unfolding distrib_right using ‹x≠y›  by auto
          also have "… ≤ e - d/2" using ‹d ≤ dist x y› and ‹d>0› and ‹?rhs›
            by (auto simp: dist_norm)
          finally have "y - (d / (2 * dist y x)) *R (y - x) ∈ ball x e" using ‹d>0›
            by auto
          moreover
          have "(d / (2*dist y x)) *R (y - x) ≠ 0"
            using ‹x≠y›[unfolded dist_nz] ‹d>0› unfolding scaleR_eq_0_iff
            by (auto simp: dist_commute)
          moreover
          have "dist (y - (d / (2 * dist y x)) *R (y - x)) y < d"
            unfolding dist_norm
            apply simp
            unfolding norm_minus_cancel
            using ‹d > 0› ‹x≠y›[unfolded dist_nz] dist_commute[of x y]
            unfolding dist_norm
            apply auto
            done
          ultimately show "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
            apply (rule_tac x = "y - (d / (2*dist y x)) *R (y - x)" in bexI)
            apply auto
            done
        qed
      next
        case False
        then have "d > dist x y" by auto
        show "∃x' ∈ ball x e. x' ≠ y ∧ dist x' y < d"
        proof (cases "x = y")
          case True
          obtain z where **: "z ≠ y" "dist z y < min e d"
            using perfect_choose_dist[of "min e d" y]
            using ‹d > 0› ‹e>0› by auto
          show "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
            unfolding ‹x = y›
            using ‹z ≠ y› **
            apply (rule_tac x=z in bexI)
            apply (auto simp: dist_commute)
            done
        next
          case False
          then show "∃x'∈ball x e. x' ≠ y ∧ dist x' y < d"
            using ‹d>0› ‹d > dist x y› ‹?rhs›
            apply (rule_tac x=x in bexI, auto)
            done
        qed
      qed
    }
    then show ?thesis
      unfolding mem_cball islimpt_approachable mem_ball by auto
  qed
qed

lemma closure_ball_lemma:
  fixes x y :: "'a::real_normed_vector"
  assumes "x ≠ y"
  shows "y islimpt ball x (dist x y)"
proof (rule islimptI)
  fix T
  assume "y ∈ T" "open T"
  then obtain r where "0 < r" "∀z. dist z y < r ⟶ z ∈ T"
    unfolding open_dist by fast
  (* choose point between x and y, within distance r of y. *)
  define k where "k = min 1 (r / (2 * dist x y))"
  define z where "z = y + scaleR k (x - y)"
  have z_def2: "z = x + scaleR (1 - k) (y - x)"
    unfolding z_def by (simp add: algebra_simps)
  have "dist z y < r"
    unfolding z_def k_def using ‹0 < r›
    by (simp add: dist_norm min_def)
  then have "z ∈ T"
    using ‹∀z. dist z y < r ⟶ z ∈ T› by simp
  have "dist x z < dist x y"
    unfolding z_def2 dist_norm
    apply (simp add: norm_minus_commute)
    apply (simp only: dist_norm [symmetric])
    apply (subgoal_tac "¦1 - k¦ * dist x y < 1 * dist x y", simp)
    apply (rule mult_strict_right_mono)
    apply (simp add: k_def ‹0 < r› ‹x ≠ y›)
    apply (simp add: ‹x ≠ y›)
    done
  then have "z ∈ ball x (dist x y)"
    by simp
  have "z ≠ y"
    unfolding z_def k_def using ‹x ≠ y› ‹0 < r›
    by (simp add: min_def)
  show "∃z∈ball x (dist x y). z ∈ T ∧ z ≠ y"
    using ‹z ∈ ball x (dist x y)› ‹z ∈ T› ‹z ≠ y›
    by fast
qed

lemma closure_ball [simp]:
  fixes x :: "'a::real_normed_vector"
  shows "0 < e ⟹ closure (ball x e) = cball x e"
  apply (rule equalityI)
  apply (rule closure_minimal)
  apply (rule ball_subset_cball)
  apply (rule closed_cball)
  apply (rule subsetI, rename_tac y)
  apply (simp add: le_less [where 'a=real])
  apply (erule disjE)
  apply (rule subsetD [OF closure_subset], simp)
  apply (simp add: closure_def, clarify)
  apply (rule closure_ball_lemma)
  apply (simp add: zero_less_dist_iff)
  done

(* In a trivial vector space, this fails for e = 0. *)
lemma interior_cball [simp]:
  fixes x :: "'a::{real_normed_vector, perfect_space}"
  shows "interior (cball x e) = ball x e"
proof (cases "e ≥ 0")
  case False note cs = this
  from cs have null: "ball x e = {}"
    using ball_empty[of e x] by auto
  moreover
  {
    fix y
    assume "y ∈ cball x e"
    then have False
      by (metis ball_eq_empty null cs dist_eq_0_iff dist_le_zero_iff empty_subsetI mem_cball subset_antisym subset_ball)
  }
  then have "cball x e = {}" by auto
  then have "interior (cball x e) = {}"
    using interior_empty by auto
  ultimately show ?thesis by blast
next
  case True note cs = this
  have "ball x e ⊆ cball x e"
    using ball_subset_cball by auto
  moreover
  {
    fix S y
    assume as: "S ⊆ cball x e" "open S" "y∈S"
    then obtain d where "d>0" and d: "∀x'. dist x' y < d ⟶ x' ∈ S"
      unfolding open_dist by blast
    then obtain xa where xa_y: "xa ≠ y" and xa: "dist xa y < d"
      using perfect_choose_dist [of d] by auto
    have "xa ∈ S"
      using d[THEN spec[where x = xa]]
      using xa by (auto simp: dist_commute)
    then have xa_cball: "xa ∈ cball x e"
      using as(1) by auto
    then have "y ∈ ball x e"
    proof (cases "x = y")
      case True
      then have "e > 0" using cs order.order_iff_strict xa_cball xa_y by fastforce
      then show "y ∈ ball x e"
        using ‹x = y › by simp
    next
      case False
      have "dist (y + (d / 2 / dist y x) *R (y - x)) y < d"
        unfolding dist_norm
        using ‹d>0› norm_ge_zero[of "y - x"] ‹x ≠ y› by auto
      then have *: "y + (d / 2 / dist y x) *R (y - x) ∈ cball x e"
        using d as(1)[unfolded subset_eq] by blast
      have "y - x ≠ 0" using ‹x ≠ y› by auto
      hence **:"d / (2 * norm (y - x)) > 0"
        unfolding zero_less_norm_iff[symmetric] using ‹d>0› by auto
      have "dist (y + (d / 2 / dist y x) *R (y - x)) x =
        norm (y + (d / (2 * norm (y - x))) *R y - (d / (2 * norm (y - x))) *R x - x)"
        by (auto simp: dist_norm algebra_simps)
      also have "… = norm ((1 + d / (2 * norm (y - x))) *R (y - x))"
        by (auto simp: algebra_simps)
      also have "… = ¦1 + d / (2 * norm (y - x))¦ * norm (y - x)"
        using ** by auto
      also have "… = (dist y x) + d/2"
        using ** by (auto simp: distrib_right dist_norm)
      finally have "e ≥ dist x y +d/2"
        using *[unfolded mem_cball] by (auto simp: dist_commute)
      then show "y ∈ ball x e"
        unfolding mem_ball using ‹d>0› by auto
    qed
  }
  then have "∀S ⊆ cball x e. open S ⟶ S ⊆ ball x e"
    by auto
  ultimately show ?thesis
    using interior_unique[of "ball x e" "cball x e"]
    using open_ball[of x e]
    by auto
qed

lemma interior_ball [simp]: "interior (ball x e) = ball x e"
  by (simp add: interior_open)

lemma frontier_ball [simp]:
  fixes a :: "'a::real_normed_vector"
  shows "0 < e ⟹ frontier (ball a e) = sphere a e"
  by (force simp: frontier_def)

lemma frontier_cball [simp]:
  fixes a :: "'a::{real_normed_vector, perfect_space}"
  shows "frontier (cball a e) = sphere a e"
  by (force simp: frontier_def)

lemma cball_eq_empty [simp]: "cball x e = {} ⟷ e < 0"
  apply (simp add: set_eq_iff not_le)
  apply (metis zero_le_dist dist_self order_less_le_trans)
  done

lemma cball_empty [simp]: "e < 0 ⟹ cball x e = {}"
  by (simp add: cball_eq_empty)

lemma cball_eq_sing:
  fixes x :: "'a::{metric_space,perfect_space}"
  shows "cball x e = {x} ⟷ e = 0"
proof (rule linorder_cases)
  assume e: "0 < e"
  obtain a where "a ≠ x" "dist a x < e"
    using perfect_choose_dist [OF e] by auto
  then have "a ≠ x" "dist x a ≤ e"
    by (auto simp: dist_commute)
  with e show ?thesis by (auto simp: set_eq_iff)
qed auto

lemma cball_sing:
  fixes x :: "'a::metric_space"
  shows "e = 0 ⟹ cball x e = {x}"
  by (auto simp: set_eq_iff)

lemma ball_divide_subset: "d ≥ 1 ⟹ ball x (e/d) ⊆ ball x e"
  apply (cases "e ≤ 0")
  apply (simp add: ball_empty divide_simps)
  apply (rule subset_ball)
  apply (simp add: divide_simps)
  done

lemma ball_divide_subset_numeral: "ball x (e / numeral w) ⊆ ball x e"
  using ball_divide_subset one_le_numeral by blast

lemma cball_divide_subset: "d ≥ 1 ⟹ cball x (e/d) ⊆ cball x e"
  apply (cases "e < 0")
  apply (simp add: divide_simps)
  apply (rule subset_cball)
  apply (metis div_by_1 frac_le not_le order_refl zero_less_one)
  done

lemma cball_divide_subset_numeral: "cball x (e / numeral w) ⊆ cball x e"
  using cball_divide_subset one_le_numeral by blast


subsection ‹Boundedness›

  (* FIXME: This has to be unified with BSEQ!! *)
definition (in metric_space) bounded :: "'a set ⇒ bool"
  where "bounded S ⟷ (∃x e. ∀y∈S. dist x y ≤ e)"

lemma bounded_subset_cball: "bounded S ⟷ (∃e x. S ⊆ cball x e ∧ 0 ≤ e)"
  unfolding bounded_def subset_eq  by auto (meson order_trans zero_le_dist)

lemma bounded_any_center: "bounded S ⟷ (∃e. ∀y∈S. dist a y ≤ e)"
  unfolding bounded_def
  by auto (metis add.commute add_le_cancel_right dist_commute dist_triangle_le)

lemma bounded_iff: "bounded S ⟷ (∃a. ∀x∈S. norm x ≤ a)"
  unfolding bounded_any_center [where a=0]
  by (simp add: dist_norm)

lemma bdd_above_norm: "bdd_above (norm ` X) ⟷ bounded X"
  by (simp add: bounded_iff bdd_above_def)

lemma bounded_norm_comp: "bounded ((λx. norm (f x)) ` S) = bounded (f ` S)"
  by (simp add: bounded_iff)

lemma boundedI:
  assumes "⋀x. x ∈ S ⟹ norm x ≤ B"
  shows "bounded S"
  using assms bounded_iff by blast

lemma bounded_empty [simp]: "bounded {}"
  by (simp add: bounded_def)

lemma bounded_subset: "bounded T ⟹ S ⊆ T ⟹ bounded S"
  by (metis bounded_def subset_eq)

lemma bounded_interior[intro]: "bounded S ⟹ bounded(interior S)"
  by (metis bounded_subset interior_subset)

lemma bounded_closure[intro]:
  assumes "bounded S"
  shows "bounded (closure S)"
proof -
  from assms obtain x and a where a: "∀y∈S. dist x y ≤ a"
    unfolding bounded_def by auto
  {
    fix y
    assume "y ∈ closure S"
    then obtain f where f: "∀n. f n ∈ S"  "(f ⤏ y) sequentially"
      unfolding closure_sequential by auto
    have "∀n. f n ∈ S ⟶ dist x (f n) ≤ a" using a by simp
    then have "eventually (λn. dist x (f n) ≤ a) sequentially"
      by (simp add: f(1))
    have "dist x y ≤ a"
      apply (rule Lim_dist_ubound [of sequentially f])
      apply (rule trivial_limit_sequentially)
      apply (rule f(2))
      apply fact
      done
  }
  then show ?thesis
    unfolding bounded_def by auto
qed

lemma bounded_closure_image: "bounded (f ` closure S) ⟹ bounded (f ` S)"
  by (simp add: bounded_subset closure_subset image_mono)

lemma bounded_cball[simp,intro]: "bounded (cball x e)"
  apply (simp add: bounded_def)
  apply (rule_tac x=x in exI)
  apply (rule_tac x=e in exI, auto)
  done

lemma bounded_ball[simp,intro]: "bounded (ball x e)"
  by (metis ball_subset_cball bounded_cball bounded_subset)

lemma bounded_Un[simp]: "bounded (S ∪ T) ⟷ bounded S ∧ bounded T"
  by (auto simp: bounded_def) (metis Un_iff bounded_any_center le_max_iff_disj)

lemma bounded_Union[intro]: "finite F ⟹ ∀S∈F. bounded S ⟹ bounded (⋃F)"
  by (induct rule: finite_induct[of F]) auto

lemma bounded_UN [intro]: "finite A ⟹ ∀x∈A. bounded (B x) ⟹ bounded (⋃x∈A. B x)"
  by (induct set: finite) auto

lemma bounded_insert [simp]: "bounded (insert x S) ⟷ bounded S"
proof -
  have "∀y∈{x}. dist x y ≤ 0"
    by simp
  then have "bounded {x}"
    unfolding bounded_def by fast
  then show ?thesis
    by (metis insert_is_Un bounded_Un)
qed

lemma bounded_subset_ballI: "S ⊆ ball x r ⟹ bounded S"
  by (meson bounded_ball bounded_subset)

lemma bounded_subset_ballD:
  assumes "bounded S" shows "∃r. 0 < r ∧ S ⊆ ball x r"
proof -
  obtain e::real and y where "S ⊆ cball y e"  "0 ≤ e"
    using assms by (auto simp: bounded_subset_cball)
  then show ?thesis
    apply (rule_tac x="dist x y + e + 1" in exI)
    apply (simp add: add.commute add_pos_nonneg)
    apply (erule subset_trans)
    apply (clarsimp simp add: cball_def)
    by (metis add_le_cancel_right add_strict_increasing dist_commute dist_triangle_le zero_less_one)
qed

lemma finite_imp_bounded [intro]: "finite S ⟹ bounded S"
  by (induct set: finite) simp_all

lemma bounded_pos: "bounded S ⟷ (∃b>0. ∀x∈ S. norm x ≤ b)"
  apply (simp add: bounded_iff)
  apply (subgoal_tac "⋀x (y::real). 0 < 1 + ¦y¦ ∧ (x ≤ y ⟶ x ≤ 1 + ¦y¦)")
  apply metis
  apply arith
  done

lemma bounded_pos_less: "bounded S ⟷ (∃b>0. ∀x∈ S. norm x < b)"
  apply (simp add: bounded_pos)
  apply (safe; rule_tac x="b+1" in exI; force)
  done

lemma Bseq_eq_bounded:
  fixes f :: "nat ⇒ 'a::real_normed_vector"
  shows "Bseq f ⟷ bounded (range f)"
  unfolding Bseq_def bounded_pos by auto

lemma bounded_Int[intro]: "bounded S ∨ bounded T ⟹ bounded (S ∩ T)"
  by (metis Int_lower1 Int_lower2 bounded_subset)

lemma bounded_diff[intro]: "bounded S ⟹ bounded (S - T)"
  by (metis Diff_subset bounded_subset)

lemma not_bounded_UNIV[simp]:
  "¬ bounded (UNIV :: 'a::{real_normed_vector, perfect_space} set)"
proof (auto simp: bounded_pos not_le)
  obtain x :: 'a where "x ≠ 0"
    using perfect_choose_dist [OF zero_less_one] by fast
  fix b :: real
  assume b: "b >0"
  have b1: "b +1 ≥ 0"
    using b by simp
  with ‹x ≠ 0› have "b < norm (scaleR (b + 1) (sgn x))"
    by (simp add: norm_sgn)
  then show "∃x::'a. b < norm x" ..
qed

corollary cobounded_imp_unbounded:
    fixes S :: "'a::{real_normed_vector, perfect_space} set"
    shows "bounded (- S) ⟹ ~ (bounded S)"
  using bounded_Un [of S "-S"]  by (simp add: sup_compl_top)

lemma bounded_dist_comp:
  assumes "bounded (f ` S)" "bounded (g ` S)"
  shows "bounded ((λx. dist (f x) (g x)) ` S)"
proof -
  from assms obtain M1 M2 where *: "dist (f x) undefined ≤ M1" "dist undefined (g x) ≤ M2" if "x ∈ S" for x
    by (auto simp: bounded_any_center[of _ undefined] dist_commute)
  have "dist (f x) (g x) ≤ M1 + M2" if "x ∈ S" for x
    using *[OF that]
    by (rule order_trans[OF dist_triangle add_mono])
  then show ?thesis
    by (auto intro!: boundedI)
qed

lemma bounded_linear_image:
  assumes "bounded S"
    and "bounded_linear f"
  shows "bounded (f ` S)"
proof -
  from assms(1) obtain b where b: "b > 0" "∀x∈S. norm x ≤ b"
    unfolding bounded_pos by auto
  from assms(2) obtain B where B: "B > 0" "∀x. norm (f x) ≤ B * norm x"
    using bounded_linear.pos_bounded by (auto simp: ac_simps)
  {
    fix x
    assume "x ∈ S"
    then have "norm x ≤ b"
      using b by auto
    then have "norm (f x) ≤ B * b"
      using B(2)
      apply (erule_tac x=x in allE)
      apply (metis B(1) B(2) order_trans mult_le_cancel_left_pos)
      done
  }
  then show ?thesis
    unfolding bounded_pos
    apply (rule_tac x="b*B" in exI)
    using b B by (auto simp: mult.commute)
qed

lemma bounded_scaling:
  fixes S :: "'a::real_normed_vector set"
  shows "bounded S ⟹ bounded ((λx. c *R x) ` S)"
  apply (rule bounded_linear_image, assumption)
  apply (rule bounded_linear_scaleR_right)
  done

lemma bounded_scaleR_comp:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  assumes "bounded (f ` S)"
  shows "bounded ((λx. r *R f x) ` S)"
  using bounded_scaling[of "f ` S" r] assms
  by (auto simp: image_image)

lemma bounded_translation:
  fixes S :: "'a::real_normed_vector set"
  assumes "bounded S"
  shows "bounded ((λx. a + x) ` S)"
proof -
  from assms obtain b where b: "b > 0" "∀x∈S. norm x ≤ b"
    unfolding bounded_pos by auto
  {
    fix x
    assume "x ∈ S"
    then have "norm (a + x) ≤ b + norm a"
      using norm_triangle_ineq[of a x] b by auto
  }
  then show ?thesis
    unfolding bounded_pos
    using norm_ge_zero[of a] b(1) and add_strict_increasing[of b 0 "norm a"]
    by (auto intro!: exI[of _ "b + norm a"])
qed

lemma bounded_translation_minus:
  fixes S :: "'a::real_normed_vector set"
  shows "bounded S ⟹ bounded ((λx. x - a) ` S)"
using bounded_translation [of S "-a"] by simp

lemma bounded_uminus [simp]:
  fixes X :: "'a::real_normed_vector set"
  shows "bounded (uminus ` X) ⟷ bounded X"
by (auto simp: bounded_def dist_norm; rule_tac x="-x" in exI; force simp: add.commute norm_minus_commute)

lemma uminus_bounded_comp [simp]:
  fixes f :: "'a ⇒ 'b::real_normed_vector"
  shows "bounded ((λx. - f x) ` S) ⟷ bounded (f ` S)"
  using bounded_uminus[of "f ` S"]
  by (auto simp: image_image)

lemma bounded_plus_comp:
  fixes f g::"'a ⇒ 'b::real_normed_vector"
  assumes "bounded (f ` S)"
  assumes "bounded (g ` S)"
  shows "bounded ((λx. f x + g x) ` S)"
proof -
  {
    fix B C
    assume "⋀x. x∈S ⟹ norm (f x) ≤ B" "⋀x. x∈S ⟹ norm (g x) ≤ C"
    then have "⋀x. x ∈ S ⟹ norm (f x + g x) ≤ B + C"
      by (auto intro!: norm_triangle_le add_mono)
  } then show ?thesis
    using assms by (fastforce simp: bounded_iff)
qed

lemma bounded_minus_comp:
  "bounded (f ` S) ⟹ bounded (g ` S) ⟹ bounded ((λx. f x - g x) ` S)"
  for f g::"'a ⇒ 'b::real_normed_vector"
  using bounded_plus_comp[of "f" S "λx. - g x"]
  by auto


subsection‹Some theorems on sups and infs using the notion "bounded".›

lemma bounded_real: "bounded (S::real set) ⟷ (∃a. ∀x∈S. ¦x¦ ≤ a)"
  by (simp add: bounded_iff)

lemma bounded_imp_bdd_above: "bounded S ⟹ bdd_above (S :: real set)"
  by (auto simp: bounded_def bdd_above_def dist_real_def)
     (metis abs_le_D1 abs_minus_commute diff_le_eq)

lemma bounded_imp_bdd_below: "bounded S ⟹ bdd_below (S :: real set)"
  by (auto simp: bounded_def bdd_below_def dist_real_def)
     (metis abs_le_D1 add.commute diff_le_eq)

lemma bounded_inner_imp_bdd_above:
  assumes "bounded s"
    shows "bdd_above ((λx. x ∙ a) ` s)"
by (simp add: assms bounded_imp_bdd_above bounded_linear_image bounded_linear_inner_left)

lemma bounded_inner_imp_bdd_below:
  assumes "bounded s"
    shows "bdd_below ((λx. x ∙ a) ` s)"
by (simp add: assms bounded_imp_bdd_below bounded_linear_image bounded_linear_inner_left)

lemma bounded_has_Sup:
  fixes S :: "real set"
  assumes "bounded S"
    and "S ≠ {}"
  shows "∀x∈S. x ≤ Sup S"
    and "∀b. (∀x∈S. x ≤ b) ⟶ Sup S ≤ b"
proof
  show "∀b. (∀x∈S. x ≤ b) ⟶ Sup S ≤ b"
    using assms by (metis cSup_least)
qed (metis cSup_upper assms(1) bounded_imp_bdd_above)

lemma Sup_insert:
  fixes S :: "real set"
  shows "bounded S ⟹ Sup (insert x S) = (if S = {} then x else max x (Sup S))"
  by (auto simp: bounded_imp_bdd_above sup_max cSup_insert_If)

lemma Sup_insert_finite:
  fixes S :: "'a::conditionally_complete_linorder set"
  shows "finite S ⟹ Sup (insert x S) = (if S = {} then x else max x (Sup S))"
by (simp add: cSup_insert sup_max)

lemma bounded_has_Inf:
  fixes S :: "real set"
  assumes "bounded S"
    and "S ≠ {}"
  shows "∀x∈S. x ≥ Inf S"
    and "∀b. (∀x∈S. x ≥ b) ⟶ Inf S ≥ b"
proof
  show "∀b. (∀x∈S. x ≥ b) ⟶ Inf S ≥ b"
    using assms by (metis cInf_greatest)
qed (metis cInf_lower assms(1) bounded_imp_bdd_below)

lemma Inf_insert:
  fixes S :: "real set"
  shows "bounded S ⟹ Inf (insert x S) = (if S = {} then x else min x (Inf S))"
  by (auto simp: bounded_imp_bdd_below inf_min cInf_insert_If)

lemma Inf_insert_finite:
  fixes S :: "'a::conditionally_complete_linorder set"
  shows "finite S ⟹ Inf (insert x S) = (if S = {} then x else min x (Inf S))"
by (simp add: cInf_eq_Min)

lemma finite_imp_less_Inf:
  fixes a :: "'a::conditionally_complete_linorder"
  shows "⟦finite X; x ∈ X; ⋀x. x∈X ⟹ a < x⟧ ⟹ a < Inf X"
  by (induction X rule: finite_induct) (simp_all add: cInf_eq_Min Inf_insert_finite)

lemma finite_less_Inf_iff:
  fixes a :: "'a :: conditionally_complete_linorder"
  shows "⟦finite X; X ≠ {}⟧ ⟹ a < Inf X ⟷ (∀x ∈ X. a < x)"
  by (auto simp: cInf_eq_Min)

lemma finite_imp_Sup_less:
  fixes a :: "'a::conditionally_complete_linorder"
  shows "⟦finite X; x ∈ X; ⋀x. x∈X ⟹ a > x⟧ ⟹ a > Sup X"
  by (induction X rule: finite_induct) (simp_all add: cSup_eq_Max Sup_insert_finite)

lemma finite_Sup_less_iff:
  fixes a :: "'a :: conditionally_complete_linorder"
  shows "⟦finite X; X ≠ {}⟧ ⟹ a > Sup X ⟷ (∀x ∈ X. a > x)"
  by (auto simp: cSup_eq_Max)

subsection ‹Compactness›

subsubsection ‹Bolzano-Weierstrass property›

lemma heine_borel_imp_bolzano_weierstrass:
  assumes "compact s"
    and "infinite t"
    and "t ⊆ s"
  shows "∃x ∈ s. x islimpt t"
proof (rule ccontr)
  assume "¬ (∃x ∈ s. x islimpt t)"
  then obtain f where f: "∀x∈s. x ∈ f x ∧ open (f x) ∧ (∀y∈t. y ∈ f x ⟶ y = x)"
    unfolding islimpt_def
    using bchoice[of s "λ x T. x ∈ T ∧ open T ∧ (∀y∈t. y ∈ T ⟶ y = x)"]
    by auto
  obtain g where g: "g ⊆ {t. ∃x. x ∈ s ∧ t = f x}" "finite g" "s ⊆ ⋃g"
    using assms(1)[unfolded compact_eq_heine_borel, THEN spec[where x="{t. ∃x. x∈s ∧ t = f x}"]]
    using f by auto
  from g(1,3) have g':"∀x∈g. ∃xa ∈ s. x = f xa"
    by auto
  {
    fix x y
    assume "x ∈ t" "y ∈ t" "f x = f y"
    then have "x ∈ f x"  "y ∈ f x ⟶ y = x"
      using f[THEN bspec[where x=x]] and ‹t ⊆ s› by auto
    then have "x = y"
      using ‹f x = f y› and f[THEN bspec[where x=y]] and ‹y ∈ t› and ‹t ⊆ s›
      by auto
  }
  then have "inj_on f t"
    unfolding inj_on_def by simp
  then have "infinite (f ` t)"
    using assms(2) using finite_imageD by auto
  moreover
  {
    fix x
    assume "x ∈ t" "f x ∉ g"
    from g(3) assms(3) ‹x ∈ t› obtain h where "h ∈ g" and "x ∈ h"
      by auto
    then obtain y where "y ∈ s" "h = f y"
      using g'[THEN bspec[where x=h]] by auto
    then have "y = x"
      using f[THEN bspec[where x=y]] and ‹x∈t› and ‹x∈h›[unfolded ‹h = f y›]
      by auto
    then have False
      using ‹f x ∉ g› ‹h ∈ g› unfolding ‹h = f y›
      by auto
  }
  then have "f ` t ⊆ g" by auto
  ultimately show False
    using g(2) using finite_subset by auto
qed

lemma acc_point_range_imp_convergent_subsequence:
  fixes l :: "'a :: first_countable_topology"
  assumes l: "∀U. l∈U ⟶ open U ⟶ infinite (U ∩ range f)"
  shows "∃r::nat⇒nat. strict_mono r ∧ (f ∘ r) ⇢ l"
proof -
  from countable_basis_at_decseq[of l]
  obtain A where A:
      "⋀i. open (A i)"
      "⋀i. l ∈ A i"
      "⋀S. open S ⟹ l ∈ S ⟹ eventually (λi. A i ⊆ S) sequentially"
    by blast
  define s where "s n i = (SOME j. i < j ∧ f j ∈ A (Suc n))" for n i
  {
    fix n i
    have "infinite (A (Suc n) ∩ range f - f`{.. i})"
      using l A by auto
    then have "∃x. x ∈ A (Suc n) ∩ range f - f`{.. i}"
      unfolding ex_in_conv by (intro notI) simp
    then have "∃j. f j ∈ A (Suc n) ∧ j ∉ {.. i}"
      by auto
    then have "∃a. i < a ∧ f a ∈ A (Suc n)"
      by (auto simp: not_le)
    then have "i < s n i" "f (s n i) ∈ A (Suc n)"
      unfolding s_def by (auto intro: someI2_ex)
  }
  note s = this
  define r where "r = rec_nat (s 0 0) s"
  have "strict_mono r"
    by (auto simp: r_def s strict_mono_Suc_iff)
  moreover
  have "(λn. f (r n)) ⇢ l"
  proof (rule topological_tendstoI)
    fix S
    assume "open S" "l ∈ S"
    with A(3) have "eventually (λi. A i ⊆ S) sequentially"
      by auto
    moreover
    {
      fix i
      assume "Suc 0 ≤ i"
      then have "f (r i) ∈ A i"
        by (cases i) (simp_all add: r_def s)
    }
    then have "eventually (λi. f (r i) ∈ A i) sequentially"
      by (auto simp: eventually_sequentially)
    ultimately show "eventually (λi. f (r i) ∈ S) sequentially"
      by eventually_elim auto
  qed
  ultimately show "∃r::nat⇒nat. strict_mono r ∧ (f ∘ r) ⇢ l"
    by (auto simp: convergent_def comp_def)
qed

lemma sequence_infinite_lemma:
  fixes f :: "nat ⇒ 'a::t1_space"
  assumes "∀n. f n ≠ l"
    and "(f ⤏ l) sequentially"
  shows "infinite (range f)"
proof
  assume "finite (range f)"
  then have "closed (range f)"
    by (rule finite_imp_closed)
  then have "open (- range f)"
    by (rule open_Compl)
  from assms(1) have "l ∈ - range f"
    by auto
  from assms(2) have "eventually (λn. f n ∈ - range f) sequentially"
    using ‹open (- range f)› ‹l ∈ - range f›
    by (rule topological_tendstoD)
  then show False
    unfolding eventually_sequentially
    by auto
qed

lemma closure_insert:
  fixes x :: "'a::t1_space"
  shows "closure (insert x s) = insert x (closure s)"
  apply (rule closure_unique)
  apply (rule insert_mono [OF closure_subset])
  apply (rule closed_insert [OF closed_closure])
  apply (simp add: closure_minimal)
  done

lemma islimpt_insert:
  fixes x :: "'a::t1_space"
  shows "x islimpt (insert a s) ⟷ x islimpt s"
proof
  assume *: "x islimpt (insert a s)"
  show "x islimpt s"
  proof (rule islimptI)
    fix t
    assume t: "x ∈ t" "open t"
    show "∃y∈s. y ∈ t ∧ y ≠ x"
    proof (cases "x = a")
      case True
      obtain y where "y ∈ insert a s" "y ∈ t" "y ≠ x"
        using * t by (rule islimptE)
      with ‹x = a› show ?thesis by auto
    next
      case False
      with t have t': "x ∈ t - {a}" "open (t - {a})"
        by (simp_all add: open_Diff)
      obtain y where "y ∈ insert a s" "y ∈ t - {a}" "y ≠ x"
        using * t' by (rule islimptE)
      then show ?thesis by auto
    qed
  qed
next
  assume "x islimpt s"
  then show "x islimpt (insert a s)"
    by (rule islimpt_subset) auto
qed

lemma islimpt_finite:
  fixes x :: "'a::t1_space"
  shows "finite s ⟹ ¬ x islimpt s"
  by (induct set: finite) (simp_all add: islimpt_insert)

lemma islimpt_Un_finite:
  fixes x :: "'a::t1_space"
  shows "finite s ⟹ x islimpt (s ∪ t) ⟷ x islimpt t"
  by (simp add: islimpt_Un islimpt_finite)

lemma islimpt_eq_acc_point:
  fixes l :: "'a :: t1_space"
  shows "l islimpt S ⟷ (∀U. l∈U ⟶ open U ⟶ infinite (U ∩ S))"
proof (safe intro!: islimptI)
  fix U
  assume "l islimpt S" "l ∈ U" "open U" "finite (U ∩ S)"
  then have "l islimpt S" "l ∈ (U - (U ∩ S - {l}))" "open (U - (U ∩ S - {l}))"
    by (auto intro: finite_imp_closed)
  then show False
    by (rule islimptE) auto
next
  fix T
  assume *: "∀U. l∈U ⟶ open U ⟶ infinite (U ∩ S)" "l ∈ T" "open T"
  then have "infinite (T ∩ S - {l})"
    by auto
  then have "∃x. x ∈ (T ∩ S - {l})"
    unfolding ex_in_conv by (intro notI) simp
  then show "∃y∈S. y ∈ T ∧ y ≠ l"
    by auto
qed

corollary infinite_openin:
  fixes S :: "'a :: t1_space set"
  shows "⟦openin (subtopology euclidean U) S; x ∈ S; x islimpt U⟧ ⟹ infinite S"
  by (clarsimp simp add: openin_open islimpt_eq_acc_point inf_commute)

lemma islimpt_range_imp_convergent_subsequence:
  fixes l :: "'a :: {t1_space, first_countable_topology}"
  assumes l: "l islimpt (range f)"
  shows "∃r::nat⇒nat. strict_mono r ∧ (f ∘ r) ⇢ l"
  using l unfolding islimpt_eq_acc_point
  by (rule acc_point_range_imp_convergent_subsequence)

lemma islimpt_eq_infinite_ball: "x islimpt S ⟷ (∀e>0. infinite(S ∩ ball x e))"
  apply (simp add: islimpt_eq_acc_point, safe)
   apply (metis Int_commute open_ball centre_in_ball)
  by (metis open_contains_ball Int_mono finite_subset inf_commute subset_refl)

lemma islimpt_eq_infinite_cball: "x islimpt S ⟷ (∀e>0. infinite(S ∩ cball x e))"
  apply (simp add: islimpt_eq_infinite_ball, safe)
   apply (meson Int_mono ball_subset_cball finite_subset order_refl)
  by (metis open_ball centre_in_ball finite_Int inf.absorb_iff2 inf_assoc open_contains_cball_eq)

lemma sequence_unique_limpt:
  fixes f :: "nat ⇒ 'a::t2_space"
  assumes "(f ⤏ l) sequentially"
    and "l' islimpt (range f)"
  shows "l' = l"
proof (rule ccontr)
  assume "l' ≠ l"
  obtain s t where "open s" "open t" "l' ∈ s" "l ∈ t" "s ∩ t = {}"
    using hausdorff [OF ‹l' ≠ l›] by auto
  have "eventually (λn. f n ∈ t) sequentially"
    using assms(1) ‹open t› ‹l ∈ t› by (rule topological_tendstoD)
  then obtain N where "∀n≥N. f n ∈ t"
    unfolding eventually_sequentially by auto

  have "UNIV = {..<N} ∪ {N..}"
    by auto
  then have "l' islimpt (f ` ({..<N} ∪ {N..}))"
    using assms(2) by simp
  then have "l' islimpt (f ` {..<N} ∪ f ` {N..})"
    by (simp add: image_Un)
  then have "l' islimpt (f ` {N..})"
    by (simp add: islimpt_Un_finite)
  then obtain y where "y ∈ f ` {N..}" "y ∈ s" "y ≠ l'"
    using ‹l' ∈ s› ‹open s› by (rule islimptE)
  then obtain n where "N ≤ n" "f n ∈ s" "f n ≠ l'"
    by auto
  with ‹∀n≥N. f n ∈ t› have "f n ∈ s ∩ t"
    by simp
  with ‹s ∩ t = {}› show False
    by simp
qed

lemma bolzano_weierstrass_imp_closed:
  fixes s :: "'a::{first_countable_topology,t2_space} set"
  assumes "∀t. infinite t ∧ t ⊆ s --> (∃x ∈ s. x islimpt t)"
  shows "closed s"
proof -
  {
    fix x l
    assume as: "∀n::nat. x n ∈ s" "(x ⤏ l) sequentially"
    then have "l ∈ s"
    proof (cases "∀n. x n ≠ l")
      case False
      then show "l∈s" using as(1) by auto
    next
      case True note cas = this
      with as(2) have "infinite (range x)"
        using sequence_infinite_lemma[of x l] by auto
      then obtain l' where "l'∈s" "l' islimpt (range x)"
        using assms[THEN spec[where x="range x"]] as(1) by auto
      then show "l∈s" using sequence_unique_limpt[of x l l']
        using as cas by auto
    qed
  }
  then show ?thesis
    unfolding closed_sequential_limits by fast
qed

lemma compact_imp_bounded:
  assumes "compact U"
  shows "bounded U"
proof -
  have "compact U" "∀x∈U. open (ball x 1)" "U ⊆ (⋃x∈U. ball x 1)"
    using assms by auto
  then obtain D where D: "D ⊆ U" "finite D" "U ⊆ (⋃x∈D. ball x 1)"
    by (metis compactE_image)
  from ‹finite D› have "bounded (⋃x∈D. ball x 1)"
    by (simp add: bounded_UN)
  then show "bounded U" using ‹U ⊆ (⋃x∈D. ball x 1)›
    by (rule bounded_subset)
qed

text‹In particular, some common special cases.›

lemma compact_Un [intro]:
  assumes "compact s"
    and "compact t"
  shows " compact (s ∪ t)"
proof (rule compactI)
  fix f
  assume *: "Ball f open" "s ∪ t ⊆ ⋃f"
  from * ‹compact s› obtain s' where "s' ⊆ f ∧ finite s' ∧ s ⊆ ⋃s'"
    unfolding compact_eq_heine_borel by (auto elim!: allE[of _ f])
  moreover
  from * ‹compact t› obtain t' where "t' ⊆ f ∧ finite t' ∧ t ⊆ ⋃t'"
    unfolding compact_eq_heine_borel by (auto elim!: allE[of _ f])
  ultimately show "∃f'⊆f. finite f' ∧ s ∪ t ⊆ ⋃f'"
    by (auto intro!: exI[of _ "s' ∪ t'"])
qed

lemma compact_Union [intro]: "finite S ⟹ (⋀T. T ∈ S ⟹ compact T) ⟹ compact (⋃S)"
  by (induct set: finite) auto

lemma compact_UN [intro]:
  "finite A ⟹ (⋀x. x ∈ A ⟹ compact (B x)) ⟹ compact (⋃x∈A. B x)"
  by (rule compact_Union) auto

lemma closed_Int_compact [intro]:
  assumes "closed s"
    and "compact t"
  shows "compact (s ∩ t)"
  using compact_Int_closed [of t s] assms
  by (simp add: Int_commute)

lemma compact_Int [intro]:
  fixes s t :: "'a :: t2_space set"
  assumes "compact s"
    and "compact t"
  shows "compact (s ∩ t)"
  using assms by (intro compact_Int_closed compact_imp_closed)

lemma compact_sing [simp]: "compact {a}"
  unfolding compact_eq_heine_borel by auto

lemma compact_insert [simp]:
  assumes "compact s"
  shows "compact (insert x s)"
proof -
  have "compact ({x} ∪ s)"
    using compact_sing assms by (rule compact_Un)
  then show ?thesis by simp
qed

lemma finite_imp_compact: "finite s ⟹ compact s"
  by (induct set: finite) simp_all

lemma open_delete:
  fixes s :: "'a::t1_space set"
  shows "open s ⟹ open (s - {x})"
  by (simp add: open_Diff)

lemma openin_delete:
  fixes a :: "'a :: t1_space"
  shows "openin (subtopology euclidean u) s
         ⟹ openin (subtopology euclidean u) (s - {a})"
by (metis Int_Diff open_delete openin_open)


text‹Compactness expressed with filters›

lemma closure_iff_nhds_not_empty:
  "x ∈ closure X ⟷ (∀A. ∀S⊆A. open S ⟶ x ∈ S ⟶ X ∩ A ≠ {})"
proof safe
  assume x: "x ∈ closure X"
  fix S A
  assume "open S" "x ∈ S" "X ∩ A = {}" "S ⊆ A"
  then have "x ∉ closure (-S)"
    by (auto simp: closure_complement subset_eq[symmetric] intro: interiorI)
  with x have "x ∈ closure X - closure (-S)"
    by auto
  also have "… ⊆ closure (X ∩ S)"
    using ‹open S› open_Int_closure_subset[of S X] by (simp add: closed_Compl ac_simps)
  finally have "X ∩ S ≠ {}" by auto
  then show False using ‹X ∩ A = {}› ‹S ⊆ A› by auto
next
  assume "∀A S. S ⊆ A ⟶ open S ⟶ x ∈ S ⟶ X ∩ A ≠ {}"
  from this[THEN spec, of "- X", THEN spec, of "- closure X"]
  show "x ∈ closure X"
    by (simp add: closure_subset open_Compl)
qed

corollary closure_Int_ball_not_empty:
  assumes "S ⊆ closure T" "x ∈ S" "r > 0"
  shows "T ∩ ball x r ≠ {}"
  using assms centre_in_ball closure_iff_nhds_not_empty by blast

lemma compact_filter:
  "compact U ⟷ (∀F. F ≠ bot ⟶ eventually (λx. x ∈ U) F ⟶ (∃x∈U. inf (nhds x) F ≠ bot))"
proof (intro allI iffI impI compact_fip[THEN iffD2] notI)
  fix F
  assume "compact U"
  assume F: "F ≠ bot" "eventually (λx. x ∈ U) F"
  then have "U ≠ {}"
    by (auto simp: eventually_False)

  define Z where "Z = closure ` {A. eventually (λx. x ∈ A) F}"
  then have "∀z∈Z. closed z"
    by auto
  moreover
  have ev_Z: "⋀z. z ∈ Z ⟹ eventually (λx. x ∈ z) F"
    unfolding Z_def by (auto elim: eventually_mono intro: set_mp[OF closure_subset])
  have "(∀B ⊆ Z. finite B ⟶ U ∩ ⋂B ≠ {})"
  proof (intro allI impI)
    fix B assume "finite B" "B ⊆ Z"
    with ‹finite B› ev_Z F(2) have "eventually (λx. x ∈ U ∩ (⋂B)) F"
      by (auto simp: eventually_ball_finite_distrib eventually_conj_iff)
    with F show "U ∩ ⋂B ≠ {}"
      by (intro notI) (simp add: eventually_False)
  qed
  ultimately have "U ∩ ⋂Z ≠ {}"
    using ‹compact U› unfolding compact_fip by blast
  then obtain x where "x ∈ U" and x: "⋀z. z ∈ Z ⟹ x ∈ z"
    by auto

  have "⋀P. eventually P (inf (nhds x) F) ⟹ P ≠ bot"
    unfolding eventually_inf eventually_nhds
  proof safe
    fix P Q R S
    assume "eventually R F" "open S" "x ∈ S"
    with open_Int_closure_eq_empty[of S "{x. R x}"] x[of "closure {x. R x}"]
    have "S ∩ {x. R x} ≠ {}" by (auto simp: Z_def)
    moreover assume "Ball S Q" "∀x. Q x ∧ R x ⟶ bot x"
    ultimately show False by (auto simp: set_eq_iff)
  qed
  with ‹x ∈ U› show "∃x∈U. inf (nhds x) F ≠ bot"
    by (metis eventually_bot)
next
  fix A
  assume A: "∀a∈A. closed a" "∀B⊆A. finite B ⟶ U ∩ ⋂B ≠ {}" "U ∩ ⋂A = {}"
  define F where "F = (INF a:insert U A. principal a)"
  have "F ≠ bot"
    unfolding F_def
  proof (rule INF_filter_not_bot)
    fix X
    assume X: "X ⊆ insert U A" "finite X"
    with A(2)[THEN spec, of "X - {U}"] have "U ∩ ⋂(X - {U}) ≠ {}"
      by auto
    with X show "(INF a:X. principal a) ≠ bot"
      by (auto simp: INF_principal_finite principal_eq_bot_iff)
  qed
  moreover
  have "F ≤ principal U"
    unfolding F_def by auto
  then have "eventually (λx. x ∈ U) F"
    by (auto simp: le_filter_def eventually_principal)
  moreover
  assume "∀F. F ≠ bot ⟶ eventually (λx. x ∈ U) F ⟶ (∃x∈U. inf (nhds x) F ≠ bot)"
  ultimately obtain x where "x ∈ U" and x: "inf (nhds x) F ≠ bot"
    by auto

  { fix V assume "V ∈ A"
    then have "F ≤ principal V"
      unfolding F_def by (intro INF_lower2[of V]) auto
    then have V: "eventually (λx. x ∈ V) F"
      by (auto simp: le_filter_def eventually_principal)
    have "x ∈ closure V"
      unfolding closure_iff_nhds_not_empty
    proof (intro impI allI)
      fix S A
      assume "open S" "x ∈ S" "S ⊆ A"
      then have "eventually (λx. x ∈ A) (nhds x)"
        by (auto simp: eventually_nhds)
      with V have "eventually (λx. x ∈ V ∩ A) (inf (nhds x) F)"
        by (auto simp: eventually_inf)
      with x show "V ∩ A ≠ {}"
        by (auto simp del: Int_iff simp add: trivial_limit_def)
    qed
    then have "x ∈ V"
      using ‹V ∈ A› A(1) by simp
  }
  with ‹x∈U› have "x ∈ U ∩ ⋂A" by auto
  with ‹U ∩ ⋂A = {}› show False by auto
qed

definition "countably_compact U ⟷
    (∀A. countable A ⟶ (∀a∈A. open a) ⟶ U ⊆ ⋃A ⟶ (∃T⊆A. finite T ∧ U ⊆ ⋃T))"

lemma countably_compactE:
  assumes "countably_compact s" and "∀t∈C. open t" and "s ⊆ ⋃C" "countable C"
  obtains C' where "C' ⊆ C" and "finite C'" and "s ⊆ ⋃C'"
  using assms unfolding countably_compact_def by metis

lemma countably_compactI:
  assumes "⋀C. ∀t∈C. open t ⟹ s ⊆ ⋃C ⟹ countable C ⟹ (∃C'⊆C. finite C' ∧ s ⊆ ⋃C')"
  shows "countably_compact s"
  using assms unfolding countably_compact_def by metis

lemma compact_imp_countably_compact: "compact U ⟹ countably_compact U"
  by (auto simp: compact_eq_heine_borel countably_compact_def)

lemma countably_compact_imp_compact:
  assumes "countably_compact U"
    and ccover: "countable B" "∀b∈B. open b"
    and basis: "⋀T x. open T ⟹ x ∈ T ⟹ x ∈ U ⟹ ∃b∈B. x ∈ b ∧ b ∩ U ⊆ T"
  shows "compact U"
  using ‹countably_compact U›
  unfolding compact_eq_heine_borel countably_compact_def
proof safe
  fix A
  assume A: "∀a∈A. open a" "U ⊆ ⋃A"
  assume *: "∀A. countable A ⟶ (∀a∈A. open a) ⟶ U ⊆ ⋃A ⟶ (∃T⊆A. finite T ∧ U ⊆ ⋃T)"
  moreover define C where "C = {b∈B. ∃a∈A. b ∩ U ⊆ a}"
  ultimately have "countable C" "∀a∈C. open a"
    unfolding C_def using ccover by auto
  moreover
  have "⋃A ∩ U ⊆ ⋃C"
  proof safe
    fix x a
    assume "x ∈ U" "x ∈ a" "a ∈ A"
    with basis[of a x] A obtain b where "b ∈ B" "x ∈ b" "b ∩ U ⊆ a"
      by blast
    with ‹a ∈ A› show "x ∈ ⋃C"
      unfolding C_def by auto
  qed
  then have "U ⊆ ⋃C" using ‹U ⊆ ⋃A› by auto
  ultimately obtain T where T: "T⊆C" "finite T" "U ⊆ ⋃T"
    using * by metis
  then have "∀t∈T. ∃a∈A. t ∩ U ⊆ a"
    by (auto simp: C_def)
  then obtain f where "∀t∈T. f t ∈ A ∧ t ∩ U ⊆ f t"
    unfolding bchoice_iff Bex_def ..
  with T show "∃T⊆A. finite T ∧ U ⊆ ⋃T"
    unfolding C_def by (intro exI[of _ "f`T"]) fastforce
qed

lemma countably_compact_imp_compact_second_countable:
  "countably_compact U ⟹ compact (U :: 'a :: second_countable_topology set)"
proof (rule countably_compact_imp_compact)
  fix T and x :: 'a
  assume "open T" "x ∈ T"
  from topological_basisE[OF is_basis this] obtain b where
    "b ∈ (SOME B. countable B ∧ topological_basis B)" "x ∈ b" "b ⊆ T" .
  then show "∃b∈SOME B. countable B ∧ topological_basis B. x ∈ b ∧ b ∩ U ⊆ T"
    by blast
qed (insert countable_basis topological_basis_open[OF is_basis], auto)

lemma countably_compact_eq_compact:
  "countably_compact U ⟷ compact (U :: 'a :: second_countable_topology set)"
  using countably_compact_imp_compact_second_countable compact_imp_countably_compact by blast

subsubsection‹Sequential compactness›

definition seq_compact :: "'a::topological_space set ⇒ bool"
  where "seq_compact S ⟷
    (∀f. (∀n. f n ∈ S) ⟶ (∃l∈S. ∃r::nat⇒nat. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially))"

lemma seq_compactI:
  assumes "⋀f. ∀n. f n ∈ S ⟹ ∃l∈S. ∃r::nat⇒nat. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
  shows "seq_compact S"
  unfolding seq_compact_def using assms by fast

lemma seq_compactE:
  assumes "seq_compact S" "∀n. f n ∈ S"
  obtains l r where "l ∈ S" "strict_mono (r :: nat ⇒ nat)" "((f ∘ r) ⤏ l) sequentially"
  using assms unfolding seq_compact_def by fast

lemma closed_sequentially: (* TODO: move upwards *)
  assumes "closed s" and "∀n. f n ∈ s" and "f ⇢ l"
  shows "l ∈ s"
proof (rule ccontr)
  assume "l ∉ s"
  with ‹closed s› and ‹f ⇢ l› have "eventually (λn. f n ∈ - s) sequentially"
    by (fast intro: topological_tendstoD)
  with ‹∀n. f n ∈ s› show "False"
    by simp
qed

lemma seq_compact_Int_closed:
  assumes "seq_compact s" and "closed t"
  shows "seq_compact (s ∩ t)"
proof (rule seq_compactI)
  fix f assume "∀n::nat. f n ∈ s ∩ t"
  hence "∀n. f n ∈ s" and "∀n. f n ∈ t"
    by simp_all
  from ‹seq_compact s› and ‹∀n. f n ∈ s›
  obtain l r where "l ∈ s" and r: "strict_mono r" and l: "(f ∘ r) ⇢ l"
    by (rule seq_compactE)
  from ‹∀n. f n ∈ t› have "∀n. (f ∘ r) n ∈ t"
    by simp
  from ‹closed t› and this and l have "l ∈ t"
    by (rule closed_sequentially)
  with ‹l ∈ s› and r and l show "∃l∈s ∩ t. ∃r. strict_mono r ∧ (f ∘ r) ⇢ l"
    by fast
qed

lemma seq_compact_closed_subset:
  assumes "closed s" and "s ⊆ t" and "seq_compact t"
  shows "seq_compact s"
  using assms seq_compact_Int_closed [of t s] by (simp add: Int_absorb1)

lemma seq_compact_imp_countably_compact:
  fixes U :: "'a :: first_countable_topology set"
  assumes "seq_compact U"
  shows "countably_compact U"
proof (safe intro!: countably_compactI)
  fix A
  assume A: "∀a∈A. open a" "U ⊆ ⋃A" "countable A"
  have subseq: "⋀X. range X ⊆ U ⟹ ∃r x. x ∈ U ∧ strict_mono (r :: nat ⇒ nat) ∧ (X ∘ r) ⇢ x"
    using ‹seq_compact U› by (fastforce simp: seq_compact_def subset_eq)
  show "∃T⊆A. finite T ∧ U ⊆ ⋃T"
  proof cases
    assume "finite A"
    with A show ?thesis by auto
  next
    assume "infinite A"
    then have "A ≠ {}" by auto
    show ?thesis
    proof (rule ccontr)
      assume "¬ (∃T⊆A. finite T ∧ U ⊆ ⋃T)"
      then have "∀T. ∃x. T ⊆ A ∧ finite T ⟶ (x ∈ U - ⋃T)"
        by auto
      then obtain X' where T: "⋀T. T ⊆ A ⟹ finite T ⟹ X' T ∈ U - ⋃T"
        by metis
      define X where "X n = X' (from_nat_into A ` {.. n})" for n
      have X: "⋀n. X n ∈ U - (⋃i≤n. from_nat_into A i)"
        using ‹A ≠ {}› unfolding X_def by (intro T) (auto intro: from_nat_into)
      then have "range X ⊆ U"
        by auto
      with subseq[of X] obtain r x where "x ∈ U" and r: "strict_mono r" "(X ∘ r) ⇢ x"
        by auto
      from ‹x∈U› ‹U ⊆ ⋃A› from_nat_into_surj[OF ‹countable A›]
      obtain n where "x ∈ from_nat_into A n" by auto
      with r(2) A(1) from_nat_into[OF ‹A ≠ {}›, of n]
      have "eventually (λi. X (r i) ∈ from_nat_into A n) sequentially"
        unfolding tendsto_def by (auto simp: comp_def)
      then obtain N where "⋀i. N ≤ i ⟹ X (r i) ∈ from_nat_into A n"
        by (auto simp: eventually_sequentially)
      moreover from X have "⋀i. n ≤ r i ⟹ X (r i) ∉ from_nat_into A n"
        by auto
      moreover from ‹strict_mono r›[THEN seq_suble, of "max n N"] have "∃i. n ≤ r i ∧ N ≤ i"
        by (auto intro!: exI[of _ "max n N"])
      ultimately show False
        by auto
    qed
  qed
qed

lemma compact_imp_seq_compact:
  fixes U :: "'a :: first_countable_topology set"
  assumes "compact U"
  shows "seq_compact U"
  unfolding seq_compact_def
proof safe
  fix X :: "nat ⇒ 'a"
  assume "∀n. X n ∈ U"
  then have "eventually (λx. x ∈ U) (filtermap X sequentially)"
    by (auto simp: eventually_filtermap)
  moreover
  have "filtermap X sequentially ≠ bot"
    by (simp add: trivial_limit_def eventually_filtermap)
  ultimately
  obtain x where "x ∈ U" and x: "inf (nhds x) (filtermap X sequentially) ≠ bot" (is "?F ≠ _")
    using ‹compact U› by (auto simp: compact_filter)

  from countable_basis_at_decseq[of x]
  obtain A where A:
      "⋀i. open (A i)"
      "⋀i. x ∈ A i"
      "⋀S. open S ⟹ x ∈ S ⟹ eventually (λi. A i ⊆ S) sequentially"
    by blast
  define s where "s n i = (SOME j. i < j ∧ X j ∈ A (Suc n))" for n i
  {
    fix n i
    have "∃a. i < a ∧ X a ∈ A (Suc n)"
    proof (rule ccontr)
      assume "¬ (∃a>i. X a ∈ A (Suc n))"
      then have "⋀a. Suc i ≤ a ⟹ X a ∉ A (Suc n)"
        by auto
      then have "eventually (λx. x ∉ A (Suc n)) (filtermap X sequentially)"
        by (auto simp: eventually_filtermap eventually_sequentially)
      moreover have "eventually (λx. x ∈ A (Suc n)) (nhds x)"
        using A(1,2)[of "Suc n"] by (auto simp: eventually_nhds)
      ultimately have "eventually (λx. False) ?F"
        by (auto simp: eventually_inf)
      with x show False
        by (simp add: eventually_False)
    qed
    then have "i < s n i" "X (s n i) ∈ A (Suc n)"
      unfolding s_def by (auto intro: someI2_ex)
  }
  note s = this
  define r where "r = rec_nat (s 0 0) s"
  have "strict_mono r"
    by (auto simp: r_def s strict_mono_Suc_iff)
  moreover
  have "(λn. X (r n)) ⇢ x"
  proof (rule topological_tendstoI)
    fix S
    assume "open S" "x ∈ S"
    with A(3) have "eventually (λi. A i ⊆ S) sequentially"
      by auto
    moreover
    {
      fix i
      assume "Suc 0 ≤ i"
      then have "X (r i) ∈ A i"
        by (cases i) (simp_all add: r_def s)
    }
    then have "eventually (λi. X (r i) ∈ A i) sequentially"
      by (auto simp: eventually_sequentially)
    ultimately show "eventually (λi. X (r i) ∈ S) sequentially"
      by eventually_elim auto
  qed
  ultimately show "∃x ∈ U. ∃r. strict_mono r ∧ (X ∘ r) ⇢ x"
    using ‹x ∈ U› by (auto simp: convergent_def comp_def)
qed

lemma countably_compact_imp_acc_point:
  assumes "countably_compact s"
    and "countable t"
    and "infinite t"
    and "t ⊆ s"
  shows "∃x∈s. ∀U. x∈U ∧ open U ⟶ infinite (U ∩ t)"
proof (rule ccontr)
  define C where "C = (λF. interior (F ∪ (- t))) ` {F. finite F ∧ F ⊆ t }"
  note ‹countably_compact s›
  moreover have "∀t∈C. open t"
    by (auto simp: C_def)
  moreover
  assume "¬ (∃x∈s. ∀U. x∈U ∧ open U ⟶ infinite (U ∩ t))"
  then have s: "⋀x. x ∈ s ⟹ ∃U. x∈U ∧ open U ∧ finite (U ∩ t)" by metis
  have "s ⊆ ⋃C"
    using ‹t ⊆ s›
    unfolding C_def
    apply (safe dest!: s)
    apply (rule_tac a="U ∩ t" in UN_I)
    apply (auto intro!: interiorI simp add: finite_subset)
    done
  moreover
  from ‹countable t› have "countable C"
    unfolding C_def by (auto intro: countable_Collect_finite_subset)
  ultimately
  obtain D where "D ⊆ C" "finite D" "s ⊆ ⋃D"
    by (rule countably_compactE)
  then obtain E where E: "E ⊆ {F. finite F ∧ F ⊆ t }" "finite E"
    and s: "s ⊆ (⋃F∈E. interior (F ∪ (- t)))"
    by (metis (lifting) finite_subset_image C_def)
  from s ‹t ⊆ s› have "t ⊆ ⋃E"
    using interior_subset by blast
  moreover have "finite (⋃E)"
    using E by auto
  ultimately show False using ‹infinite t›
    by (auto simp: finite_subset)
qed

lemma countable_acc_point_imp_seq_compact:
  fixes s :: "'a::first_countable_topology set"
  assumes "∀t. infinite t ∧ countable t ∧ t ⊆ s ⟶
    (∃x∈s. ∀U. x∈U ∧ open U ⟶ infinite (U ∩ t))"
  shows "seq_compact s"
proof -
  {
    fix f :: "nat ⇒ 'a"
    assume f: "∀n. f n ∈ s"
    have "∃l∈s. ∃r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
    proof (cases "finite (range f)")
      case True
      obtain l where "infinite {n. f n = f l}"
        using pigeonhole_infinite[OF _ True] by auto
      then obtain r :: "nat ⇒ nat" where "strict_mono  r" and fr: "∀n. f (r n) = f l"
        using infinite_enumerate by blast
      then have "strict_mono r ∧ (f ∘ r) ⇢ f l"
        by (simp add: fr o_def)
      with f show "∃l∈s. ∃r. strict_mono  r ∧ (f ∘ r) ⇢ l"
        by auto
    next
      case False
      with f assms have "∃x∈s. ∀U. x∈U ∧ open U ⟶ infinite (U ∩ range f)"
        by auto
      then obtain l where "l ∈ s" "∀U. l∈U ∧ open U ⟶ infinite (U ∩ range f)" ..
      from this(2) have "∃r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
        using acc_point_range_imp_convergent_subsequence[of l f] by auto
      with ‹l ∈ s› show "∃l∈s. ∃r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially" ..
    qed
  }
  then show ?thesis
    unfolding seq_compact_def by auto
qed

lemma seq_compact_eq_countably_compact:
  fixes U :: "'a :: first_countable_topology set"
  shows "seq_compact U ⟷ countably_compact U"
  using
    countable_acc_point_imp_seq_compact
    countably_compact_imp_acc_point
    seq_compact_imp_countably_compact
  by metis

lemma seq_compact_eq_acc_point:
  fixes s :: "'a :: first_countable_topology set"
  shows "seq_compact s ⟷
    (∀t. infinite t ∧ countable t ∧ t ⊆ s --> (∃x∈s. ∀U. x∈U ∧ open U ⟶ infinite (U ∩ t)))"
  using
    countable_acc_point_imp_seq_compact[of s]
    countably_compact_imp_acc_point[of s]
    seq_compact_imp_countably_compact[of s]
  by metis

lemma seq_compact_eq_compact:
  fixes U :: "'a :: second_countable_topology set"
  shows "seq_compact U ⟷ compact U"
  using seq_compact_eq_countably_compact countably_compact_eq_compact by blast

lemma bolzano_weierstrass_imp_seq_compact:
  fixes s :: "'a::{t1_space, first_countable_topology} set"
  shows "∀t. infinite t ∧ t ⊆ s ⟶ (∃x ∈ s. x islimpt t) ⟹ seq_compact s"
  by (rule countable_acc_point_imp_seq_compact) (metis islimpt_eq_acc_point)


subsubsection‹Totally bounded›

lemma cauchy_def: "Cauchy s ⟷ (∀e>0. ∃N. ∀m n. m ≥ N ∧ n ≥ N ⟶ dist (s m) (s n) < e)"
  unfolding Cauchy_def by metis

lemma seq_compact_imp_totally_bounded:
  assumes "seq_compact s"
  shows "∀e>0. ∃k. finite k ∧ k ⊆ s ∧ s ⊆ (⋃x∈k. ball x e)"
proof -
  { fix e::real assume "e > 0" assume *: "⋀k. finite k ⟹ k ⊆ s ⟹ ¬ s ⊆ (⋃x∈k. ball x e)"
    let ?Q = "λx n r. r ∈ s ∧ (∀m < (n::nat). ¬ (dist (x m) r < e))"
    have "∃x. ∀n::nat. ?Q x n (x n)"
    proof (rule dependent_wellorder_choice)
      fix n x assume "⋀y. y < n ⟹ ?Q x y (x y)"
      then have "¬ s ⊆ (⋃x∈x ` {0..<n}. ball x e)"
        using *[of "x ` {0 ..< n}"] by (auto simp: subset_eq)
      then obtain z where z:"z∈s" "z ∉ (⋃x∈x ` {0..<n}. ball x e)"
        unfolding subset_eq by auto
      show "∃r. ?Q x n r"
        using z by auto
    qed simp
    then obtain x where "∀n::nat. x n ∈ s" and x:"⋀n m. m < n ⟹ ¬ (dist (x m) (x n) < e)"
      by blast
    then obtain l r where "l ∈ s" and r:"strict_mono  r" and "((x ∘ r) ⤏ l) sequentially"
      using assms by (metis seq_compact_def)
    from this(3) have "Cauchy (x ∘ r)"
      using LIMSEQ_imp_Cauchy by auto
    then obtain N::nat where "⋀m n. N ≤ m ⟹ N ≤ n ⟹ dist ((x ∘ r) m) ((x ∘ r) n) < e"
      unfolding cauchy_def using ‹e > 0› by blast
    then have False
      using x[of "r N" "r (N+1)"] r by (auto simp: strict_mono_def) }
  then show ?thesis
    by metis
qed

subsubsection‹Heine-Borel theorem›

lemma seq_compact_imp_heine_borel:
  fixes s :: "'a :: metric_space set"
  assumes "seq_compact s"
  shows "compact s"
proof -
  from seq_compact_imp_totally_bounded[OF ‹seq_compact s›]
  obtain f where f: "∀e>0. finite (f e) ∧ f e ⊆ s ∧ s ⊆ (⋃x∈f e. ball x e)"
    unfolding choice_iff' ..
  define K where "K = (λ(x, r). ball x r) ` ((⋃e ∈ ℚ ∩ {0 <..}. f e) × ℚ)"
  have "countably_compact s"
    using ‹seq_compact s› by (rule seq_compact_imp_countably_compact)
  then show "compact s"
  proof (rule countably_compact_imp_compact)
    show "countable K"
      unfolding K_def using f
      by (auto intro: countable_finite countable_subset countable_rat
               intro!: countable_image countable_SIGMA countable_UN)
    show "∀b∈K. open b" by (auto simp: K_def)
  next
    fix T x
    assume T: "open T" "x ∈ T" and x: "x ∈ s"
    from openE[OF T] obtain e where "0 < e" "ball x e ⊆ T"
      by auto
    then have "0 < e / 2" "ball x (e / 2) ⊆ T"
      by auto
    from Rats_dense_in_real[OF ‹0 < e / 2›] obtain r where "r ∈ ℚ" "0 < r" "r < e / 2"
      by auto
    from f[rule_format, of r] ‹0 < r› ‹x ∈ s› obtain k where "k ∈ f r" "x ∈ ball k r"
      by auto
    from ‹r ∈ ℚ› ‹0 < r› ‹k ∈ f r› have "ball k r ∈ K"
      by (auto simp: K_def)
    then show "∃b∈K. x ∈ b ∧ b ∩ s ⊆ T"
    proof (rule bexI[rotated], safe)
      fix y
      assume "y ∈ ball k r"
      with ‹r < e / 2› ‹x ∈ ball k r› have "dist x y < e"
        by (intro dist_triangle_half_r [of k _ e]) (auto simp: dist_commute)
      with ‹ball x e ⊆ T› show "y ∈ T"
        by auto
    next
      show "x ∈ ball k r" by fact
    qed
  qed
qed

lemma compact_eq_seq_compact_metric:
  "compact (s :: 'a::metric_space set) ⟷ seq_compact s"
  using compact_imp_seq_compact seq_compact_imp_heine_borel by blast

lemma compact_def: ‹this is the definition of compactness in HOL Light›
  "compact (S :: 'a::metric_space set) ⟷
   (∀f. (∀n. f n ∈ S) ⟶ (∃l∈S. ∃r::nat⇒nat. strict_mono r ∧ (f ∘ r) ⇢ l))"
  unfolding compact_eq_seq_compact_metric seq_compact_def by auto

subsubsection ‹Complete the chain of compactness variants›

lemma compact_eq_bolzano_weierstrass:
  fixes s :: "'a::metric_space set"
  shows "compact s ⟷ (∀t. infinite t ∧ t ⊆ s --> (∃x ∈ s. x islimpt t))"
  (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    using heine_borel_imp_bolzano_weierstrass[of s] by auto
next
  assume ?rhs
  then show ?lhs
    unfolding compact_eq_seq_compact_metric by (rule bolzano_weierstrass_imp_seq_compact)
qed

lemma bolzano_weierstrass_imp_bounded:
  "∀t. infinite t ∧ t ⊆ s ⟶ (∃x ∈ s. x islimpt t) ⟹ bounded s"
  using compact_imp_bounded unfolding compact_eq_bolzano_weierstrass .


subsection ‹Metric spaces with the Heine-Borel property›

text ‹
  A metric space (or topological vector space) is said to have the
  Heine-Borel property if every closed and bounded subset is compact.
›

class heine_borel = metric_space +
  assumes bounded_imp_convergent_subsequence:
    "bounded (range f) ⟹ ∃l r. strict_mono (r::nat⇒nat) ∧ ((f ∘ r) ⤏ l) sequentially"

lemma bounded_closed_imp_seq_compact:
  fixes s::"'a::heine_borel set"
  assumes "bounded s"
    and "closed s"
  shows "seq_compact s"
proof (unfold seq_compact_def, clarify)
  fix f :: "nat ⇒ 'a"
  assume f: "∀n. f n ∈ s"
  with ‹bounded s› have "bounded (range f)"
    by (auto intro: bounded_subset)
  obtain l r where r: "strict_mono (r :: nat ⇒ nat)" and l: "((f ∘ r) ⤏ l) sequentially"
    using bounded_imp_convergent_subsequence [OF ‹bounded (range f)›] by auto
  from f have fr: "∀n. (f ∘ r) n ∈ s"
    by simp
  have "l ∈ s" using ‹closed s› fr l
    by (rule closed_sequentially)
  show "∃l∈s. ∃r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
    using ‹l ∈ s› r l by blast
qed

lemma compact_eq_bounded_closed:
  fixes s :: "'a::heine_borel set"
  shows "compact s ⟷ bounded s ∧ closed s"
  (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    using compact_imp_closed compact_imp_bounded
    by blast
next
  assume ?rhs
  then show ?lhs
    using bounded_closed_imp_seq_compact[of s]
    unfolding compact_eq_seq_compact_metric
    by auto
qed

lemma compact_closure [simp]:
  fixes S :: "'a::heine_borel set"
  shows "compact(closure S) ⟷ bounded S"
by (meson bounded_closure bounded_subset closed_closure closure_subset compact_eq_bounded_closed)

lemma compact_components:
  fixes s :: "'a::heine_borel set"
  shows "⟦compact s; c ∈ components s⟧ ⟹ compact c"
by (meson bounded_subset closed_components in_components_subset compact_eq_bounded_closed)

lemma not_compact_UNIV[simp]:
  fixes s :: "'a::{real_normed_vector,perfect_space,heine_borel} set"
  shows "~ compact (UNIV::'a set)"
    by (simp add: compact_eq_bounded_closed)

instance real :: heine_borel
proof
  fix f :: "nat ⇒ real"
  assume f: "bounded (range f)"
  obtain r :: "nat ⇒ nat" where r: "strict_mono r" "monoseq (f ∘ r)"
    unfolding comp_def by (metis seq_monosub)
  then have "Bseq (f ∘ r)"
    unfolding Bseq_eq_bounded using f by (force intro: bounded_subset)
  with r show "∃l r. strict_mono r ∧ (f ∘ r) ⇢ l"
    using Bseq_monoseq_convergent[of "f ∘ r"] by (auto simp: convergent_def)
qed

lemma compact_lemma_general:
  fixes f :: "nat ⇒ 'a"
  fixes proj::"'a ⇒ 'b ⇒ 'c::heine_borel" (infixl "proj" 60)
  fixes unproj:: "('b ⇒ 'c) ⇒ 'a"
  assumes finite_basis: "finite basis"
  assumes bounded_proj: "⋀k. k ∈ basis ⟹ bounded ((λx. x proj k) ` range f)"
  assumes proj_unproj: "⋀e k. k ∈ basis ⟹ (unproj e) proj k = e k"
  assumes unproj_proj: "⋀x. unproj (λk. x proj k) = x"
  shows "∀d⊆basis. ∃l::'a. ∃ r::nat⇒nat.
    strict_mono r ∧ (∀e>0. eventually (λn. ∀i∈d. dist (f (r n) proj i) (l proj i) < e) sequentially)"
proof safe
  fix d :: "'b set"
  assume d: "d ⊆ basis"
  with finite_basis have "finite d"
    by (blast intro: finite_subset)
  from this d show "∃l::'a. ∃r::nat⇒nat. strict_mono r ∧
    (∀e>0. eventually (λn. ∀i∈d. dist (f (r n) proj i) (l proj i) < e) sequentially)"
  proof (induct d)
    case empty
    then show ?case
      unfolding strict_mono_def by auto
  next
    case (insert k d)
    have k[intro]: "k ∈ basis"
      using insert by auto
    have s': "bounded ((λx. x proj k) ` range f)"
      using k
      by (rule bounded_proj)
    obtain l1::"'a" and r1 where r1: "strict_mono r1"
      and lr1: "∀e > 0. eventually (λn. ∀i∈d. dist (f (r1 n) proj i) (l1 proj i) < e) sequentially"
      using insert(3) using insert(4) by auto
    have f': "∀n. f (r1 n) proj k ∈ (λx. x proj k) ` range f"
      by simp
    have "bounded (range (λi. f (r1 i) proj k))"
      by (metis (lifting) bounded_subset f' image_subsetI s')
    then obtain l2 r2 where r2:"strict_mono r2" and lr2:"((λi. f (r1 (r2 i)) proj k) ⤏ l2) sequentially"
      using bounded_imp_convergent_subsequence[of "λi. f (r1 i) proj k"]
      by (auto simp: o_def)
    define r where "r = r1 ∘ r2"
    have r:"strict_mono r"
      using r1 and r2 unfolding r_def o_def strict_mono_def by auto
    moreover
    define l where "l = unproj (λi. if i = k then l2 else l1 proj i)"
    {
      fix e::real
      assume "e > 0"
      from lr1 ‹e > 0› have N1: "eventually (λn. ∀i∈d. dist (f (r1 n) proj i) (l1 proj i) < e) sequentially"
        by blast
      from lr2 ‹e > 0› have N2:"eventually (λn. dist (f (r1 (r2 n)) proj k) l2 < e) sequentially"
        by (rule tendstoD)
      from r2 N1 have N1': "eventually (λn. ∀i∈d. dist (f (r1 (r2 n)) proj i) (l1 proj i) < e) sequentially"
        by (rule eventually_subseq)
      have "eventually (λn. ∀i∈(insert k d). dist (f (r n) proj i) (l proj i) < e) sequentially"
        using N1' N2
        by eventually_elim (insert insert.prems, auto simp: l_def r_def o_def proj_unproj)
    }
    ultimately show ?case by auto
  qed
qed

lemma compact_lemma:
  fixes f :: "nat ⇒ 'a::euclidean_space"
  assumes "bounded (range f)"
  shows "∀d⊆Basis. ∃l::'a. ∃ r.
    strict_mono r ∧ (∀e>0. eventually (λn. ∀i∈d. dist (f (r n) ∙ i) (l ∙ i) < e) sequentially)"
  by (rule compact_lemma_general[where unproj="λe. ∑i∈Basis. e i *R i"])
     (auto intro!: assms bounded_linear_inner_left bounded_linear_image
       simp: euclidean_representation)

instance euclidean_space  heine_borel
proof
  fix f :: "nat ⇒ 'a"
  assume f: "bounded (range f)"
  then obtain l::'a and r where r: "strict_mono r"
    and l: "∀e>0. eventually (λn. ∀i∈Basis. dist (f (r n) ∙ i) (l ∙ i) < e) sequentially"
    using compact_lemma [OF f] by blast
  {
    fix e::real
    assume "e > 0"
    hence "e / real_of_nat DIM('a) > 0" by (simp add: DIM_positive)
    with l have "eventually (λn. ∀i∈Basis. dist (f (r n) ∙ i) (l ∙ i) < e / (real_of_nat DIM('a))) sequentially"
      by simp
    moreover
    {
      fix n
      assume n: "∀i∈Basis. dist (f (r n) ∙ i) (l ∙ i) < e / (real_of_nat DIM('a))"
      have "dist (f (r n)) l ≤ (∑i∈Basis. dist (f (r n) ∙ i) (l ∙ i))"
        apply (subst euclidean_dist_l2)
        using zero_le_dist
        apply (rule setL2_le_sum)
        done
      also have "… < (∑i∈(Basis::'a set). e / (real_of_nat DIM('a)))"
        apply (rule sum_strict_mono)
        using n
        apply auto
        done
      finally have "dist (f (r n)) l < e"
        by auto
    }
    ultimately have "eventually (λn. dist (f (r n)) l < e) sequentially"
      by (rule eventually_mono)
  }
  then have *: "((f ∘ r) ⤏ l) sequentially"
    unfolding o_def tendsto_iff by simp
  with r show "∃l r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
    by auto
qed

lemma bounded_fst: "bounded s ⟹ bounded (fst ` s)"
  unfolding bounded_def
  by (metis (erased, hide_lams) dist_fst_le image_iff order_trans)

lemma bounded_snd: "bounded s ⟹ bounded (snd ` s)"
  unfolding bounded_def
  by (metis (no_types, hide_lams) dist_snd_le image_iff order.trans)

instance prod :: (heine_borel, heine_borel) heine_borel
proof
  fix f :: "nat ⇒ 'a × 'b"
  assume f: "bounded (range f)"
  then have "bounded (fst ` range f)"
    by (rule bounded_fst)
  then have s1: "bounded (range (fst ∘ f))"
    by (simp add: image_comp)
  obtain l1 r1 where r1: "strict_mono r1" and l1: "(λn. fst (f (r1 n))) ⇢ l1"
    using bounded_imp_convergent_subsequence [OF s1] unfolding o_def by fast
  from f have s2: "bounded (range (snd ∘ f ∘ r1))"
    by (auto simp: image_comp intro: bounded_snd bounded_subset)
  obtain l2 r2 where r2: "strict_mono r2" and l2: "((λn. snd (f (r1 (r2 n)))) ⤏ l2) sequentially"
    using bounded_imp_convergent_subsequence [OF s2]
    unfolding o_def by fast
  have l1': "((λn. fst (f (r1 (r2 n)))) ⤏ l1) sequentially"
    using LIMSEQ_subseq_LIMSEQ [OF l1 r2] unfolding o_def .
  have l: "((f ∘ (r1 ∘ r2)) ⤏ (l1, l2)) sequentially"
    using tendsto_Pair [OF l1' l2] unfolding o_def by simp
  have r: "strict_mono (r1 ∘ r2)"
    using r1 r2 unfolding strict_mono_def by simp
  show "∃l r. strict_mono r ∧ ((f ∘ r) ⤏ l) sequentially"
    using l r by fast
qed

subsubsection ‹Intersecting chains of compact sets›

proposition bounded_closed_chain:
  fixes  :: "'a::heine_borel set set"
  assumes "B ∈ ℱ" "bounded B" and : "⋀S. S ∈ ℱ ⟹ closed S" and "{} ∉ ℱ"
      and chain: "⋀S T. S ∈ ℱ ∧ T ∈ ℱ ⟹ S ⊆ T ∨ T ⊆ S"
    shows "⋂ℱ ≠ {}"
proof -
  have "B ∩ ⋂ℱ ≠ {}"
  proof (rule compact_imp_fip)
    show "compact B" "⋀T. T ∈ ℱ ⟹ closed T"
      by (simp_all add: assms compact_eq_bounded_closed)
    show "⟦finite 𝒢; 𝒢 ⊆ ℱ⟧ ⟹ B ∩ ⋂𝒢 ≠ {}" for 𝒢
    proof (induction 𝒢 rule: finite_induct)
      case empty
      with assms show ?case by force
    next
      case (insert U 𝒢)
      then have "U ∈ ℱ" and ne: "B ∩ ⋂𝒢 ≠ {}" by auto
      then consider "B ⊆ U" | "U ⊆ B"
          using ‹B ∈ ℱ› chain by blast
        then show ?case
        proof cases
          case 1
          then show ?thesis
            using Int_left_commute ne by auto
        next
          case 2
          have "U ≠ {}"
            using ‹U ∈ ℱ› ‹{} ∉ ℱ› by blast
          moreover
          have False if "⋀x. x ∈ U ⟹ ∃Y∈𝒢. x ∉ Y"
          proof -
            have "⋀x. x ∈ U ⟹ ∃Y∈𝒢. Y ⊆ U"
              by (metis chain contra_subsetD insert.prems insert_subset that)
            then obtain Y where "Y ∈ 𝒢" "Y ⊆ U"
              by (metis all_not_in_conv ‹U ≠ {}›)
            moreover obtain x where "x ∈ ⋂𝒢"
              by (metis Int_emptyI ne)
            ultimately show ?thesis
              by (metis Inf_lower subset_eq that)
          qed
          with 2 show ?thesis
            by blast
        qed
      qed
  qed
  then show ?thesis by blast
qed

corollary compact_chain:
  fixes  :: "'a::heine_borel set set"
  assumes "⋀S. S ∈ ℱ ⟹ compact S" "{} ∉ ℱ"
          "⋀S T. S ∈ ℱ ∧ T ∈ ℱ ⟹ S ⊆ T ∨ T ⊆ S"
    shows "⋂ ℱ ≠ {}"
proof (cases "ℱ = {}")
  case True
  then show ?thesis by auto
next
  case False
  show ?thesis
    by (metis False all_not_in_conv assms compact_imp_bounded compact_imp_closed bounded_closed_chain)
qed

lemma compact_nest:
  fixes F :: "'a::linorder ⇒ 'b::heine_borel set"
  assumes F: "⋀n. compact(F n)" "⋀n. F n ≠ {}" and mono: "⋀m n. m ≤ n ⟹ F n ⊆ F m"
  shows "⋂range F ≠ {}"
proof -
  have *: "⋀S T. S ∈ range F ∧ T ∈ range F ⟹ S ⊆ T ∨ T ⊆ S"
    by (metis mono image_iff le_cases)
  show ?thesis
    apply (rule compact_chain [OF _ _ *])
    using F apply (blast intro: dest: *)+
    done
qed

text‹The Baire property of dense sets›
theorem Baire:
  fixes S::"'a::{real_normed_vector,heine_borel} set"
  assumes "closed S" "countable 𝒢"
      and ope: "⋀T. T ∈ 𝒢 ⟹ openin (subtopology euclidean S) T ∧ S ⊆ closure T"
 shows "S ⊆ closure(⋂𝒢)"
proof (cases "𝒢 = {}")
  case True
  then show ?thesis
    using closure_subset by auto
next
  let ?g = "from_nat_into 𝒢"
  case False
  then have gin: "?g n ∈ 𝒢" for n
    by (simp add: from_nat_into)
  show ?thesis
  proof (clarsimp simp: closure_approachable)
    fix x and e::real
    assume "x ∈ S" "0 < e"
    obtain TF where opeF: "⋀n. openin (subtopology euclidean S) (TF n)"
               and ne: "⋀n. TF n ≠ {}"
               and subg: "⋀n. S ∩ closure(TF n) ⊆ ?g n"
               and subball: "⋀n. closure(TF n) ⊆ ball x e"
               and decr: "⋀n. TF(Suc n) ⊆ TF n"
    proof -
      have *: "∃Y. (openin (subtopology euclidean S) Y ∧ Y ≠ {} ∧
                   S ∩ closure Y ⊆ ?g n ∧ closure Y ⊆ ball x e) ∧ Y ⊆ U"
        if opeU: "openin (subtopology euclidean S) U" and "U ≠ {}" and cloU: "closure U ⊆ ball x e" for U n
      proof -
        obtain T where T: "open T" "U = T ∩ S"
          using ‹openin (subtopology euclidean S) U› by (auto simp: openin_subtopology)
        with ‹U ≠ {}› have "T ∩ closure (?g n) ≠ {}"
          using gin ope by fastforce
        then have "T ∩ ?g n ≠ {}"
          using ‹open T› open_Int_closure_eq_empty by blast
        then obtain y where "y ∈ U" "y ∈ ?g n"
          using T ope [of "?g n", OF gin] by (blast dest:  openin_imp_subset)
        moreover have "openin (subtopology euclidean S) (U ∩ ?g n)"
          using gin ope opeU by blast
        ultimately obtain d where U: "U ∩ ?g n ⊆ S" and "d > 0" and d: "ball y d ∩ S ⊆ U ∩ ?g n"
          by (force simp: openin_contains_ball)
        show ?thesis
        proof (intro exI conjI)
          show "openin (subtopology euclidean S) (S ∩ ball y (d/2))"
            by (simp add: openin_open_Int)
          show "S ∩ ball y (d/2) ≠ {}"
            using ‹0 < d› ‹y ∈ U› opeU openin_imp_subset by fastforce
          have "S ∩ closure (S ∩ ball y (d/2)) ⊆ S ∩ closure (ball y (d/2))"
            using closure_mono by blast
          also have "... ⊆ ?g n"
            using ‹d > 0› d by force
          finally show "S ∩ closure (S ∩ ball y (d/2)) ⊆ ?g n" .
          have "closure (S ∩ ball y (d/2)) ⊆ S ∩ ball y d"
          proof -
            have "closure (ball y (d/2)) ⊆ ball y d"
              using ‹d > 0› by auto
            then have "closure (S ∩ ball y (d/2)) ⊆ ball y d"
              by (meson closure_mono inf.cobounded2 subset_trans)
            then show ?thesis
              by (simp add: ‹closed S› closure_minimal)
          qed
          also have "...  ⊆ ball x e"
            using cloU closure_subset d by blast
          finally show "closure (S ∩ ball y (d/2)) ⊆ ball x e" .
          show "S ∩ ball y (d/2) ⊆ U"
            using ball_divide_subset_numeral d by blast
        qed
      qed
      let  = "λn X. openin (subtopology euclidean S) X ∧ X ≠ {} ∧
                      S ∩ closure X ⊆ ?g n ∧ closure X ⊆ ball x e"
      have "closure (S ∩ ball x (e / 2)) ⊆ closure(ball x (e/2))"
        by (simp add: closure_mono)
      also have "...  ⊆ ball x e"
        using ‹e > 0› by auto
      finally have "closure (S ∩ ball x (e / 2)) ⊆ ball x e" .
      moreover have"openin (subtopology euclidean S) (S ∩ ball x (e / 2))" "S ∩ ball x (e / 2) ≠ {}"
        using ‹0 < e› ‹x ∈ S› by auto
      ultimately obtain Y where Y: "?Φ 0 Y ∧ Y ⊆ S ∩ ball x (e / 2)"
            using * [of "S ∩ ball x (e/2)" 0] by metis
      show thesis
      proof (rule exE [OF dependent_nat_choice [of  "λn X Y. Y ⊆ X"]])
        show "∃x. ?Φ 0 x"
          using Y by auto
        show "∃Y. ?Φ (Suc n) Y ∧ Y ⊆ X" if "?Φ n X" for X n
          using that by (blast intro: *)
      qed (use that in metis)
    qed
    have "(⋂n. S ∩ closure (TF n)) ≠ {}"
    proof (rule compact_nest)
      show "⋀n. compact (S ∩ closure (TF n))"
        by (metis closed_closure subball bounded_subset_ballI compact_eq_bounded_closed closed_Int_compact [OF ‹closed S›])
      show "⋀n. S ∩ closure (TF n) ≠ {}"
        by (metis Int_absorb1 opeF ‹closed S› closure_eq_empty closure_minimal ne openin_imp_subset)
      show "⋀m n. m ≤ n ⟹ S ∩ closure (TF n) ⊆ S ∩ closure (TF m)"
        by (meson closure_mono decr dual_order.refl inf_mono lift_Suc_antimono_le)
    qed
    moreover have "(⋂n. S ∩ closure (TF n)) ⊆ {y ∈ ⋂𝒢. dist y x < e}"
    proof (clarsimp, intro conjI)
      fix y
      assume "y ∈ S" and y: "∀n. y ∈ closure (TF n)"
      then show "∀T∈𝒢. y ∈ T"
        by (metis Int_iff from_nat_into_surj [OF ‹countable 𝒢›] set_mp subg)
      show "dist y x < e"
        by (metis y dist_commute mem_ball subball subsetCE)
    qed
    ultimately show "∃y ∈ ⋂𝒢. dist y x < e"
      by auto
  qed
qed

subsubsection ‹Completeness›

lemma (in metric_space) completeI:
  assumes "⋀f. ∀n. f n ∈ s ⟹ Cauchy f ⟹ ∃l∈s. f ⇢ l"
  shows "complete s"
  using assms unfolding complete_def by fast

lemma (in metric_space) completeE:
  assumes "complete s" and "∀n. f n ∈ s" and "Cauchy f"
  obtains l where "l ∈ s" and "f ⇢ l"
  using assms unfolding complete_def by fast

(* TODO: generalize to uniform spaces *)
lemma compact_imp_complete:
  fixes s :: "'a::metric_space set"
  assumes "compact s"
  shows "complete s"
proof -
  {
    fix f
    assume as: "(∀n::nat. f n ∈ s)" "Cauchy f"
    from as(1) obtain l r where lr: "l∈s" "strict_mono r" "(f ∘ r) ⇢ l"
      using assms unfolding compact_def by blast

    note lr' = seq_suble [OF lr(2)]
    {
      fix e :: real
      assume "e > 0"
      from as(2) obtain N where N:"∀m n. N ≤ m ∧ N ≤ n ⟶ dist (f m) (f n) < e/2"
        unfolding cauchy_def
        using ‹e > 0›
        apply (erule_tac x="e/2" in allE, auto)
        done
      from lr(3)[unfolded lim_sequentially, THEN spec[where x="e/2"]]
      obtain M where M:"∀n≥M. dist ((f ∘ r) n) l < e/2"
        using ‹e > 0› by auto
      {
        fix n :: nat
        assume n: "n ≥ max N M"
        have "dist ((f ∘ r) n) l < e/2"
          using n M by auto
        moreover have "r n ≥ N"
          using lr'[of n] n by auto
        then have "dist (f n) ((f ∘ r) n) < e / 2"
          using N and n by auto
        ultimately have "dist (f n) l < e"
          using dist_triangle_half_r[of "f (r n)" "f n" e l]
          by (auto simp: dist_commute)
      }
      then have "∃N. ∀n≥N. dist (f n) l < e" by blast
    }
    then have "∃l∈s. (f ⤏ l) sequentially" using ‹l∈s›
      unfolding lim_sequentially by auto
  }
  then show ?thesis unfolding complete_def by auto
qed

lemma nat_approx_posE:
  fixes e::real
  assumes "0 < e"
  obtains n :: nat where "1 / (Suc n) < e"
proof atomize_elim
  have "1 / real (Suc (nat ⌈1/e⌉)) < 1 / ⌈1/e⌉"
    by (rule divide_strict_left_mono) (auto simp: ‹0 < e›)
  also have "1 / ⌈1/e⌉ ≤ 1 / (1/e)"
    by (rule divide_left_mono) (auto simp: ‹0 < e› ceiling_correct)
  also have "… = e" by simp
  finally show  "∃n. 1 / real (Suc n) < e" ..
qed

lemma compact_eq_totally_bounded:
  "compact s ⟷ complete s ∧ (∀e>0. ∃k. finite k ∧ s ⊆ (⋃x∈k. ball x e))"
    (is "_ ⟷ ?rhs")
proof
  assume assms: "?rhs"
  then obtain k where k: "⋀e. 0 < e ⟹ finite (k e)" "⋀e. 0 < e ⟹ s ⊆ (⋃x∈k e. ball x e)"
    by (auto simp: choice_iff')

  show "compact s"
  proof cases
    assume "s = {}"
    then show "compact s" by (simp add: compact_def)
  next
    assume "s ≠ {}"
    show ?thesis
      unfolding compact_def
    proof safe
      fix f :: "nat ⇒ 'a"
      assume f: "∀n. f n ∈ s"

      define e where "e n = 1 / (2 * Suc n)" for n
      then have [simp]: "⋀n. 0 < e n" by auto
      define B where "B n U = (SOME b. infinite {n. f n ∈ b} ∧ (∃x. b ⊆ ball x (e n) ∩ U))" for n U
      {
        fix n U
        assume "infinite {n. f n ∈ U}"
        then have "∃b∈k (e n). infinite {i∈{n. f n ∈ U}. f i ∈ ball b (e n)}"
          using k f by (intro pigeonhole_infinite_rel) (auto simp: subset_eq)
        then obtain a where
          "a ∈ k (e n)"
          "infinite {i ∈ {n. f n ∈ U}. f i ∈ ball a (e n)}" ..
        then have "∃b. infinite {i. f i ∈ b} ∧ (∃x. b ⊆ ball x (e n) ∩ U)"
          by (intro exI[of _ "ball a (e n) ∩ U"] exI[of _ a]) (auto simp: ac_simps)
        from someI_ex[OF this]
        have "infinite {i. f i ∈ B n U}" "∃x. B n U ⊆ ball x (e n) ∩ U"
          unfolding B_def by auto
      }
      note B = this

      define F where "F = rec_nat (B 0 UNIV) B"
      {
        fix n
        have "infinite {i. f i ∈ F n}"
          by (induct n) (auto simp: F_def B)
      }
      then have F: "⋀n. ∃x. F (Suc n) ⊆ ball x (e n) ∩ F n"
        using B by (simp add: F_def)
      then have F_dec: "⋀m n. m ≤ n ⟹ F n ⊆ F m"
        using decseq_SucI[of F] by (auto simp: decseq_def)

      obtain sel where sel: "⋀k i. i < sel k i" "⋀k i. f (sel k i) ∈ F k"
      proof (atomize_elim, unfold all_conj_distrib[symmetric], intro choice allI)
        fix k i
        have "infinite ({n. f n ∈ F k} - {.. i})"
          using ‹infinite {n. f n ∈ F k}› by auto
        from infinite_imp_nonempty[OF this]
        show "∃x>i. f x ∈ F k"
          by (simp add: set_eq_iff not_le conj_commute)
      qed

      define t where "t = rec_nat (sel 0 0) (λn i. sel (Suc n) i)"
      have "strict_mono t"
        unfolding strict_mono_Suc_iff by (simp add: t_def sel)
      moreover have "∀i. (f ∘ t) i ∈ s"
        using f by auto
      moreover
      {
        fix n
        have "(f ∘ t) n ∈ F n"
          by (cases n) (simp_all add: t_def sel)
      }
      note t = this

      have "Cauchy (f ∘ t)"
      proof (safe intro!: metric_CauchyI exI elim!: nat_approx_posE)
        fix r :: real and N n m
        assume "1 / Suc N < r" "Suc N ≤ n" "Suc N ≤ m"
        then have "(f ∘ t) n ∈ F (Suc N)" "(f ∘ t) m ∈ F (Suc N)" "2 * e N < r"
          using F_dec t by (auto simp: e_def field_simps of_nat_Suc)
        with F[of N] obtain x where "dist x ((f ∘ t) n) < e N" "dist x ((f ∘ t) m) < e N"
          by (auto simp: subset_eq)
        with dist_triangle[of "(f ∘ t) m" "(f ∘ t) n" x] ‹2 * e N < r›
        show "dist ((f ∘ t) m) ((f ∘ t) n) < r"
          by (simp add: dist_commute)
      qed

      ultimately show "∃l∈s. ∃r. strict_mono r ∧ (f ∘ r) ⇢ l"
        using assms unfolding complete_def by blast
    qed
  qed
qed (metis compact_imp_complete compact_imp_seq_compact seq_compact_imp_totally_bounded)

lemma cauchy_imp_bounded:
  assumes "Cauchy s"
  shows "bounded (range s)"
proof -
  from assms obtain N :: nat where "∀m n. N ≤ m ∧ N ≤ n ⟶ dist (s m) (s n) < 1"
    unfolding cauchy_def by force
  then have N:"∀n. N ≤ n ⟶ dist (s N) (s n) < 1" by auto
  moreover
  have "bounded (s ` {0..N})"
    using finite_imp_bounded[of "s ` {1..N}"] by auto
  then obtain a where a:"∀x∈s ` {0..N}. dist (s N) x ≤ a"
    unfolding bounded_any_center [where a="s N"] by auto
  ultimately show "?thesis"
    unfolding bounded_any_center [where a="s N"]
    apply (rule_tac x="max a 1" in exI, auto)
    apply (erule_tac x=y in allE)
    apply (erule_tac x=y in ballE, auto)
    done
qed

instance heine_borel < complete_space
proof
  fix f :: "nat ⇒ 'a" assume "Cauchy f"
  then have "bounded (range f)"
    by (rule cauchy_imp_bounded)
  then have "compact (closure (range f))"
    unfolding compact_eq_bounded_closed by auto
  then have "complete (closure (range f))"
    by (rule compact_imp_complete)
  moreover have "∀n. f n ∈ closure (range f)"
    using closure_subset [of "range f"] by auto
  ultimately have "∃l∈closure (range f). (f ⤏ l) sequentially"
    using ‹Cauchy f› unfolding complete_def by auto
  then show "convergent f"
    unfolding convergent_def by auto
qed

instance euclidean_space  banach ..

lemma complete_UNIV: "complete (UNIV :: ('a::complete_space) set)"
proof (rule completeI)
  fix f :: "nat ⇒ 'a" assume "Cauchy f"
  then have "convergent f" by (rule Cauchy_convergent)
  then show "∃l∈UNIV. f ⇢ l" unfolding convergent_def by simp
qed

lemma complete_imp_closed:
  fixes S :: "'a::metric_space set"
  assumes "complete S"
  shows "closed S"
proof (unfold closed_sequential_limits, clarify)
  fix f x assume "∀n. f n ∈ S" and "f ⇢ x"
  from ‹f ⇢ x› have "Cauchy f"
    by (rule LIMSEQ_imp_Cauchy)
  with ‹complete S› and ‹∀n. f n ∈ S› obtain l where "l ∈ S" and "f ⇢ l"
    by (rule completeE)
  from ‹f ⇢ x› and ‹f ⇢ l› have "x = l"
    by (rule LIMSEQ_unique)
  with ‹l ∈ S› show "x ∈ S"
    by simp
qed

lemma complete_Int_closed:
  fixes S :: "'a::metric_space set"
  assumes "complete S" and "closed t"
  shows "complete (S ∩ t)"
proof (rule completeI)
  fix f assume "∀n. f n ∈ S ∩ t" and "Cauchy f"
  then have "∀n. f n ∈ S" and "∀n. f n ∈ t"
    by simp_all
  from ‹complete S› obtain l where "l ∈ S" and "f ⇢ l"
    using ‹∀n. f n ∈ S› and ‹Cauchy f› by (rule completeE)
  from ‹closed t› and ‹∀n. f n ∈ t› and ‹f ⇢ l› have "l ∈ t"
    by (rule closed_sequentially)
  with ‹l ∈ S› and ‹f ⇢ l› show "∃l∈S ∩ t. f ⇢ l"
    by fast
qed

lemma complete_closed_subset:
  fixes S :: "'a::metric_space set"
  assumes "closed S" and "S ⊆ 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 ⟷ closed S"
proof
  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"
    by (rule complete_imp_closed)
qed

lemma convergent_eq_Cauchy:
  fixes S :: "nat ⇒ 'a::complete_space"
  shows "(∃l. (S ⤏ l) sequentially) ⟷ Cauchy S"
  unfolding Cauchy_convergent_iff convergent_def ..

lemma convergent_imp_bounded:
  fixes S :: "nat ⇒ 'a::metric_space"
  shows "(S ⤏ l) sequentially ⟹ bounded (range S)"
  by (intro cauchy_imp_bounded LIMSEQ_imp_Cauchy)

lemma compact_cball[simp]:
  fixes x :: "'a::heine_borel"
  shows "compact (cball x e)"
  using compact_eq_bounded_closed bounded_cball closed_cball
  by blast

lemma compact_frontier_bounded[intro]:
  fixes S :: "'a::heine_borel set"
  shows "bounded S ⟹ 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 ⟹ compact (frontier S)"
  using compact_eq_bounded_closed compact_frontier_bounded
  by blast

corollary compact_sphere [simp]:
  fixes a :: "'a::{real_normed_vector,perfect_space,heine_borel}"
  shows "compact (sphere a r)"
using compact_frontier [of "cball a r"] by simp

corollary bounded_sphere [simp]:
  fixes a :: "'a::{real_normed_vector,perfect_space,heine_borel}"
  shows "bounded (sphere a r)"
by (simp add: compact_imp_bounded)

corollary closed_sphere  [simp]:
  fixes a :: "'a::{real_normed_vector,perfect_space,heine_borel}"
  shows "closed (sphere a r)"
by (simp add: compact_imp_closed)

lemma frontier_subset_compact:
  fixes S :: "'a::heine_borel set"
  shows "compact S ⟹ frontier S ⊆ S"
  using frontier_subset_closed compact_eq_bounded_closed
  by blast

subsection‹Relations among convergence and absolute convergence for power series.›

lemma summable_imp_bounded:
  fixes f :: "nat ⇒ 'a::real_normed_vector"
  shows "summable f ⟹ bounded (range f)"
by (frule summable_LIMSEQ_zero) (simp add: convergent_imp_bounded)

lemma summable_imp_sums_bounded:
   "summable f ⟹ bounded (range (λn. sum f {..<n}))"
by (auto simp: summable_def sums_def dest: convergent_imp_bounded)

lemma power_series_conv_imp_absconv_weak:
  fixes a:: "nat ⇒ 'a::{real_normed_div_algebra,banach}" and w :: 'a
  assumes sum: "summable (λn. a n * z ^ n)" and no: "norm w < norm z"
    shows "summable (λn. of_real(norm(a n)) * w ^ n)"
proof -
  obtain M where M: "⋀x. norm (a x * z ^ x) ≤ M"
    using summable_imp_bounded [OF sum] by (force simp: bounded_iff)
  then have *: "summable (λn. norm (a n) * norm w ^ n)"
    by (rule_tac M=M in Abel_lemma) (auto simp: norm_mult norm_power intro: no)
  show ?thesis
    apply (rule series_comparison_complex [of "(λn. of_real(norm(a n) * norm w ^ n))"])
    apply (simp only: summable_complex_of_real *)
    apply (auto simp: norm_mult norm_power)
    done
qed

subsection ‹Bounded closed nest property (proof does not use Heine-Borel)›

lemma bounded_closed_nest:
  fixes s :: "nat ⇒ ('a::heine_borel) set"
  assumes "∀n. closed (s n)"
    and "∀n. s n ≠ {}"
    and "∀m n. m ≤ n ⟶ s n ⊆ s m"
    and "bounded (s 0)"
  shows "∃a. ∀n. a ∈ s n"
proof -
  from assms(2) obtain x where x: "∀n. x n ∈ s n"
    using choice[of "λn x. x ∈ s n"] by auto
  from assms(4,1) have "seq_compact (s 0)"
    by (simp add: bounded_closed_imp_seq_compact)
  then obtain l r where lr: "l ∈ s 0" "strict_mono r" "(x ∘ r) ⇢ l"
    using x and assms(3) unfolding seq_compact_def by blast
  have "∀n. l ∈ s n"
  proof
    fix n :: nat
    have "closed (s n)"
      using assms(1) by simp
    moreover have "∀i. (x ∘ r) i ∈ s i"
      using x and assms(3) and lr(2) [THEN seq_suble] by auto
    then have "∀i. (x ∘ r) (i + n) ∈ s n"
      using assms(3) by (fast intro!: le_add2)
    moreover have "(λi. (x ∘ r) (i + n)) ⇢ l"
      using lr(3) by (rule LIMSEQ_ignore_initial_segment)
    ultimately show "l ∈ s n"
      by (rule closed_sequentially)
  qed
  then show ?thesis ..
qed

text ‹Decreasing case does not even need compactness, just completeness.›

lemma decreasing_closed_nest:
  fixes s :: "nat ⇒ ('a::complete_space) set"
  assumes
    "∀n. closed (s n)"
    "∀n. s n ≠ {}"
    "∀m n. m ≤ n ⟶ s n ⊆ s m"
    "∀e>0. ∃n. ∀x∈s n. ∀y∈s n. dist x y < e"
  shows "∃a. ∀n. a ∈ s n"
proof -
  have "∀n. ∃x. x ∈ s n"
    using assms(2) by auto
  then have "∃t. ∀n. t n ∈ s n"
    using choice[of "λn x. x ∈ s n"] by auto
  then obtain t where t: "∀n. t n ∈ s n" by auto
  {
    fix e :: real
    assume "e > 0"
    then obtain N where N:"∀x∈s N. ∀y∈s N. dist x y < e"
      using assms(4) by auto
    {
      fix m n :: nat
      assume "N ≤ m ∧ N ≤ n"
      then have "t m ∈ s N" "t n ∈ s N"
        using assms(3) t unfolding  subset_eq t by blast+
      then have "dist (t m) (t n) < e"
        using N by auto
    }
    then have "∃N. ∀m n. N ≤ m ∧ N ≤ n ⟶ dist (t m) (t n) < e"
      by auto
  }
  then have "Cauchy t"
    unfolding cauchy_def by auto
  then obtain l where l:"(t ⤏ l) sequentially"
    using complete_UNIV unfolding complete_def by auto
  {
    fix n :: nat
    {
      fix e :: real
      assume "e > 0"
      then obtain N :: nat where N: "∀n≥N. dist (t n) l < e"
        using l[unfolded lim_sequentially] by auto
      have "t (max n N) ∈ s n"
        using assms(3)
        unfolding subset_eq
        apply (erule_tac x=n in allE)
        apply (erule_tac x="max n N" in allE)
        using t
        apply auto
        done
      then have "∃y∈s n. dist y l < e"
        apply (rule_tac x="t (max n N)" in bexI)
        using N
        apply auto
        done
    }
    then have "l ∈ s n"
      using closed_approachable[of "s n" l] assms(1) by auto
  }
  then show ?thesis by auto
qed

text ‹Strengthen it to the intersection actually being a singleton.›

lemma decreasing_closed_nest_sing:
  fixes s :: "nat ⇒ 'a::complete_space set"
  assumes
    "∀n. closed(s n)"
    "∀n. s n ≠ {}"
    "∀m n. m ≤ n ⟶ s n ⊆ s m"
    "∀e>0. ∃n. ∀x ∈ (s n). ∀ y∈(s n). dist x y < e"
  shows "∃a. ⋂(range s) = {a}"
proof -
  obtain a where a: "∀n. a ∈ s n"
    using decreasing_closed_nest[of s] using assms by auto
  {
    fix b
    assume b: "b ∈ ⋂(range s)"
    {
      fix e :: real
      assume "e > 0"
      then have "dist a b < e"
        using assms(4) and b and a by blast
    }
    then have "dist a b = 0"
      by (metis dist_eq_0_iff dist_nz less_le)
  }
  with a have "⋂(range s) = {a}"
    unfolding image_def by auto
  then show ?thesis ..
qed


subsection ‹Continuity›

text‹Derive the epsilon-delta forms, which we often use as "definitions"›

lemma continuous_within_eps_delta:
  "continuous (at x within s) f ⟷ (∀e>0. ∃d>0. ∀x'∈ s.  dist x' x < d --> dist (f x') (f x) < e)"
  unfolding continuous_within and Lim_within
  apply auto
  apply (metis dist_nz dist_self, blast)
  done

corollary continuous_at_eps_delta:
  "continuous (at x) f ⟷ (∀e > 0. ∃d > 0. ∀x'. dist x' x < d ⟶ dist (f x') (f x) < e)"
  using continuous_within_eps_delta [of x UNIV f] by simp

lemma continuous_at_right_real_increasing:
  fixes f :: "real ⇒ real"
  assumes nondecF: "⋀x y. x ≤ y ⟹ f x ≤ f y"
  shows "continuous (at_right a) f ⟷ (∀e>0. ∃d>0. f (a + d) - f a < e)"
  apply (simp add: greaterThan_def dist_real_def continuous_within Lim_within_le)
  apply (intro all_cong ex_cong, safe)
  apply (erule_tac x="a + d" in allE, simp)
  apply (simp add: nondecF field_simps)
  apply (drule nondecF, simp)
  done

lemma continuous_at_left_real_increasing:
  assumes nondecF: "⋀ x y. x ≤ y ⟹ f x ≤ ((f y) :: real)"
  shows "(continuous (at_left (a :: real)) f) = (∀e > 0. ∃delta > 0. f a - f (a - delta) < e)"
  apply (simp add: lessThan_def dist_real_def continuous_within Lim_within_le)
  apply (intro all_cong ex_cong, safe)
  apply (erule_tac x="a - d" in allE, simp)
  apply (simp add: nondecF field_simps)
  apply (cut_tac x="a - d" and y=x in nondecF, simp_all)
  done

text‹Versions in terms of open balls.›

lemma continuous_within_ball:
  "continuous (at x within s) f ⟷
    (∀e > 0. ∃d > 0. f ` (ball x d ∩ s) ⊆ ball (f x) e)"
  (is "?lhs = ?rhs")
proof
  assume ?lhs
  {
    fix e :: real
    assume "e > 0"
    then obtain d where d: "d>0" "∀xa∈s. 0 < dist xa x ∧ dist xa x < d ⟶ dist (f xa) (f x) < e"
      using ‹?lhs›[unfolded continuous_within Lim_within] by auto
    {
      fix y
      assume "y ∈ f ` (ball x d ∩ s)"
      then have "y ∈ ball (f x) e"
        using d(2)
        apply (auto simp: dist_commute)
        apply (erule_tac x=xa in ballE, auto)
        using ‹e > 0›
        apply auto
        done
    }
    then have "∃d>0. f ` (ball x d ∩ s) ⊆ ball (f x) e"
      using ‹d > 0›
      unfolding subset_eq ball_def by (auto simp: dist_commute)
  }
  then show ?rhs by auto
next
  assume ?rhs
  then show ?lhs
    unfolding continuous_within Lim_within ball_def subset_eq
    apply (auto simp: dist_commute)
    apply (erule_tac x=e in allE, auto)
    done
qed

lemma continuous_at_ball:
  "continuous (at x) f ⟷ (∀e>0. ∃d>0. f ` (ball x d) ⊆ ball (f x) e)" (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball
    apply auto
    apply (erule_tac x=e in allE, auto)
    apply (rule_tac x=d in exI, auto)
    apply (erule_tac x=xa in allE)
    apply (auto simp: dist_commute)
    done
next
  assume ?rhs
  then show ?lhs
    unfolding continuous_at Lim_at subset_eq Ball_def Bex_def image_iff mem_ball
    apply auto
    apply (erule_tac x=e in allE, auto)
    apply (rule_tac x=d in exI, auto)
    apply (erule_tac x="f xa" in allE)
    apply (auto simp: dist_commute)
    done
qed

text‹Define setwise continuity in terms of limits within the set.›

lemma continuous_on_iff:
  "continuous_on s f ⟷
    (∀x∈s. ∀e>0. ∃d>0. ∀x'∈s. dist x' x < d ⟶ dist (f x') (f x) < e)"
  unfolding continuous_on_def Lim_within
  by (metis dist_pos_lt dist_self)

lemma continuous_within_E:
  assumes "continuous (at x within s) f" "e>0"
  obtains d where "d>0"  "⋀x'. ⟦x'∈ s; dist x' x ≤ d⟧ ⟹ dist (f x') (f x) < e"
  using assms apply (simp add: continuous_within_eps_delta)
  apply (drule spec [of _ e], clarify)
  apply (rule_tac d="d/2" in that, auto)
  done

lemma continuous_onI [intro?]:
  assumes "⋀x e. ⟦e > 0; x ∈ s⟧ ⟹ ∃d>0. ∀x'∈s. dist x' x < d ⟶ dist (f x') (f x) ≤ e"
  shows "continuous_on s f"
apply (simp add: continuous_on_iff, clarify)
apply (rule ex_forward [OF assms [OF half_gt_zero]], auto)
done

text‹Some simple consequential lemmas.›

lemma continuous_onE:
    assumes "continuous_on s f" "x∈s" "e>0"
    obtains d where "d>0"  "⋀x'. ⟦x' ∈ s; dist x' x ≤ d⟧ ⟹ dist (f x') (f x) < e"
  using assms
  apply (simp add: continuous_on_iff)
  apply (elim ballE allE)
  apply (auto intro: that [where d="d/2" for d])
  done

lemma uniformly_continuous_onE:
  assumes "uniformly_continuous_on s f" "0 < e"
  obtains d where "d>0" "⋀x x'. ⟦x∈s; x'∈s; dist x' x < d⟧ ⟹ dist (f x') (f x) < e"
using assms
by (auto simp: uniformly_continuous_on_def)

lemma continuous_at_imp_continuous_within:
  "continuous (at x) f ⟹ continuous (at x within s) f"
  unfolding continuous_within continuous_at using Lim_at_imp_Lim_at_within by auto

lemma Lim_trivial_limit: "trivial_limit net ⟹ (f ⤏ l) net"
  by simp

lemmas continuous_on = continuous_on_def  "legacy theorem name"

lemma continuous_within_subset:
  "continuous (at x within s) f ⟹ t ⊆ s ⟹ continuous (at x within t) f"
  unfolding continuous_within by(metis tendsto_within_subset)

lemma continuous_on_interior:
  "continuous_on s f ⟹ x ∈ interior s ⟹ continuous (at x) f"
  by (metis continuous_on_eq_continuous_at continuous_on_subset interiorE)

lemma continuous_on_eq:
  "⟦continuous_on s f; ⋀x. x ∈ s ⟹ f x = g x⟧ ⟹ continuous_on s g"
  unfolding continuous_on_def tendsto_def eventually_at_topological
  by simp

text ‹Characterization of various kinds of continuity in terms of sequences.›

lemma continuous_within_sequentially:
  fixes f :: "'a::metric_space ⇒ 'b::topological_space"
  shows "continuous (at a within s) f ⟷
    (∀x. (∀n::nat. x n ∈ s) ∧ (x ⤏ a) sequentially
         ⟶ ((f ∘ x) ⤏ f a) sequentially)"
  (is "?lhs = ?rhs")
proof
  assume ?lhs
  {
    fix x :: "nat ⇒ 'a"
    assume x: "∀n. x n ∈ s" "∀e>0. eventually (λn. dist (x n) a < e) sequentially"
    fix T :: "'b set"
    assume "open T" and "f a ∈ T"
    with ‹?lhs› obtain d where "d>0" and d:"∀x∈s. 0 < dist x a ∧ dist x a < d ⟶ f x ∈ T"
      unfolding continuous_within tendsto_def eventually_at by auto
    have "eventually (λn. dist (x n) a < d) sequentially"
      using x(2) ‹d>0› by simp
    then have "eventually (λn. (f ∘ x) n ∈ T) sequentially"
    proof eventually_elim
      case (elim n)
      then show ?case
        using d x(1) ‹f a ∈ T› by auto
    qed
  }
  then show ?rhs
    unfolding tendsto_iff tendsto_def by simp
next
  assume ?rhs
  then show ?lhs
    unfolding continuous_within tendsto_def [where l="f a"]
    by (simp add: sequentially_imp_eventually_within)
qed

lemma continuous_at_sequentially:
  fixes f :: "'a::metric_space ⇒ 'b::topological_space"
  shows "continuous (at a) f ⟷
    (∀x. (x ⤏ a) sequentially --> ((f ∘ x) ⤏ f a) sequentially)"
  using continuous_within_sequentially[of a UNIV f] by simp

lemma continuous_on_sequentially:
  fixes f :: "'a::metric_space ⇒ 'b::topological_space"
  shows "continuous_on s f ⟷
    (∀x. ∀a ∈ s. (∀n. x(n) ∈ s) ∧ (x ⤏ a) sequentially
      --> ((f ∘ x) ⤏ f a) sequentially)"
  (is "?lhs = ?rhs")
proof
  assume ?rhs
  then show ?lhs
    using continuous_within_sequentially[of _ s f]
    unfolding continuous_on_eq_continuous_within
    by auto
next
  assume ?lhs
  then show ?rhs
    unfolding continuous_on_eq_continuous_within
    using continuous_within_sequentially[of _ s f]
    by auto
qed

lemma uniformly_continuous_on_sequentially:
  "uniformly_continuous_on s f ⟷ (∀x y. (∀n. x n ∈ s) ∧ (∀n. y n ∈ s) ∧
    (λn. dist (x n) (y n)) ⇢ 0 ⟶ (λn. dist (f(x n)) (f(y n))) ⇢ 0)" (is "?lhs = ?rhs")
proof
  assume ?lhs
  {
    fix x y
    assume x: "∀n. x n ∈ s"
      and y: "∀n. y n ∈ s"
      and xy: "((λn. dist (x n) (y n)) ⤏ 0) sequentially"
    {
      fix e :: real
      assume "e > 0"
      then obtain d where "d > 0" and d: "∀x∈s. ∀x'∈s. dist x' x < d ⟶ dist (f x') (f x) < e"
        using ‹?lhs›[unfolded uniformly_continuous_on_def, THEN spec[where x=e]] by auto
      obtain N where N: "∀n≥N. dist (x n) (y n) < d"
        using xy[unfolded lim_sequentially dist_norm] and ‹d>0› by auto
      {
        fix n
        assume "n≥N"
        then have "dist (f (x n)) (f (y n)) < e"
          using N[THEN spec[where x=n]]
          using d[THEN bspec[where x="x n"], THEN bspec[where x="y n"]]
          using x and y
          by (simp add: dist_commute)
      }
      then have "∃N. ∀n≥N. dist (f (x n)) (f (y n)) < e"
        by auto
    }
    then have "((λn. dist (f(x n)) (f(y n))) ⤏ 0) sequentially"
      unfolding lim_sequentially and dist_real_def by auto
  }
  then show ?rhs by auto
next
  assume ?rhs
  {
    assume "¬ ?lhs"
    then obtain e where "e > 0" "∀d>0. ∃x∈s. ∃x'∈s. dist x' x < d ∧ ¬ dist (f x') (f x) < e"
      unfolding uniformly_continuous_on_def by auto
    then obtain fa where fa:
      "∀x. 0 < x ⟶ fst (fa x) ∈ s ∧ snd (fa x) ∈ s ∧ dist (fst (fa x)) (snd (fa x)) < x ∧ ¬ dist (f (fst (fa x))) (f (snd (fa x))) < e"
      using choice[of "λd x. d>0 ⟶ fst x ∈ s ∧ snd x ∈ s ∧ dist (snd x) (fst x) < d ∧ ¬ dist (f (snd x)) (f (fst x)) < e"]
      unfolding Bex_def
      by (auto simp: dist_commute)
    define x where "x n = fst (fa (inverse (real n + 1)))" for n
    define y where "y n = snd (fa (inverse (real n + 1)))" for n
    have xyn: "∀n. x n ∈ s ∧ y n ∈ s"
      and xy0: "∀n. dist (x n) (y n) < inverse (real n + 1)"
      and fxy:"∀n. ¬ dist (f (x n)) (f (y n)) < e"
      unfolding x_def and y_def using fa
      by auto
    {
      fix e :: real
      assume "e > 0"
      then obtain N :: nat where "N ≠ 0" and N: "0 < inverse (real N) ∧ inverse (real N) < e"
        unfolding real_arch_inverse[of e] by auto
      {
        fix n :: nat
        assume "n ≥ N"
        then have "inverse (real n + 1) < inverse (real N)"
          using of_nat_0_le_iff and ‹N≠0› by auto
        also have "… < e" using N by auto
        finally have "inverse (real n + 1) < e" by auto
        then have "dist (x n) (y n) < e"
          using xy0[THEN spec[where x=n]] by auto
      }
      then have "∃N. ∀n≥N. dist (x n) (y n) < e" by auto
    }
    then have "∀e>0. ∃N. ∀n≥N. dist (f (x n)) (f (y n)) < e"
      using ‹?rhs›[THEN spec[where x=x], THEN spec[where x=y]] and xyn
      unfolding lim_sequentially dist_real_def by auto
    then have False using fxy and ‹e>0› by auto
  }
  then show ?lhs
    unfolding uniformly_continuous_on_def by blast
qed

lemma continuous_closed_imp_Cauchy_continuous:
  fixes S :: "('a::complete_space) set"
  shows "⟦continuous_on S f; closed S; Cauchy σ; ⋀n. (σ n) ∈ S⟧ ⟹ Cauchy(f o σ)"
  apply (simp add: complete_eq_closed [symmetric] continuous_on_sequentially)
  by (meson LIMSEQ_imp_Cauchy complete_def)

text‹The usual transformation theorems.›

lemma continuous_transform_within:
  fixes f g :: "'a::metric_space ⇒ 'b::topological_space"
  assumes "continuous (at x within s) f"
    and "0 < d"
    and "x ∈ s"
    and "⋀x'. ⟦x' ∈ s; dist x' x < d⟧ ⟹ f x' = g x'"
  shows "continuous (at x within s) g"
  using assms
  unfolding continuous_within
  by (force intro: Lim_transform_within)


subsubsection ‹Structural rules for pointwise continuity›

lemma continuous_infdist[continuous_intros]:
  assumes "continuous F f"
  shows "continuous F (λx. infdist (f x) A)"
  using assms unfolding continuous_def by (rule tendsto_infdist)

lemma continuous_infnorm[continuous_intros]:
  "continuous F f ⟹ continuous F (λx. infnorm (f x))"
  unfolding continuous_def by (rule tendsto_infnorm)

lemma continuous_inner[continuous_intros]:
  assumes "continuous F f"
    and "continuous F g"
  shows "continuous F (λx. inner (f x) (g x))"
  using assms unfolding continuous_def by (rule tendsto_inner)

lemmas continuous_at_inverse = isCont_inverse

subsubsection ‹Structural rules for setwise continuity›

lemma continuous_on_infnorm[continuous_intros]:
  "continuous_on s f ⟹ continuous_on s (λx. infnorm (f x))"
  unfolding continuous_on by (fast intro: tendsto_infnorm)

lemma continuous_on_inner[continuous_intros]:
  fixes g :: "'a::topological_space ⇒ 'b::real_inner"
  assumes "continuous_on s f"
    and "continuous_on s g"
  shows "continuous_on s (λx. inner (f x) (g x))"
  using bounded_bilinear_inner assms
  by (rule bounded_bilinear.continuous_on)

subsubsection ‹Structural rules for uniform continuity›

lemma uniformly_continuous_on_dist[continuous_intros]:
  fixes f g :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "uniformly_continuous_on s f"
    and "uniformly_continuous_on s g"
  shows "uniformly_continuous_on s (λx. dist (f x) (g x))"
proof -
  {
    fix a b c d :: 'b
    have "¦dist a b - dist c d¦ ≤ dist a c + dist b d"
      using dist_triangle2 [of a b c] dist_triangle2 [of b c d]
      using dist_triangle3 [of c d a] dist_triangle [of a d b]
      by arith
  } note le = this
  {
    fix x y
    assume f: "(λn. dist (f (x n)) (f (y n))) ⇢ 0"
    assume g: "(λn. dist (g (x n)) (g (y n))) ⇢ 0"
    have "(λn. ¦dist (f (x n)) (g (x n)) - dist (f (y n)) (g (y n))¦) ⇢ 0"
      by (rule Lim_transform_bound [OF _ tendsto_add_zero [OF f g]],
        simp add: le)
  }
  then show ?thesis
    using assms unfolding uniformly_continuous_on_sequentially
    unfolding dist_real_def by simp
qed

lemma uniformly_continuous_on_norm[continuous_intros]:
  fixes f :: "'a :: metric_space ⇒ 'b :: real_normed_vector"
  assumes "uniformly_continuous_on s f"
  shows "uniformly_continuous_on s (λx. norm (f x))"
  unfolding norm_conv_dist using assms
  by (intro uniformly_continuous_on_dist uniformly_continuous_on_const)

lemma (in bounded_linear) uniformly_continuous_on[continuous_intros]:
  fixes g :: "_::metric_space ⇒ _"
  assumes "uniformly_continuous_on s g"
  shows "uniformly_continuous_on s (λx. f (g x))"
  using assms unfolding uniformly_continuous_on_sequentially
  unfolding dist_norm tendsto_norm_zero_iff diff[symmetric]
  by (auto intro: tendsto_zero)

lemma uniformly_continuous_on_cmul[continuous_intros]:
  fixes f :: "'a::metric_space ⇒ 'b::real_normed_vector"
  assumes "uniformly_continuous_on s f"
  shows "uniformly_continuous_on s (λx. c *R f(x))"
  using bounded_linear_scaleR_right assms
  by (rule bounded_linear.uniformly_continuous_on)

lemma dist_minus:
  fixes x y :: "'a::real_normed_vector"
  shows "dist (- x) (- y) = dist x y"
  unfolding dist_norm minus_diff_minus norm_minus_cancel ..

lemma uniformly_continuous_on_minus[continuous_intros]:
  fixes f :: "'a::metric_space ⇒ 'b::real_normed_vector"
  shows "uniformly_continuous_on s f ⟹ uniformly_continuous_on s (λx. - f x)"
  unfolding uniformly_continuous_on_def dist_minus .

lemma uniformly_continuous_on_add[continuous_intros]:
  fixes f g :: "'a::metric_space ⇒ 'b::real_normed_vector"
  assumes "uniformly_continuous_on s f"
    and "uniformly_continuous_on s g"
  shows "uniformly_continuous_on s (λx. f x + g x)"
  using assms
  unfolding uniformly_continuous_on_sequentially
  unfolding dist_norm tendsto_norm_zero_iff add_diff_add
  by (auto intro: tendsto_add_zero)

lemma uniformly_continuous_on_diff[continuous_intros]:
  fixes f :: "'a::metric_space ⇒ 'b::real_normed_vector"
  assumes "uniformly_continuous_on s f"
    and "uniformly_continuous_on s g"
  shows "uniformly_continuous_on s (λx. f x - g x)"
  using assms uniformly_continuous_on_add [of s f "- g"]
    by (simp add: fun_Compl_def uniformly_continuous_on_minus)

lemmas continuous_at_compose = isCont_o

text ‹Continuity in terms of open preimages.›

lemma continuous_at_open:
  "continuous (at x) f ⟷ (∀t. open t ∧ f x ∈ t --> (∃s. open s ∧ x ∈ s ∧ (∀x' ∈ s. (f x') ∈ t)))"
  unfolding continuous_within_topological [of x UNIV f]
  unfolding imp_conjL
  by (intro all_cong imp_cong ex_cong conj_cong refl) auto

lemma continuous_imp_tendsto:
  assumes "continuous (at x0) f"
    and "x ⇢ x0"
  shows "(f ∘ x) ⇢ (f x0)"
proof (rule topological_tendstoI)
  fix S
  assume "open S" "f x0 ∈ S"
  then obtain T where T_def: "open T" "x0 ∈ T" "∀x∈T. f x ∈ S"
     using assms continuous_at_open by metis
  then have "eventually (λn. x n ∈ T) sequentially"
    using assms T_def by (auto simp: tendsto_def)
  then show "eventually (λn. (f ∘ x) n ∈ S) sequentially"
    using T_def by (auto elim!: eventually_mono)
qed

lemma continuous_on_open:
  "continuous_on s f ⟷
    (∀t. openin (subtopology euclidean (f ` s)) t ⟶
      openin (subtopology euclidean s) {x ∈ s. f x ∈ t})"
  unfolding continuous_on_open_invariant openin_open Int_def vimage_def Int_commute
  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)

lemma continuous_on_open_gen:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "f ` S ⊆ T"
    shows "continuous_on S f ⟷
             (∀U. openin (subtopology euclidean T) U
                  ⟶ openin (subtopology euclidean S) {x ∈ S. f x ∈ U})"
     (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    apply (auto simp: openin_euclidean_subtopology_iff continuous_on_iff)
    by (metis assms image_subset_iff)
next
  have ope: "openin (subtopology euclidean T) (ball y e ∩ T)" for y e
    by (simp add: Int_commute openin_open_Int)
  assume ?rhs
  then show ?lhs
    apply (clarsimp simp add: continuous_on_iff)
    apply (drule_tac x = "ball (f x) e ∩ T" in spec)
    apply (clarsimp simp add: ope openin_euclidean_subtopology_iff [of S])
    by (metis (no_types, hide_lams) assms dist_commute dist_self image_subset_iff)
qed

lemma continuous_openin_preimage:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  shows
   "⟦continuous_on S f; f ` S ⊆ T; openin (subtopology euclidean T) U⟧
        ⟹ openin (subtopology euclidean S) {x ∈ S. f x ∈ U}"
by (simp add: continuous_on_open_gen)

text ‹Similarly in terms of closed sets.›

lemma continuous_on_closed:
  "continuous_on s f ⟷
    (∀t. closedin (subtopology euclidean (f ` s)) t ⟶
      closedin (subtopology euclidean s) {x ∈ s. f x ∈ t})"
  unfolding continuous_on_closed_invariant closedin_closed Int_def vimage_def Int_commute
  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)

lemma continuous_on_closed_gen:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "f ` S ⊆ T"
    shows "continuous_on S f ⟷
             (∀U. closedin (subtopology euclidean T) U
                  ⟶ closedin (subtopology euclidean S) {x ∈ S. f x ∈ U})"
proof -
  have *: "U ⊆ T ⟹ {x ∈ S. f x ∈ T ∧ f x ∉ U} = S - {x ∈ S. f x ∈ U}" for U
    using assms by blast
  show ?thesis
    apply (simp add: continuous_on_open_gen [OF assms], safe)
    apply (drule_tac [!] x="T-U" in spec)
    apply (force simp: closedin_def *)
    apply (force simp: openin_closedin_eq *)
    done
qed

lemma continuous_closedin_preimage_gen:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "continuous_on S f" "f ` S ⊆ T" "closedin (subtopology euclidean T) U"
    shows "closedin (subtopology euclidean S) {x ∈ S. f x ∈ U}"
using assms continuous_on_closed_gen by blast

lemma continuous_on_imp_closedin:
  assumes "continuous_on S f" "closedin (subtopology euclidean (f ` S)) T"
    shows "closedin (subtopology euclidean S) {x. x ∈ S ∧ f x ∈ T}"
using assms continuous_on_closed by blast

subsection ‹Half-global and completely global cases.›

lemma continuous_openin_preimage_gen:
  assumes "continuous_on s f"  "open t"
  shows "openin (subtopology euclidean s) {x ∈ s. f x ∈ t}"
proof -
  have *: "∀x. x ∈ s ∧ f x ∈ t ⟷ x ∈ s ∧ f x ∈ (t ∩ f ` s)"
    by auto
  have "openin (subtopology euclidean (f ` s)) (t ∩ f ` s)"
    using openin_open_Int[of t "f ` s", OF assms(2)] unfolding openin_open by auto
  then show ?thesis
    using assms(1)[unfolded continuous_on_open, THEN spec[where x="t ∩ f ` s"]]
    using * by auto
qed

lemma continuous_closedin_preimage:
  assumes "continuous_on s f" and "closed t"
  shows "closedin (subtopology euclidean s) {x ∈ s. f x ∈ t}"
proof -
  have *: "∀x. x ∈ s ∧ f x ∈ t ⟷ x ∈ s ∧ f x ∈ (t ∩ f ` s)"
    by auto
  have "closedin (subtopology euclidean (f ` s)) (t ∩ f ` s)"
    using closedin_closed_Int[of t "f ` s", OF assms(2)]
    by (simp add: Int_commute)
  then show ?thesis
    using assms(1)[unfolded continuous_on_closed, THEN spec[where x="t ∩ f ` s"]]
    using * by auto
qed

lemma continuous_openin_preimage_eq:
   "continuous_on S f ⟷
    (∀t. open t ⟶ openin (subtopology euclidean S) {x. x ∈ S ∧ f x ∈ t})"
apply safe
apply (simp add: continuous_openin_preimage_gen)
apply (fastforce simp add: continuous_on_open openin_open)
done

lemma continuous_closedin_preimage_eq:
   "continuous_on S f ⟷
    (∀t. closed t ⟶ closedin (subtopology euclidean S) {x. x ∈ S ∧ f x ∈ t})"
apply safe
apply (simp add: continuous_closedin_preimage)
apply (fastforce simp add: continuous_on_closed closedin_closed)
done

lemma continuous_open_preimage:
  assumes "continuous_on s f"
    and "open s"
    and "open t"
  shows "open {x ∈ s. f x ∈ t}"
proof-
  obtain T where T: "open T" "{x ∈ s. f x ∈ t} = s ∩ T"
    using continuous_openin_preimage_gen[OF assms(1,3)] unfolding openin_open by auto
  then show ?thesis
    using open_Int[of s T, OF assms(2)] by auto
qed

lemma continuous_closed_preimage:
  assumes "continuous_on s f"
    and "closed s"
    and "closed t"
  shows "closed {x ∈ s. f x ∈ t}"
proof-
  obtain T where "closed T" "{x ∈ s. f x ∈ t} = s ∩ T"
    using continuous_closedin_preimage[OF assms(1,3)]
    unfolding closedin_closed by auto
  then show ?thesis using closed_Int[of s T, OF assms(2)] by auto
qed

lemma continuous_open_preimage_univ:
  "open s ⟹ (⋀x. continuous (at x) f) ⟹ open {x. f x ∈ s}"
  using continuous_open_preimage[of UNIV f s] open_UNIV continuous_at_imp_continuous_on by auto

lemma continuous_closed_preimage_univ:
  "closed s ⟹ (⋀x. continuous (at x) f) ⟹ closed {x. f x ∈ s}"
  using continuous_closed_preimage[of UNIV f s] closed_UNIV continuous_at_imp_continuous_on by auto

lemma continuous_open_vimage: "open s ⟹ (⋀x. continuous (at x) f) ⟹ open (f -` s)"
  unfolding vimage_def by (rule continuous_open_preimage_univ)

lemma continuous_closed_vimage: "closed s ⟹ (⋀x. continuous (at x) f) ⟹ closed (f -` s)"
  unfolding vimage_def by (rule continuous_closed_preimage_univ)

lemma interior_image_subset:
  assumes "inj f" "⋀x. continuous (at x) f"
  shows "interior (f ` s) ⊆ f ` (interior s)"
proof
  fix x assume "x ∈ interior (f ` s)"
  then obtain T where as: "open T" "x ∈ T" "T ⊆ f ` s" ..
  then have "x ∈ f ` s" by auto
  then obtain y where y: "y ∈ s" "x = f y" by auto
  have "open (vimage f T)"
    using assms ‹open T› by (metis continuous_open_vimage)
  moreover have "y ∈ vimage f T"
    using ‹x = f y› ‹x ∈ T› by simp
  moreover have "vimage f T ⊆ s"
    using ‹T ⊆ image f s› ‹inj f› unfolding inj_on_def subset_eq by auto
  ultimately have "y ∈ interior s" ..
  with ‹x = f y› show "x ∈ f ` interior s" ..
qed

subsection ‹Equality of continuous functions on closure and related results.›

lemma continuous_closedin_preimage_constant:
  fixes f :: "_ ⇒ 'b::t1_space"
  shows "continuous_on s f ⟹ closedin (subtopology euclidean s) {x ∈ s. f x = a}"
  using continuous_closedin_preimage[of s f "{a}"] by auto

lemma continuous_closed_preimage_constant:
  fixes f :: "_ ⇒ 'b::t1_space"
  shows "continuous_on s f ⟹ closed s ⟹ closed {x ∈ s. f x = a}"
  using continuous_closed_preimage[of s f "{a}"] by auto

lemma continuous_constant_on_closure:
  fixes f :: "_ ⇒ 'b::t1_space"
  assumes "continuous_on (closure S) f"
      and "⋀x. x ∈ S ⟹ f x = a"
      and "x ∈ closure S"
  shows "f x = a"
    using continuous_closed_preimage_constant[of "closure S" f a]
      assms closure_minimal[of S "{x ∈ closure S. f x = a}"] closure_subset
    unfolding subset_eq
    by auto

lemma image_closure_subset:
  assumes "continuous_on (closure s) f"
    and "closed t"
    and "(f ` s) ⊆ t"
  shows "f ` (closure s) ⊆ t"
proof -
  have "s ⊆ {x ∈ closure s. f x ∈ t}"
    using assms(3) closure_subset by auto
  moreover have "closed {x ∈ closure s. f x ∈ t}"
    using continuous_closed_preimage[OF assms(1)] and assms(2) by auto
  ultimately have "closure s = {x ∈ closure s . f x ∈ t}"
    using closure_minimal[of s "{x ∈ closure s. f x ∈ t}"] by auto
  then show ?thesis by auto
qed

lemma continuous_on_closure_norm_le:
  fixes f :: "'a::metric_space ⇒ 'b::real_normed_vector"
  assumes "continuous_on (closure s) f"
    and "∀y ∈ s. norm(f y) ≤ b"
    and "x ∈ (closure s)"
  shows "norm (f x) ≤ b"
proof -
  have *: "f ` s ⊆ cball 0 b"
    using assms(2)[unfolded mem_cball_0[symmetric]] by auto
  show ?thesis
    using image_closure_subset[OF assms(1) closed_cball[of 0 b] *] assms(3)
    unfolding subset_eq
    apply (erule_tac x="f x" in ballE)
    apply (auto simp: dist_norm)
    done
qed

lemma isCont_indicator:
  fixes x :: "'a::t2_space"
  shows "isCont (indicator A :: 'a ⇒ real) x = (x ∉ frontier A)"
proof auto
  fix x
  assume cts_at: "isCont (indicator A :: 'a ⇒ real) x" and fr: "x ∈ frontier A"
  with continuous_at_open have 1: "∀V::real set. open V ∧ indicator A x ∈ V ⟶
    (∃U::'a set. open U ∧ x ∈ U ∧ (∀y∈U. indicator A y ∈ V))" by auto
  show False
  proof (cases "x ∈ A")
    assume x: "x ∈ A"
    hence "indicator A x ∈ ({0<..<2} :: real set)" by simp
    hence "∃U. open U ∧ x ∈ U ∧ (∀y∈U. indicator A y ∈ ({0<..<2} :: real set))"
      using 1 open_greaterThanLessThan by blast
    then guess U .. note U = this
    hence "∀y∈U. indicator A y > (0::real)"
      unfolding greaterThanLessThan_def by auto
    hence "U ⊆ A" using indicator_eq_0_iff by force
    hence "x ∈ interior A" using U interiorI by auto
    thus ?thesis using fr unfolding frontier_def by simp
  next
    assume x: "x ∉ A"
    hence "indicator A x ∈ ({-1<..<1} :: real set)" by simp
    hence "∃U. open U ∧ x ∈ U ∧ (∀y∈U. indicator A y ∈ ({-1<..<1} :: real set))"
      using 1 open_greaterThanLessThan by blast
    then guess U .. note U = this
    hence "∀y∈U. indicator A y < (1::real)"
      unfolding greaterThanLessThan_def by auto
    hence "U ⊆ -A" by auto
    hence "x ∈ interior (-A)" using U interiorI by auto
    thus ?thesis using fr interior_complement unfolding frontier_def by auto
  qed
next
  assume nfr: "x ∉ frontier A"
  hence "x ∈ interior A ∨ x ∈ interior (-A)"
    by (auto simp: frontier_def closure_interior)
  thus "isCont ((indicator A)::'a ⇒ real) x"
  proof
    assume int: "x ∈ interior A"
    then obtain U where U: "open U" "x ∈ U" "U ⊆ A" unfolding interior_def by auto
    hence "∀y∈U. indicator A y = (1::real)" unfolding indicator_def by auto
    hence "continuous_on U (indicator A)" by (simp add: continuous_on_const indicator_eq_1_iff)
    thus ?thesis using U continuous_on_eq_continuous_at by auto
  next
    assume ext: "x ∈ interior (-A)"
    then obtain U where U: "open U" "x ∈ U" "U ⊆ -A" unfolding interior_def by auto
    then have "continuous_on U (indicator A)"
      using continuous_on_topological by (auto simp: subset_iff)
    thus ?thesis using U continuous_on_eq_continuous_at by auto
  qed
qed

subsection‹ Theorems relating continuity and uniform continuity to closures›

lemma continuous_on_closure:
   "continuous_on (closure S) f ⟷
    (∀x e. x ∈ closure S ∧ 0 < e
           ⟶ (∃d. 0 < d ∧ (∀y. y ∈ S ∧ dist y x < d ⟶ dist (f y) (f x) < e)))"
   (is "?lhs = ?rhs")
proof
  assume ?lhs then show ?rhs
    unfolding continuous_on_iff  by (metis Un_iff closure_def)
next
  assume R [rule_format]: ?rhs
  show ?lhs
  proof
    fix x and e::real
    assume "0 < e" and x: "x ∈ closure S"
    obtain δ::real where "δ > 0"
                   and δ: "⋀y. ⟦y ∈ S; dist y x < δ⟧ ⟹ dist (f y) (f x) < e/2"
      using R [of x "e/2"] ‹0 < e› x by auto
    have "dist (f y) (f x) ≤ e" if y: "y ∈ closure S" and dyx: "dist y x < δ/2" for y
    proof -
      obtain δ'::real where "δ' > 0"
                      and δ': "⋀z. ⟦z ∈ S; dist z y < δ'⟧ ⟹ dist (f z) (f y) < e/2"
        using R [of y "e/2"] ‹0 < e› y by auto
      obtain z where "z ∈ S" and z: "dist z y < min δ' δ / 2"
        using closure_approachable y
        by (metis ‹0 < δ'› ‹0 < δ› divide_pos_pos min_less_iff_conj zero_less_numeral)
      have "dist (f z) (f y) < e/2"
        apply (rule δ' [OF ‹z ∈ S›])
        using z ‹0 < δ'› by linarith
      moreover have "dist (f z) (f x) < e/2"
        apply (rule δ [OF ‹z ∈ S›])
        using z ‹0 < δ›  dist_commute[of y z] dist_triangle_half_r [of y] dyx by auto
      ultimately show ?thesis
        by (metis dist_commute dist_triangle_half_l less_imp_le)
    qed
    then show "∃d>0. ∀x'∈closure S. dist x' x < d ⟶ dist (f x') (f x) ≤ e"
      by (rule_tac x="δ/2" in exI) (simp add: ‹δ > 0›)
  qed
qed

lemma continuous_on_closure_sequentially:
  fixes f :: "'a::metric_space ⇒ 'b :: metric_space"
  shows
   "continuous_on (closure S) f ⟷
    (∀x a. a ∈ closure S ∧ (∀n. x n ∈ S) ∧ x ⇢ a ⟶ (f ∘ x) ⇢ f a)"
   (is "?lhs = ?rhs")
proof -
  have "continuous_on (closure S) f ⟷
           (∀x ∈ closure S. continuous (at x within S) f)"
    by (force simp: continuous_on_closure Topology_Euclidean_Space.continuous_within_eps_delta)
  also have "... = ?rhs"
    by (force simp: continuous_within_sequentially)
  finally show ?thesis .
qed

lemma uniformly_continuous_on_closure:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes ucont: "uniformly_continuous_on S f"
      and cont: "continuous_on (closure S) f"
    shows "uniformly_continuous_on (closure S) f"
unfolding uniformly_continuous_on_def
proof (intro allI impI)
  fix e::real
  assume "0 < e"
  then obtain d::real
    where "d>0"
      and d: "⋀x x'. ⟦x∈S; x'∈S; dist x' x < d⟧ ⟹ dist (f x') (f x) < e/3"
    using ucont [unfolded uniformly_continuous_on_def, rule_format, of "e/3"] by auto
  show "∃d>0. ∀x∈closure S. ∀x'∈closure S. dist x' x < d ⟶ dist (f x') (f x) < e"
  proof (rule exI [where x="d/3"], clarsimp simp: ‹d > 0›)
    fix x y
    assume x: "x ∈ closure S" and y: "y ∈ closure S" and dyx: "dist y x * 3 < d"
    obtain d1::real where "d1 > 0"
           and d1: "⋀w. ⟦w ∈ closure S; dist w x < d1⟧ ⟹ dist (f w) (f x) < e/3"
      using cont [unfolded continuous_on_iff, rule_format, of "x" "e/3"] ‹0 < e› x by auto
     obtain x' where "x' ∈ S" and x': "dist x' x < min d1 (d / 3)"
        using closure_approachable [of x S]
        by (metis ‹0 < d1› ‹0 < d› divide_pos_pos min_less_iff_conj x zero_less_numeral)
    obtain d2::real where "d2 > 0"
           and d2: "∀w ∈ closure S. dist w y < d2 ⟶ dist (f w) (f y) < e/3"
      using cont [unfolded continuous_on_iff, rule_format, of "y" "e/3"] ‹0 < e› y by auto
     obtain y' where "y' ∈ S" and y': "dist y' y < min d2 (d / 3)"
        using closure_approachable [of y S]
        by (metis ‹0 < d2› ‹0 < d› divide_pos_pos min_less_iff_conj y zero_less_numeral)
     have "dist x' x < d/3" using x' by auto
     moreover have "dist x y < d/3"
       by (metis dist_commute dyx less_divide_eq_numeral1(1))
     moreover have "dist y y' < d/3"
       by (metis (no_types) dist_commute min_less_iff_conj y')
     ultimately have "dist x' y' < d/3 + d/3 + d/3"
       by (meson dist_commute_lessI dist_triangle_lt add_strict_mono)
     then have "dist x' y' < d" by simp
     then have "dist (f x') (f y') < e/3"
       by (rule d [OF ‹y' ∈ S› ‹x' ∈ S›])
     moreover have "dist (f x') (f x) < e/3" using ‹x' ∈ S› closure_subset x' d1
       by (simp add: closure_def)
     moreover have "dist (f y') (f y) < e/3" using ‹y' ∈ S› closure_subset y' d2
       by (simp add: closure_def)
     ultimately have "dist (f y) (f x) < e/3 + e/3 + e/3"
       by (meson dist_commute_lessI dist_triangle_lt add_strict_mono)
    then show "dist (f y) (f x) < e" by simp
  qed
qed

lemma uniformly_continuous_on_extension_at_closure:
  fixes f::"'a::metric_space ⇒ 'b::complete_space"
  assumes uc: "uniformly_continuous_on X f"
  assumes "x ∈ closure X"
  obtains l where "(f ⤏ l) (at x within X)"
proof -
  from assms obtain xs where xs: "xs ⇢ x" "⋀n. xs n ∈ X"
    by (auto simp: closure_sequential)

  from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF xs]
  obtain l where l: "(λn. f (xs n)) ⇢ l"
    by atomize_elim (simp only: convergent_eq_Cauchy)

  have "(f ⤏ l) (at x within X)"
  proof (safe intro!: Lim_within_LIMSEQ)
    fix xs'
    assume "∀n. xs' n ≠ x ∧ xs' n ∈ X"
      and xs': "xs' ⇢ x"
    then have "xs' n ≠ x" "xs' n ∈ X" for n by auto

    from uniformly_continuous_on_Cauchy[OF uc LIMSEQ_imp_Cauchy, OF ‹xs' ⇢ x› ‹xs' _ ∈ X›]
    obtain l' where l': "(λn. f (xs' n)) ⇢ l'"
      by atomize_elim (simp only: convergent_eq_Cauchy)

    show "(λn. f (xs' n)) ⇢ l"
    proof (rule tendstoI)
      fix e::real assume "e > 0"
      define e' where "e' ≡ e / 2"
      have "e' > 0" using ‹e > 0› by (simp add: e'_def)

      have "∀F n in sequentially. dist (f (xs n)) l < e'"
        by (simp add: ‹0 < e'› l tendstoD)
      moreover
      from uc[unfolded uniformly_continuous_on_def, rule_format, OF ‹e' > 0›]
      obtain d where d: "d > 0" "⋀x x'. x ∈ X ⟹ x' ∈ X ⟹ dist x x' < d ⟹ dist (f x) (f x') < e'"
        by auto
      have "∀F n in sequentially. dist (xs n) (xs' n) < d"
        by (auto intro!: ‹0 < d› order_tendstoD tendsto_eq_intros xs xs')
      ultimately
      show "∀F n in sequentially. dist (f (xs' n)) l < e"
      proof eventually_elim
        case (elim n)
        have "dist (f (xs' n)) l ≤ dist (f (xs n)) (f (xs' n)) + dist (f (xs n)) l"
          by (metis dist_triangle dist_commute)
        also have "dist (f (xs n)) (f (xs' n)) < e'"
          by (auto intro!: d xs ‹xs' _ ∈ _› elim)
        also note ‹dist (f (xs n)) l < e'›
        also have "e' + e' = e" by (simp add: e'_def)
        finally show ?case by simp
      qed
    qed
  qed
  thus ?thesis ..
qed

lemma uniformly_continuous_on_extension_on_closure:
  fixes f::"'a::metric_space ⇒ 'b::complete_space"
  assumes uc: "uniformly_continuous_on X f"
  obtains g where "uniformly_continuous_on (closure X) g" "⋀x. x ∈ X ⟹ f x = g x"
    "⋀Y h x. X ⊆ Y ⟹ Y ⊆ closure X ⟹ continuous_on Y h ⟹ (⋀x. x ∈ X ⟹ f x = h x) ⟹ x ∈ Y ⟹ h x = g x"
proof -
  from uc have cont_f: "continuous_on X f"
    by (simp add: uniformly_continuous_imp_continuous)
  obtain y where y: "(f ⤏ y x) (at x within X)" if "x ∈ closure X" for x
    apply atomize_elim
    apply (rule choice)
    using uniformly_continuous_on_extension_at_closure[OF assms]
    by metis
  let ?g = "λx. if x ∈ X then f x else y x"

  have "uniformly_continuous_on (closure X) ?g"
    unfolding uniformly_continuous_on_def
  proof safe
    fix e::real assume "e > 0"
    define e' where "e' ≡ e / 3"
    have "e' > 0" using ‹e > 0› by (simp add: e'_def)
    from uc[unfolded uniformly_continuous_on_def, rule_format, OF ‹0 < e'›]
    obtain d where "d > 0" and d: "⋀x x'. x ∈ X ⟹ x' ∈ X ⟹ dist x' x < d ⟹ dist (f x') (f x) < e'"
      by auto
    define d' where "d' = d / 3"
    have "d' > 0" using ‹d > 0› by (simp add: d'_def)
    show "∃d>0. ∀x∈closure X. ∀x'∈closure X. dist x' x < d ⟶ dist (?g x') (?g x) < e"
    proof (safe intro!: exI[where x=d'] ‹d' > 0›)
      fix x x' assume x: "x ∈ closure X" and x': "x' ∈ closure X" and dist: "dist x' x < d'"
      then obtain xs xs' where xs: "xs ⇢ x" "⋀n. xs n ∈ X"
        and xs': "xs' ⇢ x'" "⋀n. xs' n ∈ X"
        by (auto simp: closure_sequential)
      have "∀F n in sequentially. dist (xs' n) x' < d'"
        and "∀F n in sequentially. dist (xs n) x < d'"
        by (auto intro!: ‹0 < d'› order_tendstoD tendsto_eq_intros xs xs')
      moreover
      have "(λx. f (xs x)) ⇢ y x" if "x ∈ closure X" "x ∉ X" "xs ⇢ x" "⋀n. xs n ∈ X" for xs x
        using that not_eventuallyD
        by (force intro!: filterlim_compose[OF y[OF ‹x ∈ closure X›]] simp: filterlim_at)
      then have "(λx. f (xs' x)) ⇢ ?g x'" "(λx. f (xs x)) ⇢ ?g x"
        using x x'
        by (auto intro!: continuous_on_tendsto_compose[OF cont_f] simp: xs' xs)
      then have "∀F n in sequentially. dist (f (xs' n)) (?g x') < e'"
        "∀F n in sequentially. dist (f (xs n)) (?g x) < e'"
        by (auto intro!: ‹0 < e'› order_tendstoD tendsto_eq_intros)
      ultimately
      have "∀F n in sequentially. dist (?g x') (?g x) < e"
      proof eventually_elim
        case (elim n)
        have "dist (?g x') (?g x) ≤
          dist (f (xs' n)) (?g x') + dist (f (xs' n)) (f (xs n)) + dist (f (xs n)) (?g x)"
          by (metis add.commute add_le_cancel_left dist_commute dist_triangle dist_triangle_le)
        also
        {
          have "dist (xs' n) (xs n) ≤ dist (xs' n) x' + dist x' x + dist (xs n) x"
            by (metis add.commute add_le_cancel_left  dist_triangle dist_triangle_le)
          also note ‹dist (xs' n) x' < d'›
          also note ‹dist x' x < d'›
          also note ‹dist (xs n) x < d'›
          finally have "dist (xs' n) (xs n) < d" by (simp add: d'_def)
        }
        with ‹xs _ ∈ X› ‹xs' _ ∈ X› have "dist (f (xs' n)) (f (xs n)) < e'"
          by (rule d)
        also note ‹dist (f (xs' n)) (?g x') < e'›
        also note ‹dist (f (xs n)) (?g x) < e'›
        finally show ?case by (simp add: e'_def)
      qed
      then show "dist (?g x') (?g x) < e" by simp
    qed
  qed
  moreover have "f x = ?g x" if "x ∈ X" for x using that by simp
  moreover
  {
    fix Y h x
    assume Y: "x ∈ Y" "X ⊆ Y" "Y ⊆ closure X" and cont_h: "continuous_on Y h"
      and extension: "(⋀x. x ∈ X ⟹ f x = h x)"
    {
      assume "x ∉ X"
      have "x ∈ closure X" using Y by auto
      then obtain xs where xs: "xs ⇢ x" "⋀n. xs n ∈ X"
        by (auto simp: closure_sequential)
      from continuous_on_tendsto_compose[OF cont_h xs(1)] xs(2) Y
      have hx: "(λx. f (xs x)) ⇢ h x"
        by (auto simp: set_mp extension)
      then have "(λx. f (xs x)) ⇢ y x"
        using ‹x ∉ X› not_eventuallyD xs(2)
        by (force intro!: filterlim_compose[OF y[OF ‹x ∈ closure X›]] simp: filterlim_at xs)
      with hx have "h x = y x" by (rule LIMSEQ_unique)
    } then
    have "h x = ?g x"
      using extension by auto
  }
  ultimately show ?thesis ..
qed

lemma bounded_uniformly_continuous_image:
  fixes f :: "'a :: heine_borel ⇒ 'b :: heine_borel"
  assumes "uniformly_continuous_on S f" "bounded S"
  shows "bounded(image f S)"
  by (metis (no_types, lifting) assms bounded_closure_image compact_closure compact_continuous_image compact_eq_bounded_closed image_cong uniformly_continuous_imp_continuous uniformly_continuous_on_extension_on_closure)

subsection‹Quotient maps›

lemma quotient_map_imp_continuous_open:
  assumes t: "f ` s ⊆ t"
      and ope: "⋀u. u ⊆ t
              ⟹ (openin (subtopology euclidean s) {x. x ∈ s ∧ f x ∈ u} ⟷
                   openin (subtopology euclidean t) u)"
    shows "continuous_on s f"
proof -
  have [simp]: "{x ∈ s. f x ∈ f ` s} = s" by auto
  show ?thesis
    using ope [OF t]
    apply (simp add: continuous_on_open)
    by (metis (no_types, lifting) "ope"  openin_imp_subset openin_trans)
qed

lemma quotient_map_imp_continuous_closed:
  assumes t: "f ` s ⊆ t"
      and ope: "⋀u. u ⊆ t
                  ⟹ (closedin (subtopology euclidean s) {x. x ∈ s ∧ f x ∈ u} ⟷
                       closedin (subtopology euclidean t) u)"
    shows "continuous_on s f"
proof -
  have [simp]: "{x ∈ s. f x ∈ f ` s} = s" by auto
  show ?thesis
    using ope [OF t]
    apply (simp add: continuous_on_closed)
    by (metis (no_types, lifting) "ope" closedin_imp_subset closedin_subtopology_refl closedin_trans openin_subtopology_refl openin_subtopology_self)
qed

lemma open_map_imp_quotient_map:
  assumes contf: "continuous_on s f"
      and t: "t ⊆ f ` s"
      and ope: "⋀t. openin (subtopology euclidean s) t
                   ⟹ openin (subtopology euclidean (f ` s)) (f ` t)"
    shows "openin (subtopology euclidean s) {x ∈ s. f x ∈ t} =
           openin (subtopology euclidean (f ` s)) t"
proof -
  have "t = image f {x. x ∈ s ∧ f x ∈ t}"
    using t by blast
  then show ?thesis
    using "ope" contf continuous_on_open by fastforce
qed

lemma closed_map_imp_quotient_map:
  assumes contf: "continuous_on s f"
      and t: "t ⊆ f ` s"
      and ope: "⋀t. closedin (subtopology euclidean s) t
              ⟹ closedin (subtopology euclidean (f ` s)) (f ` t)"
    shows "openin (subtopology euclidean s) {x ∈ s. f x ∈ t} ⟷
           openin (subtopology euclidean (f ` s)) t"
          (is "?lhs = ?rhs")
proof
  assume ?lhs
  then have *: "closedin (subtopology euclidean s) (s - {x ∈ s. f x ∈ t})"
    using closedin_diff by fastforce
  have [simp]: "(f ` s - f ` (s - {x ∈ s. f x ∈ t})) = t"
    using t by blast
  show ?rhs
    using ope [OF *, unfolded closedin_def] by auto
next
  assume ?rhs
  with contf show ?lhs
    by (auto simp: continuous_on_open)
qed

lemma continuous_right_inverse_imp_quotient_map:
  assumes contf: "continuous_on s f" and imf: "f ` s ⊆ t"
      and contg: "continuous_on t g" and img: "g ` t ⊆ s"
      and fg [simp]: "⋀y. y ∈ t ⟹ f(g y) = y"
      and u: "u ⊆ t"
    shows "openin (subtopology euclidean s) {x. x ∈ s ∧ f x ∈ u} ⟷
           openin (subtopology euclidean t) u"
          (is "?lhs = ?rhs")
proof -
  have f: "⋀z. openin (subtopology euclidean (f ` s)) z ⟹
                openin (subtopology euclidean s) {x ∈ s. f x ∈ z}"
  and  g: "⋀z. openin (subtopology euclidean (g ` t)) z ⟹
                openin (subtopology euclidean t) {x ∈ t. g x ∈ z}"
    using contf contg by (auto simp: continuous_on_open)
  show ?thesis
  proof
    have "{x ∈ t. g x ∈ g ` t ∧ g x ∈ s ∧ f (g x) ∈ u} = {x ∈ t. f (g x) ∈ u}"
      using imf img by blast
    also have "... = u"
      using u by auto
    finally have [simp]: "{x ∈ t. g x ∈ g ` t ∧ g x ∈ s ∧ f (g x) ∈ u} = u" .
    assume ?lhs
    then have *: "openin (subtopology euclidean (g ` t)) (g ` t ∩ {x ∈ s. f x ∈ u})"
      by (meson img openin_Int openin_subtopology_Int_subset openin_subtopology_self)
    show ?rhs
      using g [OF *] by simp
  next
    assume rhs: ?rhs
    show ?lhs
      apply (rule f)
      by (metis fg image_eqI image_subset_iff imf img openin_subopen openin_subtopology_self openin_trans rhs)
  qed
qed

lemma continuous_left_inverse_imp_quotient_map:
  assumes "continuous_on s f"
      and "continuous_on (f ` s) g"
      and  "⋀x. x ∈ s ⟹ g(f x) = x"
      and "u ⊆ f ` s"
    shows "openin (subtopology euclidean s) {x. x ∈ s ∧ f x ∈ u} ⟷
           openin (subtopology euclidean (f ` s)) u"
apply (rule continuous_right_inverse_imp_quotient_map)
using assms
apply force+
done

subsection ‹A function constant on a set›

definition constant_on  (infixl "(constant'_on)" 50)
  where "f constant_on A ≡ ∃y. ∀x∈A. f x = y"

lemma constant_on_subset: "⟦f constant_on A; B ⊆ A⟧ ⟹ f constant_on B"
  unfolding constant_on_def by blast

lemma injective_not_constant:
  fixes S :: "'a::{perfect_space} set"
  shows "⟦open S; inj_on f S; f constant_on S⟧ ⟹ S = {}"
unfolding constant_on_def
by (metis equals0I inj_on_contraD islimpt_UNIV islimpt_def)

lemma constant_on_closureI:
  fixes f :: "_ ⇒ 'b::t1_space"
  assumes cof: "f constant_on S" and contf: "continuous_on (closure S) f"
    shows "f constant_on (closure S)"
using continuous_constant_on_closure [OF contf] cof unfolding constant_on_def
by metis

text ‹Making a continuous function avoid some value in a neighbourhood.›

lemma continuous_within_avoid:
  fixes f :: "'a::metric_space ⇒ 'b::t1_space"
  assumes "continuous (at x within s) f"
    and "f x ≠ a"
  shows "∃e>0. ∀y ∈ s. dist x y < e --> f y ≠ a"
proof -
  obtain U where "open U" and "f x ∈ U" and "a ∉ U"
    using t1_space [OF ‹f x ≠ a›] by fast
  have "(f ⤏ f x) (at x within s)"
    using assms(1) by (simp add: continuous_within)
  then have "eventually (λy. f y ∈ U) (at x within s)"
    using ‹open U› and ‹f x ∈ U›
    unfolding tendsto_def by fast
  then have "eventually (λy. f y ≠ a) (at x within s)"
    using ‹a ∉ U› by (fast elim: eventually_mono)
  then show ?thesis
    using ‹f x ≠ a› by (auto simp: dist_commute zero_less_dist_iff eventually_at)
qed

lemma continuous_at_avoid:
  fixes f :: "'a::metric_space ⇒ 'b::t1_space"
  assumes "continuous (at x) f"
    and "f x ≠ a"
  shows "∃e>0. ∀y. dist x y < e ⟶ f y ≠ a"
  using assms continuous_within_avoid[of x UNIV f a] by simp

lemma continuous_on_avoid:
  fixes f :: "'a::metric_space ⇒ 'b::t1_space"
  assumes "continuous_on s f"
    and "x ∈ s"
    and "f x ≠ a"
  shows "∃e>0. ∀y ∈ s. dist x y < e ⟶ f y ≠ a"
  using assms(1)[unfolded continuous_on_eq_continuous_within, THEN bspec[where x=x],
    OF assms(2)] continuous_within_avoid[of x s f a]
  using assms(3)
  by auto

lemma continuous_on_open_avoid:
  fixes f :: "'a::metric_space ⇒ 'b::t1_space"
  assumes "continuous_on s f"
    and "open s"
    and "x ∈ s"
    and "f x ≠ a"
  shows "∃e>0. ∀y. dist x y < e ⟶ f y ≠ a"
  using assms(1)[unfolded continuous_on_eq_continuous_at[OF assms(2)], THEN bspec[where x=x], OF assms(3)]
  using continuous_at_avoid[of x f a] assms(4)
  by auto

text ‹Proving a function is constant by proving open-ness of level set.›

lemma continuous_levelset_openin_cases:
  fixes f :: "_ ⇒ 'b::t1_space"
  shows "connected s ⟹ continuous_on s f ⟹
        openin (subtopology euclidean s) {x ∈ s. f x = a}
        ⟹ (∀x ∈ s. f x ≠ a) ∨ (∀x ∈ s. f x = a)"
  unfolding connected_clopen
  using continuous_closedin_preimage_constant by auto

lemma continuous_levelset_openin:
  fixes f :: "_ ⇒ 'b::t1_space"
  shows "connected s ⟹ continuous_on s f ⟹
        openin (subtopology euclidean s) {x ∈ s. f x = a} ⟹
        (∃x ∈ s. f x = a)  ⟹ (∀x ∈ s. f x = a)"
  using continuous_levelset_openin_cases[of s f ]
  by meson

lemma continuous_levelset_open:
  fixes f :: "_ ⇒ 'b::t1_space"
  assumes "connected s"
    and "continuous_on s f"
    and "open {x ∈ s. f x = a}"
    and "∃x ∈ s.  f x = a"
  shows "∀x ∈ s. f x = a"
  using continuous_levelset_openin[OF assms(1,2), of a, unfolded openin_open]
  using assms (3,4)
  by fast

text ‹Some arithmetical combinations (more to prove).›

lemma open_scaling[intro]:
  fixes s :: "'a::real_normed_vector set"
  assumes "c ≠ 0"
    and "open s"
  shows "open((λx. c *R x) ` s)"
proof -
  {
    fix x
    assume "x ∈ s"
    then obtain e where "e>0"
      and e:"∀x'. dist x' x < e ⟶ x' ∈ s" using assms(2)[unfolded open_dist, THEN bspec[where x=x]]
      by auto
    have "e * ¦c¦ > 0"
      using assms(1)[unfolded zero_less_abs_iff[symmetric]] ‹e>0› by auto
    moreover
    {
      fix y
      assume "dist y (c *R x) < e * ¦c¦"
      then have "norm ((1 / c) *R y - x) < e"
        unfolding dist_norm
        using norm_scaleR[of c "(1 / c) *R y - x", unfolded scaleR_right_diff_distrib, unfolded scaleR_scaleR] assms(1)
          assms(1)[unfolded zero_less_abs_iff[symmetric]] by (simp del:zero_less_abs_iff)
      then have "y ∈ op *R c ` s"
        using rev_image_eqI[of "(1 / c) *R y" s y "op *R c"]
        using e[THEN spec[where x="(1 / c) *R y"]]
        using assms(1)
        unfolding dist_norm scaleR_scaleR
        by auto
    }
    ultimately have "∃e>0. ∀x'. dist x' (c *R x) < e ⟶ x' ∈ op *R c ` s"
      apply (rule_tac x="e * ¦c¦" in exI, auto)
      done
  }
  then show ?thesis unfolding open_dist by auto
qed

lemma minus_image_eq_vimage:
  fixes A :: "'a::ab_group_add set"
  shows "(λx. - x) ` A = (λx. - x) -` A"
  by (auto intro!: image_eqI [where f="λx. - x"])

lemma open_negations:
  fixes S :: "'a::real_normed_vector set"
  shows "open S ⟹ open ((λx. - x) ` S)"
  using open_scaling [of "- 1" S] by simp

lemma open_translation:
  fixes S :: "'a::real_normed_vector set"
  assumes "open S"
  shows "open((λx. a + x) ` S)"
proof -
  {
    fix x
    have "continuous (at x) (λx. x - a)"
      by (intro continuous_diff continuous_ident continuous_const)
  }
  moreover have "{x. x - a ∈ S} = op + a ` S"
    by force
  ultimately show ?thesis
    by (metis assms continuous_open_vimage vimage_def)
qed

lemma open_affinity:
  fixes S :: "'a::real_normed_vector set"
  assumes "open S"  "c ≠ 0"
  shows "open ((λx. a + c *R x) ` S)"
proof -
  have *: "(λx. a + c *R x) = (λx. a + x) ∘ (λx. c *R x)"
    unfolding o_def ..
  have "op + a ` op *R c ` S = (op + a ∘ op *R c) ` S"
    by auto
  then show ?thesis
    using assms open_translation[of "op *R c ` S" a]
    unfolding *
    by auto
qed

lemma interior_translation:
  fixes S :: "'a::real_normed_vector set"
  shows "interior ((λx. a + x) ` S) = (λx. a + x) ` (interior S)"
proof (rule set_eqI, rule)
  fix x
  assume "x ∈ interior (op + a ` S)"
  then obtain e where "e > 0" and e: "ball x e ⊆ op + a ` S"
    unfolding mem_interior by auto
  then have "ball (x - a) e ⊆ S"
    unfolding subset_eq Ball_def mem_ball dist_norm
    by (auto simp: diff_diff_eq)
  then show "x ∈ op + a ` interior S"
    unfolding image_iff
    apply (rule_tac x="x - a" in bexI)
    unfolding mem_interior
    using ‹e > 0›
    apply auto
    done
next
  fix x
  assume "x ∈ op + a ` interior S"
  then obtain y e where "e > 0" and e: "ball y e ⊆ S" and y: "x = a + y"
    unfolding image_iff Bex_def mem_interior by auto
  {
    fix z
    have *: "a + y - z = y + a - z" by auto
    assume "z ∈ ball x e"
    then have "z - a ∈ S"
      using e[unfolded subset_eq, THEN bspec[where x="z - a"]]
      unfolding mem_ball dist_norm y group_add_class.diff_diff_eq2 *
      by auto
    then have "z ∈ op + a ` S"
      unfolding image_iff by (auto intro!: bexI[where x="z - a"])
  }
  then have "ball x e ⊆ op + a ` S"
    unfolding subset_eq by auto
  then show "x ∈ interior (op + a ` S)"
    unfolding mem_interior using ‹e > 0› by auto
qed

subsection ‹Topological properties of linear functions.›

lemma linear_lim_0:
  assumes "bounded_linear f"
  shows "(f ⤏ 0) (at (0))"
proof -
  interpret f: bounded_linear f by fact
  have "(f ⤏ f 0) (at 0)"
    using tendsto_ident_at by (rule f.tendsto)
  then show ?thesis unfolding f.zero .
qed

lemma linear_continuous_at:
  assumes "bounded_linear f"
  shows "continuous (at a) f"
  unfolding continuous_at using assms
  apply (rule bounded_linear.tendsto)
  apply (rule tendsto_ident_at)
  done

lemma linear_continuous_within:
  "bounded_linear f ⟹ continuous (at x within s) f"
  using continuous_at_imp_continuous_within[of x f s] using linear_continuous_at[of f] by auto

lemma linear_continuous_on:
  "bounded_linear f ⟹ continuous_on s f"
  using continuous_at_imp_continuous_on[of s f] using linear_continuous_at[of f] by auto

subsubsection‹Relating linear images to open/closed/interior/closure.›

proposition open_surjective_linear_image:
  fixes f :: "'a::real_normed_vector ⇒ 'b::euclidean_space"
  assumes "open A" "linear f" "surj f"
    shows "open(f ` A)"
unfolding open_dist
proof clarify
  fix x
  assume "x ∈ A"
  have "bounded (inv f ` Basis)"
    by (simp add: finite_imp_bounded)
  with bounded_pos obtain B where "B > 0" and B: "⋀x. x ∈ inv f ` Basis ⟹ norm x ≤ B"
    by metis
  obtain e where "e > 0" and e: "⋀z. dist z x < e ⟹ z ∈ A"
    by (metis open_dist ‹x ∈ A› ‹open A›)
  define δ where "δ ≡ e / B / DIM('b)"
  show "∃e>0. ∀y. dist y (f x) < e ⟶ y ∈ f ` A"
  proof (intro exI conjI)
    show "δ > 0"
      using ‹e > 0› ‹B > 0›  by (simp add: δ_def divide_simps)
    have "y ∈ f ` A" if "dist y (f x) * (B * real DIM('b)) < e" for y
    proof -
      define u where "u ≡ y - f x"
      show ?thesis
      proof (rule image_eqI)
        show "y = f (x + (∑i∈Basis. (u ∙ i) *R inv f i))"
          apply (simp add: linear_add linear_sum linear.scaleR ‹linear f› surj_f_inv_f ‹surj f›)
          apply (simp add: euclidean_representation u_def)
          done
        have "dist (x + (∑i∈Basis. (u ∙ i) *R inv f i)) x ≤ (∑i∈Basis. norm ((u ∙ i) *R inv f i))"
          by (simp add: dist_norm sum_norm_le)
        also have "... = (∑i∈Basis. ¦u ∙ i¦ * norm (inv f i))"
          by simp
        also have "... ≤ (∑i∈Basis. ¦u ∙ i¦) * B"
          by (simp add: B sum_distrib_right sum_mono mult_left_mono)
        also have "... ≤ DIM('b) * dist y (f x) * B"
          apply (rule mult_right_mono [OF sum_bounded_above])
          using ‹0 < B› by (auto simp: Basis_le_norm dist_norm u_def)
        also have "... < e"
          by (metis mult.commute mult.left_commute that)
        finally show "x + (∑i∈Basis. (u ∙ i) *R inv f i) ∈ A"
          by (rule e)
      qed
    qed
    then show "∀y. dist y (f x) < δ ⟶ y ∈ f ` A"
      using ‹e > 0› ‹B > 0›
      by (auto simp: δ_def divide_simps mult_less_0_iff)
  qed
qed

corollary open_bijective_linear_image_eq:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "linear f" "bij f"
    shows "open(f ` A) ⟷ open A"
proof
  assume "open(f ` A)"
  then have "open(f -` (f ` A))"
    using assms by (force simp: linear_continuous_at linear_conv_bounded_linear continuous_open_vimage)
  then show "open A"
    by (simp add: assms bij_is_inj inj_vimage_image_eq)
next
  assume "open A"
  then show "open(f ` A)"
    by (simp add: assms bij_is_surj open_surjective_linear_image)
qed

corollary interior_bijective_linear_image:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "linear f" "bij f"
  shows "interior (f ` S) = f ` interior S"  (is "?lhs = ?rhs")
proof safe
  fix x
  assume x: "x ∈ ?lhs"
  then obtain T where "open T" and "x ∈ T" and "T ⊆ f ` S"
    by (metis interiorE)
  then show "x ∈ ?rhs"
    by (metis (no_types, hide_lams) assms subsetD interior_maximal open_bijective_linear_image_eq subset_image_iff)
next
  fix x
  assume x: "x ∈ interior S"
  then show "f x ∈ interior (f ` S)"
    by (meson assms imageI image_mono interiorI interior_subset open_bijective_linear_image_eq open_interior)
qed

lemma interior_injective_linear_image:
  fixes f :: "'a::euclidean_space ⇒ 'a::euclidean_space"
  assumes "linear f" "inj f"
   shows "interior(f ` S) = f ` (interior S)"
  by (simp add: linear_injective_imp_surjective assms bijI interior_bijective_linear_image)

lemma interior_surjective_linear_image:
  fixes f :: "'a::euclidean_space ⇒ 'a::euclidean_space"
  assumes "linear f" "surj f"
   shows "interior(f ` S) = f ` (interior S)"
  by (simp add: assms interior_injective_linear_image linear_surjective_imp_injective)

lemma interior_negations:
  fixes S :: "'a::euclidean_space set"
  shows "interior(uminus ` S) = image uminus (interior S)"
  by (simp add: bij_uminus interior_bijective_linear_image linear_uminus)

text ‹Also bilinear functions, in composition form.›

lemma bilinear_continuous_at_compose:
  "continuous (at x) f ⟹ continuous (at x) g ⟹ bounded_bilinear h ⟹
    continuous (at x) (λx. h (f x) (g x))"
  unfolding continuous_at
  using Lim_bilinear[of f "f x" "(at x)" g "g x" h]
  by auto

lemma bilinear_continuous_within_compose:
  "continuous (at x within s) f ⟹ continuous (at x within s) g ⟹ bounded_bilinear h ⟹
    continuous (at x within s) (λx. h (f x) (g x))"
  by (rule Limits.bounded_bilinear.continuous)

lemma bilinear_continuous_on_compose:
  "continuous_on s f ⟹ continuous_on s g ⟹ bounded_bilinear h ⟹
    continuous_on s (λx. h (f x) (g x))"
  by (rule Limits.bounded_bilinear.continuous_on)

text ‹Preservation of compactness and connectedness under continuous function.›

lemma compact_eq_openin_cover:
  "compact S ⟷
    (∀C. (∀c∈C. openin (subtopology euclidean S) c) ∧ S ⊆ ⋃C ⟶
      (∃D⊆C. finite D ∧ S ⊆ ⋃D))"
proof safe
  fix C
  assume "compact S" and "∀c∈C. openin (subtopology euclidean S) c" and "S ⊆ ⋃C"
  then have "∀c∈{T. open T ∧ S ∩ T ∈ C}. open c" and "S ⊆ ⋃{T. open T ∧ S ∩ T ∈ C}"
    unfolding openin_open by force+
  with ‹compact S› obtain D where "D ⊆ {T. open T ∧ S ∩ T ∈ C}" and "finite D" and "S ⊆ ⋃D"
    by (meson compactE)
  then have "image (λT. S ∩ T) D ⊆ C ∧ finite (image (λT. S ∩ T) D) ∧ S ⊆ ⋃(image (λT. S ∩ T) D)"
    by auto
  then show "∃D⊆C. finite D ∧ S ⊆ ⋃D" ..
next
  assume 1: "∀C. (∀c∈C. openin (subtopology euclidean S) c) ∧ S ⊆ ⋃C ⟶
        (∃D⊆C. finite D ∧ S ⊆ ⋃D)"
  show "compact S"
  proof (rule compactI)
    fix C
    let ?C = "image (λT. S ∩ T) C"
    assume "∀t∈C. open t" and "S ⊆ ⋃C"
    then have "(∀c∈?C. openin (subtopology euclidean S) c) ∧ S ⊆ ⋃?C"
      unfolding openin_open by auto
    with 1 obtain D where "D ⊆ ?C" and "finite D" and "S ⊆ ⋃D"
      by metis
    let ?D = "inv_into C (λT. S ∩ T) ` D"
    have "?D ⊆ C ∧ finite ?D ∧ S ⊆ ⋃?D"
    proof (intro conjI)
      from ‹D ⊆ ?C› show "?D ⊆ C"
        by (fast intro: inv_into_into)
      from ‹finite D› show "finite ?D"
        by (rule finite_imageI)
      from ‹S ⊆ ⋃D› show "S ⊆ ⋃?D"
        apply (rule subset_trans, clarsimp)
        apply (frule subsetD [OF ‹D ⊆ ?C›, THEN f_inv_into_f])
        apply (erule rev_bexI, fast)
        done
    qed
    then show "∃D⊆C. finite D ∧ S ⊆ ⋃D" ..
  qed
qed

lemma connected_continuous_image:
  assumes "continuous_on s f"
    and "connected s"
  shows "connected(f ` s)"
proof -
  {
    fix T
    assume as:
      "T ≠ {}"
      "T ≠ f ` s"
      "openin (subtopology euclidean (f ` s)) T"
      "closedin (subtopology euclidean (f ` s)) T"
    have "{x ∈ s. f x ∈ T} = {} ∨ {x ∈ s. f x ∈ T} = s"
      using assms(1)[unfolded continuous_on_open, THEN spec[where x=T]]
      using assms(1)[unfolded continuous_on_closed, THEN spec[where x=T]]
      using assms(2)[unfolded connected_clopen, THEN spec[where x="{x ∈ s. f x ∈ T}"]] as(3,4) by auto
    then have False using as(1,2)
      using as(4)[unfolded closedin_def topspace_euclidean_subtopology] by auto
  }
  then show ?thesis
    unfolding connected_clopen by auto
qed

lemma connected_linear_image:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "linear f" and "connected s"
  shows "connected (f ` s)"
using connected_continuous_image assms linear_continuous_on linear_conv_bounded_linear by blast

text ‹Continuity implies uniform continuity on a compact domain.›

subsection ‹Continuity implies uniform continuity on a compact domain.›

text‹From the proof of the Heine-Borel theorem: Lemma 2 in section 3.7, page 69 of
J. C. Burkill and H. Burkill. A Second Course in Mathematical Analysis (CUP, 2002)›

lemma Heine_Borel_lemma:
  assumes "compact S" and Ssub: "S ⊆ ⋃𝒢" and op: "⋀G. G ∈ 𝒢 ⟹ open G"
  obtains e where "0 < e" "⋀x. x ∈ S ⟹ ∃G ∈ 𝒢. ball x e ⊆ G"
proof -
  have False if neg: "⋀e. 0 < e ⟹ ∃x ∈ S. ∀G ∈ 𝒢. ¬ ball x e ⊆ G"
  proof -
    have "∃x ∈ S. ∀G ∈ 𝒢. ¬ ball x (1 / Suc n) ⊆ G" for n
      using neg by simp
    then obtain f where "⋀n. f n ∈ S" and fG: "⋀G n. G ∈ 𝒢 ⟹ ¬ ball (f n) (1 / Suc n) ⊆ G"
      by metis
    then obtain l r where "l ∈ S" "strict_mono r" and to_l: "(f ∘ r) ⇢ l"
      using ‹compact S› compact_def that by metis
    then obtain G where "l ∈ G" "G ∈ 𝒢"
      using Ssub by auto
    then obtain e where "0 < e" and e: "⋀z. dist z l < e ⟹ z ∈ G"
      using op open_dist by blast
    obtain N1 where N1: "⋀n. n ≥ N1 ⟹ dist (f (r n)) l < e/2"
      using to_l apply (simp add: lim_sequentially)
      using ‹0 < e› half_gt_zero that by blast
    obtain N2 where N2: "of_nat N2 > 2/e"
      using reals_Archimedean2 by blast
    obtain x where "x ∈ ball (f (r (max N1 N2))) (1 / real (Suc (r (max N1 N2))))" and "x ∉ G"
      using fG [OF ‹G ∈ 𝒢›, of "r (max N1 N2)"] by blast
    then have "dist (f (r (max N1 N2))) x < 1 / real (Suc (r (max N1 N2)))"
      by simp
    also have "... ≤ 1 / real (Suc (max N1 N2))"
      apply (simp add: divide_simps del: max.bounded_iff)
      using ‹strict_mono r› seq_suble by blast
    also have "... ≤ 1 / real (Suc N2)"
      by (simp add: field_simps)
    also have "... < e/2"
      using N2 ‹0 < e› by (simp add: field_simps)
    finally have "dist (f (r (max N1 N2))) x < e / 2" .
    moreover have "dist (f (r (max N1 N2))) l < e/2"
      using N1 max.cobounded1 by blast
    ultimately have "dist x l < e"
      using dist_triangle_half_r by blast
    then show ?thesis
      using e ‹x ∉ G› by blast
  qed
  then show ?thesis
    by (meson that)
qed

lemma compact_uniformly_equicontinuous:
  assumes "compact S"
      and cont: "⋀x e. ⟦x ∈ S; 0 < e⟧
                        ⟹ ∃d. 0 < d ∧
                                (∀f ∈ ℱ. ∀x' ∈ S. dist x' x < d ⟶ dist (f x') (f x) < e)"
      and "0 < e"
  obtains d where "0 < d"
                  "⋀f x x'. ⟦f ∈ ℱ; x ∈ S; x' ∈ S; dist x' x < d⟧ ⟹ dist (f x') (f x) < e"
proof -
  obtain d where d_pos: "⋀x e. ⟦x ∈ S; 0 < e⟧ ⟹ 0 < d x e"
     and d_dist : "⋀x x' e f. ⟦dist x' x < d x e; x ∈ S; x' ∈ S; 0 < e; f ∈ ℱ⟧ ⟹ dist (f x') (f x) < e"
    using cont by metis
  let ?𝒢 = "((λx. ball x (d x (e / 2))) ` S)"
  have Ssub: "S ⊆ ⋃ ?𝒢"
    by clarsimp (metis d_pos ‹0 < e› dist_self half_gt_zero_iff)
  then obtain k where "0 < k" and k: "⋀x. x ∈ S ⟹ ∃G ∈ ?𝒢. ball x k ⊆ G"
    by (rule Heine_Borel_lemma [OF ‹compact S›]) auto
  moreover have "dist (f v) (f u) < e" if "f ∈ ℱ" "u ∈ S" "v ∈ S" "dist v u < k" for f u v
  proof -
    obtain G where "G ∈ ?𝒢" "u ∈ G" "v ∈ G"
      using k that
      by (metis ‹dist v u < k› ‹u ∈ S› ‹0 < k› centre_in_ball subsetD dist_commute mem_ball)
    then obtain w where w: "dist w u < d w (e / 2)" "dist w v < d w (e / 2)" "w ∈ S"
      by auto
    with that d_dist have "dist (f w) (f v) < e/2"
      by (metis ‹0 < e› dist_commute half_gt_zero)
    moreover
    have "dist (f w) (f u) < e/2"
      using that d_dist w by (metis ‹0 < e› dist_commute divide_pos_pos zero_less_numeral)
    ultimately show ?thesis
      using dist_triangle_half_r by blast
  qed
  ultimately show ?thesis using that by blast
qed

corollary compact_uniformly_continuous:
  fixes f :: "'a :: metric_space ⇒ 'b :: metric_space"
  assumes f: "continuous_on S f" and S: "compact S"
  shows "uniformly_continuous_on S f"
  using f
    unfolding continuous_on_iff uniformly_continuous_on_def
    by (force intro: compact_uniformly_equicontinuous [OF S, of "{f}"])

subsection ‹Topological stuff about the set of Reals›

lemma open_real:
  fixes s :: "real set"
  shows "open s ⟷ (∀x ∈ s. ∃e>0. ∀x'. ¦x' - x¦ < e --> x' ∈ s)"
  unfolding open_dist dist_norm by simp

lemma islimpt_approachable_real:
  fixes s :: "real set"
  shows "x islimpt s ⟷ (∀e>0. ∃x'∈ s. x' ≠ x ∧ ¦x' - x¦ < e)"
  unfolding islimpt_approachable dist_norm by simp

lemma closed_real:
  fixes s :: "real set"
  shows "closed s ⟷ (∀x. (∀e>0.  ∃x' ∈ s. x' ≠ x ∧ ¦x' - x¦ < e) ⟶ x ∈ s)"
  unfolding closed_limpt islimpt_approachable dist_norm by simp

lemma continuous_at_real_range:
  fixes f :: "'a::real_normed_vector ⇒ real"
  shows "continuous (at x) f ⟷ (∀e>0. ∃d>0. ∀x'. norm(x' - x) < d --> ¦f x' - f x¦ < e)"
  unfolding continuous_at
  unfolding Lim_at
  unfolding dist_norm
  apply auto
  apply (erule_tac x=e in allE, auto)
  apply (rule_tac x=d in exI, auto)
  apply (erule_tac x=x' in allE, auto)
  apply (erule_tac x=e in allE, auto)
  done

lemma continuous_on_real_range:
  fixes f :: "'a::real_normed_vector ⇒ real"
  shows "continuous_on s f ⟷
    (∀x ∈ s. ∀e>0. ∃d>0. (∀x' ∈ s. norm(x' - x) < d ⟶ ¦f x' - f x¦ < e))"
  unfolding continuous_on_iff dist_norm by simp

text ‹Hence some handy theorems on distance, diameter etc. of/from a set.›

lemma distance_attains_sup:
  assumes "compact s" "s ≠ {}"
  shows "∃x∈s. ∀y∈s. dist a y ≤ dist a x"
proof (rule continuous_attains_sup [OF assms])
  {
    fix x
    assume "x∈s"
    have "(dist a ⤏ dist a x) (at x within s)"
      by (intro tendsto_dist tendsto_const tendsto_ident_at)
  }
  then show "continuous_on s (dist a)"
    unfolding continuous_on ..
qed

text ‹For \emph{minimal} distance, we only need closure, not compactness.›

lemma distance_attains_inf:
  fixes a :: "'a::heine_borel"
  assumes "closed s" and "s ≠ {}"
  obtains x where "x∈s" "⋀y. y ∈ s ⟹ dist a x ≤ dist a y"
proof -
  from assms obtain b where "b ∈ s" by auto
  let ?B = "s ∩ cball a (dist b a)"
  have "?B ≠ {}" using ‹b ∈ s›
    by (auto simp: dist_commute)
  moreover have "continuous_on ?B (dist a)"
    by (auto intro!: continuous_at_imp_continuous_on continuous_dist continuous_ident continuous_const)
  moreover have "compact ?B"
    by (intro closed_Int_compact ‹closed s› compact_cball)
  ultimately obtain x where "x ∈ ?B" "∀y∈?B. dist a x ≤ dist a y"
    by (metis continuous_attains_inf)
  with that show ?thesis by fastforce
qed


subsection ‹Cartesian products›

lemma bounded_Times:
  assumes "bounded s" "bounded t"
  shows "bounded (s × t)"
proof -
  obtain x y a b where "∀z∈s. dist x z ≤ a" "∀z∈t. dist y z ≤ b"
    using assms [unfolded bounded_def] by auto
  then have "∀z∈s × t. dist (x, y) z ≤ sqrt (a2 + b2)"
    by (auto simp: dist_Pair_Pair real_sqrt_le_mono add_mono power_mono)
  then show ?thesis unfolding bounded_any_center [where a="(x, y)"] by auto
qed

lemma mem_Times_iff: "x ∈ A × B ⟷ fst x ∈ A ∧ snd x ∈ B"
  by (induct x) simp

lemma seq_compact_Times: "seq_compact s ⟹ seq_compact t ⟹ seq_compact (s × t)"
  unfolding seq_compact_def
  apply clarify
  apply (drule_tac x="fst ∘ f" in spec)
  apply (drule mp, simp add: mem_Times_iff)
  apply (clarify, rename_tac l1 r1)
  apply (drule_tac x="snd ∘ f ∘ r1" in spec)
  apply (drule mp, simp add: mem_Times_iff)
  apply (clarify, rename_tac l2 r2)
  apply (rule_tac x="(l1, l2)" in rev_bexI, simp)
  apply (rule_tac x="r1 ∘ r2" in exI)
  apply (rule conjI, simp add: strict_mono_def)
  apply (drule_tac f=r2 in LIMSEQ_subseq_LIMSEQ, assumption)
  apply (drule (1) tendsto_Pair) back
  apply (simp add: o_def)
  done

lemma compact_Times:
  assumes "compact s" "compact t"
  shows "compact (s × t)"
proof (rule compactI)
  fix C
  assume C: "∀t∈C. open t" "s × t ⊆ ⋃C"
  have "∀x∈s. ∃a. open a ∧ x ∈ a ∧ (∃d⊆C. finite d ∧ a × t ⊆ ⋃d)"
  proof
    fix x
    assume "x ∈ s"
    have "∀y∈t. ∃a b c. c ∈ C ∧ open a ∧ open b ∧ x ∈ a ∧ y ∈ b ∧ a × b ⊆ c" (is "∀y∈t. ?P y")
    proof
      fix y
      assume "y ∈ t"
      with ‹x ∈ s› C obtain c where "c ∈ C" "(x, y) ∈ c" "open c" by auto
      then show "?P y" by (auto elim!: open_prod_elim)
    qed
    then obtain a b c where b: "⋀y. y ∈ t ⟹ open (b y)"
      and c: "⋀y. y ∈ t ⟹ c y ∈ C ∧ open (a y) ∧ open (b y) ∧ x ∈ a y ∧ y ∈ b y ∧ a y × b y ⊆ c y"
      by metis
    then have "∀y∈t. open (b y)" "t ⊆ (⋃y∈t. b y)" by auto
    with compactE_image[OF ‹compact t›] obtain D where D: "D ⊆ t" "finite D" "t ⊆ (⋃y∈D. b y)"
      by metis
    moreover from D c have "(⋂y∈D. a y) × t ⊆ (⋃y∈D. c y)"
      by (fastforce simp: subset_eq)
    ultimately show "∃a. open a ∧ x ∈ a ∧ (∃d⊆C. finite d ∧ a × t ⊆ ⋃d)"
      using c by (intro exI[of _ "c`D"] exI[of _ "⋂(a`D)"] conjI) (auto intro!: open_INT)
  qed
  then obtain a d where a: "⋀x. x∈s ⟹ open (a x)" "s ⊆ (⋃x∈s. a x)"
    and d: "⋀x. x ∈ s ⟹ d x ⊆ C ∧ finite (d x) ∧ a x × t ⊆ ⋃d x"
    unfolding subset_eq UN_iff by metis
  moreover
  from compactE_image[OF ‹compact s› a]
  obtain e where e: "e ⊆ s" "finite e" and s: "s ⊆ (⋃x∈e. a x)"
    by auto
  moreover
  {
    from s have "s × t ⊆ (⋃x∈e. a x × t)"
      by auto
    also have "… ⊆ (⋃x∈e. ⋃d x)"
      using d ‹e ⊆ s› by (intro UN_mono) auto
    finally have "s × t ⊆ (⋃x∈e. ⋃d x)" .
  }
  ultimately show "∃C'⊆C. finite C' ∧ s × t ⊆ ⋃C'"
    by (intro exI[of _ "(⋃x∈e. d x)"]) (auto simp: subset_eq)
qed

text‹Hence some useful properties follow quite easily.›

lemma compact_scaling:
  fixes s :: "'a::real_normed_vector set"
  assumes "compact s"
  shows "compact ((λx. c *R x) ` s)"
proof -
  let ?f = "λx. scaleR c x"
  have *: "bounded_linear ?f" by (rule bounded_linear_scaleR_right)
  show ?thesis
    using compact_continuous_image[of s ?f] continuous_at_imp_continuous_on[of s ?f]
    using linear_continuous_at[OF *] assms
    by auto
qed

lemma compact_negations:
  fixes s :: "'a::real_normed_vector set"
  assumes "compact s"
  shows "compact ((λx. - x) ` s)"
  using compact_scaling [OF assms, of "- 1"] by auto

lemma compact_sums:
  fixes s t :: "'a::real_normed_vector set"
  assumes "compact s"
    and "compact t"
  shows "compact {x + y | x y. x ∈ s ∧ y ∈ t}"
proof -
  have *: "{x + y | x y. x ∈ s ∧ y ∈ t} = (λz. fst z + snd z) ` (s × t)"
    apply auto
    unfolding image_iff
    apply (rule_tac x="(xa, y)" in bexI)
    apply auto
    done
  have "continuous_on (s × t) (λz. fst z + snd z)"
    unfolding continuous_on by (rule ballI) (intro tendsto_intros)
  then show ?thesis
    unfolding * using compact_continuous_image compact_Times [OF assms] by auto
qed

lemma compact_differences:
  fixes s t :: "'a::real_normed_vector set"
  assumes "compact s"
    and "compact t"
  shows "compact {x - y | x y. x ∈ s ∧ y ∈ t}"
proof-
  have "{x - y | x y. x∈s ∧ y ∈ t} =  {x + y | x y. x ∈ s ∧ y ∈ (uminus ` t)}"
    apply auto
    apply (rule_tac x= xa in exI, auto)
    done
  then show ?thesis
    using compact_sums[OF assms(1) compact_negations[OF assms(2)]] by auto
qed

lemma compact_translation:
  fixes s :: "'a::real_normed_vector set"
  assumes "compact s"
  shows "compact ((λx. a + x) ` s)"
proof -
  have "{x + y |x y. x ∈ s ∧ y ∈ {a}} = (λx. a + x) ` s"
    by auto
  then show ?thesis
    using compact_sums[OF assms compact_sing[of a]] by auto
qed

lemma compact_affinity:
  fixes s :: "'a::real_normed_vector set"
  assumes "compact s"
  shows "compact ((λx. a + c *R x) ` s)"
proof -
  have "op + a ` op *R c ` s = (λx. a + c *R x) ` s"
    by auto
  then show ?thesis
    using compact_translation[OF compact_scaling[OF assms], of a c] by auto
qed

text ‹Hence we get the following.›

lemma compact_sup_maxdistance:
  fixes s :: "'a::metric_space set"
  assumes "compact s"
    and "s ≠ {}"
  shows "∃x∈s. ∃y∈s. ∀u∈s. ∀v∈s. dist u v ≤ dist x y"
proof -
  have "compact (s × s)"
    using ‹compact s› by (intro compact_Times)
  moreover have "s × s ≠ {}"
    using ‹s ≠ {}› by auto
  moreover have "continuous_on (s × s) (λx. dist (fst x) (snd x))"
    by (intro continuous_at_imp_continuous_on ballI continuous_intros)
  ultimately show ?thesis
    using continuous_attains_sup[of "s × s" "λx. dist (fst x) (snd x)"] by auto
qed

subsection ‹The diameter of a set.›

definition diameter :: "'a::metric_space set ⇒ real" where
  "diameter S = (if S = {} then 0 else SUP (x,y):S×S. dist x y)"

lemma diameter_empty [simp]: "diameter{} = 0"
  by (auto simp: diameter_def)

lemma diameter_singleton [simp]: "diameter{x} = 0"
  by (auto simp: diameter_def)

lemma diameter_le:
  assumes "S ≠ {} ∨ 0 ≤ d"
      and no: "⋀x y. ⟦x ∈ S; y ∈ S⟧ ⟹ norm(x - y) ≤ d"
    shows "diameter S ≤ d"
using assms
  by (auto simp: dist_norm diameter_def intro: cSUP_least)

lemma diameter_bounded_bound:
  fixes s :: "'a :: metric_space set"
  assumes s: "bounded s" "x ∈ s" "y ∈ s"
  shows "dist x y ≤ diameter s"
proof -
  from s obtain z d where z: "⋀x. x ∈ s ⟹ dist z x ≤ d"
    unfolding bounded_def by auto
  have "bdd_above (case_prod dist ` (s×s))"
  proof (intro bdd_aboveI, safe)
    fix a b
    assume "a ∈ s" "b ∈ s"
    with z[of a] z[of b] dist_triangle[of a b z]
    show "dist a b ≤ 2 * d"
      by (simp add: dist_commute)
  qed
  moreover have "(x,y) ∈ s×s" using s by auto
  ultimately have "dist x y ≤ (SUP (x,y):s×s. dist x y)"
    by (rule cSUP_upper2) simp
  with ‹x ∈ s› show ?thesis
    by (auto simp: diameter_def)
qed

lemma diameter_lower_bounded:
  fixes s :: "'a :: metric_space set"
  assumes s: "bounded s"
    and d: "0 < d" "d < diameter s"
  shows "∃x∈s. ∃y∈s. d < dist x y"
proof (rule ccontr)
  assume contr: "¬ ?thesis"
  moreover have "s ≠ {}"
    using d by (auto simp: diameter_def)
  ultimately have "diameter s ≤ d"
    by (auto simp: not_less diameter_def intro!: cSUP_least)
  with ‹d < diameter s› show False by auto
qed

lemma diameter_bounded:
  assumes "bounded s"
  shows "∀x∈s. ∀y∈s. dist x y ≤ diameter s"
    and "∀d>0. d < diameter s ⟶ (∃x∈s. ∃y∈s. dist x y > d)"
  using diameter_bounded_bound[of s] diameter_lower_bounded[of s] assms
  by auto

lemma diameter_compact_attained:
  assumes "compact s"
    and "s ≠ {}"
  shows "∃x∈s. ∃y∈s. dist x y = diameter s"
proof -
  have b: "bounded s" using assms(1)
    by (rule compact_imp_bounded)
  then obtain x y where xys: "x∈s" "y∈s"
    and xy: "∀u∈s. ∀v∈s. dist u v ≤ dist x y"
    using compact_sup_maxdistance[OF assms] by auto
  then have "diameter s ≤ dist x y"
    unfolding diameter_def
    apply clarsimp
    apply (rule cSUP_least, fast+)
    done
  then show ?thesis
    by (metis b diameter_bounded_bound order_antisym xys)
qed

lemma diameter_ge_0:
  assumes "bounded S"  shows "0 ≤ diameter S"
  by (metis all_not_in_conv assms diameter_bounded_bound diameter_empty dist_self order_refl)

lemma diameter_subset:
  assumes "S ⊆ T" "bounded T"
  shows "diameter S ≤ diameter T"
proof (cases "S = {} ∨ T = {}")
  case True
  with assms show ?thesis
    by (force simp: diameter_ge_0)
next
  case False
  then have "bdd_above ((λx. case x of (x, xa) ⇒ dist x xa) ` (T × T))"
    using ‹bounded T› diameter_bounded_bound by (force simp: bdd_above_def)
  with False ‹S ⊆ T› show ?thesis
    apply (simp add: diameter_def)
    apply (rule cSUP_subset_mono, auto)
    done
qed

lemma diameter_closure:
  assumes "bounded S"
  shows "diameter(closure S) = diameter S"
proof (rule order_antisym)
  have "False" if "diameter S < diameter (closure S)"
  proof -
    define d where "d = diameter(closure S) - diameter(S)"
    have "d > 0"
      using that by (simp add: d_def)
    then have "diameter(closure(S)) - d / 2 < diameter(closure(S))"
      by simp
    have dd: "diameter (closure S) - d / 2 = (diameter(closure(S)) + diameter(S)) / 2"
      by (simp add: d_def divide_simps)
     have bocl: "bounded (closure S)"
      using assms by blast
    moreover have "0 ≤ diameter S"
      using assms diameter_ge_0 by blast
    ultimately obtain x y where "x ∈ closure S" "y ∈ closure S" and xy: "diameter(closure(S)) - d / 2 < dist x y"
      using diameter_bounded(2) [OF bocl, rule_format, of "diameter(closure(S)) - d / 2"] ‹d > 0› d_def by auto
    then obtain x' y' where x'y': "x' ∈ S" "dist x' x < d/4" "y' ∈ S" "dist y' y < d/4"
      using closure_approachable
      by (metis ‹0 < d› zero_less_divide_iff zero_less_numeral)
    then have "dist x' y' ≤ diameter S"
      using assms diameter_bounded_bound by blast
    with x'y' have "dist x y ≤ d / 4 + diameter S + d / 4"
      by (meson add_mono_thms_linordered_semiring(1) dist_triangle dist_triangle3 less_eq_real_def order_trans)
    then show ?thesis
      using xy d_def by linarith
  qed
  then show "diameter (closure S) ≤ diameter S"
    by fastforce
  next
    show "diameter S ≤ diameter (closure S)"
      by (simp add: assms bounded_closure closure_subset diameter_subset)
qed

lemma diameter_cball [simp]:
  fixes a :: "'a::euclidean_space"
  shows "diameter(cball a r) = (if r < 0 then 0 else 2*r)"
proof -
  have "diameter(cball a r) = 2*r" if "r ≥ 0"
  proof (rule order_antisym)
    show "diameter (cball a r) ≤ 2*r"
    proof (rule diameter_le)
      fix x y assume "x ∈ cball a r" "y ∈ cball a r"
      then have "norm (x - a) ≤ r" "norm (a - y) ≤ r"
        by (auto simp: dist_norm norm_minus_commute)
      then have "norm (x - y) ≤ r+r"
        using norm_diff_triangle_le by blast
      then show "norm (x - y) ≤ 2*r" by simp
    qed (simp add: that)
    have "2*r = dist (a + r *R (SOME i. i ∈ Basis)) (a - r *R (SOME i. i ∈ Basis))"
      apply (simp add: dist_norm)
      by (metis abs_of_nonneg mult.right_neutral norm_numeral norm_scaleR norm_some_Basis real_norm_def scaleR_2 that)
    also have "... ≤ diameter (cball a r)"
      apply (rule diameter_bounded_bound)
      using that by (auto simp: dist_norm)
    finally show "2*r ≤ diameter (cball a r)" .
  qed
  then show ?thesis by simp
qed

lemma diameter_ball [simp]:
  fixes a :: "'a::euclidean_space"
  shows "diameter(ball a r) = (if r < 0 then 0 else 2*r)"
proof -
  have "diameter(ball a r) = 2*r" if "r > 0"
    by (metis bounded_ball diameter_closure closure_ball diameter_cball less_eq_real_def linorder_not_less that)
  then show ?thesis
    by (simp add: diameter_def)
qed

lemma diameter_closed_interval [simp]: "diameter {a..b} = (if b < a then 0 else b-a)"
proof -
  have "{a .. b} = cball ((a+b)/2) ((b-a)/2)"
    by (auto simp: dist_norm abs_if divide_simps split: if_split_asm)
  then show ?thesis
    by simp
qed

lemma diameter_open_interval [simp]: "diameter {a<..<b} = (if b < a then 0 else b-a)"
proof -
  have "{a <..< b} = ball ((a+b)/2) ((b-a)/2)"
    by (auto simp: dist_norm abs_if divide_simps split: if_split_asm)
  then show ?thesis
    by simp
qed

proposition Lebesgue_number_lemma:
  assumes "compact S" "𝒞 ≠ {}" "S ⊆ ⋃𝒞" and ope: "⋀B. B ∈ 𝒞 ⟹ open B"
  obtains δ where "0 < δ" "⋀T. ⟦T ⊆ S; diameter T < δ⟧ ⟹ ∃B ∈ 𝒞. T ⊆ B"
proof (cases "S = {}")
  case True
  then show ?thesis
    by (metis ‹𝒞 ≠ {}› zero_less_one empty_subsetI equals0I subset_trans that)
next
  case False
  { fix x assume "x ∈ S"
    then obtain C where C: "x ∈ C" "C ∈ 𝒞"
      using ‹S ⊆ ⋃𝒞› by blast
    then obtain r where r: "r>0" "ball x (2*r) ⊆ C"
      by (metis mult.commute mult_2_right not_le ope openE real_sum_of_halves zero_le_numeral zero_less_mult_iff)
    then have "∃r C. r > 0 ∧ ball x (2*r) ⊆ C ∧ C ∈ 𝒞"
      using C by blast
  }
  then obtain r where r: "⋀x. x ∈ S ⟹ r x > 0 ∧ (∃C ∈ 𝒞. ball x (2*r x) ⊆ C)"
    by metis
  then have "S ⊆ (⋃x ∈ S. ball x (r x))"
    by auto
  then obtain 𝒯 where "finite 𝒯" "S ⊆ ⋃𝒯" and 𝒯: "𝒯 ⊆ (λx. ball x (r x)) ` S"
    by (rule compactE [OF ‹compact S›]) auto
  then obtain S0 where "S0 ⊆ S" "finite S0" and S0: "𝒯 = (λx. ball x (r x)) ` S0"
    by (meson finite_subset_image)
  then have "S0 ≠ {}"
    using False ‹S ⊆ ⋃𝒯› by auto
  define δ where "δ = Inf (r ` S0)"
  have "δ > 0"
    using ‹finite S0› ‹S0 ⊆ S› ‹S0 ≠ {}› r by (auto simp: δ_def finite_less_Inf_iff)
  show ?thesis
  proof
    show "0 < δ"
      by (simp add: ‹0 < δ›)
    show "∃B ∈ 𝒞. T ⊆ B" if "T ⊆ S" and dia: "diameter T < δ" for T
    proof (cases "T = {}")
      case True
      then show ?thesis
        using ‹𝒞 ≠ {}› by blast
    next
      case False
      then obtain y where "y ∈ T" by blast
      then have "y ∈ S"
        using ‹T ⊆ S› by auto
      then obtain x where "x ∈ S0" and x: "y ∈ ball x (r x)"
        using ‹S ⊆ ⋃𝒯› S0 that by blast
      have "ball y δ ⊆ ball y (r x)"
        by (metis δ_def ‹S0 ≠ {}› ‹finite S0› ‹x ∈ S0› empty_is_image finite_imageI finite_less_Inf_iff imageI less_irrefl not_le subset_ball)
      also have "... ⊆ ball x (2*r x)"
        by clarsimp (metis dist_commute dist_triangle_less_add mem_ball mult_2 x)
      finally obtain C where "C ∈ 𝒞" "ball y δ ⊆ C"
        by (meson r ‹S0 ⊆ S› ‹x ∈ S0› dual_order.trans subsetCE)
      have "bounded T"
        using ‹compact S› bounded_subset compact_imp_bounded ‹T ⊆ S› by blast
      then have "T ⊆ ball y δ"
        using ‹y ∈ T› dia diameter_bounded_bound by fastforce
      then show ?thesis
        apply (rule_tac x=C in bexI)
        using ‹ball y δ ⊆ C› ‹C ∈ 𝒞› by auto
    qed
  qed
qed


subsection ‹Compact sets and the closure operation.›

lemma closed_scaling:
  fixes S :: "'a::real_normed_vector set"
  assumes "closed S"
  shows "closed ((λx. c *R x) ` S)"
proof (cases "c = 0")
  case True then show ?thesis
    by (auto simp: image_constant_conv)
next
  case False
  from assms have "closed ((λx. inverse c *R x) -` S)"
    by (simp add: continuous_closed_vimage)
  also have "(λx. inverse c *R x) -` S = (λx. c *R x) ` S"
    using ‹c ≠ 0› by (auto elim: image_eqI [rotated])
  finally show ?thesis .
qed

lemma closed_negations:
  fixes S :: "'a::real_normed_vector set"
  assumes "closed S"
  shows "closed ((λx. -x) ` S)"
  using closed_scaling[OF assms, of "- 1"] by simp

lemma compact_closed_sums:
  fixes S :: "'a::real_normed_vector set"
  assumes "compact S" and "closed T"
  shows "closed (⋃x∈ S. ⋃y ∈ T. {x + y})"
proof -
  let ?S = "{x + y |x y. x ∈ S ∧ y ∈ T}"
  {
    fix x l
    assume as: "∀n. x n ∈ ?S"  "(x ⤏ l) sequentially"
    from as(1) obtain f where f: "∀n. x n = fst (f n) + snd (f n)"  "∀n. fst (f n) ∈ S"  "∀n. snd (f n) ∈ T"
      using choice[of "λn y. x n = (fst y) + (snd y) ∧ fst y ∈ S ∧ snd y ∈ T"] by auto
    obtain l' r where "l'∈S" and r: "strict_mono r" and lr: "(((λn. fst (f n)) ∘ r) ⤏ l') sequentially"
      using assms(1)[unfolded compact_def, THEN spec[where x="λ n. fst (f n)"]] using f(2) by auto
    have "((λn. snd (f (r n))) ⤏ l - l') sequentially"
      using tendsto_diff[OF LIMSEQ_subseq_LIMSEQ[OF as(2) r] lr] and f(1)
      unfolding o_def
      by auto
    then have "l - l' ∈ T"
      using assms(2)[unfolded closed_sequential_limits,
        THEN spec[where x="λ n. snd (f (r n))"],
        THEN spec[where x="l - l'"]]
      using f(3)
      by auto
    then have "l ∈ ?S"
      using ‹l' ∈ S›
      apply auto
      apply (rule_tac x=l' in exI)
      apply (rule_tac x="l - l'" in exI, auto)
      done
  }
  moreover have "?S = (⋃x∈ S. ⋃y ∈ T. {x + y})"
    by force
  ultimately show ?thesis
    unfolding closed_sequential_limits
    by (metis (no_types, lifting))
qed

lemma closed_compact_sums:
  fixes S T :: "'a::real_normed_vector set"
  assumes "closed S" "compact T"
  shows "closed (⋃x∈ S. ⋃y ∈ T. {x + y})"
proof -
  have "(⋃x∈ T. ⋃y ∈ S. {x + y}) = (⋃x∈ S. ⋃y ∈ T. {x + y})"
    by auto
  then show ?thesis
    using compact_closed_sums[OF assms(2,1)] by simp
qed

lemma compact_closed_differences:
  fixes S T :: "'a::real_normed_vector set"
  assumes "compact S" "closed T"
  shows "closed (⋃x∈ S. ⋃y ∈ T. {x - y})"
proof -
  have "(⋃x∈ S. ⋃y ∈ uminus ` T. {x + y}) = (⋃x∈ S. ⋃y ∈ T. {x - y})"
    by force
  then show ?thesis
    using compact_closed_sums[OF assms(1) closed_negations[OF assms(2)]] by auto
qed

lemma closed_compact_differences:
  fixes S T :: "'a::real_normed_vector set"
  assumes "closed S" "compact T"
  shows "closed (⋃x∈ S. ⋃y ∈ T. {x - y})"
proof -
  have "(⋃x∈ S. ⋃y ∈ uminus ` T. {x + y}) = {x - y |x y. x ∈ S ∧ y ∈ T}"
    by auto
 then show ?thesis
  using closed_compact_sums[OF assms(1) compact_negations[OF assms(2)]] by simp
qed

lemma closed_translation:
  fixes a :: "'a::real_normed_vector"
  assumes "closed S"
  shows "closed ((λx. a + x) ` S)"
proof -
  have "(⋃x∈ {a}. ⋃y ∈ S. {x + y}) = (op + a ` S)" by auto
  then show ?thesis
    using compact_closed_sums[OF compact_sing[of a] assms] by auto
qed

lemma translation_Compl:
  fixes a :: "'a::ab_group_add"
  shows "(λx. a + x) ` (- t) = - ((λx. a + x) ` t)"
  apply (auto simp: image_iff)
  apply (rule_tac x="x - a" in bexI, auto)
  done

lemma translation_UNIV:
  fixes a :: "'a::ab_group_add"
  shows "range (λx. a + x) = UNIV"
  apply (auto simp: image_iff)
  apply (rule_tac x="x - a" in exI, auto)
  done

lemma translation_diff:
  fixes a :: "'a::ab_group_add"
  shows "(λx. a + x) ` (s - t) = ((λx. a + x) ` s) - ((λx. a + x) ` t)"
  by auto

lemma translation_Int:
  fixes a :: "'a::ab_group_add"
  shows "(λx. a + x) ` (s ∩ t) = ((λx. a + x) ` s) ∩ ((λx. a + x) ` t)"
  by auto

lemma closure_translation:
  fixes a :: "'a::real_normed_vector"
  shows "closure ((λx. a + x) ` s) = (λx. a + x) ` (closure s)"
proof -
  have *: "op + a ` (- s) = - op + a ` s"
    apply auto
    unfolding image_iff
    apply (rule_tac x="x - a" in bexI, auto)
    done
  show ?thesis
    unfolding closure_interior translation_Compl
    using interior_translation[of a "- s"]
    unfolding *
    by auto
qed

lemma frontier_translation:
  fixes a :: "'a::real_normed_vector"
  shows "frontier((λx. a + x) ` s) = (λx. a + x) ` (frontier s)"
  unfolding frontier_def translation_diff interior_translation closure_translation
  by auto

lemma sphere_translation:
  fixes a :: "'n::euclidean_space"
  shows "sphere (a+c) r = op+a ` sphere c r"
apply safe
apply (rule_tac x="x-a" in image_eqI)
apply (auto simp: dist_norm algebra_simps)
done

lemma cball_translation:
  fixes a :: "'n::euclidean_space"
  shows "cball (a+c) r = op+a ` cball c r"
apply safe
apply (rule_tac x="x-a" in image_eqI)
apply (auto simp: dist_norm algebra_simps)
done

lemma ball_translation:
  fixes a :: "'n::euclidean_space"
  shows "ball (a+c) r = op+a ` ball c r"
apply safe
apply (rule_tac x="x-a" in image_eqI)
apply (auto simp: dist_norm algebra_simps)
done


subsection ‹Separation between points and sets›

lemma separate_point_closed:
  fixes s :: "'a::heine_borel set"
  assumes "closed s" and "a ∉ s"
  shows "∃d>0. ∀x∈s. d ≤ dist a x"
proof (cases "s = {}")
  case True
  then show ?thesis by(auto intro!: exI[where x=1])
next
  case False
  from assms obtain x where "x∈s" "∀y∈s. dist a x ≤ dist a y"
    using ‹s ≠ {}› by (blast intro: distance_attains_inf [of s a])
  with ‹x∈s› show ?thesis using dist_pos_lt[of a x] and‹a ∉ s›
    by blast
qed

lemma separate_compact_closed:
  fixes s t :: "'a::heine_borel set"
  assumes "compact s"
    and t: "closed t" "s ∩ t = {}"
  shows "∃d>0. ∀x∈s. ∀y∈t. d ≤ dist x y"
proof cases
  assume "s ≠ {} ∧ t ≠ {}"
  then have "s ≠ {}" "t ≠ {}" by auto
  let ?inf = "λx. infdist x t"
  have "continuous_on s ?inf"
    by (auto intro!: continuous_at_imp_continuous_on continuous_infdist continuous_ident)
  then obtain x where x: "x ∈ s" "∀y∈s. ?inf x ≤ ?inf y"
    using continuous_attains_inf[OF ‹compact s› ‹s ≠ {}›] by auto
  then have "0 < ?inf x"
    using t ‹t ≠ {}› in_closed_iff_infdist_zero by (auto simp: less_le infdist_nonneg)
  moreover have "∀x'∈s. ∀y∈t. ?inf x ≤ dist x' y"
    using x by (auto intro: order_trans infdist_le)
  ultimately show ?thesis by auto
qed (auto intro!: exI[of _ 1])

lemma separate_closed_compact:
  fixes s t :: "'a::heine_borel set"
  assumes "closed s"
    and "compact t"
    and "s ∩ t = {}"
  shows "∃d>0. ∀x∈s. ∀y∈t. d ≤ dist x y"
proof -
  have *: "t ∩ s = {}"
    using assms(3) by auto
  show ?thesis
    using separate_compact_closed[OF assms(2,1) *]
    apply auto
    apply (rule_tac x=d in exI, auto)
    apply (erule_tac x=y in ballE)
    apply (auto simp: dist_commute)
    done
qed


subsection ‹Closure of halfspaces and hyperplanes›

lemma isCont_open_vimage:
  assumes "⋀x. isCont f x"
    and "open s"
  shows "open (f -` s)"
proof -
  from assms(1) have "continuous_on UNIV f"
    unfolding isCont_def continuous_on_def by simp
  then have "open {x ∈ UNIV. f x ∈ s}"
    using open_UNIV ‹open s› by (rule continuous_open_preimage)
  then show "open (f -` s)"
    by (simp add: vimage_def)
qed

lemma isCont_closed_vimage:
  assumes "⋀x. isCont f x"
    and "closed s"
  shows "closed (f -` s)"
  using assms unfolding closed_def vimage_Compl [symmetric]
  by (rule isCont_open_vimage)

lemma continuous_on_closed_Collect_le:
  fixes f g :: "'a::t2_space ⇒ real"
  assumes f: "continuous_on s f" and g: "continuous_on s g" and s: "closed s"
  shows "closed {x ∈ s. f x ≤ g x}"
proof -
  have "closed ((λx. g x - f x) -` {0..} ∩ s)"
    using closed_real_atLeast continuous_on_diff [OF g f]
    by (simp add: continuous_on_closed_vimage [OF s])
  also have "((λx. g x - f x) -` {0..} ∩ s) = {x∈s. f x ≤ g x}"
    by auto
  finally show ?thesis .
qed

lemma continuous_at_inner: "continuous (at x) (inner a)"
  unfolding continuous_at by (intro tendsto_intros)

lemma closed_halfspace_le: "closed {x. inner a x ≤ b}"
  by (simp add: closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_halfspace_ge: "closed {x. inner a x ≥ b}"
  by (simp add: closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_hyperplane: "closed {x. inner a x = b}"
  by (simp add: closed_Collect_eq continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_halfspace_component_le: "closed {x::'a::euclidean_space. x∙i ≤ a}"
  by (simp add: closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_halfspace_component_ge: "closed {x::'a::euclidean_space. x∙i ≥ a}"
  by (simp add: closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_interval_left:
  fixes b :: "'a::euclidean_space"
  shows "closed {x::'a. ∀i∈Basis. x∙i ≤ b∙i}"
  by (simp add: Collect_ball_eq closed_INT closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma closed_interval_right:
  fixes a :: "'a::euclidean_space"
  shows "closed {x::'a. ∀i∈Basis. a∙i ≤ x∙i}"
  by (simp add: Collect_ball_eq closed_INT closed_Collect_le continuous_on_inner continuous_on_const continuous_on_id)

lemma continuous_le_on_closure:
  fixes a::real
  assumes f: "continuous_on (closure s) f"
      and x: "x ∈ closure(s)"
      and xlo: "⋀x. x ∈ s ==> f(x) ≤ a"
    shows "f(x) ≤ a"
    using image_closure_subset [OF f]
  using image_closure_subset [OF f] closed_halfspace_le [of "1::real" a] assms
  by force

lemma continuous_ge_on_closure:
  fixes a::real
  assumes f: "continuous_on (closure s) f"
      and x: "x ∈ closure(s)"
      and xlo: "⋀x. x ∈ s ==> f(x) ≥ a"
    shows "f(x) ≥ a"
  using image_closure_subset [OF f] closed_halfspace_ge [of a "1::real"] assms
  by force

text ‹Openness of halfspaces.›

lemma open_halfspace_lt: "open {x. inner a x < b}"
  by (simp add: open_Collect_less continuous_on_inner continuous_on_const continuous_on_id)

lemma open_halfspace_gt: "open {x. inner a x > b}"
  by (simp add: open_Collect_less continuous_on_inner continuous_on_const continuous_on_id)

lemma open_halfspace_component_lt: "open {x::'a::euclidean_space. x∙i < a}"
  by (simp add: open_Collect_less continuous_on_inner continuous_on_const continuous_on_id)

lemma open_halfspace_component_gt: "open {x::'a::euclidean_space. x∙i > a}"
  by (simp add: open_Collect_less continuous_on_inner continuous_on_const continuous_on_id)

text ‹This gives a simple derivation of limit component bounds.›

lemma Lim_component_le:
  fixes f :: "'a ⇒ 'b::euclidean_space"
  assumes "(f ⤏ l) net"
    and "¬ (trivial_limit net)"
    and "eventually (λx. f(x)∙i ≤ b) net"
  shows "l∙i ≤ b"
  by (rule tendsto_le[OF assms(2) tendsto_const tendsto_inner[OF assms(1) tendsto_const] assms(3)])

lemma Lim_component_ge:
  fixes f :: "'a ⇒ 'b::euclidean_space"
  assumes "(f ⤏ l) net"
    and "¬ (trivial_limit net)"
    and "eventually (λx. b ≤ (f x)∙i) net"
  shows "b ≤ l∙i"
  by (rule tendsto_le[OF assms(2) tendsto_inner[OF assms(1) tendsto_const] tendsto_const assms(3)])

lemma Lim_component_eq:
  fixes f :: "'a ⇒ 'b::euclidean_space"
  assumes net: "(f ⤏ l) net" "¬ trivial_limit net"
    and ev:"eventually (λx. f(x)∙i = b) net"
  shows "l∙i = b"
  using ev[unfolded order_eq_iff eventually_conj_iff]
  using Lim_component_ge[OF net, of b i]
  using Lim_component_le[OF net, of i b]
  by auto

text ‹Limits relative to a union.›

lemma eventually_within_Un:
  "eventually P (at x within (s ∪ t)) ⟷
    eventually P (at x within s) ∧ eventually P (at x within t)"
  unfolding eventually_at_filter
  by (auto elim!: eventually_rev_mp)

lemma Lim_within_union:
 "(f ⤏ l) (at x within (s ∪ t)) ⟷
  (f ⤏ l) (at x within s) ∧ (f ⤏ l) (at x within t)"
  unfolding tendsto_def
  by (auto simp: eventually_within_Un)

lemma Lim_topological:
  "(f ⤏ l) net ⟷
    trivial_limit net ∨ (∀S. open S ⟶ l ∈ S ⟶ eventually (λx. f x ∈ S) net)"
  unfolding tendsto_def trivial_limit_eq by auto

text ‹Continuity relative to a union.›

lemma continuous_on_Un_local:
    "⟦closedin (subtopology euclidean (s ∪ t)) s; closedin (subtopology euclidean (s ∪ t)) t;
      continuous_on s f; continuous_on t f⟧
     ⟹ continuous_on (s ∪ t) f"
  unfolding continuous_on closedin_limpt
  by (metis Lim_trivial_limit Lim_within_union Un_iff trivial_limit_within)

lemma continuous_on_cases_local:
     "⟦closedin (subtopology euclidean (s ∪ t)) s; closedin (subtopology euclidean (s ∪ t)) t;
       continuous_on s f; continuous_on t g;
       ⋀x. ⟦x ∈ s ∧ ~P x ∨ x ∈ t ∧ P x⟧ ⟹ f x = g x⟧
      ⟹ continuous_on (s ∪ t) (λx. if P x then f x else g x)"
  by (rule continuous_on_Un_local) (auto intro: continuous_on_eq)

lemma continuous_on_cases_le:
  fixes h :: "'a :: topological_space ⇒ real"
  assumes "continuous_on {t ∈ s. h t ≤ a} f"
      and "continuous_on {t ∈ s. a ≤ h t} g"
      and h: "continuous_on s h"
      and "⋀t. ⟦t ∈ s; h t = a⟧ ⟹ f t = g t"
    shows "continuous_on s (λt. if h t ≤ a then f(t) else g(t))"
proof -
  have s: "s = {t ∈ s. h t ∈ atMost a} ∪ {t ∈ s. h t ∈ atLeast a}"
    by force
  have 1: "closedin (subtopology euclidean s) {t ∈ s. h t ∈ atMost a}"
    by (rule continuous_closedin_preimage [OF h closed_atMost])
  have 2: "closedin (subtopology euclidean s) {t ∈ s. h t ∈ atLeast a}"
    by (rule continuous_closedin_preimage [OF h closed_atLeast])
  show ?thesis
    apply (rule continuous_on_subset [of s, OF _ order_refl])
    apply (subst s)
    apply (rule continuous_on_cases_local)
    using 1 2 s assms apply auto
    done
qed

lemma continuous_on_cases_1:
  fixes s :: "real set"
  assumes "continuous_on {t ∈ s. t ≤ a} f"
      and "continuous_on {t ∈ s. a ≤ t} g"
      and "a ∈ s ⟹ f a = g a"
    shows "continuous_on s (λt. if t ≤ a then f(t) else g(t))"
using assms
by (auto simp: continuous_on_id intro: continuous_on_cases_le [where h = id, simplified])

text‹Some more convenient intermediate-value theorem formulations.›

lemma connected_ivt_hyperplane:
  assumes "connected s"
    and "x ∈ s"
    and "y ∈ s"
    and "inner a x ≤ b"
    and "b ≤ inner a y"
  shows "∃z ∈ s. inner a z = b"
proof (rule ccontr)
  assume as:"¬ (∃z∈s. inner a z = b)"
  let ?A = "{x. inner a x < b}"
  let ?B = "{x. inner a x > b}"
  have "open ?A" "open ?B"
    using open_halfspace_lt and open_halfspace_gt by auto
  moreover
  have "?A ∩ ?B = {}" by auto
  moreover
  have "s ⊆ ?A ∪ ?B" using as by auto
  ultimately
  show False
    using assms(1)[unfolded connected_def not_ex,
      THEN spec[where x="?A"], THEN spec[where x="?B"]]
    using assms(2-5)
    by auto
qed

lemma connected_ivt_component:
  fixes x::"'a::euclidean_space"
  shows "connected s ⟹
    x ∈ s ⟹ y ∈ s ⟹
    x∙k ≤ a ⟹ a ≤ y∙k ⟹ (∃z∈s.  z∙k = a)"
  using connected_ivt_hyperplane[of s x y "k::'a" a]
  by (auto simp: inner_commute)


subsection ‹Intervals›

lemma open_box[intro]: "open (box a b)"
proof -
  have "open (⋂i∈Basis. (op ∙ i) -` {a ∙ i <..< b ∙ i})"
    by (auto intro!: continuous_open_vimage continuous_inner continuous_ident continuous_const)
  also have "(⋂i∈Basis. (op ∙ i) -` {a ∙ i <..< b ∙ i}) = box a b"
    by (auto simp: box_def inner_commute)
  finally show ?thesis .
qed

instance euclidean_space  second_countable_topology
proof
  define a where "a f = (∑i∈Basis. fst (f i) *R i)" for f :: "'a ⇒ real × real"
  then have a: "⋀f. (∑i∈Basis. fst (f i) *R i) = a f"
    by simp
  define b where "b f = (∑i∈Basis. snd (f i) *R i)" for f :: "'a ⇒ real × real"
  then have b: "⋀f. (∑i∈Basis. snd (f i) *R i) = b f"
    by simp
  define B where "B = (λf. box (a f) (b f)) ` (Basis →E (ℚ × ℚ))"

  have "Ball B open" by (simp add: B_def open_box)
  moreover have "(∀A. open A ⟶ (∃B'⊆B. ⋃B' = A))"
  proof safe
    fix A::"'a set"
    assume "open A"
    show "∃B'⊆B. ⋃B' = A"
      apply (rule exI[of _ "{b∈B. b ⊆ A}"])
      apply (subst (3) open_UNION_box[OF ‹open A›])
      apply (auto simp: a b B_def)
      done
  qed
  ultimately
  have "topological_basis B"
    unfolding topological_basis_def by blast
  moreover
  have "countable B"
    unfolding B_def
    by (intro countable_image countable_PiE finite_Basis countable_SIGMA countable_rat)
  ultimately show "∃B::'a set set. countable B ∧ open = generate_topology B"
    by (blast intro: topological_basis_imp_subbasis)
qed

instance euclidean_space  polish_space ..

lemma closed_cbox[intro]:
  fixes a b :: "'a::euclidean_space"
  shows "closed (cbox a b)"
proof -
  have "closed (⋂i∈Basis. (λx. x∙i) -` {a∙i .. b∙i})"
    by (intro closed_INT ballI continuous_closed_vimage allI
      linear_continuous_at closed_real_atLeastAtMost finite_Basis bounded_linear_inner_left)
  also have "(⋂i∈Basis. (λx. x∙i) -` {a∙i .. b∙i}) = cbox a b"
    by (auto simp: cbox_def)
  finally show "closed (cbox a b)" .
qed

lemma interior_cbox [simp]:
  fixes a b :: "'a::euclidean_space"
  shows "interior (cbox a b) = box a b" (is "?L = ?R")
proof(rule subset_antisym)
  show "?R ⊆ ?L"
    using box_subset_cbox open_box
    by (rule interior_maximal)
  {
    fix x
    assume "x ∈ interior (cbox a b)"
    then obtain s where s: "open s" "x ∈ s" "s ⊆ cbox a b" ..
    then obtain e where "e>0" and e:"∀x'. dist x' x < e ⟶ x' ∈ cbox a b"
      unfolding open_dist and subset_eq by auto
    {
      fix i :: 'a
      assume i: "i ∈ Basis"
      have "dist (x - (e / 2) *R i) x < e"
        and "dist (x + (e / 2) *R i) x < e"
        unfolding dist_norm
        apply auto
        unfolding norm_minus_cancel
        using norm_Basis[OF i] ‹e>0›
        apply auto
        done
      then have "a ∙ i ≤ (x - (e / 2) *R i) ∙ i" and "(x + (e / 2) *R i) ∙ i ≤ b ∙ i"
        using e[THEN spec[where x="x - (e/2) *R i"]]
          and e[THEN spec[where x="x + (e/2) *R i"]]
        unfolding mem_box
        using i
        by blast+
      then have "a ∙ i < x ∙ i" and "x ∙ i < b ∙ i"
        using ‹e>0› i
        by (auto simp: inner_diff_left inner_Basis inner_add_left)
    }
    then have "x ∈ box a b"
      unfolding mem_box by auto
  }
  then show "?L ⊆ ?R" ..
qed

lemma bounded_cbox [simp]:
  fixes a :: "'a::euclidean_space"
  shows "bounded (cbox a b)"
proof -
  let ?b = "∑i∈Basis. ¦a∙i¦ + ¦b∙i¦"
  {
    fix x :: "'a"
    assume x: "∀i∈Basis. a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i"
    {
      fix i :: 'a
      assume "i ∈ Basis"
      then have "¦x∙i¦ ≤ ¦a∙i¦ + ¦b∙i¦"
        using x[THEN bspec[where x=i]] by auto
    }
    then have "(∑i∈Basis. ¦x ∙ i¦) ≤ ?b"
      apply -
      apply (rule sum_mono, auto)
      done
    then have "norm x ≤ ?b"
      using norm_le_l1[of x] by auto
  }
  then show ?thesis
    unfolding cbox_def bounded_iff by auto
qed

lemma bounded_box [simp]:
  fixes a :: "'a::euclidean_space"
  shows "bounded (box a b)"
  using bounded_cbox[of a b]
  using box_subset_cbox[of a b]
  using bounded_subset[of "cbox a b" "box a b"]
  by simp

lemma not_interval_UNIV [simp]:
  fixes a :: "'a::euclidean_space"
  shows "cbox a b ≠ UNIV" "box a b ≠ UNIV"
  using bounded_box[of a b] bounded_cbox[of a b] by force+

lemma not_interval_UNIV2 [simp]:
  fixes a :: "'a::euclidean_space"
  shows "UNIV ≠ cbox a b" "UNIV ≠ box a b"
  using bounded_box[of a b] bounded_cbox[of a b] by force+

lemma compact_cbox [simp]:
  fixes a :: "'a::euclidean_space"
  shows "compact (cbox a b)"
  using bounded_closed_imp_seq_compact[of "cbox a b"] using bounded_cbox[of a b]
  by (auto simp: compact_eq_seq_compact_metric)

proposition is_interval_compact:
   "is_interval S ∧ compact S ⟷ (∃a b. S = cbox a b)"   (is "?lhs = ?rhs")
proof (cases "S = {}")
  case True
  with empty_as_interval show ?thesis by auto
next
  case False
  show ?thesis
  proof
    assume L: ?lhs
    then have "is_interval S" "compact S" by auto
    define a where "a ≡ ∑i∈Basis. (INF x:S. x ∙ i) *R i"
    define b where "b ≡ ∑i∈Basis. (SUP x:S. x ∙ i) *R i"
    have 1: "⋀x i. ⟦x ∈ S; i ∈ Basis⟧ ⟹ (INF x:S. x ∙ i) ≤ x ∙ i"
      by (simp add: cInf_lower bounded_inner_imp_bdd_below compact_imp_bounded L)
    have 2: "⋀x i. ⟦x ∈ S; i ∈ Basis⟧ ⟹ x ∙ i ≤ (SUP x:S. x ∙ i)"
      by (simp add: cSup_upper bounded_inner_imp_bdd_above compact_imp_bounded L)
    have 3: "x ∈ S" if inf: "⋀i. i ∈ Basis ⟹ (INF x:S. x ∙ i) ≤ x ∙ i"
                   and sup: "⋀i. i ∈ Basis ⟹ x ∙ i ≤ (SUP x:S. x ∙ i)" for x
    proof (rule mem_box_componentwiseI [OF ‹is_interval S›])
      fix i::'a
      assume i: "i ∈ Basis"
      have cont: "continuous_on S (λx. x ∙ i)"
        by (intro continuous_intros)
      obtain a where "a ∈ S" and a: "⋀y. y∈S ⟹ a ∙ i ≤ y ∙ i"
        using continuous_attains_inf [OF ‹compact S› False cont] by blast
      obtain b where "b ∈ S" and b: "⋀y. y∈S ⟹ y ∙ i ≤ b ∙ i"
        using continuous_attains_sup [OF ‹compact S› False cont] by blast
      have "a ∙ i ≤ (INF x:S. x ∙ i)"
        by (simp add: False a cINF_greatest)
      also have "… ≤ x ∙ i"
        by (simp add: i inf)
      finally have ai: "a ∙ i ≤ x ∙ i" .
      have "x ∙ i ≤ (SUP x:S. x ∙ i)"
        by (simp add: i sup)
      also have "(SUP x:S. x ∙ i) ≤ b ∙ i"
        by (simp add: False b cSUP_least)
      finally have bi: "x ∙ i ≤ b ∙ i" .
      show "x ∙ i ∈ (λx. x ∙ i) ` S"
        apply (rule_tac x="∑j∈Basis. (if j = i then x ∙ i else a ∙ j) *R j" in image_eqI)
        apply (simp add: i)
        apply (rule mem_is_intervalI [OF ‹is_interval S› ‹a ∈ S› ‹b ∈ S›])
        using i ai bi apply force
        done
    qed
    have "S = cbox a b"
      by (auto simp: a_def b_def mem_box intro: 1 2 3)
    then show ?rhs
      by blast
  next
    assume R: ?rhs
    then show ?lhs
      using compact_cbox is_interval_cbox by blast
  qed
qed


lemma box_midpoint:
  fixes a :: "'a::euclidean_space"
  assumes "box a b ≠ {}"
  shows "((1/2) *R (a + b)) ∈ box a b"
proof -
  {
    fix i :: 'a
    assume "i ∈ Basis"
    then have "a ∙ i < ((1 / 2) *R (a + b)) ∙ i ∧ ((1 / 2) *R (a + b)) ∙ i < b ∙ i"
      using assms[unfolded box_ne_empty, THEN bspec[where x=i]] by (auto simp: inner_add_left)
  }
  then show ?thesis unfolding mem_box by auto
qed

lemma open_cbox_convex:
  fixes x :: "'a::euclidean_space"
  assumes x: "x ∈ box a b"
    and y: "y ∈ cbox a b"
    and e: "0 < e" "e ≤ 1"
  shows "(e *R x + (1 - e) *R y) ∈ box a b"
proof -
  {
    fix i :: 'a
    assume i: "i ∈ Basis"
    have "a ∙ i = e * (a ∙ i) + (1 - e) * (a ∙ i)"
      unfolding left_diff_distrib by simp
    also have "… < e * (x ∙ i) + (1 - e) * (y ∙ i)"
      apply (rule add_less_le_mono)
      using e unfolding mult_less_cancel_left and mult_le_cancel_left
      apply simp_all
      using x unfolding mem_box using i
      apply simp
      using y unfolding mem_box using i
      apply simp
      done
    finally have "a ∙ i < (e *R x + (1 - e) *R y) ∙ i"
      unfolding inner_simps by auto
    moreover
    {
      have "b ∙ i = e * (b∙i) + (1 - e) * (b∙i)"
        unfolding left_diff_distrib by simp
      also have "… > e * (x ∙ i) + (1 - e) * (y ∙ i)"
        apply (rule add_less_le_mono)
        using e unfolding mult_less_cancel_left and mult_le_cancel_left
        apply simp_all
        using x
        unfolding mem_box
        using i
        apply simp
        using y
        unfolding mem_box
        using i
        apply simp
        done
      finally have "(e *R x + (1 - e) *R y) ∙ i < b ∙ i"
        unfolding inner_simps by auto
    }
    ultimately have "a ∙ i < (e *R x + (1 - e) *R y) ∙ i ∧ (e *R x + (1 - e) *R y) ∙ i < b ∙ i"
      by auto
  }
  then show ?thesis
    unfolding mem_box by auto
qed

lemma closure_cbox [simp]: "closure (cbox a b) = cbox a b"
  by (simp add: closed_cbox)

lemma closure_box [simp]:
  fixes a :: "'a::euclidean_space"
   assumes "box a b ≠ {}"
  shows "closure (box a b) = cbox a b"
proof -
  have ab: "a <e b"
    using assms by (simp add: eucl_less_def box_ne_empty)
  let ?c = "(1 / 2) *R (a + b)"
  {
    fix x
    assume as:"x ∈ cbox a b"
    define f where [abs_def]: "f n = x + (inverse (real n + 1)) *R (?c - x)" for n
    {
      fix n
      assume fn: "f n <e b ⟶ a <e f n ⟶ f n = x" and xc: "x ≠ ?c"
      have *: "0 < inverse (real n + 1)" "inverse (real n + 1) ≤ 1"
        unfolding inverse_le_1_iff by auto
      have "(inverse (real n + 1)) *R ((1 / 2) *R (a + b)) + (1 - inverse (real n + 1)) *R x =
        x + (inverse (real n + 1)) *R (((1 / 2) *R (a + b)) - x)"
        by (auto simp: algebra_simps)
      then have "f n <e b" and "a <e f n"
        using open_cbox_convex[OF box_midpoint[OF assms] as *]
        unfolding f_def by (auto simp: box_def eucl_less_def)
      then have False
        using fn unfolding f_def using xc by auto
    }
    moreover
    {
      assume "¬ (f ⤏ x) sequentially"
      {
        fix e :: real
        assume "e > 0"
        then have "∃N::nat. inverse (real (N + 1)) < e"
          using real_arch_inverse[of e]
          apply (auto simp: Suc_pred')
          apply (metis Suc_pred' of_nat_Suc)
          done
        then obtain N :: nat where N: "inverse (real (N + 1)) < e"
          by auto
        have "inverse (real n + 1) < e" if "N ≤ n" for n
          by (auto intro!: that le_less_trans [OF _ N])
        then have "∃N::nat. ∀n≥N. inverse (real n + 1) < e" by auto
      }
      then have "((λn. inverse (real n + 1)) ⤏ 0) sequentially"
        unfolding lim_sequentially by(auto simp: dist_norm)
      then have "(f ⤏ x) sequentially"
        unfolding f_def
        using tendsto_add[OF tendsto_const, of "λn::nat. (inverse (real n + 1)) *R ((1 / 2) *R (a + b) - x)" 0 sequentially x]
        using tendsto_scaleR [OF _ tendsto_const, of "λn::nat. inverse (real n + 1)" 0 sequentially "((1 / 2) *R (a + b) - x)"]
        by auto
    }
    ultimately have "x ∈ closure (box a b)"
      using as and box_midpoint[OF assms]
      unfolding closure_def
      unfolding islimpt_sequential
      by (cases "x=?c") (auto simp: in_box_eucl_less)
  }
  then show ?thesis
    using closure_minimal[OF box_subset_cbox, of a b] by blast
qed

lemma bounded_subset_box_symmetric:
  fixes s::"('a::euclidean_space) set"
  assumes "bounded s"
  shows "∃a. s ⊆ box (-a) a"
proof -
  obtain b where "b>0" and b: "∀x∈s. norm x ≤ b"
    using assms[unfolded bounded_pos] by auto
  define a :: 'a where "a = (∑i∈Basis. (b + 1) *R i)"
  {
    fix x
    assume "x ∈ s"
    fix i :: 'a
    assume i: "i ∈ Basis"
    then have "(-a)∙i < x∙i" and "x∙i < a∙i"
      using b[THEN bspec[where x=x], OF ‹x∈s›]
      using Basis_le_norm[OF i, of x]
      unfolding inner_simps and a_def
      by auto
  }
  then show ?thesis
    by (auto intro: exI[where x=a] simp add: box_def)
qed

lemma bounded_subset_open_interval:
  fixes s :: "('a::euclidean_space) set"
  shows "bounded s ⟹ (∃a b. s ⊆ box a b)"
  by (auto dest!: bounded_subset_box_symmetric)

lemma bounded_subset_cbox_symmetric:
  fixes s :: "('a::euclidean_space) set"
   assumes "bounded s"
  shows "∃a. s ⊆ cbox (-a) a"
proof -
  obtain a where "s ⊆ box (-a) a"
    using bounded_subset_box_symmetric[OF assms] by auto
  then show ?thesis
    using box_subset_cbox[of "-a" a] by auto
qed

lemma bounded_subset_cbox:
  fixes s :: "('a::euclidean_space) set"
  shows "bounded s ⟹ ∃a b. s ⊆ cbox a b"
  using bounded_subset_cbox_symmetric[of s] by auto

lemma frontier_cbox:
  fixes a b :: "'a::euclidean_space"
  shows "frontier (cbox a b) = cbox a b - box a b"
  unfolding frontier_def unfolding interior_cbox and closure_closed[OF closed_cbox] ..

lemma frontier_box:
  fixes a b :: "'a::euclidean_space"
  shows "frontier (box a b) = (if box a b = {} then {} else cbox a b - box a b)"
proof (cases "box a b = {}")
  case True
  then show ?thesis
    using frontier_empty by auto
next
  case False
  then show ?thesis
    unfolding frontier_def and closure_box[OF False] and interior_open[OF open_box]
    by auto
qed

lemma inter_interval_mixed_eq_empty:
  fixes a :: "'a::euclidean_space"
   assumes "box c d ≠ {}"
  shows "box a b ∩ cbox c d = {} ⟷ box a b ∩ box c d = {}"
  unfolding closure_box[OF assms, symmetric]
  unfolding open_Int_closure_eq_empty[OF open_box] ..

lemma diameter_cbox:
  fixes a b::"'a::euclidean_space"
  shows "(∀i ∈ Basis. a ∙ i ≤ b ∙ i) ⟹ diameter (cbox a b) = dist a b"
  by (force simp: diameter_def intro!: cSup_eq_maximum setL2_mono
     simp: euclidean_dist_l2[where 'a='a] cbox_def dist_norm)

lemma eucl_less_eq_halfspaces:
  fixes a :: "'a::euclidean_space"
  shows "{x. x <e a} = (⋂i∈Basis. {x. x ∙ i < a ∙ i})"
    "{x. a <e x} = (⋂i∈Basis. {x. a ∙ i < x ∙ i})"
  by (auto simp: eucl_less_def)

lemma eucl_le_eq_halfspaces:
  fixes a :: "'a::euclidean_space"
  shows "{x. ∀i∈Basis. x ∙ i ≤ a ∙ i} = (⋂i∈Basis. {x. x ∙ i ≤ a ∙ i})"
    "{x. ∀i∈Basis. a ∙ i ≤ x ∙ i} = (⋂i∈Basis. {x. a ∙ i ≤ x ∙ i})"
  by auto

lemma open_Collect_eucl_less[simp, intro]:
  fixes a :: "'a::euclidean_space"
  shows "open {x. x <e a}"
    "open {x. a <e x}"
  by (auto simp: eucl_less_eq_halfspaces open_halfspace_component_lt open_halfspace_component_gt)

lemma closed_Collect_eucl_le[simp, intro]:
  fixes a :: "'a::euclidean_space"
  shows "closed {x. ∀i∈Basis. a ∙ i ≤ x ∙ i}"
    "closed {x. ∀i∈Basis. x ∙ i ≤ a ∙ i}"
  unfolding eucl_le_eq_halfspaces
  by (simp_all add: closed_INT closed_Collect_le  continuous_on_inner continuous_on_const continuous_on_id)

lemma image_affinity_cbox: fixes m::real
  fixes a b c :: "'a::euclidean_space"
  shows "(λx. m *R x + c) ` cbox a b =
    (if cbox a b = {} then {}
     else (if 0 ≤ m then cbox (m *R a + c) (m *R b + c)
     else cbox (m *R b + c) (m *R a + c)))"
proof (cases "m = 0")
  case True
  {
    fix x
    assume "∀i∈Basis. x ∙ i ≤ c ∙ i" "∀i∈Basis. c ∙ i ≤ x ∙ i"
    then have "x = c"
      apply -
      apply (subst euclidean_eq_iff)
      apply (auto intro: order_antisym)
      done
  }
  moreover have "c ∈ cbox (m *R a + c) (m *R b + c)"
    unfolding True by (auto simp: cbox_sing)
  ultimately show ?thesis using True by (auto simp: cbox_def)
next
  case False
  {
    fix y
    assume "∀i∈Basis. a ∙ i ≤ y ∙ i" "∀i∈Basis. y ∙ i ≤ b ∙ i" "m > 0"
    then have "∀i∈Basis. (m *R a + c) ∙ i ≤ (m *R y + c) ∙ i" and "∀i∈Basis. (m *R y + c) ∙ i ≤ (m *R b + c) ∙ i"
      by (auto simp: inner_distrib)
  }
  moreover
  {
    fix y
    assume "∀i∈Basis. a ∙ i ≤ y ∙ i" "∀i∈Basis. y ∙ i ≤ b ∙ i" "m < 0"
    then have "∀i∈Basis. (m *R b + c) ∙ i ≤ (m *R y + c) ∙ i" and "∀i∈Basis. (m *R y + c) ∙ i ≤ (m *R a + c) ∙ i"
      by (auto simp: mult_left_mono_neg inner_distrib)
  }
  moreover
  {
    fix y
    assume "m > 0" and "∀i∈Basis. (m *R a + c) ∙ i ≤ y ∙ i" and "∀i∈Basis. y ∙ i ≤ (m *R b + c) ∙ i"
    then have "y ∈ (λx. m *R x + c) ` cbox a b"
      unfolding image_iff Bex_def mem_box
      apply (intro exI[where x="(1 / m) *R (y - c)"])
      apply (auto simp: pos_le_divide_eq pos_divide_le_eq mult.commute inner_distrib inner_diff_left)
      done
  }
  moreover
  {
    fix y
    assume "∀i∈Basis. (m *R b + c) ∙ i ≤ y ∙ i" "∀i∈Basis. y ∙ i ≤ (m *R a + c) ∙ i" "m < 0"
    then have "y ∈ (λx. m *R x + c) ` cbox a b"
      unfolding image_iff Bex_def mem_box
      apply (intro exI[where x="(1 / m) *R (y - c)"])
      apply (auto simp: neg_le_divide_eq neg_divide_le_eq mult.commute inner_distrib inner_diff_left)
      done
  }
  ultimately show ?thesis using False by (auto simp: cbox_def)
qed

lemma image_smult_cbox:"(λx. m *R (x::_::euclidean_space)) ` cbox a b =
  (if cbox a b = {} then {} else if 0 ≤ m then cbox (m *R a) (m *R b) else cbox (m *R b) (m *R a))"
  using image_affinity_cbox[of m 0 a b] by auto

lemma islimpt_greaterThanLessThan1:
  fixes a b::"'a::{linorder_topology, dense_order}"
  assumes "a < b"
  shows  "a islimpt {a<..<b}"
proof (rule islimptI)
  fix T
  assume "open T" "a ∈ T"
  from open_right[OF this ‹a < b›]
  obtain c where c: "a < c" "{a..<c} ⊆ T" by auto
  with assms dense[of a "min c b"]
  show "∃y∈{a<..<b}. y ∈ T ∧ y ≠ a"
    by (metis atLeastLessThan_iff greaterThanLessThan_iff min_less_iff_conj
      not_le order.strict_implies_order subset_eq)
qed

lemma islimpt_greaterThanLessThan2:
  fixes a b::"'a::{linorder_topology, dense_order}"
  assumes "a < b"
  shows  "b islimpt {a<..<b}"
proof (rule islimptI)
  fix T
  assume "open T" "b ∈ T"
  from open_left[OF this ‹a < b›]
  obtain c where c: "c < b" "{c<..b} ⊆ T" by auto
  with assms dense[of "max a c" b]
  show "∃y∈{a<..<b}. y ∈ T ∧ y ≠ b"
    by (metis greaterThanAtMost_iff greaterThanLessThan_iff max_less_iff_conj
      not_le order.strict_implies_order subset_eq)
qed

lemma closure_greaterThanLessThan[simp]:
  fixes a b::"'a::{linorder_topology, dense_order}"
  shows "a < b ⟹ closure {a <..< b} = {a .. b}" (is "_ ⟹ ?l = ?r")
proof
  have "?l ⊆ closure ?r"
    by (rule closure_mono) auto
  thus "closure {a<..<b} ⊆ {a..b}" by simp
qed (auto simp: closure_def order.order_iff_strict islimpt_greaterThanLessThan1
  islimpt_greaterThanLessThan2)

lemma closure_greaterThan[simp]:
  fixes a b::"'a::{no_top, linorder_topology, dense_order}"
  shows "closure {a<..} = {a..}"
proof -
  from gt_ex obtain b where "a < b" by auto
  hence "{a<..} = {a<..<b} ∪ {b..}" by auto
  also have "closure … = {a..}" using ‹a < b› unfolding closure_Un
    by auto
  finally show ?thesis .
qed

lemma closure_lessThan[simp]:
  fixes b::"'a::{no_bot, linorder_topology, dense_order}"
  shows "closure {..<b} = {..b}"
proof -
  from lt_ex obtain a where "a < b" by auto
  hence "{..<b} = {a<..<b} ∪ {..a}" by auto
  also have "closure … = {..b}" using ‹a < b› unfolding closure_Un
    by auto
  finally show ?thesis .
qed

lemma closure_atLeastLessThan[simp]:
  fixes a b::"'a::{linorder_topology, dense_order}"
  assumes "a < b"
  shows "closure {a ..< b} = {a .. b}"
proof -
  from assms have "{a ..< b} = {a} ∪ {a <..< b}" by auto
  also have "closure … = {a .. b}" unfolding closure_Un
    by (auto simp: assms less_imp_le)
  finally show ?thesis .
qed

lemma closure_greaterThanAtMost[simp]:
  fixes a b::"'a::{linorder_topology, dense_order}"
  assumes "a < b"
  shows "closure {a <.. b} = {a .. b}"
proof -
  from assms have "{a <.. b} = {b} ∪ {a <..< b}" by auto
  also have "closure … = {a .. b}" unfolding closure_Un
    by (auto simp: assms less_imp_le)
  finally show ?thesis .
qed


subsection ‹Homeomorphisms›

definition "homeomorphism s t f g ⟷
  (∀x∈s. (g(f x) = x)) ∧ (f ` s = t) ∧ continuous_on s f ∧
  (∀y∈t. (f(g y) = y)) ∧ (g ` t = s) ∧ continuous_on t g"

lemma homeomorphismI [intro?]:
  assumes "continuous_on S f" "continuous_on T g"
          "f ` S ⊆ T" "g ` T ⊆ S" "⋀x. x ∈ S ⟹ g(f x) = x" "⋀y. y ∈ T ⟹ f(g y) = y"
    shows "homeomorphism S T f g"
  using assms by (force simp: homeomorphism_def)

lemma homeomorphism_translation:
  fixes a :: "'a :: real_normed_vector"
  shows "homeomorphism (op + a ` S) S (op + (- a)) (op + a)"
unfolding homeomorphism_def by (auto simp: algebra_simps continuous_intros)

lemma homeomorphism_ident: "homeomorphism T T (λa. a) (λa. a)"
  by (rule homeomorphismI) (auto simp: continuous_on_id)

lemma homeomorphism_compose:
  assumes "homeomorphism S T f g" "homeomorphism T U h k"
    shows "homeomorphism S U (h o f) (g o k)"
  using assms
  unfolding homeomorphism_def
  by (intro conjI ballI continuous_on_compose) (auto simp: image_comp [symmetric])

lemma homeomorphism_symD: "homeomorphism S t f g ⟹ homeomorphism t S g f"
  by (simp add: homeomorphism_def)

lemma homeomorphism_sym: "homeomorphism S t f g = homeomorphism t S g f"
  by (force simp: homeomorphism_def)

definition homeomorphic :: "'a::topological_space set ⇒ 'b::topological_space set ⇒ bool"
    (infixr "homeomorphic" 60)
  where "s homeomorphic t ≡ (∃f g. homeomorphism s t f g)"

lemma homeomorphic_empty [iff]:
     "S homeomorphic {} ⟷ S = {}" "{} homeomorphic S ⟷ S = {}"
  by (auto simp: homeomorphic_def homeomorphism_def)

lemma homeomorphic_refl: "s homeomorphic s"
  unfolding homeomorphic_def homeomorphism_def
  using continuous_on_id
  apply (rule_tac x = "(λx. x)" in exI)
  apply (rule_tac x = "(λx. x)" in exI)
  apply blast
  done

lemma homeomorphic_sym: "s homeomorphic t ⟷ t homeomorphic s"
  unfolding homeomorphic_def homeomorphism_def
  by blast

lemma homeomorphic_trans [trans]:
  assumes "S homeomorphic T"
      and "T homeomorphic U"
    shows "S homeomorphic U"
  using assms
  unfolding homeomorphic_def
by (metis homeomorphism_compose)

lemma homeomorphic_minimal:
  "s homeomorphic t ⟷
    (∃f g. (∀x∈s. f(x) ∈ t ∧ (g(f(x)) = x)) ∧
           (∀y∈t. g(y) ∈ s ∧ (f(g(y)) = y)) ∧
           continuous_on s f ∧ continuous_on t g)"
   (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    by (fastforce simp: homeomorphic_def homeomorphism_def)
next
  assume ?rhs
  then show ?lhs
    apply clarify
    unfolding homeomorphic_def homeomorphism_def
    by (metis equalityI image_subset_iff subsetI)
 qed

lemma homeomorphicI [intro?]:
   "⟦f ` S = T; g ` T = S;
     continuous_on S f; continuous_on T g;
     ⋀x. x ∈ S ⟹ g(f(x)) = x;
     ⋀y. y ∈ T ⟹ f(g(y)) = y⟧ ⟹ S homeomorphic T"
unfolding homeomorphic_def homeomorphism_def by metis

lemma homeomorphism_of_subsets:
   "⟦homeomorphism S T f g; S' ⊆ S; T'' ⊆ T; f ` S' = T'⟧
    ⟹ homeomorphism S' T' f g"
apply (auto simp: homeomorphism_def elim!: continuous_on_subset)
by (metis subsetD imageI)

lemma homeomorphism_apply1: "⟦homeomorphism S T f g; x ∈ S⟧ ⟹ g(f x) = x"
  by (simp add: homeomorphism_def)

lemma homeomorphism_apply2: "⟦homeomorphism S T f g; x ∈ T⟧ ⟹ f(g x) = x"
  by (simp add: homeomorphism_def)

lemma homeomorphism_image1: "homeomorphism S T f g ⟹ f ` S = T"
  by (simp add: homeomorphism_def)

lemma homeomorphism_image2: "homeomorphism S T f g ⟹ g ` T = S"
  by (simp add: homeomorphism_def)

lemma homeomorphism_cont1: "homeomorphism S T f g ⟹ continuous_on S f"
  by (simp add: homeomorphism_def)

lemma homeomorphism_cont2: "homeomorphism S T f g ⟹ continuous_on T g"
  by (simp add: homeomorphism_def)

lemma continuous_on_no_limpt:
   "(⋀x. ¬ x islimpt S) ⟹ continuous_on S f"
  unfolding continuous_on_def
  by (metis UNIV_I empty_iff eventually_at_topological islimptE open_UNIV tendsto_def trivial_limit_within)

lemma continuous_on_finite:
  fixes S :: "'a::t1_space set"
  shows "finite S ⟹ continuous_on S f"
by (metis continuous_on_no_limpt islimpt_finite)

lemma homeomorphic_finite:
  fixes S :: "'a::t1_space set" and T :: "'b::t1_space set"
  assumes "finite T"
  shows "S homeomorphic T ⟷ finite S ∧ finite T ∧ card S = card T" (is "?lhs = ?rhs")
proof
  assume "S homeomorphic T"
  with assms show ?rhs
    apply (auto simp: homeomorphic_def homeomorphism_def)
     apply (metis finite_imageI)
    by (metis card_image_le finite_imageI le_antisym)
next
  assume R: ?rhs
  with finite_same_card_bij obtain h where "bij_betw h S T"
    by auto
  with R show ?lhs
    apply (auto simp: homeomorphic_def homeomorphism_def continuous_on_finite)
    apply (rule_tac x=h in exI)
    apply (rule_tac x="inv_into S h" in exI)
    apply (auto simp:  bij_betw_inv_into_left bij_betw_inv_into_right bij_betw_imp_surj_on inv_into_into bij_betwE)
    apply (metis bij_betw_def bij_betw_inv_into)
    done
qed

text ‹Relatively weak hypotheses if a set is compact.›

lemma homeomorphism_compact:
  fixes f :: "'a::topological_space ⇒ 'b::t2_space"
  assumes "compact s" "continuous_on s f"  "f ` s = t"  "inj_on f s"
  shows "∃g. homeomorphism s t f g"
proof -
  define g where "g x = (SOME y. y∈s ∧ f y = x)" for x
  have g: "∀x∈s. g (f x) = x"
    using assms(3) assms(4)[unfolded inj_on_def] unfolding g_def by auto
  {
    fix y
    assume "y ∈ t"
    then obtain x where x:"f x = y" "x∈s"
      using assms(3) by auto
    then have "g (f x) = x" using g by auto
    then have "f (g y) = y" unfolding x(1)[symmetric] by auto
  }
  then have g':"∀x∈t. f (g x) = x" by auto
  moreover
  {
    fix x
    have "x∈s ⟹ x ∈ g ` t"
      using g[THEN bspec[where x=x]]
      unfolding image_iff
      using assms(3)
      by (auto intro!: bexI[where x="f x"])
    moreover
    {
      assume "x∈g ` t"
      then obtain y where y:"y∈t" "g y = x" by auto
      then obtain x' where x':"x'∈s" "f x' = y"
        using assms(3) by auto
      then have "x ∈ s"
        unfolding g_def
        using someI2[of "λb. b∈s ∧ f b = y" x' "λx. x∈s"]
        unfolding y(2)[symmetric] and g_def
        by auto
    }
    ultimately have "x∈s ⟷ x ∈ g ` t" ..
  }
  then have "g ` t = s" by auto
  ultimately show ?thesis
    unfolding homeomorphism_def homeomorphic_def
    apply (rule_tac x=g in exI)
    using g and assms(3) and continuous_on_inv[OF assms(2,1), of g, unfolded assms(3)] and assms(2)
    apply auto
    done
qed

lemma homeomorphic_compact:
  fixes f :: "'a::topological_space ⇒ 'b::t2_space"
  shows "compact s ⟹ continuous_on s f ⟹ (f ` s = t) ⟹ inj_on f s ⟹ s homeomorphic t"
  unfolding homeomorphic_def by (metis homeomorphism_compact)

text‹Preservation of topological properties.›

lemma homeomorphic_compactness: "s homeomorphic t ⟹ (compact s ⟷ compact t)"
  unfolding homeomorphic_def homeomorphism_def
  by (metis compact_continuous_image)

text‹Results on translation, scaling etc.›

lemma homeomorphic_scaling:
  fixes s :: "'a::real_normed_vector set"
  assumes "c ≠ 0"
  shows "s homeomorphic ((λx. c *R x) ` s)"
  unfolding homeomorphic_minimal
  apply (rule_tac x="λx. c *R x" in exI)
  apply (rule_tac x="λx. (1 / c) *R x" in exI)
  using assms
  apply (auto simp: continuous_intros)
  done

lemma homeomorphic_translation:
  fixes s :: "'a::real_normed_vector set"
  shows "s homeomorphic ((λx. a + x) ` s)"
  unfolding homeomorphic_minimal
  apply (rule_tac x="λx. a + x" in exI)
  apply (rule_tac x="λx. -a + x" in exI)
  using continuous_on_add [OF continuous_on_const continuous_on_id, of s a]
    continuous_on_add [OF continuous_on_const continuous_on_id, of "plus a ` s" "- a"]
  apply auto
  done

lemma homeomorphic_affinity:
  fixes s :: "'a::real_normed_vector set"
  assumes "c ≠ 0"
  shows "s homeomorphic ((λx. a + c *R x) ` s)"
proof -
  have *: "op + a ` op *R c ` s = (λx. a + c *R x) ` s" by auto
  show ?thesis
    using homeomorphic_trans
    using homeomorphic_scaling[OF assms, of s]
    using homeomorphic_translation[of "(λx. c *R x) ` s" a]
    unfolding *
    by auto
qed

lemma homeomorphic_balls:
  fixes a b ::"'a::real_normed_vector"
  assumes "0 < d"  "0 < e"
  shows "(ball a d) homeomorphic  (ball b e)" (is ?th)
    and "(cball a d) homeomorphic (cball b e)" (is ?cth)
proof -
  show ?th unfolding homeomorphic_minimal
    apply(rule_tac x="λx. b + (e/d) *R (x - a)" in exI)
    apply(rule_tac x="λx. a + (d/e) *R (x - b)" in exI)
    using assms
    apply (auto intro!: continuous_intros
      simp: dist_commute dist_norm pos_divide_less_eq mult_strict_left_mono)
    done
  show ?cth unfolding homeomorphic_minimal
    apply(rule_tac x="λx. b + (e/d) *R (x - a)" in exI)
    apply(rule_tac x="λx. a + (d/e) *R (x - b)" in exI)
    using assms
    apply (auto intro!: continuous_intros
      simp: dist_commute dist_norm pos_divide_le_eq mult_strict_left_mono)
    done
qed

lemma homeomorphic_spheres:
  fixes a b ::"'a::real_normed_vector"
  assumes "0 < d"  "0 < e"
  shows "(sphere a d) homeomorphic (sphere b e)"
unfolding homeomorphic_minimal
    apply(rule_tac x="λx. b + (e/d) *R (x - a)" in exI)
    apply(rule_tac x="λx. a + (d/e) *R (x - b)" in exI)
    using assms
    apply (auto intro!: continuous_intros
      simp: dist_commute dist_norm pos_divide_less_eq mult_strict_left_mono)
    done

subsection‹Inverse function property for open/closed maps›

lemma continuous_on_inverse_open_map:
  assumes contf: "continuous_on S f"
    and imf: "f ` S = T"
    and injf: "⋀x. x ∈ S ⟹ g (f x) = x"
    and oo: "⋀U. openin (subtopology euclidean S) U ⟹ openin (subtopology euclidean T) (f ` U)"
  shows "continuous_on T g"
proof -
  from imf injf have gTS: "g ` T = S"
    by force
  from imf injf have fU: "U ⊆ S ⟹ (f ` U) = {x ∈ T. g x ∈ U}" for U
    by force
  show ?thesis
    by (simp add: continuous_on_open [of T g] gTS) (metis openin_imp_subset fU oo)
qed

lemma continuous_on_inverse_closed_map:
  assumes contf: "continuous_on S f"
    and imf: "f ` S = T"
    and injf: "⋀x. x ∈ S ⟹ g(f x) = x"
    and oo: "⋀U. closedin (subtopology euclidean S) U ⟹ closedin (subtopology euclidean T) (f ` U)"
  shows "continuous_on T g"
proof -
  from imf injf have gTS: "g ` T = S"
    by force
  from imf injf have fU: "U ⊆ S ⟹ (f ` U) = {x ∈ T. g x ∈ U}" for U
    by force
  show ?thesis
    by (simp add: continuous_on_closed [of T g] gTS) (metis closedin_imp_subset fU oo)
qed

lemma homeomorphism_injective_open_map:
  assumes contf: "continuous_on S f"
    and imf: "f ` S = T"
    and injf: "inj_on f S"
    and oo: "⋀U. openin (subtopology euclidean S) U ⟹ openin (subtopology euclidean T) (f ` U)"
  obtains g where "homeomorphism S T f g"
proof
  have "continuous_on T (inv_into S f)"
    by (metis contf continuous_on_inverse_open_map imf injf inv_into_f_f oo)
  with imf injf contf show "homeomorphism S T f (inv_into S f)"
    by (auto simp: homeomorphism_def)
qed

lemma homeomorphism_injective_closed_map:
  assumes contf: "continuous_on S f"
    and imf: "f ` S = T"
    and injf: "inj_on f S"
    and oo: "⋀U. closedin (subtopology euclidean S) U ⟹ closedin (subtopology euclidean T) (f ` U)"
  obtains g where "homeomorphism S T f g"
proof
  have "continuous_on T (inv_into S f)"
    by (metis contf continuous_on_inverse_closed_map imf injf inv_into_f_f oo)
  with imf injf contf show "homeomorphism S T f (inv_into S f)"
    by (auto simp: homeomorphism_def)
qed

lemma homeomorphism_imp_open_map:
  assumes hom: "homeomorphism S T f g"
    and oo: "openin (subtopology euclidean S) U"
  shows "openin (subtopology euclidean T) (f ` U)"
proof -
  from hom oo have [simp]: "f ` U = {y. y ∈ T ∧ g y ∈ U}"
    using openin_subset by (fastforce simp: homeomorphism_def rev_image_eqI)
  from hom have "continuous_on T g"
    unfolding homeomorphism_def by blast
  moreover have "g ` T = S"
    by (metis hom homeomorphism_def)
  ultimately show ?thesis
    by (simp add: continuous_on_open oo)
qed

lemma homeomorphism_imp_closed_map:
  assumes hom: "homeomorphism S T f g"
    and oo: "closedin (subtopology euclidean S) U"
  shows "closedin (subtopology euclidean T) (f ` U)"
proof -
  from hom oo have [simp]: "f ` U = {y. y ∈ T ∧ g y ∈ U}"
    using closedin_subset by (fastforce simp: homeomorphism_def rev_image_eqI)
  from hom have "continuous_on T g"
    unfolding homeomorphism_def by blast
  moreover have "g ` T = S"
    by (metis hom homeomorphism_def)
  ultimately show ?thesis
    by (simp add: continuous_on_closed oo)
qed


subsection ‹"Isometry" (up to constant bounds) of injective linear map etc.›

lemma cauchy_isometric:
  assumes e: "e > 0"
    and s: "subspace s"
    and f: "bounded_linear f"
    and normf: "∀x∈s. norm (f x) ≥ e * norm x"
    and xs: "∀n. x n ∈ s"
    and cf: "Cauchy (f ∘ x)"
  shows "Cauchy x"
proof -
  interpret f: bounded_linear f by fact
  have "∃N. ∀n≥N. norm (x n - x N) < d" if "d > 0" for d :: real
  proof -
    from that obtain N where N: "∀n≥N. norm (f (x n) - f (x N)) < e * d"
      using cf[unfolded Cauchy_def o_def dist_norm, THEN spec[where x="e*d"]] e
      by auto
    have "norm (x n - x N) < d" if "n ≥ N" for n
    proof -
      have "e * norm (x n - x N) ≤ norm (f (x n - x N))"
        using subspace_diff[OF s, of "x n" "x N"]
        using xs[THEN spec[where x=N]] and xs[THEN spec[where x=n]]
        using normf[THEN bspec[where x="x n - x N"]]
        by auto
      also have "norm (f (x n - x N)) < e * d"
        using ‹N ≤ n› N unfolding f.diff[symmetric] by auto
      finally show ?thesis
        using ‹e>0› by simp
    qed
    then show ?thesis by auto
  qed
  then show ?thesis
    by (simp add: Cauchy_altdef2 dist_norm)
qed

lemma complete_isometric_image:
  assumes "0 < e"
    and s: "subspace s"
    and f: "bounded_linear f"
    and normf: "∀x∈s. norm(f x) ≥ e * norm(x)"
    and cs: "complete s"
  shows "complete (f ` s)"
proof -
  have "∃l∈f ` s. (g ⤏ l) sequentially"
    if as:"∀n::nat. g n ∈ f ` s" and cfg:"Cauchy g" for g
  proof -
    from that obtain x where "∀n. x n ∈ s ∧ g n = f (x n)"
      using choice[of "λ n xa. xa ∈ s ∧ g n = f xa"] by auto
    then have x: "∀n. x n ∈ s" "∀n. g n = f (x n)" by auto
    then have "f ∘ x = g" by (simp add: fun_eq_iff)
    then obtain l where "l∈s" and l:"(x ⤏ l) sequentially"
      using cs[unfolded complete_def, THEN spec[where x=x]]
      using cauchy_isometric[OF ‹0 < e› s f normf] and cfg and x(1)
      by auto
    then show ?thesis
      using linear_continuous_at[OF f, unfolded continuous_at_sequentially, THEN spec[where x=x], of l]
      by (auto simp: ‹f ∘ x = g›)
  qed
  then show ?thesis
    unfolding complete_def by auto
qed

lemma injective_imp_isometric:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes s: "closed s" "subspace s"
    and f: "bounded_linear f" "∀x∈s. f x = 0 ⟶ x = 0"
  shows "∃e>0. ∀x∈s. norm (f x) ≥ e * norm x"
proof (cases "s ⊆ {0::'a}")
  case True
  have "norm x ≤ norm (f x)" if "x ∈ s" for x
  proof -
    from True that have "x = 0" by auto
    then show ?thesis by simp
  qed
  then show ?thesis
    by (auto intro!: exI[where x=1])
next
  case False
  interpret f: bounded_linear f by fact
  from False obtain a where a: "a ≠ 0" "a ∈ s"
    by auto
  from False have "s ≠ {}"
    by auto
  let ?S = "{f x| x. x ∈ s ∧ norm x = norm a}"
  let ?S' = "{x::'a. x∈s ∧ norm x = norm a}"
  let ?S'' = "{x::'a. norm x = norm a}"

  have "?S'' = frontier (cball 0 (norm a))"
    by (simp add: sphere_def dist_norm)
  then have "compact ?S''" by (metis compact_cball compact_frontier)
  moreover have "?S' = s ∩ ?S''" by auto
  ultimately have "compact ?S'"
    using closed_Int_compact[of s ?S''] using s(1) by auto
  moreover have *:"f ` ?S' = ?S" by auto
  ultimately have "compact ?S"
    using compact_continuous_image[OF linear_continuous_on[OF f(1)], of ?S'] by auto
  then have "closed ?S"
    using compact_imp_closed by auto
  moreover from a have "?S ≠ {}" by auto
  ultimately obtain b' where "b'∈?S" "∀y∈?S. norm b' ≤ norm y"
    using distance_attains_inf[of ?S 0] unfolding dist_0_norm by auto
  then obtain b where "b∈s"
    and ba: "norm b = norm a"
    and b: "∀x∈{x ∈ s. norm x = norm a}. norm (f b) ≤ norm (f x)"
    unfolding *[symmetric] unfolding image_iff by auto

  let ?e = "norm (f b) / norm b"
  have "norm b > 0"
    using ba and a and norm_ge_zero by auto
  moreover have "norm (f b) > 0"
    using f(2)[THEN bspec[where x=b], OF ‹b∈s›]
    using ‹norm b >0› by simp
  ultimately have "0 < norm (f b) / norm b" by simp
  moreover
  have "norm (f b) / norm b * norm x ≤ norm (f x)" if "x∈s" for x
  proof (cases "x = 0")
    case True
    then show "norm (f b) / norm b * norm x ≤ norm (f x)"
      by auto
  next
    case False
    with ‹a ≠ 0› have *: "0 < norm a / norm x"
      unfolding zero_less_norm_iff[symmetric] by simp
    have "∀x∈s. c *R x ∈ s" for c
      using s[unfolded subspace_def] by simp
    with ‹x ∈ s› ‹x ≠ 0› have "(norm a / norm x) *R x ∈ {x ∈ s. norm x = norm a}"
      by simp
    with ‹x ≠ 0› ‹a ≠ 0› show "norm (f b) / norm b * norm x ≤ norm (f x)"
      using b[THEN bspec[where x="(norm a / norm x) *R x"]]
      unfolding f.scaleR and ba
      by (auto simp: mult.commute pos_le_divide_eq pos_divide_le_eq)
  qed
  ultimately show ?thesis by auto
qed

lemma closed_injective_image_subspace:
  fixes f :: "'a::euclidean_space ⇒ 'b::euclidean_space"
  assumes "subspace s" "bounded_linear f" "∀x∈s. f x = 0 ⟶ x = 0" "closed s"
  shows "closed(f ` s)"
proof -
  obtain e where "e > 0" and e: "∀x∈s. e * norm x ≤ norm (f x)"
    using injective_imp_isometric[OF assms(4,1,2,3)] by auto
  show ?thesis
    using complete_isometric_image[OF ‹e>0› assms(1,2) e] and assms(4)
    unfolding complete_eq_closed[symmetric] by auto
qed


subsection ‹Some properties of a canonical subspace›

lemma subspace_substandard: "subspace {x::'a::euclidean_space. (∀i∈Basis. P i ⟶ x∙i = 0)}"
  by (auto simp: subspace_def inner_add_left)

lemma closed_substandard: "closed {x::'a::euclidean_space. ∀i∈Basis. P i ⟶ x∙i = 0}"
  (is "closed ?A")
proof -
  let ?D = "{i∈Basis. P i}"
  have "closed (⋂i∈?D. {x::'a. x∙i = 0})"
    by (simp add: closed_INT closed_Collect_eq continuous_on_inner
        continuous_on_const continuous_on_id)
  also have "(⋂i∈?D. {x::'a. x∙i = 0}) = ?A"
    by auto
  finally show "closed ?A" .
qed

lemma dim_substandard:
  assumes d: "d ⊆ Basis"
  shows "dim {x::'a::euclidean_space. ∀i∈Basis. i ∉ d ⟶ x∙i = 0} = card d" (is "dim ?A = _")
proof (rule dim_unique)
  from d show "d ⊆ ?A"
    by (auto simp: inner_Basis)
  from d show "independent d"
    by (rule independent_mono [OF independent_Basis])
  have "x ∈ span d" if "∀i∈Basis. i ∉ d ⟶ x ∙ i = 0" for x
  proof -
    have "finite d"
      by (rule finite_subset [OF d finite_Basis])
    then have "(∑i∈d. (x ∙ i) *R i) ∈ span d"
      by (simp add: span_sum span_clauses)
    also have "(∑i∈d. (x ∙ i) *R i) = (∑i∈Basis. (x ∙ i) *R i)"
      by (rule sum.mono_neutral_cong_left [OF finite_Basis d]) (auto simp: that)
    finally show "x ∈ span d"
      by (simp only: euclidean_representation)
  qed
  then show "?A ⊆ span d" by auto
qed simp

text ‹Hence closure and completeness of all subspaces.›
lemma ex_card:
  assumes "n ≤ card A"
  shows "∃S⊆A. card S = n"
proof (cases "finite A")
  case True
  from ex_bij_betw_nat_finite[OF this] obtain f where f: "bij_betw f {0..<card A} A" ..
  moreover from f ‹n ≤ card A› have "{..< n} ⊆ {..< card A}" "inj_on f {..< n}"
    by (auto simp: bij_betw_def intro: subset_inj_on)
  ultimately have "f ` {..< n} ⊆ A" "card (f ` {..< n}) = n"
    by (auto simp: bij_betw_def card_image)
  then show ?thesis by blast
next
  case False
  with ‹n ≤ card A› show ?thesis by force
qed

lemma closed_subspace:
  fixes s :: "'a::euclidean_space set"
  assumes "subspace s"
  shows "closed s"
proof -
  have "dim s ≤ card (Basis :: 'a set)"
    using dim_subset_UNIV by auto
  with ex_card[OF this] obtain d :: "'a set" where t: "card d = dim s" and d: "d ⊆ Basis"
    by auto
  let ?t = "{x::'a. ∀i∈Basis. i ∉ d ⟶ x∙i = 0}"
  have "∃f. linear f ∧ f ` {x::'a. ∀i∈Basis. i ∉ d ⟶ x ∙ i = 0} = s ∧
      inj_on f {x::'a. ∀i∈Basis. i ∉ d ⟶ x ∙ i = 0}"
    using dim_substandard[of d] t d assms
    by (intro subspace_isomorphism[OF subspace_substandard[of "λi. i ∉ d"]]) (auto simp: inner_Basis)
  then obtain f where f:
      "linear f"
      "f ` {x. ∀i∈Basis. i ∉ d ⟶ x ∙ i = 0} = s"
      "inj_on f {x. ∀i∈Basis. i ∉ d ⟶ x ∙ i = 0}"
    by blast
  interpret f: bounded_linear f
    using f by (simp add: linear_conv_bounded_linear)
  have "x ∈ ?t ⟹ f x = 0 ⟹ x = 0" for x
    using f.zero d f(3)[THEN inj_onD, of x 0] by auto
  moreover have "closed ?t" by (rule closed_substandard)
  moreover have "subspace ?t" by (rule subspace_substandard)
  ultimately show ?thesis
    using closed_injective_image_subspace[of ?t f]
    unfolding f(2) using f(1) unfolding linear_conv_bounded_linear by auto
qed

lemma complete_subspace: "subspace s ⟹ complete s"
  for s :: "'a::euclidean_space set"
  using complete_eq_closed closed_subspace by auto

lemma closed_span [iff]: "closed (span s)"
  for s :: "'a::euclidean_space set"
  by (simp add: closed_subspace)

lemma dim_closure [simp]: "dim (closure s) = dim s" (is "?dc = ?d")
  for s :: "'a::euclidean_space set"
proof -
  have "?dc ≤ ?d"
    using closure_minimal[OF span_inc, of s]
    using closed_subspace[OF subspace_span, of s]
    using dim_subset[of "closure s" "span s"]
    by simp
  then show ?thesis
    using dim_subset[OF closure_subset, of s]
    by simp
qed


subsection ‹Affine transformations of intervals›

lemma real_affinity_le: "0 < m ⟹ m * x + c ≤ y ⟷ x ≤ inverse m * y + - (c / m)"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)

lemma real_le_affinity: "0 < m ⟹ y ≤ m * x + c ⟷ inverse m * y + - (c / m) ≤ x"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)

lemma real_affinity_lt: "0 < m ⟹ m * x + c < y ⟷ x < inverse m * y + - (c / m)"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)

lemma real_lt_affinity: "0 < m ⟹ y < m * x + c ⟷ inverse m * y + - (c / m) < x"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)

lemma real_affinity_eq: "m ≠ 0 ⟹ m * x + c = y ⟷ x = inverse m * y + - (c / m)"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)

lemma real_eq_affinity: "m ≠ 0 ⟹ y = m * x + c  ⟷ inverse m * y + - (c / m) = x"
  for m :: "'a::linordered_field"
  by (simp add: field_simps)


subsection ‹Banach fixed point theorem (not really topological ...)›

theorem banach_fix:
  assumes s: "complete s" "s ≠ {}"
    and c: "0 ≤ c" "c < 1"
    and f: "f ` s ⊆ s"
    and lipschitz: "∀x∈s. ∀y∈s. dist (f x) (f y) ≤ c * dist x y"
  shows "∃!x∈s. f x = x"
proof -
  from c have "1 - c > 0" by simp

  from s(2) obtain z0 where z0: "z0 ∈ s" by blast
  define z where "z n = (f ^^ n) z0" for n
  with f z0 have z_in_s: "z n ∈ s" for n :: nat
    by (induct n) auto
  define d where "d = dist (z 0) (z 1)"

  have fzn: "f (z n) = z (Suc n)" for n
    by (simp add: z_def)
  have cf_z: "dist (z n) (z (Suc n)) ≤ (c ^ n) * d" for n :: nat
  proof (induct n)
    case 0
    then show ?case
      by (simp add: d_def)
  next
    case (Suc m)
    with ‹0 ≤ c› have "c * dist (z m) (z (Suc m)) ≤ c ^ Suc m * d"
      using mult_left_mono[of "dist (z m) (z (Suc m))" "c ^ m * d" c] by simp
    then show ?case
      using lipschitz[THEN bspec[where x="z m"], OF z_in_s, THEN bspec[where x="z (Suc m)"], OF z_in_s]
      by (simp add: fzn mult_le_cancel_left)
  qed

  have cf_z2: "(1 - c) * dist (z m) (z (m + n)) ≤ (c ^ m) * d * (1 - c ^ n)" for n m :: nat
  proof (induct n)
    case 0
    show ?case by simp
  next
    case (Suc k)
    from c have "(1 - c) * dist (z m) (z (m + Suc k)) ≤
        (1 - c) * (dist (z m) (z (m + k)) + dist (z (m + k)) (z (Suc (m + k))))"
      by (simp add: dist_triangle)
    also from c cf_z[of "m + k"] have "… ≤ (1 - c) * (dist (z m) (z (m + k)) + c ^ (m + k) * d)"
      by simp
    also from Suc have "… ≤ c ^ m * d * (1 - c ^ k) + (1 - c) * c ^ (m + k) * d"
      by (simp add: field_simps)
    also have "… = (c ^ m) * (d * (1 - c ^ k) + (1 - c) * c ^ k * d)"
      by (simp add: power_add field_simps)
    also from c have "… ≤ (c ^ m) * d * (1 - c ^ Suc k)"
      by (simp add: field_simps)
    finally show ?case by simp
  qed

  have "∃N. ∀m n. N ≤ m ∧ N ≤ n ⟶ dist (z m) (z n) < e" if "e > 0" for e
  proof (cases "d = 0")
    case True
    from ‹1 - c > 0› have "(1 - c) * x ≤ 0 ⟷ x ≤ 0" for x
      by (metis mult_zero_left mult.commute real_mult_le_cancel_iff1)
    with c cf_z2[of 0] True have "z n = z0" for n
      by (simp add: z_def)
    with ‹e > 0› show ?thesis by simp
  next
    case False
    with zero_le_dist[of "z 0" "z 1"] have "d > 0"
      by (metis d_def less_le)
    with ‹1 - c > 0› ‹e > 0› have "0 < e * (1 - c) / d"
      by simp
    with c obtain N where N: "c ^ N < e * (1 - c) / d"
      using real_arch_pow_inv[of "e * (1 - c) / d" c] by auto
    have *: "dist (z m) (z n) < e" if "m > n" and as: "m ≥ N" "n ≥ N" for m n :: nat
    proof -
      from c ‹n ≥ N› have *: "c ^ n ≤ c ^ N"
        using power_decreasing[OF ‹n≥N›, of c] by simp
      from c ‹m > n› have "1 - c ^ (m - n) > 0"
        using power_strict_mono[of c 1 "m - n"] by simp
      with ‹d > 0› ‹0 < 1 - c› have **: "d * (1 - c ^ (m - n)) / (1 - c) > 0"
        by simp
      from cf_z2[of n "m - n"] ‹m > n›
      have "dist (z m) (z n) ≤ c ^ n * d * (1 - c ^ (m - n)) / (1 - c)"
        by (simp add: pos_le_divide_eq[OF ‹1 - c > 0›] mult.commute dist_commute)
      also have "… ≤ c ^ N * d * (1 - c ^ (m - n)) / (1 - c)"
        using mult_right_mono[OF * order_less_imp_le[OF **]]
        by (simp add: mult.assoc)
      also have "… < (e * (1 - c) / d) * d * (1 - c ^ (m - n)) / (1 - c)"
        using mult_strict_right_mono[OF N **] by (auto simp: mult.assoc)
      also from c ‹d > 0› ‹1 - c > 0› have "… = e * (1 - c ^ (m - n))"
        by simp
      also from c ‹1 - c ^ (m - n) > 0› ‹e > 0› have "… ≤ e"
        using mult_right_le_one_le[of e "1 - c ^ (m - n)"] by auto
      finally show ?thesis by simp
    qed
    have "dist (z n) (z m) < e" if "N ≤ m" "N ≤ n" for m n :: nat
    proof (cases "n = m")
      case True
      with ‹e > 0› show ?thesis by simp
    next
      case False
      with *[of n m] *[of m n] and that show ?thesis
        by (auto simp: dist_commute nat_neq_iff)
    qed
    then show ?thesis by auto
  qed
  then have "Cauchy z"
    by (simp add: cauchy_def)
  then obtain x where "x∈s" and x:"(z ⤏ x) sequentially"
    using s(1)[unfolded compact_def complete_def, THEN spec[where x=z]] and z_in_s by auto

  define e where "e = dist (f x) x"
  have "e = 0"
  proof (rule ccontr)
    assume "e ≠ 0"
    then have "e > 0"
      unfolding e_def using zero_le_dist[of "f x" x]
      by (metis dist_eq_0_iff dist_nz e_def)
    then obtain N where N:"∀n≥N. dist (z n) x < e / 2"
      using x[unfolded lim_sequentially, THEN spec[where x="e/2"]] by auto
    then have N':"dist (z N) x < e / 2" by auto
    have *: "c * dist (z N) x ≤ dist (z N) x"
      unfolding mult_le_cancel_right2
      using zero_le_dist[of "z N" x] and c
      by (metis dist_eq_0_iff dist_nz order_less_asym less_le)
    have "dist (f (z N)) (f x) ≤ c * dist (z N) x"
      using lipschitz[THEN bspec[where x="z N"], THEN bspec[where x=x]]
      using z_in_s[of N] ‹x∈s›
      using c
      by auto
    also have "… < e / 2"
      using N' and c using * by auto
    finally show False
      unfolding fzn
      using N[THEN spec[where x="Suc N"]] and dist_triangle_half_r[of "z (Suc N)" "f x" e x]
      unfolding e_def
      by auto
  qed
  then have "f x = x" by (auto simp: e_def)
  moreover have "y = x" if "f y = y" "y ∈ s" for y
  proof -
    from ‹x ∈ s› ‹f x = x› that have "dist x y ≤ c * dist x y"
      using lipschitz[THEN bspec[where x=x], THEN bspec[where x=y]] by simp
    with c and zero_le_dist[of x y] have "dist x y = 0"
      by (simp add: mult_le_cancel_right1)
    then show ?thesis by simp
  qed
  ultimately show ?thesis
    using ‹x∈s› by blast
qed


subsection ‹Edelstein fixed point theorem›

theorem edelstein_fix:
  fixes s :: "'a::metric_space set"
  assumes s: "compact s" "s ≠ {}"
    and gs: "(g ` s) ⊆ s"
    and dist: "∀x∈s. ∀y∈s. x ≠ y ⟶ dist (g x) (g y) < dist x y"
  shows "∃!x∈s. g x = x"
proof -
  let ?D = "(λx. (x, x)) ` s"
  have D: "compact ?D" "?D ≠ {}"
    by (rule compact_continuous_image)
       (auto intro!: s continuous_Pair continuous_ident simp: continuous_on_eq_continuous_within)

  have "⋀x y e. x ∈ s ⟹ y ∈ s ⟹ 0 < e ⟹ dist y x < e ⟹ dist (g y) (g x) < e"
    using dist by fastforce
  then have "continuous_on s g"
    by (auto simp: continuous_on_iff)
  then have cont: "continuous_on ?D (λx. dist ((g ∘ fst) x) (snd x))"
    unfolding continuous_on_eq_continuous_within
    by (intro continuous_dist ballI continuous_within_compose)
       (auto intro!: continuous_fst continuous_snd continuous_ident simp: image_image)

  obtain a where "a ∈ s" and le: "⋀x. x ∈ s ⟹ dist (g a) a ≤ dist (g x) x"
    using continuous_attains_inf[OF D cont] by auto

  have "g a = a"
  proof (rule ccontr)
    assume "g a ≠ a"
    with ‹a ∈ s› gs have "dist (g (g a)) (g a) < dist (g a) a"
      by (intro dist[rule_format]) auto
    moreover have "dist (g a) a ≤ dist (g (g a)) (g a)"
      using ‹a ∈ s› gs by (intro le) auto
    ultimately show False by auto
  qed
  moreover have "⋀x. x ∈ s ⟹ g x = x ⟹ x = a"
    using dist[THEN bspec[where x=a]] ‹g a = a› and ‹a∈s› by auto
  ultimately show "∃!x∈s. g x = x"
    using ‹a ∈ s› by blast
qed


lemma cball_subset_cball_iff:
  fixes a :: "'a :: euclidean_space"
  shows "cball a r ⊆ cball a' r' ⟷ dist a a' + r ≤ r' ∨ r < 0"
    (is "?lhs ⟷ ?rhs")
proof
  assume ?lhs
  then show ?rhs
  proof (cases "r < 0")
    case True
    then show ?rhs by simp
  next
    case False
    then have [simp]: "r ≥ 0" by simp
    have "norm (a - a') + r ≤ r'"
    proof (cases "a = a'")
      case True
      then show ?thesis
        using subsetD [where c = "a + r *R (SOME i. i ∈ Basis)", OF ‹?lhs›] subsetD [where c = a, OF ‹?lhs›]
        by (force simp: SOME_Basis dist_norm)
    next
      case False
      have "norm (a' - (a + (r / norm (a - a')) *R (a - a'))) = norm (a' - a - (r / norm (a - a')) *R (a - a'))"
        by (simp add: algebra_simps)
      also have "... = norm ((-1 - (r / norm (a - a'))) *R (a - a'))"
        by (simp add: algebra_simps)
      also from ‹a ≠ a'› have "... = ¦- norm (a - a') - r¦"
        by (simp add: abs_mult_pos field_simps)
      finally have [simp]: "norm (a' - (a + (r / norm (a - a')) *R (a - a'))) = ¦norm (a - a') + r¦"
        by linarith
      from ‹a ≠ a'› show ?thesis
        using subsetD [where c = "a' + (1 + r / norm(a - a')) *R (a - a')", OF ‹?lhs›]
        by (simp add: dist_norm scaleR_add_left)
    qed
    then show ?rhs
      by (simp add: dist_norm)
  qed
next
  assume ?rhs
  then show ?lhs
    by (auto simp: ball_def dist_norm)
      (metis add.commute add_le_cancel_right dist_norm dist_triangle3 order_trans)
qed

lemma cball_subset_ball_iff: "cball a r ⊆ ball a' r' ⟷ dist a a' + r < r' ∨ r < 0"
  (is "?lhs ⟷ ?rhs")
  for a :: "'a::euclidean_space"
proof
  assume ?lhs
  then show ?rhs
  proof (cases "r < 0")
    case True then
    show ?rhs by simp
  next
    case False
    then have [simp]: "r ≥ 0" by simp
    have "norm (a - a') + r < r'"
    proof (cases "a = a'")
      case True
      then show ?thesis
        using subsetD [where c = "a + r *R (SOME i. i ∈ Basis)", OF ‹?lhs›] subsetD [where c = a, OF ‹?lhs›]
        by (force simp: SOME_Basis dist_norm)
    next
      case False
      have False if "norm (a - a') + r ≥ r'"
      proof -
        from that have "¦r' - norm (a - a')¦ ≤ r"
          by (simp split: abs_split)
            (metis ‹0 ≤ r› ‹?lhs› centre_in_cball dist_commute dist_norm less_asym mem_ball subset_eq)
        then show ?thesis
          using subsetD [where c = "a + (r' / norm(a - a') - 1) *R (a - a')", OF ‹?lhs›] ‹a ≠ a'›
          by (simp add: dist_norm field_simps)
            (simp add: diff_divide_distrib scaleR_left_diff_distrib)
      qed
      then show ?thesis by force
    qed
    then show ?rhs by (simp add: dist_norm)
  qed
next
  assume ?rhs
  then show ?lhs
    by (auto simp: ball_def dist_norm)
      (metis add.commute add_le_cancel_right dist_norm dist_triangle3 le_less_trans)
qed

lemma ball_subset_cball_iff: "ball a r ⊆ cball a' r' ⟷ dist a a' + r ≤ r' ∨ r ≤ 0"
  (is "?lhs = ?rhs")
  for a :: "'a::euclidean_space"
proof (cases "r ≤ 0")
  case True
  then show ?thesis
    using dist_not_less_zero less_le_trans by force
next
  case False
  show ?thesis
  proof
    assume ?lhs
    then have "(cball a r ⊆ cball a' r')"
      by (metis False closed_cball closure_ball closure_closed closure_mono not_less)
    with False show ?rhs
      by (fastforce iff: cball_subset_cball_iff)
  next
    assume ?rhs
    with False show ?lhs
      using ball_subset_cball cball_subset_cball_iff by blast
  qed
qed

lemma ball_subset_ball_iff:
  fixes a :: "'a :: euclidean_space"
  shows "ball a r ⊆ ball a' r' ⟷ dist a a' + r ≤ r' ∨ r ≤ 0"
        (is "?lhs = ?rhs")
proof (cases "r ≤ 0")
  case True then show ?thesis
    using dist_not_less_zero less_le_trans by force
next
  case False show ?thesis
  proof
    assume ?lhs
    then have "0 < r'"
      by (metis (no_types) False ‹?lhs› centre_in_ball dist_norm le_less_trans mem_ball norm_ge_zero not_less set_mp)
    then have "(cball a r ⊆ cball a' r')"
      by (metis False‹?lhs› closure_ball closure_mono not_less)
    then show ?rhs
      using False cball_subset_cball_iff by fastforce
  next
  assume ?rhs then show ?lhs
    apply (auto simp: ball_def)
    apply (metis add.commute add_le_cancel_right dist_commute dist_triangle_lt not_le order_trans)
    using dist_not_less_zero order.strict_trans2 apply blast
    done
  qed
qed


lemma ball_eq_ball_iff:
  fixes x :: "'a :: euclidean_space"
  shows "ball x d = ball y e ⟷ d ≤ 0 ∧ e ≤ 0 ∨ x=y ∧ d=e"
        (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
  proof (cases "d ≤ 0 ∨ e ≤ 0")
    case True
      with ‹?lhs› show ?rhs
        by safe (simp_all only: ball_eq_empty [of y e, symmetric] ball_eq_empty [of x d, symmetric])
  next
    case False
    with ‹?lhs› show ?rhs
      apply (auto simp: set_eq_subset ball_subset_ball_iff dist_norm norm_minus_commute algebra_simps)
      apply (metis add_le_same_cancel1 le_add_same_cancel1 norm_ge_zero norm_pths(2) order_trans)
      apply (metis add_increasing2 add_le_imp_le_right eq_iff norm_ge_zero)
      done
  qed
next
  assume ?rhs then show ?lhs
    by (auto simp: set_eq_subset ball_subset_ball_iff)
qed

lemma cball_eq_cball_iff:
  fixes x :: "'a :: euclidean_space"
  shows "cball x d = cball y e ⟷ d < 0 ∧ e < 0 ∨ x=y ∧ d=e"
        (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
  proof (cases "d < 0 ∨ e < 0")
    case True
      with ‹?lhs› show ?rhs
        by safe (simp_all only: cball_eq_empty [of y e, symmetric] cball_eq_empty [of x d, symmetric])
  next
    case False
    with ‹?lhs› show ?rhs
      apply (auto simp: set_eq_subset cball_subset_cball_iff dist_norm norm_minus_commute algebra_simps)
      apply (metis add_le_same_cancel1 le_add_same_cancel1 norm_ge_zero norm_pths(2) order_trans)
      apply (metis add_increasing2 add_le_imp_le_right eq_iff norm_ge_zero)
      done
  qed
next
  assume ?rhs then show ?lhs
    by (auto simp: set_eq_subset cball_subset_cball_iff)
qed

lemma ball_eq_cball_iff:
  fixes x :: "'a :: euclidean_space"
  shows "ball x d = cball y e ⟷ d ≤ 0 ∧ e < 0" (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    apply (auto simp: set_eq_subset ball_subset_cball_iff cball_subset_ball_iff algebra_simps)
    apply (metis add_increasing2 add_le_cancel_right add_less_same_cancel1 dist_not_less_zero less_le_trans zero_le_dist)
    apply (metis add_less_same_cancel1 dist_not_less_zero less_le_trans not_le)
    using ‹?lhs› ball_eq_empty cball_eq_empty apply blast+
    done
next
  assume ?rhs then show ?lhs by auto
qed

lemma cball_eq_ball_iff:
  fixes x :: "'a :: euclidean_space"
  shows "cball x d = ball y e ⟷ d < 0 ∧ e ≤ 0"
  using ball_eq_cball_iff by blast

lemma finite_ball_avoid:
  fixes S :: "'a :: euclidean_space set"
  assumes "open S" "finite X" "p ∈ S"
  shows "∃e>0. ∀w∈ball p e. w∈S ∧ (w≠p ⟶ w∉X)"
proof -
  obtain e1 where "0 < e1" and e1_b:"ball p e1 ⊆ S"
    using open_contains_ball_eq[OF ‹open S›] assms by auto
  obtain e2 where "0 < e2" and "∀x∈X. x ≠ p ⟶ e2 ≤ dist p x"
    using finite_set_avoid[OF ‹finite X›,of p] by auto
  hence "∀w∈ball p (min e1 e2). w∈S ∧ (w≠p ⟶ w∉X)" using e1_b by auto
  thus "∃e>0. ∀w∈ball p e. w ∈ S ∧ (w ≠ p ⟶ w ∉ X)" using ‹e2>0› ‹e1>0›
    apply (rule_tac x="min e1 e2" in exI)
    by auto
qed

lemma finite_cball_avoid:
  fixes S :: "'a :: euclidean_space set"
  assumes "open S" "finite X" "p ∈ S"
  shows "∃e>0. ∀w∈cball p e. w∈S ∧ (w≠p ⟶ w∉X)"
proof -
  obtain e1 where "e1>0" and e1: "∀w∈ball p e1. w∈S ∧ (w≠p ⟶ w∉X)"
    using finite_ball_avoid[OF assms] by auto
  define e2 where "e2 ≡ e1/2"
  have "e2>0" and "e2 < e1" unfolding e2_def using ‹e1>0› by auto
  then have "cball p e2 ⊆ ball p e1" by (subst cball_subset_ball_iff,auto)
  then show "∃e>0. ∀w∈cball p e. w ∈ S ∧ (w ≠ p ⟶ w ∉ X)" using ‹e2>0› e1 by auto
qed

subsection‹Various separability-type properties›

lemma univ_second_countable:
  obtains  :: "'a::euclidean_space set set"
  where "countable ℬ" "⋀C. C ∈ ℬ ⟹ open C"
       "⋀S. open S ⟹ ∃U. U ⊆ ℬ ∧ S = ⋃U"
by (metis ex_countable_basis topological_basis_def)

lemma subset_second_countable:
  obtains  :: "'a:: euclidean_space set set"
    where "countable ℬ"
          "{} ∉ ℬ"
          "⋀C. C ∈ ℬ ⟹ openin(subtopology euclidean S) C"
          "⋀T. openin(subtopology euclidean S) T ⟹ ∃𝒰. 𝒰 ⊆ ℬ ∧ T = ⋃𝒰"
proof -
  obtain  :: "'a set set"
    where "countable ℬ"
      and opeB: "⋀C. C ∈ ℬ ⟹ openin(subtopology euclidean S) C"
      and :    "⋀T. openin(subtopology euclidean S) T ⟹ ∃𝒰. 𝒰 ⊆ ℬ ∧ T = ⋃𝒰"
  proof -
    obtain 𝒞 :: "'a set set"
      where "countable 𝒞" and ope: "⋀C. C ∈ 𝒞 ⟹ open C"
        and 𝒞: "⋀S. open S ⟹ ∃U. U ⊆ 𝒞 ∧ S = ⋃U"
      by (metis univ_second_countable that)
    show ?thesis
    proof
      show "countable ((λC. S ∩ C) ` 𝒞)"
        by (simp add: ‹countable 𝒞›)
      show "⋀C. C ∈ op ∩ S ` 𝒞 ⟹ openin (subtopology euclidean S) C"
        using ope by auto
      show "⋀T. openin (subtopology euclidean S) T ⟹ ∃𝒰⊆op ∩ S ` 𝒞. T = ⋃𝒰"
        by (metis 𝒞 image_mono inf_Sup openin_open)
    qed
  qed
  show ?thesis
  proof
    show "countable (ℬ - {{}})"
      using ‹countable ℬ› by blast
    show "⋀C. ⟦C ∈ ℬ - {{}}⟧ ⟹ openin (subtopology euclidean S) C"
      by (simp add: ‹⋀C. C ∈ ℬ ⟹ openin (subtopology euclidean S) C›)
    show "∃𝒰⊆ℬ - {{}}. T = ⋃𝒰" if "openin (subtopology euclidean S) T" for T
      using  [OF that]
      apply clarify
      apply (rule_tac x="𝒰 - {{}}" in exI, auto)
        done
  qed auto
qed

lemma univ_second_countable_sequence:
  obtains B :: "nat ⇒ 'a::euclidean_space set"
    where "inj B" "⋀n. open(B n)" "⋀S. open S ⟹ ∃k. S = ⋃{B n |n. n ∈ k}"
proof -
  obtain  :: "'a set set"
  where "countable ℬ"
    and op: "⋀C. C ∈ ℬ ⟹ open C"
    and Un: "⋀S. open S ⟹ ∃U. U ⊆ ℬ ∧ S = ⋃U"
    using univ_second_countable by blast
  have *: "infinite (range (λn. ball (0::'a) (inverse(Suc n))))"
    apply (rule Infinite_Set.range_inj_infinite)
    apply (simp add: inj_on_def ball_eq_ball_iff)
    done
  have "infinite ℬ"
  proof
    assume "finite ℬ"
    then have "finite (Union ` (Pow ℬ))"
      by simp
    then have "finite (range (λn. ball (0::'a) (inverse(Suc n))))"
      apply (rule rev_finite_subset)
      by (metis (no_types, lifting) PowI image_eqI image_subset_iff Un [OF open_ball])
    with * show False by simp
  qed
  obtain f :: "nat ⇒ 'a set" where "ℬ = range f" "inj f"
    by (blast intro: countable_as_injective_image [OF ‹countable ℬ› ‹infinite ℬ›])
  have *: "∃k. S = ⋃{f n |n. n ∈ k}" if "open S" for S
    using Un [OF that]
    apply clarify
    apply (rule_tac x="f-`U" in exI)
    using ‹inj f› ‹ℬ = range f› apply force
    done
  show ?thesis
    apply (rule that [OF ‹inj f› _ *])
    apply (auto simp: ‹ℬ = range f› op)
    done
qed

proposition separable:
  fixes S :: "'a:: euclidean_space set"
  obtains T where "countable T" "T ⊆ S" "S ⊆ closure T"
proof -
  obtain  :: "'a:: euclidean_space set set"
    where "countable ℬ"
      and "{} ∉ ℬ"
      and ope: "⋀C. C ∈ ℬ ⟹ openin(subtopology euclidean S) C"
      and if_ope: "⋀T. openin(subtopology euclidean S) T ⟹ ∃𝒰. 𝒰 ⊆ ℬ ∧ T = ⋃𝒰"
    by (meson subset_second_countable)
  then obtain f where f: "⋀C. C ∈ ℬ ⟹ f C ∈ C"
    by (metis equals0I)
  show ?thesis
  proof
    show "countable (f ` ℬ)"
      by (simp add: ‹countable ℬ›)
    show "f ` ℬ ⊆ S"
      using ope f openin_imp_subset by blast
    show "S ⊆ closure (f ` ℬ)"
    proof (clarsimp simp: closure_approachable)
      fix x and e::real
      assume "x ∈ S" "0 < e"
      have "openin (subtopology euclidean S) (S ∩ ball x e)"
        by (simp add: openin_Int_open)
      with if_ope obtain 𝒰 where  𝒰: "𝒰 ⊆ ℬ" "S ∩ ball x e = ⋃𝒰"
        by meson
      show "∃C ∈ ℬ. dist (f C) x < e"
      proof (cases "𝒰 = {}")
        case True
        then show ?thesis
          using ‹0 < e›  𝒰 ‹x ∈ S› by auto
      next
        case False
        then obtain C where "C ∈ 𝒰" by blast
        show ?thesis
        proof
          show "dist (f C) x < e"
            by (metis Int_iff Union_iff 𝒰 ‹C ∈ 𝒰› dist_commute f mem_ball subsetCE)
          show "C ∈ ℬ"
            using ‹𝒰 ⊆ ℬ› ‹C ∈ 𝒰› by blast
        qed
      qed
    qed
  qed
qed

proposition Lindelof:
  fixes  :: "'a::euclidean_space set set"
  assumes : "⋀S. S ∈ ℱ ⟹ open S"
  obtains ℱ' where "ℱ' ⊆ ℱ" "countable ℱ'" "⋃ℱ' = ⋃ℱ"
proof -
  obtain  :: "'a set set"
    where "countable ℬ" "⋀C. C ∈ ℬ ⟹ open C"
      and : "⋀S. open S ⟹ ∃U. U ⊆ ℬ ∧ S = ⋃U"
    using univ_second_countable by blast
  define 𝒟 where "𝒟 ≡ {S. S ∈ ℬ ∧ (∃U. U ∈ ℱ ∧ S ⊆ U)}"
  have "countable 𝒟"
    apply (rule countable_subset [OF _ ‹countable ℬ›])
    apply (force simp: 𝒟_def)
    done
  have "⋀S. ∃U. S ∈ 𝒟 ⟶ U ∈ ℱ ∧ S ⊆ U"
    by (simp add: 𝒟_def)
  then obtain G where G: "⋀S. S ∈ 𝒟 ⟶ G S ∈ ℱ ∧ S ⊆ G S"
    by metis
  have "⋃ℱ ⊆ ⋃𝒟"
    unfolding 𝒟_def by (blast dest:  )
  moreover have "⋃𝒟 ⊆ ⋃ℱ"
    using 𝒟_def by blast
  ultimately have eq1: "⋃ℱ = ⋃𝒟" ..
  have eq2: "⋃𝒟 = UNION 𝒟 G"
    using G eq1 by auto
  show ?thesis
    apply (rule_tac ℱ' = "G ` 𝒟" in that)
    using G ‹countable 𝒟›  apply (auto simp: eq1 eq2)
    done
qed

lemma Lindelof_openin:
  fixes  :: "'a::euclidean_space set set"
  assumes "⋀S. S ∈ ℱ ⟹ openin (subtopology euclidean U) S"
  obtains ℱ' where "ℱ' ⊆ ℱ" "countable ℱ'" "⋃ℱ' = ⋃ℱ"
proof -
  have "⋀S. S ∈ ℱ ⟹ ∃T. open T ∧ S = U ∩ T"
    using assms by (simp add: openin_open)
  then obtain tf where tf: "⋀S. S ∈ ℱ ⟹ open (tf S) ∧ (S = U ∩ tf S)"
    by metis
  have [simp]: "⋀ℱ'. ℱ' ⊆ ℱ ⟹ ⋃ℱ' = U ∩ ⋃(tf ` ℱ')"
    using tf by fastforce
  obtain 𝒢 where "countable 𝒢 ∧ 𝒢 ⊆ tf ` ℱ" "⋃𝒢 = UNION ℱ tf"
    using tf by (force intro: Lindelof [of "tf ` ℱ"])
  then obtain ℱ' where ℱ': "ℱ' ⊆ ℱ" "countable ℱ'" "⋃ℱ' = ⋃ℱ"
    by (clarsimp simp add: countable_subset_image)
  then show ?thesis ..
qed

lemma countable_disjoint_open_subsets:
  fixes  :: "'a::euclidean_space set set"
  assumes "⋀S. S ∈ ℱ ⟹ open S" and pw: "pairwise disjnt ℱ"
    shows "countable ℱ"
proof -
  obtain ℱ' where "ℱ' ⊆ ℱ" "countable ℱ'" "⋃ℱ' = ⋃ℱ"
    by (meson assms Lindelof)
  with pw have "ℱ ⊆ insert {} ℱ'"
    by (fastforce simp add: pairwise_def disjnt_iff)
  then show ?thesis
    by (simp add: ‹countable ℱ'› countable_subset)
qed

lemma closedin_compact:
   "⟦compact S; closedin (subtopology euclidean S) T⟧ ⟹ compact T"
by (metis closedin_closed compact_Int_closed)

lemma closedin_compact_eq:
  fixes S :: "'a::t2_space set"
  shows
   "compact S
         ⟹ (closedin (subtopology euclidean S) T ⟷
              compact T ∧ T ⊆ S)"
by (metis closedin_imp_subset closedin_compact closed_subset compact_imp_closed)

lemma continuous_imp_closed_map:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "closedin (subtopology euclidean S) U"
          "continuous_on S f" "image f S = T" "compact S"
    shows "closedin (subtopology euclidean T) (image f U)"
  by (metis assms closedin_compact_eq compact_continuous_image continuous_on_subset subset_image_iff)

lemma continuous_imp_quotient_map:
  fixes f :: "'a::metric_space ⇒ 'b::metric_space"
  assumes "continuous_on S f" "image f S = T" "compact S" "U ⊆ T"
    shows "openin (subtopology euclidean S) {x. x ∈ S ∧ f x ∈ U} ⟷
           openin (subtopology euclidean T) U"
  by (metis (no_types, lifting) Collect_cong assms closed_map_imp_quotient_map continuous_imp_closed_map)

subsection‹ Finite intersection property›

text‹Also developed in HOL's toplogical spaces theory, but the Heine-Borel type class isn't available there.›

lemma closed_imp_fip:
  fixes S :: "'a::heine_borel set"
  assumes "closed S"
      and T: "T ∈ ℱ" "bounded T"
      and clof: "⋀T. T ∈ ℱ ⟹ closed T"
      and none: "⋀ℱ'. ⟦finite ℱ'; ℱ' ⊆ ℱ⟧ ⟹ S ∩ ⋂ℱ' ≠ {}"
    shows "S ∩ ⋂ℱ ≠ {}"
proof -
  have "compact (S ∩ T)"
    using ‹closed S› clof compact_eq_bounded_closed T by blast
  then have "(S ∩ T) ∩ ⋂ℱ ≠ {}"
    apply (rule compact_imp_fip)
     apply (simp add: clof)
    by (metis Int_assoc complete_lattice_class.Inf_insert finite_insert insert_subset none ‹T ∈ ℱ›)
  then show ?thesis by blast
qed

lemma closed_imp_fip_compact:
  fixes S :: "'a::heine_borel set"
  shows
   "⟦closed S; ⋀T. T ∈ ℱ ⟹ compact T;
     ⋀ℱ'. ⟦finite ℱ'; ℱ' ⊆ ℱ⟧ ⟹ S ∩ ⋂ℱ' ≠ {}⟧
        ⟹ S ∩ ⋂ℱ ≠ {}"
by (metis Inf_greatest closed_imp_fip compact_eq_bounded_closed empty_subsetI finite.emptyI inf.orderE)

lemma closed_fip_heine_borel:
  fixes  :: "'a::heine_borel set set"
  assumes "closed S" "T ∈ ℱ" "bounded T"
      and "⋀T. T ∈ ℱ ⟹ closed T"
      and "⋀ℱ'. ⟦finite ℱ'; ℱ' ⊆ ℱ⟧ ⟹ ⋂ℱ' ≠ {}"
    shows "⋂ℱ ≠ {}"
proof -
  have "UNIV ∩ ⋂ℱ ≠ {}"
    using assms closed_imp_fip [OF closed_UNIV] by auto
  then show ?thesis by simp
qed

lemma compact_fip_heine_borel:
  fixes  :: "'a::heine_borel set set"
  assumes clof: "⋀T. T ∈ ℱ ⟹ compact T"
      and none: "⋀ℱ'. ⟦finite ℱ'; ℱ' ⊆ ℱ⟧ ⟹ ⋂ℱ' ≠ {}"
    shows "⋂ℱ ≠ {}"
by (metis InterI all_not_in_conv clof closed_fip_heine_borel compact_eq_bounded_closed none)

lemma compact_sequence_with_limit:
  fixes f :: "nat ⇒ 'a::heine_borel"
  shows "(f ⤏ l) sequentially ⟹ compact (insert l (range f))"
apply (simp add: compact_eq_bounded_closed, auto)
apply (simp add: convergent_imp_bounded)
by (simp add: closed_limpt islimpt_insert sequence_unique_limpt)


subsection‹Componentwise limits and continuity›

text‹But is the premise really necessary? Need to generalise @{thm euclidean_dist_l2}›
lemma Euclidean_dist_upper: "i ∈ Basis ⟹ dist (x ∙ i) (y ∙ i) ≤ dist x y"
  by (metis (no_types) member_le_setL2 euclidean_dist_l2 finite_Basis)

text‹But is the premise @{term ‹i ∈ Basis›} really necessary?›
lemma open_preimage_inner:
  assumes "open S" "i ∈ Basis"
    shows "open {x. x ∙ i ∈ S}"
proof (rule openI, simp)
  fix x
  assume x: "x ∙ i ∈ S"
  with assms obtain e where "0 < e" and e: "ball (x ∙ i) e ⊆ S"
    by (auto simp: open_contains_ball_eq)
  have "∃e>0. ball (y ∙ i) e ⊆ S" if dxy: "dist x y < e / 2" for y
  proof (intro exI conjI)
    have "dist (x ∙ i) (y ∙ i) < e / 2"
      by (meson ‹i ∈ Basis› dual_order.trans Euclidean_dist_upper not_le that)
    then have "dist (x ∙ i) z < e" if "dist (y ∙ i) z < e / 2" for z
      by (metis dist_commute dist_triangle_half_l that)
    then have "ball (y ∙ i) (e / 2) ⊆ ball (x ∙ i) e"
      using mem_ball by blast
      with e show "ball (y ∙ i) (e / 2) ⊆ S"
        by (metis order_trans)
  qed (simp add: ‹0 < e›)
  then show "∃e>0. ball x e ⊆ {s. s ∙ i ∈ S}"
    by (metis (no_types, lifting) ‹0 < e› ‹open S› half_gt_zero_iff mem_Collect_eq mem_ball open_contains_ball_eq subsetI)
qed

proposition tendsto_componentwise_iff:
  fixes f :: "_ ⇒ 'b::euclidean_space"
  shows "(f ⤏ l) F ⟷ (∀i ∈ Basis. ((λx. (f x ∙ i)) ⤏ (l ∙ i)) F)"
         (is "?lhs = ?rhs")
proof
  assume ?lhs
  then show ?rhs
    unfolding tendsto_def
    apply clarify
    apply (drule_tac x="{s. s ∙ i ∈ S}" in spec)
    apply (auto simp: open_preimage_inner)
    done
next
  assume R: ?rhs
  then have "⋀e. e > 0 ⟹ ∀i∈Basis. ∀F x in F. dist (f x ∙ i) (l ∙ i) < e"
    unfolding tendsto_iff by blast
  then have R': "⋀e. e > 0 ⟹ ∀F x in F. ∀i∈Basis. dist (f x ∙ i) (l ∙ i) < e"
      by (simp add: eventually_ball_finite_distrib [symmetric])
  show ?lhs
  unfolding tendsto_iff
  proof clarify
    fix e::real
    assume "0 < e"
    have *: "setL2 (λi. dist (f x ∙ i) (l ∙ i)) Basis < e"
             if "∀i∈Basis. dist (f x ∙ i) (l ∙ i) < e / real DIM('b)" for x
    proof -
      have "setL2 (λi. dist (f x ∙ i) (l ∙ i)) Basis ≤ sum (λi. dist (f x ∙ i) (l ∙ i)) Basis"
        by (simp add: setL2_le_sum)
      also have "... < DIM('b) * (e / real DIM('b))"
        apply (rule sum_bounded_above_strict)
        using that by auto
      also have "... = e"
        by (simp add: field_simps)
      finally show "setL2 (λi. dist (f x ∙ i) (l ∙ i)) Basis < e" .
    qed
    have "∀F x in F. ∀i∈Basis. dist (f x ∙ i) (l ∙ i) < e / DIM('b)"
      apply (rule R')
      using ‹0 < e› by simp
    then show "∀F x in F. dist (f x) l < e"
      apply (rule eventually_mono)
      apply (subst euclidean_dist_l2)
      using * by blast
  qed
qed


corollary continuous_componentwise:
   "continuous F f ⟷ (∀i ∈ Basis. continuous F (λx. (f x ∙ i)))"
by (simp add: continuous_def tendsto_componentwise_iff [symmetric])

corollary continuous_on_componentwise:
  fixes S :: "'a :: t2_space set"
  shows "continuous_on S f ⟷ (∀i ∈ Basis. continuous_on S (λx. (f x ∙ i)))"
  apply (simp add: continuous_on_eq_continuous_within)
  using continuous_componentwise by blast

lemma linear_componentwise_iff:
     "(linear f') ⟷ (∀i∈Basis. linear (λx. f' x ∙ i))"
  apply (auto simp: linear_iff inner_left_distrib)
   apply (metis inner_left_distrib euclidean_eq_iff)
  by (metis euclidean_eqI inner_scaleR_left)

lemma bounded_linear_componentwise_iff:
     "(bounded_linear f') ⟷ (∀i∈Basis. bounded_linear (λx. f' x ∙ i))"
     (is "?lhs = ?rhs")
proof
  assume ?lhs then show ?rhs
    by (simp add: bounded_linear_inner_left_comp)
next
  assume ?rhs
  then have "(∀i∈Basis. ∃K. ∀x. ¦f' x ∙ i¦ ≤ norm x * K)" "linear f'"
    by (auto simp: bounded_linear_def bounded_linear_axioms_def linear_componentwise_iff [symmetric] ball_conj_distrib)
  then obtain F where F: "⋀i x. i ∈ Basis ⟹ ¦f' x ∙ i¦ ≤ norm x * F i"
    by metis
  have "norm (f' x) ≤ norm x * sum F Basis" for x
  proof -
    have "norm (f' x) ≤ (∑i∈Basis. ¦f' x ∙ i¦)"
      by (rule norm_le_l1)
    also have "... ≤ (∑i∈Basis. norm x * F i)"
      by (metis F sum_mono)
    also have "... = norm x * sum F Basis"
      by (simp add: sum_distrib_left)
    finally show ?thesis .
  qed
  then show ?lhs
    by (force simp: bounded_linear_def bounded_linear_axioms_def ‹linear f'›)
qed

subsection‹Pasting functions together›

subsubsection‹on open sets›

lemma pasting_lemma:
  fixes f :: "'i ⇒ 'a::topological_space ⇒ 'b::topological_space"
  assumes clo: "⋀i. i ∈ I ⟹ openin (subtopology euclidean S) (T i)"
      and cont: "⋀i. i ∈ I ⟹ continuous_on (T i) (f i)"
      and f: "⋀i j x. ⟦i ∈ I; j ∈ I; x ∈ S ∩ T i ∩ T j⟧ ⟹ f i x = f j x"
      and g: "⋀x. x ∈ S ⟹ ∃j. j ∈ I ∧ x ∈ T j ∧ g x = f j x"
    shows "continuous_on S g"
proof (clarsimp simp: continuous_openin_preimage_eq)
  fix U :: "'b set"
  assume "open U"
  have S: "⋀i. i ∈ I ⟹ (T i) ⊆ S"
    using clo openin_imp_subset by blast
  have *: "{x ∈ S. g x ∈ U} = ⋃{{x. x ∈ (T i) ∧ (f i x) ∈ U} |i. i ∈ I}"
    apply (auto simp: dest: S)
      apply (metis (no_types, lifting) g mem_Collect_eq)
    using clo f g openin_imp_subset by fastforce
  show "openin (subtopology euclidean S) {x ∈ S. g x ∈ U}"
    apply (subst *)
    apply (rule openin_Union, clarify)
    apply (metis (full_types) ‹open U› cont clo openin_trans continuous_openin_preimage_gen)
    done
qed

lemma pasting_lemma_exists:
  fixes f :: "'i ⇒ 'a::topological_space ⇒ 'b::topological_space"
  assumes S: "S ⊆ (⋃i ∈ I. T i)"
      and clo: "⋀i. i ∈ I ⟹ openin (subtopology euclidean S) (T i)"
      and cont: "⋀i. i ∈ I ⟹ continuous_on (T i) (f i)"
      and f: "⋀i j x. ⟦i ∈ I; j ∈ I; x ∈ S ∩ T i ∩ T j⟧ ⟹ f i x = f j x"
    obtains g where "continuous_on S g" "⋀x i. ⟦i ∈ I; x ∈ S ∩ T i⟧ ⟹ g x = f i x"
proof
  show "continuous_on S (λx. f (SOME i. i ∈ I ∧ x ∈ T i) x)"
    apply (rule pasting_lemma [OF clo cont])
     apply (blast intro: f)+
    apply (metis (mono_tags, lifting) S UN_iff subsetCE someI)
    done
next
  fix x i
  assume "i ∈ I" "x ∈ S ∩ T i"
  then show "f (SOME i. i ∈ I ∧ x ∈ T i) x = f i x"
    by (metis (no_types, lifting) IntD2 IntI f someI_ex)
qed

subsubsection‹Likewise on closed sets, with a finiteness assumption›

lemma pasting_lemma_closed:
  fixes f :: "'i ⇒ 'a::topological_space ⇒ 'b::topological_space"
  assumes "finite I"
      and clo: "⋀i. i ∈ I ⟹ closedin (subtopology euclidean S) (T i)"
      and cont: "⋀i. i ∈ I ⟹ continuous_on (T i) (f i)"
      and f: "⋀i j x. ⟦i ∈ I; j ∈ I; x ∈ S ∩ T i ∩ T j⟧ ⟹ f i x = f j x"
      and g: "⋀x. x ∈ S ⟹ ∃j. j ∈ I ∧ x ∈ T j ∧ g x = f j x"
    shows "continuous_on S g"
proof (clarsimp simp: continuous_closedin_preimage_eq)
  fix U :: "'b set"
  assume "closed U"
  have *: "{x ∈ S. g x ∈ U} = ⋃{{x. x ∈ (T i) ∧ (f i x) ∈ U} |i. i ∈ I}"
    apply auto
    apply (metis (no_types, lifting) g mem_Collect_eq)
    using clo closedin_closed apply blast
    apply (metis Int_iff f g clo closedin_limpt inf.absorb_iff2)
    done
  show "closedin (subtopology euclidean S) {x ∈ S. g x ∈ U}"
    apply (subst *)
    apply (rule closedin_Union)
    using ‹finite I› apply simp
    apply (blast intro: ‹closed U› continuous_closedin_preimage cont clo closedin_trans)
    done
qed

lemma pasting_lemma_exists_closed:
  fixes f :: "'i ⇒ 'a::topological_space ⇒ 'b::topological_space"
  assumes "finite I"
      and S: "S ⊆ (⋃i ∈ I. T i)"
      and clo: "⋀i. i ∈ I ⟹ closedin (subtopology euclidean S) (T i)"
      and cont: "⋀i. i ∈ I ⟹ continuous_on (T i) (f i)"
      and f: "⋀i j x. ⟦i ∈ I; j ∈ I; x ∈ S ∩ T i ∩ T j⟧ ⟹ f i x = f j x"
    obtains g where "continuous_on S g" "⋀x i. ⟦i ∈ I; x ∈ S ∩ T i⟧ ⟹ g x = f i x"
proof
  show "continuous_on S (λx. f (SOME i. i ∈ I ∧ x ∈ T i) x)"
    apply (rule pasting_lemma_closed [OF ‹finite I› clo cont])
     apply (blast intro: f)+
    apply (metis (mono_tags, lifting) S UN_iff subsetCE someI)
    done
next
  fix x i
  assume "i ∈ I" "x ∈ S ∩ T i"
  then show "f (SOME i. i ∈ I ∧ x ∈ T i) x = f i x"
    by (metis (no_types, lifting) IntD2 IntI f someI_ex)
qed

lemma tube_lemma:
  assumes "compact K"
  assumes "open W"
  assumes "{x0} × K ⊆ W"
  shows "∃X0. x0 ∈ X0 ∧ open X0 ∧ X0 × K ⊆ W"
proof -
  {
    fix y assume "y ∈ K"
    then have "(x0, y) ∈ W" using assms by auto
    with ‹open W›
    have "∃X0 Y. open X0 ∧ open Y ∧ x0 ∈ X0 ∧ y ∈ Y ∧ X0 × Y ⊆ W"
      by (rule open_prod_elim) blast
  }
  then obtain X0 Y where
    *: "∀y ∈ K. open (X0 y) ∧ open (Y y) ∧ x0 ∈ X0 y ∧ y ∈ Y y ∧ X0 y × Y y ⊆ W"
    by metis
  from * have "∀t∈Y ` K. open t" "K ⊆ ⋃(Y ` K)" by auto
  with ‹compact K› obtain CC where CC: "CC ⊆ Y ` K" "finite CC" "K ⊆ ⋃CC"
    by (meson compactE)
  then obtain c where c: "⋀C. C ∈ CC ⟹ c C ∈ K ∧ C = Y (c C)"
    by (force intro!: choice)
  with * CC show ?thesis
    by (force intro!: exI[where x="⋂C∈CC. X0 (c C)"]) (* SLOW *)
qed

lemma continuous_on_prod_compactE:
  fixes fx::"'a::topological_space × 'b::topological_space ⇒ 'c::metric_space"
    and e::real
  assumes cont_fx: "continuous_on (U × C) fx"
  assumes "compact C"
  assumes [intro]: "x0 ∈ U"
  notes [continuous_intros] = continuous_on_compose2[OF cont_fx]
  assumes "e > 0"
  obtains X0 where "x0 ∈ X0" "open X0"
    "∀x∈X0 ∩ U. ∀t ∈ C. dist (fx (x, t)) (fx (x0, t)) ≤ e"
proof -
  define psi where "psi = (λ(x, t). dist (fx (x, t)) (fx (x0, t)))"
  define W0 where "W0 = {(x, t) ∈ U × C. psi (x, t) < e}"
  have W0_eq: "W0 = psi -` {..<e} ∩ U × C"
    by (auto simp: vimage_def W0_def)
  have "open {..<e}" by simp
  have "continuous_on (U × C) psi"
    by (auto intro!: continuous_intros simp: psi_def split_beta')
  from this[unfolded continuous_on_open_invariant, rule_format, OF ‹open {..<e}›]
  obtain W where W: "open W" "W ∩ U × C = W0 ∩ U × C"
    unfolding W0_eq by blast
  have "{x0} × C ⊆ W ∩ U × C"
    unfolding W
    by (auto simp: W0_def psi_def ‹0 < e›)
  then have "{x0} × C ⊆ W" by blast
  from tube_lemma[OF ‹compact C› ‹open W› this]
  obtain X0 where X0: "x0 ∈ X0" "open X0" "X0 × C ⊆ W"
    by blast

  have "∀x∈X0 ∩ U. ∀t ∈ C. dist (fx (x, t)) (fx (x0, t)) ≤ e"
  proof safe
    fix x assume x: "x ∈ X0" "x ∈ U"
    fix t assume t: "t ∈ C"
    have "dist (fx (x, t)) (fx (x0, t)) = psi (x, t)"
      by (auto simp: psi_def)
    also
    {
      have "(x, t) ∈ X0 × C"
        using t x
        by auto
      also note ‹… ⊆ W›
      finally have "(x, t) ∈ W" .
      with t x have "(x, t) ∈ W ∩ U × C"
        by blast
      also note ‹W ∩ U × C = W0 ∩ U × C›
      finally  have "psi (x, t) < e"
        by (auto simp: W0_def)
    }
    finally show "dist (fx (x, t)) (fx (x0, t)) ≤ e" by simp
  qed
  from X0(1,2) this show ?thesis ..
qed


subsection‹Constancy of a function from a connected set into a finite, disconnected or discrete set›

text‹Still missing: versions for a set that is smaller than R, or countable.›

lemma continuous_disconnected_range_constant:
  assumes s: "connected s"
      and conf: "continuous_on s f"
      and fim: "f ` s ⊆ t"
      and cct: "⋀y. y ∈ t ⟹ connected_component_set t y = {y}"
    shows "∃a. ∀x ∈ s. f x = a"
proof (cases "s = {}")
  case True then show ?thesis by force
next
  case False
  { fix x assume "x ∈ s"
    then have "f ` s ⊆ {f x}"
    by (metis connected_continuous_image conf connected_component_maximal fim image_subset_iff rev_image_eqI s cct)
  }
  with False show ?thesis
    by blast
qed

lemma discrete_subset_disconnected:
  fixes s :: "'a::topological_space set"
  fixes t :: "'b::real_normed_vector set"
  assumes conf: "continuous_on s f"
      and no: "⋀x. x ∈ s ⟹ ∃e>0. ∀y. y ∈ s ∧ f y ≠ f x ⟶ e ≤ norm (f y - f x)"
   shows "f ` s ⊆ {y. connected_component_set (f ` s) y = {y}}"
proof -
  { fix x assume x: "x ∈ s"
    then obtain e where "e>0" and ele: "⋀y. ⟦y ∈ s; f y ≠ f x⟧ ⟹ e ≤ norm (f y - f x)"
      using conf no [OF x] by auto
    then have e2: "0 ≤ e / 2"
      by simp
    have "f y = f x" if "y ∈ s" and ccs: "f y ∈ connected_component_set (f ` s) (f x)" for y
      apply (rule ccontr)
      using connected_closed [of "connected_component_set (f ` s) (f x)"] ‹e>0›
      apply (simp add: del: ex_simps)
      apply (drule spec [where x="cball (f x) (e / 2)"])
      apply (drule spec [where x="- ball(f x) e"])
      apply (auto simp: dist_norm open_closed [symmetric] simp del: le_divide_eq_numeral1 dest!: connected_component_in)
        apply (metis diff_self e2 ele norm_minus_commute norm_zero not_less)
       using centre_in_cball connected_component_refl_eq e2 x apply blast
      using ccs
      apply (force simp: cball_def dist_norm norm_minus_commute dest: ele [OF ‹y ∈ s›])
      done
    moreover have "connected_component_set (f ` s) (f x) ⊆ f ` s"
      by (auto simp: connected_component_in)
    ultimately have "connected_component_set (f ` s) (f x) = {f x}"
      by (auto simp: x)
  }
  with assms show ?thesis
    by blast
qed

lemma finite_implies_discrete:
  fixes s :: "'a::topological_space set"
  assumes "finite (f ` s)"
  shows "(∀x ∈ s. ∃e>0. ∀y. y ∈ s ∧ f y ≠ f x ⟶ e ≤ norm (f y - f x))"
proof -
  have "∃e>0. ∀y. y ∈ s ∧ f y ≠ f x ⟶ e ≤ norm (f y - f x)" if "x ∈ s" for x
  proof (cases "f ` s - {f x} = {}")
    case True
    with zero_less_numeral show ?thesis
      by (fastforce simp add: Set.image_subset_iff cong: conj_cong)
  next
    case False
    then obtain z where z: "z ∈ s" "f z ≠ f x"
      by blast
    have finn: "finite {norm (z - f x) |z. z ∈ f ` s - {f x}}"
      using assms by simp
    then have *: "0 < Inf{norm(z - f x) | z. z ∈ f ` s - {f x}}"
      apply (rule finite_imp_less_Inf)
      using z apply force+
      done
    show ?thesis
      by (force intro!: * cInf_le_finite [OF finn])
  qed
  with assms show ?thesis
    by blast
qed

text‹This proof requires the existence of two separate values of the range type.›
lemma finite_range_constant_imp_connected:
  assumes "⋀f::'a::topological_space ⇒ 'b::real_normed_algebra_1.
              ⟦continuous_on s f; finite(f ` s)⟧ ⟹ ∃a. ∀x ∈ s. f x = a"
    shows "connected s"
proof -
  { fix t u
    assume clt: "closedin (subtopology euclidean s) t"
       and clu: "closedin (subtopology euclidean s) u"
       and tue: "t ∩ u = {}" and tus: "t ∪ u = s"
    have conif: "continuous_on s (λx. if x ∈ t then 0 else 1)"
      apply (subst tus [symmetric])
      apply (rule continuous_on_cases_local)
      using clt clu tue
      apply (auto simp: tus continuous_on_const)
      done
    have fi: "finite ((λx. if x ∈ t then 0 else 1) ` s)"
      by (rule finite_subset [of _ "{0,1}"]) auto
    have "t = {} ∨ u = {}"
      using assms [OF conif fi] tus [symmetric]
      by (auto simp: Ball_def) (metis IntI empty_iff one_neq_zero tue)
  }
  then show ?thesis
    by (simp add: connected_closedin_eq)
qed

lemma continuous_disconnected_range_constant_eq:
      "(connected S ⟷
           (∀f::'a::topological_space ⇒ 'b::real_normed_algebra_1.
            ∀t. continuous_on S f ∧ f ` S ⊆ t ∧ (∀y ∈ t. connected_component_set t y = {y})
            ⟶ (∃a::'b. ∀x ∈ S. f x = a)))" (is ?thesis1)
  and continuous_discrete_range_constant_eq:
      "(connected S ⟷
         (∀f::'a::topological_space ⇒ 'b::real_normed_algebra_1.
          continuous_on S f ∧
          (∀x ∈ S. ∃e. 0 < e ∧ (∀y. y ∈ S ∧ (f y ≠ f x) ⟶ e ≤ norm(f y - f x)))
          ⟶ (∃a::'b. ∀x ∈ S. f x = a)))" (is ?thesis2)
  and continuous_finite_range_constant_eq:
      "(connected S ⟷
         (∀f::'a::topological_space ⇒ 'b::real_normed_algebra_1.
          continuous_on S f ∧ finite (f ` S)
          ⟶ (∃a::'b. ∀x ∈ S. f x = a)))" (is ?thesis3)
proof -
  have *: "⋀s t u v. ⟦s ⟹ t; t ⟹ u; u ⟹ v; v ⟹ s⟧
    ⟹ (s ⟷ t) ∧ (s ⟷ u) ∧ (s ⟷ v)"
    by blast
  have "?thesis1 ∧ ?thesis2 ∧ ?thesis3"
    apply (rule *)
    using continuous_disconnected_range_constant apply metis
    apply clarify
    apply (frule discrete_subset_disconnected; blast)
    apply (blast dest: finite_implies_discrete)
    apply (blast intro!: finite_range_constant_imp_connected)
    done
  then show ?thesis1 ?thesis2 ?thesis3
    by blast+
qed

lemma continuous_discrete_range_constant:
  fixes f :: "'a::topological_space ⇒ 'b::real_normed_algebra_1"
  assumes S: "connected S"
      and "continuous_on S f"
      and "⋀x. x ∈ S ⟹ ∃e>0. ∀y. y ∈ S ∧ f y ≠ f x ⟶ e ≤ norm (f y - f x)"
    obtains a where "⋀x. x ∈ S ⟹ f x = a"
  using continuous_discrete_range_constant_eq [THEN iffD1, OF S] assms
  by blast

lemma continuous_finite_range_constant:
  fixes f :: "'a::topological_space ⇒ 'b::real_normed_algebra_1"
  assumes "connected S"
      and "continuous_on S f"
      and "finite (f ` S)"
    obtains a where "⋀x. x ∈ S ⟹ f x = a"
  using assms continuous_finite_range_constant_eq
  by blast



subsection ‹Continuous Extension›

definition clamp :: "'a::euclidean_space ⇒ 'a ⇒ 'a ⇒ 'a" where
  "clamp a b x = (if (∀i∈Basis. a ∙ i ≤ b ∙ i)
    then (∑i∈Basis. (if x∙i < a∙i then a∙i else if x∙i ≤ b∙i then x∙i else b∙i) *R i)
    else a)"

lemma clamp_in_interval[simp]:
  assumes "⋀i. i ∈ Basis ⟹ a ∙ i ≤ b ∙ i"
  shows "clamp a b x ∈ cbox a b"
  unfolding clamp_def
  using box_ne_empty(1)[of a b] assms by (auto simp: cbox_def)

lemma clamp_cancel_cbox[simp]:
  fixes x a b :: "'a::euclidean_space"
  assumes x: "x ∈ cbox a b"
  shows "clamp a b x = x"
  using assms
  by (auto simp: clamp_def mem_box intro!: euclidean_eqI[where 'a='a])

lemma clamp_empty_interval:
  assumes "i ∈ Basis" "a ∙ i > b ∙ i"
  shows "clamp a b = (λ_. a)"
  using assms
  by (force simp: clamp_def[abs_def] split: if_splits intro!: ext)

lemma dist_clamps_le_dist_args:
  fixes x :: "'a::euclidean_space"
  shows "dist (clamp a b y) (clamp a b x) ≤ dist y x"
proof cases
  assume le: "(∀i∈Basis. a ∙ i ≤ b ∙ i)"
  then have "(∑i∈Basis. (dist (clamp a b y ∙ i) (clamp a b x ∙ i))2) ≤
    (∑i∈Basis. (dist (y ∙ i) (x ∙ i))2)"
    by (auto intro!: sum_mono simp: clamp_def dist_real_def abs_le_square_iff[symmetric])
  then show ?thesis
    by (auto intro: real_sqrt_le_mono
      simp: euclidean_dist_l2[where y=x] euclidean_dist_l2[where y="clamp a b x"] setL2_def)
qed (auto simp: clamp_def)

lemma clamp_continuous_at:
  fixes f :: "'a::euclidean_space ⇒ 'b::metric_space"
    and x :: 'a
  assumes f_cont: "continuous_on (cbox a b) f"
  shows "continuous (at x) (λx. f (clamp a b x))"
proof cases
  assume le: "(∀i∈Basis. a ∙ i ≤ b ∙ i)"
  show ?thesis
    unfolding continuous_at_eps_delta
  proof safe
    fix x :: 'a
    fix e :: real
    assume "e > 0"
    moreover have "clamp a b x ∈ cbox a b"
      by (simp add: clamp_in_interval le)
    moreover note f_cont[simplified continuous_on_iff]
    ultimately
    obtain d where d: "0 < d"
      "⋀x'. x' ∈ cbox a b ⟹ dist x' (clamp a b x) < d ⟹ dist (f x') (f (clamp a b x)) < e"
      by force
    show "∃d>0. ∀x'. dist x' x < d ⟶
      dist (f (clamp a b x')) (f (clamp a b x)) < e"
      using le
      by (auto intro!: d clamp_in_interval dist_clamps_le_dist_args[THEN le_less_trans])
  qed
qed (auto simp: clamp_empty_interval)

lemma clamp_continuous_on:
  fixes f :: "'a::euclidean_space ⇒ 'b::metric_space"
  assumes f_cont: "continuous_on (cbox a b) f"
  shows "continuous_on S (λx. f (clamp a b x))"
  using assms
  by (auto intro: continuous_at_imp_continuous_on clamp_continuous_at)

lemma clamp_bounded:
  fixes f :: "'a::euclidean_space ⇒ 'b::metric_space"
  assumes bounded: "bounded (f ` (cbox a b))"
  shows "bounded (range (λx. f (clamp a b x)))"
proof cases
  assume le: "(∀i∈Basis. a ∙ i ≤ b ∙ i)"
  from bounded obtain c where f_bound: "∀x∈f ` cbox a b. dist undefined x ≤ c"
    by (auto simp: bounded_any_center[where a=undefined])
  then show ?thesis
    by (auto intro!: exI[where x=c] clamp_in_interval[OF le[rule_format]]
        simp: bounded_any_center[where a=undefined])
qed (auto simp: clamp_empty_interval image_def)


definition ext_cont :: "('a::euclidean_space ⇒ 'b::metric_space) ⇒ 'a ⇒ 'a ⇒ 'a ⇒ 'b"
  where "ext_cont f a b = (λx. f (clamp a b x))"

lemma ext_cont_cancel_cbox[simp]:
  fixes x a b :: "'a::euclidean_space"
  assumes x: "x ∈ cbox a b"
  shows "ext_cont f a b x = f x"
  using assms
  unfolding ext_cont_def
  by (auto simp: clamp_def mem_box intro!: euclidean_eqI[where 'a='a] arg_cong[where f=f])

lemma continuous_on_ext_cont[continuous_intros]:
  "continuous_on (cbox a b) f ⟹ continuous_on S (ext_cont f a b)"
  by (auto intro!: clamp_continuous_on simp: ext_cont_def)

no_notation
  eucl_less (infix "<e" 50)

end