src/HOL/Library/Sum_Of_Squares/sum_of_squares.ML
author wenzelm
Thu, 06 Aug 2009 19:51:59 +0200
changeset 32332 bc5cec7b2be6
parent 32265 src/HOL/Library/sum_of_squares.ML@d50f0cb67578
child 32645 1cc5b24f5a01
permissions -rw-r--r--
misc changes to SOS by Philipp Meyer:
CSDP_EXE as central setting;
separate component src/HOL/Library/Sum_Of_Squares;
misc tuning and rearrangement of neos_csdp_client;
more robust treatment of shell paths;
debugging depends on local flag;
removed unused parts;
     1 (* Title:      sum_of_squares.ML
     2    Authors:    Amine Chaieb, University of Cambridge
     3                Philipp Meyer, TU Muenchen
     4 
     5 A tactic for proving nonlinear inequalities
     6 *)
     7 
     8 signature SOS =
     9 sig
    10 
    11   val sos_tac : (string -> string) -> Proof.context -> int -> Tactical.tactic
    12 
    13   val debugging : bool ref;
    14   
    15   exception Failure of string;
    16 end
    17 
    18 structure Sos : SOS = 
    19 struct
    20 
    21 val rat_0 = Rat.zero;
    22 val rat_1 = Rat.one;
    23 val rat_2 = Rat.two;
    24 val rat_10 = Rat.rat_of_int 10;
    25 val rat_1_2 = rat_1 // rat_2;
    26 val max = curry IntInf.max;
    27 val min = curry IntInf.min;
    28 
    29 val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
    30 val numerator_rat = Rat.quotient_of_rat #> fst #> Rat.rat_of_int;
    31 fun int_of_rat a = 
    32     case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
    33 fun lcm_rat x y = Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
    34 
    35 fun rat_pow r i = 
    36  let fun pow r i = 
    37    if i = 0 then rat_1 else 
    38    let val d = pow r (i div 2)
    39    in d */ d */ (if i mod 2 = 0 then rat_1 else r)
    40    end
    41  in if i < 0 then pow (Rat.inv r) (~ i) else pow r i end;
    42 
    43 fun round_rat r = 
    44  let val (a,b) = Rat.quotient_of_rat (Rat.abs r)
    45      val d = a div b
    46      val s = if r </ rat_0 then (Rat.neg o Rat.rat_of_int) else Rat.rat_of_int
    47      val x2 = 2 * (a - (b * d))
    48  in s (if x2 >= b then d + 1 else d) end
    49 
    50 val abs_rat = Rat.abs;
    51 val pow2 = rat_pow rat_2;
    52 val pow10 = rat_pow rat_10;
    53 
    54 val debugging = ref false;
    55 
    56 exception Sanity;
    57 
    58 exception Unsolvable;
    59 
    60 exception Failure of string;
    61 
    62 (* Turn a rational into a decimal string with d sig digits.                  *)
    63 
    64 local
    65 fun normalize y =
    66   if abs_rat y </ (rat_1 // rat_10) then normalize (rat_10 */ y) - 1
    67   else if abs_rat y >=/ rat_1 then normalize (y // rat_10) + 1
    68   else 0 
    69  in
    70 fun decimalize d x =
    71   if x =/ rat_0 then "0.0" else
    72   let 
    73    val y = Rat.abs x
    74    val e = normalize y
    75    val z = pow10(~ e) */ y +/ rat_1
    76    val k = int_of_rat (round_rat(pow10 d */ z))
    77   in (if x </ rat_0 then "-0." else "0.") ^
    78      implode(tl(explode(string_of_int k))) ^
    79      (if e = 0 then "" else "e"^string_of_int e)
    80   end
    81 end;
    82 
    83 (* Iterations over numbers, and lists indexed by numbers.                    *)
    84 
    85 fun itern k l f a =
    86   case l of
    87     [] => a
    88   | h::t => itern (k + 1) t f (f h k a);
    89 
    90 fun iter (m,n) f a =
    91   if n < m then a
    92   else iter (m+1,n) f (f m a);
    93 
    94 (* The main types.                                                           *)
    95 
    96 fun strict_ord ord (x,y) = case ord (x,y) of LESS => LESS | _ => GREATER
    97 
    98 structure Intpairfunc = FuncFun(type key = int*int val ord = prod_ord int_ord int_ord);
    99 
   100 type vector = int* Rat.rat Intfunc.T;
   101 
   102 type matrix = (int*int)*(Rat.rat Intpairfunc.T);
   103 
   104 type monomial = int Ctermfunc.T;
   105 
   106 val cterm_ord = (fn (s,t) => TermOrd.fast_term_ord(term_of s, term_of t))
   107  fun monomial_ord (m1,m2) = list_ord (prod_ord cterm_ord int_ord) (Ctermfunc.graph m1, Ctermfunc.graph m2)
   108 structure Monomialfunc = FuncFun(type key = monomial val ord = monomial_ord)
   109 
   110 type poly = Rat.rat Monomialfunc.T;
   111 
   112  fun iszero (k,r) = r =/ rat_0;
   113 
   114 fun fold_rev2 f l1 l2 b =
   115   case (l1,l2) of
   116     ([],[]) => b
   117   | (h1::t1,h2::t2) => f h1 h2 (fold_rev2 f t1 t2 b)
   118   | _ => error "fold_rev2";
   119  
   120 (* Vectors. Conventionally indexed 1..n.                                     *)
   121 
   122 fun vector_0 n = (n,Intfunc.undefined):vector;
   123 
   124 fun dim (v:vector) = fst v;
   125 
   126 fun vector_const c n =
   127   if c =/ rat_0 then vector_0 n
   128   else (n,fold_rev (fn k => Intfunc.update (k,c)) (1 upto n) Intfunc.undefined) :vector;
   129 
   130 val vector_1 = vector_const rat_1;
   131 
   132 fun vector_cmul c (v:vector) =
   133  let val n = dim v 
   134  in if c =/ rat_0 then vector_0 n
   135     else (n,Intfunc.mapf (fn x => c */ x) (snd v))
   136  end;
   137 
   138 fun vector_neg (v:vector) = (fst v,Intfunc.mapf Rat.neg (snd v)) :vector;
   139 
   140 fun vector_add (v1:vector) (v2:vector) =
   141  let val m = dim v1  
   142      val n = dim v2 
   143  in if m <> n then error "vector_add: incompatible dimensions"
   144     else (n,Intfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd v1) (snd v2)) :vector 
   145  end;
   146 
   147 fun vector_sub v1 v2 = vector_add v1 (vector_neg v2);
   148 
   149 fun vector_dot (v1:vector) (v2:vector) =
   150  let val m = dim v1 
   151      val n = dim v2 
   152  in if m <> n then error "vector_dot: incompatible dimensions" 
   153     else Intfunc.fold (fn (i,x) => fn a => x +/ a) 
   154         (Intfunc.combine (curry op */) (fn x => x =/ rat_0) (snd v1) (snd v2)) rat_0
   155  end;
   156 
   157 fun vector_of_list l =
   158  let val n = length l 
   159  in (n,fold_rev2 (curry Intfunc.update) (1 upto n) l Intfunc.undefined) :vector
   160  end;
   161 
   162 (* Matrices; again rows and columns indexed from 1.                          *)
   163 
   164 fun matrix_0 (m,n) = ((m,n),Intpairfunc.undefined):matrix;
   165 
   166 fun dimensions (m:matrix) = fst m;
   167 
   168 fun matrix_const c (mn as (m,n)) =
   169   if m <> n then error "matrix_const: needs to be square"
   170   else if c =/ rat_0 then matrix_0 mn
   171   else (mn,fold_rev (fn k => Intpairfunc.update ((k,k), c)) (1 upto n) Intpairfunc.undefined) :matrix;;
   172 
   173 val matrix_1 = matrix_const rat_1;
   174 
   175 fun matrix_cmul c (m:matrix) =
   176  let val (i,j) = dimensions m 
   177  in if c =/ rat_0 then matrix_0 (i,j)
   178     else ((i,j),Intpairfunc.mapf (fn x => c */ x) (snd m))
   179  end;
   180 
   181 fun matrix_neg (m:matrix) = 
   182   (dimensions m, Intpairfunc.mapf Rat.neg (snd m)) :matrix;
   183 
   184 fun matrix_add (m1:matrix) (m2:matrix) =
   185  let val d1 = dimensions m1 
   186      val d2 = dimensions m2 
   187  in if d1 <> d2 
   188      then error "matrix_add: incompatible dimensions"
   189     else (d1,Intpairfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd m1) (snd m2)) :matrix
   190  end;;
   191 
   192 fun matrix_sub m1 m2 = matrix_add m1 (matrix_neg m2);
   193 
   194 fun row k (m:matrix) =
   195  let val (i,j) = dimensions m 
   196  in (j,
   197    Intpairfunc.fold (fn ((i,j), c) => fn a => if i = k then Intfunc.update (j,c) a else a) (snd m) Intfunc.undefined ) : vector
   198  end;
   199 
   200 fun column k (m:matrix) =
   201   let val (i,j) = dimensions m 
   202   in (i,
   203    Intpairfunc.fold (fn ((i,j), c) => fn a => if j = k then Intfunc.update (i,c) a else a) (snd m)  Intfunc.undefined)
   204    : vector
   205  end;
   206 
   207 fun transp (m:matrix) =
   208   let val (i,j) = dimensions m 
   209   in
   210   ((j,i),Intpairfunc.fold (fn ((i,j), c) => fn a => Intpairfunc.update ((j,i), c) a) (snd m) Intpairfunc.undefined) :matrix
   211  end;
   212 
   213 fun diagonal (v:vector) =
   214  let val n = dim v 
   215  in ((n,n),Intfunc.fold (fn (i, c) => fn a => Intpairfunc.update ((i,i), c) a) (snd v) Intpairfunc.undefined) : matrix
   216  end;
   217 
   218 fun matrix_of_list l =
   219  let val m = length l 
   220  in if m = 0 then matrix_0 (0,0) else
   221    let val n = length (hd l) 
   222    in ((m,n),itern 1 l (fn v => fn i => itern 1 v (fn c => fn j => Intpairfunc.update ((i,j), c))) Intpairfunc.undefined)
   223    end
   224  end;
   225 
   226 (* Monomials.                                                                *)
   227 
   228 fun monomial_eval assig (m:monomial) =
   229   Ctermfunc.fold (fn (x, k) => fn a => a */ rat_pow (Ctermfunc.apply assig x) k)
   230         m rat_1;
   231 val monomial_1 = (Ctermfunc.undefined:monomial);
   232 
   233 fun monomial_var x = Ctermfunc.onefunc (x, 1) :monomial;
   234 
   235 val (monomial_mul:monomial->monomial->monomial) =
   236   Ctermfunc.combine (curry op +) (K false);
   237 
   238 fun monomial_pow (m:monomial) k =
   239   if k = 0 then monomial_1
   240   else Ctermfunc.mapf (fn x => k * x) m;
   241 
   242 fun monomial_divides (m1:monomial) (m2:monomial) =
   243   Ctermfunc.fold (fn (x, k) => fn a => Ctermfunc.tryapplyd m2 x 0 >= k andalso a) m1 true;;
   244 
   245 fun monomial_div (m1:monomial) (m2:monomial) =
   246  let val m = Ctermfunc.combine (curry op +) 
   247    (fn x => x = 0) m1 (Ctermfunc.mapf (fn x => ~ x) m2) 
   248  in if Ctermfunc.fold (fn (x, k) => fn a => k >= 0 andalso a) m true then m
   249   else error "monomial_div: non-divisible"
   250  end;
   251 
   252 fun monomial_degree x (m:monomial) = 
   253   Ctermfunc.tryapplyd m x 0;;
   254 
   255 fun monomial_lcm (m1:monomial) (m2:monomial) =
   256   fold_rev (fn x => Ctermfunc.update (x, max (monomial_degree x m1) (monomial_degree x m2)))
   257           (gen_union (is_equal o  cterm_ord) (Ctermfunc.dom m1, Ctermfunc.dom m2)) (Ctermfunc.undefined :monomial);
   258 
   259 fun monomial_multidegree (m:monomial) = 
   260  Ctermfunc.fold (fn (x, k) => fn a => k + a) m 0;;
   261 
   262 fun monomial_variables m = Ctermfunc.dom m;;
   263 
   264 (* Polynomials.                                                              *)
   265 
   266 fun eval assig (p:poly) =
   267   Monomialfunc.fold (fn (m, c) => fn a => a +/ c */ monomial_eval assig m) p rat_0;
   268 
   269 val poly_0 = (Monomialfunc.undefined:poly);
   270 
   271 fun poly_isconst (p:poly) = 
   272   Monomialfunc.fold (fn (m, c) => fn a => Ctermfunc.is_undefined m andalso a) p true;
   273 
   274 fun poly_var x = Monomialfunc.onefunc (monomial_var x,rat_1) :poly;
   275 
   276 fun poly_const c =
   277   if c =/ rat_0 then poly_0 else Monomialfunc.onefunc(monomial_1, c);
   278 
   279 fun poly_cmul c (p:poly) =
   280   if c =/ rat_0 then poly_0
   281   else Monomialfunc.mapf (fn x => c */ x) p;
   282 
   283 fun poly_neg (p:poly) = (Monomialfunc.mapf Rat.neg p :poly);;
   284 
   285 fun poly_add (p1:poly) (p2:poly) =
   286   (Monomialfunc.combine (curry op +/) (fn x => x =/ rat_0) p1 p2 :poly);
   287 
   288 fun poly_sub p1 p2 = poly_add p1 (poly_neg p2);
   289 
   290 fun poly_cmmul (c,m) (p:poly) =
   291  if c =/ rat_0 then poly_0
   292  else if Ctermfunc.is_undefined m 
   293       then Monomialfunc.mapf (fn d => c */ d) p
   294       else Monomialfunc.fold (fn (m', d) => fn a => (Monomialfunc.update (monomial_mul m m', c */ d) a)) p poly_0;
   295 
   296 fun poly_mul (p1:poly) (p2:poly) =
   297   Monomialfunc.fold (fn (m, c) => fn a => poly_add (poly_cmmul (c,m) p2) a) p1 poly_0;
   298 
   299 fun poly_div (p1:poly) (p2:poly) =
   300  if not(poly_isconst p2) 
   301  then error "poly_div: non-constant" else
   302  let val c = eval Ctermfunc.undefined p2 
   303  in if c =/ rat_0 then error "poly_div: division by zero"
   304     else poly_cmul (Rat.inv c) p1
   305  end;
   306 
   307 fun poly_square p = poly_mul p p;
   308 
   309 fun poly_pow p k =
   310  if k = 0 then poly_const rat_1
   311  else if k = 1 then p
   312  else let val q = poly_square(poly_pow p (k div 2)) in
   313       if k mod 2 = 1 then poly_mul p q else q end;
   314 
   315 fun poly_exp p1 p2 =
   316   if not(poly_isconst p2) 
   317   then error "poly_exp: not a constant" 
   318   else poly_pow p1 (int_of_rat (eval Ctermfunc.undefined p2));
   319 
   320 fun degree x (p:poly) = 
   321  Monomialfunc.fold (fn (m,c) => fn a => max (monomial_degree x m) a) p 0;
   322 
   323 fun multidegree (p:poly) =
   324   Monomialfunc.fold (fn (m, c) => fn a => max (monomial_multidegree m) a) p 0;
   325 
   326 fun poly_variables (p:poly) =
   327   sort cterm_ord (Monomialfunc.fold_rev (fn (m, c) => curry (gen_union (is_equal o  cterm_ord)) (monomial_variables m)) p []);;
   328 
   329 (* Order monomials for human presentation.                                   *)
   330 
   331 fun cterm_ord (t,t') = TermOrd.fast_term_ord (term_of t, term_of t');
   332 
   333 val humanorder_varpow = prod_ord cterm_ord (rev_order o int_ord);
   334 
   335 local
   336  fun ord (l1,l2) = case (l1,l2) of
   337   (_,[]) => LESS 
   338  | ([],_) => GREATER
   339  | (h1::t1,h2::t2) => 
   340    (case humanorder_varpow (h1, h2) of 
   341      LESS => LESS
   342    | EQUAL => ord (t1,t2)
   343    | GREATER => GREATER)
   344 in fun humanorder_monomial m1 m2 = 
   345  ord (sort humanorder_varpow (Ctermfunc.graph m1),
   346   sort humanorder_varpow (Ctermfunc.graph m2))
   347 end;
   348 
   349 fun fold1 f l =  case l of
   350    []     => error "fold1"
   351  | [x]    => x
   352  | (h::t) => f h (fold1 f t);
   353 
   354 (* Conversions to strings.                                                   *)
   355 
   356 fun string_of_vector min_size max_size (v:vector) =
   357  let val n_raw = dim v 
   358  in if n_raw = 0 then "[]" else
   359   let 
   360    val n = max min_size (min n_raw max_size) 
   361    val xs = map (Rat.string_of_rat o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n) 
   362   in "[" ^ fold1 (fn s => fn t => s ^ ", " ^ t) xs ^
   363   (if n_raw > max_size then ", ...]" else "]")
   364   end
   365  end;
   366 
   367 fun string_of_matrix max_size (m:matrix) =
   368  let 
   369   val (i_raw,j_raw) = dimensions m
   370   val i = min max_size i_raw 
   371   val j = min max_size j_raw
   372   val rstr = map (fn k => string_of_vector j j (row k m)) (1 upto i) 
   373  in "["^ fold1 (fn s => fn t => s^";\n "^t) rstr ^
   374   (if j > max_size then "\n ...]" else "]")
   375  end;
   376 
   377 fun string_of_term t = 
   378  case t of
   379    a$b => "("^(string_of_term a)^" "^(string_of_term b)^")"
   380  | Abs x => 
   381     let val (xn, b) = Term.dest_abs x
   382     in "(\\"^xn^"."^(string_of_term b)^")"
   383     end
   384  | Const(s,_) => s
   385  | Free (s,_) => s
   386  | Var((s,_),_) => s
   387  | _ => error "string_of_term";
   388 
   389 val string_of_cterm = string_of_term o term_of;
   390 
   391 fun string_of_varpow x k =
   392   if k = 1 then string_of_cterm x 
   393   else string_of_cterm x^"^"^string_of_int k;
   394 
   395 fun string_of_monomial m =
   396  if Ctermfunc.is_undefined m then "1" else
   397  let val vps = fold_rev (fn (x,k) => fn a => string_of_varpow x k :: a)
   398   (sort humanorder_varpow (Ctermfunc.graph m)) [] 
   399  in fold1 (fn s => fn t => s^"*"^t) vps
   400  end;
   401 
   402 fun string_of_cmonomial (c,m) =
   403  if Ctermfunc.is_undefined m then Rat.string_of_rat c
   404  else if c =/ rat_1 then string_of_monomial m
   405  else Rat.string_of_rat c ^ "*" ^ string_of_monomial m;;
   406 
   407 fun string_of_poly (p:poly) =
   408  if Monomialfunc.is_undefined p then "<<0>>" else
   409  let 
   410   val cms = sort (fn ((m1,_),(m2,_)) => humanorder_monomial m1  m2) (Monomialfunc.graph p)
   411   val s = fold (fn (m,c) => fn a =>
   412              if c </ rat_0 then a ^ " - " ^ string_of_cmonomial(Rat.neg c,m)
   413              else a ^ " + " ^ string_of_cmonomial(c,m))
   414           cms ""
   415   val s1 = String.substring (s, 0, 3)
   416   val s2 = String.substring (s, 3, String.size s - 3) 
   417  in "<<" ^(if s1 = " + " then s2 else "-"^s2)^">>"
   418  end;
   419 
   420 (* Conversion from HOL term.                                                 *)
   421 
   422 local
   423  val neg_tm = @{cterm "uminus :: real => _"}
   424  val add_tm = @{cterm "op + :: real => _"}
   425  val sub_tm = @{cterm "op - :: real => _"}
   426  val mul_tm = @{cterm "op * :: real => _"}
   427  val inv_tm = @{cterm "inverse :: real => _"}
   428  val div_tm = @{cterm "op / :: real => _"}
   429  val pow_tm = @{cterm "op ^ :: real => _"}
   430  val zero_tm = @{cterm "0:: real"}
   431  val is_numeral = can (HOLogic.dest_number o term_of)
   432  fun is_comb t = case t of _$_ => true | _ => false
   433  fun poly_of_term tm =
   434   if tm aconvc zero_tm then poly_0
   435   else if RealArith.is_ratconst tm 
   436        then poly_const(RealArith.dest_ratconst tm)
   437   else 
   438   (let val (lop,r) = Thm.dest_comb tm
   439    in if lop aconvc neg_tm then poly_neg(poly_of_term r)
   440       else if lop aconvc inv_tm then
   441        let val p = poly_of_term r 
   442        in if poly_isconst p 
   443           then poly_const(Rat.inv (eval Ctermfunc.undefined p))
   444           else error "poly_of_term: inverse of non-constant polyomial"
   445        end
   446    else (let val (opr,l) = Thm.dest_comb lop
   447          in 
   448           if opr aconvc pow_tm andalso is_numeral r 
   449           then poly_pow (poly_of_term l) ((snd o HOLogic.dest_number o term_of) r)
   450           else if opr aconvc add_tm 
   451            then poly_add (poly_of_term l) (poly_of_term r)
   452           else if opr aconvc sub_tm 
   453            then poly_sub (poly_of_term l) (poly_of_term r)
   454           else if opr aconvc mul_tm 
   455            then poly_mul (poly_of_term l) (poly_of_term r)
   456           else if opr aconvc div_tm 
   457            then let 
   458                   val p = poly_of_term l 
   459                   val q = poly_of_term r 
   460                 in if poly_isconst q then poly_cmul (Rat.inv (eval Ctermfunc.undefined q)) p
   461                    else error "poly_of_term: division by non-constant polynomial"
   462                 end
   463           else poly_var tm
   464  
   465          end
   466          handle CTERM ("dest_comb",_) => poly_var tm)
   467    end
   468    handle CTERM ("dest_comb",_) => poly_var tm)
   469 in
   470 val poly_of_term = fn tm =>
   471  if type_of (term_of tm) = @{typ real} then poly_of_term tm
   472  else error "poly_of_term: term does not have real type"
   473 end;
   474 
   475 (* String of vector (just a list of space-separated numbers).                *)
   476 
   477 fun sdpa_of_vector (v:vector) =
   478  let 
   479   val n = dim v
   480   val strs = map (decimalize 20 o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n) 
   481  in fold1 (fn x => fn y => x ^ " " ^ y) strs ^ "\n"
   482  end;
   483 
   484 fun increasing f ord (x,y) = ord (f x, f y);
   485 fun triple_int_ord ((a,b,c),(a',b',c')) = 
   486  prod_ord int_ord (prod_ord int_ord int_ord) 
   487     ((a,(b,c)),(a',(b',c')));
   488 structure Inttriplefunc = FuncFun(type key = int*int*int val ord = triple_int_ord);
   489 
   490 (* String for block diagonal matrix numbered k.                              *)
   491 
   492 fun sdpa_of_blockdiagonal k m =
   493  let 
   494   val pfx = string_of_int k ^" "
   495   val ents =
   496     Inttriplefunc.fold (fn ((b,i,j), c) => fn a => if i > j then a else ((b,i,j),c)::a) m []
   497   val entss = sort (increasing fst triple_int_ord ) ents
   498  in  fold_rev (fn ((b,i,j),c) => fn a =>
   499      pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
   500      " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
   501  end;
   502 
   503 (* String for a matrix numbered k, in SDPA sparse format.                    *)
   504 
   505 fun sdpa_of_matrix k (m:matrix) =
   506  let 
   507   val pfx = string_of_int k ^ " 1 "
   508   val ms = Intpairfunc.fold (fn ((i,j), c) => fn  a => if i > j then a else ((i,j),c)::a) (snd m) [] 
   509   val mss = sort (increasing fst (prod_ord int_ord int_ord)) ms 
   510  in fold_rev (fn ((i,j),c) => fn a =>
   511      pfx ^ string_of_int i ^ " " ^ string_of_int j ^
   512      " " ^ decimalize 20 c ^ "\n" ^ a) mss ""
   513  end;;
   514 
   515 (* ------------------------------------------------------------------------- *)
   516 (* String in SDPA sparse format for standard SDP problem:                    *)
   517 (*                                                                           *)
   518 (*    X = v_1 * [M_1] + ... + v_m * [M_m] - [M_0] must be PSD                *)
   519 (*    Minimize obj_1 * v_1 + ... obj_m * v_m                                 *)
   520 (* ------------------------------------------------------------------------- *)
   521 
   522 fun sdpa_of_problem obj mats =
   523  let 
   524   val m = length mats - 1
   525   val (n,_) = dimensions (hd mats) 
   526  in
   527   string_of_int m ^ "\n" ^
   528   "1\n" ^
   529   string_of_int n ^ "\n" ^
   530   sdpa_of_vector obj ^
   531   fold_rev2 (fn k => fn m => fn a => sdpa_of_matrix (k - 1) m ^ a) (1 upto length mats) mats ""
   532  end;
   533 
   534 fun index_char str chr pos =
   535   if pos >= String.size str then ~1
   536   else if String.sub(str,pos) = chr then pos
   537   else index_char str chr (pos + 1);
   538 fun rat_of_quotient (a,b) = if b = 0 then rat_0 else Rat.rat_of_quotient (a,b);
   539 fun rat_of_string s = 
   540  let val n = index_char s #"/" 0 in
   541   if n = ~1 then s |> IntInf.fromString |> valOf |> Rat.rat_of_int
   542   else 
   543    let val SOME numer = IntInf.fromString(String.substring(s,0,n))
   544        val SOME den = IntInf.fromString (String.substring(s,n+1,String.size s - n - 1))
   545    in rat_of_quotient(numer, den)
   546    end
   547  end;
   548 
   549 fun isspace x = x = " " ;
   550 fun isnum x = x mem_string ["0","1","2","3","4","5","6","7","8","9"]
   551 
   552 (* More parser basics.                                                       *)
   553 
   554 local
   555  open Scan
   556 in 
   557  val word = this_string
   558  fun token s =
   559   repeat ($$ " ") |-- word s --| repeat ($$ " ")
   560  val numeral = one isnum
   561  val decimalint = bulk numeral >> (rat_of_string o implode)
   562  val decimalfrac = bulk numeral
   563     >> (fn s => rat_of_string(implode s) // pow10 (length s))
   564  val decimalsig =
   565     decimalint -- option (Scan.$$ "." |-- decimalfrac)
   566     >> (fn (h,NONE) => h | (h,SOME x) => h +/ x)
   567  fun signed prs =
   568        $$ "-" |-- prs >> Rat.neg 
   569     || $$ "+" |-- prs
   570     || prs;
   571 
   572 fun emptyin def xs = if null xs then (def,xs) else Scan.fail xs
   573 
   574  val exponent = ($$ "e" || $$ "E") |-- signed decimalint;
   575 
   576  val decimal = signed decimalsig -- (emptyin rat_0|| exponent)
   577     >> (fn (h, x) => h */ pow10 (int_of_rat x));
   578 end;
   579 
   580  fun mkparser p s =
   581   let val (x,rst) = p (explode s) 
   582   in if null rst then x 
   583      else error "mkparser: unparsed input"
   584   end;;
   585 
   586 (* Parse back csdp output.                                                      *)
   587 
   588  fun ignore inp = ((),[])
   589  fun csdpoutput inp =  ((decimal -- Scan.bulk (Scan.$$ " " |-- Scan.option decimal) >> (fn (h,to) => map_filter I ((SOME h)::to))) --| ignore >> vector_of_list) inp
   590  val parse_csdpoutput = mkparser csdpoutput
   591 
   592 (* Run prover on a problem in linear form.                       *)
   593 
   594 fun run_problem prover obj mats =
   595   parse_csdpoutput (prover (sdpa_of_problem obj mats))
   596 
   597 (* Try some apparently sensible scaling first. Note that this is purely to   *)
   598 (* get a cleaner translation to floating-point, and doesn't affect any of    *)
   599 (* the results, in principle. In practice it seems a lot better when there   *)
   600 (* are extreme numbers in the original problem.                              *)
   601 
   602   (* Version for (int*int) keys *)
   603 local
   604   fun max_rat x y = if x </ y then y else x
   605   fun common_denominator fld amat acc =
   606       fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
   607   fun maximal_element fld amat acc =
   608     fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc 
   609 fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
   610                      in Real.fromLargeInt a / Real.fromLargeInt b end;
   611 in
   612 
   613 fun pi_scale_then solver (obj:vector)  mats =
   614  let 
   615   val cd1 = fold_rev (common_denominator Intpairfunc.fold) mats (rat_1)
   616   val cd2 = common_denominator Intfunc.fold (snd obj)  (rat_1) 
   617   val mats' = map (Intpairfunc.mapf (fn x => cd1 */ x)) mats
   618   val obj' = vector_cmul cd2 obj
   619   val max1 = fold_rev (maximal_element Intpairfunc.fold) mats' (rat_0)
   620   val max2 = maximal_element Intfunc.fold (snd obj') (rat_0) 
   621   val scal1 = pow2 (20 - trunc(Math.ln (float_of_rat max1) / Math.ln 2.0))
   622   val scal2 = pow2 (20 - trunc(Math.ln (float_of_rat max2) / Math.ln 2.0)) 
   623   val mats'' = map (Intpairfunc.mapf (fn x => x */ scal1)) mats'
   624   val obj'' = vector_cmul scal2 obj' 
   625  in solver obj'' mats''
   626   end
   627 end;
   628 
   629 (* Try some apparently sensible scaling first. Note that this is purely to   *)
   630 (* get a cleaner translation to floating-point, and doesn't affect any of    *)
   631 (* the results, in principle. In practice it seems a lot better when there   *)
   632 (* are extreme numbers in the original problem.                              *)
   633 
   634   (* Version for (int*int*int) keys *)
   635 local
   636   fun max_rat x y = if x </ y then y else x
   637   fun common_denominator fld amat acc =
   638       fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
   639   fun maximal_element fld amat acc =
   640     fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc 
   641 fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
   642                      in Real.fromLargeInt a / Real.fromLargeInt b end;
   643 fun int_of_float x = (trunc x handle Overflow => 0 | Domain => 0)
   644 in
   645 
   646 fun tri_scale_then solver (obj:vector)  mats =
   647  let 
   648   val cd1 = fold_rev (common_denominator Inttriplefunc.fold) mats (rat_1)
   649   val cd2 = common_denominator Intfunc.fold (snd obj)  (rat_1) 
   650   val mats' = map (Inttriplefunc.mapf (fn x => cd1 */ x)) mats
   651   val obj' = vector_cmul cd2 obj
   652   val max1 = fold_rev (maximal_element Inttriplefunc.fold) mats' (rat_0)
   653   val max2 = maximal_element Intfunc.fold (snd obj') (rat_0) 
   654   val scal1 = pow2 (20 - int_of_float(Math.ln (float_of_rat max1) / Math.ln 2.0))
   655   val scal2 = pow2 (20 - int_of_float(Math.ln (float_of_rat max2) / Math.ln 2.0)) 
   656   val mats'' = map (Inttriplefunc.mapf (fn x => x */ scal1)) mats'
   657   val obj'' = vector_cmul scal2 obj' 
   658  in solver obj'' mats''
   659   end
   660 end;
   661 
   662 (* Round a vector to "nice" rationals.                                       *)
   663 
   664 fun nice_rational n x = round_rat (n */ x) // n;;
   665 fun nice_vector n ((d,v) : vector) = 
   666  (d, Intfunc.fold (fn (i,c) => fn a => 
   667    let val y = nice_rational n c 
   668    in if c =/ rat_0 then a 
   669       else Intfunc.update (i,y) a end) v Intfunc.undefined):vector
   670 
   671 fun dest_ord f x = is_equal (f x);
   672 
   673 (* Stuff for "equations" ((int*int*int)->num functions).                         *)
   674 
   675 fun tri_equation_cmul c eq =
   676   if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
   677 
   678 fun tri_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
   679 
   680 fun tri_equation_eval assig eq =
   681  let fun value v = Inttriplefunc.apply assig v 
   682  in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
   683  end;
   684 
   685 (* Eliminate among linear equations: return unconstrained variables and      *)
   686 (* assignments for the others in terms of them. We give one pseudo-variable  *)
   687 (* "one" that's used for a constant term.                                    *)
   688 
   689 local
   690   fun extract_first p l = case l of  (* FIXME : use find_first instead *)
   691    [] => error "extract_first"
   692  | h::t => if p h then (h,t) else
   693           let val (k,s) = extract_first p t in (k,h::s) end
   694 fun eliminate vars dun eqs = case vars of 
   695   [] => if forall Inttriplefunc.is_undefined eqs then dun
   696         else raise Unsolvable
   697  | v::vs =>
   698   ((let 
   699     val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs 
   700     val a = Inttriplefunc.apply eq v
   701     val eq' = tri_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
   702     fun elim e =
   703      let val b = Inttriplefunc.tryapplyd e v rat_0 
   704      in if b =/ rat_0 then e else
   705         tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
   706      end
   707    in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
   708    end)
   709   handle Failure _ => eliminate vs dun eqs)
   710 in
   711 fun tri_eliminate_equations one vars eqs =
   712  let 
   713   val assig = eliminate vars Inttriplefunc.undefined eqs
   714   val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   715   in (distinct (dest_ord triple_int_ord) vs, assig)
   716   end
   717 end;
   718 
   719 (* Eliminate all variables, in an essentially arbitrary order.               *)
   720 
   721 fun tri_eliminate_all_equations one =
   722  let 
   723   fun choose_variable eq =
   724    let val (v,_) = Inttriplefunc.choose eq 
   725    in if is_equal (triple_int_ord(v,one)) then
   726       let val eq' = Inttriplefunc.undefine v eq 
   727       in if Inttriplefunc.is_undefined eq' then error "choose_variable" 
   728          else fst (Inttriplefunc.choose eq')
   729       end
   730     else v 
   731    end
   732   fun eliminate dun eqs = case eqs of 
   733     [] => dun
   734   | eq::oeqs =>
   735     if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
   736     let val v = choose_variable eq
   737         val a = Inttriplefunc.apply eq v
   738         val eq' = tri_equation_cmul ((Rat.rat_of_int ~1) // a) 
   739                    (Inttriplefunc.undefine v eq)
   740         fun elim e =
   741          let val b = Inttriplefunc.tryapplyd e v rat_0 
   742          in if b =/ rat_0 then e 
   743             else tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
   744          end
   745     in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun)) 
   746                  (map elim oeqs) 
   747     end
   748 in fn eqs =>
   749  let 
   750   val assig = eliminate Inttriplefunc.undefined eqs
   751   val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   752  in (distinct (dest_ord triple_int_ord) vs,assig)
   753  end
   754 end;
   755  
   756 (* Solve equations by assigning arbitrary numbers.                           *)
   757 
   758 fun tri_solve_equations one eqs =
   759  let 
   760   val (vars,assigs) = tri_eliminate_all_equations one eqs
   761   val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars 
   762             (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
   763   val ass =
   764     Inttriplefunc.combine (curry op +/) (K false) 
   765     (Inttriplefunc.mapf (tri_equation_eval vfn) assigs) vfn 
   766  in if forall (fn e => tri_equation_eval ass e =/ rat_0) eqs
   767     then Inttriplefunc.undefine one ass else raise Sanity
   768  end;
   769 
   770 (* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
   771 
   772 fun tri_epoly_pmul p q acc =
   773  Monomialfunc.fold (fn (m1, c) => fn a =>
   774   Monomialfunc.fold (fn (m2,e) => fn b =>
   775    let val m =  monomial_mul m1 m2
   776        val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined 
   777    in Monomialfunc.update (m,tri_equation_add (tri_equation_cmul c e) es) b 
   778    end) q a) p acc ;
   779 
   780 (* Usual operations on equation-parametrized poly.                           *)
   781 
   782 fun tri_epoly_cmul c l =
   783   if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (tri_equation_cmul c) l;;
   784 
   785 val tri_epoly_neg = tri_epoly_cmul (Rat.rat_of_int ~1);
   786 
   787 val tri_epoly_add = Inttriplefunc.combine tri_equation_add Inttriplefunc.is_undefined;
   788 
   789 fun tri_epoly_sub p q = tri_epoly_add p (tri_epoly_neg q);;
   790 
   791 (* Stuff for "equations" ((int*int)->num functions).                         *)
   792 
   793 fun pi_equation_cmul c eq =
   794   if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
   795 
   796 fun pi_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
   797 
   798 fun pi_equation_eval assig eq =
   799  let fun value v = Inttriplefunc.apply assig v 
   800  in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
   801  end;
   802 
   803 (* Eliminate among linear equations: return unconstrained variables and      *)
   804 (* assignments for the others in terms of them. We give one pseudo-variable  *)
   805 (* "one" that's used for a constant term.                                    *)
   806 
   807 local
   808 fun extract_first p l = case l of 
   809    [] => error "extract_first"
   810  | h::t => if p h then (h,t) else
   811           let val (k,s) = extract_first p t in (k,h::s) end
   812 fun eliminate vars dun eqs = case vars of 
   813   [] => if forall Inttriplefunc.is_undefined eqs then dun
   814         else raise Unsolvable
   815  | v::vs =>
   816    let 
   817     val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs 
   818     val a = Inttriplefunc.apply eq v
   819     val eq' = pi_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
   820     fun elim e =
   821      let val b = Inttriplefunc.tryapplyd e v rat_0 
   822      in if b =/ rat_0 then e else
   823         pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
   824      end
   825    in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
   826    end
   827   handle Failure _ => eliminate vs dun eqs
   828 in
   829 fun pi_eliminate_equations one vars eqs =
   830  let 
   831   val assig = eliminate vars Inttriplefunc.undefined eqs
   832   val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   833   in (distinct (dest_ord triple_int_ord) vs, assig)
   834   end
   835 end;
   836 
   837 (* Eliminate all variables, in an essentially arbitrary order.               *)
   838 
   839 fun pi_eliminate_all_equations one =
   840  let 
   841   fun choose_variable eq =
   842    let val (v,_) = Inttriplefunc.choose eq 
   843    in if is_equal (triple_int_ord(v,one)) then
   844       let val eq' = Inttriplefunc.undefine v eq 
   845       in if Inttriplefunc.is_undefined eq' then error "choose_variable" 
   846          else fst (Inttriplefunc.choose eq')
   847       end
   848     else v 
   849    end
   850   fun eliminate dun eqs = case eqs of 
   851     [] => dun
   852   | eq::oeqs =>
   853     if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
   854     let val v = choose_variable eq
   855         val a = Inttriplefunc.apply eq v
   856         val eq' = pi_equation_cmul ((Rat.rat_of_int ~1) // a) 
   857                    (Inttriplefunc.undefine v eq)
   858         fun elim e =
   859          let val b = Inttriplefunc.tryapplyd e v rat_0 
   860          in if b =/ rat_0 then e 
   861             else pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
   862          end
   863     in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun)) 
   864                  (map elim oeqs) 
   865     end
   866 in fn eqs =>
   867  let 
   868   val assig = eliminate Inttriplefunc.undefined eqs
   869   val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
   870  in (distinct (dest_ord triple_int_ord) vs,assig)
   871  end
   872 end;
   873  
   874 (* Solve equations by assigning arbitrary numbers.                           *)
   875 
   876 fun pi_solve_equations one eqs =
   877  let 
   878   val (vars,assigs) = pi_eliminate_all_equations one eqs
   879   val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars 
   880             (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
   881   val ass =
   882     Inttriplefunc.combine (curry op +/) (K false) 
   883     (Inttriplefunc.mapf (pi_equation_eval vfn) assigs) vfn 
   884  in if forall (fn e => pi_equation_eval ass e =/ rat_0) eqs
   885     then Inttriplefunc.undefine one ass else raise Sanity
   886  end;
   887 
   888 (* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
   889 
   890 fun pi_epoly_pmul p q acc =
   891  Monomialfunc.fold (fn (m1, c) => fn a =>
   892   Monomialfunc.fold (fn (m2,e) => fn b =>
   893    let val m =  monomial_mul m1 m2
   894        val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined 
   895    in Monomialfunc.update (m,pi_equation_add (pi_equation_cmul c e) es) b 
   896    end) q a) p acc ;
   897 
   898 (* Usual operations on equation-parametrized poly.                           *)
   899 
   900 fun pi_epoly_cmul c l =
   901   if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (pi_equation_cmul c) l;;
   902 
   903 val pi_epoly_neg = pi_epoly_cmul (Rat.rat_of_int ~1);
   904 
   905 val pi_epoly_add = Inttriplefunc.combine pi_equation_add Inttriplefunc.is_undefined;
   906 
   907 fun pi_epoly_sub p q = pi_epoly_add p (pi_epoly_neg q);;
   908 
   909 fun allpairs f l1 l2 =  fold_rev (fn x => (curry (op @)) (map (f x) l2)) l1 [];
   910 
   911 (* Hence produce the "relevant" monomials: those whose squares lie in the    *)
   912 (* Newton polytope of the monomials in the input. (This is enough according  *)
   913 (* to Reznik: "Extremal PSD forms with few terms", Duke Math. Journal,       *)
   914 (* vol 45, pp. 363--374, 1978.                                               *)
   915 (*                                                                           *)
   916 (* These are ordered in sort of decreasing degree. In particular the         *)
   917 (* constant monomial is last; this gives an order in diagonalization of the  *)
   918 (* quadratic form that will tend to display constants.                       *)
   919 
   920 (* Diagonalize (Cholesky/LDU) the matrix corresponding to a quadratic form.  *)
   921 
   922 local
   923 fun diagonalize n i m =
   924  if Intpairfunc.is_undefined (snd m) then [] 
   925  else
   926   let val a11 = Intpairfunc.tryapplyd (snd m) (i,i) rat_0 
   927   in if a11 </ rat_0 then raise Failure "diagonalize: not PSD"
   928     else if a11 =/ rat_0 then
   929           if Intfunc.is_undefined (snd (row i m)) then diagonalize n (i + 1) m
   930           else raise Failure "diagonalize: not PSD ___ "
   931     else
   932      let 
   933       val v = row i m
   934       val v' = (fst v, Intfunc.fold (fn (i, c) => fn a => 
   935        let val y = c // a11 
   936        in if y = rat_0 then a else Intfunc.update (i,y) a 
   937        end)  (snd v) Intfunc.undefined)
   938       fun upt0 x y a = if y = rat_0 then a else Intpairfunc.update (x,y) a
   939       val m' =
   940       ((n,n),
   941       iter (i+1,n) (fn j =>
   942           iter (i+1,n) (fn k =>
   943               (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))))
   944           Intpairfunc.undefined)
   945      in (a11,v')::diagonalize n (i + 1) m' 
   946      end
   947   end
   948 in
   949 fun diag m =
   950  let 
   951    val nn = dimensions m 
   952    val n = fst nn 
   953  in if snd nn <> n then error "diagonalize: non-square matrix" 
   954     else diagonalize n 1 m
   955  end
   956 end;
   957 
   958 fun gcd_rat a b = Rat.rat_of_int (Integer.gcd (int_of_rat a) (int_of_rat b));
   959 
   960 (* Adjust a diagonalization to collect rationals at the start.               *)
   961   (* FIXME : Potentially polymorphic keys, but here only: integers!! *)
   962 local
   963  fun upd0 x y a = if y =/ rat_0 then a else Intfunc.update(x,y) a;
   964  fun mapa f (d,v) = 
   965   (d, Intfunc.fold (fn (i,c) => fn a => upd0 i (f c) a) v Intfunc.undefined)
   966  fun adj (c,l) =
   967  let val a = 
   968   Intfunc.fold (fn (i,c) => fn a => lcm_rat a (denominator_rat c)) 
   969     (snd l) rat_1 //
   970   Intfunc.fold (fn (i,c) => fn a => gcd_rat a (numerator_rat c)) 
   971     (snd l) rat_0
   972   in ((c // (a */ a)),mapa (fn x => a */ x) l)
   973   end
   974 in
   975 fun deration d = if null d then (rat_0,d) else
   976  let val d' = map adj d
   977      val a = fold (lcm_rat o denominator_rat o fst) d' rat_1 //
   978           fold (gcd_rat o numerator_rat o fst) d' rat_0 
   979  in ((rat_1 // a),map (fn (c,l) => (a */ c,l)) d')
   980  end
   981 end;
   982  
   983 (* Enumeration of monomials with given multidegree bound.                    *)
   984 
   985 fun enumerate_monomials d vars = 
   986  if d < 0 then []
   987  else if d = 0 then [Ctermfunc.undefined]
   988  else if null vars then [monomial_1] else
   989  let val alts =
   990   map (fn k => let val oths = enumerate_monomials (d - k) (tl vars) 
   991                in map (fn ks => if k = 0 then ks else Ctermfunc.update (hd vars, k) ks) oths end) (0 upto d) 
   992  in fold1 (curry op @) alts
   993  end;
   994 
   995 (* Enumerate products of distinct input polys with degree <= d.              *)
   996 (* We ignore any constant input polynomials.                                 *)
   997 (* Give the output polynomial and a record of how it was derived.            *)
   998 
   999 local
  1000  open RealArith
  1001 in
  1002 fun enumerate_products d pols =
  1003 if d = 0 then [(poly_const rat_1,Rational_lt rat_1)] 
  1004 else if d < 0 then [] else
  1005 case pols of 
  1006    [] => [(poly_const rat_1,Rational_lt rat_1)]
  1007  | (p,b)::ps => 
  1008     let val e = multidegree p 
  1009     in if e = 0 then enumerate_products d ps else
  1010        enumerate_products d ps @
  1011        map (fn (q,c) => (poly_mul p q,Product(b,c)))
  1012          (enumerate_products (d - e) ps)
  1013     end
  1014 end;
  1015 
  1016 (* Convert regular polynomial. Note that we treat (0,0,0) as -1.             *)
  1017 
  1018 fun epoly_of_poly p =
  1019   Monomialfunc.fold (fn (m,c) => fn a => Monomialfunc.update (m, Inttriplefunc.onefunc ((0,0,0), Rat.neg c)) a) p Monomialfunc.undefined;
  1020 
  1021 (* String for block diagonal matrix numbered k.                              *)
  1022 
  1023 fun sdpa_of_blockdiagonal k m =
  1024  let 
  1025   val pfx = string_of_int k ^" "
  1026   val ents =
  1027     Inttriplefunc.fold 
  1028       (fn ((b,i,j),c) => fn a => if i > j then a else ((b,i,j),c)::a) 
  1029       m [] 
  1030   val entss = sort (increasing fst triple_int_ord) ents 
  1031  in fold_rev (fn ((b,i,j),c) => fn a =>
  1032      pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
  1033      " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
  1034  end;
  1035 
  1036 (* SDPA for problem using block diagonal (i.e. multiple SDPs)                *)
  1037 
  1038 fun sdpa_of_blockproblem nblocks blocksizes obj mats =
  1039  let val m = length mats - 1 
  1040  in
  1041   string_of_int m ^ "\n" ^
  1042   string_of_int nblocks ^ "\n" ^
  1043   (fold1 (fn s => fn t => s^" "^t) (map string_of_int blocksizes)) ^
  1044   "\n" ^
  1045   sdpa_of_vector obj ^
  1046   fold_rev2 (fn k => fn m => fn a => sdpa_of_blockdiagonal (k - 1) m ^ a)
  1047     (1 upto length mats) mats ""
  1048  end;
  1049 
  1050 (* Run prover on a problem in block diagonal form.                       *)
  1051 
  1052 fun run_blockproblem prover nblocks blocksizes obj mats=
  1053   parse_csdpoutput (prover (sdpa_of_blockproblem nblocks blocksizes obj mats))
  1054 
  1055 (* 3D versions of matrix operations to consider blocks separately.           *)
  1056 
  1057 val bmatrix_add = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0);
  1058 fun bmatrix_cmul c bm =
  1059   if c =/ rat_0 then Inttriplefunc.undefined
  1060   else Inttriplefunc.mapf (fn x => c */ x) bm;
  1061 
  1062 val bmatrix_neg = bmatrix_cmul (Rat.rat_of_int ~1);
  1063 fun bmatrix_sub m1 m2 = bmatrix_add m1 (bmatrix_neg m2);;
  1064 
  1065 (* Smash a block matrix into components.                                     *)
  1066 
  1067 fun blocks blocksizes bm =
  1068  map (fn (bs,b0) =>
  1069       let val m = Inttriplefunc.fold
  1070           (fn ((b,i,j),c) => fn a => if b = b0 then Intpairfunc.update ((i,j),c) a else a) bm Intpairfunc.undefined
  1071           val d = Intpairfunc.fold (fn ((i,j),c) => fn a => max a (max i j)) m 0 
  1072       in (((bs,bs),m):matrix) end)
  1073  (blocksizes ~~ (1 upto length blocksizes));;
  1074 
  1075 (* FIXME : Get rid of this !!!*)
  1076 local
  1077   fun tryfind_with msg f [] = raise Failure msg
  1078     | tryfind_with msg f (x::xs) = (f x handle Failure s => tryfind_with s f xs);
  1079 in 
  1080   fun tryfind f = tryfind_with "tryfind" f
  1081 end
  1082 
  1083 (*
  1084 fun tryfind f [] = error "tryfind"
  1085   | tryfind f (x::xs) = (f x handle ERROR _ => tryfind f xs);
  1086 *)
  1087 
  1088 (* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
  1089 
  1090  
  1091 local
  1092  open RealArith
  1093 in
  1094 fun real_positivnullstellensatz_general prover linf d eqs leqs pol =
  1095 let 
  1096  val vars = fold_rev (curry (gen_union (op aconvc)) o poly_variables) 
  1097               (pol::eqs @ map fst leqs) []
  1098  val monoid = if linf then 
  1099       (poly_const rat_1,Rational_lt rat_1)::
  1100       (filter (fn (p,c) => multidegree p <= d) leqs)
  1101     else enumerate_products d leqs
  1102  val nblocks = length monoid
  1103  fun mk_idmultiplier k p =
  1104   let 
  1105    val e = d - multidegree p
  1106    val mons = enumerate_monomials e vars
  1107    val nons = mons ~~ (1 upto length mons) 
  1108   in (mons,
  1109       fold_rev (fn (m,n) => Monomialfunc.update(m,Inttriplefunc.onefunc((~k,~n,n),rat_1))) nons Monomialfunc.undefined)
  1110   end
  1111 
  1112  fun mk_sqmultiplier k (p,c) =
  1113   let 
  1114    val e = (d - multidegree p) div 2
  1115    val mons = enumerate_monomials e vars
  1116    val nons = mons ~~ (1 upto length mons) 
  1117   in (mons, 
  1118       fold_rev (fn (m1,n1) =>
  1119        fold_rev (fn (m2,n2) => fn  a =>
  1120         let val m = monomial_mul m1 m2 
  1121         in if n1 > n2 then a else
  1122           let val c = if n1 = n2 then rat_1 else rat_2
  1123               val e = Monomialfunc.tryapplyd a m Inttriplefunc.undefined 
  1124           in Monomialfunc.update(m, tri_equation_add (Inttriplefunc.onefunc((k,n1,n2), c)) e) a
  1125           end
  1126         end)  nons)
  1127        nons Monomialfunc.undefined)
  1128   end
  1129 
  1130   val (sqmonlist,sqs) = split_list (map2 mk_sqmultiplier (1 upto length monoid) monoid)
  1131   val (idmonlist,ids) =  split_list(map2 mk_idmultiplier (1 upto length eqs) eqs)
  1132   val blocksizes = map length sqmonlist
  1133   val bigsum =
  1134     fold_rev2 (fn p => fn q => fn a => tri_epoly_pmul p q a) eqs ids
  1135             (fold_rev2 (fn (p,c) => fn s => fn a => tri_epoly_pmul p s a) monoid sqs
  1136                      (epoly_of_poly(poly_neg pol)))
  1137   val eqns = Monomialfunc.fold (fn (m,e) => fn a => e::a) bigsum []
  1138   val (pvs,assig) = tri_eliminate_all_equations (0,0,0) eqns
  1139   val qvars = (0,0,0)::pvs
  1140   val allassig = fold_rev (fn v => Inttriplefunc.update(v,(Inttriplefunc.onefunc(v,rat_1)))) pvs assig
  1141   fun mk_matrix v =
  1142     Inttriplefunc.fold (fn ((b,i,j), ass) => fn m => 
  1143         if b < 0 then m else
  1144          let val c = Inttriplefunc.tryapplyd ass v rat_0
  1145          in if c = rat_0 then m else
  1146             Inttriplefunc.update ((b,j,i), c) (Inttriplefunc.update ((b,i,j), c) m)
  1147          end)
  1148           allassig Inttriplefunc.undefined
  1149   val diagents = Inttriplefunc.fold
  1150     (fn ((b,i,j), e) => fn a => if b > 0 andalso i = j then tri_equation_add e a else a)
  1151     allassig Inttriplefunc.undefined
  1152 
  1153   val mats = map mk_matrix qvars
  1154   val obj = (length pvs,
  1155             itern 1 pvs (fn v => fn i => Intfunc.updatep iszero (i,Inttriplefunc.tryapplyd diagents v rat_0))
  1156                         Intfunc.undefined)
  1157   val raw_vec = if null pvs then vector_0 0
  1158                 else tri_scale_then (run_blockproblem prover nblocks blocksizes) obj mats
  1159   fun int_element (d,v) i = Intfunc.tryapplyd v i rat_0
  1160   fun cterm_element (d,v) i = Ctermfunc.tryapplyd v i rat_0
  1161 
  1162   fun find_rounding d =
  1163    let 
  1164     val _ = if !debugging 
  1165           then writeln ("Trying rounding with limit "^Rat.string_of_rat d ^ "\n") 
  1166           else ()
  1167     val vec = nice_vector d raw_vec
  1168     val blockmat = iter (1,dim vec)
  1169      (fn i => fn a => bmatrix_add (bmatrix_cmul (int_element vec i) (nth mats i)) a)
  1170      (bmatrix_neg (nth mats 0))
  1171     val allmats = blocks blocksizes blockmat 
  1172    in (vec,map diag allmats)
  1173    end
  1174   val (vec,ratdias) =
  1175     if null pvs then find_rounding rat_1
  1176     else tryfind find_rounding (map Rat.rat_of_int (1 upto 31) @
  1177                                 map pow2 (5 upto 66))
  1178   val newassigs =
  1179     fold_rev (fn k => Inttriplefunc.update (nth pvs (k - 1), int_element vec k))
  1180            (1 upto dim vec) (Inttriplefunc.onefunc ((0,0,0), Rat.rat_of_int ~1))
  1181   val finalassigs =
  1182     Inttriplefunc.fold (fn (v,e) => fn a => Inttriplefunc.update(v, tri_equation_eval newassigs e) a) allassig newassigs
  1183   fun poly_of_epoly p =
  1184     Monomialfunc.fold (fn (v,e) => fn a => Monomialfunc.updatep iszero (v,tri_equation_eval finalassigs e) a)
  1185           p Monomialfunc.undefined
  1186   fun  mk_sos mons =
  1187    let fun mk_sq (c,m) =
  1188     (c,fold_rev (fn k=> fn a => Monomialfunc.updatep iszero (nth mons (k - 1), int_element m k) a)
  1189                  (1 upto length mons) Monomialfunc.undefined)
  1190    in map mk_sq
  1191    end
  1192   val sqs = map2 mk_sos sqmonlist ratdias
  1193   val cfs = map poly_of_epoly ids
  1194   val msq = filter (fn (a,b) => not (null b)) (map2 pair monoid sqs)
  1195   fun eval_sq sqs = fold_rev (fn (c,q) => poly_add (poly_cmul c (poly_mul q q))) sqs poly_0
  1196   val sanity =
  1197     fold_rev (fn ((p,c),s) => poly_add (poly_mul p (eval_sq s))) msq
  1198            (fold_rev2 (fn p => fn q => poly_add (poly_mul p q)) cfs eqs
  1199                     (poly_neg pol))
  1200 
  1201 in if not(Monomialfunc.is_undefined sanity) then raise Sanity else
  1202   (cfs,map (fn (a,b) => (snd a,b)) msq)
  1203  end
  1204 
  1205 
  1206 end;
  1207 
  1208 (* Iterative deepening.                                                      *)
  1209 
  1210 fun deepen f n = 
  1211   (writeln ("Searching with depth limit " ^ string_of_int n) ; (f n handle Failure s => (writeln ("failed with message: " ^ s) ; deepen f (n+1))))
  1212 
  1213 (* The ordering so we can create canonical HOL polynomials.                  *)
  1214 
  1215 fun dest_monomial mon = sort (increasing fst cterm_ord) (Ctermfunc.graph mon);
  1216 
  1217 fun monomial_order (m1,m2) =
  1218  if Ctermfunc.is_undefined m2 then LESS 
  1219  else if Ctermfunc.is_undefined m1 then GREATER 
  1220  else
  1221   let val mon1 = dest_monomial m1 
  1222       val mon2 = dest_monomial m2
  1223       val deg1 = fold (curry op + o snd) mon1 0
  1224       val deg2 = fold (curry op + o snd) mon2 0 
  1225   in if deg1 < deg2 then GREATER else if deg1 > deg2 then LESS
  1226      else list_ord (prod_ord cterm_ord int_ord) (mon1,mon2)
  1227   end;
  1228 
  1229 fun dest_poly p =
  1230   map (fn (m,c) => (c,dest_monomial m))
  1231       (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p));
  1232 
  1233 (* Map back polynomials and their composites to HOL.                         *)
  1234 
  1235 local
  1236  open Thm Numeral RealArith
  1237 in
  1238 
  1239 fun cterm_of_varpow x k = if k = 1 then x else capply (capply @{cterm "op ^ :: real => _"} x) 
  1240   (mk_cnumber @{ctyp nat} k)
  1241 
  1242 fun cterm_of_monomial m = 
  1243  if Ctermfunc.is_undefined m then @{cterm "1::real"} 
  1244  else 
  1245   let 
  1246    val m' = dest_monomial m
  1247    val vps = fold_rev (fn (x,k) => cons (cterm_of_varpow x k)) m' [] 
  1248   in fold1 (fn s => fn t => capply (capply @{cterm "op * :: real => _"} s) t) vps
  1249   end
  1250 
  1251 fun cterm_of_cmonomial (m,c) = if Ctermfunc.is_undefined m then cterm_of_rat c
  1252     else if c = Rat.one then cterm_of_monomial m
  1253     else capply (capply @{cterm "op *::real => _"} (cterm_of_rat c)) (cterm_of_monomial m);
  1254 
  1255 fun cterm_of_poly p = 
  1256  if Monomialfunc.is_undefined p then @{cterm "0::real"} 
  1257  else
  1258   let 
  1259    val cms = map cterm_of_cmonomial
  1260      (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p))
  1261   in fold1 (fn t1 => fn t2 => capply(capply @{cterm "op + :: real => _"} t1) t2) cms
  1262   end;
  1263 
  1264 fun cterm_of_sqterm (c,p) = Product(Rational_lt c,Square(cterm_of_poly p));
  1265 
  1266 fun cterm_of_sos (pr,sqs) = if null sqs then pr
  1267   else Product(pr,fold1 (fn a => fn b => Sum(a,b)) (map cterm_of_sqterm sqs));
  1268 
  1269 end
  1270 
  1271 (* Interface to HOL.                                                         *)
  1272 local
  1273   open Thm Conv RealArith
  1274   val concl = dest_arg o cprop_of
  1275   fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
  1276 in
  1277   (* FIXME: Replace tryfind by get_first !! *)
  1278 fun real_nonlinear_prover prover ctxt =
  1279  let 
  1280   val {add,mul,neg,pow,sub,main} =  Normalizer.semiring_normalizers_ord_wrapper ctxt
  1281       (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
  1282      simple_cterm_ord
  1283   val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
  1284        real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
  1285   fun mainf  translator (eqs,les,lts) = 
  1286   let 
  1287    val eq0 = map (poly_of_term o dest_arg1 o concl) eqs
  1288    val le0 = map (poly_of_term o dest_arg o concl) les
  1289    val lt0 = map (poly_of_term o dest_arg o concl) lts
  1290    val eqp0 = map (fn (t,i) => (t,Axiom_eq i)) (eq0 ~~ (0 upto (length eq0 - 1)))
  1291    val lep0 = map (fn (t,i) => (t,Axiom_le i)) (le0 ~~ (0 upto (length le0 - 1)))
  1292    val ltp0 = map (fn (t,i) => (t,Axiom_lt i)) (lt0 ~~ (0 upto (length lt0 - 1)))
  1293    val (keq,eq) = List.partition (fn (p,_) => multidegree p = 0) eqp0
  1294    val (klep,lep) = List.partition (fn (p,_) => multidegree p = 0) lep0
  1295    val (kltp,ltp) = List.partition (fn (p,_) => multidegree p = 0) ltp0
  1296    fun trivial_axiom (p,ax) =
  1297     case ax of
  1298        Axiom_eq n => if eval Ctermfunc.undefined p <>/ Rat.zero then nth eqs n 
  1299                      else raise Failure "trivial_axiom: Not a trivial axiom"
  1300      | Axiom_le n => if eval Ctermfunc.undefined p </ Rat.zero then nth les n 
  1301                      else raise Failure "trivial_axiom: Not a trivial axiom"
  1302      | Axiom_lt n => if eval Ctermfunc.undefined p <=/ Rat.zero then nth lts n 
  1303                      else raise Failure "trivial_axiom: Not a trivial axiom"
  1304      | _ => error "trivial_axiom: Not a trivial axiom"
  1305    in 
  1306   ((let val th = tryfind trivial_axiom (keq @ klep @ kltp)
  1307    in fconv_rule (arg_conv (arg1_conv real_poly_conv) then_conv field_comp_conv) th end)
  1308    handle Failure _ => (
  1309     let 
  1310      val pol = fold_rev poly_mul (map fst ltp) (poly_const Rat.one)
  1311      val leq = lep @ ltp
  1312      fun tryall d =
  1313       let val e = multidegree pol
  1314           val k = if e = 0 then 0 else d div e
  1315           val eq' = map fst eq 
  1316       in tryfind (fn i => (d,i,real_positivnullstellensatz_general prover false d eq' leq
  1317                             (poly_neg(poly_pow pol i))))
  1318               (0 upto k)
  1319       end
  1320     val (d,i,(cert_ideal,cert_cone)) = deepen tryall 0
  1321     val proofs_ideal =
  1322       map2 (fn q => fn (p,ax) => Eqmul(cterm_of_poly q,ax)) cert_ideal eq
  1323     val proofs_cone = map cterm_of_sos cert_cone
  1324     val proof_ne = if null ltp then Rational_lt Rat.one else
  1325       let val p = fold1 (fn s => fn t => Product(s,t)) (map snd ltp) 
  1326       in  funpow i (fn q => Product(p,q)) (Rational_lt Rat.one)
  1327       end
  1328     val proof = fold1 (fn s => fn t => Sum(s,t))
  1329                            (proof_ne :: proofs_ideal @ proofs_cone) 
  1330     in writeln "Translating proof certificate to HOL";
  1331        translator (eqs,les,lts) proof
  1332     end))
  1333    end
  1334  in mainf end
  1335 end
  1336 
  1337 fun C f x y = f y x;
  1338   (* FIXME : This is very bad!!!*)
  1339 fun subst_conv eqs t = 
  1340  let 
  1341   val t' = fold (Thm.cabs o Thm.lhs_of) eqs t
  1342  in Conv.fconv_rule (Thm.beta_conversion true) (fold (C combination) eqs (reflexive t'))
  1343  end
  1344 
  1345 (* A wrapper that tries to substitute away variables first.                  *)
  1346 
  1347 local
  1348  open Thm Conv RealArith
  1349   fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
  1350  val concl = dest_arg o cprop_of
  1351  val shuffle1 = 
  1352    fconv_rule (rewr_conv @{lemma "(a + x == y) == (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps) })
  1353  val shuffle2 =
  1354     fconv_rule (rewr_conv @{lemma "(x + a == y) ==  (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps)})
  1355  fun substitutable_monomial fvs tm = case term_of tm of
  1356     Free(_,@{typ real}) => if not (member (op aconvc) fvs tm) then (Rat.one,tm) 
  1357                            else raise Failure "substitutable_monomial"
  1358   | @{term "op * :: real => _"}$c$(t as Free _ ) => 
  1359      if is_ratconst (dest_arg1 tm) andalso not (member (op aconvc) fvs (dest_arg tm))
  1360          then (dest_ratconst (dest_arg1 tm),dest_arg tm) else raise Failure "substitutable_monomial"
  1361   | @{term "op + :: real => _"}$s$t => 
  1362        (substitutable_monomial (add_cterm_frees (dest_arg tm) fvs) (dest_arg1 tm)
  1363         handle Failure _ => substitutable_monomial (add_cterm_frees (dest_arg1 tm) fvs) (dest_arg tm))
  1364   | _ => raise Failure "substitutable_monomial"
  1365 
  1366   fun isolate_variable v th = 
  1367    let val w = dest_arg1 (cprop_of th)
  1368    in if v aconvc w then th
  1369       else case term_of w of
  1370            @{term "op + :: real => _"}$s$t => 
  1371               if dest_arg1 w aconvc v then shuffle2 th 
  1372               else isolate_variable v (shuffle1 th)
  1373           | _ => error "isolate variable : This should not happen?"
  1374    end 
  1375 in
  1376 
  1377 fun real_nonlinear_subst_prover prover ctxt =
  1378  let 
  1379   val {add,mul,neg,pow,sub,main} =  Normalizer.semiring_normalizers_ord_wrapper ctxt
  1380       (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
  1381      simple_cterm_ord
  1382 
  1383   val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
  1384        real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
  1385 
  1386   fun make_substitution th =
  1387    let 
  1388     val (c,v) = substitutable_monomial [] (dest_arg1(concl th))
  1389     val th1 = Drule.arg_cong_rule (capply @{cterm "op * :: real => _"} (cterm_of_rat (Rat.inv c))) (mk_meta_eq th)
  1390     val th2 = fconv_rule (binop_conv real_poly_mul_conv) th1
  1391    in fconv_rule (arg_conv real_poly_conv) (isolate_variable v th2)
  1392    end
  1393    fun oprconv cv ct = 
  1394     let val g = Thm.dest_fun2 ct
  1395     in if g aconvc @{cterm "op <= :: real => _"} 
  1396          orelse g aconvc @{cterm "op < :: real => _"} 
  1397        then arg_conv cv ct else arg1_conv cv ct
  1398     end
  1399   fun mainf translator =
  1400    let 
  1401     fun substfirst(eqs,les,lts) =
  1402       ((let 
  1403            val eth = tryfind make_substitution eqs
  1404            val modify = fconv_rule (arg_conv (oprconv(subst_conv [eth] then_conv real_poly_conv)))
  1405        in  substfirst
  1406              (filter_out (fn t => (Thm.dest_arg1 o Thm.dest_arg o cprop_of) t 
  1407                                    aconvc @{cterm "0::real"}) (map modify eqs),
  1408                                    map modify les,map modify lts)
  1409        end)
  1410        handle Failure  _ => real_nonlinear_prover prover ctxt translator (rev eqs, rev les, rev lts))
  1411     in substfirst
  1412    end
  1413 
  1414 
  1415  in mainf
  1416  end
  1417 
  1418 (* Overall function. *)
  1419 
  1420 fun real_sos prover ctxt t = gen_prover_real_arith ctxt (real_nonlinear_subst_prover prover ctxt) t;
  1421 end;
  1422 
  1423 (* A tactic *)
  1424 fun strip_all ct = 
  1425  case term_of ct of 
  1426   Const("all",_) $ Abs (xn,xT,p) => 
  1427    let val (a,(v,t')) = (apsnd (Thm.dest_abs (SOME xn)) o Thm.dest_comb) ct
  1428    in apfst (cons v) (strip_all t')
  1429    end
  1430 | _ => ([],ct)
  1431 
  1432 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})
  1433 
  1434 val known_sos_constants = 
  1435   [@{term "op ==>"}, @{term "Trueprop"}, 
  1436    @{term "op -->"}, @{term "op &"}, @{term "op |"}, 
  1437    @{term "Not"}, @{term "op = :: bool => _"}, 
  1438    @{term "All :: (real => _) => _"}, @{term "Ex :: (real => _) => _"}, 
  1439    @{term "op = :: real => _"}, @{term "op < :: real => _"}, 
  1440    @{term "op <= :: real => _"}, 
  1441    @{term "op + :: real => _"}, @{term "op - :: real => _"}, 
  1442    @{term "op * :: real => _"}, @{term "uminus :: real => _"}, 
  1443    @{term "op / :: real => _"}, @{term "inverse :: real => _"},
  1444    @{term "op ^ :: real => _"}, @{term "abs :: real => _"}, 
  1445    @{term "min :: real => _"}, @{term "max :: real => _"},
  1446    @{term "0::real"}, @{term "1::real"}, @{term "number_of :: int => real"},
  1447    @{term "number_of :: int => nat"},
  1448    @{term "Int.Bit0"}, @{term "Int.Bit1"}, 
  1449    @{term "Int.Pls"}, @{term "Int.Min"}];
  1450 
  1451 fun check_sos kcts ct = 
  1452  let
  1453   val t = term_of ct
  1454   val _ = if not (null (Term.add_tfrees t []) 
  1455                   andalso null (Term.add_tvars t [])) 
  1456           then error "SOS: not sos. Additional type varables" else ()
  1457   val fs = Term.add_frees t []
  1458   val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs 
  1459           then error "SOS: not sos. Variables with type not real" else ()
  1460   val vs = Term.add_vars t []
  1461   val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs 
  1462           then error "SOS: not sos. Variables with type not real" else ()
  1463   val ukcs = subtract (fn (t,p) => Const p aconv t) kcts (Term.add_consts t [])
  1464   val _ = if  null ukcs then () 
  1465               else error ("SOSO: Unknown constants in Subgoal:" ^ commas (map fst ukcs))
  1466 in () end
  1467 
  1468 fun core_sos_tac prover ctxt = CSUBGOAL (fn (ct, i) => 
  1469   let val _ = check_sos known_sos_constants ct
  1470       val (avs, p) = strip_all ct
  1471       val th = standard (fold_rev forall_intr avs (real_sos prover ctxt (Thm.dest_arg p)))
  1472   in rtac th i end);
  1473 
  1474 fun default_SOME f NONE v = SOME v
  1475   | default_SOME f (SOME v) _ = SOME v;
  1476 
  1477 fun lift_SOME f NONE a = f a
  1478   | lift_SOME f (SOME a) _ = SOME a;
  1479 
  1480 
  1481 local
  1482  val is_numeral = can (HOLogic.dest_number o term_of)
  1483 in
  1484 fun get_denom b ct = case term_of ct of
  1485   @{term "op / :: real => _"} $ _ $ _ => 
  1486      if is_numeral (Thm.dest_arg ct) then get_denom b (Thm.dest_arg1 ct)
  1487      else default_SOME (get_denom b) (get_denom b (Thm.dest_arg ct))   (Thm.dest_arg ct, b)
  1488  | @{term "op < :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
  1489  | @{term "op <= :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
  1490  | _ $ _ => lift_SOME (get_denom b) (get_denom b (Thm.dest_fun ct)) (Thm.dest_arg ct)
  1491  | _ => NONE
  1492 end;
  1493 
  1494 fun elim_one_denom_tac ctxt = 
  1495 CSUBGOAL (fn (P,i) => 
  1496  case get_denom false P of 
  1497    NONE => no_tac
  1498  | SOME (d,ord) => 
  1499      let 
  1500       val ss = simpset_of ctxt addsimps @{thms field_simps} 
  1501                addsimps [@{thm nonzero_power_divide}, @{thm power_divide}]
  1502       val th = instantiate' [] [SOME d, SOME (Thm.dest_arg P)] 
  1503          (if ord then @{lemma "(d=0 --> P) & (d>0 --> P) & (d<(0::real) --> P) ==> P" by auto}
  1504           else @{lemma "(d=0 --> P) & (d ~= (0::real) --> P) ==> P" by blast})
  1505      in (rtac th i THEN Simplifier.asm_full_simp_tac ss i) end);
  1506 
  1507 fun elim_denom_tac ctxt i = REPEAT (elim_one_denom_tac ctxt i);
  1508 
  1509 fun sos_tac prover ctxt = ObjectLogic.full_atomize_tac THEN' elim_denom_tac ctxt THEN' core_sos_tac prover ctxt
  1510 
  1511 
  1512 end;