merged
authorblanchet
Wed, 11 Feb 2009 13:47:28 +0100
changeset 29873 7c301075eef1
parent 29862 d203e9d4675b (diff)
parent 29872 14e208d607af (current diff)
child 29876 68e9a8d97475
merged
--- a/CONTRIBUTORS	Tue Feb 10 18:57:02 2009 +0100
+++ b/CONTRIBUTORS	Wed Feb 11 13:47:28 2009 +0100
@@ -7,6 +7,9 @@
 Contributions to this Isabelle version
 --------------------------------------
 
+* February 2008: Timothy Bourke, NICTA
+  "solves" criterion for find_theorems and auto_solve option
+
 * December 2008: Clemens Ballarin, TUM
   New locale implementation.
 
--- a/NEWS	Tue Feb 10 18:57:02 2009 +0100
+++ b/NEWS	Wed Feb 11 13:47:28 2009 +0100
@@ -183,6 +183,16 @@
 * The 'axiomatization' command now only works within a global theory
 context.  INCOMPATIBILITY.
 
+* New find_theorems criterion "solves" matching theorems that 
+  directly solve the current goal. Try "find_theorems solves".
+
+* Added an auto solve option, which can be enabled through the
+  ProofGeneral Isabelle settings menu (disabled by default).
+ 
+  When enabled, find_theorems solves is called whenever a new lemma
+  is stated. Any theorems that could solve the lemma directly are
+  listed underneath the goal.
+
 
 *** Document preparation ***
 
--- a/src/HOL/Decision_Procs/Dense_Linear_Order.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Decision_Procs/Dense_Linear_Order.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -875,5 +875,58 @@
 end
 *}
 
+lemma upper_bound_finite_set:
+  assumes fS: "finite S"
+  shows "\<exists>(a::'a::linorder). \<forall>x \<in> S. f x \<le> a"
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by simp
+next
+  case (2 x F)
+  from "2.hyps" obtain a where a:"\<forall>x \<in>F. f x \<le> a" by blast
+  let ?a = "max a (f x)"
+  have m: "a \<le> ?a" "f x \<le> ?a" by simp_all
+  {fix y assume y: "y \<in> insert x F"
+    {assume "y = x" hence "f y \<le> ?a" using m by simp}
+    moreover
+    {assume yF: "y\<in> F" from a[rule_format, OF yF] m have "f y \<le> ?a" by (simp add: max_def)}
+    ultimately have "f y \<le> ?a" using y by blast}
+  then show ?case by blast
+qed
+
+lemma lower_bound_finite_set:
+  assumes fS: "finite S"
+  shows "\<exists>(a::'a::linorder). \<forall>x \<in> S. f x \<ge> a"
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by simp
+next
+  case (2 x F)
+  from "2.hyps" obtain a where a:"\<forall>x \<in>F. f x \<ge> a" by blast
+  let ?a = "min a (f x)"
+  have m: "a \<ge> ?a" "f x \<ge> ?a" by simp_all
+  {fix y assume y: "y \<in> insert x F"
+    {assume "y = x" hence "f y \<ge> ?a" using m by simp}
+    moreover
+    {assume yF: "y\<in> F" from a[rule_format, OF yF] m have "f y \<ge> ?a" by (simp add: min_def)}
+    ultimately have "f y \<ge> ?a" using y by blast}
+  then show ?case by blast
+qed
+
+lemma bound_finite_set: assumes f: "finite S"
+  shows "\<exists>a. \<forall>x \<in>S. (f x:: 'a::linorder) \<le> a"
+proof-
+  let ?F = "f ` S"
+  from f have fF: "finite ?F" by simp
+  let ?a = "Max ?F"
+  {assume "S = {}" hence ?thesis by blast}
+  moreover
+  {assume Se: "S \<noteq> {}" hence Fe: "?F \<noteq> {}" by simp
+  {fix x assume x: "x \<in> S"
+    hence th0: "f x \<in> ?F" by simp
+    hence "f x \<le> ?a" using Max_ge[OF fF th0] ..}
+  hence ?thesis by blast}
+ultimately show ?thesis by blast
+qed
+
+
 
 end 
--- a/src/HOL/IsaMakefile	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/IsaMakefile	Wed Feb 11 13:47:28 2009 +0100
@@ -285,7 +285,6 @@
   Taylor.thy \
   Transcendental.thy \
   GCD.thy \
-  Order_Relation.thy \
   Parity.thy \
   Lubs.thy \
   Polynomial.thy \
@@ -314,13 +313,15 @@
 $(LOG)/HOL-Library.gz: $(OUT)/HOL Library/SetsAndFunctions.thy		\
   Library/Abstract_Rat.thy \
   Library/BigO.thy Library/ContNotDenum.thy Library/Efficient_Nat.thy	\
+  Library/Euclidean_Space.thy Library/Glbs.thy Library/normarith.ML \
   Library/Executable_Set.thy Library/Infinite_Set.thy			\
-  Library/FuncSet.thy	\
+  Library/FuncSet.thy Library/Permutations.thy Library/Determinants.thy\
+  Library/Finite_Cartesian_Product.thy \
   Library/Library.thy Library/List_Prefix.thy Library/State_Monad.thy	\
   Library/Multiset.thy Library/Permutation.thy	\
   Library/Primes.thy Library/Pocklington.thy Library/Quotient.thy	\
   Library/Quicksort.thy Library/Nat_Infinity.thy Library/Word.thy	\
-  Library/README.html Library/Continuity.thy				\
+  Library/README.html Library/Continuity.thy Library/Order_Relation.thy \
   Library/Nested_Environment.thy Library/Ramsey.thy Library/Zorn.thy	\
   Library/Library/ROOT.ML Library/Library/document/root.tex		\
   Library/Library/document/root.bib Library/While_Combinator.thy	\
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Determinants.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,1151 @@
+(* Title:      Determinants
+   ID:         $Id: 
+   Author:     Amine Chaieb, University of Cambridge
+*)
+
+header {* Traces, Determinant of square matrices and some properties *}
+
+theory Determinants
+  imports Euclidean_Space Permutations
+begin
+
+subsection{* First some facts about products*}
+lemma setprod_insert_eq: "finite A \<Longrightarrow> setprod f (insert a A) = (if a \<in> A then setprod f A else f a * setprod f A)"
+apply clarsimp
+by(subgoal_tac "insert a A = A", auto)
+
+lemma setprod_add_split:
+  assumes mn: "(m::nat) <= n + 1"
+  shows "setprod f {m.. n+p} = setprod f {m .. n} * setprod f {n+1..n+p}"
+proof-
+  let ?A = "{m .. n+p}"
+  let ?B = "{m .. n}"
+  let ?C = "{n+1..n+p}"
+  from mn have un: "?B \<union> ?C = ?A" by auto
+  from mn have dj: "?B \<inter> ?C = {}" by auto
+  have f: "finite ?B" "finite ?C" by simp_all
+  from setprod_Un_disjoint[OF f dj, of f, unfolded un] show ?thesis .
+qed
+
+
+lemma setprod_offset: "setprod f {(m::nat) + p .. n + p} = setprod (\<lambda>i. f (i + p)) {m..n}"
+apply (rule setprod_reindex_cong[where f="op + p"])
+apply (auto simp add: image_iff Bex_def inj_on_def)
+apply arith
+apply (rule ext)
+apply (simp add: add_commute)
+done
+
+lemma setprod_singleton: "setprod f {x} = f x" by simp
+
+lemma setprod_singleton_nat_seg: "setprod f {n..n} = f (n::'a::order)" by simp
+
+lemma setprod_numseg: "setprod f {m..0} = (if m=0 then f 0 else 1)"
+  "setprod f {m .. Suc n} = (if m \<le> Suc n then f (Suc n) * setprod f {m..n} 
+                             else setprod f {m..n})"
+  by (auto simp add: atLeastAtMostSuc_conv)
+
+lemma setprod_le: assumes fS: "finite S" and fg: "\<forall>x\<in>S. f x \<ge> 0 \<and> f x \<le> (g x :: 'a::ordered_idom)"
+  shows "setprod f S \<le> setprod g S"
+using fS fg
+apply(induct S)
+apply simp
+apply auto
+apply (rule mult_mono)
+apply (auto intro: setprod_nonneg)
+done
+
+  (* FIXME: In Finite_Set there is a useless further assumption *)
+lemma setprod_inversef: "finite A ==> setprod (inverse \<circ> f) A = (inverse (setprod f A) :: 'a:: {division_by_zero, field})"
+  apply (erule finite_induct)
+  apply (simp)
+  apply simp
+  done
+
+lemma setprod_le_1: assumes fS: "finite S" and f: "\<forall>x\<in>S. f x \<ge> 0 \<and> f x \<le> (1::'a::ordered_idom)"
+  shows "setprod f S \<le> 1"
+using setprod_le[OF fS f] unfolding setprod_1 .
+
+subsection{* Trace *}
+
+definition trace :: "'a::semiring_1^'n^'n \<Rightarrow> 'a" where
+  "trace A = setsum (\<lambda>i. ((A$i)$i)) {1..dimindex(UNIV::'n set)}"
+
+lemma trace_0: "trace(mat 0) = 0"
+  by (simp add: trace_def mat_def Cart_lambda_beta setsum_0)
+
+lemma trace_I: "trace(mat 1 :: 'a::semiring_1^'n^'n) = of_nat(dimindex(UNIV::'n set))"
+  by (simp add: trace_def mat_def Cart_lambda_beta)
+
+lemma trace_add: "trace ((A::'a::comm_semiring_1^'n^'n) + B) = trace A + trace B"
+  by (simp add: trace_def setsum_addf Cart_lambda_beta vector_component)
+
+lemma trace_sub: "trace ((A::'a::comm_ring_1^'n^'n) - B) = trace A - trace B"
+  by (simp add: trace_def setsum_subtractf Cart_lambda_beta vector_component)
+
+lemma trace_mul_sym:"trace ((A::'a::comm_semiring_1^'n^'n) ** B) = trace (B**A)"
+  apply (simp add: trace_def matrix_matrix_mult_def Cart_lambda_beta)
+  apply (subst setsum_commute)
+  by (simp add: mult_commute)
+
+(* ------------------------------------------------------------------------- *)
+(* Definition of determinant.                                                *)
+(* ------------------------------------------------------------------------- *)
+
+definition det:: "'a::comm_ring_1^'n^'n \<Rightarrow> 'a" where
+  "det A = setsum (\<lambda>p. of_int (sign p) * setprod (\<lambda>i. A$i$p i) {1 .. dimindex(UNIV :: 'n set)}) {p. p permutes {1 .. dimindex(UNIV :: 'n set)}}"
+
+(* ------------------------------------------------------------------------- *)
+(* A few general lemmas we need below.                                       *)
+(* ------------------------------------------------------------------------- *)
+
+lemma Cart_lambda_beta_perm: assumes p: "p permutes {1..dimindex(UNIV::'n set)}" 
+  and i: "i \<in> {1..dimindex(UNIV::'n set)}" 
+  shows "Cart_nth (Cart_lambda g ::'a^'n) (p i) = g(p i)"
+  using permutes_in_image[OF p] i
+  by (simp add:  Cart_lambda_beta permutes_in_image[OF p])
+
+lemma setprod_permute:
+  assumes p: "p permutes S" 
+  shows "setprod f S = setprod (f o p) S"
+proof-
+  {assume "\<not> finite S" hence ?thesis by simp}
+  moreover
+  {assume fS: "finite S"
+    then have ?thesis 
+      apply (simp add: setprod_def)
+      apply (rule ab_semigroup_mult.fold_image_permute)
+      apply (auto simp add: p)
+      apply unfold_locales
+      done}
+  ultimately show ?thesis by blast
+qed
+
+lemma setproduct_permute_nat_interval: "p permutes {m::nat .. n} ==> setprod f {m..n} = setprod (f o p) {m..n}"
+  by (auto intro: setprod_permute)
+
+(* ------------------------------------------------------------------------- *)
+(* Basic determinant properties.                                             *)
+(* ------------------------------------------------------------------------- *)
+
+lemma det_transp: "det (transp A) = det (A::'a::comm_ring_1 ^'n^'n)"
+proof-
+  let ?di = "\<lambda>A i j. A$i$j"
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  have fU: "finite ?U" by blast
+  {fix p assume p: "p \<in> {p. p permutes ?U}"
+    from p have pU: "p permutes ?U" by blast
+    have sth: "sign (inv p) = sign p" 
+      by (metis sign_inverse fU p mem_def Collect_def permutation_permutes)
+    from permutes_inj[OF pU] 
+    have pi: "inj_on p ?U" by (blast intro: subset_inj_on)
+    from permutes_image[OF pU]
+    have "setprod (\<lambda>i. ?di (transp A) i (inv p i)) ?U = setprod (\<lambda>i. ?di (transp A) i (inv p i)) (p ` ?U)" by simp
+    also have "\<dots> = setprod ((\<lambda>i. ?di (transp A) i (inv p i)) o p) ?U"
+      unfolding setprod_reindex[OF pi] ..
+    also have "\<dots> = setprod (\<lambda>i. ?di A i (p i)) ?U"
+    proof-
+      {fix i assume i: "i \<in> ?U"
+	from i permutes_inv_o[OF pU] permutes_in_image[OF pU]
+	have "((\<lambda>i. ?di (transp A) i (inv p i)) o p) i = ?di A i (p i)"
+	  unfolding transp_def by (simp add: Cart_lambda_beta expand_fun_eq)}
+      then show "setprod ((\<lambda>i. ?di (transp A) i (inv p i)) o p) ?U = setprod (\<lambda>i. ?di A i (p i)) ?U" by (auto intro: setprod_cong)  
+    qed
+    finally have "of_int (sign (inv p)) * (setprod (\<lambda>i. ?di (transp A) i (inv p i)) ?U) = of_int (sign p) * (setprod (\<lambda>i. ?di A i (p i)) ?U)" using sth
+      by simp}
+  then show ?thesis unfolding det_def apply (subst setsum_permutations_inverse)
+  apply (rule setsum_cong2) by blast
+qed
+
+lemma det_lowerdiagonal: 
+  fixes A :: "'a::comm_ring_1^'n^'n"
+  assumes ld: "\<And>i j. i \<in> {1 .. dimindex (UNIV:: 'n set)} \<Longrightarrow> j \<in> {1 .. dimindex(UNIV:: 'n set)} \<Longrightarrow> i < j \<Longrightarrow> A$i$j = 0"
+  shows "det A = setprod (\<lambda>i. A$i$i) {1..dimindex(UNIV:: 'n set)}"
+proof-
+  let ?U = "{1..dimindex(UNIV:: 'n set)}"
+  let ?PU = "{p. p permutes ?U}"
+  let ?pp = "\<lambda>p. of_int (sign p) * setprod (\<lambda>i. A$i$p i) {1 .. dimindex(UNIV :: 'n set)}"
+  have fU: "finite ?U" by blast
+  from finite_permutations[OF fU] have fPU: "finite ?PU" .
+  have id0: "{id} \<subseteq> ?PU" by (auto simp add: permutes_id)
+  {fix p assume p: "p \<in> ?PU -{id}"
+    from p have pU: "p permutes ?U" and pid: "p \<noteq> id" by blast+
+    from permutes_natset_le[OF pU] pid obtain i where
+      i: "i \<in> ?U" "p i > i" by (metis not_le)
+    from permutes_in_image[OF pU] i(1) have piU: "p i \<in> ?U" by blast
+    from ld[OF i(1) piU i(2)] i(1) have ex:"\<exists>i \<in> ?U. A$i$p i = 0" by blast
+    from setprod_zero[OF fU ex] have "?pp p = 0" by simp}
+  then have p0: "\<forall>p \<in> ?PU -{id}. ?pp p = 0"  by blast
+  from setsum_superset[OF fPU id0 p0] show ?thesis
+    unfolding det_def by (simp add: sign_id)
+qed
+
+lemma det_upperdiagonal: 
+  fixes A :: "'a::comm_ring_1^'n^'n"
+  assumes ld: "\<And>i j. i \<in> {1 .. dimindex (UNIV:: 'n set)} \<Longrightarrow> j \<in> {1 .. dimindex(UNIV:: 'n set)} \<Longrightarrow> i > j \<Longrightarrow> A$i$j = 0"
+  shows "det A = setprod (\<lambda>i. A$i$i) {1..dimindex(UNIV:: 'n set)}"
+proof-
+  let ?U = "{1..dimindex(UNIV:: 'n set)}"
+  let ?PU = "{p. p permutes ?U}"
+  let ?pp = "(\<lambda>p. of_int (sign p) * setprod (\<lambda>i. A$i$p i) {1 .. dimindex(UNIV :: 'n set)})"
+  have fU: "finite ?U" by blast
+  from finite_permutations[OF fU] have fPU: "finite ?PU" .
+  have id0: "{id} \<subseteq> ?PU" by (auto simp add: permutes_id)
+  {fix p assume p: "p \<in> ?PU -{id}"
+    from p have pU: "p permutes ?U" and pid: "p \<noteq> id" by blast+
+    from permutes_natset_ge[OF pU] pid obtain i where
+      i: "i \<in> ?U" "p i < i" by (metis not_le)
+    from permutes_in_image[OF pU] i(1) have piU: "p i \<in> ?U" by blast
+    from ld[OF i(1) piU i(2)] i(1) have ex:"\<exists>i \<in> ?U. A$i$p i = 0" by blast
+    from setprod_zero[OF fU ex] have "?pp p = 0" by simp}
+  then have p0: "\<forall>p \<in> ?PU -{id}. ?pp p = 0"  by blast
+  from setsum_superset[OF fPU id0 p0] show ?thesis
+    unfolding det_def by (simp add: sign_id)
+qed
+
+lemma det_I: "det (mat 1 :: 'a::comm_ring_1^'n^'n) = 1"
+proof-
+  let ?A = "mat 1 :: 'a::comm_ring_1^'n^'n"
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?f = "\<lambda>i j. ?A$i$j"
+  {fix i assume i: "i \<in> ?U"
+    have "?f i i = 1" using i by (vector mat_def)}
+  hence th: "setprod (\<lambda>i. ?f i i) ?U = setprod (\<lambda>x. 1) ?U"
+    by (auto intro: setprod_cong)
+  {fix i j assume i: "i \<in> ?U" and j: "j \<in> ?U" and ij: "i < j"
+    have "?f i j = 0" using i j ij by (vector mat_def) }
+  then have "det ?A = setprod (\<lambda>i. ?f i i) ?U" using det_lowerdiagonal
+    by blast
+  also have "\<dots> = 1" unfolding th setprod_1 ..
+  finally show ?thesis . 
+qed
+
+lemma det_0: "det (mat 0 :: 'a::comm_ring_1^'n^'n) = 0"
+proof-
+  let ?A = "mat 0 :: 'a::comm_ring_1^'n^'n"
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?f = "\<lambda>i j. ?A$i$j"
+  have th:"setprod (\<lambda>i. ?f i i) ?U = 0"
+    apply (rule setprod_zero)
+    apply simp
+    apply (rule bexI[where x=1])
+    using dimindex_ge_1[of "UNIV :: 'n set"]
+    by (simp_all add: mat_def Cart_lambda_beta)
+  {fix i j assume i: "i \<in> ?U" and j: "j \<in> ?U" and ij: "i < j"
+    have "?f i j = 0" using i j ij by (vector mat_def) }
+  then have "det ?A = setprod (\<lambda>i. ?f i i) ?U" using det_lowerdiagonal
+    by blast
+  also have "\<dots> = 0" unfolding th  ..
+  finally show ?thesis . 
+qed
+
+lemma det_permute_rows:
+  fixes A :: "'a::comm_ring_1^'n^'n"
+  assumes p: "p permutes {1 .. dimindex (UNIV :: 'n set)}"
+  shows "det(\<chi> i. A$p i :: 'a^'n^'n) = of_int (sign p) * det A"
+  apply (simp add: det_def setsum_right_distrib mult_assoc[symmetric] del: One_nat_def)
+  apply (subst sum_permutations_compose_right[OF p])  
+proof(rule setsum_cong2)
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?PU = "{p. p permutes ?U}"
+  let ?Ap = "(\<chi> i. A$p i :: 'a^'n^'n)"
+  fix q assume qPU: "q \<in> ?PU"
+  have fU: "finite ?U" by blast
+  from qPU have q: "q permutes ?U" by blast
+  from p q have pp: "permutation p" and qp: "permutation q"
+    by (metis fU permutation_permutes)+
+  from permutes_inv[OF p] have ip: "inv p permutes ?U" .
+    {fix i assume i: "i \<in> ?U"
+      from Cart_lambda_beta[rule_format, OF i, of "\<lambda>i. A$ p i"]
+      have "?Ap$i$ (q o p) i = A $ p i $ (q o p) i " by simp}
+    hence "setprod (\<lambda>i. ?Ap$i$ (q o p) i) ?U = setprod (\<lambda>i. A$p i$(q o p) i) ?U"
+      by (auto intro: setprod_cong)
+    also have "\<dots> = setprod ((\<lambda>i. A$p i$(q o p) i) o inv p) ?U" 
+      by (simp only: setprod_permute[OF ip, symmetric])
+    also have "\<dots> = setprod (\<lambda>i. A $ (p o inv p) i $ (q o (p o inv p)) i) ?U"
+      by (simp only: o_def)
+    also have "\<dots> = setprod (\<lambda>i. A$i$q i) ?U" by (simp only: o_def permutes_inverses[OF p])
+    finally   have thp: "setprod (\<lambda>i. ?Ap$i$ (q o p) i) ?U = setprod (\<lambda>i. A$i$q i) ?U" 
+      by blast
+  show "of_int (sign (q o p)) * setprod (\<lambda>i. ?Ap$i$ (q o p) i) ?U = of_int (sign p) * of_int (sign q) * setprod (\<lambda>i. A$i$q i) ?U" 
+    by (simp only: thp sign_compose[OF qp pp] mult_commute of_int_mult)
+qed
+
+lemma det_permute_columns:
+  fixes A :: "'a::comm_ring_1^'n^'n"
+  assumes p: "p permutes {1 .. dimindex (UNIV :: 'n set)}"
+  shows "det(\<chi> i j. A$i$ p j :: 'a^'n^'n) = of_int (sign p) * det A"
+proof-
+  let ?Ap = "\<chi> i j. A$i$ p j :: 'a^'n^'n"
+  let ?At = "transp A"
+  have "of_int (sign p) * det A = det (transp (\<chi> i. transp A $ p i))"
+    unfolding det_permute_rows[OF p, of ?At] det_transp ..
+  moreover
+  have "?Ap = transp (\<chi> i. transp A $ p i)"
+    by (simp add: transp_def Cart_eq Cart_lambda_beta Cart_lambda_beta_perm[OF p])
+  ultimately show ?thesis by simp 
+qed
+
+lemma det_identical_rows:
+  fixes A :: "'a::ordered_idom^'n^'n"
+  assumes i: "i\<in>{1 .. dimindex (UNIV :: 'n set)}" 
+  and j: "j\<in>{1 .. dimindex (UNIV :: 'n set)}"
+  and ij: "i \<noteq> j"
+  and r: "row i A = row j A"
+  shows	"det A = 0"
+proof-
+  have tha: "\<And>(a::'a) b. a = b ==> b = - a ==> a = 0" 
+    by simp
+  have th1: "of_int (-1) = - 1" by (metis of_int_1 of_int_minus number_of_Min)
+  let ?p = "Fun.swap i j id"
+  let ?A = "\<chi> i. A $ ?p i"
+  from r have "A = ?A" by (simp add: Cart_eq Cart_lambda_beta Cart_lambda_beta_perm[OF permutes_swap_id[OF i j]] row_def swap_def)
+  hence "det A = det ?A" by simp
+  moreover have "det A = - det ?A"
+    by (simp add: det_permute_rows[OF permutes_swap_id[OF i j]] sign_swap_id ij th1)
+  ultimately show "det A = 0" by (metis tha) 
+qed
+
+lemma det_identical_columns:
+  fixes A :: "'a::ordered_idom^'n^'n"
+  assumes i: "i\<in>{1 .. dimindex (UNIV :: 'n set)}" 
+  and j: "j\<in>{1 .. dimindex (UNIV :: 'n set)}"
+  and ij: "i \<noteq> j"
+  and r: "column i A = column j A"
+  shows	"det A = 0"
+apply (subst det_transp[symmetric])
+apply (rule det_identical_rows[OF i j ij])
+by (metis row_transp i j r)
+
+lemma det_zero_row: 
+  fixes A :: "'a::{idom, ring_char_0}^'n^'n"
+  assumes i: "i\<in>{1 .. dimindex (UNIV :: 'n set)}" 
+  and r: "row i A = 0"
+  shows "det A = 0"
+using i r
+apply (simp add: row_def det_def Cart_lambda_beta Cart_eq vector_component del: One_nat_def)
+apply (rule setsum_0')
+apply (clarsimp simp add: sign_nz simp del: One_nat_def)
+apply (rule setprod_zero)
+apply simp
+apply (rule bexI[where x=i])
+apply (erule_tac x="a i" in ballE)
+apply (subgoal_tac "(0\<Colon>'a ^ 'n) $ a i = 0")
+apply simp
+apply (rule zero_index)
+apply (drule permutes_in_image[of _ _ i]) 
+apply simp
+apply (drule permutes_in_image[of _ _ i]) 
+apply simp
+apply simp
+done
+
+lemma det_zero_column:
+  fixes A :: "'a::{idom,ring_char_0}^'n^'n"
+  assumes i: "i\<in>{1 .. dimindex (UNIV :: 'n set)}" 
+  and r: "column i A = 0"
+  shows "det A = 0"
+  apply (subst det_transp[symmetric])
+  apply (rule det_zero_row[OF i])
+  by (metis row_transp r i)
+
+lemma setsum_lambda_beta[simp]: "setsum (\<lambda>i. ((\<chi> i. g i) :: 'a::{comm_monoid_add}^'n) $ i ) {1 .. dimindex (UNIV :: 'n set)} = setsum g {1 .. dimindex (UNIV :: 'n set)}"
+  by (simp add: Cart_lambda_beta)
+
+lemma setprod_lambda_beta[simp]: "setprod (\<lambda>i. ((\<chi> i. g i) :: 'a::{comm_monoid_mult}^'n) $ i ) {1 .. dimindex (UNIV :: 'n set)} = setprod g {1 .. dimindex (UNIV :: 'n set)}"
+  apply (rule setprod_cong)
+  apply simp
+  apply (simp add: Cart_lambda_beta')
+  done
+
+lemma setprod_lambda_beta2[simp]: "setprod (\<lambda>i. ((\<chi> i. g i) :: 'a::{comm_monoid_mult}^'n^'n) $ i$ f i ) {1 .. dimindex (UNIV :: 'n set)} = setprod (\<lambda>i. g i $ f i) {1 .. dimindex (UNIV :: 'n set)}"
+proof(rule setprod_cong[OF refl])
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  fix i assume i: "i \<in> ?U"
+  from Cart_lambda_beta'[OF i, of g] have 
+    "((\<chi> i. g i) :: 'a^'n^'n) $ i = g i" .
+  hence "((\<chi> i. g i) :: 'a^'n^'n) $ i $ f i = g i $ f i" by simp
+  then
+  show "((\<chi> i. g i):: 'a^'n^'n) $ i $ f i = g i $ f i"   .
+qed
+
+lemma det_row_add:
+  assumes k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}" 
+  shows "det((\<chi> i. if i = k then a i + b i else c i)::'a::comm_ring_1^'n^'n) =
+             det((\<chi> i. if i = k then a i else c i)::'a::comm_ring_1^'n^'n) +
+             det((\<chi> i. if i = k then b i else c i)::'a::comm_ring_1^'n^'n)"
+unfolding det_def setprod_lambda_beta2 setsum_addf[symmetric]
+proof (rule setsum_cong2)
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?pU = "{p. p permutes ?U}"
+  let ?f = "(\<lambda>i. if i = k then a i + b i else c i)::nat \<Rightarrow> 'a::comm_ring_1^'n"
+  let ?g = "(\<lambda> i. if i = k then a i else c i)::nat \<Rightarrow> 'a::comm_ring_1^'n"
+  let ?h = "(\<lambda> i. if i = k then b i else c i)::nat \<Rightarrow> 'a::comm_ring_1^'n"
+  fix p assume p: "p \<in> ?pU"
+  let ?Uk = "?U - {k}"
+  from p have pU: "p permutes ?U" by blast
+  from k have pkU: "p k \<in> ?U" by (simp only: permutes_in_image[OF pU])
+  note pin[simp] = permutes_in_image[OF pU]
+  have kU: "?U = insert k ?Uk" using k by blast
+  {fix j assume j: "j \<in> ?Uk"
+    from j have "?f j $ p j = ?g j $ p j" and "?f j $ p j= ?h j $ p j" 
+      by simp_all}
+  then have th1: "setprod (\<lambda>i. ?f i $ p i) ?Uk = setprod (\<lambda>i. ?g i $ p i) ?Uk"
+    and th2: "setprod (\<lambda>i. ?f i $ p i) ?Uk = setprod (\<lambda>i. ?h i $ p i) ?Uk"
+    apply -
+    apply (rule setprod_cong, simp_all)+
+    done
+  have th3: "finite ?Uk" "k \<notin> ?Uk" using k by auto
+  have "setprod (\<lambda>i. ?f i $ p i) ?U = setprod (\<lambda>i. ?f i $ p i) (insert k ?Uk)"
+    unfolding kU[symmetric] ..
+  also have "\<dots> = ?f k $ p k  * setprod (\<lambda>i. ?f i $ p i) ?Uk"
+    apply (rule setprod_insert)
+    apply simp
+    using k by blast
+  also have "\<dots> = (a k $ p k * setprod (\<lambda>i. ?f i $ p i) ?Uk) + (b k$ p k * setprod (\<lambda>i. ?f i $ p i) ?Uk)" using pkU by (simp add: ring_simps vector_component)
+  also have "\<dots> = (a k $ p k * setprod (\<lambda>i. ?g i $ p i) ?Uk) + (b k$ p k * setprod (\<lambda>i. ?h i $ p i) ?Uk)" by (metis th1 th2)
+  also have "\<dots> = setprod (\<lambda>i. ?g i $ p i) (insert k ?Uk) + setprod (\<lambda>i. ?h i $ p i) (insert k ?Uk)"
+    unfolding  setprod_insert[OF th3] by simp
+  finally have "setprod (\<lambda>i. ?f i $ p i) ?U = setprod (\<lambda>i. ?g i $ p i) ?U + setprod (\<lambda>i. ?h i $ p i) ?U" unfolding kU[symmetric] .
+  then show "of_int (sign p) * setprod (\<lambda>i. ?f i $ p i) ?U = of_int (sign p) * setprod (\<lambda>i. ?g i $ p i) ?U + of_int (sign p) * setprod (\<lambda>i. ?h i $ p i) ?U"
+    by (simp add: ring_simps)
+qed
+
+lemma det_row_mul:
+  assumes k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}" 
+  shows "det((\<chi> i. if i = k then c *s a i else b i)::'a::comm_ring_1^'n^'n) =
+             c* det((\<chi> i. if i = k then a i else b i)::'a::comm_ring_1^'n^'n)"
+
+unfolding det_def setprod_lambda_beta2 setsum_right_distrib
+proof (rule setsum_cong2)
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?pU = "{p. p permutes ?U}"
+  let ?f = "(\<lambda>i. if i = k then c*s a i else b i)::nat \<Rightarrow> 'a::comm_ring_1^'n"
+  let ?g = "(\<lambda> i. if i = k then a i else b i)::nat \<Rightarrow> 'a::comm_ring_1^'n"
+  fix p assume p: "p \<in> ?pU"
+  let ?Uk = "?U - {k}"
+  from p have pU: "p permutes ?U" by blast
+  from k have pkU: "p k \<in> ?U" by (simp only: permutes_in_image[OF pU])
+  note pin[simp] = permutes_in_image[OF pU]
+  have kU: "?U = insert k ?Uk" using k by blast
+  {fix j assume j: "j \<in> ?Uk"
+    from j have "?f j $ p j = ?g j $ p j" by simp}
+  then have th1: "setprod (\<lambda>i. ?f i $ p i) ?Uk = setprod (\<lambda>i. ?g i $ p i) ?Uk"
+    apply -
+    apply (rule setprod_cong, simp_all)
+    done
+  have th3: "finite ?Uk" "k \<notin> ?Uk" using k by auto
+  have "setprod (\<lambda>i. ?f i $ p i) ?U = setprod (\<lambda>i. ?f i $ p i) (insert k ?Uk)"
+    unfolding kU[symmetric] ..
+  also have "\<dots> = ?f k $ p k  * setprod (\<lambda>i. ?f i $ p i) ?Uk"
+    apply (rule setprod_insert)
+    apply simp
+    using k by blast
+  also have "\<dots> = (c*s a k) $ p k * setprod (\<lambda>i. ?f i $ p i) ?Uk" using pkU by (simp add: ring_simps vector_component)
+  also have "\<dots> = c* (a k $ p k * setprod (\<lambda>i. ?g i $ p i) ?Uk)"
+    unfolding th1 using pkU by (simp add: vector_component mult_ac)
+  also have "\<dots> = c* (setprod (\<lambda>i. ?g i $ p i) (insert k ?Uk))"
+    unfolding  setprod_insert[OF th3] by simp
+  finally have "setprod (\<lambda>i. ?f i $ p i) ?U = c* (setprod (\<lambda>i. ?g i $ p i) ?U)" unfolding kU[symmetric] .
+  then show "of_int (sign p) * setprod (\<lambda>i. ?f i $ p i) ?U = c * (of_int (sign p) * setprod (\<lambda>i. ?g i $ p i) ?U)"
+    by (simp add: ring_simps)
+qed
+
+lemma det_row_0:
+  assumes k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}" 
+  shows "det((\<chi> i. if i = k then 0 else b i)::'a::comm_ring_1^'n^'n) = 0"
+using det_row_mul[OF k, of 0 "\<lambda>i. 1" b]
+apply (simp)
+  unfolding vector_smult_lzero .
+
+lemma det_row_operation:
+  fixes A :: "'a::ordered_idom^'n^'n"
+  assumes i: "i \<in> {1 .. dimindex(UNIV :: 'n set)}"
+  and j: "j \<in> {1 .. dimindex(UNIV :: 'n set)}"
+  and ij: "i \<noteq> j"
+  shows "det (\<chi> k. if k = i then row i A + c *s row j A else row k A) = det A"
+proof-
+  let ?Z = "(\<chi> k. if k = i then row j A else row k A) :: 'a ^'n^'n"
+  have th: "row i ?Z = row j ?Z" using i j by (vector row_def)
+  have th2: "((\<chi> k. if k = i then row i A else row k A) :: 'a^'n^'n) = A"
+    using i j by (vector row_def)
+  show ?thesis
+    unfolding det_row_add [OF i] det_row_mul[OF i] det_identical_rows[OF i j ij th] th2
+    by simp
+qed
+
+lemma det_row_span:
+  fixes A :: "'a:: ordered_idom^'n^'n"
+  assumes i: "i \<in> {1 .. dimindex(UNIV :: 'n set)}"
+  and x: "x \<in> span {row j A |j. j\<in> {1 .. dimindex(UNIV :: 'n set)} \<and> j\<noteq> i}"
+  shows "det (\<chi> k. if k = i then row i A + x else row k A) = det A"
+proof-
+  let ?U = "{1 .. dimindex(UNIV :: 'n set)}"
+  let ?S = "{row j A |j. j\<in> ?U \<and> j\<noteq> i}"
+  let ?d = "\<lambda>x. det (\<chi> k. if k = i then x else row k A)"
+  let ?P = "\<lambda>x. ?d (row i A + x) = det A"
+  {fix k 
+    
+    have "(if k = i then row i A + 0 else row k A) = row k A" by simp}
+  then have P0: "?P 0"
+    apply -
+    apply (rule cong[of det, OF refl])
+    using i by (vector row_def)
+  moreover
+  {fix c z y assume zS: "z \<in> ?S" and Py: "?P y"
+    from zS obtain j where j: "z = row j A" "j \<in> ?U" "i \<noteq> j" by blast
+    let ?w = "row i A + y"
+    have th0: "row i A + (c*s z + y) = ?w + c*s z" by vector
+    have thz: "?d z = 0"
+      apply (rule det_identical_rows[OF i j(2,3)])
+      using i j by (vector row_def)
+    have "?d (row i A + (c*s z + y)) = ?d (?w + c*s z)" unfolding th0 ..
+    then have "?P (c*s z + y)" unfolding thz Py det_row_mul[OF i] det_row_add[OF i] 
+      by simp }
+
+  ultimately show ?thesis 
+    apply -
+    apply (rule span_induct_alt[of ?P ?S, OF P0])
+    apply blast
+    apply (rule x)
+    done
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* May as well do this, though it's a bit unsatisfactory since it ignores    *)
+(* exact duplicates by considering the rows/columns as a set.                *)
+(* ------------------------------------------------------------------------- *)
+
+lemma det_dependent_rows:
+  fixes A:: "'a::ordered_idom^'n^'n"
+  assumes d: "dependent (rows A)"
+  shows "det A = 0"
+proof-
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  from d obtain i where i: "i \<in> ?U" "row i A \<in> span (rows A - {row i A})"
+    unfolding dependent_def rows_def by blast
+  {fix j k assume j: "j \<in>?U" and k: "k \<in> ?U" and jk: "j \<noteq> k"
+    and c: "row j A = row k A" 
+    from det_identical_rows[OF j k jk c] have ?thesis .}
+  moreover
+  {assume H: "\<And> i j. i\<in> ?U \<Longrightarrow> j \<in> ?U \<Longrightarrow> i \<noteq> j \<Longrightarrow> row i A \<noteq> row j A"
+    have th0: "- row i A \<in> span {row j A|j. j \<in> ?U \<and> j \<noteq> i}"
+      apply (rule span_neg)
+      apply (rule set_rev_mp)
+      apply (rule i(2))
+      apply (rule span_mono)
+      using H i by (auto simp add: rows_def)
+    from det_row_span[OF i(1) th0]
+    have "det A = det (\<chi> k. if k = i then 0 *s 1 else row k A)"
+      unfolding right_minus vector_smult_lzero ..
+    with det_row_mul[OF i(1), of "0::'a" "\<lambda>i. 1"] 
+    have "det A = 0" by simp}
+  ultimately show ?thesis by blast
+qed
+
+lemma det_dependent_columns: assumes d: "dependent(columns (A::'a::ordered_idom^'n^'n))" shows "det A = 0"
+by (metis d det_dependent_rows rows_transp det_transp)
+
+(* ------------------------------------------------------------------------- *)
+(* Multilinearity and the multiplication formula.                            *)
+(* ------------------------------------------------------------------------- *)
+
+lemma Cart_lambda_cong: "(\<And>x. x \<in> {1 .. dimindex (UNIV :: 'n set)} \<Longrightarrow> f x = g x) \<Longrightarrow> (Cart_lambda f::'a^'n) = (Cart_lambda g :: 'a^'n)"
+  apply (rule iffD1[OF Cart_lambda_unique]) by vector
+
+lemma det_linear_row_setsum: 
+  assumes fS: "finite S" and k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "det ((\<chi> i. if i = k then setsum (a i) S else c i)::'a::comm_ring_1^'n^'n) = setsum (\<lambda>j. det ((\<chi> i. if i = k then a  i j else c i)::'a^'n^'n)) S"
+  using k
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case apply simp  unfolding setsum_empty det_row_0[OF k] ..
+next
+  case (2 x F)
+  then  show ?case by (simp add: det_row_add cong del: if_weak_cong)
+qed
+
+lemma finite_bounded_functions:
+  assumes fS: "finite S"
+  shows "finite {f. (\<forall>i \<in> {1.. (k::nat)}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1 .. k} \<longrightarrow> f i = i)}"
+proof(induct k)
+  case 0 
+  have th: "{f. \<forall>i. f i = i} = {id}" by (auto intro: ext)
+  show ?case by (auto simp add: th)
+next
+  case (Suc k)
+  let ?f = "\<lambda>(y::nat,g) i. if i = Suc k then y else g i"
+  let ?S = "?f ` (S \<times> {f. (\<forall>i\<in>{1..k}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1..k} \<longrightarrow> f i = i)})"
+  have "?S = {f. (\<forall>i\<in>{1.. Suc k}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1.. Suc k} \<longrightarrow> f i = i)}"
+    apply (auto simp add: image_iff)
+    apply (rule_tac x="x (Suc k)" in bexI)
+    apply (rule_tac x = "\<lambda>i. if i = Suc k then i else x i" in exI)
+    apply (auto intro: ext)
+    done
+  with finite_imageI[OF finite_cartesian_product[OF fS Suc.hyps(1)], of ?f]
+  show ?case by metis 
+qed
+
+
+lemma eq_id_iff[simp]: "(\<forall>x. f x = x) = (f = id)" by (auto intro: ext)
+
+lemma det_linear_rows_setsum_lemma:
+  assumes fS: "finite S" and k: "k \<le> dimindex (UNIV :: 'n set)"
+  shows "det((\<chi> i. if i <= k then setsum (a i) S else c i):: 'a::comm_ring_1^'n^'n) =
+             setsum (\<lambda>f. det((\<chi> i. if i <= k then a i (f i) else c i)::'a^'n^'n))
+                 {f. (\<forall>i \<in> {1 .. k}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1..k} \<longrightarrow> f i = i)}"
+using k
+proof(induct k arbitrary: a c)
+  case 0
+  have th0: "\<And>x y. (\<chi> i. if i <= 0 then x i else y i) = (\<chi> i. y i)" by vector
+  from "0.prems"  show ?case unfolding th0 by simp
+next
+  case (Suc k a c)
+  let ?F = "\<lambda>k. {f. (\<forall>i \<in> {1 .. k}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1..k} \<longrightarrow> f i = i)}"
+  let ?h = "\<lambda>(y::nat,g) i. if i = Suc k then y else g i"
+  let ?k = "\<lambda>h. (h(Suc k),(\<lambda>i. if i = Suc k then i else h i))"
+  let ?s = "\<lambda> k a c f. det((\<chi> i. if i <= k then a i (f i) else c i)::'a^'n^'n)"
+  let ?c = "\<lambda>i. if i = Suc k then a i j else c i"
+  from Suc.prems have Sk: "Suc k \<in> {1 .. dimindex (UNIV :: 'n set)}" by simp
+  from Suc.prems have k': "k \<le> dimindex (UNIV :: 'n set)" by arith
+  have thif: "\<And>a b c d. (if b \<or> a then c else d) = (if a then c else if b then c else d)" by simp
+  have thif2: "\<And>a b c d e. (if a then b else if c then d else e) =
+     (if c then (if a then b else d) else (if a then b else e))" by simp 
+  have "det (\<chi> i. if i \<le> Suc k then setsum (a i) S else c i) = 
+        det (\<chi> i. if i = Suc k then setsum (a i) S 
+                 else if i \<le> k then setsum (a i) S else c i)"
+    unfolding le_Suc_eq thif  ..
+  also have "\<dots> = (\<Sum>j\<in>S. det (\<chi> i. if i \<le> k then setsum (a i) S
+                    else if i = Suc k then a i j else c i))"
+    unfolding det_linear_row_setsum[OF fS Sk]
+    apply (subst thif2)
+    by (simp cong del: if_weak_cong cong add: if_cong)
+  finally have tha: 
+    "det (\<chi> i. if i \<le> Suc k then setsum (a i) S else c i) = 
+     (\<Sum>(j, f)\<in>S \<times> ?F k. det (\<chi> i. if i \<le> k then a i (f i)
+                                else if i = Suc k then a i j
+                                else c i))" 
+    unfolding  Suc.hyps[OF k'] unfolding setsum_cartesian_product by blast
+  show ?case unfolding tha
+    apply(rule setsum_eq_general_reverses[where h= "?h" and k= "?k"], 
+      blast intro: finite_cartesian_product fS finite_bounded_functions[OF fS],
+      blast intro: finite_cartesian_product fS finite_bounded_functions[OF fS], auto intro: ext)
+    apply (rule cong[OF refl[of det]])
+    by vector
+qed
+
+lemma det_linear_rows_setsum:
+  assumes fS: "finite S"
+  shows "det (\<chi> i. setsum (a i) S) = setsum (\<lambda>f. det (\<chi> i. a i (f i) :: 'a::comm_ring_1 ^ 'n^'n)) {f. (\<forall>i \<in> {1 .. dimindex (UNIV :: 'n set)}. f i \<in> S) \<and> (\<forall>i. i \<notin> {1.. dimindex (UNIV :: 'n set)} \<longrightarrow> f i = i)}"
+proof-
+  have th0: "\<And>x y. ((\<chi> i. if i <= dimindex(UNIV:: 'n set) then x i else y i) :: 'a^'n^'n) = (\<chi> i. x i)" by vector
+  
+  from det_linear_rows_setsum_lemma[OF fS, of "dimindex (UNIV :: 'n set)" a, unfolded th0, OF order_refl] show ?thesis by blast
+qed
+
+lemma matrix_mul_setsum_alt:
+  fixes A B :: "'a::comm_ring_1^'n^'n"
+  shows "A ** B = (\<chi> i. setsum (\<lambda>k. A$i$k *s B $ k) {1 .. dimindex (UNIV :: 'n set)})"
+  by (vector matrix_matrix_mult_def setsum_component)
+
+lemma det_rows_mul:
+  "det((\<chi> i. c i *s a i)::'a::comm_ring_1^'n^'n) =
+  setprod (\<lambda>i. c i) {1..dimindex(UNIV:: 'n set)} * det((\<chi> i. a i)::'a^'n^'n)"
+proof (simp add: det_def Cart_lambda_beta' setsum_right_distrib vector_component cong add: setprod_cong del: One_nat_def, rule setsum_cong2)
+  let ?U = "{1 .. dimindex(UNIV :: 'n set)}"
+  let ?PU = "{p. p permutes ?U}"
+  fix p assume pU: "p \<in> ?PU"
+  let ?s = "of_int (sign p)"
+  from pU have p: "p permutes ?U" by blast
+  have "setprod (\<lambda>i. (c i *s a i) $ p i) ?U = setprod (\<lambda>i. c i * a i $ p i) ?U"
+    apply (rule setprod_cong, blast)
+    by (auto simp only: permutes_in_image[OF p] intro: vector_smult_component)
+  also have "\<dots> = setprod c ?U * setprod (\<lambda>i. a i $ p i) ?U"
+    unfolding setprod_timesf ..
+  finally show "?s * (\<Prod>xa\<in>?U. (c xa *s a xa) $ p xa) =
+        setprod c ?U * (?s* (\<Prod>xa\<in>?U. a xa $ p xa))" by (simp add: ring_simps)
+qed
+
+lemma det_mul:
+  fixes A B :: "'a::ordered_idom^'n^'n"
+  shows "det (A ** B) = det A * det B"
+proof-
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?F = "{f. (\<forall>i\<in> ?U. f i \<in> ?U) \<and> (\<forall>i. i \<notin> ?U \<longrightarrow> f i = i)}"
+  let ?PU = "{p. p permutes ?U}"
+  have fU: "finite ?U" by simp
+  have fF: "finite ?F"  using finite_bounded_functions[OF fU] .
+  {fix p assume p: "p permutes ?U"
+    
+    have "p \<in> ?F" unfolding mem_Collect_eq permutes_in_image[OF p]
+      using p[unfolded permutes_def] by simp}
+  then have PUF: "?PU \<subseteq> ?F"  by blast 
+  {fix f assume fPU: "f \<in> ?F - ?PU"
+    have fUU: "f ` ?U \<subseteq> ?U" using fPU by auto
+    from fPU have f: "\<forall>i \<in> ?U. f i \<in> ?U"
+      "\<forall>i. i \<notin> ?U \<longrightarrow> f i = i" "\<not>(\<forall>y. \<exists>!x. f x = y)" unfolding permutes_def 
+      by auto
+    
+    let ?A = "(\<chi> i. A$i$f i *s B$f i) :: 'a^'n^'n"
+    let ?B = "(\<chi> i. B$f i) :: 'a^'n^'n"
+    {assume fni: "\<not> inj_on f ?U"
+      then obtain i j where ij: "i \<in> ?U" "j \<in> ?U" "f i = f j" "i \<noteq> j"
+	unfolding inj_on_def by blast
+      from ij 
+      have rth: "row i ?B = row j ?B" by (vector row_def)
+      from det_identical_rows[OF ij(1,2,4) rth] 
+      have "det (\<chi> i. A$i$f i *s B$f i) = 0" 
+	unfolding det_rows_mul by simp}
+    moreover
+    {assume fi: "inj_on f ?U"
+      from f fi have fith: "\<And>i j. f i = f j \<Longrightarrow> i = j"
+	unfolding inj_on_def
+	apply (case_tac "i \<in> ?U")
+	apply (case_tac "j \<in> ?U") by metis+
+      note fs = fi[unfolded surjective_iff_injective_gen[OF fU fU refl fUU, symmetric]]
+      
+      {fix y
+	from fs f have "\<exists>x. f x = y" by (cases "y \<in> ?U") blast+
+	then obtain x where x: "f x = y" by blast
+	{fix z assume z: "f z = y" from fith x z have "z = x" by metis}
+	with x have "\<exists>!x. f x = y" by blast}
+      with f(3) have "det (\<chi> i. A$i$f i *s B$f i) = 0" by blast}
+    ultimately have "det (\<chi> i. A$i$f i *s B$f i) = 0" by blast}
+  hence zth: "\<forall> f\<in> ?F - ?PU. det (\<chi> i. A$i$f i *s B$f i) = 0" by simp
+  {fix p assume pU: "p \<in> ?PU"
+    from pU have p: "p permutes ?U" by blast
+    let ?s = "\<lambda>p. of_int (sign p)"
+    let ?f = "\<lambda>q. ?s p * (\<Prod>i\<in> ?U. A $ i $ p i) *
+               (?s q * (\<Prod>i\<in> ?U. B $ i $ q i))"
+    have "(setsum (\<lambda>q. ?s q *
+            (\<Prod>i\<in> ?U. (\<chi> i. A $ i $ p i *s B $ p i :: 'a^'n^'n) $ i $ q i)) ?PU) =
+        (setsum (\<lambda>q. ?s p * (\<Prod>i\<in> ?U. A $ i $ p i) *
+               (?s q * (\<Prod>i\<in> ?U. B $ i $ q i))) ?PU)"
+      unfolding sum_permutations_compose_right[OF permutes_inv[OF p], of ?f]
+    proof(rule setsum_cong2)
+      fix q assume qU: "q \<in> ?PU"
+      hence q: "q permutes ?U" by blast
+      from p q have pp: "permutation p" and pq: "permutation q"
+	unfolding permutation_permutes by auto 
+      have th00: "of_int (sign p) * of_int (sign p) = (1::'a)" 
+	"\<And>a. of_int (sign p) * (of_int (sign p) * a) = a" 
+	unfolding mult_assoc[symmetric]	unfolding of_int_mult[symmetric] 
+	by (simp_all add: sign_idempotent)
+      have ths: "?s q = ?s p * ?s (q o inv p)"
+	using pp pq permutation_inverse[OF pp] sign_inverse[OF pp]
+	by (simp add:  th00 mult_ac sign_idempotent sign_compose)
+      have th001: "setprod (\<lambda>i. B$i$ q (inv p i)) ?U = setprod ((\<lambda>i. B$i$ q (inv p i)) o p) ?U"
+	by (rule setprod_permute[OF p])
+      have thp: "setprod (\<lambda>i. (\<chi> i. A$i$p i *s B$p i :: 'a^'n^'n) $i $ q i) ?U = setprod (\<lambda>i. A$i$p i) ?U * setprod (\<lambda>i. B$i$ q (inv p i)) ?U" 
+	unfolding th001 setprod_timesf[symmetric] o_def permutes_inverses[OF p]
+	apply (rule setprod_cong[OF refl])
+	using permutes_in_image[OF q] by vector
+      show "?s q * setprod (\<lambda>i. (((\<chi> i. A$i$p i *s B$p i) :: 'a^'n^'n)$i$q i)) ?U = ?s p * (setprod (\<lambda>i. A$i$p i) ?U) * (?s (q o inv p) * setprod (\<lambda>i. B$i$(q o inv p) i) ?U)"
+	using ths thp pp pq permutation_inverse[OF pp] sign_inverse[OF pp]
+	by (simp add: sign_nz th00 ring_simps sign_idempotent sign_compose)
+    qed
+  }
+  then have th2: "setsum (\<lambda>f. det (\<chi> i. A$i$f i *s B$f i)) ?PU = det A * det B" 
+    unfolding det_def setsum_product
+    by (rule setsum_cong2) 
+  have "det (A**B) = setsum (\<lambda>f.  det (\<chi> i. A $ i $ f i *s B $ f i)) ?F"
+    unfolding matrix_mul_setsum_alt det_linear_rows_setsum[OF fU] .. 
+  also have "\<dots> = setsum (\<lambda>f. det (\<chi> i. A$i$f i *s B$f i)) ?PU"
+    unfolding setsum_superset[OF fF PUF zth, symmetric] 
+    unfolding det_rows_mul ..
+  finally show ?thesis unfolding th2 .
+qed  
+
+(* ------------------------------------------------------------------------- *)
+(* Relation to invertibility.                                                *)
+(* ------------------------------------------------------------------------- *)
+
+lemma invertible_left_inverse:
+  fixes A :: "real^'n^'n"
+  shows "invertible A \<longleftrightarrow> (\<exists>(B::real^'n^'n). B** A = mat 1)"
+  by (metis invertible_def matrix_left_right_inverse)
+
+lemma invertible_righ_inverse:
+  fixes A :: "real^'n^'n"
+  shows "invertible A \<longleftrightarrow> (\<exists>(B::real^'n^'n). A** B = mat 1)"
+  by (metis invertible_def matrix_left_right_inverse)
+
+lemma invertible_det_nz: 
+  fixes A::"real ^'n^'n"
+  shows "invertible A \<longleftrightarrow> det A \<noteq> 0"
+proof-
+  {assume "invertible A"
+    then obtain B :: "real ^'n^'n" where B: "A ** B = mat 1"
+      unfolding invertible_righ_inverse by blast
+    hence "det (A ** B) = det (mat 1 :: real ^'n^'n)" by simp
+    hence "det A \<noteq> 0"
+      apply (simp add: det_mul det_I) by algebra }
+  moreover
+  {assume H: "\<not> invertible A"
+    let ?U = "{1 .. dimindex(UNIV :: 'n set)}"
+    have fU: "finite ?U" by simp
+    from H obtain c i where c: "setsum (\<lambda>i. c i *s row i A) ?U = 0" 
+      and iU: "i \<in> ?U" and ci: "c i \<noteq> 0"
+      unfolding invertible_righ_inverse
+      unfolding matrix_right_invertible_independent_rows by blast
+    have stupid: "\<And>(a::real^'n) b. a + b = 0 \<Longrightarrow> -a = b"
+      apply (drule_tac f="op + (- a)" in cong[OF refl])
+      apply (simp only: ab_left_minus add_assoc[symmetric])
+      apply simp
+      done
+    from c ci 
+    have thr0: "- row i A = setsum (\<lambda>j. (1/ c i) *s c j *s row j A) (?U - {i})"
+      unfolding setsum_diff1'[OF fU iU] setsum_cmul 
+      apply (simp add: field_simps)
+      apply (rule vector_mul_lcancel_imp[OF ci])
+      apply (auto simp add: vector_smult_assoc vector_smult_rneg field_simps)
+      unfolding stupid ..
+    have thr: "- row i A \<in> span {row j A| j. j\<in> ?U \<and> j \<noteq> i}" 
+      unfolding thr0
+      apply (rule span_setsum)
+      apply simp
+      apply (rule ballI)
+      apply (rule span_mul)+
+      apply (rule span_superset)
+      apply auto
+      done
+    let ?B = "(\<chi> k. if k = i then 0 else row k A) :: real ^'n^'n"
+    have thrb: "row i ?B = 0" using iU by (vector row_def) 
+    have "det A = 0" 
+      unfolding det_row_span[OF iU thr, symmetric] right_minus
+      unfolding  det_zero_row[OF iU thrb]  ..}
+  ultimately show ?thesis by blast
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Cramer's rule.                                                            *)
+(* ------------------------------------------------------------------------- *)
+
+lemma cramer_lemma_transp:
+  fixes A:: "'a::ordered_idom^'n^'n" and x :: "'a ^'n"
+  assumes k: "k \<in> {1 .. dimindex(UNIV ::'n set)}"
+  shows "det ((\<chi> i. if i = k then setsum (\<lambda>i. x$i *s row i A) {1 .. dimindex(UNIV::'n set)}
+                           else row i A)::'a^'n^'n) = x$k * det A" 
+  (is "?lhs = ?rhs") 
+proof-
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?Uk = "?U - {k}"
+  have U: "?U = insert k ?Uk" using k by blast
+  have fUk: "finite ?Uk" by simp
+  have kUk: "k \<notin> ?Uk" by simp
+  have th00: "\<And>k s. x$k *s row k A + s = (x$k - 1) *s row k A + row k A + s"
+    by (vector ring_simps)
+  have th001: "\<And>f k . (\<lambda>x. if x = k then f k else f x) = f" by (auto intro: ext)
+  have "(\<chi> i. row i A) = A" by (vector row_def)
+  then have thd1: "det (\<chi> i. row i A) = det A"  by simp 
+  have thd0: "det (\<chi> i. if i = k then row k A + (\<Sum>i \<in> ?Uk. x $ i *s row i A) else row i A) = det A"
+    apply (rule det_row_span[OF k])
+    apply (rule span_setsum[OF fUk])
+    apply (rule ballI)
+    apply (rule span_mul)
+    apply (rule span_superset)
+    apply auto
+    done
+  show "?lhs = x$k * det A"
+    apply (subst U)
+    unfolding setsum_insert[OF fUk kUk] 
+    apply (subst th00)
+    unfolding add_assoc
+    apply (subst det_row_add[OF k])
+    unfolding thd0
+    unfolding det_row_mul[OF k]
+    unfolding th001[of k "\<lambda>i. row i A"]
+    unfolding thd1  by (simp add: ring_simps)
+qed
+
+lemma cramer_lemma:
+  fixes A :: "'a::ordered_idom ^'n^'n"
+  assumes k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}" (is " _ \<in> ?U")
+  shows "det((\<chi> i j. if j = k then (A *v x)$i else A$i$j):: 'a^'n^'n) = x$k * det A"
+proof-
+  have stupid: "\<And>c. setsum (\<lambda>i. c i *s row i (transp A)) ?U = setsum (\<lambda>i. c i *s column i A) ?U"
+    by (auto simp add: row_transp intro: setsum_cong2)
+  show ?thesis 
+  unfolding matrix_mult_vsum 
+  unfolding cramer_lemma_transp[OF k, of x "transp A", unfolded det_transp, symmetric]
+  unfolding stupid[of "\<lambda>i. x$i"]
+  apply (subst det_transp[symmetric])
+  apply (rule cong[OF refl[of det]]) by (vector transp_def column_def row_def)
+qed
+
+lemma cramer:
+  fixes A ::"real^'n^'n"
+  assumes d0: "det A \<noteq> 0" 
+  shows "A *v x = b \<longleftrightarrow> x = (\<chi> k. det(\<chi> i j. if j=k then b$i else A$i$j :: real^'n^'n) / det A)"
+proof-
+  from d0 obtain B where B: "A ** B = mat 1" "B ** A = mat 1"  
+    unfolding invertible_det_nz[symmetric] invertible_def by blast
+  have "(A ** B) *v b = b" by (simp add: B matrix_vector_mul_lid)
+  hence "A *v (B *v b) = b" by (simp add: matrix_vector_mul_assoc)
+  then have xe: "\<exists>x. A*v x = b" by blast
+  {fix x assume x: "A *v x = b"
+  have "x = (\<chi> k. det(\<chi> i j. if j=k then b$i else A$i$j :: real^'n^'n) / det A)"
+    unfolding x[symmetric]
+    using d0 by (simp add: Cart_eq Cart_lambda_beta' cramer_lemma field_simps)}
+  with xe show ?thesis by auto
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Orthogonality of a transformation and matrix.                             *)
+(* ------------------------------------------------------------------------- *)
+
+definition "orthogonal_transformation f \<longleftrightarrow> linear f \<and> (\<forall>v w. f v \<bullet> f w = v \<bullet> w)"
+
+lemma orthogonal_transformation: "orthogonal_transformation f \<longleftrightarrow> linear f \<and> (\<forall>(v::real ^'n). norm (f v) = norm v)"
+  unfolding orthogonal_transformation_def
+  apply auto 
+  apply (erule_tac x=v in allE)+
+  apply (simp add: real_vector_norm_def)
+  by (simp add: dot_norm  linear_add[symmetric]) 
+
+definition "orthogonal_matrix (Q::'a::semiring_1^'n^'n) \<longleftrightarrow> transp Q ** Q = mat 1 \<and> Q ** transp Q = mat 1"
+
+lemma orthogonal_matrix: "orthogonal_matrix (Q:: real ^'n^'n)  \<longleftrightarrow> transp Q ** Q = mat 1"
+  by (metis matrix_left_right_inverse orthogonal_matrix_def)
+
+lemma orthogonal_matrix_id: "orthogonal_matrix (mat 1)"
+  by (simp add: orthogonal_matrix_def transp_mat matrix_mul_lid)
+
+lemma orthogonal_matrix_mul: 
+  fixes A :: "real ^'n^'n"
+  assumes oA : "orthogonal_matrix A"
+  and oB: "orthogonal_matrix B" 
+  shows "orthogonal_matrix(A ** B)"
+  using oA oB 
+  unfolding orthogonal_matrix matrix_transp_mul
+  apply (subst matrix_mul_assoc)
+  apply (subst matrix_mul_assoc[symmetric])
+  by (simp add: matrix_mul_rid)
+
+lemma orthogonal_transformation_matrix:
+  fixes f:: "real^'n \<Rightarrow> real^'n"
+  shows "orthogonal_transformation f \<longleftrightarrow> linear f \<and> orthogonal_matrix(matrix f)"
+  (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  let ?mf = "matrix f"
+  let ?ot = "orthogonal_transformation f"
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  have fU: "finite ?U" by simp
+  let ?m1 = "mat 1 :: real ^'n^'n"
+  {assume ot: ?ot
+    from ot have lf: "linear f" and fd: "\<forall>v w. f v \<bullet> f w = v \<bullet> w"
+      unfolding  orthogonal_transformation_def orthogonal_matrix by blast+
+    {fix i j assume i: "i \<in> ?U" and j: "j \<in> ?U"
+      let ?A = "transp ?mf ** ?mf"
+      have th0: "\<And>b (x::'a::comm_ring_1). (if b then 1 else 0)*x = (if b then x else 0)"
+	"\<And>b (x::'a::comm_ring_1). x*(if b then 1 else 0) = (if b then x else 0)"
+	by simp_all
+      from fd[rule_format, of "basis i" "basis j", unfolded matrix_works[OF lf, symmetric] dot_matrix_vector_mul] i j
+      have "?A$i$j = ?m1 $ i $ j" 
+	by (simp add: Cart_lambda_beta' dot_def matrix_matrix_mult_def columnvector_def rowvector_def basis_def th0 setsum_delta[OF fU] mat_def del: One_nat_def)}
+    hence "orthogonal_matrix ?mf" unfolding orthogonal_matrix by vector
+    with lf have ?rhs by blast}
+  moreover
+  {assume lf: "linear f" and om: "orthogonal_matrix ?mf"
+    from lf om have ?lhs
+      unfolding orthogonal_matrix_def norm_eq orthogonal_transformation
+      unfolding matrix_works[OF lf, symmetric]
+      apply (subst dot_matrix_vector_mul)
+      by (simp add: dot_matrix_product matrix_mul_lid del: One_nat_def)}
+  ultimately show ?thesis by blast
+qed
+
+lemma det_orthogonal_matrix: 
+  fixes Q:: "'a::ordered_idom^'n^'n"
+  assumes oQ: "orthogonal_matrix Q"
+  shows "det Q = 1 \<or> det Q = - 1"
+proof-
+  
+  have th: "\<And>x::'a. x = 1 \<or> x = - 1 \<longleftrightarrow> x*x = 1" (is "\<And>x::'a. ?ths x") 
+  proof- 
+    fix x:: 'a
+    have th0: "x*x - 1 = (x - 1)*(x + 1)" by (simp add: ring_simps)
+    have th1: "\<And>(x::'a) y. x = - y \<longleftrightarrow> x + y = 0" 
+      apply (subst eq_iff_diff_eq_0) by simp
+    have "x*x = 1 \<longleftrightarrow> x*x - 1 = 0" by simp
+    also have "\<dots> \<longleftrightarrow> x = 1 \<or> x = - 1" unfolding th0 th1 by simp
+    finally show "?ths x" ..
+  qed
+  from oQ have "Q ** transp Q = mat 1" by (metis orthogonal_matrix_def)
+  hence "det (Q ** transp Q) = det (mat 1:: 'a^'n^'n)" by simp
+  hence "det Q * det Q = 1" by (simp add: det_mul det_I det_transp)
+  then show ?thesis unfolding th . 
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Linearity of scaling, and hence isometry, that preserves origin.          *)
+(* ------------------------------------------------------------------------- *)
+lemma scaling_linear: 
+  fixes f :: "real ^'n \<Rightarrow> real ^'n"
+  assumes f0: "f 0 = 0" and fd: "\<forall>x y. dist (f x) (f y) = c * dist x y"
+  shows "linear f"
+proof-
+  {fix v w 
+    {fix x note fd[rule_format, of x 0, unfolded dist_def f0 diff_0_right] }
+    note th0 = this
+    have "f v \<bullet> f w = c^2 * (v \<bullet> w)" 
+      unfolding dot_norm_neg dist_def[symmetric]
+      unfolding th0 fd[rule_format] by (simp add: power2_eq_square field_simps)}
+  note fc = this
+  show ?thesis unfolding linear_def vector_eq
+    by (simp add: dot_lmult dot_ladd dot_rmult dot_radd fc ring_simps)
+qed    
+
+lemma isometry_linear:
+  "f (0:: real^'n) = (0:: real^'n) \<Longrightarrow> \<forall>x y. dist(f x) (f y) = dist x y
+        \<Longrightarrow> linear f"
+by (rule scaling_linear[where c=1]) simp_all
+
+(* ------------------------------------------------------------------------- *)
+(* Hence another formulation of orthogonal transformation.                   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma orthogonal_transformation_isometry:
+  "orthogonal_transformation f \<longleftrightarrow> f(0::real^'n) = (0::real^'n) \<and> (\<forall>x y. dist(f x) (f y) = dist x y)"
+  unfolding orthogonal_transformation 
+  apply (rule iffI)
+  apply clarify
+  apply (clarsimp simp add: linear_0 linear_sub[symmetric] dist_def)
+  apply (rule conjI)
+  apply (rule isometry_linear)
+  apply simp
+  apply simp
+  apply clarify
+  apply (erule_tac x=v in allE)
+  apply (erule_tac x=0 in allE)
+  by (simp add: dist_def)
+
+(* ------------------------------------------------------------------------- *)
+(* Can extend an isometry from unit sphere.                                  *)
+(* ------------------------------------------------------------------------- *)
+
+lemma isometry_sphere_extend:
+  fixes f:: "real ^'n \<Rightarrow> real ^'n"
+  assumes f1: "\<forall>x. norm x = 1 \<longrightarrow> norm (f x) = 1"
+  and fd1: "\<forall> x y. norm x = 1 \<longrightarrow> norm y = 1 \<longrightarrow> dist (f x) (f y) = dist x y"
+  shows "\<exists>g. orthogonal_transformation g \<and> (\<forall>x. norm x = 1 \<longrightarrow> g x = f x)"
+proof-
+  {fix x y x' y' x0 y0 x0' y0' :: "real ^'n" 
+    assume H: "x = norm x *s x0" "y = norm y *s y0"
+    "x' = norm x *s x0'" "y' = norm y *s y0'" 
+    "norm x0 = 1" "norm x0' = 1" "norm y0 = 1" "norm y0' = 1"
+    "norm(x0' - y0') = norm(x0 - y0)"
+    
+    have "norm(x' - y') = norm(x - y)"
+      apply (subst H(1))
+      apply (subst H(2))
+      apply (subst H(3))
+      apply (subst H(4))
+      using H(5-9)
+      apply (simp add: norm_eq norm_eq_1)
+      apply (simp add: dot_lsub dot_rsub dot_lmult dot_rmult)
+      apply (simp add: ring_simps)
+      by (simp only: right_distrib[symmetric])}
+  note th0 = this
+  let ?g = "\<lambda>x. if x = 0 then 0 else norm x *s f (inverse (norm x) *s x)"
+  {fix x:: "real ^'n" assume nx: "norm x = 1"
+    have "?g x = f x" using nx by (simp add: norm_eq_0[symmetric])}
+  hence thfg: "\<forall>x. norm x = 1 \<longrightarrow> ?g x = f x" by blast
+  have g0: "?g 0 = 0" by simp
+  {fix x y :: "real ^'n"
+    {assume "x = 0" "y = 0"
+      then have "dist (?g x) (?g y) = dist x y" by simp }
+    moreover
+    {assume "x = 0" "y \<noteq> 0"
+      then have "dist (?g x) (?g y) = dist x y" 
+	apply (simp add: dist_def norm_neg norm_mul norm_eq_0)
+	apply (rule f1[rule_format])
+	by(simp add: norm_mul norm_eq_0 field_simps)}
+    moreover
+    {assume "x \<noteq> 0" "y = 0"
+      then have "dist (?g x) (?g y) = dist x y" 
+	apply (simp add: dist_def norm_neg norm_mul norm_eq_0)
+	apply (rule f1[rule_format])
+	by(simp add: norm_mul norm_eq_0 field_simps)}
+    moreover
+    {assume z: "x \<noteq> 0" "y \<noteq> 0"
+      have th00: "x = norm x *s inverse (norm x) *s x" "y = norm y *s inverse (norm y) *s y" "norm x *s f (inverse (norm x) *s x) = norm x *s f (inverse (norm x) *s x)"
+	"norm y *s f (inverse (norm y) *s y) = norm y *s f (inverse (norm y) *s y)"
+	"norm (inverse (norm x) *s x) = 1"
+	"norm (f (inverse (norm x) *s x)) = 1"
+	"norm (inverse (norm y) *s y) = 1"
+	"norm (f (inverse (norm y) *s y)) = 1"
+	"norm (f (inverse (norm x) *s x) - f (inverse (norm y) *s y)) =
+	norm (inverse (norm x) *s x - inverse (norm y) *s y)"
+	using z
+	by (auto simp add: norm_eq_0 vector_smult_assoc field_simps norm_mul intro: f1[rule_format] fd1[rule_format, unfolded dist_def])
+      from z th0[OF th00] have "dist (?g x) (?g y) = dist x y" 
+	by (simp add: dist_def)}
+    ultimately have "dist (?g x) (?g y) = dist x y" by blast}
+  note thd = this
+    show ?thesis 
+    apply (rule exI[where x= ?g])
+    unfolding orthogonal_transformation_isometry
+      using  g0 thfg thd by metis 
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Rotation, reflection, rotoinversion.                                      *)
+(* ------------------------------------------------------------------------- *)
+
+definition "rotation_matrix Q \<longleftrightarrow> orthogonal_matrix Q \<and> det Q = 1"
+definition "rotoinversion_matrix Q \<longleftrightarrow> orthogonal_matrix Q \<and> det Q = - 1"
+
+lemma orthogonal_rotation_or_rotoinversion: 
+  fixes Q :: "'a::ordered_idom^'n^'n"
+  shows " orthogonal_matrix Q \<longleftrightarrow> rotation_matrix Q \<or> rotoinversion_matrix Q"
+  by (metis rotoinversion_matrix_def rotation_matrix_def det_orthogonal_matrix)
+(* ------------------------------------------------------------------------- *)
+(* Explicit formulas for low dimensions.                                     *)
+(* ------------------------------------------------------------------------- *)
+
+lemma setprod_1: "setprod f {(1::nat)..1} = f 1" by simp
+
+lemma setprod_2: "setprod f {(1::nat)..2} = f 1 * f 2" 
+  by (simp add: nat_number setprod_numseg mult_commute)
+lemma setprod_3: "setprod f {(1::nat)..3} = f 1 * f 2 * f 3" 
+  by (simp add: nat_number setprod_numseg mult_commute)
+
+lemma det_1: "det (A::'a::comm_ring_1^1^1) = A$1$1"
+  by (simp add: det_def dimindex_def permutes_sing sign_id del: One_nat_def)
+
+lemma det_2: "det (A::'a::comm_ring_1^2^2) = A$1$1 * A$2$2 - A$1$2 * A$2$1"
+proof-
+  have f12: "finite {2::nat}" "1 \<notin> {2::nat}" by auto
+  have th12: "{1 .. 2} = insert (1::nat) {2}" by auto
+  show ?thesis 
+  apply (simp add: det_def dimindex_def th12 del: One_nat_def)
+  unfolding setsum_over_permutations_insert[OF f12]
+  unfolding permutes_sing
+  apply (simp add: sign_swap_id sign_id swap_id_eq del: One_nat_def)
+  by (simp add: arith_simps(31)[symmetric] of_int_minus of_int_1 del: arith_simps(31))
+qed
+
+lemma det_3: "det (A::'a::comm_ring_1^3^3) = 
+  A$1$1 * A$2$2 * A$3$3 +
+  A$1$2 * A$2$3 * A$3$1 +
+  A$1$3 * A$2$1 * A$3$2 -
+  A$1$1 * A$2$3 * A$3$2 -
+  A$1$2 * A$2$1 * A$3$3 -
+  A$1$3 * A$2$2 * A$3$1"
+proof-
+  have f123: "finite {(2::nat), 3}" "1 \<notin> {(2::nat), 3}" by auto
+  have f23: "finite {(3::nat)}" "2 \<notin> {(3::nat)}" by auto
+  have th12: "{1 .. 3} = insert (1::nat) (insert 2 {3})" by auto
+
+  show ?thesis 
+  apply (simp add: det_def dimindex_def th12 del: One_nat_def)
+  unfolding setsum_over_permutations_insert[OF f123]
+  unfolding setsum_over_permutations_insert[OF f23]
+
+  unfolding permutes_sing
+  apply (simp add: sign_swap_id permutation_swap_id sign_compose sign_id swap_id_eq del: One_nat_def)
+  apply (simp add: arith_simps(31)[symmetric] of_int_minus of_int_1 del: arith_simps(31) One_nat_def)
+  by (simp add: ring_simps)
+qed
+
+end
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Euclidean_Space.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,5170 @@
+(* Title:      Library/Euclidean_Space
+   ID:         $Id: 
+   Author:     Amine Chaieb, University of Cambridge
+*)
+
+header {* (Real) Vectors in Euclidean space, and elementary linear algebra.*}
+
+theory Euclidean_Space
+  imports "~~/src/HOL/Decision_Procs/Dense_Linear_Order" Complex_Main 
+  Finite_Cartesian_Product Glbs Infinite_Set Numeral_Type
+  uses ("normarith.ML")
+begin
+
+text{* Some common special cases.*}
+
+lemma forall_1: "(\<forall>(i::'a::{order,one}). 1 <= i \<and> i <= 1 --> P i) \<longleftrightarrow> P 1"
+  by (metis order_eq_iff)
+lemma forall_dimindex_1: "(\<forall>i \<in> {1..dimindex(UNIV:: 1 set)}. P i) \<longleftrightarrow> P 1"
+  by (simp add: dimindex_def)
+
+lemma forall_2: "(\<forall>(i::nat). 1 <= i \<and> i <= 2 --> P i) \<longleftrightarrow> P 1 \<and> P 2"
+proof-
+  have "\<And>i::nat. 1 <= i \<and> i <= 2 \<longleftrightarrow> i = 1 \<or> i = 2" by arith
+  thus ?thesis by metis
+qed
+
+lemma forall_3: "(\<forall>(i::nat). 1 <= i \<and> i <= 3 --> P i) \<longleftrightarrow> P 1 \<and> P 2 \<and> P 3"
+proof-
+  have "\<And>i::nat. 1 <= i \<and> i <= 3 \<longleftrightarrow> i = 1 \<or> i = 2 \<or> i = 3" by arith
+  thus ?thesis by metis
+qed
+
+lemma setsum_singleton[simp]: "setsum f {x} = f x" by simp
+lemma setsum_1: "setsum f {(1::'a::{order,one})..1} = f 1" 
+  by (simp add: atLeastAtMost_singleton)
+
+lemma setsum_2: "setsum f {1::nat..2} = f 1 + f 2" 
+  by (simp add: nat_number  atLeastAtMostSuc_conv add_commute)
+
+lemma setsum_3: "setsum f {1::nat..3} = f 1 + f 2 + f 3" 
+  by (simp add: nat_number  atLeastAtMostSuc_conv add_commute)
+
+section{* Basic componentwise operations on vectors. *}
+
+instantiation "^" :: (plus,type) plus
+begin
+definition  vector_add_def : "op + \<equiv> (\<lambda> x y.  (\<chi> i. (x$i) + (y$i)))" 
+instance ..
+end
+
+instantiation "^" :: (times,type) times
+begin
+  definition vector_mult_def : "op * \<equiv> (\<lambda> x y.  (\<chi> i. (x$i) * (y$i)))" 
+  instance ..
+end
+
+instantiation "^" :: (minus,type) minus begin
+  definition vector_minus_def : "op - \<equiv> (\<lambda> x y.  (\<chi> i. (x$i) - (y$i)))"
+instance ..
+end
+
+instantiation "^" :: (uminus,type) uminus begin
+  definition vector_uminus_def : "uminus \<equiv> (\<lambda> x.  (\<chi> i. - (x$i)))"
+instance ..
+end
+instantiation "^" :: (zero,type) zero begin
+  definition vector_zero_def : "0 \<equiv> (\<chi> i. 0)" 
+instance ..
+end
+
+instantiation "^" :: (one,type) one begin
+  definition vector_one_def : "1 \<equiv> (\<chi> i. 1)" 
+instance ..
+end
+
+instantiation "^" :: (ord,type) ord
+ begin
+definition vector_less_eq_def:
+  "less_eq (x :: 'a ^'b) y = (ALL i : {1 .. dimindex (UNIV :: 'b set)}.
+  x$i <= y$i)"
+definition vector_less_def: "less (x :: 'a ^'b) y = (ALL i : {1 ..
+  dimindex (UNIV :: 'b set)}. x$i < y$i)"
+ 
+instance by (intro_classes)
+end
+
+text{* Also the scalar-vector multiplication. FIXME: We should unify this with the scalar multiplication in real_vector *}
+
+definition vector_scalar_mult:: "'a::times \<Rightarrow> 'a ^'n \<Rightarrow> 'a ^ 'n" (infixr "*s" 75)
+  where "c *s x = (\<chi> i. c * (x$i))"
+
+text{* Constant Vectors *}
+
+definition "vec x = (\<chi> i. x)"
+
+text{* Dot products. *}
+
+definition dot :: "'a::{comm_monoid_add, times} ^ 'n \<Rightarrow> 'a ^ 'n \<Rightarrow> 'a" (infix "\<bullet>" 70) where
+  "x \<bullet> y = setsum (\<lambda>i. x$i * y$i) {1 .. dimindex (UNIV:: 'n set)}"
+lemma dot_1[simp]: "(x::'a::{comm_monoid_add, times}^1) \<bullet> y = (x$1) * (y$1)"
+  by (simp add: dot_def dimindex_def)
+
+lemma dot_2[simp]: "(x::'a::{comm_monoid_add, times}^2) \<bullet> y = (x$1) * (y$1) + (x$2) * (y$2)"
+  by (simp add: dot_def dimindex_def nat_number)
+
+lemma dot_3[simp]: "(x::'a::{comm_monoid_add, times}^3) \<bullet> y = (x$1) * (y$1) + (x$2) * (y$2) + (x$3) * (y$3)"
+  by (simp add: dot_def dimindex_def nat_number)
+
+section {* A naive proof procedure to lift really trivial arithmetic stuff from the basis of the vector space. *}
+
+lemmas Cart_lambda_beta' = Cart_lambda_beta[rule_format]
+method_setup vector = {*
+let
+  val ss1 = HOL_basic_ss addsimps [@{thm dot_def}, @{thm setsum_addf} RS sym, 
+  @{thm setsum_subtractf} RS sym, @{thm setsum_right_distrib}, 
+  @{thm setsum_left_distrib}, @{thm setsum_negf} RS sym]
+  val ss2 = @{simpset} addsimps 
+             [@{thm vector_add_def}, @{thm vector_mult_def},  
+              @{thm vector_minus_def}, @{thm vector_uminus_def}, 
+              @{thm vector_one_def}, @{thm vector_zero_def}, @{thm vec_def}, 
+              @{thm Cart_lambda_beta'}, @{thm vector_scalar_mult_def}]
+ fun vector_arith_tac ths = 
+   simp_tac ss1
+   THEN' (fn i => rtac @{thm setsum_cong2} i
+         ORELSE rtac @{thm setsum_0'} i 
+         ORELSE simp_tac (HOL_basic_ss addsimps [@{thm "Cart_eq"}]) i)
+   (* THEN' TRY o clarify_tac HOL_cs  THEN' (TRY o rtac @{thm iffI}) *)
+   THEN' asm_full_simp_tac (ss2 addsimps ths)
+ in
+  Method.thms_args (Method.SIMPLE_METHOD' o vector_arith_tac)
+end
+*} "Lifts trivial vector statements to real arith statements"
+
+lemma vec_0[simp]: "vec 0 = 0" by (vector vector_zero_def)
+lemma vec_1[simp]: "vec 1 = 1" by (vector vector_one_def)
+
+
+
+text{* Obvious "component-pushing". *}
+
+lemma vec_component: " i \<in> {1 .. dimindex (UNIV :: 'n set)} \<Longrightarrow> (vec x :: 'a ^ 'n)$i = x" 
+  by (vector vec_def) 
+
+lemma vector_add_component: 
+  fixes x y :: "'a::{plus} ^ 'n"  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(x + y)$i = x$i + y$i"
+  using i by vector
+
+lemma vector_minus_component: 
+  fixes x y :: "'a::{minus} ^ 'n"  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(x - y)$i = x$i - y$i"
+  using i  by vector
+
+lemma vector_mult_component: 
+  fixes x y :: "'a::{times} ^ 'n"  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(x * y)$i = x$i * y$i"
+  using i by vector
+
+lemma vector_smult_component: 
+  fixes y :: "'a::{times} ^ 'n"  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(c *s y)$i = c * (y$i)"
+  using i by vector
+
+lemma vector_uminus_component: 
+  fixes x :: "'a::{uminus} ^ 'n"  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(- x)$i = - (x$i)"
+  using i by vector
+
+lemma cond_component: "(if b then x else y)$i = (if b then x$i else y$i)" by vector
+
+lemmas vector_component = vec_component vector_add_component vector_mult_component vector_smult_component vector_minus_component vector_uminus_component cond_component 
+
+subsection {* Some frequently useful arithmetic lemmas over vectors. *}
+
+instance "^" :: (semigroup_add,type) semigroup_add 
+  apply (intro_classes) by (vector add_assoc)
+
+
+instance "^" :: (monoid_add,type) monoid_add 
+  apply (intro_classes) by vector+ 
+
+instance "^" :: (group_add,type) group_add 
+  apply (intro_classes) by (vector algebra_simps)+ 
+
+instance "^" :: (ab_semigroup_add,type) ab_semigroup_add 
+  apply (intro_classes) by (vector add_commute)
+
+instance "^" :: (comm_monoid_add,type) comm_monoid_add
+  apply (intro_classes) by vector
+
+instance "^" :: (ab_group_add,type) ab_group_add 
+  apply (intro_classes) by vector+
+
+instance "^" :: (cancel_semigroup_add,type) cancel_semigroup_add 
+  apply (intro_classes)
+  by (vector Cart_eq)+
+
+instance "^" :: (cancel_ab_semigroup_add,type) cancel_ab_semigroup_add
+  apply (intro_classes)
+  by (vector Cart_eq)
+
+instance "^" :: (semigroup_mult,type) semigroup_mult 
+  apply (intro_classes) by (vector mult_assoc)
+
+instance "^" :: (monoid_mult,type) monoid_mult 
+  apply (intro_classes) by vector+
+
+instance "^" :: (ab_semigroup_mult,type) ab_semigroup_mult 
+  apply (intro_classes) by (vector mult_commute)
+
+instance "^" :: (ab_semigroup_idem_mult,type) ab_semigroup_idem_mult 
+  apply (intro_classes) by (vector mult_idem)
+
+instance "^" :: (comm_monoid_mult,type) comm_monoid_mult 
+  apply (intro_classes) by vector
+
+fun vector_power :: "('a::{one,times} ^'n) \<Rightarrow> nat \<Rightarrow> 'a^'n" where
+  "vector_power x 0 = 1"
+  | "vector_power x (Suc n) = x * vector_power x n"
+
+instantiation "^" :: (recpower,type) recpower 
+begin
+  definition vec_power_def: "op ^ \<equiv> vector_power"
+  instance 
+  apply (intro_classes) by (simp_all add: vec_power_def) 
+end
+
+instance "^" :: (semiring,type) semiring
+  apply (intro_classes) by (vector ring_simps)+
+
+instance "^" :: (semiring_0,type) semiring_0
+  apply (intro_classes) by (vector ring_simps)+
+instance "^" :: (semiring_1,type) semiring_1
+  apply (intro_classes) apply vector using dimindex_ge_1 by auto 
+instance "^" :: (comm_semiring,type) comm_semiring
+  apply (intro_classes) by (vector ring_simps)+
+
+instance "^" :: (comm_semiring_0,type) comm_semiring_0 by (intro_classes) 
+instance "^" :: (semiring_0_cancel,type) semiring_0_cancel by (intro_classes) 
+instance "^" :: (comm_semiring_0_cancel,type) comm_semiring_0_cancel by (intro_classes) 
+instance "^" :: (ring,type) ring by (intro_classes) 
+instance "^" :: (semiring_1_cancel,type) semiring_1_cancel by (intro_classes) 
+instance "^" :: (comm_semiring_1,type) comm_semiring_1 by (intro_classes)
+lemma of_nat_index: 
+  "i\<in>{1 .. dimindex (UNIV :: 'n set)} \<Longrightarrow> (of_nat n :: 'a::semiring_1 ^'n)$i = of_nat n"
+  apply (induct n)
+  apply vector
+  apply vector
+  done
+lemma zero_index[simp]: 
+  "i\<in>{1 .. dimindex (UNIV :: 'n set)} \<Longrightarrow> (0 :: 'a::zero ^'n)$i = 0" by vector
+
+lemma one_index[simp]: 
+  "i\<in>{1 .. dimindex (UNIV :: 'n set)} \<Longrightarrow> (1 :: 'a::one ^'n)$i = 1" by vector
+
+lemma one_plus_of_nat_neq_0: "(1::'a::semiring_char_0) + of_nat n \<noteq> 0"
+proof-
+  have "(1::'a) + of_nat n = 0 \<longleftrightarrow> of_nat 1 + of_nat n = (of_nat 0 :: 'a)" by simp
+  also have "\<dots> \<longleftrightarrow> 1 + n = 0" by (simp only: of_nat_add[symmetric] of_nat_eq_iff) 
+  finally show ?thesis by simp 
+qed
+
+instance "^" :: (semiring_char_0,type) semiring_char_0 
+proof (intro_classes) 
+  fix m n ::nat
+  show "(of_nat m :: 'a^'b) = of_nat n \<longleftrightarrow> m = n"
+  proof(induct m arbitrary: n)
+    case 0 thus ?case apply vector 
+      apply (induct n,auto simp add: ring_simps)
+      using dimindex_ge_1 apply auto
+      apply vector
+      by (auto simp add: of_nat_index one_plus_of_nat_neq_0)
+  next
+    case (Suc n m)
+    thus ?case  apply vector
+      apply (induct m, auto simp add: ring_simps of_nat_index zero_index)
+      using dimindex_ge_1 apply simp apply blast
+      apply (simp add: one_plus_of_nat_neq_0)
+      using dimindex_ge_1 apply simp apply blast
+      apply (simp add: vector_component one_index of_nat_index)
+      apply (simp only: of_nat.simps(2)[where ?'a = 'a, symmetric] of_nat_eq_iff)
+      using  dimindex_ge_1 apply simp apply blast
+      apply (simp add: vector_component one_index of_nat_index)
+      apply (simp only: of_nat.simps(2)[where ?'a = 'a, symmetric] of_nat_eq_iff)
+      using dimindex_ge_1 apply simp apply blast
+      apply (simp add: vector_component one_index of_nat_index)
+      done
+  qed
+qed
+
+instance "^" :: (comm_ring_1,type) comm_ring_1 by intro_classes
+  (* FIXME!!! Why does the axclass package complain here !!*)
+(* instance "^" :: (ring_char_0,type) ring_char_0 by intro_classes *)
+
+lemma vector_smult_assoc: "a *s (b *s x) = ((a::'a::semigroup_mult) * b) *s x"  
+  by (vector mult_assoc)
+lemma vector_sadd_rdistrib: "((a::'a::semiring) + b) *s x = a *s x + b *s x" 
+  by (vector ring_simps)
+lemma vector_add_ldistrib: "(c::'a::semiring) *s (x + y) = c *s x + c *s y" 
+  by (vector ring_simps)
+lemma vector_smult_lzero[simp]: "(0::'a::mult_zero) *s x = 0" by vector
+lemma vector_smult_lid[simp]: "(1::'a::monoid_mult) *s x = x" by vector
+lemma vector_ssub_ldistrib: "(c::'a::ring) *s (x - y) = c *s x - c *s y" 
+  by (vector ring_simps)
+lemma vector_smult_rneg: "(c::'a::ring) *s -x = -(c *s x)" by vector
+lemma vector_smult_lneg: "- (c::'a::ring) *s x = -(c *s x)" by vector
+lemma vector_sneg_minus1: "-x = (- (1::'a::ring_1)) *s x" by vector
+lemma vector_smult_rzero[simp]: "c *s 0 = (0::'a::mult_zero ^ 'n)" by vector
+lemma vector_sub_rdistrib: "((a::'a::ring) - b) *s x = a *s x - b *s x" 
+  by (vector ring_simps)
+
+lemma vec_eq[simp]: "(vec m = vec n) \<longleftrightarrow> (m = n)" 
+  apply (auto simp add: vec_def Cart_eq vec_component Cart_lambda_beta )
+  using dimindex_ge_1 apply auto done
+
+subsection{* Properties of the dot product.  *}
+
+lemma dot_sym: "(x::'a:: {comm_monoid_add, ab_semigroup_mult} ^ 'n) \<bullet> y = y \<bullet> x" 
+  by (vector mult_commute)
+lemma dot_ladd: "((x::'a::ring ^ 'n) + y) \<bullet> z = (x \<bullet> z) + (y \<bullet> z)"
+  by (vector ring_simps)
+lemma dot_radd: "x \<bullet> (y + (z::'a::ring ^ 'n)) = (x \<bullet> y) + (x \<bullet> z)" 
+  by (vector ring_simps)
+lemma dot_lsub: "((x::'a::ring ^ 'n) - y) \<bullet> z = (x \<bullet> z) - (y \<bullet> z)" 
+  by (vector ring_simps)
+lemma dot_rsub: "(x::'a::ring ^ 'n) \<bullet> (y - z) = (x \<bullet> y) - (x \<bullet> z)" 
+  by (vector ring_simps)
+lemma dot_lmult: "(c *s x) \<bullet> y = (c::'a::ring) * (x \<bullet> y)" by (vector ring_simps)
+lemma dot_rmult: "x \<bullet> (c *s y) = (c::'a::comm_ring) * (x \<bullet> y)" by (vector ring_simps)
+lemma dot_lneg: "(-x) \<bullet> (y::'a::ring ^ 'n) = -(x \<bullet> y)" by vector
+lemma dot_rneg: "(x::'a::ring ^ 'n) \<bullet> (-y) = -(x \<bullet> y)" by vector
+lemma dot_lzero[simp]: "0 \<bullet> x = (0::'a::{comm_monoid_add, mult_zero})" by vector
+lemma dot_rzero[simp]: "x \<bullet> 0 = (0::'a::{comm_monoid_add, mult_zero})" by vector
+lemma dot_pos_le[simp]: "(0::'a\<Colon>ordered_ring_strict) <= x \<bullet> x"
+  by (simp add: dot_def setsum_nonneg)
+
+lemma setsum_squares_eq_0_iff: assumes fS: "finite F" and fp: "\<forall>x \<in> F. f x \<ge> (0 ::'a::pordered_ab_group_add)" shows "setsum f F = 0 \<longleftrightarrow> (ALL x:F. f x = 0)"
+using fS fp setsum_nonneg[OF fp]
+proof (induct set: finite)
+  case empty thus ?case by simp
+next
+  case (insert x F)
+  from insert.prems have Fx: "f x \<ge> 0" and Fp: "\<forall> a \<in> F. f a \<ge> 0" by simp_all
+  from insert.hyps Fp setsum_nonneg[OF Fp]
+  have h: "setsum f F = 0 \<longleftrightarrow> (\<forall>a \<in>F. f a = 0)" by metis
+  from sum_nonneg_eq_zero_iff[OF Fx  setsum_nonneg[OF Fp]] insert.hyps(1,2)
+  show ?case by (simp add: h)
+qed
+
+lemma dot_eq_0: "x \<bullet> x = 0 \<longleftrightarrow> (x::'a::{ordered_ring_strict,ring_no_zero_divisors} ^ 'n) = 0"
+proof-
+  {assume f: "finite (UNIV :: 'n set)"
+    let ?S = "{Suc 0 .. card (UNIV :: 'n set)}"
+    have fS: "finite ?S" using f by simp
+    have fp: "\<forall> i\<in> ?S. x$i * x$i>= 0" by simp
+    have ?thesis by (vector dimindex_def f setsum_squares_eq_0_iff[OF fS fp])}
+  moreover
+  {assume "\<not> finite (UNIV :: 'n set)" then have ?thesis by (vector dimindex_def)}
+  ultimately show ?thesis by metis
+qed
+
+lemma dot_pos_lt: "(0 < x \<bullet> x) \<longleftrightarrow> (x::'a::{ordered_ring_strict,ring_no_zero_divisors} ^ 'n) \<noteq> 0" using dot_eq_0[of x] dot_pos_le[of x] 
+  by (auto simp add: le_less) 
+
+subsection {* Introduce norms, but defer many properties till we get square roots. *}
+text{* FIXME : This is ugly *}
+defs (overloaded) 
+  real_of_real_def [code inline, simp]: "real == id"
+
+instantiation "^" :: ("{times, comm_monoid_add}", type) norm begin
+definition  real_vector_norm_def: "norm \<equiv> (\<lambda>x. sqrt (real (x \<bullet> x)))" 
+instance ..
+end
+
+
+subsection{* The collapse of the general concepts to dimention one. *}
+
+lemma vector_one: "(x::'a ^1) = (\<chi> i. (x$1))"
+  by (vector dimindex_def)
+
+lemma forall_one: "(\<forall>(x::'a ^1). P x) \<longleftrightarrow> (\<forall>x. P(\<chi> i. x))"
+  apply auto
+  apply (erule_tac x= "x$1" in allE)
+  apply (simp only: vector_one[symmetric])
+  done
+
+lemma norm_real: "norm(x::real ^ 1) = abs(x$1)" 
+  by (simp add: real_vector_norm_def)
+
+text{* Metric *}
+
+definition dist:: "real ^ 'n \<Rightarrow> real ^ 'n \<Rightarrow> real" where 
+  "dist x y = norm (x - y)"
+
+lemma dist_real: "dist(x::real ^ 1) y = abs((x$1) - (y$1))"
+  using dimindex_ge_1[of "UNIV :: 1 set"]
+  by (auto simp add: norm_real dist_def vector_component Cart_lambda_beta[where ?'a = "1"] )
+
+subsection {* A connectedness or intermediate value lemma with several applications. *}
+
+lemma connected_real_lemma:
+  fixes f :: "real \<Rightarrow> real ^ 'n"
+  assumes ab: "a \<le> b" and fa: "f a \<in> e1" and fb: "f b \<in> e2"
+  and dst: "\<And>e x. a <= x \<Longrightarrow> x <= b \<Longrightarrow> 0 < e ==> \<exists>d > 0. \<forall>y. abs(y - x) < d \<longrightarrow> dist(f y) (f x) < e"
+  and e1: "\<forall>y \<in> e1. \<exists>e > 0. \<forall>y'. dist y' y < e \<longrightarrow> y' \<in> e1"
+  and e2: "\<forall>y \<in> e2. \<exists>e > 0. \<forall>y'. dist y' y < e \<longrightarrow> y' \<in> e2"
+  and e12: "~(\<exists>x \<ge> a. x <= b \<and> f x \<in> e1 \<and> f x \<in> e2)"
+  shows "\<exists>x \<ge> a. x <= b \<and> f x \<notin> e1 \<and> f x \<notin> e2" (is "\<exists> x. ?P x")
+proof-
+  let ?S = "{c. \<forall>x \<ge> a. x <= c \<longrightarrow> f x \<in> e1}"
+  have Se: " \<exists>x. x \<in> ?S" apply (rule exI[where x=a]) by (auto simp add: fa) 
+  have Sub: "\<exists>y. isUb UNIV ?S y" 
+    apply (rule exI[where x= b])
+    using ab fb e12 by (auto simp add: isUb_def setle_def)  
+  from reals_complete[OF Se Sub] obtain l where 
+    l: "isLub UNIV ?S l"by blast
+  have alb: "a \<le> l" "l \<le> b" using l ab fa fb e12
+    apply (auto simp add: isLub_def leastP_def isUb_def setle_def setge_def)    
+    by (metis linorder_linear)
+  have ale1: "\<forall>z \<ge> a. z < l \<longrightarrow> f z \<in> e1" using l
+    apply (auto simp add: isLub_def leastP_def isUb_def setle_def setge_def)
+    by (metis linorder_linear not_le)
+    have th1: "\<And>z x e d :: real. z <= x + e \<Longrightarrow> e < d ==> z < x \<or> abs(z - x) < d" by arith
+    have th2: "\<And>e x:: real. 0 < e ==> ~(x + e <= x)" by arith
+    have th3: "\<And>d::real. d > 0 \<Longrightarrow> \<exists>e > 0. e < d" by dlo
+    {assume le2: "f l \<in> e2"
+      from le2 fa fb e12 alb have la: "l \<noteq> a" by metis
+      hence lap: "l - a > 0" using alb by arith
+      from e2[rule_format, OF le2] obtain e where 
+	e: "e > 0" "\<forall>y. dist y (f l) < e \<longrightarrow> y \<in> e2" by metis
+      from dst[OF alb e(1)] obtain d where 
+	d: "d > 0" "\<forall>y. \<bar>y - l\<bar> < d \<longrightarrow> dist (f y) (f l) < e" by metis
+      have "\<exists>d'. d' < d \<and> d' >0 \<and> l - d' > a" using lap d(1) 
+	apply ferrack by arith
+      then obtain d' where d': "d' > 0" "d' < d" "l - d' > a" by metis
+      from d e have th0: "\<forall>y. \<bar>y - l\<bar> < d \<longrightarrow> f y \<in> e2" by metis
+      from th0[rule_format, of "l - d'"] d' have "f (l - d') \<in> e2" by auto
+      moreover
+      have "f (l - d') \<in> e1" using ale1[rule_format, of "l -d'"] d' by auto
+      ultimately have False using e12 alb d' by auto}
+    moreover
+    {assume le1: "f l \<in> e1"
+    from le1 fa fb e12 alb have lb: "l \<noteq> b" by metis
+      hence blp: "b - l > 0" using alb by arith
+      from e1[rule_format, OF le1] obtain e where 
+	e: "e > 0" "\<forall>y. dist y (f l) < e \<longrightarrow> y \<in> e1" by metis
+      from dst[OF alb e(1)] obtain d where 
+	d: "d > 0" "\<forall>y. \<bar>y - l\<bar> < d \<longrightarrow> dist (f y) (f l) < e" by metis
+      have "\<exists>d'. d' < d \<and> d' >0" using d(1) by dlo 
+      then obtain d' where d': "d' > 0" "d' < d" by metis
+      from d e have th0: "\<forall>y. \<bar>y - l\<bar> < d \<longrightarrow> f y \<in> e1" by auto
+      hence "\<forall>y. l \<le> y \<and> y \<le> l + d' \<longrightarrow> f y \<in> e1" using d' by auto
+      with ale1 have "\<forall>y. a \<le> y \<and> y \<le> l + d' \<longrightarrow> f y \<in> e1" by auto
+      with l d' have False 
+	by (auto simp add: isLub_def isUb_def setle_def setge_def leastP_def) }
+    ultimately show ?thesis using alb by metis
+qed
+
+text{* One immediately useful corollary is the existence of square roots! --- Should help to get rid of all the development of square-root for reals as a special case real ^1 *}
+
+lemma square_bound_lemma: "(x::real) < (1 + x) * (1 + x)"
+proof-
+  have "(x + 1/2)^2 + 3/4 > 0" using zero_le_power2[of "x+1/2"] by arith 
+  thus ?thesis by (simp add: ring_simps power2_eq_square)
+qed
+
+lemma square_continuous: "0 < (e::real) ==> \<exists>d. 0 < d \<and> (\<forall>y. abs(y - x) < d \<longrightarrow> abs(y * y - x * x) < e)"
+  using isCont_power[OF isCont_ident, of 2, unfolded isCont_def LIM_def, rule_format, of e x] apply (auto simp add: power2_eq_square)
+  apply (rule_tac x="s" in exI)
+  apply auto
+  apply (erule_tac x=y in allE)
+  apply auto
+  done
+
+lemma real_le_lsqrt: "0 <= x \<Longrightarrow> 0 <= y \<Longrightarrow> x <= y^2 ==> sqrt x <= y"
+  using real_sqrt_le_iff[of x "y^2"] by simp
+
+lemma real_le_rsqrt: "x^2 \<le> y \<Longrightarrow> x \<le> sqrt y"
+  using real_sqrt_le_mono[of "x^2" y] by simp
+
+lemma real_less_rsqrt: "x^2 < y \<Longrightarrow> x < sqrt y"
+  using real_sqrt_less_mono[of "x^2" y] by simp
+
+lemma sqrt_even_pow2: assumes n: "even n" 
+  shows "sqrt(2 ^ n) = 2 ^ (n div 2)"
+proof-
+  from n obtain m where m: "n = 2*m" unfolding even_nat_equiv_def2 
+    by (auto simp add: nat_number) 
+  from m  have "sqrt(2 ^ n) = sqrt ((2 ^ m) ^ 2)"
+    by (simp only: power_mult[symmetric] mult_commute)
+  then show ?thesis  using m by simp 
+qed
+
+lemma real_div_sqrt: "0 <= x ==> x / sqrt(x) = sqrt(x)"
+  apply (cases "x = 0", simp_all)
+  using sqrt_divide_self_eq[of x]
+  apply (simp add: inverse_eq_divide real_sqrt_ge_0_iff field_simps)
+  done
+
+text{* Hence derive more interesting properties of the norm. *}
+
+lemma norm_0: "norm (0::real ^ 'n) = 0"
+  by (simp add: real_vector_norm_def dot_eq_0)
+
+lemma norm_pos_le: "0 <= norm (x::real^'n)" 
+  by (simp add: real_vector_norm_def dot_pos_le)
+lemma norm_neg: " norm(-x) = norm (x:: real ^ 'n)" 
+  by (simp add: real_vector_norm_def dot_lneg dot_rneg)
+lemma norm_sub: "norm(x - y) = norm(y - (x::real ^ 'n))" 
+  by (metis norm_neg minus_diff_eq)
+lemma norm_mul: "norm(a *s x) = abs(a) * norm x"
+  by (simp add: real_vector_norm_def dot_lmult dot_rmult mult_assoc[symmetric] real_sqrt_mult)
+lemma norm_eq_0_dot: "(norm x = 0) \<longleftrightarrow> (x \<bullet> x = (0::real))"
+  by (simp add: real_vector_norm_def)
+lemma norm_eq_0: "norm x = 0 \<longleftrightarrow> x = (0::real ^ 'n)"
+  by (simp add: real_vector_norm_def dot_eq_0)
+lemma norm_pos_lt: "0 < norm x \<longleftrightarrow> x \<noteq> (0::real ^ 'n)"
+  by (metis less_le real_vector_norm_def norm_pos_le norm_eq_0)
+lemma norm_pow_2: "norm x ^ 2 = x \<bullet> x"
+  by (simp add: real_vector_norm_def dot_pos_le)
+lemma norm_eq_0_imp: "norm x = 0 ==> x = (0::real ^'n)" by (metis norm_eq_0)
+lemma norm_le_0: "norm x <= 0 \<longleftrightarrow> x = (0::real ^'n)"
+  by (metis norm_eq_0 norm_pos_le order_antisym) 
+lemma vector_mul_eq_0: "(a *s x = 0) \<longleftrightarrow> a = (0::'a::idom) \<or> x = 0"
+  by vector
+lemma vector_mul_lcancel: "a *s x = a *s y \<longleftrightarrow> a = (0::real) \<or> x = y"
+  by (metis eq_iff_diff_eq_0 vector_mul_eq_0 vector_ssub_ldistrib)
+lemma vector_mul_rcancel: "a *s x = b *s x \<longleftrightarrow> (a::real) = b \<or> x = 0"
+  by (metis eq_iff_diff_eq_0 vector_mul_eq_0 vector_sub_rdistrib)
+lemma vector_mul_lcancel_imp: "a \<noteq> (0::real) ==>  a *s x = a *s y ==> (x = y)"
+  by (metis vector_mul_lcancel)
+lemma vector_mul_rcancel_imp: "x \<noteq> 0 \<Longrightarrow> (a::real) *s x = b *s x ==> a = b"
+  by (metis vector_mul_rcancel)
+lemma norm_cauchy_schwarz: "x \<bullet> y <= norm x * norm y"
+proof-
+  {assume "norm x = 0"
+    hence ?thesis by (simp add: norm_eq_0 dot_lzero dot_rzero norm_0)}
+  moreover
+  {assume "norm y = 0" 
+    hence ?thesis by (simp add: norm_eq_0 dot_lzero dot_rzero norm_0)}
+  moreover
+  {assume h: "norm x \<noteq> 0" "norm y \<noteq> 0"
+    let ?z = "norm y *s x - norm x *s y"
+    from h have p: "norm x * norm y > 0" by (metis norm_pos_le le_less zero_compare_simps)
+    from dot_pos_le[of ?z]
+    have "(norm x * norm y) * (x \<bullet> y) \<le> norm x ^2 * norm y ^2"
+      apply (simp add: dot_rsub dot_lsub dot_lmult dot_rmult ring_simps)
+      by (simp add: norm_pow_2[symmetric] power2_eq_square dot_sym)
+    hence "x\<bullet>y \<le> (norm x ^2 * norm y ^2) / (norm x * norm y)" using p
+      by (simp add: field_simps)
+    hence ?thesis using h by (simp add: power2_eq_square)}
+  ultimately show ?thesis by metis
+qed
+
+lemma norm_abs[simp]: "abs (norm x) = norm (x::real ^'n)" 
+  using norm_pos_le[of x] by (simp add: real_abs_def linorder_linear)
+
+lemma norm_cauchy_schwarz_abs: "\<bar>x \<bullet> y\<bar> \<le> norm x * norm y"
+  using norm_cauchy_schwarz[of x y] norm_cauchy_schwarz[of x "-y"]
+  by (simp add: real_abs_def dot_rneg norm_neg)
+lemma norm_triangle: "norm(x + y) <= norm x + norm (y::real ^'n)"
+  unfolding real_vector_norm_def
+  apply (rule real_le_lsqrt)
+  apply (auto simp add: dot_pos_le real_vector_norm_def[symmetric] norm_pos_le norm_pow_2[symmetric] intro: add_nonneg_nonneg)[1]
+  apply (auto simp add: dot_pos_le real_vector_norm_def[symmetric] norm_pos_le norm_pow_2[symmetric] intro: add_nonneg_nonneg)[1]
+  apply (simp add: dot_ladd dot_radd dot_sym )
+    by (simp add: norm_pow_2[symmetric] power2_eq_square ring_simps norm_cauchy_schwarz)
+
+lemma norm_triangle_sub: "norm (x::real ^'n) <= norm(y) + norm(x - y)"
+  using norm_triangle[of "y" "x - y"] by (simp add: ring_simps)
+lemma norm_triangle_le: "norm(x::real ^'n) + norm y <= e ==> norm(x + y) <= e"
+  by (metis order_trans norm_triangle)
+lemma norm_triangle_lt: "norm(x::real ^'n) + norm(y) < e ==> norm(x + y) < e"
+  by (metis basic_trans_rules(21) norm_triangle)
+
+lemma setsum_delta: 
+  assumes fS: "finite S"
+  shows "setsum (\<lambda>k. if k=a then b k else 0) S = (if a \<in> S then b a else 0)"
+proof-
+  let ?f = "(\<lambda>k. if k=a then b k else 0)"
+  {assume a: "a \<notin> S"
+    hence "\<forall> k\<in> S. ?f k = 0" by simp
+    hence ?thesis  using a by simp}
+  moreover 
+  {assume a: "a \<in> S"
+    let ?A = "S - {a}"
+    let ?B = "{a}"
+    have eq: "S = ?A \<union> ?B" using a by blast 
+    have dj: "?A \<inter> ?B = {}" by simp
+    from fS have fAB: "finite ?A" "finite ?B" by auto  
+    have "setsum ?f S = setsum ?f ?A + setsum ?f ?B"
+      using setsum_Un_disjoint[OF fAB dj, of ?f, unfolded eq[symmetric]]
+      by simp
+    then have ?thesis  using a by simp}
+  ultimately show ?thesis by blast
+qed
+  
+lemma component_le_norm: "i \<in> {1 .. dimindex(UNIV :: 'n set)} ==> \<bar>x$i\<bar> <= norm (x::real ^ 'n)"
+proof(simp add: real_vector_norm_def, rule real_le_rsqrt, clarsimp)
+  assume i: "Suc 0 \<le> i" "i \<le> dimindex (UNIV :: 'n set)"
+  let ?S = "{1 .. dimindex(UNIV :: 'n set)}"
+  let ?f = "(\<lambda>k. if k = i then x$i ^2 else 0)"
+  have fS: "finite ?S" by simp
+  from i setsum_delta[OF fS, of i "\<lambda>k. x$i ^ 2"]
+  have th: "x$i^2 = setsum ?f ?S" by simp
+  let ?g = "\<lambda>k. x$k * x$k"
+  {fix x assume x: "x \<in> ?S" have "?f x \<le> ?g x" by (simp add: power2_eq_square)}
+  with setsum_mono[of ?S ?f ?g] 
+  have "setsum ?f ?S \<le> setsum ?g ?S" by blast 
+  then show "x$i ^2 \<le> x \<bullet> (x:: real ^ 'n)" unfolding dot_def th[symmetric] .
+qed    
+lemma norm_bound_component_le: "norm(x::real ^ 'n) <= e
+                ==> \<forall>i \<in> {1 .. dimindex(UNIV:: 'n set)}. \<bar>x$i\<bar> <= e"
+  by (metis component_le_norm order_trans)
+
+lemma norm_bound_component_lt: "norm(x::real ^ 'n) < e
+                ==> \<forall>i \<in> {1 .. dimindex(UNIV:: 'n set)}. \<bar>x$i\<bar> < e"
+  by (metis component_le_norm basic_trans_rules(21))
+
+lemma norm_le_l1: "norm (x:: real ^'n) <= setsum(\<lambda>i. \<bar>x$i\<bar>) {1..dimindex(UNIV::'n set)}"
+proof (simp add: real_vector_norm_def, rule real_le_lsqrt,simp add: dot_pos_le, simp add: setsum_mono, simp add: dot_def, induct "dimindex(UNIV::'n set)")
+  case 0 thus ?case by simp
+next
+  case (Suc n)
+  have th: "2 * (\<bar>x$(Suc n)\<bar> * (\<Sum>i = Suc 0..n. \<bar>x$i\<bar>)) \<ge> 0" 
+    apply simp
+    apply (rule mult_nonneg_nonneg)
+    by (simp_all add: setsum_abs_ge_zero)
+  
+  from Suc
+  show ?case using th by (simp add: power2_eq_square ring_simps)
+qed
+
+lemma real_abs_norm: "\<bar> norm x\<bar> = norm (x :: real ^'n)" 
+  by (simp add: norm_pos_le)
+lemma real_abs_sub_norm: "\<bar>norm(x::real ^'n) - norm y\<bar> <= norm(x - y)"
+  apply (simp add: abs_le_iff ring_simps)
+  by (metis norm_triangle_sub norm_sub)
+lemma norm_le: "norm(x::real ^ 'n) <= norm(y) \<longleftrightarrow> x \<bullet> x <= y \<bullet> y"
+  by (simp add: real_vector_norm_def)
+lemma norm_lt: "norm(x::real ^'n) < norm(y) \<longleftrightarrow> x \<bullet> x < y \<bullet> y"
+  by (simp add: real_vector_norm_def)
+lemma norm_eq: "norm (x::real ^'n) = norm y \<longleftrightarrow> x \<bullet> x = y \<bullet> y"
+  by (simp add: order_eq_iff norm_le)
+lemma norm_eq_1: "norm(x::real ^ 'n) = 1 \<longleftrightarrow> x \<bullet> x = 1"
+  by (simp add: real_vector_norm_def)
+
+text{* Squaring equations and inequalities involving norms.  *}
+
+lemma dot_square_norm: "x \<bullet> x = norm(x)^2"
+  by (simp add: real_vector_norm_def  dot_pos_le )
+
+lemma norm_eq_square: "norm(x) = a \<longleftrightarrow> 0 <= a \<and> x \<bullet> x = a^2"
+proof-
+  have th: "\<And>x y::real. x^2 = y^2 \<longleftrightarrow> x = y \<or> x = -y" by algebra
+  show ?thesis using norm_pos_le[of x]
+  apply (simp add: dot_square_norm th)
+  apply arith
+  done
+qed
+
+lemma real_abs_le_square_iff: "\<bar>x\<bar> \<le> \<bar>y\<bar> \<longleftrightarrow> (x::real)^2 \<le> y^2"
+proof-
+  have "x^2 \<le> y^2 \<longleftrightarrow> (x -y) * (y + x) \<le> 0" by (simp add: ring_simps power2_eq_square)
+  also have "\<dots> \<longleftrightarrow> \<bar>x\<bar> \<le> \<bar>y\<bar>" apply (simp add: zero_compare_simps real_abs_def not_less) by arith
+finally show ?thesis ..
+qed
+
+lemma norm_le_square: "norm(x) <= a \<longleftrightarrow> 0 <= a \<and> x \<bullet> x <= a^2"
+  using norm_pos_le[of x]
+  apply (simp add: dot_square_norm real_abs_le_square_iff[symmetric])
+  apply arith
+  done
+
+lemma norm_ge_square: "norm(x) >= a \<longleftrightarrow> a <= 0 \<or> x \<bullet> x >= a ^ 2" 
+  using norm_pos_le[of x]
+  apply (simp add: dot_square_norm real_abs_le_square_iff[symmetric])
+  apply arith
+  done
+
+lemma norm_lt_square: "norm(x) < a \<longleftrightarrow> 0 < a \<and> x \<bullet> x < a^2"
+  by (metis not_le norm_ge_square)
+lemma norm_gt_square: "norm(x) > a \<longleftrightarrow> a < 0 \<or> x \<bullet> x > a^2"
+  by (metis norm_le_square not_less)
+
+text{* Dot product in terms of the norm rather than conversely. *}
+
+lemma dot_norm: "x \<bullet> y = (norm(x + y) ^2 - norm x ^ 2 - norm y ^ 2) / 2"
+  by (simp add: norm_pow_2 dot_ladd dot_radd dot_sym)
+
+lemma dot_norm_neg: "x \<bullet> y = ((norm x ^ 2 + norm y ^ 2) - norm(x - y) ^ 2) / 2"
+  by (simp add: norm_pow_2 dot_ladd dot_radd dot_lsub dot_rsub dot_sym)
+
+
+text{* Equality of vectors in terms of @{term "op \<bullet>"} products.    *}
+
+lemma vector_eq: "(x:: real ^ 'n) = y \<longleftrightarrow> x \<bullet> x = x \<bullet> y\<and> y \<bullet> y = x \<bullet> x" (is "?lhs \<longleftrightarrow> ?rhs")
+proof
+  assume "?lhs" then show ?rhs by simp
+next
+  assume ?rhs
+  then have "x \<bullet> x - x \<bullet> y = 0 \<and> x \<bullet> y - y\<bullet> y = 0" by simp
+  hence "x \<bullet> (x - y) = 0 \<and> y \<bullet> (x - y) = 0" 
+    by (simp add: dot_rsub dot_lsub dot_sym)
+  then have "(x - y) \<bullet> (x - y) = 0" by (simp add: ring_simps dot_lsub dot_rsub)
+  then show "x = y" by (simp add: dot_eq_0)
+qed
+
+
+subsection{* General linear decision procedure for normed spaces. *}
+
+lemma norm_cmul_rule_thm: "b >= norm(x) ==> \<bar>c\<bar> * b >= norm(c *s x)"
+  apply (clarsimp simp add: norm_mul)
+  apply (rule mult_mono1)
+  apply simp_all
+  done
+
+lemma norm_add_rule_thm: "b1 >= norm(x1 :: real ^'n) \<Longrightarrow> b2 >= norm(x2) ==> b1 + b2 >= norm(x1 + x2)"
+  apply (rule norm_triangle_le) by simp
+
+lemma ge_iff_diff_ge_0: "(a::'a::ordered_ring) \<ge> b == a - b \<ge> 0"
+  by (simp add: ring_simps)
+
+lemma pth_1: "(x::real^'n) == 1 *s x" by (simp only: vector_smult_lid)
+lemma pth_2: "x - (y::real^'n) == x + -y" by (atomize (full)) simp
+lemma pth_3: "(-x::real^'n) == -1 *s x" by vector
+lemma pth_4: "0 *s (x::real^'n) == 0" "c *s 0 = (0::real ^ 'n)" by vector+
+lemma pth_5: "c *s (d *s x) == (c * d) *s (x::real ^ 'n)" by (atomize (full)) vector
+lemma pth_6: "(c::real) *s (x + y) == c *s x + c *s y" by (atomize (full)) (vector ring_simps)
+lemma pth_7: "0 + x == (x::real^'n)" "x + 0 == x" by simp_all 
+lemma pth_8: "(c::real) *s x + d *s x == (c + d) *s x" by (atomize (full)) (vector ring_simps) 
+lemma pth_9: "((c::real) *s x + z) + d *s x == (c + d) *s x + z"
+  "c *s x + (d *s x + z) == (c + d) *s x + z"
+  "(c *s x + w) + (d *s x + z) == (c + d) *s x + (w + z)" by ((atomize (full)), vector ring_simps)+
+lemma pth_a: "(0::real) *s x + y == y" by (atomize (full)) vector
+lemma pth_b: "(c::real) *s x + d *s y == c *s x + d *s y" 
+  "(c *s x + z) + d *s y == c *s x + (z + d *s y)"
+  "c *s x + (d *s y + z) == c *s x + (d *s y + z)"
+  "(c *s x + w) + (d *s y + z) == c *s x + (w + (d *s y + z))"
+  by ((atomize (full)), vector)+
+lemma pth_c: "(c::real) *s x + d *s y == d *s y + c *s x"
+  "(c *s x + z) + d *s y == d *s y + (c *s x + z)"
+  "c *s x + (d *s y + z) == d *s y + (c *s x + z)"
+  "(c *s x + w) + (d *s y + z) == d *s y + ((c *s x + w) + z)" by ((atomize (full)), vector)+
+lemma pth_d: "x + (0::real ^'n) == x" by (atomize (full)) vector
+
+lemma norm_imp_pos_and_ge: "norm (x::real ^ 'n) == n \<Longrightarrow> norm x \<ge> 0 \<and> n \<ge> norm x"
+  by (atomize) (auto simp add: norm_pos_le)
+
+lemma real_eq_0_iff_le_ge_0: "(x::real) = 0 == x \<ge> 0 \<and> -x \<ge> 0" by arith
+
+lemma norm_pths: 
+  "(x::real ^'n) = y \<longleftrightarrow> norm (x - y) \<le> 0"
+  "x \<noteq> y \<longleftrightarrow> \<not> (norm (x - y) \<le> 0)"
+  using norm_pos_le[of "x - y"] by (auto simp add: norm_0 norm_eq_0)
+
+use "normarith.ML"
+
+method_setup norm = {* Method.ctxt_args (Method.SIMPLE_METHOD' o NormArith.norm_arith_tac)
+*} "Proves simple linear statements about vector norms"
+
+
+
+text{* Hence more metric properties. *}
+
+lemma dist_refl: "dist x x = 0" by norm
+
+lemma dist_sym: "dist x y = dist y x"by norm
+
+lemma dist_pos_le: "0 <= dist x y" by norm
+
+lemma dist_triangle: "dist x z <= dist x y + dist y z" by norm
+
+lemma dist_triangle_alt: "dist y z <= dist x y + dist x z" by norm
+
+lemma dist_eq_0: "dist x y = 0 \<longleftrightarrow> x = y" by norm
+
+lemma dist_pos_lt: "x \<noteq> y ==> 0 < dist x y" by norm 
+lemma dist_nz:  "x \<noteq> y \<longleftrightarrow> 0 < dist x y" by norm 
+
+lemma dist_triangle_le: "dist x z + dist y z <= e \<Longrightarrow> dist x y <= e" by norm 
+
+lemma dist_triangle_lt: "dist x z + dist y z < e ==> dist x y < e" by norm 
+
+lemma dist_triangle_half_l: "dist x1 y < e / 2 \<Longrightarrow> dist x2 y < e / 2 ==> dist x1 x2 < e" by norm 
+
+lemma dist_triangle_half_r: "dist y x1 < e / 2 \<Longrightarrow> dist y x2 < e / 2 ==> dist x1 x2 < e" by norm 
+
+lemma dist_triangle_add: "dist (x + y) (x' + y') <= dist x x' + dist y y'"
+  by norm 
+
+lemma dist_mul: "dist (c *s x) (c *s y) = \<bar>c\<bar> * dist x y" 
+  unfolding dist_def vector_ssub_ldistrib[symmetric] norm_mul .. 
+
+lemma dist_triangle_add_half: " dist x x' < e / 2 \<Longrightarrow> dist y y' < e / 2 ==> dist(x + y) (x' + y') < e" by norm 
+
+lemma dist_le_0: "dist x y <= 0 \<longleftrightarrow> x = y" by norm 
+
+instantiation "^" :: (monoid_add,type) monoid_add
+begin
+  instance by (intro_classes)
+end
+
+lemma setsum_eq: "setsum f S = (\<chi> i. setsum (\<lambda>x. (f x)$i ) S)"
+  apply vector
+  apply auto
+  apply (cases "finite S")
+  apply (rule finite_induct[of S])
+  apply (auto simp add: vector_component zero_index)
+  done
+
+lemma setsum_clauses: 
+  shows "setsum f {} = 0"
+  and "finite S \<Longrightarrow> setsum f (insert x S) =
+                 (if x \<in> S then setsum f S else f x + setsum f S)"
+  by (auto simp add: insert_absorb)
+
+lemma setsum_cmul: 
+  fixes f:: "'c \<Rightarrow> ('a::semiring_1)^'n"
+  shows "setsum (\<lambda>x. c *s f x) S = c *s setsum f S"
+  by (simp add: setsum_eq Cart_eq Cart_lambda_beta vector_component setsum_right_distrib)
+
+lemma setsum_component: 
+  fixes f:: " 'a \<Rightarrow> ('b::semiring_1) ^'n"
+  assumes i: "i \<in> {1 .. dimindex(UNIV:: 'n set)}"
+  shows "(setsum f S)$i = setsum (\<lambda>x. (f x)$i) S"
+  using i by (simp add: setsum_eq Cart_lambda_beta)
+
+  (* This needs finiteness assumption due to the definition of fold!!! *)
+
+lemma setsum_superset:
+  assumes fb: "finite B" and ab: "A \<subseteq> B" 
+  and f0: "\<forall>x \<in> B - A. f x = 0"
+  shows "setsum f B = setsum f A"
+proof-
+  from ab fb have fa: "finite A" by (metis finite_subset)
+  from fb have fba: "finite (B - A)" by (metis finite_Diff)
+  have d: "A \<inter> (B - A) = {}" by blast
+  from ab have b: "B = A \<union> (B - A)" by blast
+  from setsum_Un_disjoint[OF fa fba d, of f] b
+    setsum_0'[OF f0]
+  show "setsum f B = setsum f A" by simp
+qed
+
+lemma setsum_restrict_set:
+  assumes fA: "finite A"
+  shows "setsum f (A \<inter> B) = setsum (\<lambda>x. if x \<in> B then f x else 0) A"
+proof-
+  from fA have fab: "finite (A \<inter> B)" by auto
+  have aba: "A \<inter> B \<subseteq> A" by blast
+  let ?g = "\<lambda>x. if x \<in> A\<inter>B then f x else 0"
+  from setsum_superset[OF fA aba, of ?g]
+  show ?thesis by simp
+qed
+
+lemma setsum_cases:
+  assumes fA: "finite A"
+  shows "setsum (\<lambda>x. if x \<in> B then f x else g x) A =
+         setsum f (A \<inter> B) + setsum g (A \<inter> - B)"
+proof-
+  have a: "A = A \<inter> B \<union> A \<inter> -B" "(A \<inter> B) \<inter> (A \<inter> -B) = {}" 
+    by blast+
+  from fA 
+  have f: "finite (A \<inter> B)" "finite (A \<inter> -B)" by auto
+  let ?g = "\<lambda>x. if x \<in> B then f x else g x"
+  from setsum_Un_disjoint[OF f a(2), of ?g] a(1)
+  show ?thesis by simp
+qed
+
+lemma setsum_norm: 
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  assumes fS: "finite S"
+  shows "norm (setsum f S) <= setsum (\<lambda>x. norm(f x)) S"
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by (simp add: norm_zero)
+next
+  case (2 x S)
+  from "2.hyps" have "norm (setsum f (insert x S)) \<le> norm (f x) + norm (setsum f S)" by (simp add: norm_triangle_ineq)
+  also have "\<dots> \<le> norm (f x) + setsum (\<lambda>x. norm(f x)) S"
+    using "2.hyps" by simp
+  finally  show ?case  using "2.hyps" by simp
+qed
+
+lemma real_setsum_norm: 
+  fixes f :: "'a \<Rightarrow> real ^'n"
+  assumes fS: "finite S"
+  shows "norm (setsum f S) <= setsum (\<lambda>x. norm(f x)) S"
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by simp norm
+next
+  case (2 x S)
+  from "2.hyps" have "norm (setsum f (insert x S)) \<le> norm (f x) + norm (setsum f S)" apply (simp add: norm_triangle_ineq) by norm
+  also have "\<dots> \<le> norm (f x) + setsum (\<lambda>x. norm(f x)) S"
+    using "2.hyps" by simp
+  finally  show ?case  using "2.hyps" by simp
+qed
+
+lemma setsum_norm_le: 
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  assumes fS: "finite S"
+  and fg: "\<forall>x \<in> S. norm (f x) \<le> g x"
+  shows "norm (setsum f S) \<le> setsum g S"
+proof-
+  from fg have "setsum (\<lambda>x. norm(f x)) S <= setsum g S" 
+    by - (rule setsum_mono, simp)
+  then show ?thesis using setsum_norm[OF fS, of f] fg
+    by arith
+qed
+
+lemma real_setsum_norm_le: 
+  fixes f :: "'a \<Rightarrow> real ^ 'n"
+  assumes fS: "finite S"
+  and fg: "\<forall>x \<in> S. norm (f x) \<le> g x"
+  shows "norm (setsum f S) \<le> setsum g S"
+proof-
+  from fg have "setsum (\<lambda>x. norm(f x)) S <= setsum g S" 
+    by - (rule setsum_mono, simp)
+  then show ?thesis using real_setsum_norm[OF fS, of f] fg
+    by arith
+qed
+
+lemma setsum_norm_bound:
+  fixes f :: "'a \<Rightarrow> 'b::real_normed_vector"
+  assumes fS: "finite S"
+  and K: "\<forall>x \<in> S. norm (f x) \<le> K"
+  shows "norm (setsum f S) \<le> of_nat (card S) * K"
+  using setsum_norm_le[OF fS K] setsum_constant[symmetric]
+  by simp
+
+lemma real_setsum_norm_bound:
+  fixes f :: "'a \<Rightarrow> real ^ 'n"
+  assumes fS: "finite S"
+  and K: "\<forall>x \<in> S. norm (f x) \<le> K"
+  shows "norm (setsum f S) \<le> of_nat (card S) * K"
+  using real_setsum_norm_le[OF fS K] setsum_constant[symmetric]
+  by simp
+
+instantiation "^" :: ("{scaleR, one, times}",type) scaleR
+begin
+
+definition vector_scaleR_def: "(scaleR :: real \<Rightarrow> 'a ^'b \<Rightarrow> 'a ^'b) \<equiv> (\<lambda> c x . (scaleR c 1) *s x)"
+instance ..
+end
+
+instantiation "^" :: ("ring_1",type) ring_1
+begin
+instance by intro_classes
+end
+
+instantiation "^" :: (real_algebra_1,type) real_vector
+begin
+
+instance
+  apply intro_classes
+  apply (simp_all  add: vector_scaleR_def)
+  apply (simp_all add: vector_sadd_rdistrib vector_add_ldistrib vector_smult_lid vector_smult_assoc scaleR_left_distrib mult_commute)
+  done
+end
+
+instantiation "^" :: (real_algebra_1,type) real_algebra
+begin
+
+instance
+  apply intro_classes
+  apply (simp_all add: vector_scaleR_def ring_simps)
+  apply vector
+  apply vector
+  done
+end
+
+instantiation "^" :: (real_algebra_1,type) real_algebra_1
+begin
+
+instance ..
+end
+
+lemma setsum_vmul:
+  fixes f :: "'a \<Rightarrow> 'b::{real_normed_vector,semiring, mult_zero}"
+  assumes fS: "finite S"
+  shows "setsum f S *s v = setsum (\<lambda>x. f x *s v) S"
+proof(induct rule: finite_induct[OF fS])
+  case 1 then show ?case by (simp add: vector_smult_lzero)
+next
+  case (2 x F)
+  from "2.hyps" have "setsum f (insert x F) *s v = (f x + setsum f F) *s v" 
+    by simp
+  also have "\<dots> = f x *s v + setsum f F *s v" 
+    by (simp add: vector_sadd_rdistrib)
+  also have "\<dots> = setsum (\<lambda>x. f x *s v) (insert x F)" using "2.hyps" by simp
+  finally show ?case .
+qed
+
+(* FIXME : Problem thm setsum_vmul[of _ "f:: 'a \<Rightarrow> real ^'n"]  ---
+ Get rid of *s and use real_vector instead! Also prove that ^ creates a real_vector !! *)
+
+lemma setsum_add_split: assumes mn: "(m::nat) \<le> n + 1"
+  shows "setsum f {m..n + p} = setsum f {m..n} + setsum f {n + 1..n + p}"
+proof-
+  let ?A = "{m .. n}"
+  let ?B = "{n + 1 .. n + p}"
+  have eq: "{m .. n+p} = ?A \<union> ?B" using mn by auto 
+  have d: "?A \<inter> ?B = {}" by auto
+  from setsum_Un_disjoint[of "?A" "?B" f] eq d show ?thesis by auto
+qed
+
+lemma setsum_reindex_nonzero: 
+  assumes fS: "finite S"
+  and nz: "\<And> x y. x \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> x \<noteq> y \<Longrightarrow> f x = f y \<Longrightarrow> h (f x) = 0"
+  shows "setsum h (f ` S) = setsum (h o f) S"
+using nz
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by simp
+next
+  case (2 x F) 
+  {assume fxF: "f x \<in> f ` F" hence "\<exists>y \<in> F . f y = f x" by auto
+    then obtain y where y: "y \<in> F" "f x = f y" by auto 
+    from "2.hyps" y have xy: "x \<noteq> y" by auto
+    
+    from "2.prems"[of x y] "2.hyps" xy y have h0: "h (f x) = 0" by simp
+    have "setsum h (f ` insert x F) = setsum h (f ` F)" using fxF by auto
+    also have "\<dots> = setsum (h o f) (insert x F)" 
+      using "2.hyps" "2.prems" h0  by auto 
+    finally have ?case .}
+  moreover
+  {assume fxF: "f x \<notin> f ` F"
+    have "setsum h (f ` insert x F) = h (f x) + setsum h (f ` F)" 
+      using fxF "2.hyps" by simp 
+    also have "\<dots> = setsum (h o f) (insert x F)"  
+      using "2.hyps" "2.prems" fxF
+      apply auto apply metis done
+    finally have ?case .}
+  ultimately show ?case by blast
+qed
+
+lemma setsum_Un_nonzero:
+  assumes fS: "finite S" and fF: "finite F"
+  and f: "\<forall> x\<in> S \<inter> F . f x = (0::'a::ab_group_add)"
+  shows "setsum f (S \<union> F) = setsum f S + setsum f F"
+  using setsum_Un[OF fS fF, of f] setsum_0'[OF f] by simp
+
+lemma setsum_natinterval_left:
+  assumes mn: "(m::nat) <= n" 
+  shows "setsum f {m..n} = f m + setsum f {m + 1..n}"
+proof-
+  from mn have "{m .. n} = insert m {m+1 .. n}" by auto
+  then show ?thesis by auto
+qed
+
+lemma setsum_natinterval_difff: 
+  fixes f:: "nat \<Rightarrow> ('a::ab_group_add)"
+  shows  "setsum (\<lambda>k. f k - f(k + 1)) {(m::nat) .. n} =
+          (if m <= n then f m - f(n + 1) else 0)"
+by (induct n, auto simp add: ring_simps not_le le_Suc_eq)
+
+lemmas setsum_restrict_set' = setsum_restrict_set[unfolded Int_def]
+
+lemma setsum_setsum_restrict:
+  "finite S \<Longrightarrow> finite T \<Longrightarrow> setsum (\<lambda>x. setsum (\<lambda>y. f x y) {y. y\<in> T \<and> R x y}) S = setsum (\<lambda>y. setsum (\<lambda>x. f x y) {x. x \<in> S \<and> R x y}) T"
+  apply (simp add: setsum_restrict_set'[unfolded mem_def] mem_def)
+  by (rule setsum_commute)
+
+lemma setsum_image_gen: assumes fS: "finite S"
+  shows "setsum g S = setsum (\<lambda>y. setsum g {x. x \<in> S \<and> f x = y}) (f ` S)"
+proof-
+  {fix x assume "x \<in> S" then have "{y. y\<in> f`S \<and> f x = y} = {f x}" by auto}
+  note th0 = this
+  have "setsum g S = setsum (\<lambda>x. setsum (\<lambda>y. g x) {y. y\<in> f`S \<and> f x = y}) S" 
+    apply (rule setsum_cong2) 
+    by (simp add: th0)
+  also have "\<dots> = setsum (\<lambda>y. setsum g {x. x \<in> S \<and> f x = y}) (f ` S)"
+    apply (rule setsum_setsum_restrict[OF fS])
+    by (rule finite_imageI[OF fS])
+  finally show ?thesis .
+qed
+
+    (* FIXME: Here too need stupid finiteness assumption on T!!! *)
+lemma setsum_group:
+  assumes fS: "finite S" and fT: "finite T" and fST: "f ` S \<subseteq> T"
+  shows "setsum (\<lambda>y. setsum g {x. x\<in> S \<and> f x = y}) T = setsum g S"
+  
+apply (subst setsum_image_gen[OF fS, of g f])
+apply (rule setsum_superset[OF fT fST])
+by (auto intro: setsum_0')
+
+(* FIXME: Change the name to fold_image\<dots> *)
+lemma (in comm_monoid_mult) fold_1': "finite S \<Longrightarrow> (\<forall>x\<in>S. f x = 1) \<Longrightarrow> fold_image op * f 1 S = 1"
+  apply (induct set: finite)
+  apply simp by (auto simp add: fold_image_insert)
+
+lemma (in comm_monoid_mult) fold_union_nonzero:
+  assumes fS: "finite S" and fT: "finite T"
+  and I0: "\<forall>x \<in> S\<inter>T. f x = 1"
+  shows "fold_image (op *) f 1 (S \<union> T) = fold_image (op *) f 1 S * fold_image (op *) f 1 T"
+proof-
+  have "fold_image op * f 1 (S \<inter> T) = 1" 
+    apply (rule fold_1')
+    using fS fT I0 by auto 
+  with fold_image_Un_Int[OF fS fT] show ?thesis by simp
+qed
+
+lemma setsum_union_nonzero:  
+  assumes fS: "finite S" and fT: "finite T"
+  and I0: "\<forall>x \<in> S\<inter>T. f x = 0"
+  shows "setsum f (S \<union> T) = setsum f S  + setsum f T"
+  using fS fT
+  apply (simp add: setsum_def)
+  apply (rule comm_monoid_add.fold_union_nonzero)
+  using I0 by auto
+
+lemma setprod_union_nonzero:  
+  assumes fS: "finite S" and fT: "finite T"
+  and I0: "\<forall>x \<in> S\<inter>T. f x = 1"
+  shows "setprod f (S \<union> T) = setprod f S  * setprod f T"
+  using fS fT
+  apply (simp add: setprod_def)
+  apply (rule fold_union_nonzero)
+  using I0 by auto
+
+lemma setsum_unions_nonzero: 
+  assumes fS: "finite S" and fSS: "\<forall>T \<in> S. finite T"
+  and f0: "\<And>T1 T2 x. T1\<in>S \<Longrightarrow> T2\<in>S \<Longrightarrow> T1 \<noteq> T2 \<Longrightarrow> x \<in> T1 \<Longrightarrow> x \<in> T2 \<Longrightarrow> f x = 0"
+  shows "setsum f (\<Union>S) = setsum (\<lambda>T. setsum f T) S"
+  using fSS f0
+proof(induct rule: finite_induct[OF fS])
+  case 1 thus ?case by simp
+next
+  case (2 T F)
+  then have fTF: "finite T" "\<forall>T\<in>F. finite T" "finite F" and TF: "T \<notin> F" 
+    and H: "setsum f (\<Union> F) = setsum (setsum f) F" by (auto simp add: finite_insert)
+  from fTF have fUF: "finite (\<Union>F)" by (auto intro: finite_Union)
+  from "2.prems" TF fTF
+  show ?case 
+    by (auto simp add: H[symmetric] intro: setsum_union_nonzero[OF fTF(1) fUF, of f])
+qed
+
+  (* FIXME : Copied from Pocklington --- should be moved to Finite_Set!!!!!!!! *)
+
+
+lemma (in comm_monoid_mult) fold_related: 
+  assumes Re: "R e e" 
+  and Rop: "\<forall>x1 y1 x2 y2. R x1 x2 \<and> R y1 y2 \<longrightarrow> R (x1 * y1) (x2 * y2)" 
+  and fS: "finite S" and Rfg: "\<forall>x\<in>S. R (h x) (g x)"
+  shows "R (fold_image (op *) h e S) (fold_image (op *) g e S)"
+  using fS by (rule finite_subset_induct) (insert assms, auto)
+
+  (* FIXME: I think we can get rid of the finite assumption!! *)	
+lemma (in comm_monoid_mult) 
+  fold_eq_general:
+  assumes fS: "finite S"
+  and h: "\<forall>y\<in>S'. \<exists>!x. x\<in> S \<and> h(x) = y" 
+  and f12:  "\<forall>x\<in>S. h x \<in> S' \<and> f2(h x) = f1 x"
+  shows "fold_image (op *) f1 e S = fold_image (op *) f2 e S'"
+proof-
+  from h f12 have hS: "h ` S = S'" by auto
+  {fix x y assume H: "x \<in> S" "y \<in> S" "h x = h y"
+    from f12 h H  have "x = y" by auto }
+  hence hinj: "inj_on h S" unfolding inj_on_def Ex1_def by blast
+  from f12 have th: "\<And>x. x \<in> S \<Longrightarrow> (f2 \<circ> h) x = f1 x" by auto 
+  from hS have "fold_image (op *) f2 e S' = fold_image (op *) f2 e (h ` S)" by simp
+  also have "\<dots> = fold_image (op *) (f2 o h) e S" 
+    using fold_image_reindex[OF fS hinj, of f2 e] .
+  also have "\<dots> = fold_image (op *) f1 e S " using th fold_image_cong[OF fS, of "f2 o h" f1 e]
+    by blast
+  finally show ?thesis ..
+qed
+
+lemma (in comm_monoid_mult) fold_eq_general_inverses:
+  assumes fS: "finite S" 
+  and kh: "\<And>y. y \<in> T \<Longrightarrow> k y \<in> S \<and> h (k y) = y"
+  and hk: "\<And>x. x \<in> S \<Longrightarrow> h x \<in> T \<and> k (h x) = x  \<and> g (h x) = f x"
+  shows "fold_image (op *) f e S = fold_image (op *) g e T"
+  using fold_eq_general[OF fS, of T h g f e] kh hk by metis
+
+lemma setsum_eq_general_reverses:
+  assumes fS: "finite S" and fT: "finite T"
+  and kh: "\<And>y. y \<in> T \<Longrightarrow> k y \<in> S \<and> h (k y) = y"
+  and hk: "\<And>x. x \<in> S \<Longrightarrow> h x \<in> T \<and> k (h x) = x  \<and> g (h x) = f x"
+  shows "setsum f S = setsum g T"
+  apply (simp add: setsum_def fS fT)
+  apply (rule comm_monoid_add.fold_eq_general_inverses[OF fS])
+  apply (erule kh)
+  apply (erule hk)
+  done
+
+lemma vsum_norm_allsubsets_bound:
+  fixes f:: "'a \<Rightarrow> real ^'n"
+  assumes fP: "finite P" and fPs: "\<And>Q. Q \<subseteq> P \<Longrightarrow> norm (setsum f Q) \<le> e" 
+  shows "setsum (\<lambda>x. norm (f x)) P \<le> 2 * real (dimindex(UNIV :: 'n set)) *  e"
+proof-
+  let ?d = "real (dimindex (UNIV ::'n set))"
+  let ?nf = "\<lambda>x. norm (f x)"
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  have th0: "setsum (\<lambda>x. setsum (\<lambda>i. \<bar>f x $ i\<bar>) ?U) P = setsum (\<lambda>i. setsum (\<lambda>x. \<bar>f x $ i\<bar>) P) ?U"
+    by (rule setsum_commute)
+  have th1: "2 * ?d * e = of_nat (card ?U) * (2 * e)" by (simp add: real_of_nat_def)
+  have "setsum ?nf P \<le> setsum (\<lambda>x. setsum (\<lambda>i. \<bar>f x $ i\<bar>) ?U) P"
+    apply (rule setsum_mono)
+    by (rule norm_le_l1)
+  also have "\<dots> \<le> 2 * ?d * e"
+    unfolding th0 th1
+  proof(rule setsum_bounded)
+    fix i assume i: "i \<in> ?U"
+    let ?Pp = "{x. x\<in> P \<and> f x $ i \<ge> 0}"
+    let ?Pn = "{x. x \<in> P \<and> f x $ i < 0}"
+    have thp: "P = ?Pp \<union> ?Pn" by auto
+    have thp0: "?Pp \<inter> ?Pn ={}" by auto
+    have PpP: "?Pp \<subseteq> P" and PnP: "?Pn \<subseteq> P" by blast+
+    have Ppe:"setsum (\<lambda>x. \<bar>f x $ i\<bar>) ?Pp \<le> e"
+      using i component_le_norm[OF i, of "setsum (\<lambda>x. f x) ?Pp"]  fPs[OF PpP]
+      by (auto simp add: setsum_component intro: abs_le_D1)
+    have Pne: "setsum (\<lambda>x. \<bar>f x $ i\<bar>) ?Pn \<le> e"
+      using i component_le_norm[OF i, of "setsum (\<lambda>x. - f x) ?Pn"]  fPs[OF PnP]
+      by (auto simp add: setsum_negf norm_neg setsum_component vector_component intro: abs_le_D1)
+    have "setsum (\<lambda>x. \<bar>f x $ i\<bar>) P = setsum (\<lambda>x. \<bar>f x $ i\<bar>) ?Pp + setsum (\<lambda>x. \<bar>f x $ i\<bar>) ?Pn" 
+      apply (subst thp)
+      apply (rule setsum_Un_nonzero) 
+      using fP thp0 by auto
+    also have "\<dots> \<le> 2*e" using Pne Ppe by arith
+    finally show "setsum (\<lambda>x. \<bar>f x $ i\<bar>) P \<le> 2*e" .
+  qed
+  finally show ?thesis .
+qed
+
+lemma dot_lsum: "finite S \<Longrightarrow> setsum f S \<bullet> (y::'a::{comm_ring}^'n) = setsum (\<lambda>x. f x \<bullet> y) S "
+  by (induct rule: finite_induct, auto simp add: dot_lzero dot_ladd)
+
+lemma dot_rsum: "finite S \<Longrightarrow> (y::'a::{comm_ring}^'n) \<bullet> setsum f S = setsum (\<lambda>x. y \<bullet> f x) S "
+  by (induct rule: finite_induct, auto simp add: dot_rzero dot_radd)
+
+subsection{* Basis vectors in coordinate directions. *}
+
+
+definition "basis k = (\<chi> i. if i = k then 1 else 0)"
+
+lemma delta_mult_idempotent: 
+  "(if k=a then 1 else (0::'a::semiring_1)) * (if k=a then 1 else 0) = (if k=a then 1 else 0)" by (cases "k=a", auto)
+
+lemma norm_basis:
+  assumes k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "norm (basis k :: real ^'n) = 1"
+  using k 
+  apply (simp add: basis_def real_vector_norm_def dot_def)
+  apply (vector delta_mult_idempotent)
+  using setsum_delta[of "{1 .. dimindex (UNIV :: 'n set)}" "k" "\<lambda>k. 1::real"]
+  apply auto
+  done
+
+lemma norm_basis_1: "norm(basis 1 :: real ^'n) = 1"
+  apply (simp add: basis_def real_vector_norm_def dot_def)
+  apply (vector delta_mult_idempotent)
+  using setsum_delta[of "{1 .. dimindex (UNIV :: 'n set)}" "1" "\<lambda>k. 1::real"] dimindex_nonzero[of "UNIV :: 'n set"]
+  apply auto
+  done
+
+lemma vector_choose_size: "0 <= c ==> \<exists>(x::real^'n). norm x = c"
+  apply (rule exI[where x="c *s basis 1"])
+  by (simp only: norm_mul norm_basis_1)
+
+lemma vector_choose_dist: assumes e: "0 <= e" 
+  shows "\<exists>(y::real^'n). dist x y = e"
+proof-
+  from vector_choose_size[OF e] obtain c:: "real ^'n"  where "norm c = e"
+    by blast
+  then have "dist x (x - c) = e" by (simp add: dist_def)
+  then show ?thesis by blast
+qed
+
+lemma basis_inj: "inj_on (basis :: nat \<Rightarrow> real ^'n) {1 .. dimindex (UNIV :: 'n set)}"
+  by (auto simp add: inj_on_def basis_def Cart_eq Cart_lambda_beta)
+
+lemma basis_component: "i \<in> {1 .. dimindex(UNIV:: 'n set)} ==> (basis k ::('a::semiring_1)^'n)$i = (if k=i then 1 else 0)"
+  by (simp add: basis_def Cart_lambda_beta)
+
+lemma cond_value_iff: "f (if b then x else y) = (if b then f x else f y)"
+  by auto
+
+lemma basis_expansion:
+  "setsum (\<lambda>i. (x$i) *s basis i) {1 .. dimindex (UNIV :: 'n set)} = (x::('a::ring_1) ^'n)" (is "?lhs = ?rhs" is "setsum ?f ?S = _")
+  by (auto simp add: Cart_eq basis_component[where ?'n = "'n"] setsum_component vector_component cond_value_iff setsum_delta[of "?S", where ?'b = "'a", simplified] cong del: if_weak_cong)
+
+lemma basis_expansion_unique: 
+  "setsum (\<lambda>i. f i *s basis i) {1 .. dimindex (UNIV :: 'n set)} = (x::('a::comm_ring_1) ^'n) \<longleftrightarrow> (\<forall>i\<in>{1 .. dimindex(UNIV:: 'n set)}. f i = x$i)"
+  by (simp add: Cart_eq setsum_component vector_component basis_component setsum_delta cond_value_iff cong del: if_weak_cong)
+
+lemma cond_application_beta: "(if b then f else g) x = (if b then f x else g x)"
+  by auto
+
+lemma dot_basis:
+  assumes i: "i \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "basis i \<bullet> x = x$i" "x \<bullet> (basis i :: 'a^'n) = (x$i :: 'a::semiring_1)"
+  using i
+  by (auto simp add: dot_def basis_def Cart_lambda_beta cond_application_beta  cond_value_iff setsum_delta cong del: if_weak_cong)
+
+lemma basis_eq_0: "basis i = (0::'a::semiring_1^'n) \<longleftrightarrow> i \<notin> {1..dimindex(UNIV ::'n set)}"
+  by (auto simp add: Cart_eq basis_component zero_index)
+
+lemma basis_nonzero: 
+  assumes k: "k \<in> {1 .. dimindex(UNIV ::'n set)}"
+  shows "basis k \<noteq> (0:: 'a::semiring_1 ^'n)"
+  using k by (simp add: basis_eq_0)
+
+lemma vector_eq_ldot: "(\<forall>x. x \<bullet> y = x \<bullet> z) \<longleftrightarrow> y = (z::'a::semiring_1^'n)"
+  apply (auto simp add: Cart_eq dot_basis)
+  apply (erule_tac x="basis i" in allE)
+  apply (simp add: dot_basis)
+  apply (subgoal_tac "y = z")
+  apply simp
+  apply vector
+  done
+
+lemma vector_eq_rdot: "(\<forall>z. x \<bullet> z = y \<bullet> z) \<longleftrightarrow> x = (y::'a::semiring_1^'n)"
+  apply (auto simp add: Cart_eq dot_basis)
+  apply (erule_tac x="basis i" in allE)
+  apply (simp add: dot_basis)
+  apply (subgoal_tac "x = y")
+  apply simp
+  apply vector
+  done
+
+subsection{* Orthogonality. *}
+
+definition "orthogonal x y \<longleftrightarrow> (x \<bullet> y = 0)"
+
+lemma orthogonal_basis:
+  assumes i:"i \<in> {1 .. dimindex(UNIV ::'n set)}" 
+  shows "orthogonal (basis i :: 'a^'n) x \<longleftrightarrow> x$i = (0::'a::ring_1)"
+  using i
+  by (auto simp add: orthogonal_def dot_def basis_def Cart_lambda_beta cond_value_iff cond_application_beta setsum_delta cong del: if_weak_cong)
+
+lemma orthogonal_basis_basis:
+  assumes i:"i \<in> {1 .. dimindex(UNIV ::'n set)}" 
+  and j: "j \<in> {1 .. dimindex(UNIV ::'n set)}" 
+  shows "orthogonal (basis i :: 'a::ring_1^'n) (basis j) \<longleftrightarrow> i \<noteq> j" 
+  unfolding orthogonal_basis[OF i] basis_component[OF i] by simp
+
+  (* FIXME : Maybe some of these require less than comm_ring, but not all*)
+lemma orthogonal_clauses:
+  "orthogonal a (0::'a::comm_ring ^'n)"
+  "orthogonal a x ==> orthogonal a (c *s x)"
+  "orthogonal a x ==> orthogonal a (-x)"
+  "orthogonal a x \<Longrightarrow> orthogonal a y ==> orthogonal a (x + y)"
+  "orthogonal a x \<Longrightarrow> orthogonal a y ==> orthogonal a (x - y)"
+  "orthogonal 0 a"
+  "orthogonal x a ==> orthogonal (c *s x) a"
+  "orthogonal x a ==> orthogonal (-x) a"
+  "orthogonal x a \<Longrightarrow> orthogonal y a ==> orthogonal (x + y) a"
+  "orthogonal x a \<Longrightarrow> orthogonal y a ==> orthogonal (x - y) a"
+  unfolding orthogonal_def dot_rneg dot_rmult dot_radd dot_rsub
+  dot_lzero dot_rzero dot_lneg dot_lmult dot_ladd dot_lsub
+  by simp_all
+
+lemma orthogonal_commute: "orthogonal (x::'a::{ab_semigroup_mult,comm_monoid_add} ^'n)y \<longleftrightarrow> orthogonal y x"
+  by (simp add: orthogonal_def dot_sym)
+
+subsection{* Explicit vector construction from lists. *}
+
+lemma Cart_lambda_beta_1[simp]: "(Cart_lambda g)$1 = g 1"
+  apply (rule Cart_lambda_beta[rule_format])
+  using dimindex_ge_1 apply auto done
+
+lemma Cart_lambda_beta_1'[simp]: "(Cart_lambda g)$(Suc 0) = g 1"
+  by (simp only: One_nat_def[symmetric] Cart_lambda_beta_1)
+
+definition "vector l = (\<chi> i. if i <= length l then l ! (i - 1) else 0)"
+
+lemma vector_1: "(vector[x]) $1 = x"
+  using dimindex_ge_1
+  by (auto simp add: vector_def Cart_lambda_beta[rule_format])
+lemma dimindex_2[simp]: "2 \<in> {1 .. dimindex (UNIV :: 2 set)}"
+  by (auto simp add: dimindex_def)
+lemma dimindex_2'[simp]: "2 \<in> {Suc 0 .. dimindex (UNIV :: 2 set)}"
+  by (auto simp add: dimindex_def)
+lemma dimindex_3[simp]: "2 \<in> {1 .. dimindex (UNIV :: 3 set)}" "3 \<in> {1 .. dimindex (UNIV :: 3 set)}"
+  by (auto simp add: dimindex_def)
+
+lemma dimindex_3'[simp]: "2 \<in> {Suc 0 .. dimindex (UNIV :: 3 set)}" "3 \<in> {Suc 0 .. dimindex (UNIV :: 3 set)}"
+  by (auto simp add: dimindex_def)
+
+lemma vector_2:
+ "(vector[x,y]) $1 = x"
+ "(vector[x,y] :: 'a^2)$2 = (y::'a::zero)"
+  apply (simp add: vector_def)
+  using Cart_lambda_beta[rule_format, OF dimindex_2, of "\<lambda>i. if i \<le> length [x,y] then [x,y] ! (i - 1) else (0::'a)"]
+  apply (simp only: vector_def )
+  apply auto
+  done
+
+lemma vector_3:
+ "(vector [x,y,z] ::('a::zero)^3)$1 = x"
+ "(vector [x,y,z] ::('a::zero)^3)$2 = y"
+ "(vector [x,y,z] ::('a::zero)^3)$3 = z"
+apply (simp_all add: vector_def Cart_lambda_beta dimindex_3)
+  using Cart_lambda_beta[rule_format, OF dimindex_3(1), of "\<lambda>i. if i \<le> length [x,y,z] then [x,y,z] ! (i - 1) else (0::'a)"]   using Cart_lambda_beta[rule_format, OF dimindex_3(2), of "\<lambda>i. if i \<le> length [x,y,z] then [x,y,z] ! (i - 1) else (0::'a)"]
+  by simp_all
+
+lemma forall_vector_1: "(\<forall>v::'a::zero^1. P v) \<longleftrightarrow> (\<forall>x. P(vector[x]))"
+  apply auto
+  apply (erule_tac x="v$1" in allE)
+  apply (subgoal_tac "vector [v$1] = v")
+  apply simp
+  by (vector vector_def dimindex_def)
+
+lemma forall_vector_2: "(\<forall>v::'a::zero^2. P v) \<longleftrightarrow> (\<forall>x y. P(vector[x, y]))"
+  apply auto
+  apply (erule_tac x="v$1" in allE)
+  apply (erule_tac x="v$2" in allE)
+  apply (subgoal_tac "vector [v$1, v$2] = v")
+  apply simp
+  apply (vector vector_def dimindex_def)
+  apply auto
+  apply (subgoal_tac "i = 1 \<or> i =2", auto)
+  done
+
+lemma forall_vector_3: "(\<forall>v::'a::zero^3. P v) \<longleftrightarrow> (\<forall>x y z. P(vector[x, y, z]))"
+  apply auto
+  apply (erule_tac x="v$1" in allE)
+  apply (erule_tac x="v$2" in allE)
+  apply (erule_tac x="v$3" in allE)
+  apply (subgoal_tac "vector [v$1, v$2, v$3] = v")
+  apply simp
+  apply (vector vector_def dimindex_def)
+  apply auto
+  apply (subgoal_tac "i = 1 \<or> i =2 \<or> i = 3", auto)
+  done
+
+subsection{* Linear functions. *}
+
+definition "linear f \<longleftrightarrow> (\<forall>x y. f(x + y) = f x + f y) \<and> (\<forall>c x. f(c *s x) = c *s f x)"
+
+lemma linear_compose_cmul: "linear f ==> linear (\<lambda>x. (c::'a::comm_semiring) *s f x)"
+  by (vector linear_def Cart_eq Cart_lambda_beta[rule_format] ring_simps)
+
+lemma linear_compose_neg: "linear (f :: 'a ^'n \<Rightarrow> 'a::comm_ring ^'m) ==> linear (\<lambda>x. -(f(x)))" by (vector linear_def Cart_eq)
+
+lemma linear_compose_add: "linear (f :: 'a ^'n \<Rightarrow> 'a::semiring_1 ^'m) \<Longrightarrow> linear g ==> linear (\<lambda>x. f(x) + g(x))"
+  by (vector linear_def Cart_eq ring_simps)
+
+lemma linear_compose_sub: "linear (f :: 'a ^'n \<Rightarrow> 'a::ring_1 ^'m) \<Longrightarrow> linear g ==> linear (\<lambda>x. f x - g x)"
+  by (vector linear_def Cart_eq ring_simps)
+
+lemma linear_compose: "linear f \<Longrightarrow> linear g ==> linear (g o f)"
+  by (simp add: linear_def)
+
+lemma linear_id: "linear id" by (simp add: linear_def id_def)
+
+lemma linear_zero: "linear (\<lambda>x. 0::'a::semiring_1 ^ 'n)" by (simp add: linear_def)
+
+lemma linear_compose_setsum:
+  assumes fS: "finite S" and lS: "\<forall>a \<in> S. linear (f a :: 'a::semiring_1 ^ 'n \<Rightarrow> 'a ^ 'm)"
+  shows "linear(\<lambda>x. setsum (\<lambda>a. f a x :: 'a::semiring_1 ^'m) S)"
+  using lS
+  apply (induct rule: finite_induct[OF fS])
+  by (auto simp add: linear_zero intro: linear_compose_add)
+
+lemma linear_vmul_component:
+  fixes f:: "'a::semiring_1^'m \<Rightarrow> 'a^'n"
+  assumes lf: "linear f" and k: "k \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "linear (\<lambda>x. f x $ k *s v)"
+  using lf k
+  apply (auto simp add: linear_def )
+  by (vector ring_simps)+
+
+lemma linear_0: "linear f ==> f 0 = (0::'a::semiring_1 ^'n)"
+  unfolding linear_def
+  apply clarsimp
+  apply (erule allE[where x="0::'a"])
+  apply simp
+  done
+
+lemma linear_cmul: "linear f ==> f(c*s x) = c *s f x" by (simp add: linear_def)
+
+lemma linear_neg: "linear (f :: 'a::ring_1 ^'n \<Rightarrow> _) ==> f (-x) = - f x"
+  unfolding vector_sneg_minus1
+  using linear_cmul[of f] by auto 
+
+lemma linear_add: "linear f ==> f(x + y) = f x + f y" by (metis linear_def) 
+
+lemma linear_sub: "linear (f::'a::ring_1 ^'n \<Rightarrow> _) ==> f(x - y) = f x - f y"
+  by (simp add: diff_def linear_add linear_neg)
+
+lemma linear_setsum: 
+  fixes f:: "'a::semiring_1^'n \<Rightarrow> _"
+  assumes lf: "linear f" and fS: "finite S"
+  shows "f (setsum g S) = setsum (f o g) S"
+proof (induct rule: finite_induct[OF fS])
+  case 1 thus ?case by (simp add: linear_0[OF lf])
+next
+  case (2 x F)
+  have "f (setsum g (insert x F)) = f (g x + setsum g F)" using "2.hyps"
+    by simp
+  also have "\<dots> = f (g x) + f (setsum g F)" using linear_add[OF lf] by simp
+  also have "\<dots> = setsum (f o g) (insert x F)" using "2.hyps" by simp
+  finally show ?case .
+qed
+
+lemma linear_setsum_mul:
+  fixes f:: "'a ^'n \<Rightarrow> 'a::semiring_1^'m"
+  assumes lf: "linear f" and fS: "finite S"
+  shows "f (setsum (\<lambda>i. c i *s v i) S) = setsum (\<lambda>i. c i *s f (v i)) S"
+  using linear_setsum[OF lf fS, of "\<lambda>i. c i *s v i" , unfolded o_def]
+  linear_cmul[OF lf] by simp 
+
+lemma linear_injective_0:
+  assumes lf: "linear (f:: 'a::ring_1 ^ 'n \<Rightarrow> _)"
+  shows "inj f \<longleftrightarrow> (\<forall>x. f x = 0 \<longrightarrow> x = 0)"
+proof-
+  have "inj f \<longleftrightarrow> (\<forall> x y. f x = f y \<longrightarrow> x = y)" by (simp add: inj_on_def)
+  also have "\<dots> \<longleftrightarrow> (\<forall> x y. f x - f y = 0 \<longrightarrow> x - y = 0)" by simp
+  also have "\<dots> \<longleftrightarrow> (\<forall> x y. f (x - y) = 0 \<longrightarrow> x - y = 0)" 
+    by (simp add: linear_sub[OF lf])
+  also have "\<dots> \<longleftrightarrow> (\<forall> x. f x = 0 \<longrightarrow> x = 0)" by auto
+  finally show ?thesis .
+qed
+
+lemma linear_bounded:
+  fixes f:: "real ^'m \<Rightarrow> real ^'n"
+  assumes lf: "linear f"
+  shows "\<exists>B. \<forall>x. norm (f x) \<le> B * norm x"
+proof-
+  let ?S = "{1..dimindex(UNIV:: 'm set)}"
+  let ?B = "setsum (\<lambda>i. norm(f(basis i))) ?S"
+  have fS: "finite ?S" by simp
+  {fix x:: "real ^ 'm"
+    let ?g = "(\<lambda>i::nat. (x$i) *s (basis i) :: real ^ 'm)"
+    have "norm (f x) = norm (f (setsum (\<lambda>i. (x$i) *s (basis i)) ?S))"
+      by (simp only:  basis_expansion)
+    also have "\<dots> = norm (setsum (\<lambda>i. (x$i) *s f (basis i))?S)"
+      using linear_setsum[OF lf fS, of ?g, unfolded o_def] linear_cmul[OF lf]
+      by auto
+    finally have th0: "norm (f x) = norm (setsum (\<lambda>i. (x$i) *s f (basis i))?S)" .
+    {fix i assume i: "i \<in> ?S"
+      from component_le_norm[OF i, of x]
+      have "norm ((x$i) *s f (basis i :: real ^'m)) \<le> norm (f (basis i)) * norm x"
+      unfolding norm_mul
+      apply (simp only: mult_commute)
+      apply (rule mult_mono)
+      by (auto simp add: ring_simps norm_pos_le) }
+    then have th: "\<forall>i\<in> ?S. norm ((x$i) *s f (basis i :: real ^'m)) \<le> norm (f (basis i)) * norm x" by metis
+    from real_setsum_norm_le[OF fS, of "\<lambda>i. (x$i) *s (f (basis i))", OF th]
+    have "norm (f x) \<le> ?B * norm x" unfolding th0 setsum_left_distrib by metis}
+  then show ?thesis by blast
+qed
+
+lemma linear_bounded_pos:
+  fixes f:: "real ^'n \<Rightarrow> real ^ 'm"
+  assumes lf: "linear f"
+  shows "\<exists>B > 0. \<forall>x. norm (f x) \<le> B * norm x"
+proof-
+  from linear_bounded[OF lf] obtain B where 
+    B: "\<forall>x. norm (f x) \<le> B * norm x" by blast
+  let ?K = "\<bar>B\<bar> + 1"
+  have Kp: "?K > 0" by arith
+    {assume C: "B < 0"
+      have "norm (1::real ^ 'n) > 0" by (simp add: norm_pos_lt)
+      with C have "B * norm (1:: real ^ 'n) < 0"
+	by (simp add: zero_compare_simps)
+      with B[rule_format, of 1] norm_pos_le[of "f 1"] have False by simp
+    }
+    then have Bp: "B \<ge> 0" by ferrack
+    {fix x::"real ^ 'n"
+      have "norm (f x) \<le> ?K *  norm x"
+      using B[rule_format, of x] norm_pos_le[of x] norm_pos_le[of "f x"] Bp
+      by (auto simp add: ring_simps split add: abs_split)
+  }
+  then show ?thesis using Kp by blast
+qed
+
+subsection{* Bilinear functions. *}
+
+definition "bilinear f \<longleftrightarrow> (\<forall>x. linear(\<lambda>y. f x y)) \<and> (\<forall>y. linear(\<lambda>x. f x y))"
+
+lemma bilinear_ladd: "bilinear h ==> h (x + y) z = (h x z) + (h y z)"
+  by (simp add: bilinear_def linear_def)
+lemma bilinear_radd: "bilinear h ==> h x (y + z) = (h x y) + (h x z)"
+  by (simp add: bilinear_def linear_def)
+
+lemma bilinear_lmul: "bilinear h ==> h (c *s x) y = c *s (h x y)"
+  by (simp add: bilinear_def linear_def)
+
+lemma bilinear_rmul: "bilinear h ==> h x (c *s y) = c *s (h x y)"
+  by (simp add: bilinear_def linear_def)
+
+lemma bilinear_lneg: "bilinear h ==> h (- (x:: 'a::ring_1 ^ 'n)) y = -(h x y)"
+  by (simp only: vector_sneg_minus1 bilinear_lmul)
+
+lemma bilinear_rneg: "bilinear h ==> h x (- (y:: 'a::ring_1 ^ 'n)) = - h x y"
+  by (simp only: vector_sneg_minus1 bilinear_rmul)
+
+lemma  (in ab_group_add) eq_add_iff: "x = x + y \<longleftrightarrow> y = 0"
+  using add_imp_eq[of x y 0] by auto
+    
+lemma bilinear_lzero: 
+  fixes h :: "'a::ring^'n \<Rightarrow> _" assumes bh: "bilinear h" shows "h 0 x = 0"
+  using bilinear_ladd[OF bh, of 0 0 x] 
+    by (simp add: eq_add_iff ring_simps)
+
+lemma bilinear_rzero: 
+  fixes h :: "'a::ring^'n \<Rightarrow> _" assumes bh: "bilinear h" shows "h x 0 = 0"
+  using bilinear_radd[OF bh, of x 0 0 ] 
+    by (simp add: eq_add_iff ring_simps)
+
+lemma bilinear_lsub: "bilinear h ==> h (x - (y:: 'a::ring_1 ^ 'n)) z = h x z - h y z"
+  by (simp  add: diff_def bilinear_ladd bilinear_lneg)
+
+lemma bilinear_rsub: "bilinear h ==> h z (x - (y:: 'a::ring_1 ^ 'n)) = h z x - h z y"
+  by (simp  add: diff_def bilinear_radd bilinear_rneg)
+
+lemma bilinear_setsum:
+  fixes h:: "'a ^'n \<Rightarrow> 'a::semiring_1^'m \<Rightarrow> 'a ^ 'k"
+  assumes bh: "bilinear h" and fS: "finite S" and fT: "finite T"
+  shows "h (setsum f S) (setsum g T) = setsum (\<lambda>(i,j). h (f i) (g j)) (S \<times> T) "
+proof- 
+  have "h (setsum f S) (setsum g T) = setsum (\<lambda>x. h (f x) (setsum g T)) S"
+    apply (rule linear_setsum[unfolded o_def])
+    using bh fS by (auto simp add: bilinear_def)
+  also have "\<dots> = setsum (\<lambda>x. setsum (\<lambda>y. h (f x) (g y)) T) S"
+    apply (rule setsum_cong, simp)
+    apply (rule linear_setsum[unfolded o_def])
+    using bh fT by (auto simp add: bilinear_def)
+  finally show ?thesis unfolding setsum_cartesian_product .
+qed
+
+lemma bilinear_bounded:
+  fixes h:: "real ^'m \<Rightarrow> real^'n \<Rightarrow> real ^ 'k"
+  assumes bh: "bilinear h"
+  shows "\<exists>B. \<forall>x y. norm (h x y) \<le> B * norm x * norm y"
+proof- 
+  let ?M = "{1 .. dimindex (UNIV :: 'm set)}"
+  let ?N = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?B = "setsum (\<lambda>(i,j). norm (h (basis i) (basis j))) (?M \<times> ?N)"
+  have fM: "finite ?M" and fN: "finite ?N" by simp_all
+  {fix x:: "real ^ 'm" and  y :: "real^'n"
+    have "norm (h x y) = norm (h (setsum (\<lambda>i. (x$i) *s basis i) ?M) (setsum (\<lambda>i. (y$i) *s basis i) ?N))" unfolding basis_expansion ..
+    also have "\<dots> = norm (setsum (\<lambda> (i,j). h ((x$i) *s basis i) ((y$j) *s basis j)) (?M \<times> ?N))"  unfolding bilinear_setsum[OF bh fM fN] ..
+    finally have th: "norm (h x y) = \<dots>" .
+    have "norm (h x y) \<le> ?B * norm x * norm y"
+      apply (simp add: setsum_left_distrib th)
+      apply (rule real_setsum_norm_le)
+      using fN fM
+      apply simp
+      apply (auto simp add: bilinear_rmul[OF bh] bilinear_lmul[OF bh] norm_mul ring_simps)
+      apply (rule mult_mono)
+      apply (auto simp add: norm_pos_le zero_le_mult_iff component_le_norm)
+      apply (rule mult_mono)
+      apply (auto simp add: norm_pos_le zero_le_mult_iff component_le_norm)
+      done}
+  then show ?thesis by metis
+qed
+
+lemma bilinear_bounded_pos:
+  fixes h:: "real ^'m \<Rightarrow> real^'n \<Rightarrow> real ^ 'k"
+  assumes bh: "bilinear h"
+  shows "\<exists>B > 0. \<forall>x y. norm (h x y) \<le> B * norm x * norm y"
+proof-
+  from bilinear_bounded[OF bh] obtain B where 
+    B: "\<forall>x y. norm (h x y) \<le> B * norm x * norm y" by blast
+  let ?K = "\<bar>B\<bar> + 1"
+  have Kp: "?K > 0" by arith
+  have KB: "B < ?K" by arith
+  {fix x::"real ^'m" and y :: "real ^'n"
+    from KB Kp
+    have "B * norm x * norm y \<le> ?K * norm x * norm y"
+      apply - 
+      apply (rule mult_right_mono, rule mult_right_mono)
+      by (auto simp add: norm_pos_le)
+    then have "norm (h x y) \<le> ?K * norm x * norm y"
+      using B[rule_format, of x y] by simp} 
+  with Kp show ?thesis by blast
+qed
+
+subsection{* Adjoints. *}
+
+definition "adjoint f = (SOME f'. \<forall>x y. f x \<bullet> y = x \<bullet> f' y)"
+
+lemma choice_iff: "(\<forall>x. \<exists>y. P x y) \<longleftrightarrow> (\<exists>f. \<forall>x. P x (f x))" by metis
+
+lemma adjoint_works_lemma:
+  fixes f:: "'a::ring_1 ^'n \<Rightarrow> 'a ^ 'm"
+  assumes lf: "linear f"
+  shows "\<forall>x y. f x \<bullet> y = x \<bullet> adjoint f y"
+proof-
+  let ?N = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?M = "{1 .. dimindex (UNIV :: 'm set)}"
+  have fN: "finite ?N" by simp
+  have fM: "finite ?M" by simp
+  {fix y:: "'a ^ 'm"
+    let ?w = "(\<chi> i. (f (basis i) \<bullet> y)) :: 'a ^ 'n"
+    {fix x
+      have "f x \<bullet> y = f (setsum (\<lambda>i. (x$i) *s basis i) ?N) \<bullet> y"
+	by (simp only: basis_expansion)
+      also have "\<dots> = (setsum (\<lambda>i. (x$i) *s f (basis i)) ?N) \<bullet> y"
+	unfolding linear_setsum[OF lf fN] 
+	by (simp add: linear_cmul[OF lf])
+      finally have "f x \<bullet> y = x \<bullet> ?w"
+	apply (simp only: )
+	apply (simp add: dot_def setsum_component Cart_lambda_beta setsum_left_distrib setsum_right_distrib vector_component setsum_commute[of _ ?M ?N] ring_simps del: One_nat_def)
+	done}
+  }
+  then show ?thesis unfolding adjoint_def 
+    some_eq_ex[of "\<lambda>f'. \<forall>x y. f x \<bullet> y = x \<bullet> f' y"]
+    using choice_iff[of "\<lambda>a b. \<forall>x. f x \<bullet> a = x \<bullet> b "]
+    by metis
+qed
+
+lemma adjoint_works:
+  fixes f:: "'a::ring_1 ^'n \<Rightarrow> 'a ^ 'm"
+  assumes lf: "linear f"
+  shows "x \<bullet> adjoint f y = f x \<bullet> y"
+  using adjoint_works_lemma[OF lf] by metis
+
+
+lemma adjoint_linear:
+  fixes f :: "'a::comm_ring_1 ^'n \<Rightarrow> 'a ^ 'm"
+  assumes lf: "linear f"
+  shows "linear (adjoint f)"
+  by (simp add: linear_def vector_eq_ldot[symmetric] dot_radd dot_rmult adjoint_works[OF lf])
+
+lemma adjoint_clauses:
+  fixes f:: "'a::comm_ring_1 ^'n \<Rightarrow> 'a ^ 'm"
+  assumes lf: "linear f"
+  shows "x \<bullet> adjoint f y = f x \<bullet> y"
+  and "adjoint f y \<bullet> x = y \<bullet> f x"
+  by (simp_all add: adjoint_works[OF lf] dot_sym )
+
+lemma adjoint_adjoint:
+  fixes f:: "'a::comm_ring_1 ^ 'n \<Rightarrow> _"
+  assumes lf: "linear f"
+  shows "adjoint (adjoint f) = f"
+  apply (rule ext)
+  by (simp add: vector_eq_ldot[symmetric] adjoint_clauses[OF adjoint_linear[OF lf]] adjoint_clauses[OF lf])
+
+lemma adjoint_unique:
+  fixes f:: "'a::comm_ring_1 ^ 'n \<Rightarrow> 'a ^ 'm"
+  assumes lf: "linear f" and u: "\<forall>x y. f' x \<bullet> y = x \<bullet> f y"
+  shows "f' = adjoint f"
+  apply (rule ext)
+  using u
+  by (simp add: vector_eq_rdot[symmetric] adjoint_clauses[OF lf])
+
+text{* Matrix notation. NB: an MxN matrix is of type 'a^'n^'m, not 'a^'m^'n *}
+
+consts generic_mult :: "'a \<Rightarrow> 'b \<Rightarrow> 'c" (infixr "\<star>" 75)
+
+defs (overloaded) 
+matrix_matrix_mult_def: "(m:: ('a::semiring_1) ^'n^'m) \<star> (m' :: 'a ^'p^'n) \<equiv> (\<chi> i j. setsum (\<lambda>k. ((m$i)$k) * ((m'$k)$j)) {1 .. dimindex (UNIV :: 'n set)}) ::'a ^ 'p ^'m"
+
+abbreviation 
+  matrix_matrix_mult' :: "('a::semiring_1) ^'n^'m \<Rightarrow> 'a ^'p^'n \<Rightarrow> 'a ^ 'p ^'m"  (infixl "**" 70)
+  where "m ** m' == m\<star> m'"
+
+defs (overloaded) 
+  matrix_vector_mult_def: "(m::('a::semiring_1) ^'n^'m) \<star> (x::'a ^'n) \<equiv> (\<chi> i. setsum (\<lambda>j. ((m$i)$j) * (x$j)) {1..dimindex(UNIV ::'n set)}) :: 'a^'m"
+
+abbreviation 
+  matrix_vector_mult' :: "('a::semiring_1) ^'n^'m \<Rightarrow> 'a ^'n \<Rightarrow> 'a ^ 'm"  (infixl "*v" 70)
+  where 
+  "m *v v == m \<star> v"
+
+defs (overloaded) 
+  vector_matrix_mult_def: "(x::'a^'m) \<star> (m::('a::semiring_1) ^'n^'m) \<equiv> (\<chi> j. setsum (\<lambda>i. ((m$i)$j) * (x$i)) {1..dimindex(UNIV :: 'm set)}) :: 'a^'n"
+
+abbreviation 
+  vactor_matrix_mult' :: "'a ^ 'm \<Rightarrow> ('a::semiring_1) ^'n^'m \<Rightarrow> 'a ^'n "  (infixl "v*" 70)
+  where 
+  "v v* m == v \<star> m"
+
+definition "(mat::'a::zero => 'a ^'n^'m) k = (\<chi> i j. if i = j then k else 0)"
+definition "(transp::'a^'n^'m \<Rightarrow> 'a^'m^'n) A = (\<chi> i j. ((A$j)$i))"
+definition "(row::nat => 'a ^'n^'m \<Rightarrow> 'a ^'n) i A = (\<chi> j. ((A$i)$j))"
+definition "(column::nat =>'a^'n^'m =>'a^'m) j A = (\<chi> i. ((A$i)$j))"
+definition "rows(A::'a^'n^'m) = { row i A | i. i \<in> {1 .. dimindex(UNIV :: 'm set)}}"
+definition "columns(A::'a^'n^'m) = { column i A | i. i \<in> {1 .. dimindex(UNIV :: 'n set)}}"
+
+lemma mat_0[simp]: "mat 0 = 0" by (vector mat_def)
+lemma matrix_add_ldistrib: "(A ** (B + C)) = (A \<star> B) + (A \<star> C)"
+  by (vector matrix_matrix_mult_def setsum_addf[symmetric] ring_simps)
+
+lemma setsum_delta': 
+  assumes fS: "finite S" shows 
+  "setsum (\<lambda>k. if a = k then b k else 0) S = 
+     (if a\<in> S then b a else 0)"
+  using setsum_delta[OF fS, of a b, symmetric] 
+  by (auto intro: setsum_cong)
+
+lemma matrix_mul_lid: "mat 1 ** A = A"
+  apply (simp add: matrix_matrix_mult_def mat_def)
+  apply vector
+  by (auto simp only: cond_value_iff cond_application_beta setsum_delta'[OF finite_atLeastAtMost]  mult_1_left mult_zero_left if_True)
+
+
+lemma matrix_mul_rid: "A ** mat 1 = A"
+  apply (simp add: matrix_matrix_mult_def mat_def)
+  apply vector
+  by (auto simp only: cond_value_iff cond_application_beta setsum_delta[OF finite_atLeastAtMost]  mult_1_right mult_zero_right if_True cong: if_cong)
+
+lemma matrix_mul_assoc: "A ** (B ** C) = (A ** B) ** C"
+  apply (vector matrix_matrix_mult_def setsum_right_distrib setsum_left_distrib mult_assoc)
+  apply (subst setsum_commute)
+  apply simp
+  done
+
+lemma matrix_vector_mul_assoc: "A *v (B *v x) = (A ** B) *v x"
+  apply (vector matrix_matrix_mult_def matrix_vector_mult_def setsum_right_distrib setsum_left_distrib mult_assoc)
+  apply (subst setsum_commute)
+  apply simp
+  done
+
+lemma matrix_vector_mul_lid: "mat 1 *v x = x"
+  apply (vector matrix_vector_mult_def mat_def)
+  by (simp add: cond_value_iff cond_application_beta 
+    setsum_delta' cong del: if_weak_cong)
+
+lemma matrix_transp_mul: "transp(A ** B) = transp B ** transp (A::'a::comm_semiring_1^'m^'n)"
+  by (simp add: matrix_matrix_mult_def transp_def Cart_eq Cart_lambda_beta mult_commute)
+
+lemma matrix_eq: "A = B \<longleftrightarrow>  (\<forall>x. A *v x = B *v x)" (is "?lhs \<longleftrightarrow> ?rhs")
+  apply auto
+  apply (subst Cart_eq)
+  apply clarify
+  apply (clarsimp simp add: matrix_vector_mult_def basis_def cond_value_iff cond_application_beta Cart_eq Cart_lambda_beta cong del: if_weak_cong)
+  apply (erule_tac x="basis ia" in allE)
+  apply (erule_tac x="i" in ballE)
+  by (auto simp add: basis_def cond_value_iff cond_application_beta Cart_lambda_beta setsum_delta[OF finite_atLeastAtMost] cong del: if_weak_cong)
+
+lemma matrix_vector_mul_component: 
+  assumes k: "k \<in> {1.. dimindex (UNIV :: 'm set)}"
+  shows "((A::'a::semiring_1^'n'^'m) *v x)$k = (A$k) \<bullet> x"
+  using k
+  by (simp add: matrix_vector_mult_def Cart_lambda_beta dot_def)
+
+lemma dot_lmul_matrix: "((x::'a::comm_semiring_1 ^'n) v* A) \<bullet> y = x \<bullet> (A *v y)"
+  apply (simp add: dot_def matrix_vector_mult_def vector_matrix_mult_def setsum_left_distrib setsum_right_distrib Cart_lambda_beta mult_ac)
+  apply (subst setsum_commute)
+  by simp
+
+lemma transp_mat: "transp (mat n) = mat n"
+  by (vector transp_def mat_def)
+
+lemma transp_transp: "transp(transp A) = A"
+  by (vector transp_def)
+
+lemma row_transp: 
+  fixes A:: "'a::semiring_1^'n^'m"
+  assumes i: "i \<in> {1.. dimindex (UNIV :: 'n set)}"
+  shows "row i (transp A) = column i A"
+  using i 
+  by (simp add: row_def column_def transp_def Cart_eq Cart_lambda_beta)
+
+lemma column_transp:
+  fixes A:: "'a::semiring_1^'n^'m"
+  assumes i: "i \<in> {1.. dimindex (UNIV :: 'm set)}"
+  shows "column i (transp A) = row i A"
+  using i 
+  by (simp add: row_def column_def transp_def Cart_eq Cart_lambda_beta)
+
+lemma rows_transp: "rows(transp (A::'a::semiring_1^'n^'m)) = columns A"
+apply (auto simp add: rows_def columns_def row_transp intro: set_ext)
+apply (rule_tac x=i in exI)
+apply (auto simp add: row_transp)
+done
+
+lemma columns_transp: "columns(transp (A::'a::semiring_1^'n^'m)) = rows A" by (metis transp_transp rows_transp)
+
+text{* Two sometimes fruitful ways of looking at matrix-vector multiplication. *}
+
+lemma matrix_mult_dot: "A *v x = (\<chi> i. A$i \<bullet> x)"
+  by (simp add: matrix_vector_mult_def dot_def)
+
+lemma matrix_mult_vsum: "(A::'a::comm_semiring_1^'n^'m) *v x = setsum (\<lambda>i. (x$i) *s column i A) {1 .. dimindex(UNIV:: 'n set)}"
+  by (simp add: matrix_vector_mult_def Cart_eq setsum_component Cart_lambda_beta vector_component column_def mult_commute)
+
+lemma vector_componentwise:
+  "(x::'a::ring_1^'n) = (\<chi> j. setsum (\<lambda>i. (x$i) * (basis i :: 'a^'n)$j) {1..dimindex(UNIV :: 'n set)})"
+  apply (subst basis_expansion[symmetric])
+  by (vector Cart_eq Cart_lambda_beta setsum_component)
+
+lemma linear_componentwise:
+  fixes f:: "'a::ring_1 ^ 'm \<Rightarrow> 'a ^ 'n"
+  assumes lf: "linear f" and j: "j \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "(f x)$j = setsum (\<lambda>i. (x$i) * (f (basis i)$j)) {1 .. dimindex (UNIV :: 'm set)}" (is "?lhs = ?rhs")
+proof-
+  let ?M = "{1 .. dimindex (UNIV :: 'm set)}"
+  let ?N = "{1 .. dimindex (UNIV :: 'n set)}"
+  have fM: "finite ?M" by simp
+  have "?rhs = (setsum (\<lambda>i.(x$i) *s f (basis i) ) ?M)$j"
+    unfolding vector_smult_component[OF j, symmetric]
+    unfolding setsum_component[OF j, of "(\<lambda>i.(x$i) *s f (basis i :: 'a^'m))" ?M]
+    ..
+  then show ?thesis unfolding linear_setsum_mul[OF lf fM, symmetric] basis_expansion ..
+qed
+
+text{* Inverse matrices  (not necessarily square) *}
+
+definition "invertible(A::'a::semiring_1^'n^'m) \<longleftrightarrow> (\<exists>A'::'a^'m^'n. A ** A' = mat 1 \<and> A' ** A = mat 1)"
+
+definition "matrix_inv(A:: 'a::semiring_1^'n^'m) =
+        (SOME A'::'a^'m^'n. A ** A' = mat 1 \<and> A' ** A = mat 1)"
+
+text{* Correspondence between matrices and linear operators. *}
+
+definition matrix:: "('a::{plus,times, one, zero}^'m \<Rightarrow> 'a ^ 'n) \<Rightarrow> 'a^'m^'n"
+where "matrix f = (\<chi> i j. (f(basis j))$i)"
+
+lemma matrix_vector_mul_linear: "linear(\<lambda>x. A *v (x::'a::comm_semiring_1 ^ 'n))"
+  by (simp add: linear_def matrix_vector_mult_def Cart_eq Cart_lambda_beta vector_component ring_simps setsum_right_distrib setsum_addf)
+
+lemma matrix_works: assumes lf: "linear f" shows "matrix f *v x = f (x::'a::comm_ring_1 ^ 'n)"
+apply (simp add: matrix_def matrix_vector_mult_def Cart_eq Cart_lambda_beta mult_commute del: One_nat_def)
+apply clarify
+apply (rule linear_componentwise[OF lf, symmetric])
+apply simp
+done
+
+lemma matrix_vector_mul: "linear f ==> f = (\<lambda>x. matrix f *v (x::'a::comm_ring_1 ^ 'n))" by (simp add: ext matrix_works)
+
+lemma matrix_of_matrix_vector_mul: "matrix(\<lambda>x. A *v (x :: 'a:: comm_ring_1 ^ 'n)) = A"
+  by (simp add: matrix_eq matrix_vector_mul_linear matrix_works)
+
+lemma matrix_compose: 
+  assumes lf: "linear (f::'a::comm_ring_1^'n \<Rightarrow> _)" and lg: "linear g" 
+  shows "matrix (g o f) = matrix g ** matrix f"
+  using lf lg linear_compose[OF lf lg] matrix_works[OF linear_compose[OF lf lg]]
+  by (simp  add: matrix_eq matrix_works matrix_vector_mul_assoc[symmetric] o_def)
+
+lemma matrix_vector_column:"(A::'a::comm_semiring_1^'n^'m) *v x = setsum (\<lambda>i. (x$i) *s ((transp A)$i)) {1..dimindex(UNIV:: 'n set)}"
+  by (simp add: matrix_vector_mult_def transp_def Cart_eq Cart_lambda_beta setsum_component vector_component mult_commute)
+
+lemma adjoint_matrix: "adjoint(\<lambda>x. (A::'a::comm_ring_1^'n^'m) *v x) = (\<lambda>x. transp A *v x)"
+  apply (rule adjoint_unique[symmetric])
+  apply (rule matrix_vector_mul_linear)
+  apply (simp add: transp_def dot_def Cart_lambda_beta matrix_vector_mult_def setsum_left_distrib setsum_right_distrib)
+  apply (subst setsum_commute)
+  apply (auto simp add: mult_ac)
+  done
+
+lemma matrix_adjoint: assumes lf: "linear (f :: 'a::comm_ring_1^'n \<Rightarrow> 'a ^ 'm)"
+  shows "matrix(adjoint f) = transp(matrix f)"
+  apply (subst matrix_vector_mul[OF lf])
+  unfolding adjoint_matrix matrix_of_matrix_vector_mul ..
+
+subsection{* Interlude: Some properties of real sets *}
+
+lemma seq_mono_lemma: assumes "\<forall>(n::nat) \<ge> m. (d n :: real) < e n" and "\<forall>n \<ge> m. e n <= e m"
+  shows "\<forall>n \<ge> m. d n < e m"
+  using prems apply auto
+  apply (erule_tac x="n" in allE)
+  apply (erule_tac x="n" in allE)
+  apply auto
+  done
+
+
+lemma real_convex_bound_lt: 
+  assumes xa: "(x::real) < a" and ya: "y < a" and u: "0 <= u" and v: "0 <= v"
+  and uv: "u + v = 1" 
+  shows "u * x + v * y < a"
+proof-
+  have uv': "u = 0 \<longrightarrow> v \<noteq> 0" using u v uv by arith
+  have "a = a * (u + v)" unfolding uv  by simp
+  hence th: "u * a + v * a = a" by (simp add: ring_simps)
+  from xa u have "u \<noteq> 0 \<Longrightarrow> u*x < u*a" by (simp add: mult_compare_simps)
+  from ya v have "v \<noteq> 0 \<Longrightarrow> v * y < v * a" by (simp add: mult_compare_simps)
+  from xa ya u v have "u * x + v * y < u * a + v * a"
+    apply (cases "u = 0", simp_all add: uv')
+    apply(rule mult_strict_left_mono)
+    using uv' apply simp_all
+    
+    apply (rule add_less_le_mono)
+    apply(rule mult_strict_left_mono)
+    apply simp_all
+    apply (rule mult_left_mono)
+    apply simp_all
+    done
+  thus ?thesis unfolding th .
+qed
+
+lemma real_convex_bound_le: 
+  assumes xa: "(x::real) \<le> a" and ya: "y \<le> a" and u: "0 <= u" and v: "0 <= v"
+  and uv: "u + v = 1" 
+  shows "u * x + v * y \<le> a"
+proof-
+  from xa ya u v have "u * x + v * y \<le> u * a + v * a" by (simp add: add_mono mult_left_mono)
+  also have "\<dots> \<le> (u + v) * a" by (simp add: ring_simps)
+  finally show ?thesis unfolding uv by simp
+qed
+
+lemma infinite_enumerate: assumes fS: "infinite S"
+  shows "\<exists>r. subseq r \<and> (\<forall>n. r n \<in> S)"
+unfolding subseq_def
+using enumerate_in_set[OF fS] enumerate_mono[of _ _ S] fS by auto
+
+lemma approachable_lt_le: "(\<exists>(d::real)>0. \<forall>x. f x < d \<longrightarrow> P x) \<longleftrightarrow> (\<exists>d>0. \<forall>x. f x \<le> d \<longrightarrow> P x)"
+apply auto
+apply (rule_tac x="d/2" in exI)
+apply auto
+done
+
+
+lemma triangle_lemma: 
+  assumes x: "0 <= (x::real)" and y:"0 <= y" and z: "0 <= z" and xy: "x^2 <= y^2 + z^2"
+  shows "x <= y + z"
+proof-
+  have "y^2 + z^2 \<le> y^2 + 2*y*z + z^2" using z y  by (simp add: zero_compare_simps)
+  with xy have th: "x ^2 \<le> (y+z)^2" by (simp add: power2_eq_square ring_simps)
+  from y z have yz: "y + z \<ge> 0" by arith
+  from power2_le_imp_le[OF th yz] show ?thesis .
+qed
+
+
+lemma lambda_skolem: "(\<forall>i \<in> {1 .. dimindex(UNIV :: 'n set)}. \<exists>x. P i x) \<longleftrightarrow>
+   (\<exists>x::'a ^ 'n. \<forall>i \<in> {1 .. dimindex(UNIV:: 'n set)}. P i (x$i))" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  let ?S = "{1 .. dimindex(UNIV :: 'n set)}"
+  {assume H: "?rhs"
+    then have ?lhs by auto}
+  moreover
+  {assume H: "?lhs"
+    then obtain f where f:"\<forall>i\<in> ?S. P i (f i)" unfolding Ball_def choice_iff by metis
+    let ?x = "(\<chi> i. (f i)) :: 'a ^ 'n"
+    {fix i assume i: "i \<in> ?S"
+      with f i have "P i (f i)" by metis
+      then have "P i (?x$i)" using Cart_lambda_beta[of f, rule_format, OF i] by auto 
+    }
+    hence "\<forall>i \<in> ?S. P i (?x$i)" by metis
+    hence ?rhs by metis }
+  ultimately show ?thesis by metis
+qed 
+
+(* Supremum and infimum of real sets *)
+
+
+definition rsup:: "real set \<Rightarrow> real" where
+  "rsup S = (SOME a. isLub UNIV S a)"
+
+lemma rsup_alt: "rsup S = (SOME a. (\<forall>x \<in> S. x \<le> a) \<and> (\<forall>b. (\<forall>x \<in> S. x \<le> b) \<longrightarrow> a \<le> b))"  by (auto simp  add: isLub_def rsup_def leastP_def isUb_def setle_def setge_def)
+
+lemma rsup: assumes Se: "S \<noteq> {}" and b: "\<exists>b. S *<= b"
+  shows "isLub UNIV S (rsup S)"
+using Se b
+unfolding rsup_def
+apply clarify
+apply (rule someI_ex)
+apply (rule reals_complete)
+by (auto simp add: isUb_def setle_def)
+
+lemma rsup_le: assumes Se: "S \<noteq> {}" and Sb: "S *<= b" shows "rsup S \<le> b"
+proof-
+  from Sb have bu: "isUb UNIV S b" by (simp add: isUb_def setle_def)
+  from rsup[OF Se] Sb have "isLub UNIV S (rsup S)"  by blast 
+  then show ?thesis using bu by (auto simp add: isLub_def leastP_def setle_def setge_def)
+qed
+
+lemma rsup_finite_Max: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "rsup S = Max S"
+using fS Se
+proof-
+  let ?m = "Max S"
+  from Max_ge[OF fS] have Sm: "\<forall> x\<in> S. x \<le> ?m" by metis
+  with rsup[OF Se] have lub: "isLub UNIV S (rsup S)" by (metis setle_def)
+  from Max_in[OF fS Se] lub have mrS: "?m \<le> rsup S" 
+    by (auto simp add: isLub_def leastP_def setle_def setge_def isUb_def)
+  moreover 
+  have "rsup S \<le> ?m" using Sm lub
+    by (auto simp add: isLub_def leastP_def isUb_def setle_def setge_def)
+  ultimately  show ?thesis by arith 
+qed
+
+lemma rsup_finite_in: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "rsup S \<in> S"
+  using rsup_finite_Max[OF fS Se] Max_in[OF fS Se] by metis
+
+lemma rsup_finite_Ub: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "isUb S S (rsup S)"
+  using rsup_finite_Max[OF fS Se] rsup_finite_in[OF fS Se] Max_ge[OF fS]
+  unfolding isUb_def setle_def by metis
+
+lemma rsup_finite_ge_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a \<le> rsup S \<longleftrightarrow> (\<exists> x \<in> S. a \<le> x)"
+using rsup_finite_Ub[OF fS Se] by (auto simp add: isUb_def setle_def)
+
+lemma rsup_finite_le_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a \<ge> rsup S \<longleftrightarrow> (\<forall> x \<in> S. a \<ge> x)"
+using rsup_finite_Ub[OF fS Se] by (auto simp add: isUb_def setle_def)
+
+lemma rsup_finite_gt_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a < rsup S \<longleftrightarrow> (\<exists> x \<in> S. a < x)"
+using rsup_finite_Ub[OF fS Se] by (auto simp add: isUb_def setle_def)
+
+lemma rsup_finite_lt_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a > rsup S \<longleftrightarrow> (\<forall> x \<in> S. a > x)"
+using rsup_finite_Ub[OF fS Se] by (auto simp add: isUb_def setle_def)
+
+lemma rsup_unique: assumes b: "S *<= b" and S: "\<forall>b' < b. \<exists>x \<in> S. b' < x"
+  shows "rsup S = b"
+using b S  
+unfolding setle_def rsup_alt
+apply -
+apply (rule some_equality)
+apply (metis  linorder_not_le order_eq_iff[symmetric])+
+done
+
+lemma rsup_le_subset: "S\<noteq>{} \<Longrightarrow> S \<subseteq> T \<Longrightarrow> (\<exists>b. T *<= b) \<Longrightarrow> rsup S \<le> rsup T"
+  apply (rule rsup_le)
+  apply simp
+  using rsup[of T] by (auto simp add: isLub_def leastP_def setge_def setle_def isUb_def)
+
+lemma isUb_def': "isUb R S = (\<lambda>x. S *<= x \<and> x \<in> R)"
+  apply (rule ext)
+  by (metis isUb_def)
+
+lemma UNIV_trivial: "UNIV x" using UNIV_I[of x] by (metis mem_def)
+lemma rsup_bounds: assumes Se: "S \<noteq> {}" and l: "a <=* S" and u: "S *<= b"
+  shows "a \<le> rsup S \<and> rsup S \<le> b"
+proof-
+  from rsup[OF Se] u have lub: "isLub UNIV S (rsup S)" by blast
+  hence b: "rsup S \<le> b" using u by (auto simp add: isLub_def leastP_def setle_def setge_def isUb_def')
+  from Se obtain y where y: "y \<in> S" by blast
+  from lub l have "a \<le> rsup S" apply (auto simp add: isLub_def leastP_def setle_def setge_def isUb_def')
+    apply (erule ballE[where x=y])
+    apply (erule ballE[where x=y])
+    apply arith
+    using y apply auto
+    done
+  with b show ?thesis by blast
+qed
+
+lemma rsup_abs_le: "S \<noteq> {} \<Longrightarrow> (\<forall>x\<in>S. \<bar>x\<bar> \<le> a) \<Longrightarrow> \<bar>rsup S\<bar> \<le> a"
+  unfolding abs_le_interval_iff  using rsup_bounds[of S "-a" a]
+  by (auto simp add: setge_def setle_def)
+
+lemma rsup_asclose: assumes S:"S \<noteq> {}" and b: "\<forall>x\<in>S. \<bar>x - l\<bar> \<le> e" shows "\<bar>rsup S - l\<bar> \<le> e"
+proof-
+  have th: "\<And>(x::real) l e. \<bar>x - l\<bar> \<le> e \<longleftrightarrow> l - e \<le> x \<and> x \<le> l + e" by arith
+  show ?thesis using S b rsup_bounds[of S "l - e" "l+e"] unfolding th 
+    by  (auto simp add: setge_def setle_def)
+qed
+
+definition rinf:: "real set \<Rightarrow> real" where
+  "rinf S = (SOME a. isGlb UNIV S a)"
+
+lemma rinf_alt: "rinf S = (SOME a. (\<forall>x \<in> S. x \<ge> a) \<and> (\<forall>b. (\<forall>x \<in> S. x \<ge> b) \<longrightarrow> a \<ge> b))"  by (auto simp  add: isGlb_def rinf_def greatestP_def isLb_def setle_def setge_def)
+
+lemma reals_complete_Glb: assumes Se: "\<exists>x. x \<in> S" and lb: "\<exists> y. isLb UNIV S y"
+  shows "\<exists>(t::real). isGlb UNIV S t"
+proof-
+  let ?M = "uminus ` S"
+  from lb have th: "\<exists>y. isUb UNIV ?M y" apply (auto simp add: isUb_def isLb_def setle_def setge_def)
+    by (rule_tac x="-y" in exI, auto)
+  from Se have Me: "\<exists>x. x \<in> ?M" by blast
+  from reals_complete[OF Me th] obtain t where t: "isLub UNIV ?M t" by blast
+  have "isGlb UNIV S (- t)" using t
+    apply (auto simp add: isLub_def isGlb_def leastP_def greatestP_def setle_def setge_def isUb_def isLb_def)
+    apply (erule_tac x="-y" in allE)
+    apply auto
+    done
+  then show ?thesis by metis
+qed
+
+lemma rinf: assumes Se: "S \<noteq> {}" and b: "\<exists>b. b <=* S"
+  shows "isGlb UNIV S (rinf S)"
+using Se b
+unfolding rinf_def
+apply clarify
+apply (rule someI_ex)
+apply (rule reals_complete_Glb)
+apply (auto simp add: isLb_def setle_def setge_def)
+done
+
+lemma rinf_ge: assumes Se: "S \<noteq> {}" and Sb: "b <=* S" shows "rinf S \<ge> b"
+proof-
+  from Sb have bu: "isLb UNIV S b" by (simp add: isLb_def setge_def)
+  from rinf[OF Se] Sb have "isGlb UNIV S (rinf S)"  by blast 
+  then show ?thesis using bu by (auto simp add: isGlb_def greatestP_def setle_def setge_def)
+qed
+
+lemma rinf_finite_Min: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "rinf S = Min S"
+using fS Se
+proof-
+  let ?m = "Min S"
+  from Min_le[OF fS] have Sm: "\<forall> x\<in> S. x \<ge> ?m" by metis
+  with rinf[OF Se] have glb: "isGlb UNIV S (rinf S)" by (metis setge_def)
+  from Min_in[OF fS Se] glb have mrS: "?m \<ge> rinf S" 
+    by (auto simp add: isGlb_def greatestP_def setle_def setge_def isLb_def)
+  moreover 
+  have "rinf S \<ge> ?m" using Sm glb
+    by (auto simp add: isGlb_def greatestP_def isLb_def setle_def setge_def)
+  ultimately  show ?thesis by arith 
+qed
+
+lemma rinf_finite_in: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "rinf S \<in> S"
+  using rinf_finite_Min[OF fS Se] Min_in[OF fS Se] by metis
+
+lemma rinf_finite_Lb: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "isLb S S (rinf S)"
+  using rinf_finite_Min[OF fS Se] rinf_finite_in[OF fS Se] Min_le[OF fS]
+  unfolding isLb_def setge_def by metis
+
+lemma rinf_finite_ge_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a \<le> rinf S \<longleftrightarrow> (\<forall> x \<in> S. a \<le> x)"
+using rinf_finite_Lb[OF fS Se] by (auto simp add: isLb_def setge_def)
+
+lemma rinf_finite_le_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a \<ge> rinf S \<longleftrightarrow> (\<exists> x \<in> S. a \<ge> x)"
+using rinf_finite_Lb[OF fS Se] by (auto simp add: isLb_def setge_def)
+
+lemma rinf_finite_gt_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a < rinf S \<longleftrightarrow> (\<forall> x \<in> S. a < x)"
+using rinf_finite_Lb[OF fS Se] by (auto simp add: isLb_def setge_def)
+
+lemma rinf_finite_lt_iff: assumes fS: "finite S" and Se: "S \<noteq> {}"
+  shows "a > rinf S \<longleftrightarrow> (\<exists> x \<in> S. a > x)"
+using rinf_finite_Lb[OF fS Se] by (auto simp add: isLb_def setge_def)
+
+lemma rinf_unique: assumes b: "b <=* S" and S: "\<forall>b' > b. \<exists>x \<in> S. b' > x"
+  shows "rinf S = b"
+using b S  
+unfolding setge_def rinf_alt
+apply -
+apply (rule some_equality)
+apply (metis  linorder_not_le order_eq_iff[symmetric])+
+done
+
+lemma rinf_ge_subset: "S\<noteq>{} \<Longrightarrow> S \<subseteq> T \<Longrightarrow> (\<exists>b. b <=* T) \<Longrightarrow> rinf S >= rinf T"
+  apply (rule rinf_ge)
+  apply simp
+  using rinf[of T] by (auto simp add: isGlb_def greatestP_def setge_def setle_def isLb_def)
+
+lemma isLb_def': "isLb R S = (\<lambda>x. x <=* S \<and> x \<in> R)"
+  apply (rule ext)
+  by (metis isLb_def)
+
+lemma rinf_bounds: assumes Se: "S \<noteq> {}" and l: "a <=* S" and u: "S *<= b"
+  shows "a \<le> rinf S \<and> rinf S \<le> b"
+proof-
+  from rinf[OF Se] l have lub: "isGlb UNIV S (rinf S)" by blast
+  hence b: "a \<le> rinf S" using l by (auto simp add: isGlb_def greatestP_def setle_def setge_def isLb_def')
+  from Se obtain y where y: "y \<in> S" by blast
+  from lub u have "b \<ge> rinf S" apply (auto simp add: isGlb_def greatestP_def setle_def setge_def isLb_def')
+    apply (erule ballE[where x=y])
+    apply (erule ballE[where x=y])
+    apply arith
+    using y apply auto
+    done
+  with b show ?thesis by blast
+qed
+
+lemma rinf_abs_ge: "S \<noteq> {} \<Longrightarrow> (\<forall>x\<in>S. \<bar>x\<bar> \<le> a) \<Longrightarrow> \<bar>rinf S\<bar> \<le> a"
+  unfolding abs_le_interval_iff  using rinf_bounds[of S "-a" a]
+  by (auto simp add: setge_def setle_def)
+
+lemma rinf_asclose: assumes S:"S \<noteq> {}" and b: "\<forall>x\<in>S. \<bar>x - l\<bar> \<le> e" shows "\<bar>rinf S - l\<bar> \<le> e"
+proof-
+  have th: "\<And>(x::real) l e. \<bar>x - l\<bar> \<le> e \<longleftrightarrow> l - e \<le> x \<and> x \<le> l + e" by arith
+  show ?thesis using S b rinf_bounds[of S "l - e" "l+e"] unfolding th 
+    by  (auto simp add: setge_def setle_def)
+qed
+
+
+
+subsection{* Operator norm. *}
+
+definition "onorm f = rsup {norm (f x)| x. norm x = 1}"
+
+lemma norm_bound_generalize:
+  fixes f:: "real ^'n \<Rightarrow> real^'m"
+  assumes lf: "linear f"
+  shows "(\<forall>x. norm x = 1 \<longrightarrow> norm (f x) \<le> b) \<longleftrightarrow> (\<forall>x. norm (f x) \<le> b * norm x)" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume H: ?rhs
+    {fix x :: "real^'n" assume x: "norm x = 1"
+      from H[rule_format, of x] x have "norm (f x) \<le> b" by simp}
+    then have ?lhs by blast }
+
+  moreover
+  {assume H: ?lhs
+    from H[rule_format, of "basis 1"] 
+    have bp: "b \<ge> 0" using norm_pos_le[of "f (basis 1)"] dimindex_ge_1[of "UNIV:: 'n set"]
+      by (auto simp add: norm_basis) 
+    {fix x :: "real ^'n"
+      {assume "x = 0"
+	then have "norm (f x) \<le> b * norm x" by (simp add: linear_0[OF lf] norm_0 bp)}
+      moreover
+      {assume x0: "x \<noteq> 0"
+	hence n0: "norm x \<noteq> 0" by (metis norm_eq_0)
+	let ?c = "1/ norm x"
+	have "norm (?c*s x) = 1" by (simp add: n0 norm_mul)
+	with H have "norm (f(?c*s x)) \<le> b" by blast
+	hence "?c * norm (f x) \<le> b" 
+	  by (simp add: linear_cmul[OF lf] norm_mul)
+	hence "norm (f x) \<le> b * norm x" 
+	  using n0 norm_pos_le[of x] by (auto simp add: field_simps)}
+      ultimately have "norm (f x) \<le> b * norm x" by blast}
+    then have ?rhs by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma onorm:
+  fixes f:: "real ^'n \<Rightarrow> real ^'m"
+  assumes lf: "linear f"
+  shows "norm (f x) <= onorm f * norm x"
+  and "\<forall>x. norm (f x) <= b * norm x \<Longrightarrow> onorm f <= b"
+proof-
+  {
+    let ?S = "{norm (f x) |x. norm x = 1}"
+    have Se: "?S \<noteq> {}" using  norm_basis_1 by auto
+    from linear_bounded[OF lf] have b: "\<exists> b. ?S *<= b" 
+      unfolding norm_bound_generalize[OF lf, symmetric] by (auto simp add: setle_def)
+    {from rsup[OF Se b, unfolded onorm_def[symmetric]]
+      show "norm (f x) <= onorm f * norm x" 
+	apply - 
+	apply (rule spec[where x = x])
+	unfolding norm_bound_generalize[OF lf, symmetric]
+	by (auto simp add: isLub_def isUb_def leastP_def setge_def setle_def)}
+    {
+      show "\<forall>x. norm (f x) <= b * norm x \<Longrightarrow> onorm f <= b"  
+	using rsup[OF Se b, unfolded onorm_def[symmetric]]
+	unfolding norm_bound_generalize[OF lf, symmetric]
+	by (auto simp add: isLub_def isUb_def leastP_def setge_def setle_def)}
+  }
+qed
+
+lemma onorm_pos_le: assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'m)" shows "0 <= onorm f"
+  using order_trans[OF norm_pos_le onorm(1)[OF lf, of "basis 1"], unfolded norm_basis_1] by simp
+
+lemma onorm_eq_0: assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'m)" 
+  shows "onorm f = 0 \<longleftrightarrow> (\<forall>x. f x = 0)"
+  using onorm[OF lf]
+  apply (auto simp add: norm_0 onorm_pos_le norm_le_0)
+  apply atomize
+  apply (erule allE[where x="0::real"])
+  using onorm_pos_le[OF lf]
+  apply arith
+  done
+
+lemma onorm_const: "onorm(\<lambda>x::real^'n. (y::real ^ 'm)) = norm y"
+proof-
+  let ?f = "\<lambda>x::real^'n. (y::real ^ 'm)"
+  have th: "{norm (?f x)| x. norm x = 1} = {norm y}"
+    by(auto intro: vector_choose_size set_ext)
+  show ?thesis
+    unfolding onorm_def th
+    apply (rule rsup_unique) by (simp_all  add: setle_def)
+qed
+
+lemma onorm_pos_lt: assumes lf: "linear (f::real ^ 'n \<Rightarrow> real ^'m)" 
+  shows "0 < onorm f \<longleftrightarrow> ~(\<forall>x. f x = 0)"
+  unfolding onorm_eq_0[OF lf, symmetric]
+  using onorm_pos_le[OF lf] by arith
+
+lemma onorm_compose:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'m)" and lg: "linear g"
+  shows "onorm (f o g) <= onorm f * onorm g"
+  apply (rule onorm(2)[OF linear_compose[OF lg lf], rule_format])
+  unfolding o_def
+  apply (subst mult_assoc)
+  apply (rule order_trans)
+  apply (rule onorm(1)[OF lf])
+  apply (rule mult_mono1)
+  apply (rule onorm(1)[OF lg])
+  apply (rule onorm_pos_le[OF lf])
+  done
+
+lemma onorm_neg_lemma: assumes lf: "linear (f::real ^'n \<Rightarrow> real^'m)"
+  shows "onorm (\<lambda>x. - f x) \<le> onorm f"
+  using onorm[OF linear_compose_neg[OF lf]] onorm[OF lf]
+  unfolding norm_neg by metis
+
+lemma onorm_neg: assumes lf: "linear (f::real ^'n \<Rightarrow> real^'m)"
+  shows "onorm (\<lambda>x. - f x) = onorm f"
+  using onorm_neg_lemma[OF lf] onorm_neg_lemma[OF linear_compose_neg[OF lf]]
+  by simp
+
+lemma onorm_triangle:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'m)" and lg: "linear g"
+  shows "onorm (\<lambda>x. f x + g x) <= onorm f + onorm g"
+  apply(rule onorm(2)[OF linear_compose_add[OF lf lg], rule_format])
+  apply (rule order_trans)
+  apply (rule norm_triangle)
+  apply (simp add: distrib)
+  apply (rule add_mono)
+  apply (rule onorm(1)[OF lf])
+  apply (rule onorm(1)[OF lg])
+  done
+
+lemma onorm_triangle_le: "linear (f::real ^'n \<Rightarrow> real ^'m) \<Longrightarrow> linear g \<Longrightarrow> onorm(f) + onorm(g) <= e
+  \<Longrightarrow> onorm(\<lambda>x. f x + g x) <= e"
+  apply (rule order_trans)
+  apply (rule onorm_triangle)
+  apply assumption+
+  done
+
+lemma onorm_triangle_lt: "linear (f::real ^'n \<Rightarrow> real ^'m) \<Longrightarrow> linear g \<Longrightarrow> onorm(f) + onorm(g) < e
+  ==> onorm(\<lambda>x. f x + g x) < e"
+  apply (rule order_le_less_trans)
+  apply (rule onorm_triangle)
+  by assumption+
+
+(* "lift" from 'a to 'a^1 and "drop" from 'a^1 to 'a -- FIXME: potential use of transfer *)
+
+definition vec1:: "'a \<Rightarrow> 'a ^ 1" where "vec1 x = (\<chi> i. x)"
+
+definition dest_vec1:: "'a ^1 \<Rightarrow> 'a" 
+  where "dest_vec1 x = (x$1)"
+
+lemma vec1_component[simp]: "(vec1 x)$1 = x"
+  by (simp add: vec1_def)
+
+lemma vec1_dest_vec1[simp]: "vec1(dest_vec1 x) = x" "dest_vec1(vec1 y) = y"
+  by (simp_all add: vec1_def dest_vec1_def Cart_eq Cart_lambda_beta dimindex_def del: One_nat_def)
+
+lemma forall_vec1: "(\<forall>x. P x) \<longleftrightarrow> (\<forall>x. P (vec1 x))" by (metis vec1_dest_vec1)
+
+lemma exists_vec1: "(\<exists>x. P x) \<longleftrightarrow> (\<exists>x. P(vec1 x))" by (metis vec1_dest_vec1) 
+
+lemma forall_dest_vec1: "(\<forall>x. P x) \<longleftrightarrow> (\<forall>x. P(dest_vec1 x))"  by (metis vec1_dest_vec1)
+
+lemma exists_dest_vec1: "(\<exists>x. P x) \<longleftrightarrow> (\<exists>x. P(dest_vec1 x))"by (metis vec1_dest_vec1)
+
+lemma vec1_eq[simp]:  "vec1 x = vec1 y \<longleftrightarrow> x = y" by (metis vec1_dest_vec1)
+
+lemma dest_vec1_eq[simp]: "dest_vec1 x = dest_vec1 y \<longleftrightarrow> x = y" by (metis vec1_dest_vec1)
+
+lemma vec1_in_image_vec1: "vec1 x \<in> (vec1 ` S) \<longleftrightarrow> x \<in> S" by auto
+
+lemma vec1_vec: "vec1 x = vec x" by (vector vec1_def)
+
+lemma vec1_add: "vec1(x + y) = vec1 x + vec1 y" by (vector vec1_def)
+lemma vec1_sub: "vec1(x - y) = vec1 x - vec1 y" by (vector vec1_def)
+lemma vec1_cmul: "vec1(c* x) = c *s vec1 x " by (vector vec1_def)
+lemma vec1_neg: "vec1(- x) = - vec1 x " by (vector vec1_def)
+
+lemma vec1_setsum: assumes fS: "finite S"
+  shows "vec1(setsum f S) = setsum (vec1 o f) S"
+  apply (induct rule: finite_induct[OF fS])
+  apply (simp add: vec1_vec)
+  apply (auto simp add: vec1_add)
+  done
+
+lemma dest_vec1_lambda: "dest_vec1(\<chi> i. x i) = x 1"
+  by (simp add: dest_vec1_def)
+
+lemma dest_vec1_vec: "dest_vec1(vec x) = x"
+  by (simp add: vec1_vec[symmetric])
+
+lemma dest_vec1_add: "dest_vec1(x + y) = dest_vec1 x + dest_vec1 y"
+ by (metis vec1_dest_vec1 vec1_add)
+
+lemma dest_vec1_sub: "dest_vec1(x - y) = dest_vec1 x - dest_vec1 y"
+ by (metis vec1_dest_vec1 vec1_sub)
+
+lemma dest_vec1_cmul: "dest_vec1(c*sx) = c * dest_vec1 x"
+ by (metis vec1_dest_vec1 vec1_cmul)
+
+lemma dest_vec1_neg: "dest_vec1(- x) = - dest_vec1 x"
+ by (metis vec1_dest_vec1 vec1_neg)
+
+lemma dest_vec1_0[simp]: "dest_vec1 0 = 0" by (metis vec_0 dest_vec1_vec)
+
+lemma dest_vec1_sum: assumes fS: "finite S"
+  shows "dest_vec1(setsum f S) = setsum (dest_vec1 o f) S"
+  apply (induct rule: finite_induct[OF fS])
+  apply (simp add: dest_vec1_vec)
+  apply (auto simp add: dest_vec1_add)
+  done
+
+lemma norm_vec1: "norm(vec1 x) = abs(x)"
+  by (simp add: vec1_def norm_real)
+
+lemma dist_vec1: "dist(vec1 x) (vec1 y) = abs(x - y)"
+  by (simp only: dist_real vec1_component)
+lemma abs_dest_vec1: "norm x = \<bar>dest_vec1 x\<bar>"
+  by (metis vec1_dest_vec1 norm_vec1)
+
+lemma linear_vmul_dest_vec1: 
+  fixes f:: "'a::semiring_1^'n \<Rightarrow> 'a^1"
+  shows "linear f \<Longrightarrow> linear (\<lambda>x. dest_vec1(f x) *s v)"
+  unfolding dest_vec1_def
+  apply (rule linear_vmul_component)
+  by (auto simp add: dimindex_def)
+
+lemma linear_from_scalars:
+  assumes lf: "linear (f::'a::comm_ring_1 ^1 \<Rightarrow> 'a^'n)"
+  shows "f = (\<lambda>x. dest_vec1 x *s column 1 (matrix f))"
+  apply (rule ext)
+  apply (subst matrix_works[OF lf, symmetric])
+  apply (auto simp add: Cart_eq matrix_vector_mult_def dest_vec1_def column_def Cart_lambda_beta vector_component dimindex_def mult_commute del: One_nat_def )
+  done
+
+lemma linear_to_scalars: assumes lf: "linear (f::'a::comm_ring_1 ^'n \<Rightarrow> 'a^1)"
+  shows "f = (\<lambda>x. vec1(row 1 (matrix f) \<bullet> x))"
+  apply (rule ext)
+  apply (subst matrix_works[OF lf, symmetric])
+  apply (auto simp add: Cart_eq matrix_vector_mult_def vec1_def row_def Cart_lambda_beta vector_component dimindex_def dot_def mult_commute)
+  done
+
+lemma dest_vec1_eq_0: "dest_vec1 x = 0 \<longleftrightarrow> x = 0"
+  by (simp add: dest_vec1_eq[symmetric])
+
+lemma setsum_scalars: assumes fS: "finite S"
+  shows "setsum f S = vec1 (setsum (dest_vec1 o f) S)"
+  unfolding vec1_setsum[OF fS] by simp
+
+lemma dest_vec1_wlog_le: "(\<And>(x::'a::linorder ^ 1) y. P x y \<longleftrightarrow> P y x)  \<Longrightarrow> (\<And>x y. dest_vec1 x <= dest_vec1 y ==> P x y) \<Longrightarrow> P x y"
+  apply (cases "dest_vec1 x \<le> dest_vec1 y")
+  apply simp
+  apply (subgoal_tac "dest_vec1 y \<le> dest_vec1 x")
+  apply (auto)
+  done
+
+text{* Pasting vectors. *}
+
+lemma linear_fstcart: "linear fstcart"
+  by (auto simp add: linear_def fstcart_def Cart_eq Cart_lambda_beta vector_component dimindex_finite_sum)
+
+lemma linear_sndcart: "linear sndcart"
+  by (auto simp add: linear_def sndcart_def Cart_eq Cart_lambda_beta vector_component dimindex_finite_sum)
+
+lemma fstcart_vec[simp]: "fstcart(vec x) = vec x"
+  by (vector fstcart_def vec_def dimindex_finite_sum)
+
+lemma fstcart_add[simp]:"fstcart(x + y) = fstcart (x::'a::{plus,times}^('b,'c) finite_sum) + fstcart y"
+  using linear_fstcart[unfolded linear_def] by blast
+
+lemma fstcart_cmul[simp]:"fstcart(c*s x) = c*s fstcart (x::'a::{plus,times}^('b,'c) finite_sum)"
+  using linear_fstcart[unfolded linear_def] by blast
+
+lemma fstcart_neg[simp]:"fstcart(- x) = - fstcart (x::'a::ring_1^('b,'c) finite_sum)"
+unfolding vector_sneg_minus1 fstcart_cmul ..
+
+lemma fstcart_sub[simp]:"fstcart(x - y) = fstcart (x::'a::ring_1^('b,'c) finite_sum) - fstcart y"
+  unfolding diff_def fstcart_add fstcart_neg  ..
+
+lemma fstcart_setsum:
+  fixes f:: "'d \<Rightarrow> 'a::semiring_1^_"
+  assumes fS: "finite S"
+  shows "fstcart (setsum f S) = setsum (\<lambda>i. fstcart (f i)) S"
+  by (induct rule: finite_induct[OF fS], simp_all add: vec_0[symmetric] del: vec_0)
+
+lemma sndcart_vec[simp]: "sndcart(vec x) = vec x"
+  by (vector sndcart_def vec_def dimindex_finite_sum)
+
+lemma sndcart_add[simp]:"sndcart(x + y) = sndcart (x::'a::{plus,times}^('b,'c) finite_sum) + sndcart y"
+  using linear_sndcart[unfolded linear_def] by blast
+
+lemma sndcart_cmul[simp]:"sndcart(c*s x) = c*s sndcart (x::'a::{plus,times}^('b,'c) finite_sum)"
+  using linear_sndcart[unfolded linear_def] by blast
+
+lemma sndcart_neg[simp]:"sndcart(- x) = - sndcart (x::'a::ring_1^('b,'c) finite_sum)"
+unfolding vector_sneg_minus1 sndcart_cmul ..
+
+lemma sndcart_sub[simp]:"sndcart(x - y) = sndcart (x::'a::ring_1^('b,'c) finite_sum) - sndcart y"
+  unfolding diff_def sndcart_add sndcart_neg  ..
+
+lemma sndcart_setsum:
+  fixes f:: "'d \<Rightarrow> 'a::semiring_1^_"
+  assumes fS: "finite S"
+  shows "sndcart (setsum f S) = setsum (\<lambda>i. sndcart (f i)) S"
+  by (induct rule: finite_induct[OF fS], simp_all add: vec_0[symmetric] del: vec_0)
+
+lemma pastecart_vec[simp]: "pastecart (vec x) (vec x) = vec x"
+  by (simp add: pastecart_eq fstcart_vec sndcart_vec fstcart_pastecart sndcart_pastecart)
+
+lemma pastecart_add[simp]:"pastecart (x1::'a::{plus,times}^_) y1 + pastecart x2 y2 = pastecart (x1 + x2) (y1 + y2)"
+  by (simp add: pastecart_eq fstcart_add sndcart_add fstcart_pastecart sndcart_pastecart)
+
+lemma pastecart_cmul[simp]: "pastecart (c *s (x1::'a::{plus,times}^_)) (c *s y1) = c *s pastecart x1 y1"
+  by (simp add: pastecart_eq fstcart_pastecart sndcart_pastecart)
+
+lemma pastecart_neg[simp]: "pastecart (- (x::'a::ring_1^_)) (- y) = - pastecart x y"
+  unfolding vector_sneg_minus1 pastecart_cmul ..
+
+lemma pastecart_sub: "pastecart (x1::'a::ring_1^_) y1 - pastecart x2 y2 = pastecart (x1 - x2) (y1 - y2)"
+  by (simp add: diff_def pastecart_neg[symmetric] del: pastecart_neg)
+
+lemma pastecart_setsum:
+  fixes f:: "'d \<Rightarrow> 'a::semiring_1^_"
+  assumes fS: "finite S"
+  shows "pastecart (setsum f S) (setsum g S) = setsum (\<lambda>i. pastecart (f i) (g i)) S"
+  by (simp  add: pastecart_eq fstcart_setsum[OF fS] sndcart_setsum[OF fS] fstcart_pastecart sndcart_pastecart)
+
+lemma norm_fstcart: "norm(fstcart x) <= norm (x::real ^('n,'m) finite_sum)"
+proof-
+  let ?n = "dimindex (UNIV :: 'n set)"
+  let ?m = "dimindex (UNIV :: 'm set)"
+  let ?N = "{1 .. ?n}"
+  let ?M = "{1 .. ?m}"
+  let ?NM = "{1 .. dimindex (UNIV :: ('n,'m) finite_sum set)}"
+  have th_0: "1 \<le> ?n +1" by simp
+  have th0: "norm x = norm (pastecart (fstcart x) (sndcart x))"
+    by (simp add: pastecart_fst_snd)
+  have th1: "fstcart x \<bullet> fstcart x \<le> pastecart (fstcart x) (sndcart x) \<bullet> pastecart (fstcart x) (sndcart x)" 
+    by (simp add: dot_def setsum_add_split[OF th_0, of _ ?m] pastecart_def dimindex_finite_sum Cart_lambda_beta setsum_nonneg zero_le_square del: One_nat_def)
+  then show ?thesis
+    unfolding th0 
+    unfolding real_vector_norm_def real_sqrt_le_iff real_of_real_def id_def
+    by (simp add: dot_def dimindex_finite_sum Cart_lambda_beta)
+qed
+
+lemma dist_fstcart: "dist(fstcart (x::real^_)) (fstcart y) <= dist x y"
+  by (metis dist_def fstcart_sub[symmetric] norm_fstcart)
+
+lemma norm_sndcart: "norm(sndcart x) <= norm (x::real ^('n,'m) finite_sum)"
+proof-
+  let ?n = "dimindex (UNIV :: 'n set)"
+  let ?m = "dimindex (UNIV :: 'm set)"
+  let ?N = "{1 .. ?n}"
+  let ?M = "{1 .. ?m}"
+  let ?nm = "dimindex (UNIV :: ('n,'m) finite_sum set)"
+  let ?NM = "{1 .. ?nm}"
+  have thnm[simp]: "?nm = ?n + ?m" by (simp add: dimindex_finite_sum)
+  have th_0: "1 \<le> ?n +1" by simp
+  have th0: "norm x = norm (pastecart (fstcart x) (sndcart x))"
+    by (simp add: pastecart_fst_snd)
+  let ?f = "\<lambda>n. n - ?n"
+  let ?S = "{?n+1 .. ?nm}"
+  have finj:"inj_on ?f ?S"
+    using dimindex_nonzero[of "UNIV :: 'n set"] dimindex_nonzero[of "UNIV :: 'm set"]
+    apply (simp add: Ball_def atLeastAtMost_iff inj_on_def dimindex_finite_sum del: One_nat_def)
+    by arith
+  have fS: "?f ` ?S = ?M" 
+    apply (rule set_ext)
+    apply (simp add: image_iff Bex_def) using dimindex_nonzero[of "UNIV :: 'n set"] dimindex_nonzero[of "UNIV :: 'm set"] by arith
+  have th1: "sndcart x \<bullet> sndcart x \<le> pastecart (fstcart x) (sndcart x) \<bullet> pastecart (fstcart x) (sndcart x)" 
+    by (simp add: dot_def setsum_add_split[OF th_0, of _ ?m] pastecart_def dimindex_finite_sum Cart_lambda_beta setsum_nonneg zero_le_square setsum_reindex[OF finj, unfolded fS] del: One_nat_def)    
+  then show ?thesis
+    unfolding th0 
+    unfolding real_vector_norm_def real_sqrt_le_iff real_of_real_def id_def
+    by (simp add: dot_def dimindex_finite_sum Cart_lambda_beta)
+qed
+
+lemma dist_sndcart: "dist(sndcart (x::real^_)) (sndcart y) <= dist x y"
+  by (metis dist_def sndcart_sub[symmetric] norm_sndcart)
+
+lemma dot_pastecart: "(pastecart (x1::'a::{times,comm_monoid_add}^'n) (x2::'a::{times,comm_monoid_add}^'m)) \<bullet> (pastecart y1 y2) =  x1 \<bullet> y1 + x2 \<bullet> y2"
+proof-
+  let ?n = "dimindex (UNIV :: 'n set)"
+  let ?m = "dimindex (UNIV :: 'm set)"
+  let ?N = "{1 .. ?n}"
+  let ?M = "{1 .. ?m}"
+  let ?nm = "dimindex (UNIV :: ('n,'m) finite_sum set)"
+  let ?NM = "{1 .. ?nm}"
+  have thnm: "?nm = ?n + ?m" by (simp add: dimindex_finite_sum)
+  have th_0: "1 \<le> ?n +1" by simp
+  have th_1: "\<And>i. i \<in> {?m + 1 .. ?nm} \<Longrightarrow> i - ?m \<in> ?N" apply (simp add: thnm) by arith
+  let ?f = "\<lambda>a b i. (a$i) * (b$i)"
+  let ?g = "?f (pastecart x1 x2) (pastecart y1 y2)"
+  let ?S = "{?n +1 .. ?nm}"
+  {fix i
+    assume i: "i \<in> ?N"
+    have "?g i = ?f x1 y1 i"
+      using i
+      apply (simp add: pastecart_def Cart_lambda_beta thnm) done
+  }
+  hence th2: "setsum ?g ?N = setsum (?f x1 y1) ?N"
+    apply -
+    apply (rule setsum_cong)
+    apply auto
+    done
+  {fix i
+    assume i: "i \<in> ?S"
+    have "?g i = ?f x2 y2 (i - ?n)"
+      using i
+      apply (simp add: pastecart_def Cart_lambda_beta thnm) done
+  }
+  hence th3: "setsum ?g ?S = setsum (\<lambda>i. ?f x2 y2 (i -?n)) ?S"
+    apply -
+    apply (rule setsum_cong)
+    apply auto
+    done
+  let ?r = "\<lambda>n. n - ?n"
+  have rinj: "inj_on ?r ?S" apply (simp add: inj_on_def Ball_def thnm) by arith
+  have rS: "?r ` ?S = ?M" apply (rule set_ext) 
+    apply (simp add: thnm image_iff Bex_def) by arith
+  have "pastecart x1 x2 \<bullet> (pastecart y1 y2) = setsum ?g ?NM" by (simp add: dot_def)
+  also have "\<dots> = setsum ?g ?N + setsum ?g ?S"
+    by (simp add: dot_def thnm setsum_add_split[OF th_0, of _ ?m] del: One_nat_def)
+  also have "\<dots> = setsum (?f x1 y1) ?N + setsum (?f x2 y2) ?M"
+    unfolding setsum_reindex[OF rinj, unfolded rS o_def] th2 th3 ..
+  finally 
+  show ?thesis by (simp add: dot_def)
+qed
+
+lemma norm_pastecart: "norm(pastecart x y) <= norm(x :: real ^ _) + norm(y)"
+  unfolding real_vector_norm_def dot_pastecart real_sqrt_le_iff real_of_real_def id_def
+  apply (rule power2_le_imp_le)
+  apply (simp add: real_sqrt_pow2[OF add_nonneg_nonneg[OF dot_pos_le[of x] dot_pos_le[of y]]])
+  apply (auto simp add: power2_eq_square ring_simps)
+  apply (simp add: power2_eq_square[symmetric])
+  apply (rule mult_nonneg_nonneg)
+  apply (simp_all add: real_sqrt_pow2[OF dot_pos_le])
+  apply (rule add_nonneg_nonneg)
+  apply (simp_all add: real_sqrt_pow2[OF dot_pos_le])
+  done
+
+subsection {* A generic notion of "hull" (convex, affine, conic hull and closure). *}
+
+definition hull :: "'a set set \<Rightarrow> 'a set \<Rightarrow> 'a set" (infixl "hull" 75) where
+  "S hull s = Inter {t. t \<in> S \<and> s \<subseteq> t}"
+
+lemma hull_same: "s \<in> S \<Longrightarrow> S hull s = s"
+  unfolding hull_def by auto
+
+lemma hull_in: "(\<And>T. T \<subseteq> S ==> Inter T \<in> S) ==> (S hull s) \<in> S"
+unfolding hull_def subset_iff by auto
+
+lemma hull_eq: "(\<And>T. T \<subseteq> S ==> Inter T \<in> S) ==> (S hull s) = s \<longleftrightarrow> s \<in> S"
+using hull_same[of s S] hull_in[of S s] by metis  
+
+
+lemma hull_hull: "S hull (S hull s) = S hull s"
+  unfolding hull_def by blast
+
+lemma hull_subset: "s \<subseteq> (S hull s)"
+  unfolding hull_def by blast
+
+lemma hull_mono: " s \<subseteq> t ==> (S hull s) \<subseteq> (S hull t)"
+  unfolding hull_def by blast
+
+lemma hull_antimono: "S \<subseteq> T ==> (T hull s) \<subseteq> (S hull s)"
+  unfolding hull_def by blast
+
+lemma hull_minimal: "s \<subseteq> t \<Longrightarrow> t \<in> S ==> (S hull s) \<subseteq> t"
+  unfolding hull_def by blast
+
+lemma subset_hull: "t \<in> S ==> S hull s \<subseteq> t \<longleftrightarrow>  s \<subseteq> t"
+  unfolding hull_def by blast
+
+lemma hull_unique: "s \<subseteq> t \<Longrightarrow> t \<in> S \<Longrightarrow> (\<And>t'. s \<subseteq> t' \<Longrightarrow> t' \<in> S ==> t \<subseteq> t')
+           ==> (S hull s = t)"
+unfolding hull_def by auto
+
+lemma hull_induct: "(\<And>x. x\<in> S \<Longrightarrow> P x) \<Longrightarrow> Q {x. P x} \<Longrightarrow> \<forall>x\<in> Q hull S. P x"
+  using hull_minimal[of S "{x. P x}" Q]
+  by (auto simp add: subset_eq Collect_def mem_def)
+
+lemma hull_inc: "x \<in> S \<Longrightarrow> x \<in> P hull S" by (metis hull_subset subset_eq)
+
+lemma hull_union_subset: "(S hull s) \<union> (S hull t) \<subseteq> (S hull (s \<union> t))"
+unfolding Un_subset_iff by (metis hull_mono Un_upper1 Un_upper2)
+
+lemma hull_union: assumes T: "\<And>T. T \<subseteq> S ==> Inter T \<in> S"
+  shows "S hull (s \<union> t) = S hull (S hull s \<union> S hull t)"
+apply rule
+apply (rule hull_mono)
+unfolding Un_subset_iff
+apply (metis hull_subset Un_upper1 Un_upper2 subset_trans)
+apply (rule hull_minimal)
+apply (metis hull_union_subset)
+apply (metis hull_in T)
+done
+
+lemma hull_redundant_eq: "a \<in> (S hull s) \<longleftrightarrow> (S hull (insert a s) = S hull s)"
+  unfolding hull_def by blast
+
+lemma hull_redundant: "a \<in> (S hull s) ==> (S hull (insert a s) = S hull s)"
+by (metis hull_redundant_eq)
+
+text{* Archimedian properties and useful consequences. *}
+
+lemma real_arch_simple: "\<exists>n. x <= real (n::nat)"
+  using reals_Archimedean2[of x] apply auto by (rule_tac x="Suc n" in exI, auto)
+lemmas real_arch_lt = reals_Archimedean2
+
+lemmas real_arch = reals_Archimedean3
+
+lemma real_arch_inv: "0 < e \<longleftrightarrow> (\<exists>n::nat. n \<noteq> 0 \<and> 0 < inverse (real n) \<and> inverse (real n) < e)"
+  using reals_Archimedean
+  apply (auto simp add: field_simps inverse_positive_iff_positive)
+  apply (subgoal_tac "inverse (real n) > 0")
+  apply arith
+  apply simp
+  done
+
+lemma real_pow_lbound: "0 <= x ==> 1 + real n * x <= (1 + x) ^ n"
+proof(induct n)
+  case 0 thus ?case by simp
+next 
+  case (Suc n)
+  hence h: "1 + real n * x \<le> (1 + x) ^ n" by simp
+  from h have p: "1 \<le> (1 + x) ^ n" using Suc.prems by simp
+  from h have "1 + real n * x + x \<le> (1 + x) ^ n + x" by simp
+  also have "\<dots> \<le> (1 + x) ^ Suc n" apply (subst diff_le_0_iff_le[symmetric]) 
+    apply (simp add: ring_simps)
+    using mult_left_mono[OF p Suc.prems] by simp
+  finally show ?case  by (simp add: real_of_nat_Suc ring_simps)
+qed
+
+lemma real_arch_pow: assumes x: "1 < (x::real)" shows "\<exists>n. y < x^n"
+proof-
+  from x have x0: "x - 1 > 0" by arith
+  from real_arch[OF x0, rule_format, of y] 
+  obtain n::nat where n:"y < real n * (x - 1)" by metis
+  from x0 have x00: "x- 1 \<ge> 0" by arith
+  from real_pow_lbound[OF x00, of n] n 
+  have "y < x^n" by auto
+  then show ?thesis by metis
+qed 
+
+lemma real_arch_pow2: "\<exists>n. (x::real) < 2^ n"
+  using real_arch_pow[of 2 x] by simp
+
+lemma real_arch_pow_inv: assumes y: "(y::real) > 0" and x1: "x < 1"
+  shows "\<exists>n. x^n < y"
+proof-
+  {assume x0: "x > 0" 
+    from x0 x1 have ix: "1 < 1/x" by (simp add: field_simps)
+    from real_arch_pow[OF ix, of "1/y"]
+    obtain n where n: "1/y < (1/x)^n" by blast
+    then 
+    have ?thesis using y x0 by (auto simp add: field_simps power_divide) }
+  moreover 
+  {assume "\<not> x > 0" with y x1 have ?thesis apply auto by (rule exI[where x=1], auto)}
+  ultimately show ?thesis by metis
+qed
+
+lemma forall_pos_mono: "(\<And>d e::real. d < e \<Longrightarrow> P d ==> P e) \<Longrightarrow> (\<And>n::nat. n \<noteq> 0 ==> P(inverse(real n))) \<Longrightarrow> (\<And>e. 0 < e ==> P e)"
+  by (metis real_arch_inv)
+
+lemma forall_pos_mono_1: "(\<And>d e::real. d < e \<Longrightarrow> P d ==> P e) \<Longrightarrow> (\<And>n. P(inverse(real (Suc n)))) ==> 0 < e ==> P e"
+  apply (rule forall_pos_mono)
+  apply auto
+  apply (atomize)
+  apply (erule_tac x="n - 1" in allE)
+  apply auto
+  done
+
+lemma real_archimedian_rdiv_eq_0: assumes x0: "x \<ge> 0" and c: "c \<ge> 0" and xc: "\<forall>(m::nat)>0. real m * x \<le> c"
+  shows "x = 0"
+proof-
+  {assume "x \<noteq> 0" with x0 have xp: "x > 0" by arith
+    from real_arch[OF xp, rule_format, of c] obtain n::nat where n: "c < real n * x"  by blast
+    with xc[rule_format, of n] have "n = 0" by arith
+    with n c have False by simp}
+  then show ?thesis by blast
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Relate max and min to sup and inf.                                        *)
+(* ------------------------------------------------------------------------- *)
+
+lemma real_max_rsup: "max x y = rsup {x,y}"
+proof-
+  have f: "finite {x, y}" "{x,y} \<noteq> {}"  by simp_all
+  from rsup_finite_le_iff[OF f, of "max x y"] have "rsup {x,y} \<le> max x y" by simp
+  moreover
+  have "max x y \<le> rsup {x,y}" using rsup_finite_ge_iff[OF f, of "max x y"]
+    by (simp add: linorder_linear)
+  ultimately show ?thesis by arith
+qed 
+
+lemma real_min_rinf: "min x y = rinf {x,y}"
+proof-
+  have f: "finite {x, y}" "{x,y} \<noteq> {}"  by simp_all
+  from rinf_finite_le_iff[OF f, of "min x y"] have "rinf {x,y} \<le> min x y" 
+    by (simp add: linorder_linear)
+  moreover
+  have "min x y \<le> rinf {x,y}" using rinf_finite_ge_iff[OF f, of "min x y"]
+    by simp
+  ultimately show ?thesis by arith
+qed 
+
+(* ------------------------------------------------------------------------- *)
+(* Geometric progression.                                                    *)
+(* ------------------------------------------------------------------------- *)
+
+lemma sum_gp_basic: "((1::'a::{field, recpower}) - x) * setsum (\<lambda>i. x^i) {0 .. n} = (1 - x^(Suc n))"
+  (is "?lhs = ?rhs")
+proof-
+  {assume x1: "x = 1" hence ?thesis by simp}
+  moreover
+  {assume x1: "x\<noteq>1"
+    hence x1': "x - 1 \<noteq> 0" "1 - x \<noteq> 0" "x - 1 = - (1 - x)" "- (1 - x) \<noteq> 0" by auto
+    from geometric_sum[OF x1, of "Suc n", unfolded x1']
+    have "(- (1 - x)) * setsum (\<lambda>i. x^i) {0 .. n} = - (1 - x^(Suc n))"
+      unfolding atLeastLessThanSuc_atLeastAtMost
+      using x1' apply (auto simp only: field_simps)
+      apply (simp add: ring_simps)
+      done
+    then have ?thesis by (simp add: ring_simps) }
+  ultimately show ?thesis by metis
+qed
+
+lemma sum_gp_multiplied: assumes mn: "m <= n"
+  shows "((1::'a::{field, recpower}) - x) * setsum (op ^ x) {m..n} = x^m - x^ Suc n"
+  (is "?lhs = ?rhs")
+proof-
+  let ?S = "{0..(n - m)}"
+  from mn have mn': "n - m \<ge> 0" by arith
+  let ?f = "op + m"
+  have i: "inj_on ?f ?S" unfolding inj_on_def by auto
+  have f: "?f ` ?S = {m..n}" 
+    using mn apply (auto simp add: image_iff Bex_def) by arith
+  have th: "op ^ x o op + m = (\<lambda>i. x^m * x^i)" 
+    by (rule ext, simp add: power_add power_mult)
+  from setsum_reindex[OF i, of "op ^ x", unfolded f th setsum_right_distrib[symmetric]]
+  have "?lhs = x^m * ((1 - x) * setsum (op ^ x) {0..n - m})" by simp
+  then show ?thesis unfolding sum_gp_basic using mn
+    by (simp add: ring_simps power_add[symmetric])
+qed
+
+lemma sum_gp: "setsum (op ^ (x::'a::{field, recpower})) {m .. n} = 
+   (if n < m then 0 else if x = 1 then of_nat ((n + 1) - m) 
+                    else (x^ m - x^ (Suc n)) / (1 - x))"
+proof-
+  {assume nm: "n < m" hence ?thesis by simp}
+  moreover
+  {assume "\<not> n < m" hence nm: "m \<le> n" by arith
+    {assume x: "x = 1"  hence ?thesis by simp}
+    moreover
+    {assume x: "x \<noteq> 1" hence nz: "1 - x \<noteq> 0" by simp
+      from sum_gp_multiplied[OF nm, of x] nz have ?thesis by (simp add: field_simps)}
+    ultimately have ?thesis by metis
+  }
+  ultimately show ?thesis by metis
+qed
+
+lemma sum_gp_offset: "setsum (op ^ (x::'a::{field,recpower})) {m .. m+n} = 
+  (if x = 1 then of_nat n + 1 else x^m * (1 - x^Suc n) / (1 - x))"
+  unfolding sum_gp[of x m "m + n"] power_Suc
+  by (simp add: ring_simps power_add)
+
+
+subsection{* A bit of linear algebra. *}
+
+definition "subspace S \<longleftrightarrow> 0 \<in> S \<and> (\<forall>x\<in> S. \<forall>y \<in>S. x + y \<in> S) \<and> (\<forall>c. \<forall>x \<in>S. c *s x \<in>S )"
+definition "span S = (subspace hull S)"
+definition "dependent S \<longleftrightarrow> (\<exists>a \<in> S. a \<in> span(S - {a}))"
+abbreviation "independent s == ~(dependent s)"
+
+(* Closure properties of subspaces.                                          *)
+
+lemma subspace_UNIV[simp]: "subspace(UNIV)" by (simp add: subspace_def)
+
+lemma subspace_0: "subspace S ==> 0 \<in> S" by (metis subspace_def)
+
+lemma subspace_add: "subspace S \<Longrightarrow> x \<in> S \<Longrightarrow> y \<in> S ==> x + y \<in> S" 
+  by (metis subspace_def)
+
+lemma subspace_mul: "subspace S \<Longrightarrow> x \<in> S \<Longrightarrow> c *s x \<in> S"
+  by (metis subspace_def)
+
+lemma subspace_neg: "subspace S \<Longrightarrow> (x::'a::ring_1^'n) \<in> S \<Longrightarrow> - x \<in> S"
+  by (metis vector_sneg_minus1 subspace_mul)
+
+lemma subspace_sub: "subspace S \<Longrightarrow> (x::'a::ring_1^'n) \<in> S \<Longrightarrow> y \<in> S \<Longrightarrow> x - y \<in> S"
+  by (metis diff_def subspace_add subspace_neg)
+
+lemma subspace_setsum:
+  assumes sA: "subspace A" and fB: "finite B"
+  and f: "\<forall>x\<in> B. f x \<in> A"
+  shows "setsum f B \<in> A"
+  using  fB f sA
+  apply(induct rule: finite_induct[OF fB])
+  by (simp add: subspace_def sA, auto simp add: sA subspace_add) 
+
+lemma subspace_linear_image: 
+  assumes lf: "linear (f::'a::semiring_1^'n \<Rightarrow> _)" and sS: "subspace S" 
+  shows "subspace(f ` S)"
+  using lf sS linear_0[OF lf]
+  unfolding linear_def subspace_def
+  apply (auto simp add: image_iff)
+  apply (rule_tac x="x + y" in bexI, auto)
+  apply (rule_tac x="c*s x" in bexI, auto)
+  done
+
+lemma subspace_linear_preimage: "linear (f::'a::semiring_1^'n \<Rightarrow> _) ==> subspace S ==> subspace {x. f x \<in> S}"
+  by (auto simp add: subspace_def linear_def linear_0[of f])
+
+lemma subspace_trivial: "subspace {0::'a::semiring_1 ^_}"
+  by (simp add: subspace_def)
+
+lemma subspace_inter: "subspace A \<Longrightarrow> subspace B ==> subspace (A \<inter> B)"
+  by (simp add: subspace_def)
+
+
+lemma span_mono: "A \<subseteq> B ==> span A \<subseteq> span B"
+  by (metis span_def hull_mono)
+
+lemma subspace_span: "subspace(span S)"
+  unfolding span_def
+  apply (rule hull_in[unfolded mem_def])
+  apply (simp only: subspace_def Inter_iff Int_iff subset_eq)
+  apply auto
+  apply (erule_tac x="X" in ballE)
+  apply (simp add: mem_def)
+  apply blast
+  apply (erule_tac x="X" in ballE)
+  apply (erule_tac x="X" in ballE)
+  apply (erule_tac x="X" in ballE)
+  apply (clarsimp simp add: mem_def)
+  apply simp
+  apply simp
+  apply simp
+  apply (erule_tac x="X" in ballE)
+  apply (erule_tac x="X" in ballE)
+  apply (simp add: mem_def)
+  apply simp
+  apply simp
+  done
+
+lemma span_clauses:
+  "a \<in> S ==> a \<in> span S"
+  "0 \<in> span S"
+  "x\<in> span S \<Longrightarrow> y \<in> span S ==> x + y \<in> span S"
+  "x \<in> span S \<Longrightarrow> c *s x \<in> span S"
+  by (metis span_def hull_subset subset_eq subspace_span subspace_def)+
+
+lemma span_induct: assumes SP: "\<And>x. x \<in> S ==> P x"
+  and P: "subspace P" and x: "x \<in> span S" shows "P x"
+proof-
+  from SP have SP': "S \<subseteq> P" by (simp add: mem_def subset_eq)
+  from P have P': "P \<in> subspace" by (simp add: mem_def)
+  from x hull_minimal[OF SP' P', unfolded span_def[symmetric]]
+  show "P x" by (metis mem_def subset_eq) 
+qed
+
+lemma span_empty: "span {} = {(0::'a::semiring_0 ^ 'n)}"
+  apply (simp add: span_def)
+  apply (rule hull_unique)
+  apply (auto simp add: mem_def subspace_def)
+  unfolding mem_def[of "0::'a^'n", symmetric]
+  apply simp
+  done
+
+lemma independent_empty: "independent {}"
+  by (simp add: dependent_def)
+
+lemma independent_mono: "independent A \<Longrightarrow> B \<subseteq> A ==> independent B"
+  apply (clarsimp simp add: dependent_def span_mono)
+  apply (subgoal_tac "span (B - {a}) \<le> span (A - {a})")
+  apply force
+  apply (rule span_mono)
+  apply auto
+  done
+
+lemma span_subspace: "A \<subseteq> B \<Longrightarrow> B \<le> span A \<Longrightarrow>  subspace B \<Longrightarrow> span A = B"
+  by (metis order_antisym span_def hull_minimal mem_def)
+
+lemma span_induct': assumes SP: "\<forall>x \<in> S. P x"
+  and P: "subspace P" shows "\<forall>x \<in> span S. P x"
+  using span_induct SP P by blast
+
+inductive span_induct_alt_help for S:: "'a::semiring_1^'n \<Rightarrow> bool"
+  where 
+  span_induct_alt_help_0: "span_induct_alt_help S 0"
+  | span_induct_alt_help_S: "x \<in> S \<Longrightarrow> span_induct_alt_help S z \<Longrightarrow> span_induct_alt_help S (c *s x + z)"
+
+lemma span_induct_alt': 
+  assumes h0: "h (0::'a::semiring_1^'n)" and hS: "\<And>c x y. x \<in> S \<Longrightarrow> h y \<Longrightarrow> h (c*s x + y)" shows "\<forall>x \<in> span S. h x"
+proof-
+  {fix x:: "'a^'n" assume x: "span_induct_alt_help S x"
+    have "h x"
+      apply (rule span_induct_alt_help.induct[OF x])
+      apply (rule h0)
+      apply (rule hS, assumption, assumption)
+      done}
+  note th0 = this
+  {fix x assume x: "x \<in> span S"
+    
+    have "span_induct_alt_help S x"
+      proof(rule span_induct[where x=x and S=S])
+	show "x \<in> span S" using x .
+      next
+	fix x assume xS : "x \<in> S"
+	  from span_induct_alt_help_S[OF xS span_induct_alt_help_0, of 1]
+	  show "span_induct_alt_help S x" by simp
+	next
+	have "span_induct_alt_help S 0" by (rule span_induct_alt_help_0)
+	moreover
+	{fix x y assume h: "span_induct_alt_help S x" "span_induct_alt_help S y"
+	  from h 
+	  have "span_induct_alt_help S (x + y)"
+	    apply (induct rule: span_induct_alt_help.induct)
+	    apply simp
+	    unfolding add_assoc
+	    apply (rule span_induct_alt_help_S)
+	    apply assumption
+	    apply simp
+	    done}
+	moreover
+	{fix c x assume xt: "span_induct_alt_help S x"
+	  then have "span_induct_alt_help S (c*s x)" 
+	    apply (induct rule: span_induct_alt_help.induct)
+	    apply (simp add: span_induct_alt_help_0)
+	    apply (simp add: vector_smult_assoc vector_add_ldistrib)
+	    apply (rule span_induct_alt_help_S)
+	    apply assumption
+	    apply simp
+	    done
+	}
+	ultimately show "subspace (span_induct_alt_help S)" 
+	  unfolding subspace_def mem_def Ball_def by blast
+      qed}
+  with th0 show ?thesis by blast
+qed 
+
+lemma span_induct_alt: 
+  assumes h0: "h (0::'a::semiring_1^'n)" and hS: "\<And>c x y. x \<in> S \<Longrightarrow> h y \<Longrightarrow> h (c*s x + y)" and x: "x \<in> span S"
+  shows "h x"
+using span_induct_alt'[of h S] h0 hS x by blast
+
+(* Individual closure properties. *)
+
+lemma span_superset: "x \<in> S ==> x \<in> span S" by (metis span_clauses)
+
+lemma span_0: "0 \<in> span S" by (metis subspace_span subspace_0)
+
+lemma span_add: "x \<in> span S \<Longrightarrow> y \<in> span S ==> x + y \<in> span S"
+  by (metis subspace_add subspace_span)
+
+lemma span_mul: "x \<in> span S ==> (c *s x) \<in> span S"
+  by (metis subspace_span subspace_mul)
+
+lemma span_neg: "x \<in> span S ==> - (x::'a::ring_1^'n) \<in> span S"
+  by (metis subspace_neg subspace_span)
+
+lemma span_sub: "(x::'a::ring_1^'n) \<in> span S \<Longrightarrow> y \<in> span S ==> x - y \<in> span S"
+  by (metis subspace_span subspace_sub)
+
+lemma span_setsum: "finite A \<Longrightarrow> \<forall>x \<in> A. f x \<in> span S ==> setsum f A \<in> span S"
+  apply (rule subspace_setsum)
+  by (metis subspace_span subspace_setsum)+
+
+lemma span_add_eq: "(x::'a::ring_1^'n) \<in> span S \<Longrightarrow> x + y \<in> span S \<longleftrightarrow> y \<in> span S"
+  apply (auto simp only: span_add span_sub)
+  apply (subgoal_tac "(x + y) - x \<in> span S", simp)
+  by (simp only: span_add span_sub)
+
+(* Mapping under linear image. *)
+
+lemma span_linear_image: assumes lf: "linear (f::'a::semiring_1 ^ 'n => _)"
+  shows "span (f ` S) = f ` (span S)"
+proof-
+  {fix x
+    assume x: "x \<in> span (f ` S)"
+    have "x \<in> f ` span S"
+      apply (rule span_induct[where x=x and S = "f ` S"])
+      apply (clarsimp simp add: image_iff)
+      apply (frule span_superset)
+      apply blast
+      apply (simp only: mem_def)
+      apply (rule subspace_linear_image[OF lf])
+      apply (rule subspace_span)
+      apply (rule x)
+      done}
+  moreover 
+  {fix x assume x: "x \<in> span S"
+    have th0:"(\<lambda>a. f a \<in> span (f ` S)) = {x. f x \<in> span (f ` S)}" apply (rule set_ext) 
+      unfolding mem_def Collect_def ..
+    have "f x \<in> span (f ` S)"
+      apply (rule span_induct[where S=S])
+      apply (rule span_superset)
+      apply simp
+      apply (subst th0)
+      apply (rule subspace_linear_preimage[OF lf subspace_span, of "f ` S"])
+      apply (rule x)
+      done}
+  ultimately show ?thesis by blast
+qed
+
+(* The key breakdown property. *)
+
+lemma span_breakdown:
+  assumes bS: "(b::'a::ring_1 ^ 'n) \<in> S" and aS: "a \<in> span S"
+  shows "\<exists>k. a - k*s b \<in> span (S - {b})" (is "?P a")
+proof-
+  {fix x assume xS: "x \<in> S"
+    {assume ab: "x = b"
+      then have "?P x"
+	apply simp
+	apply (rule exI[where x="1"], simp)
+	by (rule span_0)}
+    moreover
+    {assume ab: "x \<noteq> b" 
+      then have "?P x"  using xS
+	apply -
+	apply (rule exI[where x=0])
+	apply (rule span_superset)
+	by simp}
+    ultimately have "?P x" by blast}
+  moreover have "subspace ?P" 
+    unfolding subspace_def 
+    apply auto
+    apply (simp add: mem_def)
+    apply (rule exI[where x=0])
+    using span_0[of "S - {b}"]
+    apply (simp add: mem_def)
+    apply (clarsimp simp add: mem_def)
+    apply (rule_tac x="k + ka" in exI)
+    apply (subgoal_tac "x + y - (k + ka) *s b = (x - k*s b) + (y - ka *s b)")
+    apply (simp only: )
+    apply (rule span_add[unfolded mem_def])
+    apply assumption+
+    apply (vector ring_simps)
+    apply (clarsimp simp add: mem_def)
+    apply (rule_tac x= "c*k" in exI)
+    apply (subgoal_tac "c *s x - (c * k) *s b = c*s (x - k*s b)")
+    apply (simp only: )
+    apply (rule span_mul[unfolded mem_def])
+    apply assumption
+    by (vector ring_simps)
+  ultimately show "?P a" using aS span_induct[where S=S and P= "?P"] by metis 
+qed
+
+lemma span_breakdown_eq:
+  "(x::'a::ring_1^'n) \<in> span (insert a S) \<longleftrightarrow> (\<exists>k. (x - k *s a) \<in> span S)" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume x: "x \<in> span (insert a S)"
+    from x span_breakdown[of "a" "insert a S" "x"]
+    have ?rhs apply clarsimp
+      apply (rule_tac x= "k" in exI)
+      apply (rule set_rev_mp[of _ "span (S - {a})" _])
+      apply assumption
+      apply (rule span_mono)      
+      apply blast
+      done}
+  moreover
+  { fix k assume k: "x - k *s a \<in> span S"
+    have eq: "x = (x - k *s a) + k *s a" by vector
+    have "(x - k *s a) + k *s a \<in> span (insert a S)"
+      apply (rule span_add)
+      apply (rule set_rev_mp[of _ "span S" _])
+      apply (rule k)
+      apply (rule span_mono)      
+      apply blast
+      apply (rule span_mul)
+      apply (rule span_superset)
+      apply blast
+      done
+    then have ?lhs using eq by metis}
+  ultimately show ?thesis by blast
+qed
+
+(* Hence some "reversal" results.*)
+
+lemma in_span_insert:
+  assumes a: "(a::'a::field^'n) \<in> span (insert b S)" and na: "a \<notin> span S"
+  shows "b \<in> span (insert a S)"
+proof-
+  from span_breakdown[of b "insert b S" a, OF insertI1 a]
+  obtain k where k: "a - k*s b \<in> span (S - {b})" by auto
+  {assume k0: "k = 0"
+    with k have "a \<in> span S"
+      apply (simp)
+      apply (rule set_rev_mp)
+      apply assumption
+      apply (rule span_mono)
+      apply blast
+      done
+    with na  have ?thesis by blast}
+  moreover
+  {assume k0: "k \<noteq> 0" 
+    have eq: "b = (1/k) *s a - ((1/k) *s a - b)" by vector
+    from k0 have eq': "(1/k) *s (a - k*s b) = (1/k) *s a - b"
+      by (vector field_simps)
+    from k have "(1/k) *s (a - k*s b) \<in> span (S - {b})"
+      by (rule span_mul)
+    hence th: "(1/k) *s a - b \<in> span (S - {b})"
+      unfolding eq' .
+
+    from k
+    have ?thesis
+      apply (subst eq)
+      apply (rule span_sub)
+      apply (rule span_mul)
+      apply (rule span_superset)
+      apply blast
+      apply (rule set_rev_mp)
+      apply (rule th)
+      apply (rule span_mono)
+      using na by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma in_span_delete: 
+  assumes a: "(a::'a::field^'n) \<in> span S" 
+  and na: "a \<notin> span (S-{b})"
+  shows "b \<in> span (insert a (S - {b}))"
+  apply (rule in_span_insert)
+  apply (rule set_rev_mp)
+  apply (rule a)
+  apply (rule span_mono)
+  apply blast
+  apply (rule na)
+  done
+
+(* Transitivity property. *)
+
+lemma span_trans:
+  assumes x: "(x::'a::ring_1^'n) \<in> span S" and y: "y \<in> span (insert x S)"
+  shows "y \<in> span S"
+proof-
+  from span_breakdown[of x "insert x S" y, OF insertI1 y]
+  obtain k where k: "y -k*s x \<in> span (S - {x})" by auto
+  have eq: "y = (y - k *s x) + k *s x" by vector
+  show ?thesis 
+    apply (subst eq)
+    apply (rule span_add)
+    apply (rule set_rev_mp)
+    apply (rule k)
+    apply (rule span_mono)
+    apply blast
+    apply (rule span_mul)
+    by (rule x)
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* An explicit expansion is sometimes needed.                                *)
+(* ------------------------------------------------------------------------- *)
+
+lemma span_explicit:
+  "span P = {y::'a::semiring_1^'n. \<exists>S u. finite S \<and> S \<subseteq> P \<and> setsum (\<lambda>v. u v *s v) S = y}"
+  (is "_ = ?E" is "_ = {y. ?h y}" is "_ = {y. \<exists>S u. ?Q S u y}")
+proof-
+  {fix x assume x: "x \<in> ?E"
+    then obtain S u where fS: "finite S" and SP: "S\<subseteq>P" and u: "setsum (\<lambda>v. u v *s v) S = x"
+      by blast
+    have "x \<in> span P"
+      unfolding u[symmetric]
+      apply (rule span_setsum[OF fS])
+      using span_mono[OF SP]
+      by (auto intro: span_superset span_mul)}
+  moreover
+  have "\<forall>x \<in> span P. x \<in> ?E"
+    unfolding mem_def Collect_def
+  proof(rule span_induct_alt')
+    show "?h 0"
+      apply (rule exI[where x="{}"]) by simp
+  next
+    fix c x y
+    assume x: "x \<in> P" and hy: "?h y"
+    from hy obtain S u where fS: "finite S" and SP: "S\<subseteq>P" 
+      and u: "setsum (\<lambda>v. u v *s v) S = y" by blast
+    let ?S = "insert x S"
+    let ?u = "\<lambda>y. if y = x then (if x \<in> S then u y + c else c)
+                  else u y"
+    from fS SP x have th0: "finite (insert x S)" "insert x S \<subseteq> P" by blast+
+    {assume xS: "x \<in> S"
+      have S1: "S = (S - {x}) \<union> {x}" 
+	and Sss:"finite (S - {x})" "finite {x}" "(S -{x}) \<inter> {x} = {}" using xS fS by auto
+      have "setsum (\<lambda>v. ?u v *s v) ?S =(\<Sum>v\<in>S - {x}. u v *s v) + (u x + c) *s x"
+	using xS 
+	by (simp add: setsum_Un_disjoint[OF Sss, unfolded S1[symmetric]] 
+	  setsum_clauses(2)[OF fS] cong del: if_weak_cong)
+      also have "\<dots> = (\<Sum>v\<in>S. u v *s v) + c *s x"
+	apply (simp add: setsum_Un_disjoint[OF Sss, unfolded S1[symmetric]])
+	by (vector ring_simps)
+      also have "\<dots> = c*s x + y"
+	by (simp add: add_commute u)
+      finally have "setsum (\<lambda>v. ?u v *s v) ?S = c*s x + y" .
+    then have "?Q ?S ?u (c*s x + y)" using th0 by blast}
+  moreover 
+  {assume xS: "x \<notin> S"
+    have th00: "(\<Sum>v\<in>S. (if v = x then c else u v) *s v) = y"
+      unfolding u[symmetric]
+      apply (rule setsum_cong2)
+      using xS by auto
+    have "?Q ?S ?u (c*s x + y)" using fS xS th0
+      by (simp add: th00 setsum_clauses add_commute cong del: if_weak_cong)}
+  ultimately have "?Q ?S ?u (c*s x + y)"
+    by (cases "x \<in> S", simp, simp)
+    then show "?h (c*s x + y)" 
+      apply -
+      apply (rule exI[where x="?S"])
+      apply (rule exI[where x="?u"]) by metis
+  qed
+  ultimately show ?thesis by blast
+qed
+
+lemma dependent_explicit:
+  "dependent P \<longleftrightarrow> (\<exists>S u. finite S \<and> S \<subseteq> P \<and> (\<exists>(v::'a::{idom,field}^'n) \<in>S. u v \<noteq> 0 \<and> setsum (\<lambda>v. u v *s v) S = 0))" (is "?lhs = ?rhs")
+proof-
+  {assume dP: "dependent P"
+    then obtain a S u where aP: "a \<in> P" and fS: "finite S" 
+      and SP: "S \<subseteq> P - {a}" and ua: "setsum (\<lambda>v. u v *s v) S = a" 
+      unfolding dependent_def span_explicit by blast
+    let ?S = "insert a S" 
+    let ?u = "\<lambda>y. if y = a then - 1 else u y" 
+    let ?v = a
+    from aP SP have aS: "a \<notin> S" by blast
+    from fS SP aP have th0: "finite ?S" "?S \<subseteq> P" "?v \<in> ?S" "?u ?v \<noteq> 0" by auto
+    have s0: "setsum (\<lambda>v. ?u v *s v) ?S = 0"
+      using fS aS
+      apply (simp add: vector_smult_lneg vector_smult_lid setsum_clauses ring_simps )
+      apply (subst (2) ua[symmetric])
+      apply (rule setsum_cong2)
+      by auto
+    with th0 have ?rhs
+      apply -
+      apply (rule exI[where x= "?S"])
+      apply (rule exI[where x= "?u"])
+      by clarsimp}
+  moreover
+  {fix S u v assume fS: "finite S" 
+      and SP: "S \<subseteq> P" and vS: "v \<in> S" and uv: "u v \<noteq> 0" 
+    and u: "setsum (\<lambda>v. u v *s v) S = 0"
+    let ?a = v 
+    let ?S = "S - {v}"
+    let ?u = "\<lambda>i. (- u i) / u v"
+    have th0: "?a \<in> P" "finite ?S" "?S \<subseteq> P"       using fS SP vS by auto 
+    have "setsum (\<lambda>v. ?u v *s v) ?S = setsum (\<lambda>v. (- (inverse (u ?a))) *s (u v *s v)) S - ?u v *s v"
+      using fS vS uv 
+      by (simp add: setsum_diff1 vector_smult_lneg divide_inverse 
+	vector_smult_assoc field_simps)
+    also have "\<dots> = ?a"
+      unfolding setsum_cmul u
+      using uv by (simp add: vector_smult_lneg)
+    finally  have "setsum (\<lambda>v. ?u v *s v) ?S = ?a" .
+    with th0 have ?lhs
+      unfolding dependent_def span_explicit
+      apply -
+      apply (rule bexI[where x= "?a"])
+      apply simp_all
+      apply (rule exI[where x= "?S"])
+      by auto}
+  ultimately show ?thesis by blast
+qed
+
+
+lemma span_finite:
+  assumes fS: "finite S"
+  shows "span S = {(y::'a::semiring_1^'n). \<exists>u. setsum (\<lambda>v. u v *s v) S = y}"
+  (is "_ = ?rhs")
+proof-
+  {fix y assume y: "y \<in> span S"
+    from y obtain S' u where fS': "finite S'" and SS': "S' \<subseteq> S" and 
+      u: "setsum (\<lambda>v. u v *s v) S' = y" unfolding span_explicit by blast
+    let ?u = "\<lambda>x. if x \<in> S' then u x else 0"
+    from setsum_restrict_set[OF fS, of "\<lambda>v. u v *s v" S', symmetric] SS'
+    have "setsum (\<lambda>v. ?u v *s v) S = setsum (\<lambda>v. u v *s v) S'"
+      unfolding cond_value_iff cond_application_beta
+      apply (simp add: cond_value_iff cong del: if_weak_cong)
+      apply (rule setsum_cong)
+      apply auto
+      done
+    hence "setsum (\<lambda>v. ?u v *s v) S = y" by (metis u)
+    hence "y \<in> ?rhs" by auto}
+  moreover 
+  {fix y u assume u: "setsum (\<lambda>v. u v *s v) S = y"
+    then have "y \<in> span S" using fS unfolding span_explicit by auto}
+  ultimately show ?thesis by blast
+qed
+
+
+(* Standard bases are a spanning set, and obviously finite.                  *)
+
+lemma span_stdbasis:"span {basis i :: 'a::ring_1^'n | i. i \<in> {1 .. dimindex(UNIV :: 'n set)}} = UNIV"
+apply (rule set_ext)
+apply auto
+apply (subst basis_expansion[symmetric])
+apply (rule span_setsum)
+apply simp
+apply auto
+apply (rule span_mul)
+apply (rule span_superset)
+apply (auto simp add: Collect_def mem_def)
+done
+
+  
+lemma has_size_stdbasis: "{basis i ::real ^'n | i. i \<in> {1 .. dimindex (UNIV :: 'n set)}} hassize (dimindex(UNIV :: 'n set))" (is "?S hassize ?n")
+proof-
+  have eq: "?S = basis ` {1 .. ?n}" by blast
+  show ?thesis unfolding eq
+    apply (rule hassize_image_inj[OF basis_inj])
+    by (simp add: hassize_def)
+qed
+
+lemma finite_stdbasis: "finite {basis i ::real^'n |i. i\<in> {1 .. dimindex(UNIV:: 'n set)}}"
+  using has_size_stdbasis[unfolded hassize_def]
+  ..
+
+lemma card_stdbasis: "card {basis i ::real^'n |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}} = dimindex(UNIV :: 'n set)"
+  using has_size_stdbasis[unfolded hassize_def]
+  ..
+
+lemma independent_stdbasis_lemma:
+  assumes x: "(x::'a::semiring_1 ^ 'n) \<in> span (basis ` S)"
+  and i: "i \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  and iS: "i \<notin> S"
+  shows "(x$i) = 0"
+proof-
+  let ?n = "dimindex (UNIV :: 'n set)"
+  let ?U = "{1 .. ?n}"
+  let ?B = "basis ` S"
+  let ?P = "\<lambda>(x::'a^'n). \<forall>i\<in> ?U. i \<notin> S \<longrightarrow> x$i =0"
+ {fix x::"'a^'n" assume xS: "x\<in> ?B"
+   from xS have "?P x" by (auto simp add: basis_component)}
+ moreover
+ have "subspace ?P" 
+   by (auto simp add: subspace_def Collect_def mem_def zero_index vector_component)
+ ultimately show ?thesis
+   using x span_induct[of ?B ?P x] i iS by blast 
+qed
+
+lemma independent_stdbasis: "independent {basis i ::real^'n |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}}"
+proof-
+  let ?n = "dimindex (UNIV :: 'n set)"
+  let ?I = "{1 .. ?n}"
+  let ?b = "basis :: nat \<Rightarrow> real ^'n"
+  let ?B = "?b ` ?I"
+  have eq: "{?b i|i. i \<in> ?I} = ?B"
+    by auto
+  {assume d: "dependent ?B"
+    then obtain k where k: "k \<in> ?I" "?b k \<in> span (?B - {?b k})"
+      unfolding dependent_def by auto
+    have eq1: "?B - {?b k} = ?B - ?b ` {k}"  by simp
+    have eq2: "?B - {?b k} = ?b ` (?I - {k})"
+      unfolding eq1
+      apply (rule inj_on_image_set_diff[symmetric])
+      apply (rule basis_inj) using k(1) by auto
+    from k(2) have th0: "?b k \<in> span (?b ` (?I - {k}))" unfolding eq2 .
+    from independent_stdbasis_lemma[OF th0 k(1), simplified]
+    have False by (simp add: basis_component[OF k(1), of k])}
+  then show ?thesis unfolding eq dependent_def ..
+qed
+
+(* This is useful for building a basis step-by-step.                         *)
+
+lemma independent_insert:
+  "independent(insert (a::'a::field ^'n) S) \<longleftrightarrow>
+      (if a \<in> S then independent S
+                else independent S \<and> a \<notin> span S)" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume aS: "a \<in> S"
+    hence ?thesis using insert_absorb[OF aS] by simp}
+  moreover
+  {assume aS: "a \<notin> S"
+    {assume i: ?lhs
+      then have ?rhs using aS
+	apply simp
+	apply (rule conjI)
+	apply (rule independent_mono)
+	apply assumption
+	apply blast
+	by (simp add: dependent_def)}
+    moreover 
+    {assume i: ?rhs
+      have ?lhs using i aS
+	apply simp
+	apply (auto simp add: dependent_def)
+	apply (case_tac "aa = a", auto)
+	apply (subgoal_tac "insert a S - {aa} = insert a (S - {aa})")
+	apply simp
+	apply (subgoal_tac "a \<in> span (insert aa (S - {aa}))")
+	apply (subgoal_tac "insert aa (S - {aa}) = S")
+	apply simp
+	apply blast
+	apply (rule in_span_insert)
+	apply assumption
+	apply blast
+	apply blast
+	done}
+    ultimately have ?thesis by blast}
+  ultimately show ?thesis by blast
+qed
+
+(* The degenerate case of the Exchange Lemma.  *)
+
+lemma mem_delete: "x \<in> (A - {a}) \<longleftrightarrow> x \<noteq> a \<and> x \<in> A"
+  by blast
+
+lemma span_span: "span (span A) = span A"
+  unfolding span_def hull_hull ..
+
+lemma span_inc: "S \<subseteq> span S"
+  by (metis subset_eq span_superset)
+
+lemma spanning_subset_independent:
+  assumes BA: "B \<subseteq> A" and iA: "independent (A::('a::field ^'n) set)" 
+  and AsB: "A \<subseteq> span B"
+  shows "A = B"
+proof
+  from BA show "B \<subseteq> A" .
+next
+  from span_mono[OF BA] span_mono[OF AsB]
+  have sAB: "span A = span B" unfolding span_span by blast
+
+  {fix x assume x: "x \<in> A"
+    from iA have th0: "x \<notin> span (A - {x})"
+      unfolding dependent_def using x by blast
+    from x have xsA: "x \<in> span A" by (blast intro: span_superset)
+    have "A - {x} \<subseteq> A" by blast
+    hence th1:"span (A - {x}) \<subseteq> span A" by (metis span_mono)
+    {assume xB: "x \<notin> B"
+      from xB BA have "B \<subseteq> A -{x}" by blast
+      hence "span B \<subseteq> span (A - {x})" by (metis span_mono)
+      with th1 th0 sAB have "x \<notin> span A" by blast
+      with x have False by (metis span_superset)}
+    then have "x \<in> B" by blast}
+  then show "A \<subseteq> B" by blast
+qed
+
+(* The general case of the Exchange Lemma, the key to what follows.  *)
+
+lemma exchange_lemma:
+  assumes f:"finite (t:: ('a::field^'n) set)" and i: "independent s"
+  and sp:"s \<subseteq> span t" 
+  shows "\<exists>t'. (t' hassize card t) \<and> s \<subseteq> t' \<and> t' \<subseteq> s \<union> t \<and> s \<subseteq> span t'"
+using f i sp
+proof(induct c\<equiv>"card(t - s)" arbitrary: s t rule: nat_less_induct)
+  fix n:: nat and s t :: "('a ^'n) set"
+  assume H: " \<forall>m<n. \<forall>(x:: ('a ^'n) set) xa.
+                finite xa \<longrightarrow>
+                independent x \<longrightarrow>
+                x \<subseteq> span xa \<longrightarrow>
+                m = card (xa - x) \<longrightarrow>
+                (\<exists>t'. (t' hassize card xa) \<and>
+                      x \<subseteq> t' \<and> t' \<subseteq> x \<union> xa \<and> x \<subseteq> span t')"
+    and ft: "finite t" and s: "independent s" and sp: "s \<subseteq> span t"
+    and n: "n = card (t - s)"
+  let ?P = "\<lambda>t'. (t' hassize card t) \<and> s \<subseteq> t' \<and> t' \<subseteq> s \<union> t \<and> s \<subseteq> span t'"
+  let ?ths = "\<exists>t'. ?P t'" 
+  {assume st: "s \<subseteq> t" 
+    from st ft span_mono[OF st] have ?ths apply - apply (rule exI[where x=t]) 
+      by (auto simp add: hassize_def intro: span_superset)}
+  moreover
+  {assume st: "t \<subseteq> s"
+    
+    from spanning_subset_independent[OF st s sp] 
+      st ft span_mono[OF st] have ?ths apply - apply (rule exI[where x=t]) 
+      by (auto simp add: hassize_def intro: span_superset)}
+  moreover
+  {assume st: "\<not> s \<subseteq> t" "\<not> t \<subseteq> s"
+    from st(2) obtain b where b: "b \<in> t" "b \<notin> s" by blast
+      from b have "t - {b} - s \<subset> t - s" by blast
+      then have cardlt: "card (t - {b} - s) < n" using n ft
+ 	by (auto intro: psubset_card_mono)
+      from b ft have ct0: "card t \<noteq> 0" by auto
+    {assume stb: "s \<subseteq> span(t -{b})"
+      from ft have ftb: "finite (t -{b})" by auto
+      from H[rule_format, OF cardlt ftb s stb] 
+      obtain u where u: "u hassize card (t-{b})" "s \<subseteq> u" "u \<subseteq> s \<union> (t - {b})" "s \<subseteq> span u" by blast
+      let ?w = "insert b u"
+      have th0: "s \<subseteq> insert b u" using u by blast
+      from u(3) b have "u \<subseteq> s \<union> t" by blast 
+      then have th1: "insert b u \<subseteq> s \<union> t" using u b by blast
+      have bu: "b \<notin> u" using b u by blast
+      from u(1) have fu: "finite u" by (simp add: hassize_def)
+      from u(1) ft b have "u hassize (card t - 1)" by auto
+      then 
+      have th2: "insert b u hassize card t" 
+	using  card_insert_disjoint[OF fu bu] ct0 by (auto simp add: hassize_def)
+      from u(4) have "s \<subseteq> span u" .
+      also have "\<dots> \<subseteq> span (insert b u)" apply (rule span_mono) by blast
+      finally have th3: "s \<subseteq> span (insert b u)" .      from th0 th1 th2 th3 have th: "?P ?w"  by blast
+      from th have ?ths by blast}
+    moreover
+    {assume stb: "\<not> s \<subseteq> span(t -{b})" 
+      from stb obtain a where a: "a \<in> s" "a \<notin> span (t - {b})" by blast
+      have ab: "a \<noteq> b" using a b by blast
+      have at: "a \<notin> t" using a ab span_superset[of a "t- {b}"] by auto
+      have mlt: "card ((insert a (t - {b})) - s) < n" 
+	using cardlt ft n  a b by auto
+      have ft': "finite (insert a (t - {b}))" using ft by auto
+      {fix x assume xs: "x \<in> s"
+	have t: "t \<subseteq> (insert b (insert a (t -{b})))" using b by auto
+	from b(1) have "b \<in> span t" by (simp add: span_superset)
+	have bs: "b \<in> span (insert a (t - {b}))"
+	  by (metis in_span_delete a sp mem_def subset_eq)
+	from xs sp have "x \<in> span t" by blast
+	with span_mono[OF t]
+	have x: "x \<in> span (insert b (insert a (t - {b})))" ..
+	from span_trans[OF bs x] have "x \<in> span (insert a (t - {b}))"  .}
+      then have sp': "s \<subseteq> span (insert a (t - {b}))" by blast
+      
+      from H[rule_format, OF mlt ft' s sp' refl] obtain u where 
+	u: "u hassize card (insert a (t -{b}))" "s \<subseteq> u" "u \<subseteq> s \<union> insert a (t -{b})"
+	"s \<subseteq> span u" by blast
+      from u a b ft at ct0 have "?P u" by (auto simp add: hassize_def)
+      then have ?ths by blast }
+    ultimately have ?ths by blast
+  }
+  ultimately 
+  show ?ths  by blast
+qed
+
+(* This implies corresponding size bounds.                                   *)
+
+lemma independent_span_bound:
+  assumes f: "finite t" and i: "independent (s::('a::field^'n) set)" and sp:"s \<subseteq> span t"
+  shows "finite s \<and> card s \<le> card t"
+  by (metis exchange_lemma[OF f i sp] hassize_def finite_subset card_mono)
+
+lemma finite_Atleast_Atmost[simp]: "finite {f x |x. x\<in> {(i::'a::finite_intvl_succ) .. j}}"
+proof-
+  have eq: "{f x |x. x\<in> {i .. j}} = f ` {i .. j}" by auto
+  show ?thesis unfolding eq 
+    apply (rule finite_imageI)
+    apply (rule finite_intvl)
+    done
+qed
+
+lemma finite_Atleast_Atmost_nat[simp]: "finite {f x |x. x\<in> {(i::nat) .. j}}"
+proof-
+  have eq: "{f x |x. x\<in> {i .. j}} = f ` {i .. j}" by auto
+  show ?thesis unfolding eq 
+    apply (rule finite_imageI)
+    apply (rule finite_atLeastAtMost)
+    done
+qed
+
+
+lemma independent_bound:
+  fixes S:: "(real^'n) set"
+  shows "independent S \<Longrightarrow> finite S \<and> card S <= dimindex(UNIV :: 'n set)"
+  apply (subst card_stdbasis[symmetric])
+  apply (rule independent_span_bound)
+  apply (rule finite_Atleast_Atmost_nat)
+  apply assumption
+  unfolding span_stdbasis 
+  apply (rule subset_UNIV)
+  done
+
+lemma dependent_biggerset: "(finite (S::(real ^'n) set) ==> card S > dimindex(UNIV:: 'n set)) ==> dependent S"
+  by (metis independent_bound not_less)
+
+(* Hence we can create a maximal independent subset.                         *)
+
+lemma maximal_independent_subset_extend:
+  assumes sv: "(S::(real^'n) set) \<subseteq> V" and iS: "independent S"
+  shows "\<exists>B. S \<subseteq> B \<and> B \<subseteq> V \<and> independent B \<and> V \<subseteq> span B"
+  using sv iS
+proof(induct d\<equiv> "dimindex (UNIV :: 'n set) - card S" arbitrary: S rule: nat_less_induct)
+  fix n and S:: "(real^'n) set"
+  assume H: "\<forall>m<n. \<forall>S \<subseteq> V. independent S \<longrightarrow> m = dimindex (UNIV::'n set) - card S \<longrightarrow>
+              (\<exists>B. S \<subseteq> B \<and> B \<subseteq> V \<and> independent B \<and> V \<subseteq> span B)"
+    and sv: "S \<subseteq> V" and i: "independent S" and n: "n = dimindex (UNIV :: 'n set) - card S"
+  let ?P = "\<lambda>B. S \<subseteq> B \<and> B \<subseteq> V \<and> independent B \<and> V \<subseteq> span B"
+  let ?ths = "\<exists>x. ?P x"
+  let ?d = "dimindex (UNIV :: 'n set)"
+  {assume "V \<subseteq> span S"
+    then have ?ths  using sv i by blast }
+  moreover
+  {assume VS: "\<not> V \<subseteq> span S"
+    from VS obtain a where a: "a \<in> V" "a \<notin> span S" by blast
+    from a have aS: "a \<notin> S" by (auto simp add: span_superset)
+    have th0: "insert a S \<subseteq> V" using a sv by blast
+    from independent_insert[of a S]  i a 
+    have th1: "independent (insert a S)" by auto
+    have mlt: "?d - card (insert a S) < n" 
+      using aS a n independent_bound[OF th1] dimindex_ge_1[of "UNIV :: 'n set"] 
+      by auto 
+      
+    from H[rule_format, OF mlt th0 th1 refl] 
+    obtain B where B: "insert a S \<subseteq> B" "B \<subseteq> V" "independent B" " V \<subseteq> span B" 
+      by blast
+    from B have "?P B" by auto
+    then have ?ths by blast}
+  ultimately show ?ths by blast
+qed
+
+lemma maximal_independent_subset:
+  "\<exists>(B:: (real ^'n) set). B\<subseteq> V \<and> independent B \<and> V \<subseteq> span B"
+  by (metis maximal_independent_subset_extend[of "{}:: (real ^'n) set"] empty_subsetI independent_empty)
+
+(* Notion of dimension.                                                      *)
+
+definition "dim V = (SOME n. \<exists>B. B \<subseteq> V \<and> independent B \<and> V \<subseteq> span B \<and> (B hassize n))"
+
+lemma basis_exists:  "\<exists>B. (B :: (real ^'n) set) \<subseteq> V \<and> independent B \<and> V \<subseteq> span B \<and> (B hassize dim V)" 
+unfolding dim_def some_eq_ex[of "\<lambda>n. \<exists>B. B \<subseteq> V \<and> independent B \<and> V \<subseteq> span B \<and> (B hassize n)"]
+unfolding hassize_def
+using maximal_independent_subset[of V] independent_bound
+by auto
+
+(* Consequences of independence or spanning for cardinality.                 *)
+
+lemma independent_card_le_dim: "(B::(real ^'n) set) \<subseteq> V \<Longrightarrow> independent B \<Longrightarrow> finite B \<and> card B \<le> dim V"
+by (metis basis_exists[of V] independent_span_bound[where ?'a=real] hassize_def subset_trans)
+
+lemma span_card_ge_dim:  "(B::(real ^'n) set) \<subseteq> V \<Longrightarrow> V \<subseteq> span B \<Longrightarrow> finite B \<Longrightarrow> dim V \<le> card B"
+  by (metis basis_exists[of V] independent_span_bound hassize_def subset_trans)
+
+lemma basis_card_eq_dim:
+  "B \<subseteq> (V:: (real ^'n) set) \<Longrightarrow> V \<subseteq> span B \<Longrightarrow> independent B \<Longrightarrow> finite B \<and> card B = dim V"
+  by (metis order_eq_iff independent_card_le_dim span_card_ge_dim independent_mono)
+
+lemma dim_unique: "(B::(real ^'n) set) \<subseteq> V \<Longrightarrow> V \<subseteq> span B \<Longrightarrow> independent B \<Longrightarrow> B hassize n \<Longrightarrow> dim V = n"
+  by (metis basis_card_eq_dim hassize_def)
+
+(* More lemmas about dimension.                                              *)
+
+lemma dim_univ: "dim (UNIV :: (real^'n) set) = dimindex (UNIV :: 'n set)"
+  apply (rule dim_unique[of "{basis i |i. i\<in> {1 .. dimindex (UNIV :: 'n set)}}"])
+  by (auto simp only: span_stdbasis has_size_stdbasis independent_stdbasis)
+
+lemma dim_subset:
+  "(S:: (real ^'n) set) \<subseteq> T \<Longrightarrow> dim S \<le> dim T"
+  using basis_exists[of T] basis_exists[of S]
+  by (metis independent_span_bound[where ?'a = real and ?'n = 'n] subset_eq hassize_def)
+
+lemma dim_subset_univ: "dim (S:: (real^'n) set) \<le> dimindex (UNIV :: 'n set)"
+  by (metis dim_subset subset_UNIV dim_univ)
+
+(* Converses to those.                                                       *)
+
+lemma card_ge_dim_independent:
+  assumes BV:"(B::(real ^'n) set) \<subseteq> V" and iB:"independent B" and dVB:"dim V \<le> card B"
+  shows "V \<subseteq> span B"
+proof-
+  {fix a assume aV: "a \<in> V"
+    {assume aB: "a \<notin> span B"
+      then have iaB: "independent (insert a B)" using iB aV  BV by (simp add: independent_insert)
+      from aV BV have th0: "insert a B \<subseteq> V" by blast
+      from aB have "a \<notin>B" by (auto simp add: span_superset)
+      with independent_card_le_dim[OF th0 iaB] dVB  have False by auto}
+    then have "a \<in> span B"  by blast}
+  then show ?thesis by blast
+qed
+
+lemma card_le_dim_spanning:
+  assumes BV: "(B:: (real ^'n) set) \<subseteq> V" and VB: "V \<subseteq> span B" 
+  and fB: "finite B" and dVB: "dim V \<ge> card B"
+  shows "independent B"
+proof-
+  {fix a assume a: "a \<in> B" "a \<in> span (B -{a})"
+    from a fB have c0: "card B \<noteq> 0" by auto
+    from a fB have cb: "card (B -{a}) = card B - 1" by auto
+    from BV a have th0: "B -{a} \<subseteq> V" by blast
+    {fix x assume x: "x \<in> V"
+      from a have eq: "insert a (B -{a}) = B" by blast
+      from x VB have x': "x \<in> span B" by blast 
+      from span_trans[OF a(2), unfolded eq, OF x']
+      have "x \<in> span (B -{a})" . }
+    then have th1: "V \<subseteq> span (B -{a})" by blast 
+    have th2: "finite (B -{a})" using fB by auto
+    from span_card_ge_dim[OF th0 th1 th2]
+    have c: "dim V \<le> card (B -{a})" .
+    from c c0 dVB cb have False by simp}
+  then show ?thesis unfolding dependent_def by blast
+qed
+
+lemma card_eq_dim: "(B:: (real ^'n) set) \<subseteq> V \<Longrightarrow> B hassize dim V \<Longrightarrow> independent B \<longleftrightarrow> V \<subseteq> span B"
+  by (metis hassize_def order_eq_iff card_le_dim_spanning 
+    card_ge_dim_independent)
+
+(* ------------------------------------------------------------------------- *)
+(* More general size bound lemmas.                                           *)
+(* ------------------------------------------------------------------------- *)
+
+lemma independent_bound_general:
+  "independent (S:: (real^'n) set) \<Longrightarrow> finite S \<and> card S \<le> dim S"
+  by (metis independent_card_le_dim independent_bound subset_refl)
+
+lemma dependent_biggerset_general: "(finite (S:: (real^'n) set) \<Longrightarrow> card S > dim S) \<Longrightarrow> dependent S"
+  using independent_bound_general[of S] by (metis linorder_not_le) 
+
+lemma dim_span: "dim (span (S:: (real ^'n) set)) = dim S"
+proof-
+  have th0: "dim S \<le> dim (span S)" 
+    by (auto simp add: subset_eq intro: dim_subset span_superset)
+  from basis_exists[of S] 
+  obtain B where B: "B \<subseteq> S" "independent B" "S \<subseteq> span B" "B hassize dim S" by blast
+  from B have fB: "finite B" "card B = dim S" unfolding hassize_def by blast+
+  have bSS: "B \<subseteq> span S" using B(1) by (metis subset_eq span_inc) 
+  have sssB: "span S \<subseteq> span B" using span_mono[OF B(3)] by (simp add: span_span) 
+  from span_card_ge_dim[OF bSS sssB fB(1)] th0 show ?thesis 
+    using fB(2)  by arith
+qed
+
+lemma subset_le_dim: "(S:: (real ^'n) set) \<subseteq> span T \<Longrightarrow> dim S \<le> dim T"
+  by (metis dim_span dim_subset)
+
+lemma span_eq_dim: "span (S:: (real ^'n) set) = span T ==> dim S = dim T"
+  by (metis dim_span)
+
+lemma spans_image:
+  assumes lf: "linear (f::'a::semiring_1^'n \<Rightarrow> _)" and VB: "V \<subseteq> span B"
+  shows "f ` V \<subseteq> span (f ` B)"
+  unfolding span_linear_image[OF lf]
+  by (metis VB image_mono)
+
+lemma dim_image_le: assumes lf: "linear f" shows "dim (f ` S) \<le> dim (S:: (real ^'n) set)"
+proof-
+  from basis_exists[of S] obtain B where 
+    B: "B \<subseteq> S" "independent B" "S \<subseteq> span B" "B hassize dim S" by blast
+  from B have fB: "finite B" "card B = dim S" unfolding hassize_def by blast+
+  have "dim (f ` S) \<le> card (f ` B)"
+    apply (rule span_card_ge_dim)
+    using lf B fB by (auto simp add: span_linear_image spans_image subset_image_iff)
+  also have "\<dots> \<le> dim S" using card_image_le[OF fB(1)] fB by simp
+  finally show ?thesis .
+qed
+
+(* Relation between bases and injectivity/surjectivity of map.               *)
+
+lemma spanning_surjective_image:
+  assumes us: "UNIV \<subseteq> span (S:: ('a::semiring_1 ^'n) set)" 
+  and lf: "linear f" and sf: "surj f"
+  shows "UNIV \<subseteq> span (f ` S)"
+proof-
+  have "UNIV \<subseteq> f ` UNIV" using sf by (auto simp add: surj_def)
+  also have " \<dots> \<subseteq> span (f ` S)" using spans_image[OF lf us] .
+finally show ?thesis .
+qed
+
+lemma independent_injective_image:
+  assumes iS: "independent (S::('a::semiring_1^'n) set)" and lf: "linear f" and fi: "inj f"
+  shows "independent (f ` S)"
+proof-
+  {fix a assume a: "a \<in> S" "f a \<in> span (f ` S - {f a})"
+    have eq: "f ` S - {f a} = f ` (S - {a})" using fi
+      by (auto simp add: inj_on_def)
+    from a have "f a \<in> f ` span (S -{a})"
+      unfolding eq span_linear_image[OF lf, of "S - {a}"]  by blast
+    hence "a \<in> span (S -{a})" using fi by (auto simp add: inj_on_def)
+    with a(1) iS  have False by (simp add: dependent_def) }
+  then show ?thesis unfolding dependent_def by blast
+qed 
+
+(* ------------------------------------------------------------------------- *)
+(* Picking an orthogonal replacement for a spanning set.                     *)
+(* ------------------------------------------------------------------------- *)
+    (* FIXME : Move to some general theory ?*)
+definition "pairwise R S \<longleftrightarrow> (\<forall>x \<in> S. \<forall>y\<in> S. x\<noteq>y \<longrightarrow> R x y)"
+
+lemma vector_sub_project_orthogonal: "(b::'a::ordered_field^'n) \<bullet> (x - ((b \<bullet> x) / (b\<bullet>b)) *s b) = 0"
+  apply (cases "b = 0", simp)
+  apply (simp add: dot_rsub dot_rmult)
+  unfolding times_divide_eq_right[symmetric]
+  by (simp add: field_simps dot_eq_0)
+
+lemma basis_orthogonal:
+  fixes B :: "(real ^'n) set"
+  assumes fB: "finite B"
+  shows "\<exists>C. finite C \<and> card C \<le> card B \<and> span C = span B \<and> pairwise orthogonal C"
+  (is " \<exists>C. ?P B C")
+proof(induct rule: finite_induct[OF fB])
+  case 1 thus ?case apply (rule exI[where x="{}"]) by (auto simp add: pairwise_def)
+next
+  case (2 a B)
+  note fB = `finite B` and aB = `a \<notin> B` 
+  from `\<exists>C. finite C \<and> card C \<le> card B \<and> span C = span B \<and> pairwise orthogonal C` 
+  obtain C where C: "finite C" "card C \<le> card B" 
+    "span C = span B" "pairwise orthogonal C" by blast
+  let ?a = "a - setsum (\<lambda>x. (x\<bullet>a / (x\<bullet>x)) *s x) C"
+  let ?C = "insert ?a C"
+  from C(1) have fC: "finite ?C" by simp
+  from fB aB C(1,2) have cC: "card ?C \<le> card (insert a B)" by (simp add: card_insert_if)
+  {fix x k 
+    have th0: "\<And>(a::'b::comm_ring) b c. a - (b - c) = c + (a - b)" by (simp add: ring_simps)
+    have "x - k *s (a - (\<Sum>x\<in>C. (x \<bullet> a / (x \<bullet> x)) *s x)) \<in> span C \<longleftrightarrow> x - k *s a \<in> span C"
+      apply (simp only: vector_ssub_ldistrib th0)
+      apply (rule span_add_eq)
+      apply (rule span_mul)
+      apply (rule span_setsum[OF C(1)])
+      apply clarify
+      apply (rule span_mul)
+      by (rule span_superset)}
+  then have SC: "span ?C = span (insert a B)"
+    unfolding expand_set_eq span_breakdown_eq C(3)[symmetric] by auto
+  thm pairwise_def 
+  {fix x y assume xC: "x \<in> ?C" and yC: "y \<in> ?C" and xy: "x \<noteq> y"
+    {assume xa: "x = ?a" and ya: "y = ?a" 
+      have "orthogonal x y" using xa ya xy by blast}
+    moreover
+    {assume xa: "x = ?a" and ya: "y \<noteq> ?a" "y \<in> C" 
+      from ya have Cy: "C = insert y (C - {y})" by blast
+      have fth: "finite (C - {y})" using C by simp
+      have "orthogonal x y"
+	using xa ya
+	unfolding orthogonal_def xa dot_lsub dot_rsub diff_eq_0_iff_eq
+	apply simp 
+	apply (subst Cy)
+	using C(1) fth
+	apply (simp only: setsum_clauses)
+	apply (auto simp add: dot_ladd dot_lmult dot_eq_0 dot_sym[of y a] dot_lsum[OF fth])
+	apply (rule setsum_0')
+	apply clarsimp
+	apply (rule C(4)[unfolded pairwise_def orthogonal_def, rule_format])
+	by auto}
+    moreover
+    {assume xa: "x \<noteq> ?a" "x \<in> C" and ya: "y = ?a" 
+      from xa have Cx: "C = insert x (C - {x})" by blast
+      have fth: "finite (C - {x})" using C by simp
+      have "orthogonal x y"
+	using xa ya
+	unfolding orthogonal_def ya dot_rsub dot_lsub diff_eq_0_iff_eq
+	apply simp 
+	apply (subst Cx)
+	using C(1) fth
+	apply (simp only: setsum_clauses)
+	apply (subst dot_sym[of x])
+	apply (auto simp add: dot_radd dot_rmult dot_eq_0 dot_sym[of x a] dot_rsum[OF fth])
+	apply (rule setsum_0')
+	apply clarsimp
+	apply (rule C(4)[unfolded pairwise_def orthogonal_def, rule_format])
+	by auto}
+    moreover
+    {assume xa: "x \<in> C" and ya: "y \<in> C" 
+      have "orthogonal x y" using xa ya xy C(4) unfolding pairwise_def by blast}
+    ultimately have "orthogonal x y" using xC yC by blast}
+  then have CPO: "pairwise orthogonal ?C" unfolding pairwise_def by blast
+  from fC cC SC CPO have "?P (insert a B) ?C" by blast
+  then show ?case by blast 
+qed
+
+lemma orthogonal_basis_exists:
+  fixes V :: "(real ^'n) set"
+  shows "\<exists>B. independent B \<and> B \<subseteq> span V \<and> V \<subseteq> span B \<and> (B hassize dim V) \<and> pairwise orthogonal B"
+proof-
+  from basis_exists[of V] obtain B where B: "B \<subseteq> V" "independent B" "V \<subseteq> span B" "B hassize dim V" by blast
+  from B have fB: "finite B" "card B = dim V" by (simp_all add: hassize_def)
+  from basis_orthogonal[OF fB(1)] obtain C where 
+    C: "finite C" "card C \<le> card B" "span C = span B" "pairwise orthogonal C" by blast
+  from C B 
+  have CSV: "C \<subseteq> span V" by (metis span_inc span_mono subset_trans) 
+  from span_mono[OF B(3)]  C have SVC: "span V \<subseteq> span C" by (simp add: span_span)
+  from card_le_dim_spanning[OF CSV SVC C(1)] C(2,3) fB
+  have iC: "independent C" by (simp add: dim_span) 
+  from C fB have "card C \<le> dim V" by simp
+  moreover have "dim V \<le> card C" using span_card_ge_dim[OF CSV SVC C(1)]
+    by (simp add: dim_span)
+  ultimately have CdV: "C hassize dim V" unfolding hassize_def using C(1) by simp
+  from C B CSV CdV iC show ?thesis by auto 
+qed
+
+lemma span_eq: "span S = span T \<longleftrightarrow> S \<subseteq> span T \<and> T \<subseteq> span S"
+  by (metis set_eq_subset span_mono span_span span_inc)
+
+(* ------------------------------------------------------------------------- *)
+(* Low-dimensional subset is in a hyperplane (weak orthogonal complement).   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma span_not_univ_orthogonal:
+  assumes sU: "span S \<noteq> UNIV"
+  shows "\<exists>(a:: real ^'n). a \<noteq>0 \<and> (\<forall>x \<in> span S. a \<bullet> x = 0)"
+proof-
+  from sU obtain a where a: "a \<notin> span S" by blast
+  from orthogonal_basis_exists obtain B where 
+    B: "independent B" "B \<subseteq> span S" "S \<subseteq> span B" "B hassize dim S" "pairwise orthogonal B" 
+    by blast
+  from B have fB: "finite B" "card B = dim S" by (simp_all add: hassize_def)
+  from span_mono[OF B(2)] span_mono[OF B(3)]
+  have sSB: "span S = span B" by (simp add: span_span)
+  let ?a = "a - setsum (\<lambda>b. (a\<bullet>b / (b\<bullet>b)) *s b) B"
+  have "setsum (\<lambda>b. (a\<bullet>b / (b\<bullet>b)) *s b) B \<in> span S"
+    unfolding sSB
+    apply (rule span_setsum[OF fB(1)])
+    apply clarsimp
+    apply (rule span_mul)
+    by (rule span_superset)
+  with a have a0:"?a  \<noteq> 0" by auto
+  have "\<forall>x\<in>span B. ?a \<bullet> x = 0"
+  proof(rule span_induct')
+    show "subspace (\<lambda>x. ?a \<bullet> x = 0)"
+      by (auto simp add: subspace_def mem_def dot_radd dot_rmult) 
+  next
+    {fix x assume x: "x \<in> B"
+      from x have B': "B = insert x (B - {x})" by blast
+      have fth: "finite (B - {x})" using fB by simp
+      have "?a \<bullet> x = 0" 
+	apply (subst B') using fB fth
+	unfolding setsum_clauses(2)[OF fth]
+	apply simp
+	apply (clarsimp simp add: dot_lsub dot_ladd dot_lmult dot_lsum dot_eq_0)
+	apply (rule setsum_0', rule ballI)
+	unfolding dot_sym
+	by (auto simp add: x field_simps dot_eq_0 intro: B(5)[unfolded pairwise_def orthogonal_def, rule_format])}
+    then show "\<forall>x \<in> B. ?a \<bullet> x = 0" by blast
+  qed
+  with a0 show ?thesis unfolding sSB by (auto intro: exI[where x="?a"])
+qed
+
+lemma span_not_univ_subset_hyperplane: 
+  assumes SU: "span S \<noteq> (UNIV ::(real^'n) set)"
+  shows "\<exists> a. a \<noteq>0 \<and> span S \<subseteq> {x. a \<bullet> x = 0}"
+  using span_not_univ_orthogonal[OF SU] by auto
+
+lemma lowdim_subset_hyperplane:
+  assumes d: "dim S < dimindex (UNIV :: 'n set)"
+  shows "\<exists>(a::real ^'n). a  \<noteq> 0 \<and> span S \<subseteq> {x. a \<bullet> x = 0}"
+proof-
+  {assume "span S = UNIV"
+    hence "dim (span S) = dim (UNIV :: (real ^'n) set)" by simp
+    hence "dim S = dimindex (UNIV :: 'n set)" by (simp add: dim_span dim_univ)
+    with d have False by arith}
+  hence th: "span S \<noteq> UNIV" by blast
+  from span_not_univ_subset_hyperplane[OF th] show ?thesis .
+qed
+
+(* We can extend a linear basis-basis injection to the whole set.            *)
+
+lemma linear_indep_image_lemma:
+  assumes lf: "linear f" and fB: "finite B" 
+  and ifB: "independent (f ` B)"
+  and fi: "inj_on f B" and xsB: "x \<in> span B" 
+  and fx: "f (x::'a::field^'n) = 0"
+  shows "x = 0"
+  using fB ifB fi xsB fx
+proof(induct arbitrary: x rule: finite_induct[OF fB])
+  case 1 thus ?case by (auto simp add:  span_empty)
+next
+  case (2 a b x)
+  have fb: "finite b" using "2.prems" by simp
+  have th0: "f ` b \<subseteq> f ` (insert a b)"
+    apply (rule image_mono) by blast 
+  from independent_mono[ OF "2.prems"(2) th0]
+  have ifb: "independent (f ` b)"  .
+  have fib: "inj_on f b" 
+    apply (rule subset_inj_on [OF "2.prems"(3)]) 
+    by blast
+  from span_breakdown[of a "insert a b", simplified, OF "2.prems"(4)]
+  obtain k where k: "x - k*s a \<in> span (b -{a})" by blast
+  have "f (x - k*s a) \<in> span (f ` b)"
+    unfolding span_linear_image[OF lf]
+    apply (rule imageI)
+    using k span_mono[of "b-{a}" b] by blast
+  hence "f x - k*s f a \<in> span (f ` b)"
+    by (simp add: linear_sub[OF lf] linear_cmul[OF lf])
+  hence th: "-k *s f a \<in> span (f ` b)" 
+    using "2.prems"(5) by (simp add: vector_smult_lneg)
+  {assume k0: "k = 0" 
+    from k0 k have "x \<in> span (b -{a})" by simp
+    then have "x \<in> span b" using span_mono[of "b-{a}" b]
+      by blast}
+  moreover
+  {assume k0: "k \<noteq> 0"
+    from span_mul[OF th, of "- 1/ k"] k0
+    have th1: "f a \<in> span (f ` b)" 
+      by (auto simp add: vector_smult_assoc)
+    from inj_on_image_set_diff[OF "2.prems"(3), of "insert a b " "{a}", symmetric]
+    have tha: "f ` insert a b - f ` {a} = f ` (insert a b - {a})" by blast
+    from "2.prems"(2)[unfolded dependent_def bex_simps(10), rule_format, of "f a"]
+    have "f a \<notin> span (f ` b)" using tha
+      using "2.hyps"(2)
+      "2.prems"(3) by auto
+    with th1 have False by blast
+    then have "x \<in> span b" by blast}
+  ultimately have xsb: "x \<in> span b" by blast
+  from "2.hyps"(3)[OF fb ifb fib xsb "2.prems"(5)]
+  show "x = 0" .
+qed
+
+(* We can extend a linear mapping from basis.                                *)
+
+lemma linear_independent_extend_lemma:
+  assumes fi: "finite B" and ib: "independent B"
+  shows "\<exists>g. (\<forall>x\<in> span B. \<forall>y\<in> span B. g ((x::'a::field^'n) + y) = g x + g y) 
+           \<and> (\<forall>x\<in> span B. \<forall>c. g (c*s x) = c *s g x)
+           \<and> (\<forall>x\<in> B. g x = f x)"
+using ib fi
+proof(induct rule: finite_induct[OF fi])
+  case 1 thus ?case by (auto simp add: span_empty) 
+next
+  case (2 a b)
+  from "2.prems" "2.hyps" have ibf: "independent b" "finite b"
+    by (simp_all add: independent_insert)
+  from "2.hyps"(3)[OF ibf] obtain g where 
+    g: "\<forall>x\<in>span b. \<forall>y\<in>span b. g (x + y) = g x + g y"
+    "\<forall>x\<in>span b. \<forall>c. g (c *s x) = c *s g x" "\<forall>x\<in>b. g x = f x" by blast
+  let ?h = "\<lambda>z. SOME k. (z - k *s a) \<in> span b"
+  {fix z assume z: "z \<in> span (insert a b)"
+    have th0: "z - ?h z *s a \<in> span b"
+      apply (rule someI_ex)
+      unfolding span_breakdown_eq[symmetric]
+      using z .
+    {fix k assume k: "z - k *s a \<in> span b"
+      have eq: "z - ?h z *s a - (z - k*s a) = (k - ?h z) *s a" 
+	by (simp add: ring_simps vector_sadd_rdistrib[symmetric])
+      from span_sub[OF th0 k]
+      have khz: "(k - ?h z) *s a \<in> span b" by (simp add: eq)
+      {assume "k \<noteq> ?h z" hence k0: "k - ?h z \<noteq> 0" by simp
+	from k0 span_mul[OF khz, of "1 /(k - ?h z)"] 
+	have "a \<in> span b" by (simp add: vector_smult_assoc)
+	with "2.prems"(1) "2.hyps"(2) have False
+	  by (auto simp add: dependent_def)}
+      then have "k = ?h z" by blast}
+    with th0 have "z - ?h z *s a \<in> span b \<and> (\<forall>k. z - k *s a \<in> span b \<longrightarrow> k = ?h z)" by blast}
+  note h = this
+  let ?g = "\<lambda>z. ?h z *s f a + g (z - ?h z *s a)"
+  {fix x y assume x: "x \<in> span (insert a b)" and y: "y \<in> span (insert a b)"
+    have tha: "\<And>(x::'a^'n) y a k l. (x + y) - (k + l) *s a = (x - k *s a) + (y - l *s a)" 
+      by (vector ring_simps)
+    have addh: "?h (x + y) = ?h x + ?h y"
+      apply (rule conjunct2[OF h, rule_format, symmetric])
+      apply (rule span_add[OF x y])
+      unfolding tha
+      by (metis span_add x y conjunct1[OF h, rule_format])
+    have "?g (x + y) = ?g x + ?g y" 
+      unfolding addh tha
+      g(1)[rule_format,OF conjunct1[OF h, OF x] conjunct1[OF h, OF y]]
+      by (simp add: vector_sadd_rdistrib)}
+  moreover
+  {fix x:: "'a^'n" and c:: 'a  assume x: "x \<in> span (insert a b)"
+    have tha: "\<And>(x::'a^'n) c k a. c *s x - (c * k) *s a = c *s (x - k *s a)" 
+      by (vector ring_simps)
+    have hc: "?h (c *s x) = c * ?h x" 
+      apply (rule conjunct2[OF h, rule_format, symmetric])
+      apply (metis span_mul x)
+      by (metis tha span_mul x conjunct1[OF h])
+    have "?g (c *s x) = c*s ?g x" 
+      unfolding hc tha g(2)[rule_format, OF conjunct1[OF h, OF x]]
+      by (vector ring_simps)}
+  moreover
+  {fix x assume x: "x \<in> (insert a b)"
+    {assume xa: "x = a"
+      have ha1: "1 = ?h a"
+	apply (rule conjunct2[OF h, rule_format])
+	apply (metis span_superset insertI1)
+	using conjunct1[OF h, OF span_superset, OF insertI1]
+	by (auto simp add: span_0)
+
+      from xa ha1[symmetric] have "?g x = f x" 
+	apply simp
+	using g(2)[rule_format, OF span_0, of 0]
+	by simp}
+    moreover
+    {assume xb: "x \<in> b"
+      have h0: "0 = ?h x"
+	apply (rule conjunct2[OF h, rule_format])
+	apply (metis  span_superset insertI1 xb x)
+	apply simp
+	apply (metis span_superset xb)
+	done
+      have "?g x = f x"
+	by (simp add: h0[symmetric] g(3)[rule_format, OF xb])}
+    ultimately have "?g x = f x" using x by blast }
+  ultimately show ?case apply - apply (rule exI[where x="?g"]) by blast
+qed
+
+lemma linear_independent_extend:
+  assumes iB: "independent (B:: (real ^'n) set)"
+  shows "\<exists>g. linear g \<and> (\<forall>x\<in>B. g x = f x)"
+proof-
+  from maximal_independent_subset_extend[of B "UNIV"] iB
+  obtain C where C: "B \<subseteq> C" "independent C" "\<And>x. x \<in> span C" by auto
+  
+  from C(2) independent_bound[of C] linear_independent_extend_lemma[of C f]
+  obtain g where g: "(\<forall>x\<in> span C. \<forall>y\<in> span C. g (x + y) = g x + g y) 
+           \<and> (\<forall>x\<in> span C. \<forall>c. g (c*s x) = c *s g x)
+           \<and> (\<forall>x\<in> C. g x = f x)" by blast
+  from g show ?thesis unfolding linear_def using C 
+    apply clarsimp by blast
+qed
+
+(* Can construct an isomorphism between spaces of same dimension.            *)
+
+lemma card_le_inj: assumes fA: "finite A" and fB: "finite B"
+  and c: "card A \<le> card B" shows "(\<exists>f. f ` A \<subseteq> B \<and> inj_on f A)"
+using fB c
+proof(induct arbitrary: B rule: finite_induct[OF fA])
+  case 1 thus ?case by simp
+next
+  case (2 x s t) 
+  thus ?case
+  proof(induct rule: finite_induct[OF "2.prems"(1)])
+    case 1    then show ?case by simp
+  next
+    case (2 y t)
+    from "2.prems"(1,2,5) "2.hyps"(1,2) have cst:"card s \<le> card t" by simp
+    from "2.prems"(3) [OF "2.hyps"(1) cst] obtain f where
+      f: "f ` s \<subseteq> t \<and> inj_on f s" by blast
+    from f "2.prems"(2) "2.hyps"(2) show ?case
+      apply -
+      apply (rule exI[where x = "\<lambda>z. if z = x then y else f z"])
+      by (auto simp add: inj_on_def)
+  qed
+qed
+
+lemma card_subset_eq: assumes fB: "finite B" and AB: "A \<subseteq> B" and 
+  c: "card A = card B"
+  shows "A = B"
+proof-
+  from fB AB have fA: "finite A" by (auto intro: finite_subset)
+  from fA fB have fBA: "finite (B - A)" by auto
+  have e: "A \<inter> (B - A) = {}" by blast
+  have eq: "A \<union> (B - A) = B" using AB by blast
+  from card_Un_disjoint[OF fA fBA e, unfolded eq c]
+  have "card (B - A) = 0" by arith
+  hence "B - A = {}" unfolding card_eq_0_iff using fA fB by simp
+  with AB show "A = B" by blast  
+qed
+
+lemma subspace_isomorphism:
+  assumes s: "subspace (S:: (real ^'n) set)" and t: "subspace T" 
+  and d: "dim S = dim T"
+  shows "\<exists>f. linear f \<and> f ` S = T \<and> inj_on f S"
+proof-
+  from basis_exists[of S] obtain B where 
+    B: "B \<subseteq> S" "independent B" "S \<subseteq> span B" "B hassize dim S" by blast
+  from basis_exists[of T] obtain C where 
+    C: "C \<subseteq> T" "independent C" "T \<subseteq> span C" "C hassize dim T" by blast
+  from B(4) C(4) card_le_inj[of B C] d obtain f where
+    f: "f ` B \<subseteq> C" "inj_on f B" unfolding hassize_def by auto 
+  from linear_independent_extend[OF B(2)] obtain g where
+    g: "linear g" "\<forall>x\<in> B. g x = f x" by blast
+  from B(4) have fB: "finite B" by (simp add: hassize_def)
+  from C(4) have fC: "finite C" by (simp add: hassize_def)
+  from inj_on_iff_eq_card[OF fB, of f] f(2) 
+  have "card (f ` B) = card B" by simp
+  with B(4) C(4) have ceq: "card (f ` B) = card C" using d 
+    by (simp add: hassize_def)
+  have "g ` B = f ` B" using g(2)
+    by (auto simp add: image_iff)
+  also have "\<dots> = C" using card_subset_eq[OF fC f(1) ceq] .
+  finally have gBC: "g ` B = C" .
+  have gi: "inj_on g B" using f(2) g(2)
+    by (auto simp add: inj_on_def)
+  note g0 = linear_indep_image_lemma[OF g(1) fB, unfolded gBC, OF C(2) gi]
+  {fix x y assume x: "x \<in> S" and y: "y \<in> S" and gxy:"g x = g y"
+    from B(3) x y have x': "x \<in> span B" and y': "y \<in> span B" by blast+
+    from gxy have th0: "g (x - y) = 0" by (simp add: linear_sub[OF g(1)])
+    have th1: "x - y \<in> span B" using x' y' by (metis span_sub) 
+    have "x=y" using g0[OF th1 th0] by simp }
+  then have giS: "inj_on g S" 
+    unfolding inj_on_def by blast
+  from span_subspace[OF B(1,3) s]
+  have "g ` S = span (g ` B)" by (simp add: span_linear_image[OF g(1)])
+  also have "\<dots> = span C" unfolding gBC ..
+  also have "\<dots> = T" using span_subspace[OF C(1,3) t] .
+  finally have gS: "g ` S = T" .
+  from g(1) gS giS show ?thesis by blast
+qed
+
+(* linear functions are equal on a subspace if they are on a spanning set.   *)
+
+lemma subspace_kernel:
+  assumes lf: "linear (f::'a::semiring_1 ^'n \<Rightarrow> _)"
+  shows "subspace {x. f x = 0}"
+apply (simp add: subspace_def)
+by (simp add: linear_add[OF lf] linear_cmul[OF lf] linear_0[OF lf])
+
+lemma linear_eq_0_span:
+  assumes lf: "linear f" and f0: "\<forall>x\<in>B. f x = 0"
+  shows "\<forall>x \<in> span B. f x = (0::'a::semiring_1 ^'n)"
+proof
+  fix x assume x: "x \<in> span B"
+  let ?P = "\<lambda>x. f x = 0"
+  from subspace_kernel[OF lf] have "subspace ?P" unfolding Collect_def .
+  with x f0 span_induct[of B "?P" x] show "f x = 0" by blast
+qed
+
+lemma linear_eq_0:
+  assumes lf: "linear f" and SB: "S \<subseteq> span B" and f0: "\<forall>x\<in>B. f x = 0" 
+  shows "\<forall>x \<in> S. f x = (0::'a::semiring_1^'n)"
+  by (metis linear_eq_0_span[OF lf] subset_eq SB f0)
+
+lemma linear_eq:
+  assumes lf: "linear (f::'a::ring_1^'n \<Rightarrow> _)" and lg: "linear g" and S: "S \<subseteq> span B"
+  and fg: "\<forall> x\<in> B. f x = g x" 
+  shows "\<forall>x\<in> S. f x = g x"
+proof-
+  let ?h = "\<lambda>x. f x - g x"
+  from fg have fg': "\<forall>x\<in> B. ?h x = 0" by simp
+  from linear_eq_0[OF linear_compose_sub[OF lf lg] S fg']
+  show ?thesis by simp
+qed    
+
+lemma linear_eq_stdbasis:
+  assumes lf: "linear (f::'a::ring_1^'m \<Rightarrow> 'a^'n)" and lg: "linear g"
+  and fg: "\<forall>i \<in> {1 .. dimindex(UNIV :: 'm set)}. f (basis i) = g(basis i)"
+  shows "f = g"
+proof-
+  let ?U = "UNIV :: 'm set"
+  let ?I = "{basis i:: 'a^'m|i. i \<in> {1 .. dimindex ?U}}" 
+  {fix x assume x: "x \<in> (UNIV :: ('a^'m) set)"
+    from equalityD2[OF span_stdbasis]
+    have IU: " (UNIV :: ('a^'m) set) \<subseteq> span ?I" by blast
+    from linear_eq[OF lf lg IU] fg x
+    have "f x = g x" unfolding Collect_def  Ball_def mem_def by metis}
+  then show ?thesis by (auto intro: ext)
+qed
+
+(* Similar results for bilinear functions.                                   *)
+
+lemma bilinear_eq:
+  assumes bf: "bilinear (f:: 'a::ring^'m \<Rightarrow> 'a^'n \<Rightarrow> 'a^'p)" 
+  and bg: "bilinear g"
+  and SB: "S \<subseteq> span B" and TC: "T \<subseteq> span C"
+  and fg: "\<forall>x\<in> B. \<forall>y\<in> C. f x y = g x y"
+  shows "\<forall>x\<in>S. \<forall>y\<in>T. f x y = g x y "
+proof-
+  let ?P = "\<lambda>x. \<forall>y\<in> span C. f x y = g x y"
+  from bf bg have sp: "subspace ?P" 
+    unfolding bilinear_def linear_def subspace_def bf bg  
+    by(auto simp add: span_0 mem_def bilinear_lzero[OF bf] bilinear_lzero[OF bg] span_add Ball_def intro:  bilinear_ladd[OF bf])
+
+  have "\<forall>x \<in> span B. \<forall>y\<in> span C. f x y = g x y" 
+    apply -
+    apply (rule ballI)
+    apply (rule span_induct[of B ?P]) 
+    defer
+    apply (rule sp)
+    apply assumption
+    apply (clarsimp simp add: Ball_def)
+    apply (rule_tac P="\<lambda>y. f xa y = g xa y" and S=C in span_induct)
+    using fg 
+    apply (auto simp add: subspace_def)
+    using bf bg unfolding bilinear_def linear_def
+    by(auto simp add: span_0 mem_def bilinear_rzero[OF bf] bilinear_rzero[OF bg] span_add Ball_def intro:  bilinear_ladd[OF bf])
+  then show ?thesis using SB TC by (auto intro: ext)
+qed
+
+lemma bilinear_eq_stdbasis:
+  assumes bf: "bilinear (f:: 'a::ring_1^'m \<Rightarrow> 'a^'n \<Rightarrow> 'a^'p)" 
+  and bg: "bilinear g"
+  and fg: "\<forall>i\<in> {1 .. dimindex (UNIV :: 'm set)}. \<forall>j\<in>  {1 .. dimindex (UNIV :: 'n set)}. f (basis i) (basis j) = g (basis i) (basis j)"
+  shows "f = g"
+proof-
+  from fg have th: "\<forall>x \<in> {basis i| i. i\<in> {1 .. dimindex (UNIV :: 'm set)}}. \<forall>y\<in>  {basis j |j. j \<in> {1 .. dimindex (UNIV :: 'n set)}}. f x y = g x y" by blast
+  from bilinear_eq[OF bf bg equalityD2[OF span_stdbasis] equalityD2[OF span_stdbasis] th] show ?thesis by (blast intro: ext)
+qed
+
+(* Detailed theorems about left and right invertibility in general case.     *)
+
+lemma left_invertible_transp:
+  "(\<exists>(B::'a^'n^'m). B ** transp (A::'a^'n^'m) = mat (1::'a::comm_semiring_1)) \<longleftrightarrow> (\<exists>(B::'a^'m^'n). A ** B = mat 1)"
+  by (metis matrix_transp_mul transp_mat transp_transp)
+
+lemma right_invertible_transp:
+  "(\<exists>(B::'a^'n^'m). transp (A::'a^'n^'m) ** B = mat (1::'a::comm_semiring_1)) \<longleftrightarrow> (\<exists>(B::'a^'m^'n). B ** A = mat 1)"
+  by (metis matrix_transp_mul transp_mat transp_transp)
+
+lemma linear_injective_left_inverse:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'m)" and fi: "inj f"
+  shows "\<exists>g. linear g \<and> g o f = id"
+proof-
+  from linear_independent_extend[OF independent_injective_image, OF independent_stdbasis, OF lf fi]
+  obtain h:: "real ^'m \<Rightarrow> real ^'n" where h: "linear h" " \<forall>x \<in> f ` {basis i|i. i \<in> {1 .. dimindex (UNIV::'n set)}}. h x = inv f x" by blast
+  from h(2) 
+  have th: "\<forall>i\<in>{1..dimindex (UNIV::'n set)}. (h \<circ> f) (basis i) = id (basis i)"
+    using inv_o_cancel[OF fi, unfolded stupid_ext[symmetric] id_def o_def]
+    apply auto
+    apply (erule_tac x="basis i" in allE)
+    by auto
+  
+  from linear_eq_stdbasis[OF linear_compose[OF lf h(1)] linear_id th]
+  have "h o f = id" .
+  then show ?thesis using h(1) by blast  
+qed
+
+lemma linear_surjective_right_inverse:
+  assumes lf: "linear (f:: real ^'m \<Rightarrow> real ^'n)" and sf: "surj f"
+  shows "\<exists>g. linear g \<and> f o g = id"
+proof-
+  from linear_independent_extend[OF independent_stdbasis]
+  obtain h:: "real ^'n \<Rightarrow> real ^'m" where 
+    h: "linear h" "\<forall> x\<in> {basis i| i. i\<in> {1 .. dimindex (UNIV :: 'n set)}}. h x = inv f x" by blast
+  from h(2) 
+  have th: "\<forall>i\<in>{1..dimindex (UNIV::'n set)}. (f o h) (basis i) = id (basis i)"
+    using sf
+    apply (auto simp add: surj_iff o_def stupid_ext[symmetric])
+    apply (erule_tac x="basis i" in allE)
+    by auto
+  
+  from linear_eq_stdbasis[OF linear_compose[OF h(1) lf] linear_id th]
+  have "f o h = id" .
+  then show ?thesis using h(1) by blast  
+qed
+
+lemma matrix_left_invertible_injective:
+"(\<exists>B. (B::real^'m^'n) ** (A::real^'n^'m) = mat 1) \<longleftrightarrow> (\<forall>x y. A *v x = A *v y \<longrightarrow> x = y)"
+proof-
+  {fix B:: "real^'m^'n" and x y assume B: "B ** A = mat 1" and xy: "A *v x = A*v y"
+    from xy have "B*v (A *v x) = B *v (A*v y)" by simp
+    hence "x = y"
+      unfolding matrix_vector_mul_assoc B matrix_vector_mul_lid .}
+  moreover
+  {assume A: "\<forall>x y. A *v x = A *v y \<longrightarrow> x = y"
+    hence i: "inj (op *v A)" unfolding inj_on_def by auto 
+    from linear_injective_left_inverse[OF matrix_vector_mul_linear i]
+    obtain g where g: "linear g" "g o op *v A = id" by blast
+    have "matrix g ** A = mat 1"
+      unfolding matrix_eq matrix_vector_mul_lid matrix_vector_mul_assoc[symmetric] matrix_works[OF g(1)]
+      using g(2) by (simp add: o_def id_def stupid_ext)
+    then have "\<exists>B. (B::real ^'m^'n) ** A = mat 1" by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma matrix_left_invertible_ker:
+  "(\<exists>B. (B::real ^'m^'n) ** (A::real^'n^'m) = mat 1) \<longleftrightarrow> (\<forall>x. A *v x = 0 \<longrightarrow> x = 0)"
+  unfolding matrix_left_invertible_injective
+  using linear_injective_0[OF matrix_vector_mul_linear, of A]
+  by (simp add: inj_on_def)
+
+lemma matrix_right_invertible_surjective:
+"(\<exists>B. (A::real^'n^'m) ** (B::real^'m^'n) = mat 1) \<longleftrightarrow> surj (\<lambda>x. A *v x)"
+proof-
+  {fix B :: "real ^'m^'n"  assume AB: "A ** B = mat 1"
+    {fix x :: "real ^ 'm" 
+      have "A *v (B *v x) = x"
+	by (simp add: matrix_vector_mul_lid matrix_vector_mul_assoc AB)}
+    hence "surj (op *v A)" unfolding surj_def by metis }
+  moreover
+  {assume sf: "surj (op *v A)"
+    from linear_surjective_right_inverse[OF matrix_vector_mul_linear sf]
+    obtain g:: "real ^'m \<Rightarrow> real ^'n" where g: "linear g" "op *v A o g = id" 
+      by blast
+
+    have "A ** (matrix g) = mat 1"
+      unfolding matrix_eq  matrix_vector_mul_lid 
+	matrix_vector_mul_assoc[symmetric] matrix_works[OF g(1)] 
+      using g(2) unfolding o_def stupid_ext[symmetric] id_def
+      .
+    hence "\<exists>B. A ** (B::real^'m^'n) = mat 1" by blast
+  }
+  ultimately show ?thesis unfolding surj_def by blast
+qed    
+
+lemma matrix_left_invertible_independent_columns:
+  fixes A :: "real^'n^'m"
+  shows "(\<exists>(B::real ^'m^'n). B ** A = mat 1) \<longleftrightarrow> (\<forall>c. setsum (\<lambda>i. c i *s column i A) {1 .. dimindex(UNIV :: 'n set)} = 0 \<longrightarrow> (\<forall>i\<in> {1 .. dimindex (UNIV :: 'n set)}. c i = 0))"
+   (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  let ?U = "{1 .. dimindex(UNIV :: 'n set)}"
+  {assume k: "\<forall>x. A *v x = 0 \<longrightarrow> x = 0"
+    {fix c i assume c: "setsum (\<lambda>i. c i *s column i A) ?U = 0" 
+      and i: "i \<in> ?U"
+      let ?x = "\<chi> i. c i"
+      have th0:"A *v ?x = 0"
+	using c
+	unfolding matrix_mult_vsum Cart_eq
+	by (auto simp add: vector_component zero_index setsum_component Cart_lambda_beta)
+      from k[rule_format, OF th0] i
+      have "c i = 0" by (vector Cart_eq)}
+    hence ?rhs by blast}
+  moreover
+  {assume H: ?rhs
+    {fix x assume x: "A *v x = 0" 
+      let ?c = "\<lambda>i. ((x$i ):: real)"
+      from H[rule_format, of ?c, unfolded matrix_mult_vsum[symmetric], OF x]
+      have "x = 0" by vector}}
+  ultimately show ?thesis unfolding matrix_left_invertible_ker by blast 
+qed
+
+lemma matrix_right_invertible_independent_rows:
+  fixes A :: "real^'n^'m"
+  shows "(\<exists>(B::real^'m^'n). A ** B = mat 1) \<longleftrightarrow> (\<forall>c. setsum (\<lambda>i. c i *s row i A) {1 .. dimindex(UNIV :: 'm set)} = 0 \<longrightarrow> (\<forall>i\<in> {1 .. dimindex (UNIV :: 'm set)}. c i = 0))"
+  unfolding left_invertible_transp[symmetric]
+    matrix_left_invertible_independent_columns
+  by (simp add: column_transp)
+
+lemma matrix_right_invertible_span_columns:
+  "(\<exists>(B::real ^'n^'m). (A::real ^'m^'n) ** B = mat 1) \<longleftrightarrow> span (columns A) = UNIV" (is "?lhs = ?rhs")
+proof-
+  let ?U = "{1 .. dimindex (UNIV :: 'm set)}"
+  have fU: "finite ?U" by simp
+  have lhseq: "?lhs \<longleftrightarrow> (\<forall>y. \<exists>(x::real^'m). setsum (\<lambda>i. (x$i) *s column i A) ?U = y)"
+    unfolding matrix_right_invertible_surjective matrix_mult_vsum surj_def
+    apply (subst eq_commute) ..    
+  have rhseq: "?rhs \<longleftrightarrow> (\<forall>x. x \<in> span (columns A))" by blast
+  {assume h: ?lhs
+    {fix x:: "real ^'n" 
+	from h[unfolded lhseq, rule_format, of x] obtain y:: "real ^'m"
+	  where y: "setsum (\<lambda>i. (y$i) *s column i A) ?U = x" by blast
+	have "x \<in> span (columns A)"  
+	  unfolding y[symmetric]
+	  apply (rule span_setsum[OF fU])
+	  apply clarify
+	  apply (rule span_mul)
+	  apply (rule span_superset)
+	  unfolding columns_def
+	  by blast}
+    then have ?rhs unfolding rhseq by blast}
+  moreover
+  {assume h:?rhs
+    let ?P = "\<lambda>(y::real ^'n). \<exists>(x::real^'m). setsum (\<lambda>i. (x$i) *s column i A) ?U = y"
+    {fix y have "?P y" 
+      proof(rule span_induct_alt[of ?P "columns A"])
+	show "\<exists>x\<Colon>real ^ 'm. setsum (\<lambda>i. (x$i) *s column i A) ?U = 0"
+	  apply (rule exI[where x=0])
+	  by (simp add: zero_index vector_smult_lzero)
+      next
+	fix c y1 y2 assume y1: "y1 \<in> columns A" and y2: "?P y2"
+	from y1 obtain i where i: "i \<in> ?U" "y1 = column i A" 
+	  unfolding columns_def by blast
+	from y2 obtain x:: "real ^'m" where 
+	  x: "setsum (\<lambda>i. (x$i) *s column i A) ?U = y2" by blast
+	let ?x = "(\<chi> j. if j = i then c + (x$i) else (x$j))::real^'m"
+	show "?P (c*s y1 + y2)"
+	  proof(rule exI[where x= "?x"], vector, auto simp add: i x[symmetric]Cart_lambda_beta setsum_component cond_value_iff right_distrib cond_application_beta vector_component cong del: if_weak_cong, simp only: One_nat_def[symmetric])
+	    fix j 
+	    have th: "\<forall>xa \<in> ?U. (if xa = i then (c + (x$i)) * ((column xa A)$j)
+           else (x$xa) * ((column xa A$j))) = (if xa = i then c * ((column i A)$j) else 0) + ((x$xa) * ((column xa A)$j))" using i(1)
+	      by (simp add: ring_simps)
+	    have "setsum (\<lambda>xa. if xa = i then (c + (x$i)) * ((column xa A)$j)
+           else (x$xa) * ((column xa A$j))) ?U = setsum (\<lambda>xa. (if xa = i then c * ((column i A)$j) else 0) + ((x$xa) * ((column xa A)$j))) ?U"
+	      apply (rule setsum_cong[OF refl])
+	      using th by blast
+	    also have "\<dots> = setsum (\<lambda>xa. if xa = i then c * ((column i A)$j) else 0) ?U + setsum (\<lambda>xa. ((x$xa) * ((column xa A)$j))) ?U"
+	      by (simp add: setsum_addf)
+	    also have "\<dots> = c * ((column i A)$j) + setsum (\<lambda>xa. ((x$xa) * ((column xa A)$j))) ?U"
+	      unfolding setsum_delta[OF fU]
+	      using i(1) by simp 
+	    finally show "setsum (\<lambda>xa. if xa = i then (c + (x$i)) * ((column xa A)$j)
+           else (x$xa) * ((column xa A$j))) ?U = c * ((column i A)$j) + setsum (\<lambda>xa. ((x$xa) * ((column xa A)$j))) ?U" .
+	  qed
+	next
+	  show "y \<in> span (columns A)" unfolding h by blast
+	qed}
+    then have ?lhs unfolding lhseq ..}
+  ultimately show ?thesis by blast
+qed
+
+lemma matrix_left_invertible_span_rows:
+  "(\<exists>(B::real^'m^'n). B ** (A::real^'n^'m) = mat 1) \<longleftrightarrow> span (rows A) = UNIV"
+  unfolding right_invertible_transp[symmetric]
+  unfolding columns_transp[symmetric]
+  unfolding matrix_right_invertible_span_columns
+ ..
+
+(* An injective map real^'n->real^'n is also surjective.                       *)
+
+lemma linear_injective_imp_surjective:
+  assumes lf: "linear (f:: real ^'n \<Rightarrow> real ^'n)" and fi: "inj f" 
+  shows "surj f"
+proof-
+  let ?U = "UNIV :: (real ^'n) set"
+  from basis_exists[of ?U] obtain B 
+    where B: "B \<subseteq> ?U" "independent B" "?U \<subseteq> span B" "B hassize dim ?U" 
+    by blast
+  from B(4) have d: "dim ?U = card B" by (simp add: hassize_def)
+  have th: "?U \<subseteq> span (f ` B)"
+    apply (rule card_ge_dim_independent)
+    apply blast
+    apply (rule independent_injective_image[OF B(2) lf fi])
+    apply (rule order_eq_refl)
+    apply (rule sym)
+    unfolding d
+    apply (rule card_image)
+    apply (rule subset_inj_on[OF fi])
+    by blast
+  from th show ?thesis
+    unfolding span_linear_image[OF lf] surj_def
+    using B(3) by blast
+qed
+
+(* And vice versa.                                                           *)
+
+lemma surjective_iff_injective_gen: 
+  assumes fS: "finite S" and fT: "finite T" and c: "card S = card T"
+  and ST: "f ` S \<subseteq> T"
+  shows "(\<forall>y \<in> T. \<exists>x \<in> S. f x = y) \<longleftrightarrow> inj_on f S" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume h: "?lhs"
+    {fix x y assume x: "x \<in> S" and y: "y \<in> S" and f: "f x = f y"
+      from x fS have S0: "card S \<noteq> 0" by auto
+      {assume xy: "x \<noteq> y"
+	have th: "card S \<le> card (f ` (S - {y}))"
+	  unfolding c
+	  apply (rule card_mono)
+	  apply (rule finite_imageI)
+	  using fS apply simp
+	  using h xy x y f unfolding subset_eq image_iff
+	  apply auto
+	  apply (case_tac "xa = f x")
+	  apply (rule bexI[where x=x])
+	  apply auto
+	  done
+	also have " \<dots> \<le> card (S -{y})"
+	  apply (rule card_image_le)
+	  using fS by simp
+	also have "\<dots> \<le> card S - 1" using y fS by simp
+	finally have False  using S0 by arith }
+      then have "x = y" by blast}
+    then have ?rhs unfolding inj_on_def by blast}
+  moreover
+  {assume h: ?rhs
+    have "f ` S = T"
+      apply (rule card_subset_eq[OF fT ST])
+      unfolding card_image[OF h] using c .
+    then have ?lhs by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma linear_surjective_imp_injective:
+  assumes lf: "linear (f::real ^'n => real ^'n)" and sf: "surj f" 
+  shows "inj f"
+proof-
+  let ?U = "UNIV :: (real ^'n) set"
+  from basis_exists[of ?U] obtain B 
+    where B: "B \<subseteq> ?U" "independent B" "?U \<subseteq> span B" "B hassize dim ?U" 
+    by blast
+  {fix x assume x: "x \<in> span B" and fx: "f x = 0"
+    from B(4) have fB: "finite B" by (simp add: hassize_def)
+    from B(4) have d: "dim ?U = card B" by (simp add: hassize_def)
+    have fBi: "independent (f ` B)" 
+      apply (rule card_le_dim_spanning[of "f ` B" ?U])
+      apply blast
+      using sf B(3)
+      unfolding span_linear_image[OF lf] surj_def subset_eq image_iff
+      apply blast
+      using fB apply (blast intro: finite_imageI)
+      unfolding d
+      apply (rule card_image_le)
+      apply (rule fB)
+      done
+    have th0: "dim ?U \<le> card (f ` B)"
+      apply (rule span_card_ge_dim)
+      apply blast
+      unfolding span_linear_image[OF lf]
+      apply (rule subset_trans[where B = "f ` UNIV"])
+      using sf unfolding surj_def apply blast
+      apply (rule image_mono)
+      apply (rule B(3))
+      apply (metis finite_imageI fB)
+      done
+
+    moreover have "card (f ` B) \<le> card B"
+      by (rule card_image_le, rule fB)
+    ultimately have th1: "card B = card (f ` B)" unfolding d by arith
+    have fiB: "inj_on f B" 
+      unfolding surjective_iff_injective_gen[OF fB finite_imageI[OF fB] th1 subset_refl, symmetric] by blast
+    from linear_indep_image_lemma[OF lf fB fBi fiB x] fx
+    have "x = 0" by blast}
+  note th = this
+  from th show ?thesis unfolding linear_injective_0[OF lf] 
+    using B(3) by blast
+qed
+
+(* Hence either is enough for isomorphism.                                   *)
+
+lemma left_right_inverse_eq:
+  assumes fg: "f o g = id" and gh: "g o h = id"
+  shows "f = h" 
+proof-
+  have "f = f o (g o h)" unfolding gh by simp
+  also have "\<dots> = (f o g) o h" by (simp add: o_assoc)
+  finally show "f = h" unfolding fg by simp
+qed
+
+lemma isomorphism_expand:
+  "f o g = id \<and> g o f = id \<longleftrightarrow> (\<forall>x. f(g x) = x) \<and> (\<forall>x. g(f x) = x)"
+  by (simp add: expand_fun_eq o_def id_def)
+
+lemma linear_injective_isomorphism:
+  assumes lf: "linear (f :: real^'n \<Rightarrow> real ^'n)" and fi: "inj f"
+  shows "\<exists>f'. linear f' \<and> (\<forall>x. f' (f x) = x) \<and> (\<forall>x. f (f' x) = x)"
+unfolding isomorphism_expand[symmetric]
+using linear_surjective_right_inverse[OF lf linear_injective_imp_surjective[OF lf fi]] linear_injective_left_inverse[OF lf fi]
+by (metis left_right_inverse_eq)
+
+lemma linear_surjective_isomorphism:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'n)" and sf: "surj f"
+  shows "\<exists>f'. linear f' \<and> (\<forall>x. f' (f x) = x) \<and> (\<forall>x. f (f' x) = x)"
+unfolding isomorphism_expand[symmetric]
+using linear_surjective_right_inverse[OF lf sf] linear_injective_left_inverse[OF lf linear_surjective_imp_injective[OF lf sf]]
+by (metis left_right_inverse_eq)
+
+(* Left and right inverses are the same for R^N->R^N.                        *)
+
+lemma linear_inverse_left:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'n)" and lf': "linear f'"
+  shows "f o f' = id \<longleftrightarrow> f' o f = id"
+proof-
+  {fix f f':: "real ^'n \<Rightarrow> real ^'n"
+    assume lf: "linear f" "linear f'" and f: "f o f' = id"
+    from f have sf: "surj f"
+      
+      apply (auto simp add: o_def stupid_ext[symmetric] id_def surj_def)
+      by metis
+    from linear_surjective_isomorphism[OF lf(1) sf] lf f
+    have "f' o f = id" unfolding stupid_ext[symmetric] o_def id_def
+      by metis}
+  then show ?thesis using lf lf' by metis
+qed
+
+(* Moreover, a one-sided inverse is automatically linear.                    *)
+
+lemma left_inverse_linear:
+  assumes lf: "linear (f::real ^'n \<Rightarrow> real ^'n)" and gf: "g o f = id" 
+  shows "linear g"
+proof-
+  from gf have fi: "inj f" apply (auto simp add: inj_on_def o_def id_def stupid_ext[symmetric])
+    by metis
+  from linear_injective_isomorphism[OF lf fi] 
+  obtain h:: "real ^'n \<Rightarrow> real ^'n" where 
+    h: "linear h" "\<forall>x. h (f x) = x" "\<forall>x. f (h x) = x" by blast
+  have "h = g" apply (rule ext) using gf h(2,3)
+    apply (simp add: o_def id_def stupid_ext[symmetric])
+    by metis
+  with h(1) show ?thesis by blast
+qed
+
+lemma right_inverse_linear:
+  assumes lf: "linear (f:: real ^'n \<Rightarrow> real ^'n)" and gf: "f o g = id" 
+  shows "linear g"
+proof-
+  from gf have fi: "surj f" apply (auto simp add: surj_def o_def id_def stupid_ext[symmetric])
+    by metis
+  from linear_surjective_isomorphism[OF lf fi] 
+  obtain h:: "real ^'n \<Rightarrow> real ^'n" where 
+    h: "linear h" "\<forall>x. h (f x) = x" "\<forall>x. f (h x) = x" by blast
+  have "h = g" apply (rule ext) using gf h(2,3)
+    apply (simp add: o_def id_def stupid_ext[symmetric])
+    by metis
+  with h(1) show ?thesis by blast
+qed
+
+(* The same result in terms of square matrices.                              *)
+
+lemma matrix_left_right_inverse:
+  fixes A A' :: "real ^'n^'n" 
+  shows "A ** A' = mat 1 \<longleftrightarrow> A' ** A = mat 1"
+proof-
+  {fix A A' :: "real ^'n^'n" assume AA': "A ** A' = mat 1"
+    have sA: "surj (op *v A)"
+      unfolding surj_def
+      apply clarify
+      apply (rule_tac x="(A' *v y)" in exI)
+      by (simp add: matrix_vector_mul_assoc AA' matrix_vector_mul_lid)
+    from linear_surjective_isomorphism[OF matrix_vector_mul_linear sA]
+    obtain f' :: "real ^'n \<Rightarrow> real ^'n"
+      where f': "linear f'" "\<forall>x. f' (A *v x) = x" "\<forall>x. A *v f' x = x" by blast
+    have th: "matrix f' ** A = mat 1" 
+      by (simp add: matrix_eq matrix_works[OF f'(1)] matrix_vector_mul_assoc[symmetric] matrix_vector_mul_lid f'(2)[rule_format])
+    hence "(matrix f' ** A) ** A' = mat 1 ** A'" by simp
+    hence "matrix f' = A'" by (simp add: matrix_mul_assoc[symmetric] AA' matrix_mul_rid matrix_mul_lid)
+    hence "matrix f' ** A = A' ** A" by simp
+    hence "A' ** A = mat 1" by (simp add: th)}
+  then show ?thesis by blast
+qed
+
+(* Considering an n-element vector as an n-by-1 or 1-by-n matrix.            *)
+
+definition "rowvector v = (\<chi> i j. (v$j))"
+
+definition "columnvector v = (\<chi> i j. (v$i))"
+
+lemma transp_columnvector:
+ "transp(columnvector v) = rowvector v"
+  by (simp add: transp_def rowvector_def columnvector_def Cart_eq Cart_lambda_beta)
+
+lemma transp_rowvector: "transp(rowvector v) = columnvector v"
+  by (simp add: transp_def columnvector_def rowvector_def Cart_eq Cart_lambda_beta)
+
+lemma dot_rowvector_columnvector:
+  "columnvector (A *v v) = A ** columnvector v"
+  by (vector columnvector_def matrix_matrix_mult_def matrix_vector_mult_def)
+
+lemma dot_matrix_product: "(x::'a::semiring_1^'n) \<bullet> y = (((rowvector x ::'a^'n^1) ** (columnvector y :: 'a^1^'n))$1)$1"
+  apply (vector matrix_matrix_mult_def rowvector_def columnvector_def dot_def)
+  by (simp add: Cart_lambda_beta)
+
+lemma dot_matrix_vector_mul:
+  fixes A B :: "real ^'n ^'n" and x y :: "real ^'n"
+  shows "(A *v x) \<bullet> (B *v y) =
+      (((rowvector x :: real^'n^1) ** ((transp A ** B) ** (columnvector y :: real ^1^'n)))$1)$1"
+unfolding dot_matrix_product transp_columnvector[symmetric]
+  dot_rowvector_columnvector matrix_transp_mul matrix_mul_assoc ..
+
+(* Infinity norm.                                                            *)
+
+definition "infnorm (x::real^'n) = rsup {abs(x$i) |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}}"
+
+lemma numseg_dimindex_nonempty: "\<exists>i. i \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  using dimindex_ge_1 by auto
+
+lemma infnorm_set_image:
+  "{abs(x$i) |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}} =
+  (\<lambda>i. abs(x$i)) ` {1 .. dimindex(UNIV :: 'n set)}" by blast
+
+lemma infnorm_set_lemma:
+  shows "finite {abs((x::'a::abs ^'n)$i) |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}}"
+  and "{abs(x$i) |i. i\<in> {1 .. dimindex(UNIV :: 'n set)}} \<noteq> {}"
+  unfolding infnorm_set_image
+  using dimindex_ge_1[of "UNIV :: 'n set"]
+  by (auto intro: finite_imageI)
+
+lemma infnorm_pos_le: "0 \<le> infnorm x"
+  unfolding infnorm_def
+  unfolding rsup_finite_ge_iff[ OF infnorm_set_lemma]
+  unfolding infnorm_set_image
+  using dimindex_ge_1
+  by auto
+
+lemma infnorm_triangle: "infnorm ((x::real^'n) + y) \<le> infnorm x + infnorm y"
+proof-
+  have th: "\<And>x y (z::real). x - y <= z \<longleftrightarrow> x - z <= y" by arith
+  have th1: "\<And>S f. f ` S = { f i| i. i \<in> S}" by blast
+  have th2: "\<And>x (y::real). abs(x + y) - abs(x) <= abs(y)" by arith
+  show ?thesis 
+  unfolding infnorm_def
+  unfolding rsup_finite_le_iff[ OF infnorm_set_lemma]
+  apply (subst diff_le_eq[symmetric])
+  unfolding rsup_finite_ge_iff[ OF infnorm_set_lemma]
+  unfolding infnorm_set_image bex_simps 
+  apply (subst th)
+  unfolding th1 
+  unfolding rsup_finite_ge_iff[ OF infnorm_set_lemma]
+  
+  unfolding infnorm_set_image ball_simps bex_simps 
+  apply (simp add: vector_add_component)
+  apply (metis numseg_dimindex_nonempty th2)
+  done
+qed
+
+lemma infnorm_eq_0: "infnorm x = 0 \<longleftrightarrow> (x::real ^'n) = 0"
+proof-
+  have "infnorm x <= 0 \<longleftrightarrow> x = 0"
+    unfolding infnorm_def
+    unfolding rsup_finite_le_iff[OF infnorm_set_lemma]
+    unfolding infnorm_set_image ball_simps
+    by vector
+  then show ?thesis using infnorm_pos_le[of x] by simp
+qed
+
+lemma infnorm_0: "infnorm 0 = 0"
+  by (simp add: infnorm_eq_0)
+
+lemma infnorm_neg: "infnorm (- x) = infnorm x"
+  unfolding infnorm_def
+  apply (rule cong[of "rsup" "rsup"])
+  apply blast
+  apply (rule set_ext)
+  apply (auto simp add: vector_component abs_minus_cancel)
+  apply (rule_tac x="i" in exI)
+  apply (simp add: vector_component)
+  done
+
+lemma infnorm_sub: "infnorm (x - y) = infnorm (y - x)" 
+proof-
+  have "y - x = - (x - y)" by simp
+  then show ?thesis  by (metis infnorm_neg)
+qed
+
+lemma real_abs_sub_infnorm: "\<bar> infnorm x - infnorm y\<bar> \<le> infnorm (x - y)"
+proof-
+  have th: "\<And>(nx::real) n ny. nx <= n + ny \<Longrightarrow> ny <= n + nx ==> \<bar>nx - ny\<bar> <= n"
+    by arith
+  from infnorm_triangle[of "x - y" " y"] infnorm_triangle[of "x - y" "-x"]
+  have ths: "infnorm x \<le> infnorm (x - y) + infnorm y" 
+    "infnorm y \<le> infnorm (x - y) + infnorm x"
+    by (simp_all add: ring_simps infnorm_neg diff_def[symmetric])
+  from th[OF ths]  show ?thesis .
+qed
+
+lemma real_abs_infnorm: " \<bar>infnorm x\<bar> = infnorm x"
+  using infnorm_pos_le[of x] by arith
+
+lemma component_le_infnorm: assumes i: "i \<in> {1 .. dimindex (UNIV :: 'n set)}"
+  shows "\<bar>x$i\<bar> \<le> infnorm (x::real^'n)"
+proof-
+  let ?U = "{1 .. dimindex (UNIV :: 'n set)}"
+  let ?S = "{\<bar>x$i\<bar> |i. i\<in> ?U}"
+  have fS: "finite ?S" unfolding image_Collect[symmetric]
+    apply (rule finite_imageI) unfolding Collect_def mem_def by simp  
+  have S0: "?S \<noteq> {}" using numseg_dimindex_nonempty by blast
+  have th1: "\<And>S f. f ` S = { f i| i. i \<in> S}" by blast
+  from rsup_finite_in[OF fS S0] rsup_finite_Ub[OF fS S0] i
+  show ?thesis unfolding infnorm_def isUb_def setle_def 
+    unfolding infnorm_set_image ball_simps by auto
+qed
+
+lemma infnorm_mul_lemma: "infnorm(a *s x) <= \<bar>a\<bar> * infnorm x"
+  apply (subst infnorm_def)
+  unfolding rsup_finite_le_iff[OF infnorm_set_lemma]
+  unfolding infnorm_set_image ball_simps
+  apply (simp add: abs_mult vector_component del: One_nat_def)
+  apply (rule ballI)
+  apply (drule component_le_infnorm[of _ x])
+  apply (rule mult_mono)
+  apply auto
+  done
+
+lemma infnorm_mul: "infnorm(a *s x) = abs a * infnorm x"
+proof-
+  {assume a0: "a = 0" hence ?thesis by (simp add: infnorm_0) }
+  moreover
+  {assume a0: "a \<noteq> 0"
+    from a0 have th: "(1/a) *s (a *s x) = x"
+      by (simp add: vector_smult_assoc)
+    from a0 have ap: "\<bar>a\<bar> > 0" by arith
+    from infnorm_mul_lemma[of "1/a" "a *s x"]
+    have "infnorm x \<le> 1/\<bar>a\<bar> * infnorm (a*s x)"
+      unfolding th by simp
+    with ap have "\<bar>a\<bar> * infnorm x \<le> \<bar>a\<bar> * (1/\<bar>a\<bar> * infnorm (a *s x))" by (simp add: field_simps)
+    then have "\<bar>a\<bar> * infnorm x \<le> infnorm (a*s x)" 
+      using ap by (simp add: field_simps)
+    with infnorm_mul_lemma[of a x] have ?thesis by arith }
+  ultimately show ?thesis by blast
+qed
+
+lemma infnorm_pos_lt: "infnorm x > 0 \<longleftrightarrow> x \<noteq> 0"
+  using infnorm_pos_le[of x] infnorm_eq_0[of x] by arith
+
+(* Prove that it differs only up to a bound from Euclidean norm.             *)
+
+lemma infnorm_le_norm: "infnorm x \<le> norm x"
+  unfolding infnorm_def rsup_finite_le_iff[OF infnorm_set_lemma] 
+  unfolding infnorm_set_image  ball_simps
+  by (metis component_le_norm)
+lemma card_enum: "card {1 .. n} = n" by auto
+lemma norm_le_infnorm: "norm(x) <= sqrt(real (dimindex(UNIV ::'n set))) * infnorm(x::real ^'n)"
+proof-
+  let ?d = "dimindex(UNIV ::'n set)"
+  have d: "?d = card {1 .. ?d}" by auto
+  have "real ?d \<ge> 0" by simp
+  hence d2: "(sqrt (real ?d))^2 = real ?d"
+    by (auto intro: real_sqrt_pow2)
+  have th: "sqrt (real ?d) * infnorm x \<ge> 0"
+    by (simp add: dimindex_ge_1 zero_le_mult_iff real_sqrt_ge_0_iff infnorm_pos_le)
+  have th1: "x\<bullet>x \<le> (sqrt (real ?d) * infnorm x)^2"
+    unfolding power_mult_distrib d2 
+    apply (subst d)
+    apply (subst power2_abs[symmetric])
+    unfolding real_of_nat_def dot_def power2_eq_square[symmetric]
+    apply (subst power2_abs[symmetric])
+    apply (rule setsum_bounded)
+    apply (rule power_mono)
+    unfolding abs_of_nonneg[OF infnorm_pos_le] 
+    unfolding infnorm_def  rsup_finite_ge_iff[OF infnorm_set_lemma]
+    unfolding infnorm_set_image bex_simps
+    apply blast
+    by (rule abs_ge_zero)
+  from real_le_lsqrt[OF dot_pos_le th th1]
+  show ?thesis unfolding real_vector_norm_def  real_of_real_def id_def . 
+qed
+
+(* Equality in Cauchy-Schwarz and triangle inequalities.                     *)
+
+lemma norm_cauchy_schwarz_eq: "(x::real ^'n) \<bullet> y = norm x * norm y \<longleftrightarrow> norm x *s y = norm y *s x" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume h: "x = 0"
+    hence ?thesis by (simp add: norm_0)}
+  moreover
+  {assume h: "y = 0"
+    hence ?thesis by (simp add: norm_0)}
+  moreover
+  {assume x: "x \<noteq> 0" and y: "y \<noteq> 0"
+    from dot_eq_0[of "norm y *s x - norm x *s y"]
+    have "?rhs \<longleftrightarrow> (norm y * (norm y * norm x * norm x - norm x * (x \<bullet> y)) - norm x * (norm y * (y \<bullet> x) - norm x * norm y * norm y) =  0)"
+      using x y
+      unfolding dot_rsub dot_lsub dot_lmult dot_rmult
+      unfolding norm_pow_2[symmetric] power2_eq_square diff_eq_0_iff_eq apply (simp add: dot_sym)
+      apply (simp add: ring_simps)
+      apply metis
+      done
+    also have "\<dots> \<longleftrightarrow> (2 * norm x * norm y * (norm x * norm y - x \<bullet> y) = 0)" using x y
+      by (simp add: ring_simps dot_sym)
+    also have "\<dots> \<longleftrightarrow> ?lhs" using x y
+      apply (simp add: norm_eq_0)
+      by metis
+    finally have ?thesis by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma norm_cauchy_schwarz_abs_eq: "abs(x \<bullet> y) = norm x * norm y \<longleftrightarrow>
+                norm x *s y = norm y *s x \<or> norm(x) *s y = - norm y *s x" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  have th: "\<And>(x::real) a. a \<ge> 0 \<Longrightarrow> abs x = a \<longleftrightarrow> x = a \<or> x = - a" by arith
+  have "?rhs \<longleftrightarrow> norm x *s y = norm y *s x \<or> norm (- x) *s y = norm y *s (- x)"
+    apply (simp add: norm_neg) by vector
+  also have "\<dots> \<longleftrightarrow>(x \<bullet> y = norm x * norm y \<or>
+     (-x) \<bullet> y = norm x * norm y)"
+    unfolding norm_cauchy_schwarz_eq[symmetric]
+    unfolding norm_neg
+      norm_mul by blast
+  also have "\<dots> \<longleftrightarrow> ?lhs"
+    unfolding th[OF mult_nonneg_nonneg, OF norm_pos_le[of x] norm_pos_le[of y]] dot_lneg
+    by arith
+  finally show ?thesis ..
+qed
+
+lemma norm_triangle_eq: "norm(x + y) = norm x + norm y \<longleftrightarrow> norm x *s y = norm y *s x"
+proof-
+  {assume x: "x =0 \<or> y =0"
+    hence ?thesis by (cases "x=0", simp_all add: norm_0)}
+  moreover
+  {assume x: "x \<noteq> 0" and y: "y \<noteq> 0"
+    hence "norm x \<noteq> 0" "norm y \<noteq> 0"
+      by (simp_all add: norm_eq_0)
+    hence n: "norm x > 0" "norm y > 0" 
+      using norm_pos_le[of x] norm_pos_le[of y]
+      by arith+
+    have th: "\<And>(a::real) b c. a + b + c \<noteq> 0 ==> (a = b + c \<longleftrightarrow> a^2 = (b + c)^2)" by algebra
+    have "norm(x + y) = norm x + norm y \<longleftrightarrow> norm(x + y)^ 2 = (norm x + norm y) ^2"
+      apply (rule th) using n norm_pos_le[of "x + y"]
+      by arith
+    also have "\<dots> \<longleftrightarrow> norm x *s y = norm y *s x"
+      unfolding norm_cauchy_schwarz_eq[symmetric]
+      unfolding norm_pow_2 dot_ladd dot_radd
+      by (simp add: norm_pow_2[symmetric] power2_eq_square dot_sym ring_simps)
+    finally have ?thesis .}
+  ultimately show ?thesis by blast
+qed
+
+(* Collinearity.*)
+
+definition "collinear S \<longleftrightarrow> (\<exists>u. \<forall>x \<in> S. \<forall> y \<in> S. \<exists>c. x - y = c *s u)"
+
+lemma collinear_empty:  "collinear {}" by (simp add: collinear_def)
+
+lemma collinear_sing: "collinear {(x::'a::ring_1^'n)}" 
+  apply (simp add: collinear_def)
+  apply (rule exI[where x=0])
+  by simp
+
+lemma collinear_2: "collinear {(x::'a::ring_1^'n),y}"
+  apply (simp add: collinear_def)
+  apply (rule exI[where x="x - y"])
+  apply auto
+  apply (rule exI[where x=0], simp)
+  apply (rule exI[where x=1], simp)
+  apply (rule exI[where x="- 1"], simp add: vector_sneg_minus1[symmetric])
+  apply (rule exI[where x=0], simp)
+  done
+
+lemma collinear_lemma: "collinear {(0::real^'n),x,y} \<longleftrightarrow> x = 0 \<or> y = 0 \<or> (\<exists>c. y = c *s x)" (is "?lhs \<longleftrightarrow> ?rhs")
+proof-
+  {assume "x=0 \<or> y = 0" hence ?thesis 
+      by (cases "x = 0", simp_all add: collinear_2 insert_commute)}
+  moreover
+  {assume x: "x \<noteq> 0" and y: "y \<noteq> 0"
+    {assume h: "?lhs"
+      then obtain u where u: "\<forall> x\<in> {0,x,y}. \<forall>y\<in> {0,x,y}. \<exists>c. x - y = c *s u" unfolding collinear_def by blast
+      from u[rule_format, of x 0] u[rule_format, of y 0]
+      obtain cx and cy where 
+	cx: "x = cx*s u" and cy: "y = cy*s u"
+	by auto
+      from cx x have cx0: "cx \<noteq> 0" by auto
+      from cy y have cy0: "cy \<noteq> 0" by auto
+      let ?d = "cy / cx"
+      from cx cy cx0 have "y = ?d *s x" 
+	by (simp add: vector_smult_assoc)
+      hence ?rhs using x y by blast}
+    moreover
+    {assume h: "?rhs"
+      then obtain c where c: "y = c*s x" using x y by blast
+      have ?lhs unfolding collinear_def c
+	apply (rule exI[where x=x])
+	apply auto
+	apply (rule exI[where x=0], simp)
+	apply (rule exI[where x="- 1"], simp only: vector_smult_lneg vector_smult_lid)
+	apply (rule exI[where x= "-c"], simp only: vector_smult_lneg)
+	apply (rule exI[where x=1], simp)
+	apply (rule exI[where x=0], simp)
+	apply (rule exI[where x="1 - c"], simp add: vector_smult_lneg vector_sub_rdistrib)
+	apply (rule exI[where x="c - 1"], simp add: vector_smult_lneg vector_sub_rdistrib)
+	apply (rule exI[where x=0], simp)
+	done}
+    ultimately have ?thesis by blast}
+  ultimately show ?thesis by blast
+qed
+
+lemma norm_cauchy_schwarz_equal: "abs(x \<bullet> y) = norm x * norm y \<longleftrightarrow> collinear {(0::real^'n),x,y}"
+unfolding norm_cauchy_schwarz_abs_eq
+apply (cases "x=0", simp_all add: collinear_2 norm_0)
+apply (cases "y=0", simp_all add: collinear_2 norm_0 insert_commute)
+unfolding collinear_lemma
+apply simp
+apply (subgoal_tac "norm x \<noteq> 0")
+apply (subgoal_tac "norm y \<noteq> 0")
+apply (rule iffI)
+apply (cases "norm x *s y = norm y *s x")
+apply (rule exI[where x="(1/norm x) * norm y"])
+apply (drule sym)
+unfolding vector_smult_assoc[symmetric]
+apply (simp add: vector_smult_assoc field_simps)
+apply (rule exI[where x="(1/norm x) * - norm y"])
+apply clarify
+apply (drule sym)
+unfolding vector_smult_assoc[symmetric]
+apply (simp add: vector_smult_assoc field_simps)
+apply (erule exE)
+apply (erule ssubst)
+unfolding vector_smult_assoc
+unfolding norm_mul
+apply (subgoal_tac "norm x * c = \<bar>c\<bar> * norm x \<or> norm x * c = - \<bar>c\<bar> * norm x")
+apply (case_tac "c <= 0", simp add: ring_simps)
+apply (simp add: ring_simps)
+apply (case_tac "c <= 0", simp add: ring_simps)
+apply (simp add: ring_simps)
+apply (simp add: norm_eq_0)
+apply (simp add: norm_eq_0)
+done
+
+end
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Finite_Cartesian_Product.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,269 @@
+(* Title:      HOL/Library/Finite_Cartesian_Product
+   ID:         $Id: Finite_Cartesian_Product.thy,v 1.5 2009/01/29 22:59:46 chaieb Exp $
+   Author:     Amine Chaieb, University of Cambridge
+*)
+
+header {* Definition of finite Cartesian product types. *}
+
+theory Finite_Cartesian_Product
+  (* imports Plain SetInterval ATP_Linkup *)
+imports Main
+begin
+
+  (* FIXME : ATP_Linkup is only needed for metis at a few places. We could dispense of that by changing the proofs*)
+subsection{* Dimention of sets *}
+
+definition "dimindex (S:: 'a set) = (if finite (UNIV::'a set) then card (UNIV:: 'a set) else 1)"
+
+syntax "_type_dimindex" :: "type => nat" ("(1DIM/(1'(_')))")
+translations "DIM(t)" => "CONST dimindex (UNIV :: t set)"
+
+lemma dimindex_nonzero: "dimindex S \<noteq>  0"
+unfolding dimindex_def 
+by (simp add: neq0_conv[symmetric] del: neq0_conv)
+
+lemma dimindex_ge_1: "dimindex S \<ge> 1"
+  using dimindex_nonzero[of S] by arith 
+lemma dimindex_univ: "dimindex (S :: 'a set) = DIM('a)" by (simp add: dimindex_def)
+
+definition hassize (infixr "hassize" 12) where
+  "(S hassize n) = (finite S \<and> card S = n)"
+
+lemma dimindex_unique: " (UNIV :: 'a set) hassize n ==> DIM('a) = n"
+by (simp add: dimindex_def hassize_def)
+
+
+section{* An indexing type parametrized by base type. *}
+
+typedef 'a finite_image = "{1 .. DIM('a)}"
+  using dimindex_ge_1 by auto
+
+lemma finite_image_image: "(UNIV :: 'a finite_image set) = Abs_finite_image ` {1 .. DIM('a)}"
+apply (auto simp add: Abs_finite_image_inverse image_def finite_image_def)
+apply (rule_tac x="Rep_finite_image x" in bexI)
+apply (simp_all add: Rep_finite_image_inverse Rep_finite_image)
+using Rep_finite_image[where ?'a = 'a]
+unfolding finite_image_def
+apply simp
+done
+
+text{* Dimension of such a type, and indexing over it. *}
+
+lemma inj_on_Abs_finite_image: 
+  "inj_on (Abs_finite_image:: _ \<Rightarrow> 'a finite_image) {1 .. DIM('a)}"
+by (auto simp add: inj_on_def finite_image_def Abs_finite_image_inject[where ?'a='a])
+
+lemma has_size_finite_image: "(UNIV:: 'a finite_image set) hassize dimindex (S :: 'a set)"
+  unfolding hassize_def finite_image_image card_image[OF inj_on_Abs_finite_image[where ?'a='a]] by (auto simp add: dimindex_def)
+
+lemma hassize_image_inj: assumes f: "inj_on f S" and S: "S hassize n"
+  shows "f ` S hassize n"
+  using f S card_image[OF f]
+    by (simp add: hassize_def inj_on_def)
+
+lemma card_finite_image: "card (UNIV:: 'a finite_image set) = dimindex(S:: 'a set)"
+using has_size_finite_image
+unfolding hassize_def by blast
+
+lemma finite_finite_image: "finite (UNIV:: 'a finite_image set)"
+using has_size_finite_image
+unfolding hassize_def by blast
+
+lemma dimindex_finite_image: "dimindex (S:: 'a finite_image set) = dimindex(T:: 'a set)"
+unfolding card_finite_image[of T, symmetric]
+by (auto simp add: dimindex_def finite_finite_image)
+
+lemma Abs_finite_image_works: 
+  fixes i:: "'a finite_image"
+  shows " \<exists>!n \<in> {1 .. DIM('a)}. Abs_finite_image n = i"
+  unfolding Bex1_def Ex1_def
+  apply (rule_tac x="Rep_finite_image i" in exI)
+  using Rep_finite_image_inverse[where ?'a = 'a] 
+    Rep_finite_image[where ?'a = 'a] 
+  Abs_finite_image_inverse[where ?'a='a, symmetric]
+  by (auto simp add: finite_image_def)
+
+lemma Abs_finite_image_inj: 
+ "i \<in> {1 .. DIM('a)} \<Longrightarrow> j \<in> {1 .. DIM('a)}
+  \<Longrightarrow> (((Abs_finite_image i ::'a finite_image) = Abs_finite_image j) \<longleftrightarrow> (i = j))"
+  using Abs_finite_image_works[where ?'a = 'a] 
+  by (auto simp add: atLeastAtMost_iff Bex1_def)
+
+lemma forall_Abs_finite_image: 
+  "(\<forall>k:: 'a finite_image. P k) \<longleftrightarrow> (\<forall>i \<in> {1 .. DIM('a)}. P(Abs_finite_image i))"
+unfolding Ball_def atLeastAtMost_iff Ex1_def
+using Abs_finite_image_works[where ?'a = 'a, unfolded atLeastAtMost_iff Bex1_def]
+by metis
+
+subsection {* Finite Cartesian products, with indexing and lambdas. *}
+
+typedef (Cart)
+  ('a, 'b) "^" (infixl "^" 15)
+    = "{f:: 'b finite_image \<Rightarrow> 'a . True}" by simp
+
+abbreviation dimset:: "('a ^ 'n) \<Rightarrow> nat set" where
+  "dimset a \<equiv> {1 .. DIM('n)}"
+
+definition Cart_nth :: "'a ^ 'b \<Rightarrow> nat \<Rightarrow> 'a" (infixl "$" 90) where
+  "x$i = Rep_Cart x (Abs_finite_image i)"
+
+lemma stupid_ext: "(\<forall>x. f x = g x) \<longleftrightarrow> (f = g)"
+  apply auto
+  apply (rule ext)
+  apply auto
+  done
+lemma Cart_eq: "((x:: 'a ^ 'b) = y) \<longleftrightarrow> (\<forall>i\<in> dimset x. x$i = y$i)"
+  unfolding Cart_nth_def forall_Abs_finite_image[symmetric, where P = "\<lambda>i. Rep_Cart x i = Rep_Cart y i"] stupid_ext
+  using Rep_Cart_inject[of x y] ..
+
+consts Cart_lambda :: "(nat \<Rightarrow> 'a) \<Rightarrow> 'a ^ 'b" 
+notation (xsymbols) Cart_lambda (binder "\<chi>" 10)
+
+defs Cart_lambda_def: "Cart_lambda g == (SOME (f:: 'a ^ 'b). \<forall>i \<in> {1 .. DIM('b)}. f$i = g i)"
+
+lemma  Cart_lambda_beta: " \<forall> i\<in> {1 .. DIM('b)}. (Cart_lambda g:: 'a ^ 'b)$i = g i"
+  unfolding Cart_lambda_def
+proof (rule someI_ex)
+  let ?p = "\<lambda>(i::nat) (k::'b finite_image). i \<in> {1 .. DIM('b)} \<and> (Abs_finite_image i = k)"
+  let ?f = "Abs_Cart (\<lambda>k. g (THE i. ?p i k)):: 'a ^ 'b"
+  let ?P = "\<lambda>f i. f$i = g i"
+  let ?Q = "\<lambda>(f::'a ^ 'b). \<forall> i \<in> {1 .. DIM('b)}. ?P f i"
+  {fix i 
+    assume i: "i \<in> {1 .. DIM('b)}"
+    let ?j = "THE j. ?p j (Abs_finite_image i)"
+    from theI'[where P = "\<lambda>j. ?p (j::nat) (Abs_finite_image i :: 'b finite_image)", OF Abs_finite_image_works[of "Abs_finite_image i :: 'b finite_image", unfolded Bex1_def]]
+    have j: "?j \<in> {1 .. DIM('b)}" "(Abs_finite_image ?j :: 'b finite_image) = Abs_finite_image i" by blast+
+    from i j Abs_finite_image_inject[of i ?j, where ?'a = 'b]
+    have th: "?j = i" by (simp add: finite_image_def)  
+    have "?P ?f i"
+      using th
+      by (simp add: Cart_nth_def Abs_Cart_inverse Rep_Cart_inverse Cart_def) }
+  hence th0: "?Q ?f" ..
+  with th0 show "\<exists>f. ?Q f" unfolding Ex1_def by auto
+qed
+
+lemma  Cart_lambda_beta': "i\<in> {1 .. DIM('b)} \<Longrightarrow> (Cart_lambda g:: 'a ^ 'b)$i = g i"
+  using Cart_lambda_beta by blast
+
+lemma Cart_lambda_unique:
+  fixes f :: "'a ^ 'b"
+  shows "(\<forall>i\<in> {1 .. DIM('b)}. f$i = g i) \<longleftrightarrow> Cart_lambda g = f"
+  by (auto simp add: Cart_eq Cart_lambda_beta)
+
+lemma Cart_lambda_eta: "(\<chi> i. (g$i)) = g" by (simp add: Cart_eq Cart_lambda_beta)
+
+text{* A non-standard sum to "paste" Cartesian products. *}
+
+typedef ('a,'b) finite_sum = "{1 .. DIM('a) + DIM('b)}"
+  apply (rule exI[where x="1"])
+  using dimindex_ge_1[of "UNIV :: 'a set"] dimindex_ge_1[of "UNIV :: 'b set"]
+  by auto
+
+definition pastecart :: "'a ^ 'm \<Rightarrow> 'a ^ 'n \<Rightarrow> 'a ^ ('m,'n) finite_sum" where
+  "pastecart f g = (\<chi> i. (if i <= DIM('m) then f$i else g$(i - DIM('m))))"
+
+definition fstcart:: "'a ^('m, 'n) finite_sum \<Rightarrow> 'a ^ 'm" where
+  "fstcart f = (\<chi> i. (f$i))"
+
+definition sndcart:: "'a ^('m, 'n) finite_sum \<Rightarrow> 'a ^ 'n" where
+  "sndcart f = (\<chi> i. (f$(i + DIM('m))))"
+
+lemma finite_sum_image: "(UNIV::('a,'b) finite_sum set) = Abs_finite_sum ` {1 .. DIM('a) + DIM('b)}"
+apply (auto  simp add: image_def)
+apply (rule_tac x="Rep_finite_sum x" in bexI)
+apply (simp add: Rep_finite_sum_inverse)
+using Rep_finite_sum[unfolded finite_sum_def, where ?'a = 'a and ?'b = 'b]
+apply (simp add: Rep_finite_sum)
+done
+
+lemma inj_on_Abs_finite_sum: "inj_on (Abs_finite_sum :: _ \<Rightarrow> ('a,'b) finite_sum) {1 .. DIM('a) + DIM('b)}" 
+  using Abs_finite_sum_inject[where ?'a = 'a and ?'b = 'b]
+  by (auto simp add: inj_on_def finite_sum_def)
+
+lemma dimindex_has_size_finite_sum:
+  "(UNIV::('m,'n) finite_sum set) hassize (DIM('m) + DIM('n))"
+  by (simp add: finite_sum_image hassize_def card_image[OF inj_on_Abs_finite_sum[where ?'a = 'm and ?'b = 'n]] del: One_nat_def)
+
+lemma dimindex_finite_sum: "DIM(('m,'n) finite_sum) = DIM('m) + DIM('n)"
+  using dimindex_has_size_finite_sum[where ?'n = 'n and ?'m = 'm, unfolded hassize_def]
+  by (simp add: dimindex_def)
+
+lemma fstcart_pastecart: "fstcart (pastecart (x::'a ^'m ) (y:: 'a ^ 'n)) = x"
+  by (simp add: pastecart_def fstcart_def Cart_eq Cart_lambda_beta dimindex_finite_sum)
+
+lemma sndcart_pastecart: "sndcart (pastecart (x::'a ^'m ) (y:: 'a ^ 'n)) = y"
+  by (simp add: pastecart_def sndcart_def Cart_eq Cart_lambda_beta dimindex_finite_sum)
+
+lemma pastecart_fst_snd: "pastecart (fstcart z) (sndcart z) = z"
+proof -
+ {fix i
+  assume H: "i \<le> DIM('b) + DIM('c)" 
+    "\<not> i \<le> DIM('b)"
+    from H have ith: "i - DIM('b) \<in> {1 .. DIM('c)}"
+      apply simp by arith
+    from H have th0: "i - DIM('b) + DIM('b) = i"
+      by simp
+  have "(\<chi> i. (z$(i + DIM('b))) :: 'a ^ 'c)$(i - DIM('b)) = z$i"
+    unfolding Cart_lambda_beta'[where g = "\<lambda> i. z$(i + DIM('b))", OF ith] th0 ..}
+thus ?thesis by (auto simp add: pastecart_def fstcart_def sndcart_def Cart_eq Cart_lambda_beta dimindex_finite_sum)
+qed
+
+lemma pastecart_eq: "(x = y) \<longleftrightarrow> (fstcart x = fstcart y) \<and> (sndcart x = sndcart y)"
+  using pastecart_fst_snd[of x] pastecart_fst_snd[of y] by metis
+
+lemma forall_pastecart: "(\<forall>p. P p) \<longleftrightarrow> (\<forall>x y. P (pastecart x y))"
+  by (metis pastecart_fst_snd fstcart_pastecart sndcart_pastecart)
+
+lemma exists_pastecart: "(\<exists>p. P p)  \<longleftrightarrow> (\<exists>x y. P (pastecart x y))"
+  by (metis pastecart_fst_snd fstcart_pastecart sndcart_pastecart)
+
+text{* The finiteness lemma. *}
+
+lemma finite_cart:
+ "\<forall>i \<in> {1 .. DIM('n)}. finite {x.  P i x}
+  \<Longrightarrow> finite {v::'a ^ 'n . (\<forall>i \<in> {1 .. DIM('n)}. P i (v$i))}"
+proof-
+  assume f: "\<forall>i \<in> {1 .. DIM('n)}. finite {x.  P i x}"
+  {fix n
+    assume n: "n \<le> DIM('n)"
+    have "finite {v:: 'a ^ 'n . (\<forall>i\<in> {1 .. DIM('n)}. i \<le> n \<longrightarrow> P i (v$i))
+                              \<and> (\<forall>i\<in> {1 .. DIM('n)}. n < i \<longrightarrow> v$i = (SOME x. False))}" 
+      using n 
+      proof(induct n)
+	case 0
+	have th0: "{v . (\<forall>i \<in> {1 .. DIM('n)}. v$i = (SOME x. False))} =
+      {(\<chi> i. (SOME x. False)::'a ^ 'n)}" by (auto simp add: Cart_lambda_beta Cart_eq)
+	with "0.prems" show ?case by auto
+      next
+	case (Suc n)
+	let ?h = "\<lambda>(x::'a,v:: 'a ^ 'n). (\<chi> i. if i = Suc n then x else v$i):: 'a ^ 'n"
+	let ?T = "{v\<Colon>'a ^ 'n.
+            (\<forall>i\<Colon>nat\<in>{1\<Colon>nat..DIM('n)}. i \<le> Suc n \<longrightarrow> P i (v$i)) \<and>
+            (\<forall>i\<Colon>nat\<in>{1\<Colon>nat..DIM('n)}.
+                Suc n < i \<longrightarrow> v$i = (SOME x\<Colon>'a. False))}"
+	let ?S = "{x::'a . P (Suc  n) x} \<times> {v:: 'a^'n. (\<forall>i \<in> {1 .. DIM('n)}. i <= n \<longrightarrow> P i (v$i)) \<and> (\<forall>i \<in> {1 .. DIM('n)}. n < i \<longrightarrow> v$i = (SOME x. False))}"
+	have th0: " ?T \<subseteq> (?h ` ?S)" 
+	  using Suc.prems
+	  apply (auto simp add: image_def)
+	  apply (rule_tac x = "x$(Suc n)" in exI)
+	  apply (rule conjI)
+	  apply (rotate_tac)
+	  apply (erule ballE[where x="Suc n"])
+	  apply simp
+	  apply simp
+	  apply (rule_tac x= "\<chi> i. if i = Suc n then (SOME x:: 'a. False) else (x:: 'a ^ 'n)$i:: 'a ^ 'n" in exI)
+	  by (simp add: Cart_eq Cart_lambda_beta)
+	have th1: "finite ?S" 
+	  apply (rule finite_cartesian_product) 
+	  using f Suc.hyps Suc.prems by auto 
+	from finite_imageI[OF th1] have th2: "finite (?h ` ?S)" . 
+	from finite_subset[OF th0 th2] show ?case by blast 
+      qed}
+
+  note th = this
+  from this[of "DIM('n)"] f
+  show ?thesis by auto
+qed
+
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Glbs.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,85 @@
+(* Title:      Glbs
+   ID:         $Id: 
+   Author:     Amine Chaieb, University of Cambridge
+*)
+
+header{*Definitions of Lower Bounds and Greatest Lower Bounds, analogous to Lubs*}
+
+theory Glbs
+imports Lubs
+begin
+
+definition
+  greatestP      :: "['a =>bool,'a::ord] => bool" where
+  "greatestP P x = (P x & Collect P *<=  x)"
+
+definition
+  isLb        :: "['a set, 'a set, 'a::ord] => bool" where
+  "isLb R S x = (x <=* S & x: R)"
+
+definition
+  isGlb       :: "['a set, 'a set, 'a::ord] => bool" where
+  "isGlb R S x = greatestP (isLb R S) x"
+
+definition
+  lbs         :: "['a set, 'a::ord set] => 'a set" where
+  "lbs R S = Collect (isLb R S)"
+
+subsection{*Rules about the Operators @{term greatestP}, @{term isLb}
+    and @{term isGlb}*}
+
+lemma leastPD1: "greatestP P x ==> P x"
+by (simp add: greatestP_def)
+
+lemma greatestPD2: "greatestP P x ==> Collect P *<= x"
+by (simp add: greatestP_def)
+
+lemma greatestPD3: "[| greatestP P x; y: Collect P |] ==> x >= y"
+by (blast dest!: greatestPD2 setleD)
+
+lemma isGlbD1: "isGlb R S x ==> x <=* S"
+by (simp add: isGlb_def isLb_def greatestP_def)
+
+lemma isGlbD1a: "isGlb R S x ==> x: R"
+by (simp add: isGlb_def isLb_def greatestP_def)
+
+lemma isGlb_isLb: "isGlb R S x ==> isLb R S x"
+apply (simp add: isLb_def)
+apply (blast dest: isGlbD1 isGlbD1a)
+done
+
+lemma isGlbD2: "[| isGlb R S x; y : S |] ==> y >= x"
+by (blast dest!: isGlbD1 setgeD)
+
+lemma isGlbD3: "isGlb R S x ==> greatestP(isLb R S) x"
+by (simp add: isGlb_def)
+
+lemma isGlbI1: "greatestP(isLb R S) x ==> isGlb R S x"
+by (simp add: isGlb_def)
+
+lemma isGlbI2: "[| isLb R S x; Collect (isLb R S) *<= x |] ==> isGlb R S x"
+by (simp add: isGlb_def greatestP_def)
+
+lemma isLbD: "[| isLb R S x; y : S |] ==> y >= x"
+by (simp add: isLb_def setge_def)
+
+lemma isLbD2: "isLb R S x ==> x <=* S "
+by (simp add: isLb_def)
+
+lemma isLbD2a: "isLb R S x ==> x: R"
+by (simp add: isLb_def)
+
+lemma isLbI: "[| x <=* S ; x: R |] ==> isLb R S x"
+by (simp add: isLb_def)
+
+lemma isGlb_le_isLb: "[| isGlb R S x; isLb R S y |] ==> x >= y"
+apply (simp add: isGlb_def)
+apply (blast intro!: greatestPD3)
+done
+
+lemma isGlb_ubs: "isGlb R S x ==> lbs R S *<= x"
+apply (simp add: lbs_def isGlb_def)
+apply (erule greatestPD2)
+done
+
+end
--- a/src/HOL/Library/Infinite_Set.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Library/Infinite_Set.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -6,7 +6,7 @@
 header {* Infinite Sets and Related Concepts *}
 
 theory Infinite_Set
-imports Plain "~~/src/HOL/SetInterval" "~~/src/HOL/Hilbert_Choice"
+imports Main "~~/src/HOL/SetInterval" "~~/src/HOL/Hilbert_Choice"
 begin
 
 
--- a/src/HOL/Library/Library.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Library/Library.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -15,6 +15,7 @@
   Continuity
   ContNotDenum
   Countable
+  Determinants
   Efficient_Nat
   Enum
   Eval_Witness
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Order_Relation.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,101 @@
+(*  ID          : $Id$
+    Author      : Tobias Nipkow
+*)
+
+header {* Orders as Relations *}
+
+theory Order_Relation
+imports Main
+begin
+
+subsection{* Orders on a set *}
+
+definition "preorder_on A r \<equiv> refl A r \<and> trans r"
+
+definition "partial_order_on A r \<equiv> preorder_on A r \<and> antisym r"
+
+definition "linear_order_on A r \<equiv> partial_order_on A r \<and> total_on A r"
+
+definition "strict_linear_order_on A r \<equiv> trans r \<and> irrefl r \<and> total_on A r"
+
+definition "well_order_on A r \<equiv> linear_order_on A r \<and> wf(r - Id)"
+
+lemmas order_on_defs =
+  preorder_on_def partial_order_on_def linear_order_on_def
+  strict_linear_order_on_def well_order_on_def
+
+
+lemma preorder_on_empty[simp]: "preorder_on {} {}"
+by(simp add:preorder_on_def trans_def)
+
+lemma partial_order_on_empty[simp]: "partial_order_on {} {}"
+by(simp add:partial_order_on_def)
+
+lemma lnear_order_on_empty[simp]: "linear_order_on {} {}"
+by(simp add:linear_order_on_def)
+
+lemma well_order_on_empty[simp]: "well_order_on {} {}"
+by(simp add:well_order_on_def)
+
+
+lemma preorder_on_converse[simp]: "preorder_on A (r^-1) = preorder_on A r"
+by (simp add:preorder_on_def)
+
+lemma partial_order_on_converse[simp]:
+  "partial_order_on A (r^-1) = partial_order_on A r"
+by (simp add: partial_order_on_def)
+
+lemma linear_order_on_converse[simp]:
+  "linear_order_on A (r^-1) = linear_order_on A r"
+by (simp add: linear_order_on_def)
+
+
+lemma strict_linear_order_on_diff_Id:
+  "linear_order_on A r \<Longrightarrow> strict_linear_order_on A (r-Id)"
+by(simp add: order_on_defs trans_diff_Id)
+
+
+subsection{* Orders on the field *}
+
+abbreviation "Refl r \<equiv> refl (Field r) r"
+
+abbreviation "Preorder r \<equiv> preorder_on (Field r) r"
+
+abbreviation "Partial_order r \<equiv> partial_order_on (Field r) r"
+
+abbreviation "Total r \<equiv> total_on (Field r) r"
+
+abbreviation "Linear_order r \<equiv> linear_order_on (Field r) r"
+
+abbreviation "Well_order r \<equiv> well_order_on (Field r) r"
+
+
+lemma subset_Image_Image_iff:
+  "\<lbrakk> Preorder r; A \<subseteq> Field r; B \<subseteq> Field r\<rbrakk> \<Longrightarrow>
+   r `` A \<subseteq> r `` B \<longleftrightarrow> (\<forall>a\<in>A.\<exists>b\<in>B. (b,a):r)"
+apply(auto simp add: subset_eq preorder_on_def refl_def Image_def)
+apply metis
+by(metis trans_def)
+
+lemma subset_Image1_Image1_iff:
+  "\<lbrakk> Preorder r; a : Field r; b : Field r\<rbrakk> \<Longrightarrow> r `` {a} \<subseteq> r `` {b} \<longleftrightarrow> (b,a):r"
+by(simp add:subset_Image_Image_iff)
+
+lemma Refl_antisym_eq_Image1_Image1_iff:
+  "\<lbrakk>Refl r; antisym r; a:Field r; b:Field r\<rbrakk> \<Longrightarrow> r `` {a} = r `` {b} \<longleftrightarrow> a=b"
+by(simp add: expand_set_eq antisym_def refl_def) metis
+
+lemma Partial_order_eq_Image1_Image1_iff:
+  "\<lbrakk>Partial_order r; a:Field r; b:Field r\<rbrakk> \<Longrightarrow> r `` {a} = r `` {b} \<longleftrightarrow> a=b"
+by(auto simp:order_on_defs Refl_antisym_eq_Image1_Image1_iff)
+
+
+subsection{* Orders on a type *}
+
+abbreviation "strict_linear_order \<equiv> strict_linear_order_on UNIV"
+
+abbreviation "linear_order \<equiv> linear_order_on UNIV"
+
+abbreviation "well_order r \<equiv> well_order_on UNIV"
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/Permutations.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,862 @@
+(* Title:      Library/Permutations
+   ID:         $Id: 
+   Author:     Amine Chaieb, University of Cambridge
+*)
+
+header {* Permutations, both general and specifically on finite sets.*}
+
+theory Permutations
+imports Main Finite_Cartesian_Product Parity 
+begin
+
+  (* Why should I import Main just to solve the Typerep problem! *)
+
+definition permutes (infixr "permutes" 41) where
+  "(p permutes S) \<longleftrightarrow> (\<forall>x. x \<notin> S \<longrightarrow> p x = x) \<and> (\<forall>y. \<exists>!x. p x = y)"
+
+(* ------------------------------------------------------------------------- *)
+(* Transpositions.                                                           *)
+(* ------------------------------------------------------------------------- *)
+
+declare swap_self[simp]
+lemma swapid_sym: "Fun.swap a b id = Fun.swap b a id" 
+  by (auto simp add: expand_fun_eq swap_def fun_upd_def)
+lemma swap_id_refl: "Fun.swap a a id = id" by simp
+lemma swap_id_sym: "Fun.swap a b id = Fun.swap b a id"
+  by (rule ext, simp add: swap_def)
+lemma swap_id_idempotent[simp]: "Fun.swap a b id o Fun.swap a b id = id"
+  by (rule ext, auto simp add: swap_def)
+
+lemma inv_unique_comp: assumes fg: "f o g = id" and gf: "g o f = id"
+  shows "inv f = g"
+  using fg gf inv_equality[of g f] by (auto simp add: expand_fun_eq)
+
+lemma inverse_swap_id: "inv (Fun.swap a b id) = Fun.swap a b id"
+  by (rule inv_unique_comp, simp_all)
+
+lemma swap_id_eq: "Fun.swap a b id x = (if x = a then b else if x = b then a else x)"
+  by (simp add: swap_def)
+
+(* ------------------------------------------------------------------------- *)
+(* Basic consequences of the definition.                                     *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutes_in_image: "p permutes S \<Longrightarrow> p x \<in> S \<longleftrightarrow> x \<in> S"
+  unfolding permutes_def by metis
+
+lemma permutes_image: assumes pS: "p permutes S" shows "p ` S = S"
+  using pS
+  unfolding permutes_def 
+  apply - 
+  apply (rule set_ext) 
+  apply (simp add: image_iff)
+  apply metis
+  done
+
+lemma permutes_inj: "p permutes S ==> inj p " 
+  unfolding permutes_def inj_on_def by blast 
+
+lemma permutes_surj: "p permutes s ==> surj p" 
+  unfolding permutes_def surj_def by metis 
+
+lemma permutes_inv_o: assumes pS: "p permutes S"
+  shows " p o inv p = id"
+  and "inv p o p = id"
+  using permutes_inj[OF pS] permutes_surj[OF pS]
+  unfolding inj_iff[symmetric] surj_iff[symmetric] by blast+
+
+
+lemma permutes_inverses: 
+  fixes p :: "'a \<Rightarrow> 'a"
+  assumes pS: "p permutes S"
+  shows "p (inv p x) = x"
+  and "inv p (p x) = x"
+  using permutes_inv_o[OF pS, unfolded expand_fun_eq o_def] by auto
+
+lemma permutes_subset: "p permutes S \<Longrightarrow> S \<subseteq> T ==> p permutes T"
+  unfolding permutes_def by blast
+
+lemma permutes_empty[simp]: "p permutes {} \<longleftrightarrow> p = id"
+  unfolding expand_fun_eq permutes_def apply simp by metis 
+
+lemma permutes_sing[simp]: "p permutes {a} \<longleftrightarrow> p = id"
+  unfolding expand_fun_eq permutes_def apply simp by metis
+ 
+lemma permutes_univ: "p permutes UNIV \<longleftrightarrow> (\<forall>y. \<exists>!x. p x = y)"
+  unfolding permutes_def by simp
+
+lemma permutes_inv_eq: "p permutes S ==> inv p y = x \<longleftrightarrow> p x = y"
+  unfolding permutes_def inv_def apply auto
+  apply (erule allE[where x=y])
+  apply (erule allE[where x=y])
+  apply (rule someI_ex) apply blast
+  apply (rule some1_equality)
+  apply blast
+  apply blast
+  done
+
+lemma permutes_swap_id: "a \<in> S \<Longrightarrow> b \<in> S ==> Fun.swap a b id permutes S"
+  unfolding permutes_def swap_def fun_upd_def  apply auto apply metis done
+
+lemma permutes_superset: "p permutes S \<Longrightarrow> (\<forall>x \<in> S - T. p x = x) \<Longrightarrow> p permutes T"
+apply (simp add: Ball_def permutes_def Diff_iff) by metis
+
+(* ------------------------------------------------------------------------- *)
+(* Group properties.                                                         *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutes_id: "id permutes S" unfolding permutes_def by simp 
+
+lemma permutes_compose: "p permutes S \<Longrightarrow> q permutes S ==> q o p permutes S"
+  unfolding permutes_def o_def by metis
+
+lemma permutes_inv: assumes pS: "p permutes S" shows "inv p permutes S"
+  using pS unfolding permutes_def permutes_inv_eq[OF pS] by metis  
+
+lemma permutes_inv_inv: assumes pS: "p permutes S" shows "inv (inv p) = p"
+  unfolding expand_fun_eq permutes_inv_eq[OF pS] permutes_inv_eq[OF permutes_inv[OF pS]]
+  by blast
+
+(* ------------------------------------------------------------------------- *)
+(* The number of permutations on a finite set.                               *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutes_insert_lemma: 
+  assumes pS: "p permutes (insert a S)"
+  shows "Fun.swap a (p a) id o p permutes S"
+  apply (rule permutes_superset[where S = "insert a S"])
+  apply (rule permutes_compose[OF pS])
+  apply (rule permutes_swap_id, simp)
+  using permutes_in_image[OF pS, of a] apply simp
+  apply (auto simp add: Ball_def Diff_iff swap_def)
+  done
+
+lemma permutes_insert: "{p. p permutes (insert a S)} =
+        (\<lambda>(b,p). Fun.swap a b id o p) ` {(b,p). b \<in> insert a S \<and> p \<in> {p. p permutes S}}"
+proof-
+
+  {fix p 
+    {assume pS: "p permutes insert a S"
+      let ?b = "p a"
+      let ?q = "Fun.swap a (p a) id o p"
+      have th0: "p = Fun.swap a ?b id o ?q" unfolding expand_fun_eq o_assoc by simp 
+      have th1: "?b \<in> insert a S " unfolding permutes_in_image[OF pS] by simp 
+      from permutes_insert_lemma[OF pS] th0 th1
+      have "\<exists> b q. p = Fun.swap a b id o q \<and> b \<in> insert a S \<and> q permutes S" by blast}
+    moreover
+    {fix b q assume bq: "p = Fun.swap a b id o q" "b \<in> insert a S" "q permutes S"
+      from permutes_subset[OF bq(3), of "insert a S"] 
+      have qS: "q permutes insert a S" by auto
+      have aS: "a \<in> insert a S" by simp
+      from bq(1) permutes_compose[OF qS permutes_swap_id[OF aS bq(2)]]
+      have "p permutes insert a S"  by simp }
+    ultimately have "p permutes insert a S \<longleftrightarrow> (\<exists> b q. p = Fun.swap a b id o q \<and> b \<in> insert a S \<and> q permutes S)" by blast}
+  thus ?thesis by auto
+qed
+
+lemma hassize_insert: "a \<notin> F \<Longrightarrow> insert a F hassize n \<Longrightarrow> F hassize (n - 1)"
+  by (auto simp add: hassize_def)
+
+lemma hassize_permutations: assumes Sn: "S hassize n"
+  shows "{p. p permutes S} hassize (fact n)"
+proof-
+  from Sn have fS:"finite S" by (simp add: hassize_def)
+
+  have "\<forall>n. (S hassize n) \<longrightarrow> ({p. p permutes S} hassize (fact n))"
+  proof(rule finite_induct[where F = S])
+    from fS show "finite S" .
+  next
+    show "\<forall>n. ({} hassize n) \<longrightarrow> ({p. p permutes {}} hassize fact n)"
+      by (simp add: hassize_def permutes_empty)
+  next
+    fix x F 
+    assume fF: "finite F" and xF: "x \<notin> F" 
+      and H: "\<forall>n. (F hassize n) \<longrightarrow> ({p. p permutes F} hassize fact n)"
+    {fix n assume H0: "insert x F hassize n"
+      let ?xF = "{p. p permutes insert x F}"
+      let ?pF = "{p. p permutes F}"
+      let ?pF' = "{(b, p). b \<in> insert x F \<and> p \<in> ?pF}"
+      let ?g = "(\<lambda>(b, p). Fun.swap x b id \<circ> p)"
+      from permutes_insert[of x F]
+      have xfgpF': "?xF = ?g ` ?pF'" .
+      from hassize_insert[OF xF H0] have Fs: "F hassize (n - 1)" .
+      from H Fs have pFs: "?pF hassize fact (n - 1)" by blast
+      hence pF'f: "finite ?pF'" using H0 unfolding hassize_def 
+	apply (simp only: Collect_split Collect_mem_eq)
+	apply (rule finite_cartesian_product)
+	apply simp_all
+	done
+
+      have ginj: "inj_on ?g ?pF'"
+      proof-
+	{
+	  fix b p c q assume bp: "(b,p) \<in> ?pF'" and cq: "(c,q) \<in> ?pF'" 
+	    and eq: "?g (b,p) = ?g (c,q)"
+	  from bp cq have ths: "b \<in> insert x F" "c \<in> insert x F" "x \<in> insert x F" "p permutes F" "q permutes F" by auto
+	  from ths(4) xF eq have "b = ?g (b,p) x" unfolding permutes_def 
+	    by (auto simp add: swap_def fun_upd_def expand_fun_eq)
+	  also have "\<dots> = ?g (c,q) x" using ths(5) xF eq  
+	    by (auto simp add: swap_def fun_upd_def expand_fun_eq)
+	  also have "\<dots> = c"using ths(5) xF unfolding permutes_def
+	    by (auto simp add: swap_def fun_upd_def expand_fun_eq)
+	  finally have bc: "b = c" .
+	  hence "Fun.swap x b id = Fun.swap x c id" by simp
+	  with eq have "Fun.swap x b id o p = Fun.swap x b id o q" by simp
+	  hence "Fun.swap x b id o (Fun.swap x b id o p) = Fun.swap x b id o (Fun.swap x b id o q)" by simp
+	  hence "p = q" by (simp add: o_assoc)
+	  with bc have "(b,p) = (c,q)" by simp }
+	thus ?thesis  unfolding inj_on_def by blast
+      qed
+      from xF H0 have n0: "n \<noteq> 0 " by (auto simp add: hassize_def)
+      hence "\<exists>m. n = Suc m" by arith
+      then obtain m where n[simp]: "n = Suc m" by blast 
+      from pFs H0 have xFc: "card ?xF = fact n" 
+	unfolding xfgpF' card_image[OF ginj] hassize_def
+	apply (simp only: Collect_split Collect_mem_eq card_cartesian_product)
+	by simp
+      from finite_imageI[OF pF'f, of ?g] have xFf: "finite ?xF" unfolding xfgpF' by simp 
+      have "?xF hassize fact n"
+	using xFf xFc 
+	unfolding hassize_def  xFf by blast }
+    thus "\<forall>n. (insert x F hassize n) \<longrightarrow> ({p. p permutes insert x F} hassize fact n)" 
+      by blast
+  qed
+  with Sn show ?thesis by blast
+qed
+
+lemma finite_permutations: "finite S ==> finite {p. p permutes S}"
+  using hassize_permutations[of S] unfolding hassize_def by blast
+
+(* ------------------------------------------------------------------------- *)
+(* Permutations of index set for iterated operations.                        *)
+(* ------------------------------------------------------------------------- *)
+
+lemma (in ab_semigroup_mult) fold_image_permute: assumes fS: "finite S" and pS: "p permutes S" 
+  shows "fold_image times f z S = fold_image times (f o p) z S"
+  using fold_image_reindex[OF fS subset_inj_on[OF permutes_inj[OF pS], of S, simplified], of f z]
+  unfolding permutes_image[OF pS] .
+lemma (in ab_semigroup_add) fold_image_permute: assumes fS: "finite S" and pS: "p permutes S" 
+  shows "fold_image plus f z S = fold_image plus (f o p) z S"
+proof-
+  interpret ab_semigroup_mult plus apply unfold_locales apply (simp add: add_assoc)
+    apply (simp add: add_commute) done
+  from fold_image_reindex[OF fS subset_inj_on[OF permutes_inj[OF pS], of S, simplified], of f z]
+  show ?thesis
+  unfolding permutes_image[OF pS] .
+qed
+
+lemma setsum_permute: assumes pS: "p permutes S" 
+  shows "setsum f S = setsum (f o p) S"
+  unfolding setsum_def using fold_image_permute[of S p f 0] pS by clarsimp
+
+lemma setsum_permute_natseg:assumes pS: "p permutes {m .. n}" 
+  shows "setsum f {m .. n} = setsum (f o p) {m .. n}"
+  using setsum_permute[OF pS, of f ] pS by blast 
+
+lemma setprod_permute: assumes pS: "p permutes S" 
+  shows "setprod f S = setprod (f o p) S"
+  unfolding setprod_def 
+  using ab_semigroup_mult_class.fold_image_permute[of S p f 1] pS by clarsimp
+
+lemma setprod_permute_natseg:assumes pS: "p permutes {m .. n}" 
+  shows "setprod f {m .. n} = setprod (f o p) {m .. n}"
+  using setprod_permute[OF pS, of f ] pS by blast 
+
+(* ------------------------------------------------------------------------- *)
+(* Various combinations of transpositions with 2, 1 and 0 common elements.   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma swap_id_common:" a \<noteq> c \<Longrightarrow> b \<noteq> c \<Longrightarrow>  Fun.swap a b id o Fun.swap a c id = Fun.swap b c id o Fun.swap a b id" by (simp add: expand_fun_eq swap_def)
+
+lemma swap_id_common': "~(a = b) \<Longrightarrow> ~(a = c) \<Longrightarrow> Fun.swap a c id o Fun.swap b c id = Fun.swap b c id o Fun.swap a b id" by (simp add: expand_fun_eq swap_def)
+
+lemma swap_id_independent: "~(a = c) \<Longrightarrow> ~(a = d) \<Longrightarrow> ~(b = c) \<Longrightarrow> ~(b = d) ==> Fun.swap a b id o Fun.swap c d id = Fun.swap c d id o Fun.swap a b id"
+  by (simp add: swap_def expand_fun_eq)
+
+(* ------------------------------------------------------------------------- *)
+(* Permutations as transposition sequences.                                  *)
+(* ------------------------------------------------------------------------- *)
+
+
+inductive swapidseq :: "nat \<Rightarrow> ('a \<Rightarrow> 'a) \<Rightarrow> bool" where
+  id[simp]: "swapidseq 0 id"
+| comp_Suc: "swapidseq n p \<Longrightarrow> a \<noteq> b \<Longrightarrow> swapidseq (Suc n) (Fun.swap a b id o p)"
+
+declare id[unfolded id_def, simp]
+definition "permutation p \<longleftrightarrow> (\<exists>n. swapidseq n p)"
+
+(* ------------------------------------------------------------------------- *)
+(* Some closure properties of the set of permutations, with lengths.         *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutation_id[simp]: "permutation id"unfolding permutation_def
+  by (rule exI[where x=0], simp)
+declare permutation_id[unfolded id_def, simp]
+
+lemma swapidseq_swap: "swapidseq (if a = b then 0 else 1) (Fun.swap a b id)"
+  apply clarsimp
+  using comp_Suc[of 0 id a b] by simp
+
+lemma permutation_swap_id: "permutation (Fun.swap a b id)"
+  apply (cases "a=b", simp_all)
+  unfolding permutation_def using swapidseq_swap[of a b] by blast 
+
+lemma swapidseq_comp_add: "swapidseq n p \<Longrightarrow> swapidseq m q ==> swapidseq (n + m) (p o q)"
+  proof (induct n p arbitrary: m q rule: swapidseq.induct)
+    case (id m q) thus ?case by simp
+  next
+    case (comp_Suc n p a b m q) 
+    have th: "Suc n + m = Suc (n + m)" by arith
+    show ?case unfolding th o_assoc[symmetric] 
+      apply (rule swapidseq.comp_Suc) using comp_Suc.hyps(2)[OF comp_Suc.prems]  comp_Suc.hyps(3) by blast+ 
+qed
+
+lemma permutation_compose: "permutation p \<Longrightarrow> permutation q ==> permutation(p o q)"
+  unfolding permutation_def using swapidseq_comp_add[of _ p _ q] by metis
+
+lemma swapidseq_endswap: "swapidseq n p \<Longrightarrow> a \<noteq> b ==> swapidseq (Suc n) (p o Fun.swap a b id)"
+  apply (induct n p rule: swapidseq.induct)
+  using swapidseq_swap[of a b]
+  by (auto simp add: o_assoc[symmetric] intro: swapidseq.comp_Suc)
+
+lemma swapidseq_inverse_exists: "swapidseq n p ==> \<exists>q. swapidseq n q \<and> p o q = id \<and> q o p = id"
+proof(induct n p rule: swapidseq.induct)
+  case id  thus ?case by (rule exI[where x=id], simp)
+next 
+  case (comp_Suc n p a b)
+  from comp_Suc.hyps obtain q where q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id" by blast
+  let ?q = "q o Fun.swap a b id"
+  note H = comp_Suc.hyps
+  from swapidseq_swap[of a b] H(3)  have th0: "swapidseq 1 (Fun.swap a b id)" by simp
+  from swapidseq_comp_add[OF q(1) th0] have th1:"swapidseq (Suc n) ?q" by simp 
+  have "Fun.swap a b id o p o ?q = Fun.swap a b id o (p o q) o Fun.swap a b id" by (simp add: o_assoc)
+  also have "\<dots> = id" by (simp add: q(2))
+  finally have th2: "Fun.swap a b id o p o ?q = id" .
+  have "?q \<circ> (Fun.swap a b id \<circ> p) = q \<circ> (Fun.swap a b id o Fun.swap a b id) \<circ> p" by (simp only: o_assoc) 
+  hence "?q \<circ> (Fun.swap a b id \<circ> p) = id" by (simp add: q(3))
+  with th1 th2 show ?case by blast
+qed
+
+
+lemma swapidseq_inverse: assumes H: "swapidseq n p" shows "swapidseq n (inv p)"
+  using swapidseq_inverse_exists[OF H] inv_unique_comp[of p] by auto
+
+lemma permutation_inverse: "permutation p ==> permutation (inv p)"
+  using permutation_def swapidseq_inverse by blast
+
+(* ------------------------------------------------------------------------- *)
+(* The identity map only has even transposition sequences.                   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma symmetry_lemma:"(\<And>a b c d. P a b c d ==> P a b d c) \<Longrightarrow>
+   (\<And>a b c d. a \<noteq> b \<Longrightarrow> c \<noteq> d \<Longrightarrow> (a = c \<and> b = d \<or>  a = c \<and> b \<noteq> d \<or> a \<noteq> c \<and> b = d \<or> a \<noteq> c \<and> a \<noteq> d \<and> b \<noteq> c \<and> b \<noteq> d) ==> P a b c d)
+   ==> (\<And>a b c d. a \<noteq> b --> c \<noteq> d \<longrightarrow>  P a b c d)" by metis
+
+lemma swap_general: "a \<noteq> b \<Longrightarrow> c \<noteq> d \<Longrightarrow> Fun.swap a b id o Fun.swap c d id = id \<or> 
+  (\<exists>x y z. x \<noteq> a \<and> y \<noteq> a \<and> z \<noteq> a \<and> x \<noteq> y \<and> Fun.swap a b id o Fun.swap c d id = Fun.swap x y id o Fun.swap a z id)" 
+proof-
+  assume H: "a\<noteq>b" "c\<noteq>d"
+have "a \<noteq> b \<longrightarrow> c \<noteq> d \<longrightarrow> 
+(  Fun.swap a b id o Fun.swap c d id = id \<or> 
+  (\<exists>x y z. x \<noteq> a \<and> y \<noteq> a \<and> z \<noteq> a \<and> x \<noteq> y \<and> Fun.swap a b id o Fun.swap c d id = Fun.swap x y id o Fun.swap a z id))" 
+  apply (rule symmetry_lemma[where a=a and b=b and c=c and d=d])
+  apply (simp_all only: swapid_sym) 
+  apply (case_tac "a = c \<and> b = d", clarsimp simp only: swapid_sym swap_id_idempotent)
+  apply (case_tac "a = c \<and> b \<noteq> d")
+  apply (rule disjI2)
+  apply (rule_tac x="b" in exI)
+  apply (rule_tac x="d" in exI)
+  apply (rule_tac x="b" in exI)
+  apply (clarsimp simp add: expand_fun_eq swap_def)
+  apply (case_tac "a \<noteq> c \<and> b = d")
+  apply (rule disjI2)
+  apply (rule_tac x="c" in exI)
+  apply (rule_tac x="d" in exI)
+  apply (rule_tac x="c" in exI)
+  apply (clarsimp simp add: expand_fun_eq swap_def)
+  apply (rule disjI2)
+  apply (rule_tac x="c" in exI)
+  apply (rule_tac x="d" in exI)
+  apply (rule_tac x="b" in exI)
+  apply (clarsimp simp add: expand_fun_eq swap_def)
+  done
+with H show ?thesis by metis 
+qed
+
+lemma swapidseq_id_iff[simp]: "swapidseq 0 p \<longleftrightarrow> p = id"
+  using swapidseq.cases[of 0 p "p = id"]
+  by auto
+
+lemma swapidseq_cases: "swapidseq n p \<longleftrightarrow> (n=0 \<and> p = id \<or> (\<exists>a b q m. n = Suc m \<and> p = Fun.swap a b id o q \<and> swapidseq m q \<and> a\<noteq> b))"
+  apply (rule iffI)
+  apply (erule swapidseq.cases[of n p])
+  apply simp
+  apply (rule disjI2)
+  apply (rule_tac x= "a" in exI)
+  apply (rule_tac x= "b" in exI)
+  apply (rule_tac x= "pa" in exI)
+  apply (rule_tac x= "na" in exI)
+  apply simp
+  apply auto
+  apply (rule comp_Suc, simp_all)
+  done
+lemma fixing_swapidseq_decrease:
+  assumes spn: "swapidseq n p" and ab: "a\<noteq>b" and pa: "(Fun.swap a b id o p) a = a"
+  shows "n \<noteq> 0 \<and> swapidseq (n - 1) (Fun.swap a b id o p)"
+  using spn ab pa
+proof(induct n arbitrary: p a b)
+  case 0 thus ?case by (auto simp add: swap_def fun_upd_def)
+next
+  case (Suc n p a b)
+  from Suc.prems(1) swapidseq_cases[of "Suc n" p] obtain
+    c d q m where cdqm: "Suc n = Suc m" "p = Fun.swap c d id o q" "swapidseq m q" "c \<noteq> d" "n = m"
+    by auto
+  {assume H: "Fun.swap a b id o Fun.swap c d id = id"
+    
+    have ?case apply (simp only: cdqm o_assoc H) 
+      by (simp add: cdqm)}
+  moreover
+  { fix x y z
+    assume H: "x\<noteq>a" "y\<noteq>a" "z \<noteq>a" "x \<noteq>y" 
+      "Fun.swap a b id o Fun.swap c d id = Fun.swap x y id o Fun.swap a z id"
+    from H have az: "a \<noteq> z" by simp
+
+    {fix h have "(Fun.swap x y id o h) a = a \<longleftrightarrow> h a = a"
+      using H by (simp add: swap_def)}
+    note th3 = this
+    from cdqm(2) have "Fun.swap a b id o p = Fun.swap a b id o (Fun.swap c d id o q)" by simp
+    hence "Fun.swap a b id o p = Fun.swap x y id o (Fun.swap a z id o q)" by (simp add: o_assoc H)
+    hence "(Fun.swap a b id o p) a = (Fun.swap x y id o (Fun.swap a z id o q)) a" by simp
+    hence "(Fun.swap x y id o (Fun.swap a z id o q)) a  = a" unfolding Suc by metis
+    hence th1: "(Fun.swap a z id o q) a = a" unfolding th3 .
+    from Suc.hyps[OF cdqm(3)[ unfolded cdqm(5)[symmetric]] az th1]
+    have th2: "swapidseq (n - 1) (Fun.swap a z id o q)" "n \<noteq> 0" by blast+
+    have th: "Suc n - 1 = Suc (n - 1)" using th2(2) by auto 
+    have ?case unfolding cdqm(2) H o_assoc th
+      apply (simp only: Suc_not_Zero simp_thms o_assoc[symmetric])
+      apply (rule comp_Suc)
+      using th2 H apply blast+
+      done}
+  ultimately show ?case using swap_general[OF Suc.prems(2) cdqm(4)] by metis 
+qed
+
+lemma swapidseq_identity_even: 
+  assumes "swapidseq n (id :: 'a \<Rightarrow> 'a)" shows "even n"
+  using `swapidseq n id`
+proof(induct n rule: nat_less_induct)
+  fix n
+  assume H: "\<forall>m<n. swapidseq m (id::'a \<Rightarrow> 'a) \<longrightarrow> even m" "swapidseq n (id :: 'a \<Rightarrow> 'a)"
+  {assume "n = 0" hence "even n" by arith} 
+  moreover 
+  {fix a b :: 'a and q m
+    assume h: "n = Suc m" "(id :: 'a \<Rightarrow> 'a) = Fun.swap a b id \<circ> q" "swapidseq m q" "a \<noteq> b"
+    from fixing_swapidseq_decrease[OF h(3,4), unfolded h(2)[symmetric]]
+    have m: "m \<noteq> 0" "swapidseq (m - 1) (id :: 'a \<Rightarrow> 'a)" by auto
+    from h m have mn: "m - 1 < n" by arith
+    from H(1)[rule_format, OF mn m(2)] h(1) m(1) have "even n" apply arith done}
+  ultimately show "even n" using H(2)[unfolded swapidseq_cases[of n id]] by auto
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Therefore we have a welldefined notion of parity.                         *)
+(* ------------------------------------------------------------------------- *)
+
+definition "evenperm p = even (SOME n. swapidseq n p)"
+
+lemma swapidseq_even_even: assumes 
+  m: "swapidseq m p" and n: "swapidseq n p"
+  shows "even m \<longleftrightarrow> even n"
+proof-
+  from swapidseq_inverse_exists[OF n]
+  obtain q where q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id" by blast
+  
+  from swapidseq_identity_even[OF swapidseq_comp_add[OF m q(1), unfolded q]]
+  show ?thesis by arith
+qed
+
+lemma evenperm_unique: assumes p: "swapidseq n p" and n:"even n = b"
+  shows "evenperm p = b"
+  unfolding n[symmetric] evenperm_def
+  apply (rule swapidseq_even_even[where p = p])
+  apply (rule someI[where x = n])
+  using p by blast+
+
+(* ------------------------------------------------------------------------- *)
+(* And it has the expected composition properties.                           *)
+(* ------------------------------------------------------------------------- *)
+
+lemma evenperm_id[simp]: "evenperm id = True"
+  apply (rule evenperm_unique[where n = 0]) by simp_all
+
+lemma evenperm_swap: "evenperm (Fun.swap a b id) = (a = b)"
+apply (rule evenperm_unique[where n="if a = b then 0 else 1"])
+by (simp_all add: swapidseq_swap)
+
+lemma evenperm_comp: 
+  assumes p: "permutation p" and q:"permutation q"
+  shows "evenperm (p o q) = (evenperm p = evenperm q)"
+proof-
+  from p q obtain 
+    n m where n: "swapidseq n p" and m: "swapidseq m q" 
+    unfolding permutation_def by blast
+  note nm =  swapidseq_comp_add[OF n m]
+  have th: "even (n + m) = (even n \<longleftrightarrow> even m)" by arith
+  from evenperm_unique[OF n refl] evenperm_unique[OF m refl]
+    evenperm_unique[OF nm th]
+  show ?thesis by blast
+qed
+
+lemma evenperm_inv: assumes p: "permutation p"
+  shows "evenperm (inv p) = evenperm p"
+proof-
+  from p obtain n where n: "swapidseq n p" unfolding permutation_def by blast
+  from evenperm_unique[OF swapidseq_inverse[OF n] evenperm_unique[OF n refl, symmetric]]
+  show ?thesis .
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* A more abstract characterization of permutations.                         *)
+(* ------------------------------------------------------------------------- *)
+
+
+lemma bij_iff: "bij f \<longleftrightarrow> (\<forall>x. \<exists>!y. f y = x)"
+  unfolding bij_def inj_on_def surj_def
+  apply auto
+  apply metis
+  apply metis
+  done
+
+lemma permutation_bijective: 
+  assumes p: "permutation p" 
+  shows "bij p"
+proof-
+  from p obtain n where n: "swapidseq n p" unfolding permutation_def by blast
+  from swapidseq_inverse_exists[OF n] obtain q where 
+    q: "swapidseq n q" "p \<circ> q = id" "q \<circ> p = id" by blast
+  thus ?thesis unfolding bij_iff  apply (auto simp add: expand_fun_eq) apply metis done
+qed  
+
+lemma permutation_finite_support: assumes p: "permutation p"
+  shows "finite {x. p x \<noteq> x}"
+proof-
+  from p obtain n where n: "swapidseq n p" unfolding permutation_def by blast
+  from n show ?thesis
+  proof(induct n p rule: swapidseq.induct)
+    case id thus ?case by simp
+  next
+    case (comp_Suc n p a b)
+    let ?S = "insert a (insert b {x. p x \<noteq> x})"
+    from comp_Suc.hyps(2) have fS: "finite ?S" by simp
+    from `a \<noteq> b` have th: "{x. (Fun.swap a b id o p) x \<noteq> x} \<subseteq> ?S"
+      by (auto simp add: swap_def)
+    from finite_subset[OF th fS] show ?case  .
+qed
+qed
+
+lemma bij_inv_eq_iff: "bij p ==> x = inv p y \<longleftrightarrow> p x = y"
+  using surj_f_inv_f[of p] inv_f_f[of f] by (auto simp add: bij_def)
+
+lemma bij_swap_comp: 
+  assumes bp: "bij p" shows "Fun.swap a b id o p = Fun.swap (inv p a) (inv p b) p"
+  using surj_f_inv_f[OF bij_is_surj[OF bp]]
+  by (simp add: expand_fun_eq swap_def bij_inv_eq_iff[OF bp])
+
+lemma bij_swap_ompose_bij: "bij p \<Longrightarrow> bij (Fun.swap a b id o p)"
+proof-
+  assume H: "bij p"
+  show ?thesis 
+    unfolding bij_swap_comp[OF H] bij_swap_iff
+    using H .
+qed
+
+lemma permutation_lemma: 
+  assumes fS: "finite S" and p: "bij p" and pS: "\<forall>x. x\<notin> S \<longrightarrow> p x = x"
+  shows "permutation p"
+using fS p pS
+proof(induct S arbitrary: p rule: finite_induct)
+  case (empty p) thus ?case by simp
+next
+  case (insert a F p)
+  let ?r = "Fun.swap a (p a) id o p"
+  let ?q = "Fun.swap a (p a) id o ?r "
+  have raa: "?r a = a" by (simp add: swap_def)
+  from bij_swap_ompose_bij[OF insert(4)]
+  have br: "bij ?r"  . 
+  
+  from insert raa have th: "\<forall>x. x \<notin> F \<longrightarrow> ?r x = x"    
+    apply (clarsimp simp add: swap_def)
+    apply (erule_tac x="x" in allE)
+    apply auto
+    unfolding bij_iff apply metis
+    done
+  from insert(3)[OF br th]
+  have rp: "permutation ?r" .
+  have "permutation ?q" by (simp add: permutation_compose permutation_swap_id rp)
+  thus ?case by (simp add: o_assoc)
+qed
+
+lemma permutation: "permutation p \<longleftrightarrow> bij p \<and> finite {x. p x \<noteq> x}" 
+  (is "?lhs \<longleftrightarrow> ?b \<and> ?f")
+proof
+  assume p: ?lhs
+  from p permutation_bijective permutation_finite_support show "?b \<and> ?f" by auto
+next
+  assume bf: "?b \<and> ?f"
+  hence bf: "?f" "?b" by blast+
+  from permutation_lemma[OF bf] show ?lhs by blast
+qed
+
+lemma permutation_inverse_works: assumes p: "permutation p"
+  shows "inv p o p = id" "p o inv p = id"
+using permutation_bijective[OF p] surj_iff bij_def inj_iff by auto
+
+lemma permutation_inverse_compose:
+  assumes p: "permutation p" and q: "permutation q"
+  shows "inv (p o q) = inv q o inv p"
+proof-
+  note ps = permutation_inverse_works[OF p]
+  note qs = permutation_inverse_works[OF q]
+  have "p o q o (inv q o inv p) = p o (q o inv q) o inv p" by (simp add: o_assoc)
+  also have "\<dots> = id" by (simp add: ps qs)
+  finally have th0: "p o q o (inv q o inv p) = id" .
+  have "inv q o inv p o (p o q) = inv q o (inv p o p) o q" by (simp add: o_assoc)
+  also have "\<dots> = id" by (simp add: ps qs)
+  finally have th1: "inv q o inv p o (p o q) = id" . 
+  from inv_unique_comp[OF th0 th1] show ?thesis .
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Relation to "permutes".                                                   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutation_permutes: "permutation p \<longleftrightarrow> (\<exists>S. finite S \<and> p permutes S)"
+unfolding permutation permutes_def bij_iff[symmetric]
+apply (rule iffI, clarify)
+apply (rule exI[where x="{x. p x \<noteq> x}"])
+apply simp
+apply clarsimp
+apply (rule_tac B="S" in finite_subset)
+apply auto
+done
+
+(* ------------------------------------------------------------------------- *)
+(* Hence a sort of induction principle composing by swaps.                   *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutes_induct: "finite S \<Longrightarrow>  P id  \<Longrightarrow> (\<And> a b p. a \<in> S \<Longrightarrow> b \<in> S \<Longrightarrow> P p \<Longrightarrow> P p \<Longrightarrow> permutation p ==> P (Fun.swap a b id o p))
+         ==> (\<And>p. p permutes S ==> P p)"
+proof(induct S rule: finite_induct)
+  case empty thus ?case by auto
+next 
+  case (insert x F p)
+  let ?r = "Fun.swap x (p x) id o p"
+  let ?q = "Fun.swap x (p x) id o ?r"
+  have qp: "?q = p" by (simp add: o_assoc)
+  from permutes_insert_lemma[OF insert.prems(3)] insert have Pr: "P ?r" by blast
+  from permutes_in_image[OF insert.prems(3), of x] 
+  have pxF: "p x \<in> insert x F" by simp
+  have xF: "x \<in> insert x F" by simp
+  have rp: "permutation ?r"
+    unfolding permutation_permutes using insert.hyps(1) 
+      permutes_insert_lemma[OF insert.prems(3)] by blast
+  from insert.prems(2)[OF xF pxF Pr Pr rp] 
+  show ?case  unfolding qp . 
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Sign of a permutation as a real number.                                   *)
+(* ------------------------------------------------------------------------- *)
+
+definition "sign p = (if evenperm p then (1::int) else -1)"
+
+lemma sign_nz: "sign p \<noteq> 0" by (simp add: sign_def) 
+lemma sign_id: "sign id = 1" by (simp add: sign_def)
+lemma sign_inverse: "permutation p ==> sign (inv p) = sign p"
+  by (simp add: sign_def evenperm_inv)
+lemma sign_compose: "permutation p \<Longrightarrow> permutation q ==> sign (p o q) = sign(p) * sign(q)" by (simp add: sign_def evenperm_comp)
+lemma sign_swap_id: "sign (Fun.swap a b id) = (if a = b then 1 else -1)"
+  by (simp add: sign_def evenperm_swap)
+lemma sign_idempotent: "sign p * sign p = 1" by (simp add: sign_def)
+
+(* ------------------------------------------------------------------------- *)
+(* More lemmas about permutations.                                           *)
+(* ------------------------------------------------------------------------- *)
+
+lemma permutes_natset_le:
+  assumes p: "p permutes (S:: nat set)" and le: "\<forall>i \<in> S.  p i <= i" shows "p = id"
+proof-
+  {fix n
+    have "p n = n" 
+      using p le
+    proof(induct n arbitrary: S rule: nat_less_induct)
+      fix n S assume H: "\<forall> m< n. \<forall>S. p permutes S \<longrightarrow> (\<forall>i\<in>S. p i \<le> i) \<longrightarrow> p m = m" 
+	"p permutes S" "\<forall>i \<in>S. p i \<le> i"
+      {assume "n \<notin> S"
+	with H(2) have "p n = n" unfolding permutes_def by metis}
+      moreover
+      {assume ns: "n \<in> S"
+	from H(3)  ns have "p n < n \<or> p n = n" by auto 
+	moreover{assume h: "p n < n"
+	  from H h have "p (p n) = p n" by metis
+	  with permutes_inj[OF H(2)] have "p n = n" unfolding inj_on_def by blast
+	  with h have False by arith}
+	ultimately have "p n = n" by blast }
+      ultimately show "p n = n"  by blast
+    qed}
+  thus ?thesis by (auto simp add: expand_fun_eq)
+qed
+
+lemma permutes_natset_ge:
+  assumes p: "p permutes (S:: nat set)" and le: "\<forall>i \<in> S.  p i \<ge> i" shows "p = id"
+proof-
+  {fix i assume i: "i \<in> S"
+    from i permutes_in_image[OF permutes_inv[OF p]] have "inv p i \<in> S" by simp
+    with le have "p (inv p i) \<ge> inv p i" by blast
+    with permutes_inverses[OF p] have "i \<ge> inv p i" by simp}
+  then have th: "\<forall>i\<in>S. inv p i \<le> i"  by blast
+  from permutes_natset_le[OF permutes_inv[OF p] th] 
+  have "inv p = inv id" by simp
+  then show ?thesis 
+    apply (subst permutes_inv_inv[OF p, symmetric])
+    apply (rule inv_unique_comp)
+    apply simp_all
+    done
+qed
+
+lemma image_inverse_permutations: "{inv p |p. p permutes S} = {p. p permutes S}"
+apply (rule set_ext)
+apply auto
+  using permutes_inv_inv permutes_inv apply auto
+  apply (rule_tac x="inv x" in exI)
+  apply auto
+  done
+
+lemma image_compose_permutations_left: 
+  assumes q: "q permutes S" shows "{q o p | p. p permutes S} = {p . p permutes S}"
+apply (rule set_ext)
+apply auto
+apply (rule permutes_compose)
+using q apply auto
+apply (rule_tac x = "inv q o x" in exI)
+by (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o)
+
+lemma image_compose_permutations_right:
+  assumes q: "q permutes S"
+  shows "{p o q | p. p permutes S} = {p . p permutes S}"
+apply (rule set_ext)
+apply auto
+apply (rule permutes_compose)
+using q apply auto
+apply (rule_tac x = "x o inv q" in exI)
+by (simp add: o_assoc permutes_inv permutes_compose permutes_inv_o o_assoc[symmetric])
+
+lemma permutes_in_seg: "p permutes {1 ..n} \<Longrightarrow> i \<in> {1..n} ==> 1 <= p i \<and> p i <= n"
+
+apply (simp add: permutes_def)
+apply metis
+done
+
+term setsum
+lemma setsum_permutations_inverse: "setsum f {p. p permutes {m..n}} = setsum (\<lambda>p. f(inv p)) {p. p permutes {m..n}}" (is "?lhs = ?rhs")
+proof-
+  let ?S = "{p . p permutes {m .. n}}"
+have th0: "inj_on inv ?S" 
+proof(auto simp add: inj_on_def)
+  fix q r
+  assume q: "q permutes {m .. n}" and r: "r permutes {m .. n}" and qr: "inv q = inv r"
+  hence "inv (inv q) = inv (inv r)" by simp
+  with permutes_inv_inv[OF q] permutes_inv_inv[OF r]
+  show "q = r" by metis
+qed
+  have th1: "inv ` ?S = ?S" using image_inverse_permutations by blast
+  have th2: "?rhs = setsum (f o inv) ?S" by (simp add: o_def)
+  from setsum_reindex[OF th0, of f]  show ?thesis unfolding th1 th2 .
+qed
+
+lemma setum_permutations_compose_left:
+  assumes q: "q permutes {m..n}"
+  shows "setsum f {p. p permutes {m..n}} =
+            setsum (\<lambda>p. f(q o p)) {p. p permutes {m..n}}" (is "?lhs = ?rhs")
+proof-
+  let ?S = "{p. p permutes {m..n}}"
+  have th0: "?rhs = setsum (f o (op o q)) ?S" by (simp add: o_def)
+  have th1: "inj_on (op o q) ?S"
+    apply (auto simp add: inj_on_def)
+  proof-
+    fix p r
+    assume "p permutes {m..n}" and r:"r permutes {m..n}" and rp: "q \<circ> p = q \<circ> r"
+    hence "inv q o q o p = inv q o q o r" by (simp add: o_assoc[symmetric])
+    with permutes_inj[OF q, unfolded inj_iff]
+
+    show "p = r" by simp
+  qed
+  have th3: "(op o q) ` ?S = ?S" using image_compose_permutations_left[OF q] by auto
+  from setsum_reindex[OF th1, of f]
+  show ?thesis unfolding th0 th1 th3 .
+qed
+
+lemma sum_permutations_compose_right:
+  assumes q: "q permutes {m..n}"
+  shows "setsum f {p. p permutes {m..n}} =
+            setsum (\<lambda>p. f(p o q)) {p. p permutes {m..n}}" (is "?lhs = ?rhs")
+proof-
+  let ?S = "{p. p permutes {m..n}}"
+  have th0: "?rhs = setsum (f o (\<lambda>p. p o q)) ?S" by (simp add: o_def)
+  have th1: "inj_on (\<lambda>p. p o q) ?S"
+    apply (auto simp add: inj_on_def)
+  proof-
+    fix p r
+    assume "p permutes {m..n}" and r:"r permutes {m..n}" and rp: "p o q = r o q"
+    hence "p o (q o inv q)  = r o (q o inv q)" by (simp add: o_assoc)
+    with permutes_surj[OF q, unfolded surj_iff]
+
+    show "p = r" by simp
+  qed
+  have th3: "(\<lambda>p. p o q) ` ?S = ?S" using image_compose_permutations_right[OF q] by auto
+  from setsum_reindex[OF th1, of f]
+  show ?thesis unfolding th0 th1 th3 .
+qed
+
+(* ------------------------------------------------------------------------- *)
+(* Sum over a set of permutations (could generalize to iteration).           *)
+(* ------------------------------------------------------------------------- *)
+
+lemma setsum_over_permutations_insert:
+  assumes fS: "finite S" and aS: "a \<notin> S"
+  shows "setsum f {p. p permutes (insert a S)} = setsum (\<lambda>b. setsum (\<lambda>q. f (Fun.swap a b id o q)) {p. p permutes S}) (insert a S)"
+proof-
+  have th0: "\<And>f a b. (\<lambda>(b,p). f (Fun.swap a b id o p)) = f o (\<lambda>(b,p). Fun.swap a b id o p)"
+    by (simp add: expand_fun_eq)
+  have th1: "\<And>P Q. P \<times> Q = {(a,b). a \<in> P \<and> b \<in> Q}" by blast
+  have th2: "\<And>P Q. P \<Longrightarrow> (P \<Longrightarrow> Q) \<Longrightarrow> P \<and> Q" by blast
+  show ?thesis 
+    unfolding permutes_insert    
+    unfolding setsum_cartesian_product
+    unfolding  th1[symmetric]
+    unfolding th0
+  proof(rule setsum_reindex)
+    let ?f = "(\<lambda>(b, y). Fun.swap a b id \<circ> y)"
+    let ?P = "{p. p permutes S}"
+    {fix b c p q assume b: "b \<in> insert a S" and c: "c \<in> insert a S" 
+      and p: "p permutes S" and q: "q permutes S" 
+      and eq: "Fun.swap a b id o p = Fun.swap a c id o q"
+      from p q aS have pa: "p a = a" and qa: "q a = a"
+	unfolding permutes_def by metis+
+      from eq have "(Fun.swap a b id o p) a  = (Fun.swap a c id o q) a" by simp
+      hence bc: "b = c"
+	apply (simp add: permutes_def pa qa o_def fun_upd_def swap_def id_def cong del: if_weak_cong)
+	apply (cases "a = b", auto)
+	by (cases "b = c", auto)
+      from eq[unfolded bc] have "(\<lambda>p. Fun.swap a c id o p) (Fun.swap a c id o p) = (\<lambda>p. Fun.swap a c id o p) (Fun.swap a c id o q)" by simp
+      hence "p = q" unfolding o_assoc swap_id_idempotent
+	by (simp add: o_def)
+      with bc have "b = c \<and> p = q" by blast
+    }
+    
+    then show "inj_on ?f (insert a S \<times> ?P)" 
+      unfolding inj_on_def
+      apply clarify by metis
+  qed
+qed
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/HOL/Library/normarith.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,1189 @@
+(* A functor for finite mappings based on Tables *)
+signature FUNC = 
+sig
+ type 'a T
+ type key
+ val apply : 'a T -> key -> 'a
+ val applyd :'a T -> (key -> 'a) -> key -> 'a
+ val combine : ('a -> 'a -> 'a) -> ('a -> bool) -> 'a T -> 'a T -> 'a T
+ val defined : 'a T -> key -> bool
+ val dom : 'a T -> key list
+ val fold : (key * 'a -> 'b -> 'b) -> 'a T -> 'b -> 'b
+ val graph : 'a T -> (key * 'a) list
+ val is_undefined : 'a T -> bool
+ val mapf : ('a -> 'b) -> 'a T -> 'b T
+ val tryapplyd : 'a T -> key -> 'a -> 'a
+ val undefine :  key -> 'a T -> 'a T
+ val undefined : 'a T
+ val update : key * 'a -> 'a T -> 'a T
+ val updatep : (key * 'a -> bool) -> key * 'a -> 'a T -> 'a T
+ val choose : 'a T -> key * 'a
+ val onefunc : key * 'a -> 'a T
+ val get_first: (key*'a -> 'a option) -> 'a T -> 'a option
+ val fns: 
+   {key_ord: key*key -> order,
+    apply : 'a T -> key -> 'a,
+    applyd :'a T -> (key -> 'a) -> key -> 'a,
+    combine : ('a -> 'a -> 'a) -> ('a -> bool) -> 'a T -> 'a T -> 'a T,
+    defined : 'a T -> key -> bool,
+    dom : 'a T -> key list,
+    fold : (key * 'a -> 'b -> 'b) -> 'a T -> 'b -> 'b,
+    graph : 'a T -> (key * 'a) list,
+    is_undefined : 'a T -> bool,
+    mapf : ('a -> 'b) -> 'a T -> 'b T,
+    tryapplyd : 'a T -> key -> 'a -> 'a,
+    undefine :  key -> 'a T -> 'a T,
+    undefined : 'a T,
+    update : key * 'a -> 'a T -> 'a T,
+    updatep : (key * 'a -> bool) -> key * 'a -> 'a T -> 'a T,
+    choose : 'a T -> key * 'a,
+    onefunc : key * 'a -> 'a T,
+    get_first: (key*'a -> 'a option) -> 'a T -> 'a option}
+end;
+
+functor FuncFun(Key: KEY) : FUNC=
+struct
+
+type key = Key.key;
+structure Tab = TableFun(Key);
+type 'a T = 'a Tab.table;
+
+val undefined = Tab.empty;
+val is_undefined = Tab.is_empty;
+val mapf = Tab.map;
+val fold = Tab.fold;
+val graph = Tab.dest;
+val dom = Tab.keys;
+fun applyd f d x = case Tab.lookup f x of 
+   SOME y => y
+ | NONE => d x;
+
+fun apply f x = applyd f (fn _ => raise Tab.UNDEF x) x;
+fun tryapplyd f a d = applyd f (K d) a;
+val defined = Tab.defined;
+fun undefine x t = (Tab.delete x t handle UNDEF => t);
+val update = Tab.update;
+fun updatep p (k,v) t = if p (k, v) then t else update (k,v) t
+fun combine f z a b = 
+ let
+  fun h (k,v) t = case Tab.lookup t k of
+     NONE => Tab.update (k,v) t
+   | SOME v' => let val w = f v v'
+     in if z w then Tab.delete k t else Tab.update (k,w) t end;
+  in Tab.fold h a b end;
+
+fun choose f = case Tab.max_key f of 
+   SOME k => (k,valOf (Tab.lookup f k))
+ | NONE => error "FuncFun.choose : Completely undefined function"
+
+fun onefunc kv = update kv undefined
+
+local
+fun  find f (k,v) NONE = f (k,v)
+   | find f (k,v) r = r
+in
+fun get_first f t = fold (find f) t NONE
+end
+
+val fns = 
+   {key_ord = Key.ord,
+    apply = apply,
+    applyd = applyd,
+    combine = combine,
+    defined = defined,
+    dom = dom,
+    fold = fold,
+    graph = graph,
+    is_undefined = is_undefined,
+    mapf = mapf,
+    tryapplyd = tryapplyd,
+    undefine = undefine,
+    undefined = undefined,
+    update = update,
+    updatep = updatep,
+    choose = choose,
+    onefunc = onefunc,
+    get_first = get_first}
+
+end;
+
+structure Intfunc = FuncFun(type key = int val ord = int_ord);
+structure Symfunc = FuncFun(type key = string val ord = fast_string_ord);
+structure Termfunc = FuncFun(type key = term val ord = TermOrd.fast_term_ord);
+structure Ctermfunc = FuncFun(type key = cterm val ord = (fn (s,t) => TermOrd.fast_term_ord(term_of s, term_of t)));
+structure Ratfunc = FuncFun(type key = Rat.rat val ord = Rat.ord);
+
+    (* Some conversions-related stuff which has been forbidden entrance into Pure/conv.ML*)
+structure Conv2 = 
+struct
+ open Conv
+fun instantiate_cterm' ty tms = Drule.cterm_rule (Drule.instantiate' ty tms)
+fun is_comb t = case (term_of t) of _$_ => true | _ => false;
+fun is_abs t = case (term_of t) of Abs _ => true | _ => false;
+
+fun end_itlist f l =
+ case l of 
+   []     => error "end_itlist"
+ | [x]    => x
+ | (h::t) => f h (end_itlist f t);
+
+ fun absc cv ct = case term_of ct of 
+ Abs (v,_, _) => 
+  let val (x,t) = Thm.dest_abs (SOME v) ct
+  in Thm.abstract_rule ((fst o dest_Free o term_of) x) x (cv t)
+  end
+ | _ => all_conv ct;
+
+fun cache_conv conv =
+ let 
+  val tab = ref Termtab.empty
+  fun cconv t =  
+    case Termtab.lookup (!tab) (term_of t) of
+     SOME th => th
+   | NONE => let val th = conv t
+             in ((tab := Termtab.insert Thm.eq_thm (term_of t, th) (!tab)); th) end
+ in cconv end;
+fun is_binop ct ct' = ct aconvc (Thm.dest_fun (Thm.dest_fun ct'))
+  handle CTERM _ => false;
+
+local
+ fun thenqc conv1 conv2 tm =
+   case try conv1 tm of
+    SOME th1 => (case try conv2 (Thm.rhs_of th1) of SOME th2 => Thm.transitive th1 th2 | NONE => th1)
+  | NONE => conv2 tm
+
+ fun thencqc conv1 conv2 tm =
+    let val th1 = conv1 tm 
+    in (case try conv2 (Thm.rhs_of th1) of SOME th2 => Thm.transitive th1 th2 | NONE => th1)
+    end
+ fun comb_qconv conv tm =
+   let val (l,r) = Thm.dest_comb tm 
+   in (case try conv l of 
+        SOME th1 => (case try conv r of SOME th2 => Thm.combination th1 th2 
+                                      | NONE => Drule.fun_cong_rule th1 r)
+      | NONE => Drule.arg_cong_rule l (conv r))
+   end
+ fun repeatqc conv tm = thencqc conv (repeatqc conv) tm 
+ fun sub_qconv conv tm =  if is_abs tm then absc conv tm else comb_qconv conv tm 
+ fun once_depth_qconv conv tm =
+      (conv else_conv (sub_qconv (once_depth_qconv conv))) tm
+ fun depth_qconv conv tm =
+    thenqc (sub_qconv (depth_qconv conv))
+           (repeatqc conv) tm
+ fun redepth_qconv conv tm =
+    thenqc (sub_qconv (redepth_qconv conv))
+           (thencqc conv (redepth_qconv conv)) tm
+ fun top_depth_qconv conv tm =
+    thenqc (repeatqc conv)
+           (thencqc (sub_qconv (top_depth_qconv conv))
+                    (thencqc conv (top_depth_qconv conv))) tm
+ fun top_sweep_qconv conv tm =
+    thenqc (repeatqc conv)
+           (sub_qconv (top_sweep_qconv conv)) tm
+in 
+val (once_depth_conv, depth_conv, rdepth_conv, top_depth_conv, top_sweep_conv) = 
+  (fn c => try_conv (once_depth_qconv c),
+   fn c => try_conv (depth_qconv c),
+   fn c => try_conv (redepth_qconv c),
+   fn c => try_conv (top_depth_qconv c),
+   fn c => try_conv (top_sweep_qconv c));
+end;
+end;
+
+
+    (* Some useful derived rules *)
+fun deduct_antisym_rule tha thb = 
+    equal_intr (implies_intr (cprop_of thb) tha) 
+     (implies_intr (cprop_of tha) thb);
+
+fun prove_hyp tha thb = 
+  if exists (curry op aconv (concl_of tha)) (#hyps (rep_thm thb)) 
+  then equal_elim (symmetric (deduct_antisym_rule tha thb)) tha else thb;
+
+
+
+signature REAL_ARITH = 
+sig
+  datatype positivstellensatz =
+   Axiom_eq of int
+ | Axiom_le of int
+ | Axiom_lt of int
+ | Rational_eq of Rat.rat
+ | Rational_le of Rat.rat
+ | Rational_lt of Rat.rat
+ | Square of cterm
+ | Eqmul of cterm * positivstellensatz
+ | Sum of positivstellensatz * positivstellensatz
+ | Product of positivstellensatz * positivstellensatz;
+
+val gen_gen_real_arith :
+  Proof.context -> (Rat.rat -> Thm.cterm) * conv * conv * conv * 
+   conv * conv * conv * conv * conv * conv * 
+    ( (thm list * thm list * thm list -> positivstellensatz -> thm) ->
+        thm list * thm list * thm list -> thm) -> conv
+val real_linear_prover : 
+  (thm list * thm list * thm list -> positivstellensatz -> thm) ->
+   thm list * thm list * thm list -> thm
+
+val gen_real_arith : Proof.context ->
+   (Rat.rat -> cterm) * conv * conv * conv * conv * conv * conv * conv *
+   ( (thm list * thm list * thm list -> positivstellensatz -> thm) ->
+       thm list * thm list * thm list -> thm) -> conv
+val gen_prover_real_arith : Proof.context ->
+   ((thm list * thm list * thm list -> positivstellensatz -> thm) ->
+     thm list * thm list * thm list -> thm) -> conv
+val real_arith : Proof.context -> conv
+end
+
+structure RealArith (* : REAL_ARITH *)=
+struct
+
+ open Conv Thm Conv2;;
+(* ------------------------------------------------------------------------- *)
+(* Data structure for Positivstellensatz refutations.                        *)
+(* ------------------------------------------------------------------------- *)
+
+datatype positivstellensatz =
+   Axiom_eq of int
+ | Axiom_le of int
+ | Axiom_lt of int
+ | Rational_eq of Rat.rat
+ | Rational_le of Rat.rat
+ | Rational_lt of Rat.rat
+ | Square of cterm
+ | Eqmul of cterm * positivstellensatz
+ | Sum of positivstellensatz * positivstellensatz
+ | Product of positivstellensatz * positivstellensatz;
+         (* Theorems used in the procedure *)
+
+fun conjunctions th = case try Conjunction.elim th of
+   SOME (th1,th2) => (conjunctions th1) @ conjunctions th2
+ | NONE => [th];
+
+val pth = @{lemma "(((x::real) < y) == (y - x > 0)) &&& ((x <= y) == (y - x >= 0)) 
+     &&& ((x = y) == (x - y = 0)) &&& ((~(x < y)) == (x - y >= 0)) &&& ((~(x <= y)) == (x - y > 0))
+     &&& ((~(x = y)) == (x - y > 0 | -(x - y) > 0))"
+  by (atomize (full), auto simp add: less_diff_eq le_diff_eq not_less)} |> 
+conjunctions;
+
+val pth_final = @{lemma "(~p ==> False) ==> p" by blast}
+val pth_add = 
+ @{lemma "(x = (0::real) ==> y = 0 ==> x + y = 0 ) &&& ( x = 0 ==> y >= 0 ==> x + y >= 0) 
+    &&& (x = 0 ==> y > 0 ==> x + y > 0) &&& (x >= 0 ==> y = 0 ==> x + y >= 0) 
+    &&& (x >= 0 ==> y >= 0 ==> x + y >= 0) &&& (x >= 0 ==> y > 0 ==> x + y > 0) 
+    &&& (x > 0 ==> y = 0 ==> x + y > 0) &&& (x > 0 ==> y >= 0 ==> x + y > 0) 
+    &&& (x > 0 ==> y > 0 ==> x + y > 0)"  by simp_all} |> conjunctions ;
+
+val pth_mul = 
+  @{lemma "(x = (0::real) ==> y = 0 ==> x * y = 0) &&& (x = 0 ==> y >= 0 ==> x * y = 0) &&& 
+           (x = 0 ==> y > 0 ==> x * y = 0) &&& (x >= 0 ==> y = 0 ==> x * y = 0) &&& 
+           (x >= 0 ==> y >= 0 ==> x * y >= 0 ) &&& ( x >= 0 ==> y > 0 ==> x * y >= 0 ) &&&
+           (x > 0 ==>  y = 0 ==> x * y = 0 ) &&& ( x > 0 ==> y >= 0 ==> x * y >= 0 ) &&&
+           (x > 0 ==>  y > 0 ==> x * y > 0)"
+  by (auto intro: mult_mono[where a="0::real" and b="x" and d="y" and c="0", simplified]
+    mult_strict_mono[where b="x" and d="y" and a="0" and c="0", simplified])} |> conjunctions;
+
+val pth_emul = @{lemma "y = (0::real) ==> x * y = 0"  by simp};
+val pth_square = @{lemma "x * x >= (0::real)"  by simp};
+
+val weak_dnf_simps = List.take (simp_thms, 34) 
+    @ conjunctions @{lemma "((P & (Q | R)) = ((P&Q) | (P&R))) &&& ((Q | R) & P) = ((Q&P) | (R&P)) &&& (P & Q) = (Q & P) &&& ((P | Q) = (Q | P))" by blast+};
+
+val nnfD_simps = conjunctions @{lemma "((~(P & Q)) = (~P | ~Q)) &&& ((~(P | Q)) = (~P & ~Q) ) &&& ((P --> Q) = (~P | Q) ) &&& ((P = Q) = ((P & Q) | (~P & ~ Q))) &&& ((~(P = Q)) = ((P & ~ Q) | (~P & Q)) ) &&& ((~ ~(P)) = P)" by blast+}
+
+val choice_iff = @{lemma "(ALL x. EX y. P x y) = (EX f. ALL x. P x (f x))" by metis};
+val prenex_simps = map (fn th => th RS sym) ([@{thm "all_conj_distrib"}, @{thm "ex_disj_distrib"}] @ @{thms "all_simps"(1-4)} @ @{thms "ex_simps"(1-4)});
+
+val real_abs_thms1 = conjunctions @{lemma
+  "((-1 * abs(x::real) >= r) = (-1 * x >= r & 1 * x >= r)) &&&
+  ((-1 * abs(x) + a >= r) = (a + -1 * x >= r & a + 1 * x >= r)) &&&
+  ((a + -1 * abs(x) >= r) = (a + -1 * x >= r & a + 1 * x >= r)) &&&
+  ((a + -1 * abs(x) + b >= r) = (a + -1 * x + b >= r & a + 1 * x + b >= r)) &&&
+  ((a + b + -1 * abs(x) >= r) = (a + b + -1 * x >= r & a + b + 1 * x >= r)) &&&
+  ((a + b + -1 * abs(x) + c >= r) = (a + b + -1 * x + c >= r & a + b + 1 * x + c >= r)) &&&
+  ((-1 * max x y >= r) = (-1 * x >= r & -1 * y >= r)) &&&
+  ((-1 * max x y + a >= r) = (a + -1 * x >= r & a + -1 * y >= r)) &&&
+  ((a + -1 * max x y >= r) = (a + -1 * x >= r & a + -1 * y >= r)) &&&
+  ((a + -1 * max x y + b >= r) = (a + -1 * x + b >= r & a + -1 * y  + b >= r)) &&&
+  ((a + b + -1 * max x y >= r) = (a + b + -1 * x >= r & a + b + -1 * y >= r)) &&&
+  ((a + b + -1 * max x y + c >= r) = (a + b + -1 * x + c >= r & a + b + -1 * y  + c >= r)) &&&
+  ((1 * min x y >= r) = (1 * x >= r & 1 * y >= r)) &&&
+  ((1 * min x y + a >= r) = (a + 1 * x >= r & a + 1 * y >= r)) &&&
+  ((a + 1 * min x y >= r) = (a + 1 * x >= r & a + 1 * y >= r)) &&&
+  ((a + 1 * min x y + b >= r) = (a + 1 * x + b >= r & a + 1 * y  + b >= r) )&&&
+  ((a + b + 1 * min x y >= r) = (a + b + 1 * x >= r & a + b + 1 * y >= r)) &&&
+  ((a + b + 1 * min x y + c >= r) = (a + b + 1 * x + c >= r & a + b + 1 * y  + c >= r)) &&&
+  ((min x y >= r) = (x >= r &  y >= r)) &&&
+  ((min x y + a >= r) = (a + x >= r & a + y >= r)) &&&
+  ((a + min x y >= r) = (a + x >= r & a + y >= r)) &&&
+  ((a + min x y + b >= r) = (a + x + b >= r & a + y  + b >= r)) &&&
+  ((a + b + min x y >= r) = (a + b + x >= r & a + b + y >= r) )&&&
+  ((a + b + min x y + c >= r) = (a + b + x + c >= r & a + b + y + c >= r)) &&&
+  ((-1 * abs(x) > r) = (-1 * x > r & 1 * x > r)) &&&
+  ((-1 * abs(x) + a > r) = (a + -1 * x > r & a + 1 * x > r)) &&&
+  ((a + -1 * abs(x) > r) = (a + -1 * x > r & a + 1 * x > r)) &&&
+  ((a + -1 * abs(x) + b > r) = (a + -1 * x + b > r & a + 1 * x + b > r)) &&&
+  ((a + b + -1 * abs(x) > r) = (a + b + -1 * x > r & a + b + 1 * x > r)) &&&
+  ((a + b + -1 * abs(x) + c > r) = (a + b + -1 * x + c > r & a + b + 1 * x + c > r)) &&&
+  ((-1 * max x y > r) = ((-1 * x > r) & -1 * y > r)) &&&
+  ((-1 * max x y + a > r) = (a + -1 * x > r & a + -1 * y > r)) &&&
+  ((a + -1 * max x y > r) = (a + -1 * x > r & a + -1 * y > r)) &&&
+  ((a + -1 * max x y + b > r) = (a + -1 * x + b > r & a + -1 * y  + b > r)) &&&
+  ((a + b + -1 * max x y > r) = (a + b + -1 * x > r & a + b + -1 * y > r)) &&&
+  ((a + b + -1 * max x y + c > r) = (a + b + -1 * x + c > r & a + b + -1 * y  + c > r)) &&&
+  ((min x y > r) = (x > r &  y > r)) &&&
+  ((min x y + a > r) = (a + x > r & a + y > r)) &&&
+  ((a + min x y > r) = (a + x > r & a + y > r)) &&&
+  ((a + min x y + b > r) = (a + x + b > r & a + y  + b > r)) &&&
+  ((a + b + min x y > r) = (a + b + x > r & a + b + y > r)) &&&
+  ((a + b + min x y + c > r) = (a + b + x + c > r & a + b + y + c > r))"
+  by auto};
+
+val abs_split' = @{lemma "P (abs (x::'a::ordered_idom)) == (x >= 0 & P x | x < 0 & P (-x))"
+  by (atomize (full)) (auto split add: abs_split)};
+
+val max_split = @{lemma "P (max x y) == ((x::'a::linorder) <= y & P y | x > y & P x)"
+  by (atomize (full)) (cases "x <= y", auto simp add: max_def)};
+
+val min_split = @{lemma "P (min x y) == ((x::'a::linorder) <= y & P x | x > y & P y)"
+  by (atomize (full)) (cases "x <= y", auto simp add: min_def)};
+
+
+         (* Miscalineous *)
+fun literals_conv bops uops cv = 
+ let fun h t =
+  case (term_of t) of 
+   b$_$_ => if member (op aconv) bops b then binop_conv h t else cv t
+ | u$_ => if member (op aconv) uops u then arg_conv h t else cv t
+ | _ => cv t
+ in h end;
+
+fun cterm_of_rat x = 
+let val (a, b) = Rat.quotient_of_rat x
+in 
+ if b = 1 then Numeral.mk_cnumber @{ctyp "real"} a
+  else Thm.capply (Thm.capply @{cterm "op / :: real => _"} 
+                   (Numeral.mk_cnumber @{ctyp "real"} a))
+        (Numeral.mk_cnumber @{ctyp "real"} b)
+end;
+
+  fun dest_ratconst t = case term_of t of
+   Const(@{const_name divide}, _)$a$b => Rat.rat_of_quotient(HOLogic.dest_number a |> snd, HOLogic.dest_number b |> snd)
+ | _ => Rat.rat_of_int (HOLogic.dest_number (term_of t) |> snd)
+ fun is_ratconst t = can dest_ratconst t
+
+fun find_term p t = if p t then t else 
+ case t of
+  a$b => (find_term p a handle TERM _ => find_term p b)
+ | Abs (_,_,t') => find_term p t'
+ | _ => raise TERM ("find_term",[t]);
+
+fun find_cterm p t = if p t then t else 
+ case term_of t of
+  a$b => (find_cterm p (Thm.dest_fun t) handle CTERM _ => find_cterm p (Thm.dest_arg t))
+ | Abs (_,_,t') => find_cterm p (Thm.dest_abs NONE t |> snd)
+ | _ => raise CTERM ("find_cterm",[t]);
+
+
+    (* A general real arithmetic prover *)
+
+fun gen_gen_real_arith ctxt (mk_numeric,
+       numeric_eq_conv,numeric_ge_conv,numeric_gt_conv,
+       poly_conv,poly_neg_conv,poly_add_conv,poly_mul_conv,
+       absconv1,absconv2,prover) = 
+let
+ open Conv Thm; 
+ val pre_ss = HOL_basic_ss addsimps simp_thms@ ex_simps@ all_simps@[@{thm not_all},@{thm not_ex},ex_disj_distrib, all_conj_distrib, @{thm if_bool_eq_disj}]
+ val prenex_ss = HOL_basic_ss addsimps prenex_simps
+ val skolemize_ss = HOL_basic_ss addsimps [choice_iff]
+ val presimp_conv = Simplifier.rewrite (Simplifier.context ctxt pre_ss)
+ val prenex_conv = Simplifier.rewrite (Simplifier.context ctxt prenex_ss)
+ val skolemize_conv = Simplifier.rewrite (Simplifier.context ctxt skolemize_ss)
+ val weak_dnf_ss = HOL_basic_ss addsimps weak_dnf_simps
+ val weak_dnf_conv = Simplifier.rewrite (Simplifier.context ctxt weak_dnf_ss)
+ fun eqT_elim th = equal_elim (symmetric th) @{thm TrueI}
+ fun oprconv cv ct = 
+  let val g = Thm.dest_fun2 ct
+  in if g aconvc @{cterm "op <= :: real => _"} 
+       orelse g aconvc @{cterm "op < :: real => _"} 
+     then arg_conv cv ct else arg1_conv cv ct
+  end
+
+ fun real_ineq_conv th ct =
+  let
+   val th' = (instantiate (match (lhs_of th, ct)) th 
+      handle MATCH => raise CTERM ("real_ineq_conv", [ct]))
+  in transitive th' (oprconv poly_conv (Thm.rhs_of th'))
+  end 
+  val [real_lt_conv, real_le_conv, real_eq_conv,
+       real_not_lt_conv, real_not_le_conv, _] =
+       map real_ineq_conv pth
+  fun match_mp_rule ths ths' = 
+   let
+     fun f ths ths' = case ths of [] => raise THM("match_mp_rule",0,ths)
+      | th::ths => (ths' MRS th handle THM _ => f ths ths')
+   in f ths ths' end
+  fun mul_rule th th' = fconv_rule (arg_conv (oprconv poly_mul_conv))
+         (match_mp_rule pth_mul [th, th'])
+  fun add_rule th th' = fconv_rule (arg_conv (oprconv poly_add_conv))
+         (match_mp_rule pth_add [th, th'])
+  fun emul_rule ct th = fconv_rule (arg_conv (oprconv poly_mul_conv)) 
+       (instantiate' [] [SOME ct] (th RS pth_emul)) 
+  fun square_rule t = fconv_rule (arg_conv (oprconv poly_mul_conv))
+       (instantiate' [] [SOME t] pth_square)
+
+  fun hol_of_positivstellensatz(eqs,les,lts) =
+   let 
+    fun translate prf = case prf of
+        Axiom_eq n => nth eqs n
+      | Axiom_le n => nth les n
+      | Axiom_lt n => nth lts n
+      | Rational_eq x => eqT_elim(numeric_eq_conv(capply @{cterm Trueprop} 
+                          (capply (capply @{cterm "op =::real => _"} (mk_numeric x)) 
+                               @{cterm "0::real"})))
+      | Rational_le x => eqT_elim(numeric_ge_conv(capply @{cterm Trueprop} 
+                          (capply (capply @{cterm "op <=::real => _"} 
+                                     @{cterm "0::real"}) (mk_numeric x))))
+      | Rational_lt x => eqT_elim(numeric_gt_conv(capply @{cterm Trueprop} 
+                      (capply (capply @{cterm "op <::real => _"} @{cterm "0::real"})
+                        (mk_numeric x))))
+      | Square t => square_rule t
+      | Eqmul(t,p) => emul_rule t (translate p)
+      | Sum(p1,p2) => add_rule (translate p1) (translate p2)
+      | Product(p1,p2) => mul_rule (translate p1) (translate p2)
+   in fn prf => 
+      fconv_rule (first_conv [numeric_ge_conv, numeric_gt_conv, numeric_eq_conv, all_conv]) 
+          (translate prf)
+   end
+  
+  val init_conv = presimp_conv then_conv
+      nnf_conv then_conv skolemize_conv then_conv prenex_conv then_conv
+      weak_dnf_conv
+
+  val concl = dest_arg o cprop_of
+  fun is_binop opr ct = (dest_fun2 ct aconvc opr handle CTERM _ => false)
+  val is_req = is_binop @{cterm "op =:: real => _"}
+  val is_ge = is_binop @{cterm "op <=:: real => _"}
+  val is_gt = is_binop @{cterm "op <:: real => _"}
+  val is_conj = is_binop @{cterm "op &"}
+  val is_disj = is_binop @{cterm "op |"}
+  fun conj_pair th = (th RS @{thm conjunct1}, th RS @{thm conjunct2})
+  fun disj_cases th th1 th2 = 
+   let val (p,q) = dest_binop (concl th)
+       val c = concl th1
+       val _ = if c aconvc (concl th2) then () else error "disj_cases : conclusions not alpha convertible"
+   in implies_elim (implies_elim (implies_elim (instantiate' [] (map SOME [p,q,c]) @{thm disjE}) th) (implies_intr (capply @{cterm Trueprop} p) th1)) (implies_intr (capply @{cterm Trueprop} q) th2)
+   end
+ fun overall dun ths = case ths of
+  [] =>
+   let 
+    val (eq,ne) = List.partition (is_req o concl) dun
+     val (le,nl) = List.partition (is_ge o concl) ne
+     val lt = filter (is_gt o concl) nl 
+    in prover hol_of_positivstellensatz (eq,le,lt) end
+ | th::oths =>
+   let 
+    val ct = concl th 
+   in 
+    if is_conj ct  then
+     let 
+      val (th1,th2) = conj_pair th in
+      overall dun (th1::th2::oths) end
+    else if is_disj ct then
+      let 
+       val th1 = overall dun (assume (capply @{cterm Trueprop} (dest_arg1 ct))::oths)
+       val th2 = overall dun (assume (capply @{cterm Trueprop} (dest_arg ct))::oths)
+      in disj_cases th th1 th2 end
+   else overall (th::dun) oths
+  end
+  fun dest_binary b ct = if is_binop b ct then dest_binop ct 
+                         else raise CTERM ("dest_binary",[b,ct])
+  val dest_eq = dest_binary @{cterm "op = :: real => _"}
+  val neq_th = nth pth 5
+  fun real_not_eq_conv ct = 
+   let 
+    val (l,r) = dest_eq (dest_arg ct)
+    val th = instantiate ([],[(@{cpat "?x::real"},l),(@{cpat "?y::real"},r)]) neq_th
+    val th_p = poly_conv(dest_arg(dest_arg1(Thm.rhs_of th)))
+    val th_x = Drule.arg_cong_rule @{cterm "uminus :: real => _"} th_p
+    val th_n = fconv_rule (arg_conv poly_neg_conv) th_x
+    val th' = Drule.binop_cong_rule @{cterm "op |"} 
+     (Drule.arg_cong_rule (capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_p)
+     (Drule.arg_cong_rule (capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_n)
+    in transitive th th' 
+  end
+ fun equal_implies_1_rule PQ = 
+  let 
+   val P = lhs_of PQ
+  in implies_intr P (equal_elim PQ (assume P))
+  end
+ (* FIXME!!! Copied from groebner.ml *)
+ val strip_exists =
+  let fun h (acc, t) =
+   case (term_of t) of
+    Const("Ex",_)$Abs(x,T,p) => h (dest_abs NONE (dest_arg t) |>> (fn v => v::acc))
+  | _ => (acc,t)
+  in fn t => h ([],t)
+  end
+  fun name_of x = case term_of x of
+   Free(s,_) => s
+ | Var ((s,_),_) => s
+ | _ => "x"
+
+  fun mk_forall x th = Drule.arg_cong_rule (instantiate_cterm' [SOME (ctyp_of_term x)] [] @{cpat "All :: (?'a => bool) => _" }) (abstract_rule (name_of x) x th)
+
+  val specl = fold_rev (fn x => fn th => instantiate' [] [SOME x] (th RS spec));
+
+ fun ext T = Drule.cterm_rule (instantiate' [SOME T] []) @{cpat Ex}
+ fun mk_ex v t = Thm.capply (ext (ctyp_of_term v)) (Thm.cabs v t)
+
+ fun choose v th th' = case concl_of th of 
+   @{term Trueprop} $ (Const("Ex",_)$_) => 
+    let
+     val p = (funpow 2 Thm.dest_arg o cprop_of) th
+     val T = (hd o Thm.dest_ctyp o ctyp_of_term) p
+     val th0 = fconv_rule (Thm.beta_conversion true)
+         (instantiate' [SOME T] [SOME p, (SOME o Thm.dest_arg o cprop_of) th'] exE)
+     val pv = (Thm.rhs_of o Thm.beta_conversion true) 
+           (Thm.capply @{cterm Trueprop} (Thm.capply p v))
+     val th1 = forall_intr v (implies_intr pv th')
+    in implies_elim (implies_elim th0 th) th1  end
+ | _ => raise THM ("choose",0,[th, th'])
+
+  fun simple_choose v th = 
+     choose v (assume ((Thm.capply @{cterm Trueprop} o mk_ex v) ((Thm.dest_arg o hd o #hyps o Thm.crep_thm) th))) th
+
+ val strip_forall =
+  let fun h (acc, t) =
+   case (term_of t) of
+    Const("All",_)$Abs(x,T,p) => h (dest_abs NONE (dest_arg t) |>> (fn v => v::acc))
+  | _ => (acc,t)
+  in fn t => h ([],t)
+  end
+
+ fun f ct =
+  let 
+   val nnf_norm_conv' = 
+     nnf_conv then_conv 
+     literals_conv [@{term "op &"}, @{term "op |"}] [] 
+     (cache_conv 
+       (first_conv [real_lt_conv, real_le_conv, 
+                    real_eq_conv, real_not_lt_conv, 
+                    real_not_le_conv, real_not_eq_conv, all_conv]))
+  fun absremover ct = (literals_conv [@{term "op &"}, @{term "op |"}] [] 
+                  (try_conv (absconv1 then_conv binop_conv (arg_conv poly_conv))) then_conv 
+        try_conv (absconv2 then_conv nnf_norm_conv' then_conv binop_conv absremover)) ct
+  val nct = capply @{cterm Trueprop} (capply @{cterm "Not"} ct)
+  val th0 = (init_conv then_conv arg_conv nnf_norm_conv') nct
+  val tm0 = dest_arg (Thm.rhs_of th0)
+  val th = if tm0 aconvc @{cterm False} then equal_implies_1_rule th0 else
+   let 
+    val (evs,bod) = strip_exists tm0
+    val (avs,ibod) = strip_forall bod
+    val th1 = Drule.arg_cong_rule @{cterm Trueprop} (fold mk_forall avs (absremover ibod))
+    val th2 = overall [] [specl avs (assume (Thm.rhs_of th1))]
+    val th3 = fold simple_choose evs (prove_hyp (equal_elim th1 (assume (capply @{cterm Trueprop} bod))) th2)
+   in  Drule.implies_intr_hyps (prove_hyp (equal_elim th0 (assume nct)) th3)
+   end
+  in implies_elim (instantiate' [] [SOME ct] pth_final) th
+ end
+in f
+end;
+
+(* A linear arithmetic prover *)
+local
+  val linear_add = Ctermfunc.combine (curry op +/) (fn z => z =/ Rat.zero)
+  fun linear_cmul c = Ctermfunc.mapf (fn x => c */ x)
+  val one_tm = @{cterm "1::real"}
+  fun contradictory p (e,_) = ((Ctermfunc.is_undefined e) andalso not(p Rat.zero)) orelse
+     ((gen_eq_set (op aconvc) (Ctermfunc.dom e, [one_tm])) andalso not(p(Ctermfunc.apply e one_tm)))
+
+  fun linear_ineqs vars (les,lts) = 
+   case find_first (contradictory (fn x => x >/ Rat.zero)) lts of
+    SOME r => r
+  | NONE => 
+   (case find_first (contradictory (fn x => x >/ Rat.zero)) les of
+     SOME r => r
+   | NONE => 
+     if null vars then error "linear_ineqs: no contradiction" else
+     let 
+      val ineqs = les @ lts
+      fun blowup v =
+       length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) ineqs) +
+       length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) ineqs) *
+       length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero </ Rat.zero) ineqs)
+      val  v = fst(hd(sort (fn ((_,i),(_,j)) => int_ord (i,j))
+                 (map (fn v => (v,blowup v)) vars)))
+      fun addup (e1,p1) (e2,p2) acc =
+       let 
+        val c1 = Ctermfunc.tryapplyd e1 v Rat.zero 
+        val c2 = Ctermfunc.tryapplyd e2 v Rat.zero
+       in if c1 */ c2 >=/ Rat.zero then acc else
+        let 
+         val e1' = linear_cmul (Rat.abs c2) e1
+         val e2' = linear_cmul (Rat.abs c1) e2
+         val p1' = Product(Rational_lt(Rat.abs c2),p1)
+         val p2' = Product(Rational_lt(Rat.abs c1),p2)
+        in (linear_add e1' e2',Sum(p1',p2'))::acc
+        end
+       end
+      val (les0,les1) = 
+         List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) les
+      val (lts0,lts1) = 
+         List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) lts
+      val (lesp,lesn) = 
+         List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) les1
+      val (ltsp,ltsn) = 
+         List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) lts1
+      val les' = fold_rev (fn ep1 => fold_rev (addup ep1) lesp) lesn les0
+      val lts' = fold_rev (fn ep1 => fold_rev (addup ep1) (lesp@ltsp)) ltsn
+                      (fold_rev (fn ep1 => fold_rev (addup ep1) (lesn@ltsn)) ltsp lts0)
+     in linear_ineqs (remove (op aconvc) v vars) (les',lts')
+     end)
+
+  fun linear_eqs(eqs,les,lts) = 
+   case find_first (contradictory (fn x => x =/ Rat.zero)) eqs of
+    SOME r => r
+  | NONE => (case eqs of 
+    [] => 
+     let val vars = remove (op aconvc) one_tm 
+           (fold_rev (curry (gen_union (op aconvc)) o Ctermfunc.dom o fst) (les@lts) []) 
+     in linear_ineqs vars (les,lts) end
+   | (e,p)::es => 
+     if Ctermfunc.is_undefined e then linear_eqs (es,les,lts) else
+     let 
+      val (x,c) = Ctermfunc.choose (Ctermfunc.undefine one_tm e)
+      fun xform (inp as (t,q)) =
+       let val d = Ctermfunc.tryapplyd t x Rat.zero in
+        if d =/ Rat.zero then inp else
+        let 
+         val k = (Rat.neg d) */ Rat.abs c // c
+         val e' = linear_cmul k e
+         val t' = linear_cmul (Rat.abs c) t
+         val p' = Eqmul(cterm_of_rat k,p)
+         val q' = Product(Rational_lt(Rat.abs c),q) 
+        in (linear_add e' t',Sum(p',q')) 
+        end 
+      end
+     in linear_eqs(map xform es,map xform les,map xform lts)
+     end)
+
+  fun linear_prover (eq,le,lt) = 
+   let 
+    val eqs = map2 (fn p => fn n => (p,Axiom_eq n)) eq (0 upto (length eq - 1))
+    val les = map2 (fn p => fn n => (p,Axiom_le n)) le (0 upto (length le - 1))
+    val lts = map2 (fn p => fn n => (p,Axiom_lt n)) lt (0 upto (length lt - 1))
+   in linear_eqs(eqs,les,lts)
+   end 
+  
+  fun lin_of_hol ct = 
+   if ct aconvc @{cterm "0::real"} then Ctermfunc.undefined
+   else if not (is_comb ct) then Ctermfunc.onefunc (ct, Rat.one)
+   else if is_ratconst ct then Ctermfunc.onefunc (one_tm, dest_ratconst ct)
+   else
+    let val (lop,r) = Thm.dest_comb ct 
+    in if not (is_comb lop) then Ctermfunc.onefunc (ct, Rat.one)
+       else
+        let val (opr,l) = Thm.dest_comb lop 
+        in if opr aconvc @{cterm "op + :: real =>_"} 
+           then linear_add (lin_of_hol l) (lin_of_hol r)
+           else if opr aconvc @{cterm "op * :: real =>_"} 
+                   andalso is_ratconst l then Ctermfunc.onefunc (r, dest_ratconst l)
+           else Ctermfunc.onefunc (ct, Rat.one)
+        end
+    end
+
+  fun is_alien ct = case term_of ct of 
+   Const(@{const_name "real"}, _)$ n => 
+     if can HOLogic.dest_number n then false else true
+  | _ => false
+ open Thm
+in 
+fun real_linear_prover translator (eq,le,lt) = 
+ let 
+  val lhs = lin_of_hol o dest_arg1 o dest_arg o cprop_of
+  val rhs = lin_of_hol o dest_arg o dest_arg o cprop_of
+  val eq_pols = map lhs eq
+  val le_pols = map rhs le
+  val lt_pols = map rhs lt 
+  val aliens =  filter is_alien
+      (fold_rev (curry (gen_union (op aconvc)) o Ctermfunc.dom) 
+          (eq_pols @ le_pols @ lt_pols) [])
+  val le_pols' = le_pols @ map (fn v => Ctermfunc.onefunc (v,Rat.one)) aliens
+  val (_,proof) = linear_prover (eq_pols,le_pols',lt_pols)
+  val le' = le @ map (fn a => instantiate' [] [SOME (dest_arg a)] @{thm real_of_nat_ge_zero}) aliens 
+ in (translator (eq,le',lt) proof) : thm
+ end
+end;
+
+(* A less general generic arithmetic prover dealing with abs,max and min*)
+
+local
+ val absmaxmin_elim_ss1 = HOL_basic_ss addsimps real_abs_thms1
+ fun absmaxmin_elim_conv1 ctxt = 
+    Simplifier.rewrite (Simplifier.context ctxt absmaxmin_elim_ss1)
+
+ val absmaxmin_elim_conv2 =
+  let 
+   val pth_abs = instantiate' [SOME @{ctyp real}] [] abs_split'
+   val pth_max = instantiate' [SOME @{ctyp real}] [] max_split
+   val pth_min = instantiate' [SOME @{ctyp real}] [] min_split
+   val abs_tm = @{cterm "abs :: real => _"}
+   val p_tm = @{cpat "?P :: real => bool"}
+   val x_tm = @{cpat "?x :: real"}
+   val y_tm = @{cpat "?y::real"}
+   val is_max = is_binop @{cterm "max :: real => _"}
+   val is_min = is_binop @{cterm "min :: real => _"} 
+   fun is_abs t = is_comb t andalso dest_fun t aconvc abs_tm
+   fun eliminate_construct p c tm =
+    let 
+     val t = find_cterm p tm
+     val th0 = (symmetric o beta_conversion false) (capply (cabs t tm) t)
+     val (p,ax) = (dest_comb o Thm.rhs_of) th0
+    in fconv_rule(arg_conv(binop_conv (arg_conv (beta_conversion false))))
+               (transitive th0 (c p ax))
+   end
+
+   val elim_abs = eliminate_construct is_abs
+    (fn p => fn ax => 
+       instantiate ([], [(p_tm,p), (x_tm, dest_arg ax)]) pth_abs)
+   val elim_max = eliminate_construct is_max
+    (fn p => fn ax => 
+      let val (ax,y) = dest_comb ax 
+      in  instantiate ([], [(p_tm,p), (x_tm, dest_arg ax), (y_tm,y)]) 
+      pth_max end)
+   val elim_min = eliminate_construct is_min
+    (fn p => fn ax => 
+      let val (ax,y) = dest_comb ax 
+      in  instantiate ([], [(p_tm,p), (x_tm, dest_arg ax), (y_tm,y)]) 
+      pth_min end)
+   in first_conv [elim_abs, elim_max, elim_min, all_conv]
+  end;
+in fun gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,prover) =
+        gen_gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,
+                       absmaxmin_elim_conv1 ctxt,absmaxmin_elim_conv2,prover)
+end;
+
+(* An instance for reals*) 
+
+fun gen_prover_real_arith ctxt prover = 
+ let
+  fun simple_cterm_ord t u = TermOrd.term_ord (term_of t, term_of u) = LESS
+  val {add,mul,neg,pow,sub,main} = 
+     Normalizer.semiring_normalizers_ord_wrapper ctxt
+      (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
+     simple_cterm_ord
+in gen_real_arith ctxt
+   (cterm_of_rat, field_comp_conv, field_comp_conv,field_comp_conv,
+    main,neg,add,mul, prover)
+end;
+
+fun real_arith ctxt = gen_prover_real_arith ctxt real_linear_prover;
+end
+
+  (* Now the norm procedure for euclidean spaces *)
+
+
+signature NORM_ARITH = 
+sig
+ val norm_arith : Proof.context -> conv
+ val norm_arith_tac : Proof.context -> int -> tactic
+end
+
+structure NormArith : NORM_ARITH = 
+struct
+
+ open Conv Thm Conv2;
+ val bool_eq = op = : bool *bool -> bool
+ fun dest_ratconst t = case term_of t of
+   Const(@{const_name divide}, _)$a$b => Rat.rat_of_quotient(HOLogic.dest_number a |> snd, HOLogic.dest_number b |> snd)
+ | _ => Rat.rat_of_int (HOLogic.dest_number (term_of t) |> snd)
+ fun is_ratconst t = can dest_ratconst t
+ fun augment_norm b t acc = case term_of t of 
+     Const(@{const_name norm}, _) $ _ => insert (eq_pair bool_eq (op aconvc)) (b,dest_arg t) acc
+   | _ => acc
+ fun find_normedterms t acc = case term_of t of
+    @{term "op + :: real => _"}$_$_ =>
+            find_normedterms (dest_arg1 t) (find_normedterms (dest_arg t) acc)
+      | @{term "op * :: real => _"}$_$n =>
+            if not (is_ratconst (dest_arg1 t)) then acc else
+            augment_norm (dest_ratconst (dest_arg1 t) >=/ Rat.zero) 
+                      (dest_arg t) acc
+      | _ => augment_norm true t acc 
+
+ val cterm_lincomb_neg = Ctermfunc.mapf Rat.neg
+ fun cterm_lincomb_cmul c t = 
+    if c =/ Rat.zero then Ctermfunc.undefined else Ctermfunc.mapf (fn x => x */ c) t
+ fun cterm_lincomb_add l r = Ctermfunc.combine (curry op +/) (fn x => x =/ Rat.zero) l r
+ fun cterm_lincomb_sub l r = cterm_lincomb_add l (cterm_lincomb_neg r)
+ fun cterm_lincomb_eq l r = Ctermfunc.is_undefined (cterm_lincomb_sub l r)
+
+ val int_lincomb_neg = Intfunc.mapf Rat.neg
+ fun int_lincomb_cmul c t = 
+    if c =/ Rat.zero then Intfunc.undefined else Intfunc.mapf (fn x => x */ c) t
+ fun int_lincomb_add l r = Intfunc.combine (curry op +/) (fn x => x =/ Rat.zero) l r
+ fun int_lincomb_sub l r = int_lincomb_add l (int_lincomb_neg r)
+ fun int_lincomb_eq l r = Intfunc.is_undefined (int_lincomb_sub l r)
+
+fun vector_lincomb t = case term_of t of 
+   Const(@{const_name plus},Type("fun",[Type("Finite_Cartesian_Product.^",_),_])) $ _ $ _ =>
+    cterm_lincomb_add (vector_lincomb (dest_arg1 t)) (vector_lincomb (dest_arg t))
+ | Const(@{const_name minus},Type("fun",[Type("Finite_Cartesian_Product.^",_),_])) $ _ $ _ =>
+    cterm_lincomb_sub (vector_lincomb (dest_arg1 t)) (vector_lincomb (dest_arg t))
+ | Const(@{const_name vector_scalar_mult},Type("fun",[Type("Finite_Cartesian_Product.^",_),_]))$_$_ =>
+    cterm_lincomb_cmul (dest_ratconst (dest_arg1 t)) (vector_lincomb (dest_arg t))
+ | Const(@{const_name uminus},Type("fun",[Type("Finite_Cartesian_Product.^",_),_]))$_ =>
+     cterm_lincomb_neg (vector_lincomb (dest_arg t))
+ | Const(@{const_name vec},_)$_ => 
+   let 
+     val b = ((snd o HOLogic.dest_number o term_of o dest_arg) t = 0 
+               handle TERM _=> false)
+   in if b then Ctermfunc.onefunc (t,Rat.one)
+      else Ctermfunc.undefined
+   end
+ | _ => Ctermfunc.onefunc (t,Rat.one)
+
+ fun vector_lincombs ts =
+  fold_rev 
+   (fn t => fn fns => case AList.lookup (op aconvc) fns t of
+     NONE => 
+       let val f = vector_lincomb t 
+       in case find_first (fn (_,f') => cterm_lincomb_eq f f') fns of
+           SOME (_,f') => (t,f') :: fns
+         | NONE => (t,f) :: fns 
+       end
+   | SOME _ => fns) ts []
+
+fun replacenegnorms cv t = case term_of t of 
+  @{term "op + :: real => _"}$_$_ => binop_conv (replacenegnorms cv) t
+| @{term "op * :: real => _"}$_$_ => 
+    if dest_ratconst (dest_arg1 t) </ Rat.zero then arg_conv cv t else reflexive t
+| _ => reflexive t
+fun flip v eq = 
+  if Ctermfunc.defined eq v 
+  then Ctermfunc.update (v, Rat.neg (Ctermfunc.apply eq v)) eq else eq
+fun allsubsets s = case s of 
+  [] => [[]]
+|(a::t) => let val res = allsubsets t in
+               map (cons a) res @ res end
+fun evaluate env lin =
+ Intfunc.fold (fn (x,c) => fn s => s +/ c */ (Intfunc.apply env x)) 
+   lin Rat.zero
+
+fun solve (vs,eqs) = case (vs,eqs) of
+  ([],[]) => SOME (Intfunc.onefunc (0,Rat.one))
+ |(_,eq::oeqs) => 
+   (case vs inter (Intfunc.dom eq) of
+     [] => NONE
+    | v::_ => 
+       if Intfunc.defined eq v 
+       then 
+        let 
+         val c = Intfunc.apply eq v
+         val vdef = int_lincomb_cmul (Rat.neg (Rat.inv c)) eq
+         fun eliminate eqn = if not (Intfunc.defined eqn v) then eqn 
+                             else int_lincomb_add (int_lincomb_cmul (Intfunc.apply eqn v) vdef) eqn
+        in (case solve (vs \ v,map eliminate oeqs) of
+            NONE => NONE
+          | SOME soln => SOME (Intfunc.update (v, evaluate soln (Intfunc.undefine v vdef)) soln))
+        end
+       else NONE)
+
+fun combinations k l = if k = 0 then [[]] else
+ case l of 
+  [] => []
+| h::t => map (cons h) (combinations (k - 1) t) @ combinations k t
+
+
+fun forall2 p l1 l2 = case (l1,l2) of 
+   ([],[]) => true
+ | (h1::t1,h2::t2) => p h1 h2 andalso forall2 p t1 t2
+ | _ => false;
+
+
+fun vertices vs eqs =
+ let 
+  fun vertex cmb = case solve(vs,cmb) of
+    NONE => NONE
+   | SOME soln => SOME (map (fn v => Intfunc.tryapplyd soln v Rat.zero) vs)
+  val rawvs = map_filter vertex (combinations (length vs) eqs)
+  val unset = filter (forall (fn c => c >=/ Rat.zero)) rawvs 
+ in fold_rev (insert (uncurry (forall2 (curry op =/)))) unset [] 
+ end 
+
+fun subsumes l m = forall2 (fn x => fn y => Rat.abs x <=/ Rat.abs y) l m 
+
+fun subsume todo dun = case todo of
+ [] => dun
+|v::ovs => 
+   let val dun' = if exists (fn w => subsumes w v) dun then dun
+                  else v::(filter (fn w => not(subsumes v w)) dun) 
+   in subsume ovs dun' 
+   end;
+
+fun match_mp PQ P = P RS PQ;
+
+fun cterm_of_rat x = 
+let val (a, b) = Rat.quotient_of_rat x
+in 
+ if b = 1 then Numeral.mk_cnumber @{ctyp "real"} a
+  else Thm.capply (Thm.capply @{cterm "op / :: real => _"} 
+                   (Numeral.mk_cnumber @{ctyp "real"} a))
+        (Numeral.mk_cnumber @{ctyp "real"} b)
+end;
+
+fun norm_cmul_rule c th = instantiate' [] [SOME (cterm_of_rat c)] (th RS @{thm norm_cmul_rule_thm});
+
+fun norm_add_rule th1 th2 = [th1, th2] MRS @{thm norm_add_rule_thm};
+
+  (* I think here the static context should be sufficient!! *)
+fun inequality_canon_rule ctxt = 
+ let 
+  (* FIXME : Should be computed statically!! *)
+  val real_poly_conv = 
+    Normalizer.semiring_normalize_wrapper ctxt
+     (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"}))
+ in fconv_rule (arg_conv ((rewr_conv @{thm ge_iff_diff_ge_0}) then_conv arg_conv (field_comp_conv then_conv real_poly_conv)))
+end;
+
+ fun absc cv ct = case term_of ct of 
+ Abs (v,_, _) => 
+  let val (x,t) = Thm.dest_abs (SOME v) ct
+  in Thm.abstract_rule ((fst o dest_Free o term_of) x) x (cv t)
+  end
+ | _ => all_conv ct;
+
+fun sub_conv cv ct = (comb_conv cv else_conv absc cv) ct;
+fun botc1 conv ct = 
+  ((sub_conv (botc1 conv)) then_conv (conv else_conv all_conv)) ct;
+
+ fun rewrs_conv eqs ct = first_conv (map rewr_conv eqs) ct;
+ val apply_pth1 = rewr_conv @{thm pth_1};
+ val apply_pth2 = rewr_conv @{thm pth_2};
+ val apply_pth3 = rewr_conv @{thm pth_3};
+ val apply_pth4 = rewrs_conv @{thms pth_4};
+ val apply_pth5 = rewr_conv @{thm pth_5};
+ val apply_pth6 = rewr_conv @{thm pth_6};
+ val apply_pth7 = rewrs_conv @{thms pth_7};
+ val apply_pth8 = rewr_conv @{thm pth_8} then_conv arg1_conv field_comp_conv then_conv (try_conv (rewr_conv (mk_meta_eq @{thm vector_smult_lzero})));
+ val apply_pth9 = rewrs_conv @{thms pth_9} then_conv arg1_conv (arg1_conv field_comp_conv);
+ val apply_ptha = rewr_conv @{thm pth_a};
+ val apply_pthb = rewrs_conv @{thms pth_b};
+ val apply_pthc = rewrs_conv @{thms pth_c};
+ val apply_pthd = try_conv (rewr_conv @{thm pth_d});
+
+fun headvector t = case t of 
+  Const(@{const_name plus}, Type("fun",[Type("Finite_Cartesian_Product.^",_),_]))$
+   (Const(@{const_name vector_scalar_mult}, _)$l$v)$r => v
+ | Const(@{const_name vector_scalar_mult}, _)$l$v => v
+ | _ => error "headvector: non-canonical term"
+
+fun vector_cmul_conv ct =
+   ((apply_pth5 then_conv arg1_conv field_comp_conv) else_conv
+    (apply_pth6 then_conv binop_conv vector_cmul_conv)) ct
+
+fun vector_add_conv ct = apply_pth7 ct 
+ handle CTERM _ => 
+  (apply_pth8 ct 
+   handle CTERM _ => 
+    (case term_of ct of 
+     Const(@{const_name plus},_)$lt$rt =>
+      let 
+       val l = headvector lt 
+       val r = headvector rt
+      in (case TermOrd.fast_term_ord (l,r) of
+         LESS => (apply_pthb then_conv arg_conv vector_add_conv 
+                  then_conv apply_pthd) ct
+        | GREATER => (apply_pthc then_conv arg_conv vector_add_conv 
+                     then_conv apply_pthd) ct 
+        | EQUAL => (apply_pth9 then_conv 
+                ((apply_ptha then_conv vector_add_conv) else_conv 
+              arg_conv vector_add_conv then_conv apply_pthd)) ct)
+      end
+     | _ => reflexive ct))
+
+fun vector_canon_conv ct = case term_of ct of
+ Const(@{const_name plus},_)$_$_ =>
+  let 
+   val ((p,l),r) = Thm.dest_comb ct |>> Thm.dest_comb
+   val lth = vector_canon_conv l 
+   val rth = vector_canon_conv r
+   val th = Drule.binop_cong_rule p lth rth 
+  in fconv_rule (arg_conv vector_add_conv) th end
+
+| Const(@{const_name vector_scalar_mult}, _)$_$_ =>
+  let 
+   val (p,r) = Thm.dest_comb ct
+   val rth = Drule.arg_cong_rule p (vector_canon_conv r) 
+  in fconv_rule (arg_conv (apply_pth4 else_conv vector_cmul_conv)) rth
+  end
+
+| Const(@{const_name minus},_)$_$_ => (apply_pth2 then_conv vector_canon_conv) ct
+
+| Const(@{const_name uminus},_)$_ => (apply_pth3 then_conv vector_canon_conv) ct
+
+| Const(@{const_name vec},_)$n => 
+  let val n = Thm.dest_arg ct
+  in if is_ratconst n andalso not (dest_ratconst n =/ Rat.zero) 
+     then reflexive ct else apply_pth1 ct
+  end
+
+| _ => apply_pth1 ct
+
+fun norm_canon_conv ct = case term_of ct of
+  Const(@{const_name norm},_)$_ => arg_conv vector_canon_conv ct
+ | _ => raise CTERM ("norm_canon_conv", [ct])
+
+fun fold_rev2 f [] [] z = z
+ | fold_rev2 f (x::xs) (y::ys) z = f x y (fold_rev2 f xs ys z)
+ | fold_rev2 f _ _ _ = raise UnequalLengths;
+
+fun int_flip v eq = 
+  if Intfunc.defined eq v 
+  then Intfunc.update (v, Rat.neg (Intfunc.apply eq v)) eq else eq;
+
+local
+ val pth_zero = @{thm "norm_0"}
+ val tv_n = (hd o tl o dest_ctyp o ctyp_of_term o dest_arg o dest_arg1 o dest_arg o cprop_of)
+             pth_zero
+ val concl = dest_arg o cprop_of 
+ fun real_vector_combo_prover ctxt translator (nubs,ges,gts) = 
+  let 
+   (* FIXME: Should be computed statically!!*)
+   val real_poly_conv = 
+      Normalizer.semiring_normalize_wrapper ctxt
+       (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"}))
+   val sources = map (dest_arg o dest_arg1 o concl) nubs
+   val rawdests = fold_rev (find_normedterms o dest_arg o concl) (ges @ gts) [] 
+   val _ = if not (forall fst rawdests) then error "real_vector_combo_prover: Sanity check" 
+           else ()
+   val dests = distinct (op aconvc) (map snd rawdests)
+   val srcfuns = map vector_lincomb sources
+   val destfuns = map vector_lincomb dests 
+   val vvs = fold_rev (curry (gen_union op aconvc) o Ctermfunc.dom) (srcfuns @ destfuns) []
+   val n = length srcfuns
+   val nvs = 1 upto n
+   val srccombs = srcfuns ~~ nvs
+   fun consider d =
+    let 
+     fun coefficients x =
+      let 
+       val inp = if Ctermfunc.defined d x then Intfunc.onefunc (0, Rat.neg(Ctermfunc.apply d x))
+                      else Intfunc.undefined 
+      in fold_rev (fn (f,v) => fn g => if Ctermfunc.defined f x then Intfunc.update (v, Ctermfunc.apply f x) g else g) srccombs inp 
+      end
+     val equations = map coefficients vvs
+     val inequalities = map (fn n => Intfunc.onefunc (n,Rat.one)) nvs
+     fun plausiblevertices f =
+      let 
+       val flippedequations = map (fold_rev int_flip f) equations
+       val constraints = flippedequations @ inequalities
+       val rawverts = vertices nvs constraints
+       fun check_solution v =
+        let 
+          val f = fold_rev2 (curry Intfunc.update) nvs v (Intfunc.onefunc (0, Rat.one))
+        in forall (fn e => evaluate f e =/ Rat.zero) flippedequations
+        end
+       val goodverts = filter check_solution rawverts
+       val signfixups = map (fn n => if n mem_int  f then ~1 else 1) nvs 
+      in map (map2 (fn s => fn c => Rat.rat_of_int s */ c) signfixups) goodverts
+      end
+     val allverts = fold_rev append (map plausiblevertices (allsubsets nvs)) [] 
+    in subsume allverts []
+    end
+   fun compute_ineq v =
+    let 
+     val ths = map_filter (fn (v,t) => if v =/ Rat.zero then NONE 
+                                     else SOME(norm_cmul_rule v t))
+                            (v ~~ nubs) 
+    in inequality_canon_rule ctxt (end_itlist norm_add_rule ths)
+    end
+   val ges' = map_filter (try compute_ineq) (fold_rev (append o consider) destfuns []) @
+                 map (inequality_canon_rule ctxt) nubs @ ges
+   val zerodests = filter
+        (fn t => null (Ctermfunc.dom (vector_lincomb t))) (map snd rawdests)
+
+  in RealArith.real_linear_prover translator
+        (map (fn t => instantiate ([(tv_n,(hd o tl o dest_ctyp o ctyp_of_term) t)],[]) pth_zero)
+            zerodests,
+        map (fconv_rule (once_depth_conv (norm_canon_conv) then_conv
+                       arg_conv (arg_conv real_poly_conv))) ges',
+        map (fconv_rule (once_depth_conv (norm_canon_conv) then_conv 
+                       arg_conv (arg_conv real_poly_conv))) gts)
+  end
+in val real_vector_combo_prover = real_vector_combo_prover
+end;
+
+local
+ val pth = @{thm norm_imp_pos_and_ge}
+ val norm_mp = match_mp pth
+ val concl = dest_arg o cprop_of
+ fun conjunct1 th = th RS @{thm conjunct1}
+ fun conjunct2 th = th RS @{thm conjunct2}
+ fun C f x y = f y x
+fun real_vector_ineq_prover ctxt translator (ges,gts) = 
+ let 
+(*   val _ = error "real_vector_ineq_prover: pause" *)
+  val ntms = fold_rev find_normedterms (map (dest_arg o concl) (ges @ gts)) []
+  val lctab = vector_lincombs (map snd (filter (not o fst) ntms))
+  val (fxns, ctxt') = Variable.variant_fixes (replicate (length lctab) "x") ctxt
+  fun mk_norm t = capply (instantiate_cterm' [SOME (ctyp_of_term t)] [] @{cpat "norm :: (?'a :: norm) => real"}) t
+  fun mk_equals l r = capply (capply (instantiate_cterm' [SOME (ctyp_of_term l)] [] @{cpat "op == :: ?'a =>_"}) l) r
+  val asl = map2 (fn (t,_) => fn n => assume (mk_equals (mk_norm t) (cterm_of (ProofContext.theory_of ctxt') (Free(n,@{typ real}))))) lctab fxns
+  val replace_conv = try_conv (rewrs_conv asl)
+  val replace_rule = fconv_rule (funpow 2 arg_conv (replacenegnorms replace_conv))
+  val ges' =
+       fold_rev (fn th => fn ths => conjunct1(norm_mp th)::ths)
+              asl (map replace_rule ges)
+  val gts' = map replace_rule gts
+  val nubs = map (conjunct2 o norm_mp) asl
+  val th1 = real_vector_combo_prover ctxt' translator (nubs,ges',gts')
+  val shs = filter (member (fn (t,th) => t aconvc cprop_of th) asl) (#hyps (crep_thm th1)) 
+  val th11 = hd (Variable.export ctxt' ctxt [fold implies_intr shs th1])
+  val cps = map (swap o dest_equals) (cprems_of th11)
+  val th12 = instantiate ([], cps) th11
+  val th13 = fold (C implies_elim) (map (reflexive o snd) cps) th12;
+ in hd (Variable.export ctxt' ctxt [th13])
+ end 
+in val real_vector_ineq_prover = real_vector_ineq_prover
+end;
+
+local
+ val rawrule = fconv_rule (arg_conv (rewr_conv @{thm real_eq_0_iff_le_ge_0}))
+ fun conj_pair th = (th RS @{thm conjunct1}, th RS @{thm conjunct2})
+ fun simple_cterm_ord t u = TermOrd.term_ord (term_of t, term_of u) = LESS;
+  (* FIXME: Lookup in the context every time!!! Fix this !!!*)
+ fun splitequation ctxt th acc =
+  let 
+   val real_poly_neg_conv = #neg
+       (Normalizer.semiring_normalizers_ord_wrapper ctxt
+        (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) simple_cterm_ord)
+   val (th1,th2) = conj_pair(rawrule th)
+  in th1::fconv_rule (arg_conv (arg_conv real_poly_neg_conv)) th2::acc
+  end
+in fun real_vector_prover ctxt translator (eqs,ges,gts) =
+     real_vector_ineq_prover ctxt translator
+         (fold_rev (splitequation ctxt) eqs ges,gts)
+end;
+
+  fun init_conv ctxt = 
+   Simplifier.rewrite (Simplifier.context ctxt 
+     (HOL_basic_ss addsimps ([@{thm vec_0}, @{thm vec_1}, @{thm dist_def}, @{thm diff_0_right}, @{thm right_minus}, @{thm diff_self}, @{thm norm_0}] @ @{thms arithmetic_simps} @ @{thms norm_pths})))
+   then_conv field_comp_conv 
+   then_conv nnf_conv
+
+ fun pure ctxt = RealArith.gen_prover_real_arith ctxt (real_vector_prover ctxt);
+ fun norm_arith ctxt ct = 
+  let 
+   val ctxt' = Variable.declare_term (term_of ct) ctxt
+   val th = init_conv ctxt' ct
+  in equal_elim (Drule.arg_cong_rule @{cterm Trueprop} (symmetric th)) 
+                (pure ctxt' (rhs_of th))
+ end
+
+ fun norm_arith_tac ctxt = 
+   clarify_tac HOL_cs THEN'
+   ObjectLogic.full_atomize_tac THEN'
+   CSUBGOAL ( fn (p,i) => rtac (norm_arith ctxt (Thm.dest_arg p )) i);
+
+end;
\ No newline at end of file
--- a/src/HOL/Library/reflection.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Library/reflection.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -86,6 +86,23 @@
 
 exception REIF of string;
 
+fun dest_listT (Type ("List.list", [T])) = T;
+
+fun partition P [] = ([],[])
+  | partition P (x::xs) = 
+     let val (yes,no) = partition P xs
+     in if P x then (x::yes,no) else (yes, x::no) end
+
+fun rearrange congs = 
+let 
+ fun P (_, th) = 
+  let val @{term "Trueprop"}$(Const ("op =",_) $l$_) = concl_of th
+  in can dest_Var l end
+ val (yes,no) = partition P congs 
+ in no @ yes end
+
+fun genreif ctxt raw_eqs t =
+ let
 val bds = ref ([]: (typ * ((term list) * (term list))) list);
 
 fun index_of t = 
@@ -106,8 +123,6 @@
     end)
  end;
 
-fun dest_listT (Type ("List.list", [T])) = T;
-
 fun decomp_genreif da cgns (t,ctxt) =
  let 
   val thy = ProofContext.theory_of ctxt 
@@ -151,8 +166,6 @@
   end;
 
  (* looks for the atoms equation and instantiates it with the right number *)
-
-
 fun mk_decompatom eqs (t,ctxt) =
 let 
  val tT = fastype_of t
@@ -229,8 +242,8 @@
   (* Generic reification procedure: *)
   (* creates all needed cong rules and then just uses the theorem synthesis *)
 
-  fun mk_congs ctxt raw_eqs = 
- let
+fun mk_congs ctxt raw_eqs = 
+let
   val fs = fold_rev (fn eq =>
 		     insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop 
 			 |> HOLogic.dest_eq |> fst |> strip_comb 
@@ -257,23 +270,6 @@
 in ps ~~ (Variable.export ctxt' ctxt congs)
 end
 
-fun partition P [] = ([],[])
-  | partition P (x::xs) = 
-     let val (yes,no) = partition P xs
-     in if P x then (x::yes,no) else (yes, x::no) end
-
-fun rearrange congs = 
-let 
- fun P (_, th) = 
-  let val @{term "Trueprop"}$(Const ("op =",_) $l$_) = concl_of th
-  in can dest_Var l end
- val (yes,no) = partition P congs 
- in no @ yes end
-
-
-
-fun genreif ctxt raw_eqs t =
- let 
   val congs = rearrange (mk_congs ctxt raw_eqs)
   val th = divide_and_conquer (decomp_genreif (mk_decompatom raw_eqs) congs) (t,ctxt)
   fun is_listVar (Var (_,t)) = can dest_listT t
--- a/src/HOL/List.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/List.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -509,11 +509,11 @@
 
 let
 
-fun len (Const("List.list.Nil",_)) acc = acc
-  | len (Const("List.list.Cons",_) $ _ $ xs) (ts,n) = len xs (ts,n+1)
-  | len (Const("List.append",_) $ xs $ ys) acc = len xs (len ys acc)
-  | len (Const("List.rev",_) $ xs) acc = len xs acc
-  | len (Const("List.map",_) $ _ $ xs) acc = len xs acc
+fun len (Const(@{const_name Nil},_)) acc = acc
+  | len (Const(@{const_name Cons},_) $ _ $ xs) (ts,n) = len xs (ts,n+1)
+  | len (Const(@{const_name append},_) $ xs $ ys) acc = len xs (len ys acc)
+  | len (Const(@{const_name rev},_) $ xs) acc = len xs acc
+  | len (Const(@{const_name map},_) $ _ $ xs) acc = len xs acc
   | len t (ts,n) = (t::ts,n);
 
 fun list_neq _ ss ct =
@@ -639,18 +639,18 @@
 ML {*
 local
 
-fun last (cons as Const("List.list.Cons",_) $ _ $ xs) =
-  (case xs of Const("List.list.Nil",_) => cons | _ => last xs)
-  | last (Const("List.append",_) $ _ $ ys) = last ys
+fun last (cons as Const(@{const_name Cons},_) $ _ $ xs) =
+  (case xs of Const(@{const_name Nil},_) => cons | _ => last xs)
+  | last (Const(@{const_name append},_) $ _ $ ys) = last ys
   | last t = t;
 
-fun list1 (Const("List.list.Cons",_) $ _ $ Const("List.list.Nil",_)) = true
+fun list1 (Const(@{const_name Cons},_) $ _ $ Const(@{const_name Nil},_)) = true
   | list1 _ = false;
 
-fun butlast ((cons as Const("List.list.Cons",_) $ x) $ xs) =
-  (case xs of Const("List.list.Nil",_) => xs | _ => cons $ butlast xs)
-  | butlast ((app as Const("List.append",_) $ xs) $ ys) = app $ butlast ys
-  | butlast xs = Const("List.list.Nil",fastype_of xs);
+fun butlast ((cons as Const(@{const_name Cons},_) $ x) $ xs) =
+  (case xs of Const(@{const_name Nil},_) => xs | _ => cons $ butlast xs)
+  | butlast ((app as Const(@{const_name append},_) $ xs) $ ys) = app $ butlast ys
+  | butlast xs = Const(@{const_name Nil},fastype_of xs);
 
 val rearr_ss = HOL_basic_ss addsimps [@{thm append_assoc},
   @{thm append_Nil}, @{thm append_Cons}];
@@ -663,7 +663,7 @@
         val lhs1 = butlast lhs and rhs1 = butlast rhs;
         val Type(_,listT::_) = eqT
         val appT = [listT,listT] ---> listT
-        val app = Const("List.append",appT)
+        val app = Const(@{const_name append},appT)
         val F2 = eq $ (app$lhs1$lastl) $ (app$rhs1$lastr)
         val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (F,F2));
         val thm = Goal.prove (Simplifier.the_context ss) [] [] eq
--- a/src/HOL/Nat.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Nat.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -846,13 +846,6 @@
   thus "P i j" by (simp add: j)
 qed
 
-lemma nat_induct2: "[|P 0; P (Suc 0); !!k. P k ==> P (Suc (Suc k))|] ==> P n"
-  apply (rule nat_less_induct)
-  apply (case_tac n)
-  apply (case_tac [2] nat)
-  apply (blast intro: less_trans)+
-  done
-
 text {* The method of infinite descent, frequently used in number theory.
 Provided by Roelof Oosterhuis.
 $P(n)$ is true for all $n\in\mathbb{N}$ if
@@ -1336,12 +1329,19 @@
 use "Tools/arith_data.ML"
 declaration {* K ArithData.setup *}
 
+ML{*
+structure ArithFacts =
+  NamedThmsFun(val name = "arith"
+               val description = "arith facts - only ground formulas");
+*}
+
+setup ArithFacts.setup
+
 use "Tools/lin_arith.ML"
 declaration {* K LinArith.setup *}
 
 lemmas [arith_split] = nat_diff_split split_min split_max
 
-
 context order
 begin
 
--- a/src/HOL/Order_Relation.thy	Tue Feb 10 18:57:02 2009 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,131 +0,0 @@
-(*  ID          : $Id$
-    Author      : Tobias Nipkow
-*)
-
-header {* Orders as Relations *}
-
-theory Order_Relation
-imports Plain "~~/src/HOL/Hilbert_Choice" "~~/src/HOL/ATP_Linkup"
-begin
-
-text{* This prelude could be moved to theory Relation: *}
-
-definition "irrefl r \<equiv> \<forall>x. (x,x) \<notin> r"
-
-definition "total_on A r \<equiv> \<forall>x\<in>A.\<forall>y\<in>A. x\<noteq>y \<longrightarrow> (x,y)\<in>r \<or> (y,x)\<in>r"
-
-abbreviation "total \<equiv> total_on UNIV"
-
-
-lemma total_on_empty[simp]: "total_on {} r"
-by(simp add:total_on_def)
-
-lemma refl_on_converse[simp]: "refl A (r^-1) = refl A r"
-by(auto simp add:refl_def)
-
-lemma total_on_converse[simp]: "total_on A (r^-1) = total_on A r"
-by (auto simp: total_on_def)
-
-lemma irrefl_diff_Id[simp]: "irrefl(r-Id)"
-by(simp add:irrefl_def)
-
-declare [[simp_depth_limit = 2]]
-lemma trans_diff_Id: " trans r \<Longrightarrow> antisym r \<Longrightarrow> trans (r-Id)"
-by(simp add: antisym_def trans_def) blast
-declare [[simp_depth_limit = 50]]
-
-lemma total_on_diff_Id[simp]: "total_on A (r-Id) = total_on A r"
-by(simp add: total_on_def)
-
-
-subsection{* Orders on a set *}
-
-definition "preorder_on A r \<equiv> refl A r \<and> trans r"
-
-definition "partial_order_on A r \<equiv> preorder_on A r \<and> antisym r"
-
-definition "linear_order_on A r \<equiv> partial_order_on A r \<and> total_on A r"
-
-definition "strict_linear_order_on A r \<equiv> trans r \<and> irrefl r \<and> total_on A r"
-
-definition "well_order_on A r \<equiv> linear_order_on A r \<and> wf(r - Id)"
-
-lemmas order_on_defs =
-  preorder_on_def partial_order_on_def linear_order_on_def
-  strict_linear_order_on_def well_order_on_def
-
-
-lemma preorder_on_empty[simp]: "preorder_on {} {}"
-by(simp add:preorder_on_def trans_def)
-
-lemma partial_order_on_empty[simp]: "partial_order_on {} {}"
-by(simp add:partial_order_on_def)
-
-lemma lnear_order_on_empty[simp]: "linear_order_on {} {}"
-by(simp add:linear_order_on_def)
-
-lemma well_order_on_empty[simp]: "well_order_on {} {}"
-by(simp add:well_order_on_def)
-
-
-lemma preorder_on_converse[simp]: "preorder_on A (r^-1) = preorder_on A r"
-by (simp add:preorder_on_def)
-
-lemma partial_order_on_converse[simp]:
-  "partial_order_on A (r^-1) = partial_order_on A r"
-by (simp add: partial_order_on_def)
-
-lemma linear_order_on_converse[simp]:
-  "linear_order_on A (r^-1) = linear_order_on A r"
-by (simp add: linear_order_on_def)
-
-
-lemma strict_linear_order_on_diff_Id:
-  "linear_order_on A r \<Longrightarrow> strict_linear_order_on A (r-Id)"
-by(simp add: order_on_defs trans_diff_Id)
-
-
-subsection{* Orders on the field *}
-
-abbreviation "Refl r \<equiv> refl (Field r) r"
-
-abbreviation "Preorder r \<equiv> preorder_on (Field r) r"
-
-abbreviation "Partial_order r \<equiv> partial_order_on (Field r) r"
-
-abbreviation "Total r \<equiv> total_on (Field r) r"
-
-abbreviation "Linear_order r \<equiv> linear_order_on (Field r) r"
-
-abbreviation "Well_order r \<equiv> well_order_on (Field r) r"
-
-
-lemma subset_Image_Image_iff:
-  "\<lbrakk> Preorder r; A \<subseteq> Field r; B \<subseteq> Field r\<rbrakk> \<Longrightarrow>
-   r `` A \<subseteq> r `` B \<longleftrightarrow> (\<forall>a\<in>A.\<exists>b\<in>B. (b,a):r)"
-apply(auto simp add: subset_eq preorder_on_def refl_def Image_def)
-apply metis
-by(metis trans_def)
-
-lemma subset_Image1_Image1_iff:
-  "\<lbrakk> Preorder r; a : Field r; b : Field r\<rbrakk> \<Longrightarrow> r `` {a} \<subseteq> r `` {b} \<longleftrightarrow> (b,a):r"
-by(simp add:subset_Image_Image_iff)
-
-lemma Refl_antisym_eq_Image1_Image1_iff:
-  "\<lbrakk>Refl r; antisym r; a:Field r; b:Field r\<rbrakk> \<Longrightarrow> r `` {a} = r `` {b} \<longleftrightarrow> a=b"
-by(simp add: expand_set_eq antisym_def refl_def) metis
-
-lemma Partial_order_eq_Image1_Image1_iff:
-  "\<lbrakk>Partial_order r; a:Field r; b:Field r\<rbrakk> \<Longrightarrow> r `` {a} = r `` {b} \<longleftrightarrow> a=b"
-by(auto simp:order_on_defs Refl_antisym_eq_Image1_Image1_iff)
-
-
-subsection{* Orders on a type *}
-
-abbreviation "strict_linear_order \<equiv> strict_linear_order_on UNIV"
-
-abbreviation "linear_order \<equiv> linear_order_on UNIV"
-
-abbreviation "well_order r \<equiv> well_order_on UNIV"
-
-end
--- a/src/HOL/Plain.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Plain.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -1,7 +1,7 @@
 header {* Plain HOL *}
 
 theory Plain
-imports Datatype FunDef Record Extraction Divides
+imports Datatype FunDef Record Extraction Divides Fact
 begin
 
 text {*
--- a/src/HOL/Relation.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Relation.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -70,6 +70,16 @@
   "trans r == (ALL x y z. (x,y):r --> (y,z):r --> (x,z):r)"
 
 definition
+irrefl :: "('a * 'a) set => bool" where
+"irrefl r \<equiv> \<forall>x. (x,x) \<notin> r"
+
+definition
+total_on :: "'a set => ('a * 'a) set => bool" where
+"total_on A r \<equiv> \<forall>x\<in>A.\<forall>y\<in>A. x\<noteq>y \<longrightarrow> (x,y)\<in>r \<or> (y,x)\<in>r"
+
+abbreviation "total \<equiv> total_on UNIV"
+
+definition
   single_valued :: "('a * 'b) set => bool" where
   "single_valued r == ALL x y. (x,y):r --> (ALL z. (x,z):r --> y=z)"
 
@@ -268,6 +278,21 @@
 lemma trans_diag [simp]: "trans (diag A)"
 by (fast intro: transI elim: transD)
 
+lemma trans_diff_Id: " trans r \<Longrightarrow> antisym r \<Longrightarrow> trans (r-Id)"
+unfolding antisym_def trans_def by blast
+
+subsection {* Irreflexivity *}
+
+lemma irrefl_diff_Id[simp]: "irrefl(r-Id)"
+by(simp add:irrefl_def)
+
+subsection {* Totality *}
+
+lemma total_on_empty[simp]: "total_on {} r"
+by(simp add:total_on_def)
+
+lemma total_on_diff_Id[simp]: "total_on A (r-Id) = total_on A r"
+by(simp add: total_on_def)
 
 subsection {* Converse *}
 
@@ -330,6 +355,9 @@
 lemma sym_Int_converse: "sym (r \<inter> r^-1)"
 by (unfold sym_def) blast
 
+lemma total_on_converse[simp]: "total_on A (r^-1) = total_on A r"
+by (auto simp: total_on_def)
+
 
 subsection {* Domain *}
 
--- a/src/HOL/Tools/lin_arith.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/Tools/lin_arith.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -814,11 +814,14 @@
       addsimprocs ArithData.nat_cancel_sums_add}) #>
   arith_discrete "nat";
 
-val lin_arith_simproc = Fast_Arith.lin_arith_simproc;
+fun add_arith_facts ss =
+  add_prems (ArithFacts.get (MetaSimplifier.the_context ss)) ss;
+
+val lin_arith_simproc = add_arith_facts #> Fast_Arith.lin_arith_simproc;
 
 val fast_nat_arith_simproc =
   Simplifier.simproc (the_context ()) "fast_nat_arith"
-    ["(m::nat) < n","(m::nat) <= n", "(m::nat) = n"] (K Fast_Arith.lin_arith_simproc);
+    ["(m::nat) < n","(m::nat) <= n", "(m::nat) = n"] (K lin_arith_simproc);
 
 (* Because of fast_nat_arith_simproc, the arithmetic solver is really only
 useful to detect inconsistencies among the premises for subgoals which are
@@ -912,7 +915,8 @@
 fun arith_method src =
   Method.syntax Args.bang_facts src
   #> (fn (prems, ctxt) => Method.METHOD (fn facts =>
-      HEADGOAL (Method.insert_tac (prems @ facts) THEN' arith_tac ctxt)));
+      HEADGOAL (Method.insert_tac (prems @ ArithFacts.get ctxt @ facts)
+      THEN' arith_tac ctxt)));
 
 end;
 
@@ -922,7 +926,8 @@
 val setup =
   init_arith_data #>
   Simplifier.map_ss (fn ss => ss addsimprocs [fast_nat_arith_simproc]
-    addSolver (mk_solver' "lin_arith" Fast_Arith.cut_lin_arith_tac)) #>
+    addSolver (mk_solver' "lin_arith"
+      (add_arith_facts #> Fast_Arith.cut_lin_arith_tac))) #>
   Context.mapping
    (setup_options #>
     Method.add_methods
--- a/src/HOL/ex/Induction_Scheme.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOL/ex/Induction_Scheme.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -15,8 +15,8 @@
   "\<lbrakk>P 0; \<And>n. P n \<Longrightarrow> P (Suc n)\<rbrakk> \<Longrightarrow> P x"
 by induct_scheme (pat_completeness, lexicographic_order)
 
-lemma nat_induct2: (* cf. Nat.thy *)
-  "\<lbrakk> P 0; P (Suc 0); \<And>k. P k ==> P (Suc (Suc k)) \<rbrakk>
+lemma nat_induct2:
+  "\<lbrakk> P 0; P (Suc 0); \<And>k. P k ==> P (Suc k) ==> P (Suc (Suc k)) \<rbrakk>
   \<Longrightarrow> P n"
 by induct_scheme (pat_completeness, lexicographic_order)
 
--- a/src/HOLCF/ex/Stream.thy	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/HOLCF/ex/Stream.thy	Wed Feb 11 13:47:28 2009 +0100
@@ -252,7 +252,9 @@
 lemma stream_finite_ind2:
 "[| P UU; !! x. x ~= UU ==> P (x && UU); !! y z s. [| y ~= UU; z ~= UU; P s |] ==> P (y && z && s )|] ==>
                                  !s. P (stream_take n$s)"
-apply (rule nat_induct2 [of _ n],auto)
+apply (rule nat_less_induct [of _ n],auto)
+apply (case_tac n, auto) 
+apply (case_tac nat, auto) 
 apply (case_tac "s=UU",clarsimp)
 apply (drule stream_exhaust_eq [THEN iffD1],clarsimp)
 apply (case_tac "s=UU",clarsimp)
--- a/src/Pure/General/name_space.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/General/name_space.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -133,10 +133,19 @@
   | SOME ((name :: _, _), _) => (name, false)
   | SOME (([], name' :: _), _) => (hidden name', true));
 
-fun get_accesses (NameSpace (_, tab)) name =
+fun ex_mapsto_in (NameSpace (tab, _)) name xname =
+    (case Symtab.lookup tab xname of
+      SOME ((name'::_, _), _) => name' = name
+    | _ => false);
+
+fun get_accesses' valid_only (ns as (NameSpace (_, tab))) name =
   (case Symtab.lookup tab name of
     NONE => [name]
-  | SOME (xnames, _) => xnames);
+  | SOME (xnames, _) => if valid_only
+                        then filter (ex_mapsto_in ns name) xnames
+                        else xnames);
+
+val get_accesses = get_accesses' true;
 
 fun put_accesses name xnames (NameSpace (tab, xtab)) =
   NameSpace (tab, Symtab.update (name, (xnames, stamp ())) xtab);
@@ -160,7 +169,7 @@
   in
     if ! long_names then name
     else if ! short_names then base name
-    else ext (get_accesses space name)
+    else ext (get_accesses' false space name)
   end;
 
 
@@ -194,7 +203,7 @@
       space
       |> add_name' name name
       |> fold (del_name name) (if fully then names else names inter_string [base name])
-      |> fold (del_name_extra name) (get_accesses space name)
+      |> fold (del_name_extra name) (get_accesses' false space name)
     end;
 
 
--- a/src/Pure/General/seq.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/General/seq.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -19,6 +19,7 @@
   val hd: 'a seq -> 'a
   val tl: 'a seq -> 'a seq
   val chop: int -> 'a seq -> 'a list * 'a seq
+  val take: int -> 'a seq -> 'a seq
   val list_of: 'a seq -> 'a list
   val of_list: 'a list -> 'a seq
   val append: 'a seq -> 'a seq -> 'a seq
@@ -94,6 +95,12 @@
       NONE => ([], xq)
     | SOME (x, xq') => apfst (Basics.cons x) (chop (n - 1) xq'));
 
+(* truncate the sequence after n elements *)
+fun take n s = let
+    fun f 0 _  () = NONE
+      | f n ss () = Option.map (apsnd (make o f (n - 1))) (pull ss);
+  in make (f n s) end;
+
 (*conversion from sequence to list*)
 fun list_of xq =
   (case pull xq of
--- a/src/Pure/IsaMakefile	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/IsaMakefile	Wed Feb 11 13:47:28 2009 +0100
@@ -85,7 +85,7 @@
   pure_setup.ML pure_thy.ML search.ML sign.ML simplifier.ML sorts.ML	\
   subgoal.ML tactic.ML tctical.ML term.ML term_ord.ML term_subst.ML	\
   theory.ML thm.ML type.ML type_infer.ML unify.ML variable.ML		\
-  ../Tools/quickcheck.ML
+  ../Tools/quickcheck.ML ../Tools/auto_solve.ML
 	@./mk
 
 
--- a/src/Pure/Isar/find_theorems.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/Isar/find_theorems.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -7,9 +7,16 @@
 signature FIND_THEOREMS =
 sig
   val limit: int ref
+  val tac_limit: int ref
+
   datatype 'term criterion =
-    Name of string | Intro | Elim | Dest | Simp of 'term | Pattern of 'term
-  val print_theorems: Proof.context -> term option -> int option -> bool ->
+    Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
+    Pattern of 'term
+
+  val find_theorems: Proof.context -> thm option -> bool ->
+    (bool * string criterion) list -> (Facts.ref * thm) list
+
+  val print_theorems: Proof.context -> thm option -> int option -> bool ->
     (bool * string criterion) list -> unit
 end;
 
@@ -19,12 +26,14 @@
 (** search criteria **)
 
 datatype 'term criterion =
-  Name of string | Intro | Elim | Dest | Simp of 'term | Pattern of 'term;
+  Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
+  Pattern of 'term;
 
 fun read_criterion _ (Name name) = Name name
   | read_criterion _ Intro = Intro
   | read_criterion _ Elim = Elim
   | read_criterion _ Dest = Dest
+  | read_criterion _ Solves = Solves
   | read_criterion ctxt (Simp str) = Simp (ProofContext.read_term_pattern ctxt str)
   | read_criterion ctxt (Pattern str) = Pattern (ProofContext.read_term_pattern ctxt str);
 
@@ -37,6 +46,7 @@
     | Intro => Pretty.str (prfx "intro")
     | Elim => Pretty.str (prfx "elim")
     | Dest => Pretty.str (prfx "dest")
+    | Solves => Pretty.str (prfx "solves")
     | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
         Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
     | Pattern pat => Pretty.enclose (prfx " \"") "\""
@@ -108,7 +118,7 @@
   then SOME (0, 0) else NONE;
 
 
-(* filter intro/elim/dest rules *)
+(* filter intro/elim/dest/solves rules *)
 
 fun filter_dest ctxt goal (_, thm) =
   let
@@ -159,6 +169,20 @@
     end
   else NONE
 
+val tac_limit = ref 5;
+
+fun filter_solves ctxt goal = let
+    val baregoal = Logic.get_goal (prop_of goal) 1;
+
+    fun etacn thm i = Seq.take (!tac_limit) o etac thm i;
+    fun try_thm thm = if Thm.no_prems thm then rtac thm 1 goal
+                      else (etacn thm THEN_ALL_NEW
+                             (Goal.norm_hhf_tac THEN'
+                               Method.assumption_tac ctxt)) 1 goal;
+  in
+    fn (_, thm) => if (is_some o Seq.pull o try_thm) thm
+                   then SOME (Thm.nprems_of thm, 0) else NONE
+  end;
 
 (* filter_simp *)
 
@@ -176,26 +200,23 @@
 
 (* filter_pattern *)
 
-fun get_names (_, thm) =
-  fold_aterms (fn Const (c, _) => insert (op =) c | Free (x, _) => insert (op =) x | _ => I)
-    (Thm.full_prop_of thm) [];
-
-fun add_pat_names (t, cs) =
-      case strip_comb t of
-          (Const (c, _), args) => foldl add_pat_names (insert (op =) c cs) args
-        | (Free (c, _), args) => foldl add_pat_names (insert (op =) c cs) args
-        | (Abs (_, _, t), _) => add_pat_names (t, cs)
-        | _ => cs;
-    (* Only include constants and frees that cannot be thrown away.
-       for example, from "(% x y z. y + 1) 7 8 9" give [1].
-       The result [1, 8] would be more accurate, but only a
-       sound approximation is required and variables must
-       be ignored: e.g. "_ 7 8 9". *)
+fun get_names t = (Term.add_const_names t []) union (Term.add_free_names t []);
+fun get_thm_names (_, thm) = get_names (Thm.full_prop_of thm);
+  (* Including all constants and frees is only sound because
+     matching uses higher-order patterns. If full matching
+     were used, then constants that may be subject to
+     beta-reduction after substitution of frees should
+     not be included for LHS set because they could be
+     thrown away by the substituted function.
+     e.g. for (?F 1 2) do not include 1 or 2, if it were
+          possible for ?F to be (% x y. 3)
+     The largest possible set should always be included on
+     the RHS. *)
 
 fun filter_pattern ctxt pat = let
-    val pat_consts = add_pat_names (pat, []);
+    val pat_consts = get_names pat;
 
-    fun check (t, NONE) = check (t, SOME (get_names t))
+    fun check (t, NONE) = check (t, SOME (get_thm_names t))
       | check ((_, thm), c as SOME thm_consts) =
           (if pat_consts subset_string thm_consts
               andalso (Pattern.matches_subterm (ProofContext.theory_of ctxt)
@@ -210,13 +231,21 @@
 fun err_no_goal c =
   error ("Current goal required for " ^ c ^ " search criterion");
 
+val fix_goal = Thm.prop_of;
+val fix_goalo = Option.map fix_goal;
+
 fun filter_crit _ _ (Name name) = apfst (filter_name name)
   | filter_crit _ NONE Intro = err_no_goal "intro"
   | filter_crit _ NONE Elim = err_no_goal "elim"
   | filter_crit _ NONE Dest = err_no_goal "dest"
-  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt goal)
-  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt goal)
-  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt goal)
+  | filter_crit _ NONE Solves = err_no_goal "solves"
+  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt
+                                                  (fix_goal goal))
+  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt 
+                                                  (fix_goal goal))
+  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt
+                                                  (fix_goal goal))
+  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
   | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
   | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
 
@@ -267,12 +296,7 @@
     | ord => ord)
   | ord => ord) <> GREATER;
 
-fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
-      nicer_name (x, i) (y, j)
-  | nicer (Facts.Fact _) (Facts.Named _) = true
-  | nicer (Facts.Named _) (Facts.Fact _) = false;
-
-fun rem_cdups xs =
+fun rem_cdups nicer xs =
   let
     fun rem_c rev_seen [] = rev rev_seen
       | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
@@ -284,10 +308,26 @@
 
 in
 
-fun rem_thm_dups xs =
+fun nicer_shortest ctxt = let
+    val ns = ProofContext.theory_of ctxt
+             |> PureThy.facts_of
+             |> Facts.space_of;
+
+    val len_sort = sort (int_ord o (pairself size));
+    fun shorten s = (case len_sort (NameSpace.get_accesses ns s) of
+                       [] => s
+                     | s'::_ => s');
+
+    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
+          nicer_name (shorten x, i) (shorten y, j)
+      | nicer (Facts.Fact _) (Facts.Named _) = true
+      | nicer (Facts.Named _) (Facts.Fact _) = false;
+  in nicer end;
+
+fun rem_thm_dups nicer xs =
   xs ~~ (1 upto length xs)
   |> sort (TermOrd.fast_term_ord o pairself (Thm.prop_of o #2 o #1))
-  |> rem_cdups
+  |> rem_cdups nicer
   |> sort (int_ord o pairself #2)
   |> map #1;
 
@@ -303,18 +343,28 @@
 
 val limit = ref 40;
 
-fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria =
+fun find_theorems ctxt opt_goal rem_dups raw_criteria =
   let
-    val start = start_timing ();
+    val add_prems = Seq.hd o (TRY (Method.insert_tac
+                                     (Assumption.prems_of ctxt) 1));
+    val opt_goal' = Option.map add_prems opt_goal;
+
     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
-    val filters = map (filter_criterion ctxt opt_goal) criteria;
+    val filters = map (filter_criterion ctxt opt_goal') criteria;
 
     val raw_matches = all_filters filters (all_facts_of ctxt);
 
     val matches =
       if rem_dups
-      then rem_thm_dups raw_matches
+      then rem_thm_dups (nicer_shortest ctxt) raw_matches
       else raw_matches;
+  in matches end;
+
+fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria = let
+    val start = start_timing ();
+
+    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
+    val matches = find_theorems ctxt opt_goal rem_dups raw_criteria;
 
     val len = length matches;
     val lim = the_default (! limit) opt_limit;
@@ -323,21 +373,17 @@
     val end_msg = " in " ^
                   (List.nth (String.tokens Char.isSpace (end_timing start), 3))
                   ^ " secs"
-
-    fun prt_fact (thmref, thm) = Pretty.block
-      [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
-        ProofContext.pretty_thm ctxt thm];
   in
     Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria)
-      :: Pretty.str "" ::
+        :: Pretty.str "" ::
      (if null thms then [Pretty.str ("nothing found" ^ end_msg)]
       else
         [Pretty.str ("found " ^ string_of_int len ^ " theorems" ^
           (if len <= lim then ""
            else " (" ^ string_of_int lim ^ " displayed)")
            ^ end_msg ^ ":"), Pretty.str ""] @
-        map prt_fact thms)
+        map Display.pretty_fact thms)
     |> Pretty.chunks |> Pretty.writeln
-  end;
+  end
 
 end;
--- a/src/Pure/Isar/isar_cmd.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/Isar/isar_cmd.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -412,7 +412,7 @@
   let
     val proof_state = Toplevel.enter_proof_body state;
     val ctxt = Proof.context_of proof_state;
-    val opt_goal = try Proof.get_goal proof_state |> Option.map (Thm.prop_of o #2 o #2);
+    val opt_goal = try Proof.get_goal proof_state |> Option.map (#2 o #2);
   in FindTheorems.print_theorems ctxt opt_goal opt_lim rem_dups spec end);
 
 
--- a/src/Pure/Isar/isar_syn.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/Isar/isar_syn.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -860,6 +860,7 @@
   P.reserved "intro" >> K FindTheorems.Intro ||
   P.reserved "elim" >> K FindTheorems.Elim ||
   P.reserved "dest" >> K FindTheorems.Dest ||
+  P.reserved "solves" >> K FindTheorems.Solves ||
   P.reserved "simp" |-- P.!!! (P.$$$ ":" |-- P.term) >> FindTheorems.Simp ||
   P.term >> FindTheorems.Pattern;
 
--- a/src/Pure/Isar/method.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/Isar/method.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -38,6 +38,7 @@
   val atomize: bool -> method
   val this: method
   val fact: thm list -> Proof.context -> method
+  val assumption_tac: Proof.context -> int -> tactic
   val assumption: Proof.context -> method
   val close: bool -> Proof.context -> method
   val trace: Proof.context -> thm list -> unit
@@ -222,22 +223,22 @@
   if cond (Logic.strip_assums_concl prop)
   then Tactic.rtac rule i else no_tac);
 
-fun assm_tac ctxt =
+in
+
+fun assumption_tac ctxt =
   assume_tac APPEND'
   Goal.assume_rule_tac ctxt APPEND'
   cond_rtac (can Logic.dest_equals) Drule.reflexive_thm APPEND'
   cond_rtac (can Logic.dest_term) Drule.termI;
 
-in
-
 fun assumption ctxt = METHOD (HEADGOAL o
-  (fn [] => assm_tac ctxt
+  (fn [] => assumption_tac ctxt
     | [fact] => solve_tac [fact]
     | _ => K no_tac));
 
 fun close immed ctxt = METHOD (K
   (FILTER Thm.no_prems
-    ((if immed then ALLGOALS (assm_tac ctxt) else all_tac) THEN flexflex_tac)));
+    ((if immed then ALLGOALS (assumption_tac ctxt) else all_tac) THEN flexflex_tac)));
 
 end;
 
--- a/src/Pure/ProofGeneral/ROOT.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/ProofGeneral/ROOT.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -17,7 +17,8 @@
 (use
   |> setmp Proofterm.proofs 1
   |> setmp quick_and_dirty true
-  |> setmp auto_quickcheck true) "preferences.ML";
+  |> setmp auto_quickcheck true
+  |> setmp auto_solve false) "preferences.ML";
 
 use "pgip_parser.ML";
 
--- a/src/Pure/ProofGeneral/preferences.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/ProofGeneral/preferences.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -151,6 +151,12 @@
   nat_pref Quickcheck.auto_time_limit
     "auto-quickcheck-time-limit"
     "Time limit for automatic quickcheck (in milliseconds).",
+  bool_pref AutoSolve.auto
+    "auto-solve"
+    "Try to solve newly declared lemmas with existing theorems.",
+  nat_pref AutoSolve.auto_time_limit
+    "auto-solve-time-limit"
+    "Time limit for seeking automatic solutions (in milliseconds).",
   thm_deps_pref];
 
 val proof_preferences =
--- a/src/Pure/Tools/ROOT.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/Tools/ROOT.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -9,5 +9,6 @@
 (*basic XML support*)
 use "xml_syntax.ML";
 
-(*quickcheck needed here because of pg preferences*)
-use "../../Tools/quickcheck.ML"
+(*quickcheck/autosolve needed here because of pg preferences*)
+use "../../Tools/quickcheck.ML";
+use "../../Tools/auto_solve.ML";
--- a/src/Pure/display.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/display.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -20,6 +20,7 @@
   val pretty_thm_aux: Pretty.pp -> bool -> bool -> term list -> thm -> Pretty.T
   val pretty_thm: thm -> Pretty.T
   val string_of_thm: thm -> string
+  val pretty_fact: Facts.ref * thm -> Pretty.T
   val pretty_thms: thm list -> Pretty.T
   val pretty_thm_sg: theory -> thm -> Pretty.T
   val pretty_thms_sg: theory -> thm list -> Pretty.T
@@ -92,6 +93,10 @@
 
 val string_of_thm = Pretty.string_of o pretty_thm;
 
+fun pretty_fact (thmref, thm) = Pretty.block
+  [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
+   pretty_thm thm];
+
 fun pretty_thms [th] = pretty_thm th
   | pretty_thms ths = Pretty.block (Pretty.fbreaks (map pretty_thm ths));
 
--- a/src/Pure/facts.ML	Tue Feb 10 18:57:02 2009 +0100
+++ b/src/Pure/facts.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -20,6 +20,7 @@
   val selections: string * thm list -> (ref * thm) list
   type T
   val empty: T
+  val space_of: T -> NameSpace.T
   val intern: T -> xstring -> string
   val extern: T -> string -> xstring
   val lookup: Context.generic -> T -> string -> (bool * thm list) option
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Tools/auto_solve.ML	Wed Feb 11 13:47:28 2009 +0100
@@ -0,0 +1,93 @@
+(*  Title:      auto_solve.ML
+    Author:     Timothy Bourke and Gerwin Klein, NICTA
+
+    Check whether a newly stated theorem can be solved directly
+    by an existing theorem. Duplicate lemmas can be detected in
+    this way.
+
+    The implemenation is based in part on Berghofer and
+    Haftmann's Pure/codegen.ML. It relies critically on
+    the FindTheorems solves feature.
+*)
+
+signature AUTO_SOLVE =
+sig
+  val auto : bool ref;
+  val auto_time_limit : int ref;
+
+  val seek_solution : bool -> Proof.state -> Proof.state;
+end;
+
+structure AutoSolve : AUTO_SOLVE =
+struct
+  structure FT = FindTheorems;
+
+  val auto = ref false;
+  val auto_time_limit = ref 5000;
+
+  fun seek_solution int state = let
+      val ctxt = Proof.context_of state;
+
+      fun conj_to_list [] = []
+        | conj_to_list (t::ts) =
+          (Conjunction.dest_conjunction t
+           |> (fn (t1, t2) => conj_to_list (t1::t2::ts)))
+          handle TERM _ => t::conj_to_list ts;
+
+      val crits = [(true, FT.Solves)];
+      fun find g = (NONE, FT.find_theorems ctxt g true crits);
+      fun find_cterm g = (SOME g, FT.find_theorems ctxt
+                                    (SOME (Goal.init g)) true crits);
+
+      fun prt_result (goal, results) = let
+          val msg = case goal of
+                      NONE => "The current goal"
+                    | SOME g => Syntax.string_of_term ctxt (term_of g);
+        in
+          Pretty.big_list (msg ^ " could be solved directly with:")
+                          (map Display.pretty_fact results)
+        end;
+
+      fun seek_against_goal () = let
+          val goal = try Proof.get_goal state
+                     |> Option.map (#2 o #2);
+
+          val goals = goal
+                      |> Option.map (fn g => cprem_of g 1)
+                      |> the_list
+                      |> conj_to_list;
+
+          val rs = if length goals = 1
+                   then [find goal]
+                   else map find_cterm goals;
+          val frs = filter_out (null o snd) rs;
+
+        in if null frs then NONE else SOME frs end;
+
+      fun go () = let
+          val res = TimeLimit.timeLimit
+                      (Time.fromMilliseconds (!auto_time_limit))
+                      (try seek_against_goal) ();
+        in
+          case Option.join res of
+            NONE => state
+          | SOME results => (Proof.goal_message
+                              (fn () => Pretty.chunks [Pretty.str "",
+                                Pretty.markup Markup.hilite
+                                (Library.separate (Pretty.brk 0)
+                                                  (map prt_result results))])
+                                state)
+        end handle TimeLimit.TimeOut => (warning "AutoSolve: timeout."; state);
+    in
+      if int andalso !auto andalso not (!Toplevel.quiet)
+      then go ()
+      else state
+    end;
+    
+end;
+
+val _ = Context.>> (Specification.add_theorem_hook AutoSolve.seek_solution);
+
+val auto_solve = AutoSolve.auto;
+val auto_solve_time_limit = AutoSolve.auto_time_limit;
+