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