src/HOL/Library/Sum_Of_Squares/sum_of_squares.ML
changeset 32332 bc5cec7b2be6
parent 32265 d50f0cb67578
child 32645 1cc5b24f5a01
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Library/Sum_Of_Squares/sum_of_squares.ML	Thu Aug 06 19:51:59 2009 +0200
     1.3 @@ -0,0 +1,1512 @@
     1.4 +(* Title:      sum_of_squares.ML
     1.5 +   Authors:    Amine Chaieb, University of Cambridge
     1.6 +               Philipp Meyer, TU Muenchen
     1.7 +
     1.8 +A tactic for proving nonlinear inequalities
     1.9 +*)
    1.10 +
    1.11 +signature SOS =
    1.12 +sig
    1.13 +
    1.14 +  val sos_tac : (string -> string) -> Proof.context -> int -> Tactical.tactic
    1.15 +
    1.16 +  val debugging : bool ref;
    1.17 +  
    1.18 +  exception Failure of string;
    1.19 +end
    1.20 +
    1.21 +structure Sos : SOS = 
    1.22 +struct
    1.23 +
    1.24 +val rat_0 = Rat.zero;
    1.25 +val rat_1 = Rat.one;
    1.26 +val rat_2 = Rat.two;
    1.27 +val rat_10 = Rat.rat_of_int 10;
    1.28 +val rat_1_2 = rat_1 // rat_2;
    1.29 +val max = curry IntInf.max;
    1.30 +val min = curry IntInf.min;
    1.31 +
    1.32 +val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
    1.33 +val numerator_rat = Rat.quotient_of_rat #> fst #> Rat.rat_of_int;
    1.34 +fun int_of_rat a = 
    1.35 +    case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
    1.36 +fun lcm_rat x y = Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
    1.37 +
    1.38 +fun rat_pow r i = 
    1.39 + let fun pow r i = 
    1.40 +   if i = 0 then rat_1 else 
    1.41 +   let val d = pow r (i div 2)
    1.42 +   in d */ d */ (if i mod 2 = 0 then rat_1 else r)
    1.43 +   end
    1.44 + in if i < 0 then pow (Rat.inv r) (~ i) else pow r i end;
    1.45 +
    1.46 +fun round_rat r = 
    1.47 + let val (a,b) = Rat.quotient_of_rat (Rat.abs r)
    1.48 +     val d = a div b
    1.49 +     val s = if r </ rat_0 then (Rat.neg o Rat.rat_of_int) else Rat.rat_of_int
    1.50 +     val x2 = 2 * (a - (b * d))
    1.51 + in s (if x2 >= b then d + 1 else d) end
    1.52 +
    1.53 +val abs_rat = Rat.abs;
    1.54 +val pow2 = rat_pow rat_2;
    1.55 +val pow10 = rat_pow rat_10;
    1.56 +
    1.57 +val debugging = ref false;
    1.58 +
    1.59 +exception Sanity;
    1.60 +
    1.61 +exception Unsolvable;
    1.62 +
    1.63 +exception Failure of string;
    1.64 +
    1.65 +(* Turn a rational into a decimal string with d sig digits.                  *)
    1.66 +
    1.67 +local
    1.68 +fun normalize y =
    1.69 +  if abs_rat y </ (rat_1 // rat_10) then normalize (rat_10 */ y) - 1
    1.70 +  else if abs_rat y >=/ rat_1 then normalize (y // rat_10) + 1
    1.71 +  else 0 
    1.72 + in
    1.73 +fun decimalize d x =
    1.74 +  if x =/ rat_0 then "0.0" else
    1.75 +  let 
    1.76 +   val y = Rat.abs x
    1.77 +   val e = normalize y
    1.78 +   val z = pow10(~ e) */ y +/ rat_1
    1.79 +   val k = int_of_rat (round_rat(pow10 d */ z))
    1.80 +  in (if x </ rat_0 then "-0." else "0.") ^
    1.81 +     implode(tl(explode(string_of_int k))) ^
    1.82 +     (if e = 0 then "" else "e"^string_of_int e)
    1.83 +  end
    1.84 +end;
    1.85 +
    1.86 +(* Iterations over numbers, and lists indexed by numbers.                    *)
    1.87 +
    1.88 +fun itern k l f a =
    1.89 +  case l of
    1.90 +    [] => a
    1.91 +  | h::t => itern (k + 1) t f (f h k a);
    1.92 +
    1.93 +fun iter (m,n) f a =
    1.94 +  if n < m then a
    1.95 +  else iter (m+1,n) f (f m a);
    1.96 +
    1.97 +(* The main types.                                                           *)
    1.98 +
    1.99 +fun strict_ord ord (x,y) = case ord (x,y) of LESS => LESS | _ => GREATER
   1.100 +
   1.101 +structure Intpairfunc = FuncFun(type key = int*int val ord = prod_ord int_ord int_ord);
   1.102 +
   1.103 +type vector = int* Rat.rat Intfunc.T;
   1.104 +
   1.105 +type matrix = (int*int)*(Rat.rat Intpairfunc.T);
   1.106 +
   1.107 +type monomial = int Ctermfunc.T;
   1.108 +
   1.109 +val cterm_ord = (fn (s,t) => TermOrd.fast_term_ord(term_of s, term_of t))
   1.110 + fun monomial_ord (m1,m2) = list_ord (prod_ord cterm_ord int_ord) (Ctermfunc.graph m1, Ctermfunc.graph m2)
   1.111 +structure Monomialfunc = FuncFun(type key = monomial val ord = monomial_ord)
   1.112 +
   1.113 +type poly = Rat.rat Monomialfunc.T;
   1.114 +
   1.115 + fun iszero (k,r) = r =/ rat_0;
   1.116 +
   1.117 +fun fold_rev2 f l1 l2 b =
   1.118 +  case (l1,l2) of
   1.119 +    ([],[]) => b
   1.120 +  | (h1::t1,h2::t2) => f h1 h2 (fold_rev2 f t1 t2 b)
   1.121 +  | _ => error "fold_rev2";
   1.122 + 
   1.123 +(* Vectors. Conventionally indexed 1..n.                                     *)
   1.124 +
   1.125 +fun vector_0 n = (n,Intfunc.undefined):vector;
   1.126 +
   1.127 +fun dim (v:vector) = fst v;
   1.128 +
   1.129 +fun vector_const c n =
   1.130 +  if c =/ rat_0 then vector_0 n
   1.131 +  else (n,fold_rev (fn k => Intfunc.update (k,c)) (1 upto n) Intfunc.undefined) :vector;
   1.132 +
   1.133 +val vector_1 = vector_const rat_1;
   1.134 +
   1.135 +fun vector_cmul c (v:vector) =
   1.136 + let val n = dim v 
   1.137 + in if c =/ rat_0 then vector_0 n
   1.138 +    else (n,Intfunc.mapf (fn x => c */ x) (snd v))
   1.139 + end;
   1.140 +
   1.141 +fun vector_neg (v:vector) = (fst v,Intfunc.mapf Rat.neg (snd v)) :vector;
   1.142 +
   1.143 +fun vector_add (v1:vector) (v2:vector) =
   1.144 + let val m = dim v1  
   1.145 +     val n = dim v2 
   1.146 + in if m <> n then error "vector_add: incompatible dimensions"
   1.147 +    else (n,Intfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd v1) (snd v2)) :vector 
   1.148 + end;
   1.149 +
   1.150 +fun vector_sub v1 v2 = vector_add v1 (vector_neg v2);
   1.151 +
   1.152 +fun vector_dot (v1:vector) (v2:vector) =
   1.153 + let val m = dim v1 
   1.154 +     val n = dim v2 
   1.155 + in if m <> n then error "vector_dot: incompatible dimensions" 
   1.156 +    else Intfunc.fold (fn (i,x) => fn a => x +/ a) 
   1.157 +        (Intfunc.combine (curry op */) (fn x => x =/ rat_0) (snd v1) (snd v2)) rat_0
   1.158 + end;
   1.159 +
   1.160 +fun vector_of_list l =
   1.161 + let val n = length l 
   1.162 + in (n,fold_rev2 (curry Intfunc.update) (1 upto n) l Intfunc.undefined) :vector
   1.163 + end;
   1.164 +
   1.165 +(* Matrices; again rows and columns indexed from 1.                          *)
   1.166 +
   1.167 +fun matrix_0 (m,n) = ((m,n),Intpairfunc.undefined):matrix;
   1.168 +
   1.169 +fun dimensions (m:matrix) = fst m;
   1.170 +
   1.171 +fun matrix_const c (mn as (m,n)) =
   1.172 +  if m <> n then error "matrix_const: needs to be square"
   1.173 +  else if c =/ rat_0 then matrix_0 mn
   1.174 +  else (mn,fold_rev (fn k => Intpairfunc.update ((k,k), c)) (1 upto n) Intpairfunc.undefined) :matrix;;
   1.175 +
   1.176 +val matrix_1 = matrix_const rat_1;
   1.177 +
   1.178 +fun matrix_cmul c (m:matrix) =
   1.179 + let val (i,j) = dimensions m 
   1.180 + in if c =/ rat_0 then matrix_0 (i,j)
   1.181 +    else ((i,j),Intpairfunc.mapf (fn x => c */ x) (snd m))
   1.182 + end;
   1.183 +
   1.184 +fun matrix_neg (m:matrix) = 
   1.185 +  (dimensions m, Intpairfunc.mapf Rat.neg (snd m)) :matrix;
   1.186 +
   1.187 +fun matrix_add (m1:matrix) (m2:matrix) =
   1.188 + let val d1 = dimensions m1 
   1.189 +     val d2 = dimensions m2 
   1.190 + in if d1 <> d2 
   1.191 +     then error "matrix_add: incompatible dimensions"
   1.192 +    else (d1,Intpairfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd m1) (snd m2)) :matrix
   1.193 + end;;
   1.194 +
   1.195 +fun matrix_sub m1 m2 = matrix_add m1 (matrix_neg m2);
   1.196 +
   1.197 +fun row k (m:matrix) =
   1.198 + let val (i,j) = dimensions m 
   1.199 + in (j,
   1.200 +   Intpairfunc.fold (fn ((i,j), c) => fn a => if i = k then Intfunc.update (j,c) a else a) (snd m) Intfunc.undefined ) : vector
   1.201 + end;
   1.202 +
   1.203 +fun column k (m:matrix) =
   1.204 +  let val (i,j) = dimensions m 
   1.205 +  in (i,
   1.206 +   Intpairfunc.fold (fn ((i,j), c) => fn a => if j = k then Intfunc.update (i,c) a else a) (snd m)  Intfunc.undefined)
   1.207 +   : vector
   1.208 + end;
   1.209 +
   1.210 +fun transp (m:matrix) =
   1.211 +  let val (i,j) = dimensions m 
   1.212 +  in
   1.213 +  ((j,i),Intpairfunc.fold (fn ((i,j), c) => fn a => Intpairfunc.update ((j,i), c) a) (snd m) Intpairfunc.undefined) :matrix
   1.214 + end;
   1.215 +
   1.216 +fun diagonal (v:vector) =
   1.217 + let val n = dim v 
   1.218 + in ((n,n),Intfunc.fold (fn (i, c) => fn a => Intpairfunc.update ((i,i), c) a) (snd v) Intpairfunc.undefined) : matrix
   1.219 + end;
   1.220 +
   1.221 +fun matrix_of_list l =
   1.222 + let val m = length l 
   1.223 + in if m = 0 then matrix_0 (0,0) else
   1.224 +   let val n = length (hd l) 
   1.225 +   in ((m,n),itern 1 l (fn v => fn i => itern 1 v (fn c => fn j => Intpairfunc.update ((i,j), c))) Intpairfunc.undefined)
   1.226 +   end
   1.227 + end;
   1.228 +
   1.229 +(* Monomials.                                                                *)
   1.230 +
   1.231 +fun monomial_eval assig (m:monomial) =
   1.232 +  Ctermfunc.fold (fn (x, k) => fn a => a */ rat_pow (Ctermfunc.apply assig x) k)
   1.233 +        m rat_1;
   1.234 +val monomial_1 = (Ctermfunc.undefined:monomial);
   1.235 +
   1.236 +fun monomial_var x = Ctermfunc.onefunc (x, 1) :monomial;
   1.237 +
   1.238 +val (monomial_mul:monomial->monomial->monomial) =
   1.239 +  Ctermfunc.combine (curry op +) (K false);
   1.240 +
   1.241 +fun monomial_pow (m:monomial) k =
   1.242 +  if k = 0 then monomial_1
   1.243 +  else Ctermfunc.mapf (fn x => k * x) m;
   1.244 +
   1.245 +fun monomial_divides (m1:monomial) (m2:monomial) =
   1.246 +  Ctermfunc.fold (fn (x, k) => fn a => Ctermfunc.tryapplyd m2 x 0 >= k andalso a) m1 true;;
   1.247 +
   1.248 +fun monomial_div (m1:monomial) (m2:monomial) =
   1.249 + let val m = Ctermfunc.combine (curry op +) 
   1.250 +   (fn x => x = 0) m1 (Ctermfunc.mapf (fn x => ~ x) m2) 
   1.251 + in if Ctermfunc.fold (fn (x, k) => fn a => k >= 0 andalso a) m true then m
   1.252 +  else error "monomial_div: non-divisible"
   1.253 + end;
   1.254 +
   1.255 +fun monomial_degree x (m:monomial) = 
   1.256 +  Ctermfunc.tryapplyd m x 0;;
   1.257 +
   1.258 +fun monomial_lcm (m1:monomial) (m2:monomial) =
   1.259 +  fold_rev (fn x => Ctermfunc.update (x, max (monomial_degree x m1) (monomial_degree x m2)))
   1.260 +          (gen_union (is_equal o  cterm_ord) (Ctermfunc.dom m1, Ctermfunc.dom m2)) (Ctermfunc.undefined :monomial);
   1.261 +
   1.262 +fun monomial_multidegree (m:monomial) = 
   1.263 + Ctermfunc.fold (fn (x, k) => fn a => k + a) m 0;;
   1.264 +
   1.265 +fun monomial_variables m = Ctermfunc.dom m;;
   1.266 +
   1.267 +(* Polynomials.                                                              *)
   1.268 +
   1.269 +fun eval assig (p:poly) =
   1.270 +  Monomialfunc.fold (fn (m, c) => fn a => a +/ c */ monomial_eval assig m) p rat_0;
   1.271 +
   1.272 +val poly_0 = (Monomialfunc.undefined:poly);
   1.273 +
   1.274 +fun poly_isconst (p:poly) = 
   1.275 +  Monomialfunc.fold (fn (m, c) => fn a => Ctermfunc.is_undefined m andalso a) p true;
   1.276 +
   1.277 +fun poly_var x = Monomialfunc.onefunc (monomial_var x,rat_1) :poly;
   1.278 +
   1.279 +fun poly_const c =
   1.280 +  if c =/ rat_0 then poly_0 else Monomialfunc.onefunc(monomial_1, c);
   1.281 +
   1.282 +fun poly_cmul c (p:poly) =
   1.283 +  if c =/ rat_0 then poly_0
   1.284 +  else Monomialfunc.mapf (fn x => c */ x) p;
   1.285 +
   1.286 +fun poly_neg (p:poly) = (Monomialfunc.mapf Rat.neg p :poly);;
   1.287 +
   1.288 +fun poly_add (p1:poly) (p2:poly) =
   1.289 +  (Monomialfunc.combine (curry op +/) (fn x => x =/ rat_0) p1 p2 :poly);
   1.290 +
   1.291 +fun poly_sub p1 p2 = poly_add p1 (poly_neg p2);
   1.292 +
   1.293 +fun poly_cmmul (c,m) (p:poly) =
   1.294 + if c =/ rat_0 then poly_0
   1.295 + else if Ctermfunc.is_undefined m 
   1.296 +      then Monomialfunc.mapf (fn d => c */ d) p
   1.297 +      else Monomialfunc.fold (fn (m', d) => fn a => (Monomialfunc.update (monomial_mul m m', c */ d) a)) p poly_0;
   1.298 +
   1.299 +fun poly_mul (p1:poly) (p2:poly) =
   1.300 +  Monomialfunc.fold (fn (m, c) => fn a => poly_add (poly_cmmul (c,m) p2) a) p1 poly_0;
   1.301 +
   1.302 +fun poly_div (p1:poly) (p2:poly) =
   1.303 + if not(poly_isconst p2) 
   1.304 + then error "poly_div: non-constant" else
   1.305 + let val c = eval Ctermfunc.undefined p2 
   1.306 + in if c =/ rat_0 then error "poly_div: division by zero"
   1.307 +    else poly_cmul (Rat.inv c) p1
   1.308 + end;
   1.309 +
   1.310 +fun poly_square p = poly_mul p p;
   1.311 +
   1.312 +fun poly_pow p k =
   1.313 + if k = 0 then poly_const rat_1
   1.314 + else if k = 1 then p
   1.315 + else let val q = poly_square(poly_pow p (k div 2)) in
   1.316 +      if k mod 2 = 1 then poly_mul p q else q end;
   1.317 +
   1.318 +fun poly_exp p1 p2 =
   1.319 +  if not(poly_isconst p2) 
   1.320 +  then error "poly_exp: not a constant" 
   1.321 +  else poly_pow p1 (int_of_rat (eval Ctermfunc.undefined p2));
   1.322 +
   1.323 +fun degree x (p:poly) = 
   1.324 + Monomialfunc.fold (fn (m,c) => fn a => max (monomial_degree x m) a) p 0;
   1.325 +
   1.326 +fun multidegree (p:poly) =
   1.327 +  Monomialfunc.fold (fn (m, c) => fn a => max (monomial_multidegree m) a) p 0;
   1.328 +
   1.329 +fun poly_variables (p:poly) =
   1.330 +  sort cterm_ord (Monomialfunc.fold_rev (fn (m, c) => curry (gen_union (is_equal o  cterm_ord)) (monomial_variables m)) p []);;
   1.331 +
   1.332 +(* Order monomials for human presentation.                                   *)
   1.333 +
   1.334 +fun cterm_ord (t,t') = TermOrd.fast_term_ord (term_of t, term_of t');
   1.335 +
   1.336 +val humanorder_varpow = prod_ord cterm_ord (rev_order o int_ord);
   1.337 +
   1.338 +local
   1.339 + fun ord (l1,l2) = case (l1,l2) of
   1.340 +  (_,[]) => LESS 
   1.341 + | ([],_) => GREATER
   1.342 + | (h1::t1,h2::t2) => 
   1.343 +   (case humanorder_varpow (h1, h2) of 
   1.344 +     LESS => LESS
   1.345 +   | EQUAL => ord (t1,t2)
   1.346 +   | GREATER => GREATER)
   1.347 +in fun humanorder_monomial m1 m2 = 
   1.348 + ord (sort humanorder_varpow (Ctermfunc.graph m1),
   1.349 +  sort humanorder_varpow (Ctermfunc.graph m2))
   1.350 +end;
   1.351 +
   1.352 +fun fold1 f l =  case l of
   1.353 +   []     => error "fold1"
   1.354 + | [x]    => x
   1.355 + | (h::t) => f h (fold1 f t);
   1.356 +
   1.357 +(* Conversions to strings.                                                   *)
   1.358 +
   1.359 +fun string_of_vector min_size max_size (v:vector) =
   1.360 + let val n_raw = dim v 
   1.361 + in if n_raw = 0 then "[]" else
   1.362 +  let 
   1.363 +   val n = max min_size (min n_raw max_size) 
   1.364 +   val xs = map (Rat.string_of_rat o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n) 
   1.365 +  in "[" ^ fold1 (fn s => fn t => s ^ ", " ^ t) xs ^
   1.366 +  (if n_raw > max_size then ", ...]" else "]")
   1.367 +  end
   1.368 + end;
   1.369 +
   1.370 +fun string_of_matrix max_size (m:matrix) =
   1.371 + let 
   1.372 +  val (i_raw,j_raw) = dimensions m
   1.373 +  val i = min max_size i_raw 
   1.374 +  val j = min max_size j_raw
   1.375 +  val rstr = map (fn k => string_of_vector j j (row k m)) (1 upto i) 
   1.376 + in "["^ fold1 (fn s => fn t => s^";\n "^t) rstr ^
   1.377 +  (if j > max_size then "\n ...]" else "]")
   1.378 + end;
   1.379 +
   1.380 +fun string_of_term t = 
   1.381 + case t of
   1.382 +   a$b => "("^(string_of_term a)^" "^(string_of_term b)^")"
   1.383 + | Abs x => 
   1.384 +    let val (xn, b) = Term.dest_abs x
   1.385 +    in "(\\"^xn^"."^(string_of_term b)^")"
   1.386 +    end
   1.387 + | Const(s,_) => s
   1.388 + | Free (s,_) => s
   1.389 + | Var((s,_),_) => s
   1.390 + | _ => error "string_of_term";
   1.391 +
   1.392 +val string_of_cterm = string_of_term o term_of;
   1.393 +
   1.394 +fun string_of_varpow x k =
   1.395 +  if k = 1 then string_of_cterm x 
   1.396 +  else string_of_cterm x^"^"^string_of_int k;
   1.397 +
   1.398 +fun string_of_monomial m =
   1.399 + if Ctermfunc.is_undefined m then "1" else
   1.400 + let val vps = fold_rev (fn (x,k) => fn a => string_of_varpow x k :: a)
   1.401 +  (sort humanorder_varpow (Ctermfunc.graph m)) [] 
   1.402 + in fold1 (fn s => fn t => s^"*"^t) vps
   1.403 + end;
   1.404 +
   1.405 +fun string_of_cmonomial (c,m) =
   1.406 + if Ctermfunc.is_undefined m then Rat.string_of_rat c
   1.407 + else if c =/ rat_1 then string_of_monomial m
   1.408 + else Rat.string_of_rat c ^ "*" ^ string_of_monomial m;;
   1.409 +
   1.410 +fun string_of_poly (p:poly) =
   1.411 + if Monomialfunc.is_undefined p then "<<0>>" else
   1.412 + let 
   1.413 +  val cms = sort (fn ((m1,_),(m2,_)) => humanorder_monomial m1  m2) (Monomialfunc.graph p)
   1.414 +  val s = fold (fn (m,c) => fn a =>
   1.415 +             if c </ rat_0 then a ^ " - " ^ string_of_cmonomial(Rat.neg c,m)
   1.416 +             else a ^ " + " ^ string_of_cmonomial(c,m))
   1.417 +          cms ""
   1.418 +  val s1 = String.substring (s, 0, 3)
   1.419 +  val s2 = String.substring (s, 3, String.size s - 3) 
   1.420 + in "<<" ^(if s1 = " + " then s2 else "-"^s2)^">>"
   1.421 + end;
   1.422 +
   1.423 +(* Conversion from HOL term.                                                 *)
   1.424 +
   1.425 +local
   1.426 + val neg_tm = @{cterm "uminus :: real => _"}
   1.427 + val add_tm = @{cterm "op + :: real => _"}
   1.428 + val sub_tm = @{cterm "op - :: real => _"}
   1.429 + val mul_tm = @{cterm "op * :: real => _"}
   1.430 + val inv_tm = @{cterm "inverse :: real => _"}
   1.431 + val div_tm = @{cterm "op / :: real => _"}
   1.432 + val pow_tm = @{cterm "op ^ :: real => _"}
   1.433 + val zero_tm = @{cterm "0:: real"}
   1.434 + val is_numeral = can (HOLogic.dest_number o term_of)
   1.435 + fun is_comb t = case t of _$_ => true | _ => false
   1.436 + fun poly_of_term tm =
   1.437 +  if tm aconvc zero_tm then poly_0
   1.438 +  else if RealArith.is_ratconst tm 
   1.439 +       then poly_const(RealArith.dest_ratconst tm)
   1.440 +  else 
   1.441 +  (let val (lop,r) = Thm.dest_comb tm
   1.442 +   in if lop aconvc neg_tm then poly_neg(poly_of_term r)
   1.443 +      else if lop aconvc inv_tm then
   1.444 +       let val p = poly_of_term r 
   1.445 +       in if poly_isconst p 
   1.446 +          then poly_const(Rat.inv (eval Ctermfunc.undefined p))
   1.447 +          else error "poly_of_term: inverse of non-constant polyomial"
   1.448 +       end
   1.449 +   else (let val (opr,l) = Thm.dest_comb lop
   1.450 +         in 
   1.451 +          if opr aconvc pow_tm andalso is_numeral r 
   1.452 +          then poly_pow (poly_of_term l) ((snd o HOLogic.dest_number o term_of) r)
   1.453 +          else if opr aconvc add_tm 
   1.454 +           then poly_add (poly_of_term l) (poly_of_term r)
   1.455 +          else if opr aconvc sub_tm 
   1.456 +           then poly_sub (poly_of_term l) (poly_of_term r)
   1.457 +          else if opr aconvc mul_tm 
   1.458 +           then poly_mul (poly_of_term l) (poly_of_term r)
   1.459 +          else if opr aconvc div_tm 
   1.460 +           then let 
   1.461 +                  val p = poly_of_term l 
   1.462 +                  val q = poly_of_term r 
   1.463 +                in if poly_isconst q then poly_cmul (Rat.inv (eval Ctermfunc.undefined q)) p
   1.464 +                   else error "poly_of_term: division by non-constant polynomial"
   1.465 +                end
   1.466 +          else poly_var tm
   1.467 + 
   1.468 +         end
   1.469 +         handle CTERM ("dest_comb",_) => poly_var tm)
   1.470 +   end
   1.471 +   handle CTERM ("dest_comb",_) => poly_var tm)
   1.472 +in
   1.473 +val poly_of_term = fn tm =>
   1.474 + if type_of (term_of tm) = @{typ real} then poly_of_term tm
   1.475 + else error "poly_of_term: term does not have real type"
   1.476 +end;
   1.477 +
   1.478 +(* String of vector (just a list of space-separated numbers).                *)
   1.479 +
   1.480 +fun sdpa_of_vector (v:vector) =
   1.481 + let 
   1.482 +  val n = dim v
   1.483 +  val strs = map (decimalize 20 o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n) 
   1.484 + in fold1 (fn x => fn y => x ^ " " ^ y) strs ^ "\n"
   1.485 + end;
   1.486 +
   1.487 +fun increasing f ord (x,y) = ord (f x, f y);
   1.488 +fun triple_int_ord ((a,b,c),(a',b',c')) = 
   1.489 + prod_ord int_ord (prod_ord int_ord int_ord) 
   1.490 +    ((a,(b,c)),(a',(b',c')));
   1.491 +structure Inttriplefunc = FuncFun(type key = int*int*int val ord = triple_int_ord);
   1.492 +
   1.493 +(* String for block diagonal matrix numbered k.                              *)
   1.494 +
   1.495 +fun sdpa_of_blockdiagonal k m =
   1.496 + let 
   1.497 +  val pfx = string_of_int k ^" "
   1.498 +  val ents =
   1.499 +    Inttriplefunc.fold (fn ((b,i,j), c) => fn a => if i > j then a else ((b,i,j),c)::a) m []
   1.500 +  val entss = sort (increasing fst triple_int_ord ) ents
   1.501 + in  fold_rev (fn ((b,i,j),c) => fn a =>
   1.502 +     pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
   1.503 +     " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
   1.504 + end;
   1.505 +
   1.506 +(* String for a matrix numbered k, in SDPA sparse format.                    *)
   1.507 +
   1.508 +fun sdpa_of_matrix k (m:matrix) =
   1.509 + let 
   1.510 +  val pfx = string_of_int k ^ " 1 "
   1.511 +  val ms = Intpairfunc.fold (fn ((i,j), c) => fn  a => if i > j then a else ((i,j),c)::a) (snd m) [] 
   1.512 +  val mss = sort (increasing fst (prod_ord int_ord int_ord)) ms 
   1.513 + in fold_rev (fn ((i,j),c) => fn a =>
   1.514 +     pfx ^ string_of_int i ^ " " ^ string_of_int j ^
   1.515 +     " " ^ decimalize 20 c ^ "\n" ^ a) mss ""
   1.516 + end;;
   1.517 +
   1.518 +(* ------------------------------------------------------------------------- *)
   1.519 +(* String in SDPA sparse format for standard SDP problem:                    *)
   1.520 +(*                                                                           *)
   1.521 +(*    X = v_1 * [M_1] + ... + v_m * [M_m] - [M_0] must be PSD                *)
   1.522 +(*    Minimize obj_1 * v_1 + ... obj_m * v_m                                 *)
   1.523 +(* ------------------------------------------------------------------------- *)
   1.524 +
   1.525 +fun sdpa_of_problem obj mats =
   1.526 + let 
   1.527 +  val m = length mats - 1
   1.528 +  val (n,_) = dimensions (hd mats) 
   1.529 + in
   1.530 +  string_of_int m ^ "\n" ^
   1.531 +  "1\n" ^
   1.532 +  string_of_int n ^ "\n" ^
   1.533 +  sdpa_of_vector obj ^
   1.534 +  fold_rev2 (fn k => fn m => fn a => sdpa_of_matrix (k - 1) m ^ a) (1 upto length mats) mats ""
   1.535 + end;
   1.536 +
   1.537 +fun index_char str chr pos =
   1.538 +  if pos >= String.size str then ~1
   1.539 +  else if String.sub(str,pos) = chr then pos
   1.540 +  else index_char str chr (pos + 1);
   1.541 +fun rat_of_quotient (a,b) = if b = 0 then rat_0 else Rat.rat_of_quotient (a,b);
   1.542 +fun rat_of_string s = 
   1.543 + let val n = index_char s #"/" 0 in
   1.544 +  if n = ~1 then s |> IntInf.fromString |> valOf |> Rat.rat_of_int
   1.545 +  else 
   1.546 +   let val SOME numer = IntInf.fromString(String.substring(s,0,n))
   1.547 +       val SOME den = IntInf.fromString (String.substring(s,n+1,String.size s - n - 1))
   1.548 +   in rat_of_quotient(numer, den)
   1.549 +   end
   1.550 + end;
   1.551 +
   1.552 +fun isspace x = x = " " ;
   1.553 +fun isnum x = x mem_string ["0","1","2","3","4","5","6","7","8","9"]
   1.554 +
   1.555 +(* More parser basics.                                                       *)
   1.556 +
   1.557 +local
   1.558 + open Scan
   1.559 +in 
   1.560 + val word = this_string
   1.561 + fun token s =
   1.562 +  repeat ($$ " ") |-- word s --| repeat ($$ " ")
   1.563 + val numeral = one isnum
   1.564 + val decimalint = bulk numeral >> (rat_of_string o implode)
   1.565 + val decimalfrac = bulk numeral
   1.566 +    >> (fn s => rat_of_string(implode s) // pow10 (length s))
   1.567 + val decimalsig =
   1.568 +    decimalint -- option (Scan.$$ "." |-- decimalfrac)
   1.569 +    >> (fn (h,NONE) => h | (h,SOME x) => h +/ x)
   1.570 + fun signed prs =
   1.571 +       $$ "-" |-- prs >> Rat.neg 
   1.572 +    || $$ "+" |-- prs
   1.573 +    || prs;
   1.574 +
   1.575 +fun emptyin def xs = if null xs then (def,xs) else Scan.fail xs
   1.576 +
   1.577 + val exponent = ($$ "e" || $$ "E") |-- signed decimalint;
   1.578 +
   1.579 + val decimal = signed decimalsig -- (emptyin rat_0|| exponent)
   1.580 +    >> (fn (h, x) => h */ pow10 (int_of_rat x));
   1.581 +end;
   1.582 +
   1.583 + fun mkparser p s =
   1.584 +  let val (x,rst) = p (explode s) 
   1.585 +  in if null rst then x 
   1.586 +     else error "mkparser: unparsed input"
   1.587 +  end;;
   1.588 +
   1.589 +(* Parse back csdp output.                                                      *)
   1.590 +
   1.591 + fun ignore inp = ((),[])
   1.592 + fun csdpoutput inp =  ((decimal -- Scan.bulk (Scan.$$ " " |-- Scan.option decimal) >> (fn (h,to) => map_filter I ((SOME h)::to))) --| ignore >> vector_of_list) inp
   1.593 + val parse_csdpoutput = mkparser csdpoutput
   1.594 +
   1.595 +(* Run prover on a problem in linear form.                       *)
   1.596 +
   1.597 +fun run_problem prover obj mats =
   1.598 +  parse_csdpoutput (prover (sdpa_of_problem obj mats))
   1.599 +
   1.600 +(* Try some apparently sensible scaling first. Note that this is purely to   *)
   1.601 +(* get a cleaner translation to floating-point, and doesn't affect any of    *)
   1.602 +(* the results, in principle. In practice it seems a lot better when there   *)
   1.603 +(* are extreme numbers in the original problem.                              *)
   1.604 +
   1.605 +  (* Version for (int*int) keys *)
   1.606 +local
   1.607 +  fun max_rat x y = if x </ y then y else x
   1.608 +  fun common_denominator fld amat acc =
   1.609 +      fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
   1.610 +  fun maximal_element fld amat acc =
   1.611 +    fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc 
   1.612 +fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
   1.613 +                     in Real.fromLargeInt a / Real.fromLargeInt b end;
   1.614 +in
   1.615 +
   1.616 +fun pi_scale_then solver (obj:vector)  mats =
   1.617 + let 
   1.618 +  val cd1 = fold_rev (common_denominator Intpairfunc.fold) mats (rat_1)
   1.619 +  val cd2 = common_denominator Intfunc.fold (snd obj)  (rat_1) 
   1.620 +  val mats' = map (Intpairfunc.mapf (fn x => cd1 */ x)) mats
   1.621 +  val obj' = vector_cmul cd2 obj
   1.622 +  val max1 = fold_rev (maximal_element Intpairfunc.fold) mats' (rat_0)
   1.623 +  val max2 = maximal_element Intfunc.fold (snd obj') (rat_0) 
   1.624 +  val scal1 = pow2 (20 - trunc(Math.ln (float_of_rat max1) / Math.ln 2.0))
   1.625 +  val scal2 = pow2 (20 - trunc(Math.ln (float_of_rat max2) / Math.ln 2.0)) 
   1.626 +  val mats'' = map (Intpairfunc.mapf (fn x => x */ scal1)) mats'
   1.627 +  val obj'' = vector_cmul scal2 obj' 
   1.628 + in solver obj'' mats''
   1.629 +  end
   1.630 +end;
   1.631 +
   1.632 +(* Try some apparently sensible scaling first. Note that this is purely to   *)
   1.633 +(* get a cleaner translation to floating-point, and doesn't affect any of    *)
   1.634 +(* the results, in principle. In practice it seems a lot better when there   *)
   1.635 +(* are extreme numbers in the original problem.                              *)
   1.636 +
   1.637 +  (* Version for (int*int*int) keys *)
   1.638 +local
   1.639 +  fun max_rat x y = if x </ y then y else x
   1.640 +  fun common_denominator fld amat acc =
   1.641 +      fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
   1.642 +  fun maximal_element fld amat acc =
   1.643 +    fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc 
   1.644 +fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
   1.645 +                     in Real.fromLargeInt a / Real.fromLargeInt b end;
   1.646 +fun int_of_float x = (trunc x handle Overflow => 0 | Domain => 0)
   1.647 +in
   1.648 +
   1.649 +fun tri_scale_then solver (obj:vector)  mats =
   1.650 + let 
   1.651 +  val cd1 = fold_rev (common_denominator Inttriplefunc.fold) mats (rat_1)
   1.652 +  val cd2 = common_denominator Intfunc.fold (snd obj)  (rat_1) 
   1.653 +  val mats' = map (Inttriplefunc.mapf (fn x => cd1 */ x)) mats
   1.654 +  val obj' = vector_cmul cd2 obj
   1.655 +  val max1 = fold_rev (maximal_element Inttriplefunc.fold) mats' (rat_0)
   1.656 +  val max2 = maximal_element Intfunc.fold (snd obj') (rat_0) 
   1.657 +  val scal1 = pow2 (20 - int_of_float(Math.ln (float_of_rat max1) / Math.ln 2.0))
   1.658 +  val scal2 = pow2 (20 - int_of_float(Math.ln (float_of_rat max2) / Math.ln 2.0)) 
   1.659 +  val mats'' = map (Inttriplefunc.mapf (fn x => x */ scal1)) mats'
   1.660 +  val obj'' = vector_cmul scal2 obj' 
   1.661 + in solver obj'' mats''
   1.662 +  end
   1.663 +end;
   1.664 +
   1.665 +(* Round a vector to "nice" rationals.                                       *)
   1.666 +
   1.667 +fun nice_rational n x = round_rat (n */ x) // n;;
   1.668 +fun nice_vector n ((d,v) : vector) = 
   1.669 + (d, Intfunc.fold (fn (i,c) => fn a => 
   1.670 +   let val y = nice_rational n c 
   1.671 +   in if c =/ rat_0 then a 
   1.672 +      else Intfunc.update (i,y) a end) v Intfunc.undefined):vector
   1.673 +
   1.674 +fun dest_ord f x = is_equal (f x);
   1.675 +
   1.676 +(* Stuff for "equations" ((int*int*int)->num functions).                         *)
   1.677 +
   1.678 +fun tri_equation_cmul c eq =
   1.679 +  if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
   1.680 +
   1.681 +fun tri_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
   1.682 +
   1.683 +fun tri_equation_eval assig eq =
   1.684 + let fun value v = Inttriplefunc.apply assig v 
   1.685 + in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
   1.686 + end;
   1.687 +
   1.688 +(* Eliminate among linear equations: return unconstrained variables and      *)
   1.689 +(* assignments for the others in terms of them. We give one pseudo-variable  *)
   1.690 +(* "one" that's used for a constant term.                                    *)
   1.691 +
   1.692 +local
   1.693 +  fun extract_first p l = case l of  (* FIXME : use find_first instead *)
   1.694 +   [] => error "extract_first"
   1.695 + | h::t => if p h then (h,t) else
   1.696 +          let val (k,s) = extract_first p t in (k,h::s) end
   1.697 +fun eliminate vars dun eqs = case vars of 
   1.698 +  [] => if forall Inttriplefunc.is_undefined eqs then dun
   1.699 +        else raise Unsolvable
   1.700 + | v::vs =>
   1.701 +  ((let 
   1.702 +    val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs 
   1.703 +    val a = Inttriplefunc.apply eq v
   1.704 +    val eq' = tri_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
   1.705 +    fun elim e =
   1.706 +     let val b = Inttriplefunc.tryapplyd e v rat_0 
   1.707 +     in if b =/ rat_0 then e else
   1.708 +        tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
   1.709 +     end
   1.710 +   in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
   1.711 +   end)
   1.712 +  handle Failure _ => eliminate vs dun eqs)
   1.713 +in
   1.714 +fun tri_eliminate_equations one vars eqs =
   1.715 + let 
   1.716 +  val assig = eliminate vars Inttriplefunc.undefined eqs
   1.717 +  val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   1.718 +  in (distinct (dest_ord triple_int_ord) vs, assig)
   1.719 +  end
   1.720 +end;
   1.721 +
   1.722 +(* Eliminate all variables, in an essentially arbitrary order.               *)
   1.723 +
   1.724 +fun tri_eliminate_all_equations one =
   1.725 + let 
   1.726 +  fun choose_variable eq =
   1.727 +   let val (v,_) = Inttriplefunc.choose eq 
   1.728 +   in if is_equal (triple_int_ord(v,one)) then
   1.729 +      let val eq' = Inttriplefunc.undefine v eq 
   1.730 +      in if Inttriplefunc.is_undefined eq' then error "choose_variable" 
   1.731 +         else fst (Inttriplefunc.choose eq')
   1.732 +      end
   1.733 +    else v 
   1.734 +   end
   1.735 +  fun eliminate dun eqs = case eqs of 
   1.736 +    [] => dun
   1.737 +  | eq::oeqs =>
   1.738 +    if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
   1.739 +    let val v = choose_variable eq
   1.740 +        val a = Inttriplefunc.apply eq v
   1.741 +        val eq' = tri_equation_cmul ((Rat.rat_of_int ~1) // a) 
   1.742 +                   (Inttriplefunc.undefine v eq)
   1.743 +        fun elim e =
   1.744 +         let val b = Inttriplefunc.tryapplyd e v rat_0 
   1.745 +         in if b =/ rat_0 then e 
   1.746 +            else tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
   1.747 +         end
   1.748 +    in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun)) 
   1.749 +                 (map elim oeqs) 
   1.750 +    end
   1.751 +in fn eqs =>
   1.752 + let 
   1.753 +  val assig = eliminate Inttriplefunc.undefined eqs
   1.754 +  val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   1.755 + in (distinct (dest_ord triple_int_ord) vs,assig)
   1.756 + end
   1.757 +end;
   1.758 + 
   1.759 +(* Solve equations by assigning arbitrary numbers.                           *)
   1.760 +
   1.761 +fun tri_solve_equations one eqs =
   1.762 + let 
   1.763 +  val (vars,assigs) = tri_eliminate_all_equations one eqs
   1.764 +  val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars 
   1.765 +            (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
   1.766 +  val ass =
   1.767 +    Inttriplefunc.combine (curry op +/) (K false) 
   1.768 +    (Inttriplefunc.mapf (tri_equation_eval vfn) assigs) vfn 
   1.769 + in if forall (fn e => tri_equation_eval ass e =/ rat_0) eqs
   1.770 +    then Inttriplefunc.undefine one ass else raise Sanity
   1.771 + end;
   1.772 +
   1.773 +(* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
   1.774 +
   1.775 +fun tri_epoly_pmul p q acc =
   1.776 + Monomialfunc.fold (fn (m1, c) => fn a =>
   1.777 +  Monomialfunc.fold (fn (m2,e) => fn b =>
   1.778 +   let val m =  monomial_mul m1 m2
   1.779 +       val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined 
   1.780 +   in Monomialfunc.update (m,tri_equation_add (tri_equation_cmul c e) es) b 
   1.781 +   end) q a) p acc ;
   1.782 +
   1.783 +(* Usual operations on equation-parametrized poly.                           *)
   1.784 +
   1.785 +fun tri_epoly_cmul c l =
   1.786 +  if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (tri_equation_cmul c) l;;
   1.787 +
   1.788 +val tri_epoly_neg = tri_epoly_cmul (Rat.rat_of_int ~1);
   1.789 +
   1.790 +val tri_epoly_add = Inttriplefunc.combine tri_equation_add Inttriplefunc.is_undefined;
   1.791 +
   1.792 +fun tri_epoly_sub p q = tri_epoly_add p (tri_epoly_neg q);;
   1.793 +
   1.794 +(* Stuff for "equations" ((int*int)->num functions).                         *)
   1.795 +
   1.796 +fun pi_equation_cmul c eq =
   1.797 +  if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
   1.798 +
   1.799 +fun pi_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
   1.800 +
   1.801 +fun pi_equation_eval assig eq =
   1.802 + let fun value v = Inttriplefunc.apply assig v 
   1.803 + in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
   1.804 + end;
   1.805 +
   1.806 +(* Eliminate among linear equations: return unconstrained variables and      *)
   1.807 +(* assignments for the others in terms of them. We give one pseudo-variable  *)
   1.808 +(* "one" that's used for a constant term.                                    *)
   1.809 +
   1.810 +local
   1.811 +fun extract_first p l = case l of 
   1.812 +   [] => error "extract_first"
   1.813 + | h::t => if p h then (h,t) else
   1.814 +          let val (k,s) = extract_first p t in (k,h::s) end
   1.815 +fun eliminate vars dun eqs = case vars of 
   1.816 +  [] => if forall Inttriplefunc.is_undefined eqs then dun
   1.817 +        else raise Unsolvable
   1.818 + | v::vs =>
   1.819 +   let 
   1.820 +    val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs 
   1.821 +    val a = Inttriplefunc.apply eq v
   1.822 +    val eq' = pi_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
   1.823 +    fun elim e =
   1.824 +     let val b = Inttriplefunc.tryapplyd e v rat_0 
   1.825 +     in if b =/ rat_0 then e else
   1.826 +        pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
   1.827 +     end
   1.828 +   in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
   1.829 +   end
   1.830 +  handle Failure _ => eliminate vs dun eqs
   1.831 +in
   1.832 +fun pi_eliminate_equations one vars eqs =
   1.833 + let 
   1.834 +  val assig = eliminate vars Inttriplefunc.undefined eqs
   1.835 +  val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   1.836 +  in (distinct (dest_ord triple_int_ord) vs, assig)
   1.837 +  end
   1.838 +end;
   1.839 +
   1.840 +(* Eliminate all variables, in an essentially arbitrary order.               *)
   1.841 +
   1.842 +fun pi_eliminate_all_equations one =
   1.843 + let 
   1.844 +  fun choose_variable eq =
   1.845 +   let val (v,_) = Inttriplefunc.choose eq 
   1.846 +   in if is_equal (triple_int_ord(v,one)) then
   1.847 +      let val eq' = Inttriplefunc.undefine v eq 
   1.848 +      in if Inttriplefunc.is_undefined eq' then error "choose_variable" 
   1.849 +         else fst (Inttriplefunc.choose eq')
   1.850 +      end
   1.851 +    else v 
   1.852 +   end
   1.853 +  fun eliminate dun eqs = case eqs of 
   1.854 +    [] => dun
   1.855 +  | eq::oeqs =>
   1.856 +    if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
   1.857 +    let val v = choose_variable eq
   1.858 +        val a = Inttriplefunc.apply eq v
   1.859 +        val eq' = pi_equation_cmul ((Rat.rat_of_int ~1) // a) 
   1.860 +                   (Inttriplefunc.undefine v eq)
   1.861 +        fun elim e =
   1.862 +         let val b = Inttriplefunc.tryapplyd e v rat_0 
   1.863 +         in if b =/ rat_0 then e 
   1.864 +            else pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
   1.865 +         end
   1.866 +    in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun)) 
   1.867 +                 (map elim oeqs) 
   1.868 +    end
   1.869 +in fn eqs =>
   1.870 + let 
   1.871 +  val assig = eliminate Inttriplefunc.undefined eqs
   1.872 +  val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   1.873 + in (distinct (dest_ord triple_int_ord) vs,assig)
   1.874 + end
   1.875 +end;
   1.876 + 
   1.877 +(* Solve equations by assigning arbitrary numbers.                           *)
   1.878 +
   1.879 +fun pi_solve_equations one eqs =
   1.880 + let 
   1.881 +  val (vars,assigs) = pi_eliminate_all_equations one eqs
   1.882 +  val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars 
   1.883 +            (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
   1.884 +  val ass =
   1.885 +    Inttriplefunc.combine (curry op +/) (K false) 
   1.886 +    (Inttriplefunc.mapf (pi_equation_eval vfn) assigs) vfn 
   1.887 + in if forall (fn e => pi_equation_eval ass e =/ rat_0) eqs
   1.888 +    then Inttriplefunc.undefine one ass else raise Sanity
   1.889 + end;
   1.890 +
   1.891 +(* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
   1.892 +
   1.893 +fun pi_epoly_pmul p q acc =
   1.894 + Monomialfunc.fold (fn (m1, c) => fn a =>
   1.895 +  Monomialfunc.fold (fn (m2,e) => fn b =>
   1.896 +   let val m =  monomial_mul m1 m2
   1.897 +       val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined 
   1.898 +   in Monomialfunc.update (m,pi_equation_add (pi_equation_cmul c e) es) b 
   1.899 +   end) q a) p acc ;
   1.900 +
   1.901 +(* Usual operations on equation-parametrized poly.                           *)
   1.902 +
   1.903 +fun pi_epoly_cmul c l =
   1.904 +  if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (pi_equation_cmul c) l;;
   1.905 +
   1.906 +val pi_epoly_neg = pi_epoly_cmul (Rat.rat_of_int ~1);
   1.907 +
   1.908 +val pi_epoly_add = Inttriplefunc.combine pi_equation_add Inttriplefunc.is_undefined;
   1.909 +
   1.910 +fun pi_epoly_sub p q = pi_epoly_add p (pi_epoly_neg q);;
   1.911 +
   1.912 +fun allpairs f l1 l2 =  fold_rev (fn x => (curry (op @)) (map (f x) l2)) l1 [];
   1.913 +
   1.914 +(* Hence produce the "relevant" monomials: those whose squares lie in the    *)
   1.915 +(* Newton polytope of the monomials in the input. (This is enough according  *)
   1.916 +(* to Reznik: "Extremal PSD forms with few terms", Duke Math. Journal,       *)
   1.917 +(* vol 45, pp. 363--374, 1978.                                               *)
   1.918 +(*                                                                           *)
   1.919 +(* These are ordered in sort of decreasing degree. In particular the         *)
   1.920 +(* constant monomial is last; this gives an order in diagonalization of the  *)
   1.921 +(* quadratic form that will tend to display constants.                       *)
   1.922 +
   1.923 +(* Diagonalize (Cholesky/LDU) the matrix corresponding to a quadratic form.  *)
   1.924 +
   1.925 +local
   1.926 +fun diagonalize n i m =
   1.927 + if Intpairfunc.is_undefined (snd m) then [] 
   1.928 + else
   1.929 +  let val a11 = Intpairfunc.tryapplyd (snd m) (i,i) rat_0 
   1.930 +  in if a11 </ rat_0 then raise Failure "diagonalize: not PSD"
   1.931 +    else if a11 =/ rat_0 then
   1.932 +          if Intfunc.is_undefined (snd (row i m)) then diagonalize n (i + 1) m
   1.933 +          else raise Failure "diagonalize: not PSD ___ "
   1.934 +    else
   1.935 +     let 
   1.936 +      val v = row i m
   1.937 +      val v' = (fst v, Intfunc.fold (fn (i, c) => fn a => 
   1.938 +       let val y = c // a11 
   1.939 +       in if y = rat_0 then a else Intfunc.update (i,y) a 
   1.940 +       end)  (snd v) Intfunc.undefined)
   1.941 +      fun upt0 x y a = if y = rat_0 then a else Intpairfunc.update (x,y) a
   1.942 +      val m' =
   1.943 +      ((n,n),
   1.944 +      iter (i+1,n) (fn j =>
   1.945 +          iter (i+1,n) (fn k =>
   1.946 +              (upt0 (j,k) (Intpairfunc.tryapplyd (snd m) (j,k) rat_0 -/ Intfunc.tryapplyd (snd v) j rat_0 */ Intfunc.tryapplyd (snd v') k rat_0))))
   1.947 +          Intpairfunc.undefined)
   1.948 +     in (a11,v')::diagonalize n (i + 1) m' 
   1.949 +     end
   1.950 +  end
   1.951 +in
   1.952 +fun diag m =
   1.953 + let 
   1.954 +   val nn = dimensions m 
   1.955 +   val n = fst nn 
   1.956 + in if snd nn <> n then error "diagonalize: non-square matrix" 
   1.957 +    else diagonalize n 1 m
   1.958 + end
   1.959 +end;
   1.960 +
   1.961 +fun gcd_rat a b = Rat.rat_of_int (Integer.gcd (int_of_rat a) (int_of_rat b));
   1.962 +
   1.963 +(* Adjust a diagonalization to collect rationals at the start.               *)
   1.964 +  (* FIXME : Potentially polymorphic keys, but here only: integers!! *)
   1.965 +local
   1.966 + fun upd0 x y a = if y =/ rat_0 then a else Intfunc.update(x,y) a;
   1.967 + fun mapa f (d,v) = 
   1.968 +  (d, Intfunc.fold (fn (i,c) => fn a => upd0 i (f c) a) v Intfunc.undefined)
   1.969 + fun adj (c,l) =
   1.970 + let val a = 
   1.971 +  Intfunc.fold (fn (i,c) => fn a => lcm_rat a (denominator_rat c)) 
   1.972 +    (snd l) rat_1 //
   1.973 +  Intfunc.fold (fn (i,c) => fn a => gcd_rat a (numerator_rat c)) 
   1.974 +    (snd l) rat_0
   1.975 +  in ((c // (a */ a)),mapa (fn x => a */ x) l)
   1.976 +  end
   1.977 +in
   1.978 +fun deration d = if null d then (rat_0,d) else
   1.979 + let val d' = map adj d
   1.980 +     val a = fold (lcm_rat o denominator_rat o fst) d' rat_1 //
   1.981 +          fold (gcd_rat o numerator_rat o fst) d' rat_0 
   1.982 + in ((rat_1 // a),map (fn (c,l) => (a */ c,l)) d')
   1.983 + end
   1.984 +end;
   1.985 + 
   1.986 +(* Enumeration of monomials with given multidegree bound.                    *)
   1.987 +
   1.988 +fun enumerate_monomials d vars = 
   1.989 + if d < 0 then []
   1.990 + else if d = 0 then [Ctermfunc.undefined]
   1.991 + else if null vars then [monomial_1] else
   1.992 + let val alts =
   1.993 +  map (fn k => let val oths = enumerate_monomials (d - k) (tl vars) 
   1.994 +               in map (fn ks => if k = 0 then ks else Ctermfunc.update (hd vars, k) ks) oths end) (0 upto d) 
   1.995 + in fold1 (curry op @) alts
   1.996 + end;
   1.997 +
   1.998 +(* Enumerate products of distinct input polys with degree <= d.              *)
   1.999 +(* We ignore any constant input polynomials.                                 *)
  1.1000 +(* Give the output polynomial and a record of how it was derived.            *)
  1.1001 +
  1.1002 +local
  1.1003 + open RealArith
  1.1004 +in
  1.1005 +fun enumerate_products d pols =
  1.1006 +if d = 0 then [(poly_const rat_1,Rational_lt rat_1)] 
  1.1007 +else if d < 0 then [] else
  1.1008 +case pols of 
  1.1009 +   [] => [(poly_const rat_1,Rational_lt rat_1)]
  1.1010 + | (p,b)::ps => 
  1.1011 +    let val e = multidegree p 
  1.1012 +    in if e = 0 then enumerate_products d ps else
  1.1013 +       enumerate_products d ps @
  1.1014 +       map (fn (q,c) => (poly_mul p q,Product(b,c)))
  1.1015 +         (enumerate_products (d - e) ps)
  1.1016 +    end
  1.1017 +end;
  1.1018 +
  1.1019 +(* Convert regular polynomial. Note that we treat (0,0,0) as -1.             *)
  1.1020 +
  1.1021 +fun epoly_of_poly p =
  1.1022 +  Monomialfunc.fold (fn (m,c) => fn a => Monomialfunc.update (m, Inttriplefunc.onefunc ((0,0,0), Rat.neg c)) a) p Monomialfunc.undefined;
  1.1023 +
  1.1024 +(* String for block diagonal matrix numbered k.                              *)
  1.1025 +
  1.1026 +fun sdpa_of_blockdiagonal k m =
  1.1027 + let 
  1.1028 +  val pfx = string_of_int k ^" "
  1.1029 +  val ents =
  1.1030 +    Inttriplefunc.fold 
  1.1031 +      (fn ((b,i,j),c) => fn a => if i > j then a else ((b,i,j),c)::a) 
  1.1032 +      m [] 
  1.1033 +  val entss = sort (increasing fst triple_int_ord) ents 
  1.1034 + in fold_rev (fn ((b,i,j),c) => fn a =>
  1.1035 +     pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
  1.1036 +     " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
  1.1037 + end;
  1.1038 +
  1.1039 +(* SDPA for problem using block diagonal (i.e. multiple SDPs)                *)
  1.1040 +
  1.1041 +fun sdpa_of_blockproblem nblocks blocksizes obj mats =
  1.1042 + let val m = length mats - 1 
  1.1043 + in
  1.1044 +  string_of_int m ^ "\n" ^
  1.1045 +  string_of_int nblocks ^ "\n" ^
  1.1046 +  (fold1 (fn s => fn t => s^" "^t) (map string_of_int blocksizes)) ^
  1.1047 +  "\n" ^
  1.1048 +  sdpa_of_vector obj ^
  1.1049 +  fold_rev2 (fn k => fn m => fn a => sdpa_of_blockdiagonal (k - 1) m ^ a)
  1.1050 +    (1 upto length mats) mats ""
  1.1051 + end;
  1.1052 +
  1.1053 +(* Run prover on a problem in block diagonal form.                       *)
  1.1054 +
  1.1055 +fun run_blockproblem prover nblocks blocksizes obj mats=
  1.1056 +  parse_csdpoutput (prover (sdpa_of_blockproblem nblocks blocksizes obj mats))
  1.1057 +
  1.1058 +(* 3D versions of matrix operations to consider blocks separately.           *)
  1.1059 +
  1.1060 +val bmatrix_add = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0);
  1.1061 +fun bmatrix_cmul c bm =
  1.1062 +  if c =/ rat_0 then Inttriplefunc.undefined
  1.1063 +  else Inttriplefunc.mapf (fn x => c */ x) bm;
  1.1064 +
  1.1065 +val bmatrix_neg = bmatrix_cmul (Rat.rat_of_int ~1);
  1.1066 +fun bmatrix_sub m1 m2 = bmatrix_add m1 (bmatrix_neg m2);;
  1.1067 +
  1.1068 +(* Smash a block matrix into components.                                     *)
  1.1069 +
  1.1070 +fun blocks blocksizes bm =
  1.1071 + map (fn (bs,b0) =>
  1.1072 +      let val m = Inttriplefunc.fold
  1.1073 +          (fn ((b,i,j),c) => fn a => if b = b0 then Intpairfunc.update ((i,j),c) a else a) bm Intpairfunc.undefined
  1.1074 +          val d = Intpairfunc.fold (fn ((i,j),c) => fn a => max a (max i j)) m 0 
  1.1075 +      in (((bs,bs),m):matrix) end)
  1.1076 + (blocksizes ~~ (1 upto length blocksizes));;
  1.1077 +
  1.1078 +(* FIXME : Get rid of this !!!*)
  1.1079 +local
  1.1080 +  fun tryfind_with msg f [] = raise Failure msg
  1.1081 +    | tryfind_with msg f (x::xs) = (f x handle Failure s => tryfind_with s f xs);
  1.1082 +in 
  1.1083 +  fun tryfind f = tryfind_with "tryfind" f
  1.1084 +end
  1.1085 +
  1.1086 +(*
  1.1087 +fun tryfind f [] = error "tryfind"
  1.1088 +  | tryfind f (x::xs) = (f x handle ERROR _ => tryfind f xs);
  1.1089 +*)
  1.1090 +
  1.1091 +(* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
  1.1092 +
  1.1093 + 
  1.1094 +local
  1.1095 + open RealArith
  1.1096 +in
  1.1097 +fun real_positivnullstellensatz_general prover linf d eqs leqs pol =
  1.1098 +let 
  1.1099 + val vars = fold_rev (curry (gen_union (op aconvc)) o poly_variables) 
  1.1100 +              (pol::eqs @ map fst leqs) []
  1.1101 + val monoid = if linf then 
  1.1102 +      (poly_const rat_1,Rational_lt rat_1)::
  1.1103 +      (filter (fn (p,c) => multidegree p <= d) leqs)
  1.1104 +    else enumerate_products d leqs
  1.1105 + val nblocks = length monoid
  1.1106 + fun mk_idmultiplier k p =
  1.1107 +  let 
  1.1108 +   val e = d - multidegree p
  1.1109 +   val mons = enumerate_monomials e vars
  1.1110 +   val nons = mons ~~ (1 upto length mons) 
  1.1111 +  in (mons,
  1.1112 +      fold_rev (fn (m,n) => Monomialfunc.update(m,Inttriplefunc.onefunc((~k,~n,n),rat_1))) nons Monomialfunc.undefined)
  1.1113 +  end
  1.1114 +
  1.1115 + fun mk_sqmultiplier k (p,c) =
  1.1116 +  let 
  1.1117 +   val e = (d - multidegree p) div 2
  1.1118 +   val mons = enumerate_monomials e vars
  1.1119 +   val nons = mons ~~ (1 upto length mons) 
  1.1120 +  in (mons, 
  1.1121 +      fold_rev (fn (m1,n1) =>
  1.1122 +       fold_rev (fn (m2,n2) => fn  a =>
  1.1123 +        let val m = monomial_mul m1 m2 
  1.1124 +        in if n1 > n2 then a else
  1.1125 +          let val c = if n1 = n2 then rat_1 else rat_2
  1.1126 +              val e = Monomialfunc.tryapplyd a m Inttriplefunc.undefined 
  1.1127 +          in Monomialfunc.update(m, tri_equation_add (Inttriplefunc.onefunc((k,n1,n2), c)) e) a
  1.1128 +          end
  1.1129 +        end)  nons)
  1.1130 +       nons Monomialfunc.undefined)
  1.1131 +  end
  1.1132 +
  1.1133 +  val (sqmonlist,sqs) = split_list (map2 mk_sqmultiplier (1 upto length monoid) monoid)
  1.1134 +  val (idmonlist,ids) =  split_list(map2 mk_idmultiplier (1 upto length eqs) eqs)
  1.1135 +  val blocksizes = map length sqmonlist
  1.1136 +  val bigsum =
  1.1137 +    fold_rev2 (fn p => fn q => fn a => tri_epoly_pmul p q a) eqs ids
  1.1138 +            (fold_rev2 (fn (p,c) => fn s => fn a => tri_epoly_pmul p s a) monoid sqs
  1.1139 +                     (epoly_of_poly(poly_neg pol)))
  1.1140 +  val eqns = Monomialfunc.fold (fn (m,e) => fn a => e::a) bigsum []
  1.1141 +  val (pvs,assig) = tri_eliminate_all_equations (0,0,0) eqns
  1.1142 +  val qvars = (0,0,0)::pvs
  1.1143 +  val allassig = fold_rev (fn v => Inttriplefunc.update(v,(Inttriplefunc.onefunc(v,rat_1)))) pvs assig
  1.1144 +  fun mk_matrix v =
  1.1145 +    Inttriplefunc.fold (fn ((b,i,j), ass) => fn m => 
  1.1146 +        if b < 0 then m else
  1.1147 +         let val c = Inttriplefunc.tryapplyd ass v rat_0
  1.1148 +         in if c = rat_0 then m else
  1.1149 +            Inttriplefunc.update ((b,j,i), c) (Inttriplefunc.update ((b,i,j), c) m)
  1.1150 +         end)
  1.1151 +          allassig Inttriplefunc.undefined
  1.1152 +  val diagents = Inttriplefunc.fold
  1.1153 +    (fn ((b,i,j), e) => fn a => if b > 0 andalso i = j then tri_equation_add e a else a)
  1.1154 +    allassig Inttriplefunc.undefined
  1.1155 +
  1.1156 +  val mats = map mk_matrix qvars
  1.1157 +  val obj = (length pvs,
  1.1158 +            itern 1 pvs (fn v => fn i => Intfunc.updatep iszero (i,Inttriplefunc.tryapplyd diagents v rat_0))
  1.1159 +                        Intfunc.undefined)
  1.1160 +  val raw_vec = if null pvs then vector_0 0
  1.1161 +                else tri_scale_then (run_blockproblem prover nblocks blocksizes) obj mats
  1.1162 +  fun int_element (d,v) i = Intfunc.tryapplyd v i rat_0
  1.1163 +  fun cterm_element (d,v) i = Ctermfunc.tryapplyd v i rat_0
  1.1164 +
  1.1165 +  fun find_rounding d =
  1.1166 +   let 
  1.1167 +    val _ = if !debugging 
  1.1168 +          then writeln ("Trying rounding with limit "^Rat.string_of_rat d ^ "\n") 
  1.1169 +          else ()
  1.1170 +    val vec = nice_vector d raw_vec
  1.1171 +    val blockmat = iter (1,dim vec)
  1.1172 +     (fn i => fn a => bmatrix_add (bmatrix_cmul (int_element vec i) (nth mats i)) a)
  1.1173 +     (bmatrix_neg (nth mats 0))
  1.1174 +    val allmats = blocks blocksizes blockmat 
  1.1175 +   in (vec,map diag allmats)
  1.1176 +   end
  1.1177 +  val (vec,ratdias) =
  1.1178 +    if null pvs then find_rounding rat_1
  1.1179 +    else tryfind find_rounding (map Rat.rat_of_int (1 upto 31) @
  1.1180 +                                map pow2 (5 upto 66))
  1.1181 +  val newassigs =
  1.1182 +    fold_rev (fn k => Inttriplefunc.update (nth pvs (k - 1), int_element vec k))
  1.1183 +           (1 upto dim vec) (Inttriplefunc.onefunc ((0,0,0), Rat.rat_of_int ~1))
  1.1184 +  val finalassigs =
  1.1185 +    Inttriplefunc.fold (fn (v,e) => fn a => Inttriplefunc.update(v, tri_equation_eval newassigs e) a) allassig newassigs
  1.1186 +  fun poly_of_epoly p =
  1.1187 +    Monomialfunc.fold (fn (v,e) => fn a => Monomialfunc.updatep iszero (v,tri_equation_eval finalassigs e) a)
  1.1188 +          p Monomialfunc.undefined
  1.1189 +  fun  mk_sos mons =
  1.1190 +   let fun mk_sq (c,m) =
  1.1191 +    (c,fold_rev (fn k=> fn a => Monomialfunc.updatep iszero (nth mons (k - 1), int_element m k) a)
  1.1192 +                 (1 upto length mons) Monomialfunc.undefined)
  1.1193 +   in map mk_sq
  1.1194 +   end
  1.1195 +  val sqs = map2 mk_sos sqmonlist ratdias
  1.1196 +  val cfs = map poly_of_epoly ids
  1.1197 +  val msq = filter (fn (a,b) => not (null b)) (map2 pair monoid sqs)
  1.1198 +  fun eval_sq sqs = fold_rev (fn (c,q) => poly_add (poly_cmul c (poly_mul q q))) sqs poly_0
  1.1199 +  val sanity =
  1.1200 +    fold_rev (fn ((p,c),s) => poly_add (poly_mul p (eval_sq s))) msq
  1.1201 +           (fold_rev2 (fn p => fn q => poly_add (poly_mul p q)) cfs eqs
  1.1202 +                    (poly_neg pol))
  1.1203 +
  1.1204 +in if not(Monomialfunc.is_undefined sanity) then raise Sanity else
  1.1205 +  (cfs,map (fn (a,b) => (snd a,b)) msq)
  1.1206 + end
  1.1207 +
  1.1208 +
  1.1209 +end;
  1.1210 +
  1.1211 +(* Iterative deepening.                                                      *)
  1.1212 +
  1.1213 +fun deepen f n = 
  1.1214 +  (writeln ("Searching with depth limit " ^ string_of_int n) ; (f n handle Failure s => (writeln ("failed with message: " ^ s) ; deepen f (n+1))))
  1.1215 +
  1.1216 +(* The ordering so we can create canonical HOL polynomials.                  *)
  1.1217 +
  1.1218 +fun dest_monomial mon = sort (increasing fst cterm_ord) (Ctermfunc.graph mon);
  1.1219 +
  1.1220 +fun monomial_order (m1,m2) =
  1.1221 + if Ctermfunc.is_undefined m2 then LESS 
  1.1222 + else if Ctermfunc.is_undefined m1 then GREATER 
  1.1223 + else
  1.1224 +  let val mon1 = dest_monomial m1 
  1.1225 +      val mon2 = dest_monomial m2
  1.1226 +      val deg1 = fold (curry op + o snd) mon1 0
  1.1227 +      val deg2 = fold (curry op + o snd) mon2 0 
  1.1228 +  in if deg1 < deg2 then GREATER else if deg1 > deg2 then LESS
  1.1229 +     else list_ord (prod_ord cterm_ord int_ord) (mon1,mon2)
  1.1230 +  end;
  1.1231 +
  1.1232 +fun dest_poly p =
  1.1233 +  map (fn (m,c) => (c,dest_monomial m))
  1.1234 +      (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p));
  1.1235 +
  1.1236 +(* Map back polynomials and their composites to HOL.                         *)
  1.1237 +
  1.1238 +local
  1.1239 + open Thm Numeral RealArith
  1.1240 +in
  1.1241 +
  1.1242 +fun cterm_of_varpow x k = if k = 1 then x else capply (capply @{cterm "op ^ :: real => _"} x) 
  1.1243 +  (mk_cnumber @{ctyp nat} k)
  1.1244 +
  1.1245 +fun cterm_of_monomial m = 
  1.1246 + if Ctermfunc.is_undefined m then @{cterm "1::real"} 
  1.1247 + else 
  1.1248 +  let 
  1.1249 +   val m' = dest_monomial m
  1.1250 +   val vps = fold_rev (fn (x,k) => cons (cterm_of_varpow x k)) m' [] 
  1.1251 +  in fold1 (fn s => fn t => capply (capply @{cterm "op * :: real => _"} s) t) vps
  1.1252 +  end
  1.1253 +
  1.1254 +fun cterm_of_cmonomial (m,c) = if Ctermfunc.is_undefined m then cterm_of_rat c
  1.1255 +    else if c = Rat.one then cterm_of_monomial m
  1.1256 +    else capply (capply @{cterm "op *::real => _"} (cterm_of_rat c)) (cterm_of_monomial m);
  1.1257 +
  1.1258 +fun cterm_of_poly p = 
  1.1259 + if Monomialfunc.is_undefined p then @{cterm "0::real"} 
  1.1260 + else
  1.1261 +  let 
  1.1262 +   val cms = map cterm_of_cmonomial
  1.1263 +     (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p))
  1.1264 +  in fold1 (fn t1 => fn t2 => capply(capply @{cterm "op + :: real => _"} t1) t2) cms
  1.1265 +  end;
  1.1266 +
  1.1267 +fun cterm_of_sqterm (c,p) = Product(Rational_lt c,Square(cterm_of_poly p));
  1.1268 +
  1.1269 +fun cterm_of_sos (pr,sqs) = if null sqs then pr
  1.1270 +  else Product(pr,fold1 (fn a => fn b => Sum(a,b)) (map cterm_of_sqterm sqs));
  1.1271 +
  1.1272 +end
  1.1273 +
  1.1274 +(* Interface to HOL.                                                         *)
  1.1275 +local
  1.1276 +  open Thm Conv RealArith
  1.1277 +  val concl = dest_arg o cprop_of
  1.1278 +  fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
  1.1279 +in
  1.1280 +  (* FIXME: Replace tryfind by get_first !! *)
  1.1281 +fun real_nonlinear_prover prover ctxt =
  1.1282 + let 
  1.1283 +  val {add,mul,neg,pow,sub,main} =  Normalizer.semiring_normalizers_ord_wrapper ctxt
  1.1284 +      (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
  1.1285 +     simple_cterm_ord
  1.1286 +  val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
  1.1287 +       real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
  1.1288 +  fun mainf  translator (eqs,les,lts) = 
  1.1289 +  let 
  1.1290 +   val eq0 = map (poly_of_term o dest_arg1 o concl) eqs
  1.1291 +   val le0 = map (poly_of_term o dest_arg o concl) les
  1.1292 +   val lt0 = map (poly_of_term o dest_arg o concl) lts
  1.1293 +   val eqp0 = map (fn (t,i) => (t,Axiom_eq i)) (eq0 ~~ (0 upto (length eq0 - 1)))
  1.1294 +   val lep0 = map (fn (t,i) => (t,Axiom_le i)) (le0 ~~ (0 upto (length le0 - 1)))
  1.1295 +   val ltp0 = map (fn (t,i) => (t,Axiom_lt i)) (lt0 ~~ (0 upto (length lt0 - 1)))
  1.1296 +   val (keq,eq) = List.partition (fn (p,_) => multidegree p = 0) eqp0
  1.1297 +   val (klep,lep) = List.partition (fn (p,_) => multidegree p = 0) lep0
  1.1298 +   val (kltp,ltp) = List.partition (fn (p,_) => multidegree p = 0) ltp0
  1.1299 +   fun trivial_axiom (p,ax) =
  1.1300 +    case ax of
  1.1301 +       Axiom_eq n => if eval Ctermfunc.undefined p <>/ Rat.zero then nth eqs n 
  1.1302 +                     else raise Failure "trivial_axiom: Not a trivial axiom"
  1.1303 +     | Axiom_le n => if eval Ctermfunc.undefined p </ Rat.zero then nth les n 
  1.1304 +                     else raise Failure "trivial_axiom: Not a trivial axiom"
  1.1305 +     | Axiom_lt n => if eval Ctermfunc.undefined p <=/ Rat.zero then nth lts n 
  1.1306 +                     else raise Failure "trivial_axiom: Not a trivial axiom"
  1.1307 +     | _ => error "trivial_axiom: Not a trivial axiom"
  1.1308 +   in 
  1.1309 +  ((let val th = tryfind trivial_axiom (keq @ klep @ kltp)
  1.1310 +   in fconv_rule (arg_conv (arg1_conv real_poly_conv) then_conv field_comp_conv) th end)
  1.1311 +   handle Failure _ => (
  1.1312 +    let 
  1.1313 +     val pol = fold_rev poly_mul (map fst ltp) (poly_const Rat.one)
  1.1314 +     val leq = lep @ ltp
  1.1315 +     fun tryall d =
  1.1316 +      let val e = multidegree pol
  1.1317 +          val k = if e = 0 then 0 else d div e
  1.1318 +          val eq' = map fst eq 
  1.1319 +      in tryfind (fn i => (d,i,real_positivnullstellensatz_general prover false d eq' leq
  1.1320 +                            (poly_neg(poly_pow pol i))))
  1.1321 +              (0 upto k)
  1.1322 +      end
  1.1323 +    val (d,i,(cert_ideal,cert_cone)) = deepen tryall 0
  1.1324 +    val proofs_ideal =
  1.1325 +      map2 (fn q => fn (p,ax) => Eqmul(cterm_of_poly q,ax)) cert_ideal eq
  1.1326 +    val proofs_cone = map cterm_of_sos cert_cone
  1.1327 +    val proof_ne = if null ltp then Rational_lt Rat.one else
  1.1328 +      let val p = fold1 (fn s => fn t => Product(s,t)) (map snd ltp) 
  1.1329 +      in  funpow i (fn q => Product(p,q)) (Rational_lt Rat.one)
  1.1330 +      end
  1.1331 +    val proof = fold1 (fn s => fn t => Sum(s,t))
  1.1332 +                           (proof_ne :: proofs_ideal @ proofs_cone) 
  1.1333 +    in writeln "Translating proof certificate to HOL";
  1.1334 +       translator (eqs,les,lts) proof
  1.1335 +    end))
  1.1336 +   end
  1.1337 + in mainf end
  1.1338 +end
  1.1339 +
  1.1340 +fun C f x y = f y x;
  1.1341 +  (* FIXME : This is very bad!!!*)
  1.1342 +fun subst_conv eqs t = 
  1.1343 + let 
  1.1344 +  val t' = fold (Thm.cabs o Thm.lhs_of) eqs t
  1.1345 + in Conv.fconv_rule (Thm.beta_conversion true) (fold (C combination) eqs (reflexive t'))
  1.1346 + end
  1.1347 +
  1.1348 +(* A wrapper that tries to substitute away variables first.                  *)
  1.1349 +
  1.1350 +local
  1.1351 + open Thm Conv RealArith
  1.1352 +  fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
  1.1353 + val concl = dest_arg o cprop_of
  1.1354 + val shuffle1 = 
  1.1355 +   fconv_rule (rewr_conv @{lemma "(a + x == y) == (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps) })
  1.1356 + val shuffle2 =
  1.1357 +    fconv_rule (rewr_conv @{lemma "(x + a == y) ==  (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps)})
  1.1358 + fun substitutable_monomial fvs tm = case term_of tm of
  1.1359 +    Free(_,@{typ real}) => if not (member (op aconvc) fvs tm) then (Rat.one,tm) 
  1.1360 +                           else raise Failure "substitutable_monomial"
  1.1361 +  | @{term "op * :: real => _"}$c$(t as Free _ ) => 
  1.1362 +     if is_ratconst (dest_arg1 tm) andalso not (member (op aconvc) fvs (dest_arg tm))
  1.1363 +         then (dest_ratconst (dest_arg1 tm),dest_arg tm) else raise Failure "substitutable_monomial"
  1.1364 +  | @{term "op + :: real => _"}$s$t => 
  1.1365 +       (substitutable_monomial (add_cterm_frees (dest_arg tm) fvs) (dest_arg1 tm)
  1.1366 +        handle Failure _ => substitutable_monomial (add_cterm_frees (dest_arg1 tm) fvs) (dest_arg tm))
  1.1367 +  | _ => raise Failure "substitutable_monomial"
  1.1368 +
  1.1369 +  fun isolate_variable v th = 
  1.1370 +   let val w = dest_arg1 (cprop_of th)
  1.1371 +   in if v aconvc w then th
  1.1372 +      else case term_of w of
  1.1373 +           @{term "op + :: real => _"}$s$t => 
  1.1374 +              if dest_arg1 w aconvc v then shuffle2 th 
  1.1375 +              else isolate_variable v (shuffle1 th)
  1.1376 +          | _ => error "isolate variable : This should not happen?"
  1.1377 +   end 
  1.1378 +in
  1.1379 +
  1.1380 +fun real_nonlinear_subst_prover prover ctxt =
  1.1381 + let 
  1.1382 +  val {add,mul,neg,pow,sub,main} =  Normalizer.semiring_normalizers_ord_wrapper ctxt
  1.1383 +      (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
  1.1384 +     simple_cterm_ord
  1.1385 +
  1.1386 +  val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
  1.1387 +       real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
  1.1388 +
  1.1389 +  fun make_substitution th =
  1.1390 +   let 
  1.1391 +    val (c,v) = substitutable_monomial [] (dest_arg1(concl th))
  1.1392 +    val th1 = Drule.arg_cong_rule (capply @{cterm "op * :: real => _"} (cterm_of_rat (Rat.inv c))) (mk_meta_eq th)
  1.1393 +    val th2 = fconv_rule (binop_conv real_poly_mul_conv) th1
  1.1394 +   in fconv_rule (arg_conv real_poly_conv) (isolate_variable v th2)
  1.1395 +   end
  1.1396 +   fun oprconv cv ct = 
  1.1397 +    let val g = Thm.dest_fun2 ct
  1.1398 +    in if g aconvc @{cterm "op <= :: real => _"} 
  1.1399 +         orelse g aconvc @{cterm "op < :: real => _"} 
  1.1400 +       then arg_conv cv ct else arg1_conv cv ct
  1.1401 +    end
  1.1402 +  fun mainf translator =
  1.1403 +   let 
  1.1404 +    fun substfirst(eqs,les,lts) =
  1.1405 +      ((let 
  1.1406 +           val eth = tryfind make_substitution eqs
  1.1407 +           val modify = fconv_rule (arg_conv (oprconv(subst_conv [eth] then_conv real_poly_conv)))
  1.1408 +       in  substfirst
  1.1409 +             (filter_out (fn t => (Thm.dest_arg1 o Thm.dest_arg o cprop_of) t 
  1.1410 +                                   aconvc @{cterm "0::real"}) (map modify eqs),
  1.1411 +                                   map modify les,map modify lts)
  1.1412 +       end)
  1.1413 +       handle Failure  _ => real_nonlinear_prover prover ctxt translator (rev eqs, rev les, rev lts))
  1.1414 +    in substfirst
  1.1415 +   end
  1.1416 +
  1.1417 +
  1.1418 + in mainf
  1.1419 + end
  1.1420 +
  1.1421 +(* Overall function. *)
  1.1422 +
  1.1423 +fun real_sos prover ctxt t = gen_prover_real_arith ctxt (real_nonlinear_subst_prover prover ctxt) t;
  1.1424 +end;
  1.1425 +
  1.1426 +(* A tactic *)
  1.1427 +fun strip_all ct = 
  1.1428 + case term_of ct of 
  1.1429 +  Const("all",_) $ Abs (xn,xT,p) => 
  1.1430 +   let val (a,(v,t')) = (apsnd (Thm.dest_abs (SOME xn)) o Thm.dest_comb) ct
  1.1431 +   in apfst (cons v) (strip_all t')
  1.1432 +   end
  1.1433 +| _ => ([],ct)
  1.1434 +
  1.1435 +fun core_sos_conv prover ctxt t = Drule.arg_cong_rule @{cterm Trueprop} (real_sos prover ctxt (Thm.dest_arg t) RS @{thm Eq_TrueI})
  1.1436 +
  1.1437 +val known_sos_constants = 
  1.1438 +  [@{term "op ==>"}, @{term "Trueprop"}, 
  1.1439 +   @{term "op -->"}, @{term "op &"}, @{term "op |"}, 
  1.1440 +   @{term "Not"}, @{term "op = :: bool => _"}, 
  1.1441 +   @{term "All :: (real => _) => _"}, @{term "Ex :: (real => _) => _"}, 
  1.1442 +   @{term "op = :: real => _"}, @{term "op < :: real => _"}, 
  1.1443 +   @{term "op <= :: real => _"}, 
  1.1444 +   @{term "op + :: real => _"}, @{term "op - :: real => _"}, 
  1.1445 +   @{term "op * :: real => _"}, @{term "uminus :: real => _"}, 
  1.1446 +   @{term "op / :: real => _"}, @{term "inverse :: real => _"},
  1.1447 +   @{term "op ^ :: real => _"}, @{term "abs :: real => _"}, 
  1.1448 +   @{term "min :: real => _"}, @{term "max :: real => _"},
  1.1449 +   @{term "0::real"}, @{term "1::real"}, @{term "number_of :: int => real"},
  1.1450 +   @{term "number_of :: int => nat"},
  1.1451 +   @{term "Int.Bit0"}, @{term "Int.Bit1"}, 
  1.1452 +   @{term "Int.Pls"}, @{term "Int.Min"}];
  1.1453 +
  1.1454 +fun check_sos kcts ct = 
  1.1455 + let
  1.1456 +  val t = term_of ct
  1.1457 +  val _ = if not (null (Term.add_tfrees t []) 
  1.1458 +                  andalso null (Term.add_tvars t [])) 
  1.1459 +          then error "SOS: not sos. Additional type varables" else ()
  1.1460 +  val fs = Term.add_frees t []
  1.1461 +  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs 
  1.1462 +          then error "SOS: not sos. Variables with type not real" else ()
  1.1463 +  val vs = Term.add_vars t []
  1.1464 +  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs 
  1.1465 +          then error "SOS: not sos. Variables with type not real" else ()
  1.1466 +  val ukcs = subtract (fn (t,p) => Const p aconv t) kcts (Term.add_consts t [])
  1.1467 +  val _ = if  null ukcs then () 
  1.1468 +              else error ("SOSO: Unknown constants in Subgoal:" ^ commas (map fst ukcs))
  1.1469 +in () end
  1.1470 +
  1.1471 +fun core_sos_tac prover ctxt = CSUBGOAL (fn (ct, i) => 
  1.1472 +  let val _ = check_sos known_sos_constants ct
  1.1473 +      val (avs, p) = strip_all ct
  1.1474 +      val th = standard (fold_rev forall_intr avs (real_sos prover ctxt (Thm.dest_arg p)))
  1.1475 +  in rtac th i end);
  1.1476 +
  1.1477 +fun default_SOME f NONE v = SOME v
  1.1478 +  | default_SOME f (SOME v) _ = SOME v;
  1.1479 +
  1.1480 +fun lift_SOME f NONE a = f a
  1.1481 +  | lift_SOME f (SOME a) _ = SOME a;
  1.1482 +
  1.1483 +
  1.1484 +local
  1.1485 + val is_numeral = can (HOLogic.dest_number o term_of)
  1.1486 +in
  1.1487 +fun get_denom b ct = case term_of ct of
  1.1488 +  @{term "op / :: real => _"} $ _ $ _ => 
  1.1489 +     if is_numeral (Thm.dest_arg ct) then get_denom b (Thm.dest_arg1 ct)
  1.1490 +     else default_SOME (get_denom b) (get_denom b (Thm.dest_arg ct))   (Thm.dest_arg ct, b)
  1.1491 + | @{term "op < :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
  1.1492 + | @{term "op <= :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
  1.1493 + | _ $ _ => lift_SOME (get_denom b) (get_denom b (Thm.dest_fun ct)) (Thm.dest_arg ct)
  1.1494 + | _ => NONE
  1.1495 +end;
  1.1496 +
  1.1497 +fun elim_one_denom_tac ctxt = 
  1.1498 +CSUBGOAL (fn (P,i) => 
  1.1499 + case get_denom false P of 
  1.1500 +   NONE => no_tac
  1.1501 + | SOME (d,ord) => 
  1.1502 +     let 
  1.1503 +      val ss = simpset_of ctxt addsimps @{thms field_simps} 
  1.1504 +               addsimps [@{thm nonzero_power_divide}, @{thm power_divide}]
  1.1505 +      val th = instantiate' [] [SOME d, SOME (Thm.dest_arg P)] 
  1.1506 +         (if ord then @{lemma "(d=0 --> P) & (d>0 --> P) & (d<(0::real) --> P) ==> P" by auto}
  1.1507 +          else @{lemma "(d=0 --> P) & (d ~= (0::real) --> P) ==> P" by blast})
  1.1508 +     in (rtac th i THEN Simplifier.asm_full_simp_tac ss i) end);
  1.1509 +
  1.1510 +fun elim_denom_tac ctxt i = REPEAT (elim_one_denom_tac ctxt i);
  1.1511 +
  1.1512 +fun sos_tac prover ctxt = ObjectLogic.full_atomize_tac THEN' elim_denom_tac ctxt THEN' core_sos_tac prover ctxt
  1.1513 +
  1.1514 +
  1.1515 +end;