src/HOL/Library/Sum_of_Squares/sum_of_squares.ML
author huffman
Sun Mar 25 20:15:39 2012 +0200 (2012-03-25)
changeset 47108 2a1953f0d20d
parent 46497 89ccf66aa73d
child 51717 9e7d1c139569
permissions -rw-r--r--
merged fork with new numeral representation (see NEWS)
wenzelm@41474
     1
(*  Title:      HOL/Library/Sum_of_Squares/sum_of_squares.ML
wenzelm@32949
     2
    Author:     Amine Chaieb, University of Cambridge
wenzelm@32949
     3
    Author:     Philipp Meyer, TU Muenchen
Philipp@32268
     4
wenzelm@32839
     5
A tactic for proving nonlinear inequalities.
Philipp@32268
     6
*)
Philipp@32268
     7
wenzelm@32949
     8
signature SUM_OF_SQUARES =
Philipp@32268
     9
sig
wenzelm@32949
    10
  datatype proof_method = Certificate of RealArith.pss_tree | Prover of string -> string
wenzelm@32949
    11
  val sos_tac: (RealArith.pss_tree -> unit) -> proof_method -> Proof.context -> int -> tactic
wenzelm@38805
    12
  val trace: bool Config.T
wenzelm@32332
    13
  exception Failure of string;
Philipp@32268
    14
end
Philipp@32268
    15
wenzelm@41474
    16
structure Sum_of_Squares: SUM_OF_SQUARES =
chaieb@31119
    17
struct
chaieb@31119
    18
chaieb@31119
    19
val rat_0 = Rat.zero;
chaieb@31119
    20
val rat_1 = Rat.one;
chaieb@31119
    21
val rat_2 = Rat.two;
chaieb@31119
    22
val rat_10 = Rat.rat_of_int 10;
wenzelm@33029
    23
val max = Integer.max;
chaieb@31119
    24
chaieb@31119
    25
val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
wenzelm@32839
    26
fun int_of_rat a =
chaieb@31119
    27
    case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
chaieb@31119
    28
fun lcm_rat x y = Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
chaieb@31119
    29
wenzelm@32839
    30
fun rat_pow r i =
wenzelm@32839
    31
 let fun pow r i =
wenzelm@32839
    32
   if i = 0 then rat_1 else
chaieb@31119
    33
   let val d = pow r (i div 2)
chaieb@31119
    34
   in d */ d */ (if i mod 2 = 0 then rat_1 else r)
chaieb@31119
    35
   end
chaieb@31119
    36
 in if i < 0 then pow (Rat.inv r) (~ i) else pow r i end;
chaieb@31119
    37
wenzelm@32839
    38
fun round_rat r =
chaieb@31119
    39
 let val (a,b) = Rat.quotient_of_rat (Rat.abs r)
chaieb@31119
    40
     val d = a div b
chaieb@31119
    41
     val s = if r </ rat_0 then (Rat.neg o Rat.rat_of_int) else Rat.rat_of_int
chaieb@31119
    42
     val x2 = 2 * (a - (b * d))
chaieb@31119
    43
 in s (if x2 >= b then d + 1 else d) end
chaieb@31119
    44
chaieb@31119
    45
val abs_rat = Rat.abs;
chaieb@31119
    46
val pow2 = rat_pow rat_2;
chaieb@31119
    47
val pow10 = rat_pow rat_10;
chaieb@31119
    48
wenzelm@42616
    49
val trace = Attrib.setup_config_bool @{binding sos_trace} (K false);
chaieb@31119
    50
chaieb@31119
    51
exception Sanity;
chaieb@31119
    52
chaieb@31119
    53
exception Unsolvable;
chaieb@31119
    54
wenzelm@32332
    55
exception Failure of string;
wenzelm@32332
    56
Philipp@32645
    57
datatype proof_method =
Philipp@32645
    58
    Certificate of RealArith.pss_tree
Philipp@32645
    59
  | Prover of (string -> string)
Philipp@32645
    60
chaieb@31119
    61
(* Turn a rational into a decimal string with d sig digits.                  *)
chaieb@31119
    62
chaieb@31119
    63
local
chaieb@31119
    64
fun normalize y =
chaieb@31119
    65
  if abs_rat y </ (rat_1 // rat_10) then normalize (rat_10 */ y) - 1
chaieb@31119
    66
  else if abs_rat y >=/ rat_1 then normalize (y // rat_10) + 1
wenzelm@32839
    67
  else 0
chaieb@31119
    68
 in
chaieb@31119
    69
fun decimalize d x =
chaieb@31119
    70
  if x =/ rat_0 then "0.0" else
wenzelm@32839
    71
  let
chaieb@31119
    72
   val y = Rat.abs x
chaieb@31119
    73
   val e = normalize y
chaieb@31119
    74
   val z = pow10(~ e) */ y +/ rat_1
chaieb@31119
    75
   val k = int_of_rat (round_rat(pow10 d */ z))
chaieb@31119
    76
  in (if x </ rat_0 then "-0." else "0.") ^
wenzelm@40627
    77
     implode(tl(raw_explode(string_of_int k))) ^
chaieb@31119
    78
     (if e = 0 then "" else "e"^string_of_int e)
chaieb@31119
    79
  end
chaieb@31119
    80
end;
chaieb@31119
    81
chaieb@31119
    82
(* Iterations over numbers, and lists indexed by numbers.                    *)
chaieb@31119
    83
chaieb@31119
    84
fun itern k l f a =
chaieb@31119
    85
  case l of
chaieb@31119
    86
    [] => a
chaieb@31119
    87
  | h::t => itern (k + 1) t f (f h k a);
chaieb@31119
    88
chaieb@31119
    89
fun iter (m,n) f a =
chaieb@31119
    90
  if n < m then a
chaieb@31119
    91
  else iter (m+1,n) f (f m a);
chaieb@31119
    92
chaieb@31119
    93
(* The main types.                                                           *)
chaieb@31119
    94
Philipp@32829
    95
type vector = int* Rat.rat FuncUtil.Intfunc.table;
chaieb@31119
    96
Philipp@32829
    97
type matrix = (int*int)*(Rat.rat FuncUtil.Intpairfunc.table);
chaieb@31119
    98
huffman@44453
    99
fun iszero (_,r) = r =/ rat_0;
chaieb@31119
   100
wenzelm@32839
   101
chaieb@31119
   102
(* Vectors. Conventionally indexed 1..n.                                     *)
chaieb@31119
   103
Philipp@32829
   104
fun vector_0 n = (n,FuncUtil.Intfunc.empty):vector;
chaieb@31119
   105
chaieb@31119
   106
fun dim (v:vector) = fst v;
chaieb@31119
   107
chaieb@31119
   108
fun vector_cmul c (v:vector) =
wenzelm@32839
   109
 let val n = dim v
chaieb@31119
   110
 in if c =/ rat_0 then vector_0 n
haftmann@39027
   111
    else (n,FuncUtil.Intfunc.map (fn _ => fn x => c */ x) (snd v))
chaieb@31119
   112
 end;
chaieb@31119
   113
chaieb@31119
   114
fun vector_of_list l =
wenzelm@32839
   115
 let val n = length l
Philipp@32829
   116
 in (n,fold_rev2 (curry FuncUtil.Intfunc.update) (1 upto n) l FuncUtil.Intfunc.empty) :vector
chaieb@31119
   117
 end;
chaieb@31119
   118
chaieb@31119
   119
(* Matrices; again rows and columns indexed from 1.                          *)
chaieb@31119
   120
chaieb@31119
   121
fun dimensions (m:matrix) = fst m;
chaieb@31119
   122
chaieb@31119
   123
fun row k (m:matrix) =
huffman@44453
   124
 let val (_,j) = dimensions m
chaieb@31119
   125
 in (j,
Philipp@32829
   126
   FuncUtil.Intpairfunc.fold (fn ((i,j), c) => fn a => if i = k then FuncUtil.Intfunc.update (j,c) a else a) (snd m) FuncUtil.Intfunc.empty ) : vector
chaieb@31119
   127
 end;
chaieb@31119
   128
chaieb@31119
   129
(* Monomials.                                                                *)
chaieb@31119
   130
Philipp@32828
   131
fun monomial_eval assig m =
Philipp@32828
   132
  FuncUtil.Ctermfunc.fold (fn (x, k) => fn a => a */ rat_pow (FuncUtil.Ctermfunc.apply assig x) k)
chaieb@31119
   133
        m rat_1;
Philipp@32829
   134
val monomial_1 = FuncUtil.Ctermfunc.empty;
chaieb@31119
   135
Philipp@32828
   136
fun monomial_var x = FuncUtil.Ctermfunc.onefunc (x, 1);
chaieb@31119
   137
Philipp@32828
   138
val monomial_mul =
wenzelm@33002
   139
  FuncUtil.Ctermfunc.combine Integer.add (K false);
chaieb@31119
   140
wenzelm@32839
   141
fun monomial_multidegree m =
huffman@44453
   142
 FuncUtil.Ctermfunc.fold (fn (_, k) => fn a => k + a) m 0;;
chaieb@31119
   143
Philipp@32828
   144
fun monomial_variables m = FuncUtil.Ctermfunc.dom m;;
chaieb@31119
   145
chaieb@31119
   146
(* Polynomials.                                                              *)
chaieb@31119
   147
Philipp@32828
   148
fun eval assig p =
Philipp@32828
   149
  FuncUtil.Monomialfunc.fold (fn (m, c) => fn a => a +/ c */ monomial_eval assig m) p rat_0;
chaieb@31119
   150
Philipp@32829
   151
val poly_0 = FuncUtil.Monomialfunc.empty;
chaieb@31119
   152
wenzelm@32839
   153
fun poly_isconst p =
huffman@44453
   154
  FuncUtil.Monomialfunc.fold (fn (m, _) => fn a => FuncUtil.Ctermfunc.is_empty m andalso a) p true;
chaieb@31119
   155
Philipp@32828
   156
fun poly_var x = FuncUtil.Monomialfunc.onefunc (monomial_var x,rat_1);
chaieb@31119
   157
chaieb@31119
   158
fun poly_const c =
Philipp@32828
   159
  if c =/ rat_0 then poly_0 else FuncUtil.Monomialfunc.onefunc(monomial_1, c);
chaieb@31119
   160
Philipp@32828
   161
fun poly_cmul c p =
chaieb@31119
   162
  if c =/ rat_0 then poly_0
haftmann@39027
   163
  else FuncUtil.Monomialfunc.map (fn _ => fn x => c */ x) p;
chaieb@31119
   164
haftmann@39027
   165
fun poly_neg p = FuncUtil.Monomialfunc.map (K Rat.neg) p;;
chaieb@31119
   166
Philipp@32828
   167
fun poly_add p1 p2 =
Philipp@32828
   168
  FuncUtil.Monomialfunc.combine (curry op +/) (fn x => x =/ rat_0) p1 p2;
chaieb@31119
   169
chaieb@31119
   170
fun poly_sub p1 p2 = poly_add p1 (poly_neg p2);
chaieb@31119
   171
Philipp@32828
   172
fun poly_cmmul (c,m) p =
chaieb@31119
   173
 if c =/ rat_0 then poly_0
wenzelm@32839
   174
 else if FuncUtil.Ctermfunc.is_empty m
haftmann@39027
   175
      then FuncUtil.Monomialfunc.map (fn _ => fn d => c */ d) p
Philipp@32828
   176
      else FuncUtil.Monomialfunc.fold (fn (m', d) => fn a => (FuncUtil.Monomialfunc.update (monomial_mul m m', c */ d) a)) p poly_0;
chaieb@31119
   177
Philipp@32828
   178
fun poly_mul p1 p2 =
Philipp@32828
   179
  FuncUtil.Monomialfunc.fold (fn (m, c) => fn a => poly_add (poly_cmmul (c,m) p2) a) p1 poly_0;
chaieb@31119
   180
chaieb@31119
   181
fun poly_square p = poly_mul p p;
chaieb@31119
   182
chaieb@31119
   183
fun poly_pow p k =
chaieb@31119
   184
 if k = 0 then poly_const rat_1
chaieb@31119
   185
 else if k = 1 then p
chaieb@31119
   186
 else let val q = poly_square(poly_pow p (k div 2)) in
chaieb@31119
   187
      if k mod 2 = 1 then poly_mul p q else q end;
chaieb@31119
   188
Philipp@32828
   189
fun multidegree p =
huffman@44453
   190
  FuncUtil.Monomialfunc.fold (fn (m, _) => fn a => max (monomial_multidegree m) a) p 0;
chaieb@31119
   191
Philipp@32828
   192
fun poly_variables p =
huffman@44453
   193
  sort FuncUtil.cterm_ord (FuncUtil.Monomialfunc.fold_rev (fn (m, _) => union (is_equal o FuncUtil.cterm_ord) (monomial_variables m)) p []);;
chaieb@31119
   194
chaieb@31119
   195
(* Conversion from HOL term.                                                 *)
chaieb@31119
   196
chaieb@31119
   197
local
chaieb@31119
   198
 val neg_tm = @{cterm "uminus :: real => _"}
chaieb@31119
   199
 val add_tm = @{cterm "op + :: real => _"}
chaieb@31119
   200
 val sub_tm = @{cterm "op - :: real => _"}
chaieb@31119
   201
 val mul_tm = @{cterm "op * :: real => _"}
chaieb@31119
   202
 val inv_tm = @{cterm "inverse :: real => _"}
chaieb@31119
   203
 val div_tm = @{cterm "op / :: real => _"}
chaieb@31119
   204
 val pow_tm = @{cterm "op ^ :: real => _"}
chaieb@31119
   205
 val zero_tm = @{cterm "0:: real"}
chaieb@31119
   206
 val is_numeral = can (HOLogic.dest_number o term_of)
chaieb@31119
   207
 fun poly_of_term tm =
chaieb@31119
   208
  if tm aconvc zero_tm then poly_0
wenzelm@32839
   209
  else if RealArith.is_ratconst tm
chaieb@31119
   210
       then poly_const(RealArith.dest_ratconst tm)
wenzelm@32839
   211
  else
chaieb@31119
   212
  (let val (lop,r) = Thm.dest_comb tm
chaieb@31119
   213
   in if lop aconvc neg_tm then poly_neg(poly_of_term r)
chaieb@31119
   214
      else if lop aconvc inv_tm then
wenzelm@32839
   215
       let val p = poly_of_term r
wenzelm@32839
   216
       in if poly_isconst p
Philipp@32829
   217
          then poly_const(Rat.inv (eval FuncUtil.Ctermfunc.empty p))
chaieb@31119
   218
          else error "poly_of_term: inverse of non-constant polyomial"
chaieb@31119
   219
       end
chaieb@31119
   220
   else (let val (opr,l) = Thm.dest_comb lop
wenzelm@32839
   221
         in
wenzelm@32839
   222
          if opr aconvc pow_tm andalso is_numeral r
chaieb@31119
   223
          then poly_pow (poly_of_term l) ((snd o HOLogic.dest_number o term_of) r)
wenzelm@32839
   224
          else if opr aconvc add_tm
chaieb@31119
   225
           then poly_add (poly_of_term l) (poly_of_term r)
wenzelm@32839
   226
          else if opr aconvc sub_tm
chaieb@31119
   227
           then poly_sub (poly_of_term l) (poly_of_term r)
wenzelm@32839
   228
          else if opr aconvc mul_tm
chaieb@31119
   229
           then poly_mul (poly_of_term l) (poly_of_term r)
wenzelm@32839
   230
          else if opr aconvc div_tm
wenzelm@32839
   231
           then let
wenzelm@32839
   232
                  val p = poly_of_term l
wenzelm@32839
   233
                  val q = poly_of_term r
Philipp@32829
   234
                in if poly_isconst q then poly_cmul (Rat.inv (eval FuncUtil.Ctermfunc.empty q)) p
chaieb@31119
   235
                   else error "poly_of_term: division by non-constant polynomial"
chaieb@31119
   236
                end
chaieb@31119
   237
          else poly_var tm
wenzelm@32839
   238
chaieb@31119
   239
         end
chaieb@31119
   240
         handle CTERM ("dest_comb",_) => poly_var tm)
chaieb@31119
   241
   end
chaieb@31119
   242
   handle CTERM ("dest_comb",_) => poly_var tm)
chaieb@31119
   243
in
chaieb@31119
   244
val poly_of_term = fn tm =>
chaieb@31119
   245
 if type_of (term_of tm) = @{typ real} then poly_of_term tm
chaieb@31119
   246
 else error "poly_of_term: term does not have real type"
chaieb@31119
   247
end;
chaieb@31119
   248
chaieb@31119
   249
(* String of vector (just a list of space-separated numbers).                *)
chaieb@31119
   250
chaieb@31119
   251
fun sdpa_of_vector (v:vector) =
wenzelm@32839
   252
 let
chaieb@31119
   253
  val n = dim v
wenzelm@32839
   254
  val strs = map (decimalize 20 o (fn i => FuncUtil.Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n)
Philipp@32830
   255
 in space_implode " " strs ^ "\n"
chaieb@31119
   256
 end;
chaieb@31119
   257
wenzelm@32839
   258
fun triple_int_ord ((a,b,c),(a',b',c')) =
wenzelm@32839
   259
 prod_ord int_ord (prod_ord int_ord int_ord)
chaieb@31119
   260
    ((a,(b,c)),(a',(b',c')));
chaieb@31119
   261
structure Inttriplefunc = FuncFun(type key = int*int*int val ord = triple_int_ord);
chaieb@31119
   262
chaieb@31119
   263
fun index_char str chr pos =
chaieb@31119
   264
  if pos >= String.size str then ~1
chaieb@31119
   265
  else if String.sub(str,pos) = chr then pos
chaieb@31119
   266
  else index_char str chr (pos + 1);
chaieb@31119
   267
fun rat_of_quotient (a,b) = if b = 0 then rat_0 else Rat.rat_of_quotient (a,b);
wenzelm@32839
   268
fun rat_of_string s =
chaieb@31119
   269
 let val n = index_char s #"/" 0 in
wenzelm@33035
   270
  if n = ~1 then s |> Int.fromString |> the |> Rat.rat_of_int
wenzelm@32839
   271
  else
wenzelm@32949
   272
   let val SOME numer = Int.fromString(String.substring(s,0,n))
wenzelm@32949
   273
       val SOME den = Int.fromString (String.substring(s,n+1,String.size s - n - 1))
chaieb@31119
   274
   in rat_of_quotient(numer, den)
chaieb@31119
   275
   end
chaieb@31119
   276
 end;
chaieb@31119
   277
haftmann@36692
   278
fun isnum x = member (op =) ["0","1","2","3","4","5","6","7","8","9"] x;
chaieb@31119
   279
chaieb@31119
   280
(* More parser basics.                                                       *)
chaieb@31119
   281
Philipp@32828
   282
 val numeral = Scan.one isnum
Philipp@33906
   283
 val decimalint = Scan.repeat1 numeral >> (rat_of_string o implode)
Philipp@33906
   284
 val decimalfrac = Scan.repeat1 numeral
chaieb@31119
   285
    >> (fn s => rat_of_string(implode s) // pow10 (length s))
chaieb@31119
   286
 val decimalsig =
Philipp@32828
   287
    decimalint -- Scan.option (Scan.$$ "." |-- decimalfrac)
chaieb@31119
   288
    >> (fn (h,NONE) => h | (h,SOME x) => h +/ x)
chaieb@31119
   289
 fun signed prs =
wenzelm@32839
   290
       $$ "-" |-- prs >> Rat.neg
chaieb@31119
   291
    || $$ "+" |-- prs
chaieb@31119
   292
    || prs;
chaieb@31119
   293
chaieb@31119
   294
fun emptyin def xs = if null xs then (def,xs) else Scan.fail xs
chaieb@31119
   295
chaieb@31119
   296
 val exponent = ($$ "e" || $$ "E") |-- signed decimalint;
chaieb@31119
   297
chaieb@31119
   298
 val decimal = signed decimalsig -- (emptyin rat_0|| exponent)
chaieb@31119
   299
    >> (fn (h, x) => h */ pow10 (int_of_rat x));
chaieb@31119
   300
chaieb@31119
   301
 fun mkparser p s =
wenzelm@40627
   302
  let val (x,rst) = p (raw_explode s)
wenzelm@32839
   303
  in if null rst then x
chaieb@31119
   304
     else error "mkparser: unparsed input"
chaieb@31119
   305
  end;;
chaieb@31119
   306
wenzelm@32332
   307
(* Parse back csdp output.                                                      *)
chaieb@31119
   308
huffman@44453
   309
 fun ignore _ = ((),[])
wenzelm@33067
   310
 fun csdpoutput inp =
wenzelm@33067
   311
   ((decimal -- Scan.repeat (Scan.$$ " " |-- Scan.option decimal) >>
wenzelm@33067
   312
    (fn (h,to) => map_filter I ((SOME h)::to))) --| ignore >> vector_of_list) inp
chaieb@31119
   313
 val parse_csdpoutput = mkparser csdpoutput
chaieb@31119
   314
chaieb@31119
   315
(* Try some apparently sensible scaling first. Note that this is purely to   *)
chaieb@31119
   316
(* get a cleaner translation to floating-point, and doesn't affect any of    *)
chaieb@31119
   317
(* the results, in principle. In practice it seems a lot better when there   *)
chaieb@31119
   318
(* are extreme numbers in the original problem.                              *)
chaieb@31119
   319
chaieb@31119
   320
  (* Version for (int*int*int) keys *)
chaieb@31119
   321
local
chaieb@31119
   322
  fun max_rat x y = if x </ y then y else x
chaieb@31119
   323
  fun common_denominator fld amat acc =
huffman@44453
   324
      fld (fn (_,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
chaieb@31119
   325
  fun maximal_element fld amat acc =
huffman@44453
   326
    fld (fn (_,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc
chaieb@31119
   327
fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
wenzelm@41490
   328
                     in Real.fromInt a / Real.fromInt b end;
chaieb@31119
   329
fun int_of_float x = (trunc x handle Overflow => 0 | Domain => 0)
chaieb@31119
   330
in
chaieb@31119
   331
chaieb@31119
   332
fun tri_scale_then solver (obj:vector)  mats =
wenzelm@32839
   333
 let
chaieb@31119
   334
  val cd1 = fold_rev (common_denominator Inttriplefunc.fold) mats (rat_1)
wenzelm@32839
   335
  val cd2 = common_denominator FuncUtil.Intfunc.fold (snd obj)  (rat_1)
haftmann@39027
   336
  val mats' = map (Inttriplefunc.map (fn _ => fn x => cd1 */ x)) mats
chaieb@31119
   337
  val obj' = vector_cmul cd2 obj
chaieb@31119
   338
  val max1 = fold_rev (maximal_element Inttriplefunc.fold) mats' (rat_0)
wenzelm@32839
   339
  val max2 = maximal_element FuncUtil.Intfunc.fold (snd obj') (rat_0)
chaieb@31119
   340
  val scal1 = pow2 (20 - int_of_float(Math.ln (float_of_rat max1) / Math.ln 2.0))
wenzelm@32839
   341
  val scal2 = pow2 (20 - int_of_float(Math.ln (float_of_rat max2) / Math.ln 2.0))
haftmann@39027
   342
  val mats'' = map (Inttriplefunc.map (fn _ => fn x => x */ scal1)) mats'
wenzelm@32839
   343
  val obj'' = vector_cmul scal2 obj'
chaieb@31119
   344
 in solver obj'' mats''
chaieb@31119
   345
  end
chaieb@31119
   346
end;
chaieb@31119
   347
chaieb@31119
   348
(* Round a vector to "nice" rationals.                                       *)
chaieb@31119
   349
chaieb@31119
   350
fun nice_rational n x = round_rat (n */ x) // n;;
wenzelm@32839
   351
fun nice_vector n ((d,v) : vector) =
wenzelm@32839
   352
 (d, FuncUtil.Intfunc.fold (fn (i,c) => fn a =>
wenzelm@32839
   353
   let val y = nice_rational n c
wenzelm@32839
   354
   in if c =/ rat_0 then a
Philipp@32829
   355
      else FuncUtil.Intfunc.update (i,y) a end) v FuncUtil.Intfunc.empty):vector
chaieb@31119
   356
chaieb@31119
   357
fun dest_ord f x = is_equal (f x);
chaieb@31119
   358
chaieb@31119
   359
(* Stuff for "equations" ((int*int*int)->num functions).                         *)
chaieb@31119
   360
chaieb@31119
   361
fun tri_equation_cmul c eq =
haftmann@39027
   362
  if c =/ rat_0 then Inttriplefunc.empty else Inttriplefunc.map (fn _ => fn d => c */ d) eq;
chaieb@31119
   363
chaieb@31119
   364
fun tri_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
chaieb@31119
   365
chaieb@31119
   366
fun tri_equation_eval assig eq =
wenzelm@32839
   367
 let fun value v = Inttriplefunc.apply assig v
chaieb@31119
   368
 in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
chaieb@31119
   369
 end;
chaieb@31119
   370
chaieb@31119
   371
(* Eliminate all variables, in an essentially arbitrary order.               *)
chaieb@31119
   372
chaieb@31119
   373
fun tri_eliminate_all_equations one =
wenzelm@32839
   374
 let
chaieb@31119
   375
  fun choose_variable eq =
wenzelm@32839
   376
   let val (v,_) = Inttriplefunc.choose eq
chaieb@31119
   377
   in if is_equal (triple_int_ord(v,one)) then
wenzelm@32839
   378
      let val eq' = Inttriplefunc.delete_safe v eq
wenzelm@32839
   379
      in if Inttriplefunc.is_empty eq' then error "choose_variable"
chaieb@31119
   380
         else fst (Inttriplefunc.choose eq')
chaieb@31119
   381
      end
wenzelm@32839
   382
    else v
chaieb@31119
   383
   end
wenzelm@32839
   384
  fun eliminate dun eqs = case eqs of
chaieb@31119
   385
    [] => dun
chaieb@31119
   386
  | eq::oeqs =>
Philipp@32829
   387
    if Inttriplefunc.is_empty eq then eliminate dun oeqs else
chaieb@31119
   388
    let val v = choose_variable eq
chaieb@31119
   389
        val a = Inttriplefunc.apply eq v
wenzelm@32839
   390
        val eq' = tri_equation_cmul ((Rat.rat_of_int ~1) // a)
Philipp@32829
   391
                   (Inttriplefunc.delete_safe v eq)
chaieb@31119
   392
        fun elim e =
wenzelm@32839
   393
         let val b = Inttriplefunc.tryapplyd e v rat_0
wenzelm@32839
   394
         in if b =/ rat_0 then e
chaieb@31119
   395
            else tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
chaieb@31119
   396
         end
haftmann@39027
   397
    in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.map (K elim) dun))
wenzelm@32839
   398
                 (map elim oeqs)
chaieb@31119
   399
    end
chaieb@31119
   400
in fn eqs =>
wenzelm@32839
   401
 let
Philipp@32829
   402
  val assig = eliminate Inttriplefunc.empty eqs
huffman@44453
   403
  val vs = Inttriplefunc.fold (fn (_, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
chaieb@31119
   404
 in (distinct (dest_ord triple_int_ord) vs,assig)
chaieb@31119
   405
 end
chaieb@31119
   406
end;
wenzelm@32839
   407
chaieb@31119
   408
(* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
chaieb@31119
   409
chaieb@31119
   410
fun tri_epoly_pmul p q acc =
Philipp@32828
   411
 FuncUtil.Monomialfunc.fold (fn (m1, c) => fn a =>
Philipp@32828
   412
  FuncUtil.Monomialfunc.fold (fn (m2,e) => fn b =>
chaieb@31119
   413
   let val m =  monomial_mul m1 m2
wenzelm@32839
   414
       val es = FuncUtil.Monomialfunc.tryapplyd b m Inttriplefunc.empty
wenzelm@32839
   415
   in FuncUtil.Monomialfunc.update (m,tri_equation_add (tri_equation_cmul c e) es) b
chaieb@31119
   416
   end) q a) p acc ;
chaieb@31119
   417
chaieb@31119
   418
(* Hence produce the "relevant" monomials: those whose squares lie in the    *)
chaieb@31119
   419
(* Newton polytope of the monomials in the input. (This is enough according  *)
chaieb@31119
   420
(* to Reznik: "Extremal PSD forms with few terms", Duke Math. Journal,       *)
chaieb@31119
   421
(* vol 45, pp. 363--374, 1978.                                               *)
chaieb@31119
   422
(*                                                                           *)
chaieb@31119
   423
(* These are ordered in sort of decreasing degree. In particular the         *)
chaieb@31119
   424
(* constant monomial is last; this gives an order in diagonalization of the  *)
chaieb@31119
   425
(* quadratic form that will tend to display constants.                       *)
chaieb@31119
   426
chaieb@31119
   427
(* Diagonalize (Cholesky/LDU) the matrix corresponding to a quadratic form.  *)
chaieb@31119
   428
chaieb@31119
   429
local
chaieb@31119
   430
fun diagonalize n i m =
wenzelm@32839
   431
 if FuncUtil.Intpairfunc.is_empty (snd m) then []
chaieb@31119
   432
 else
wenzelm@32839
   433
  let val a11 = FuncUtil.Intpairfunc.tryapplyd (snd m) (i,i) rat_0
wenzelm@32332
   434
  in if a11 </ rat_0 then raise Failure "diagonalize: not PSD"
chaieb@31119
   435
    else if a11 =/ rat_0 then
Philipp@32829
   436
          if FuncUtil.Intfunc.is_empty (snd (row i m)) then diagonalize n (i + 1) m
wenzelm@32332
   437
          else raise Failure "diagonalize: not PSD ___ "
chaieb@31119
   438
    else
wenzelm@32839
   439
     let
chaieb@31119
   440
      val v = row i m
wenzelm@32839
   441
      val v' = (fst v, FuncUtil.Intfunc.fold (fn (i, c) => fn a =>
wenzelm@32839
   442
       let val y = c // a11
wenzelm@32839
   443
       in if y = rat_0 then a else FuncUtil.Intfunc.update (i,y) a
Philipp@32829
   444
       end)  (snd v) FuncUtil.Intfunc.empty)
Philipp@32828
   445
      fun upt0 x y a = if y = rat_0 then a else FuncUtil.Intpairfunc.update (x,y) a
chaieb@31119
   446
      val m' =
chaieb@31119
   447
      ((n,n),
chaieb@31119
   448
      iter (i+1,n) (fn j =>
chaieb@31119
   449
          iter (i+1,n) (fn k =>
Philipp@32828
   450
              (upt0 (j,k) (FuncUtil.Intpairfunc.tryapplyd (snd m) (j,k) rat_0 -/ FuncUtil.Intfunc.tryapplyd (snd v) j rat_0 */ FuncUtil.Intfunc.tryapplyd (snd v') k rat_0))))
Philipp@32829
   451
          FuncUtil.Intpairfunc.empty)
wenzelm@32839
   452
     in (a11,v')::diagonalize n (i + 1) m'
chaieb@31119
   453
     end
chaieb@31119
   454
  end
chaieb@31119
   455
in
chaieb@31119
   456
fun diag m =
wenzelm@32839
   457
 let
wenzelm@32839
   458
   val nn = dimensions m
wenzelm@32839
   459
   val n = fst nn
wenzelm@32839
   460
 in if snd nn <> n then error "diagonalize: non-square matrix"
chaieb@31119
   461
    else diagonalize n 1 m
chaieb@31119
   462
 end
chaieb@31119
   463
end;
chaieb@31119
   464
chaieb@31119
   465
(* Enumeration of monomials with given multidegree bound.                    *)
chaieb@31119
   466
wenzelm@32839
   467
fun enumerate_monomials d vars =
chaieb@31119
   468
 if d < 0 then []
Philipp@32829
   469
 else if d = 0 then [FuncUtil.Ctermfunc.empty]
chaieb@31119
   470
 else if null vars then [monomial_1] else
chaieb@31119
   471
 let val alts =
haftmann@33063
   472
  map_range (fn k => let val oths = enumerate_monomials (d - k) (tl vars)
haftmann@33063
   473
               in map (fn ks => if k = 0 then ks else FuncUtil.Ctermfunc.update (hd vars, k) ks) oths end) (d + 1)
Philipp@32830
   474
 in flat alts
chaieb@31119
   475
 end;
chaieb@31119
   476
chaieb@31119
   477
(* Enumerate products of distinct input polys with degree <= d.              *)
chaieb@31119
   478
(* We ignore any constant input polynomials.                                 *)
chaieb@31119
   479
(* Give the output polynomial and a record of how it was derived.            *)
chaieb@31119
   480
chaieb@31119
   481
fun enumerate_products d pols =
wenzelm@32839
   482
if d = 0 then [(poly_const rat_1,RealArith.Rational_lt rat_1)]
chaieb@31119
   483
else if d < 0 then [] else
wenzelm@32839
   484
case pols of
Philipp@32828
   485
   [] => [(poly_const rat_1,RealArith.Rational_lt rat_1)]
wenzelm@32839
   486
 | (p,b)::ps =>
wenzelm@32839
   487
    let val e = multidegree p
chaieb@31119
   488
    in if e = 0 then enumerate_products d ps else
chaieb@31119
   489
       enumerate_products d ps @
Philipp@32828
   490
       map (fn (q,c) => (poly_mul p q,RealArith.Product(b,c)))
chaieb@31119
   491
         (enumerate_products (d - e) ps)
chaieb@31119
   492
    end
chaieb@31119
   493
chaieb@31119
   494
(* Convert regular polynomial. Note that we treat (0,0,0) as -1.             *)
chaieb@31119
   495
chaieb@31119
   496
fun epoly_of_poly p =
Philipp@32829
   497
  FuncUtil.Monomialfunc.fold (fn (m,c) => fn a => FuncUtil.Monomialfunc.update (m, Inttriplefunc.onefunc ((0,0,0), Rat.neg c)) a) p FuncUtil.Monomialfunc.empty;
chaieb@31119
   498
chaieb@31119
   499
(* String for block diagonal matrix numbered k.                              *)
chaieb@31119
   500
chaieb@31119
   501
fun sdpa_of_blockdiagonal k m =
wenzelm@32839
   502
 let
chaieb@31119
   503
  val pfx = string_of_int k ^" "
chaieb@31119
   504
  val ents =
wenzelm@32839
   505
    Inttriplefunc.fold
wenzelm@32839
   506
      (fn ((b,i,j),c) => fn a => if i > j then a else ((b,i,j),c)::a)
wenzelm@32839
   507
      m []
wenzelm@32839
   508
  val entss = sort (triple_int_ord o pairself fst) ents
chaieb@31119
   509
 in fold_rev (fn ((b,i,j),c) => fn a =>
chaieb@31119
   510
     pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
chaieb@31119
   511
     " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
chaieb@31119
   512
 end;
chaieb@31119
   513
chaieb@31119
   514
(* SDPA for problem using block diagonal (i.e. multiple SDPs)                *)
chaieb@31119
   515
Philipp@32268
   516
fun sdpa_of_blockproblem nblocks blocksizes obj mats =
wenzelm@32839
   517
 let val m = length mats - 1
Philipp@32268
   518
 in
chaieb@31119
   519
  string_of_int m ^ "\n" ^
chaieb@31119
   520
  string_of_int nblocks ^ "\n" ^
Philipp@32830
   521
  (space_implode " " (map string_of_int blocksizes)) ^
chaieb@31119
   522
  "\n" ^
chaieb@31119
   523
  sdpa_of_vector obj ^
chaieb@31119
   524
  fold_rev2 (fn k => fn m => fn a => sdpa_of_blockdiagonal (k - 1) m ^ a)
chaieb@31119
   525
    (1 upto length mats) mats ""
chaieb@31119
   526
 end;
chaieb@31119
   527
Philipp@32268
   528
(* Run prover on a problem in block diagonal form.                       *)
Philipp@32268
   529
Philipp@32268
   530
fun run_blockproblem prover nblocks blocksizes obj mats=
Philipp@32268
   531
  parse_csdpoutput (prover (sdpa_of_blockproblem nblocks blocksizes obj mats))
Philipp@32268
   532
chaieb@31119
   533
(* 3D versions of matrix operations to consider blocks separately.           *)
chaieb@31119
   534
chaieb@31119
   535
val bmatrix_add = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0);
chaieb@31119
   536
fun bmatrix_cmul c bm =
Philipp@32829
   537
  if c =/ rat_0 then Inttriplefunc.empty
haftmann@39027
   538
  else Inttriplefunc.map (fn _ => fn x => c */ x) bm;
chaieb@31119
   539
chaieb@31119
   540
val bmatrix_neg = bmatrix_cmul (Rat.rat_of_int ~1);
chaieb@31119
   541
chaieb@31119
   542
(* Smash a block matrix into components.                                     *)
chaieb@31119
   543
chaieb@31119
   544
fun blocks blocksizes bm =
chaieb@31119
   545
 map (fn (bs,b0) =>
chaieb@31119
   546
      let val m = Inttriplefunc.fold
Philipp@32829
   547
          (fn ((b,i,j),c) => fn a => if b = b0 then FuncUtil.Intpairfunc.update ((i,j),c) a else a) bm FuncUtil.Intpairfunc.empty
huffman@44453
   548
          val _ = FuncUtil.Intpairfunc.fold (fn ((i,j),_) => fn a => max a (max i j)) m 0
chaieb@31119
   549
      in (((bs,bs),m):matrix) end)
chaieb@31119
   550
 (blocksizes ~~ (1 upto length blocksizes));;
chaieb@31119
   551
chaieb@31119
   552
(* FIXME : Get rid of this !!!*)
Philipp@32268
   553
local
huffman@44453
   554
  fun tryfind_with msg _ [] = raise Failure msg
huffman@44453
   555
    | tryfind_with _ f (x::xs) = (f x handle Failure s => tryfind_with s f xs);
wenzelm@32839
   556
in
Philipp@32268
   557
  fun tryfind f = tryfind_with "tryfind" f
Philipp@32268
   558
end
Philipp@32268
   559
chaieb@31119
   560
(* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
chaieb@31119
   561
wenzelm@32839
   562
wenzelm@38805
   563
fun real_positivnullstellensatz_general ctxt prover linf d eqs leqs pol =
wenzelm@32839
   564
let
haftmann@33042
   565
 val vars = fold_rev (union (op aconvc) o poly_variables)
haftmann@33042
   566
   (pol :: eqs @ map fst leqs) []
wenzelm@32839
   567
 val monoid = if linf then
Philipp@32828
   568
      (poly_const rat_1,RealArith.Rational_lt rat_1)::
huffman@44453
   569
      (filter (fn (p,_) => multidegree p <= d) leqs)
chaieb@31119
   570
    else enumerate_products d leqs
chaieb@31119
   571
 val nblocks = length monoid
chaieb@31119
   572
 fun mk_idmultiplier k p =
wenzelm@32839
   573
  let
chaieb@31119
   574
   val e = d - multidegree p
chaieb@31119
   575
   val mons = enumerate_monomials e vars
wenzelm@32839
   576
   val nons = mons ~~ (1 upto length mons)
chaieb@31119
   577
  in (mons,
Philipp@32829
   578
      fold_rev (fn (m,n) => FuncUtil.Monomialfunc.update(m,Inttriplefunc.onefunc((~k,~n,n),rat_1))) nons FuncUtil.Monomialfunc.empty)
chaieb@31119
   579
  end
chaieb@31119
   580
huffman@44453
   581
 fun mk_sqmultiplier k (p,_) =
wenzelm@32839
   582
  let
chaieb@31119
   583
   val e = (d - multidegree p) div 2
chaieb@31119
   584
   val mons = enumerate_monomials e vars
wenzelm@32839
   585
   val nons = mons ~~ (1 upto length mons)
wenzelm@32839
   586
  in (mons,
chaieb@31119
   587
      fold_rev (fn (m1,n1) =>
chaieb@31119
   588
       fold_rev (fn (m2,n2) => fn  a =>
wenzelm@32839
   589
        let val m = monomial_mul m1 m2
chaieb@31119
   590
        in if n1 > n2 then a else
chaieb@31119
   591
          let val c = if n1 = n2 then rat_1 else rat_2
wenzelm@32839
   592
              val e = FuncUtil.Monomialfunc.tryapplyd a m Inttriplefunc.empty
Philipp@32828
   593
          in FuncUtil.Monomialfunc.update(m, tri_equation_add (Inttriplefunc.onefunc((k,n1,n2), c)) e) a
chaieb@31119
   594
          end
chaieb@31119
   595
        end)  nons)
Philipp@32829
   596
       nons FuncUtil.Monomialfunc.empty)
chaieb@31119
   597
  end
chaieb@31119
   598
chaieb@31119
   599
  val (sqmonlist,sqs) = split_list (map2 mk_sqmultiplier (1 upto length monoid) monoid)
huffman@44453
   600
  val (_(*idmonlist*),ids) =  split_list(map2 mk_idmultiplier (1 upto length eqs) eqs)
chaieb@31119
   601
  val blocksizes = map length sqmonlist
chaieb@31119
   602
  val bigsum =
chaieb@31119
   603
    fold_rev2 (fn p => fn q => fn a => tri_epoly_pmul p q a) eqs ids
huffman@44453
   604
            (fold_rev2 (fn (p,_) => fn s => fn a => tri_epoly_pmul p s a) monoid sqs
chaieb@31119
   605
                     (epoly_of_poly(poly_neg pol)))
huffman@44453
   606
  val eqns = FuncUtil.Monomialfunc.fold (fn (_,e) => fn a => e::a) bigsum []
chaieb@31119
   607
  val (pvs,assig) = tri_eliminate_all_equations (0,0,0) eqns
chaieb@31119
   608
  val qvars = (0,0,0)::pvs
chaieb@31119
   609
  val allassig = fold_rev (fn v => Inttriplefunc.update(v,(Inttriplefunc.onefunc(v,rat_1)))) pvs assig
chaieb@31119
   610
  fun mk_matrix v =
wenzelm@32839
   611
    Inttriplefunc.fold (fn ((b,i,j), ass) => fn m =>
chaieb@31119
   612
        if b < 0 then m else
chaieb@31119
   613
         let val c = Inttriplefunc.tryapplyd ass v rat_0
chaieb@31119
   614
         in if c = rat_0 then m else
chaieb@31119
   615
            Inttriplefunc.update ((b,j,i), c) (Inttriplefunc.update ((b,i,j), c) m)
chaieb@31119
   616
         end)
Philipp@32829
   617
          allassig Inttriplefunc.empty
chaieb@31119
   618
  val diagents = Inttriplefunc.fold
chaieb@31119
   619
    (fn ((b,i,j), e) => fn a => if b > 0 andalso i = j then tri_equation_add e a else a)
Philipp@32829
   620
    allassig Inttriplefunc.empty
chaieb@31119
   621
chaieb@31119
   622
  val mats = map mk_matrix qvars
chaieb@31119
   623
  val obj = (length pvs,
Philipp@32828
   624
            itern 1 pvs (fn v => fn i => FuncUtil.Intfunc.updatep iszero (i,Inttriplefunc.tryapplyd diagents v rat_0))
Philipp@32829
   625
                        FuncUtil.Intfunc.empty)
chaieb@31119
   626
  val raw_vec = if null pvs then vector_0 0
Philipp@32268
   627
                else tri_scale_then (run_blockproblem prover nblocks blocksizes) obj mats
huffman@44453
   628
  fun int_element (_,v) i = FuncUtil.Intfunc.tryapplyd v i rat_0
chaieb@31119
   629
chaieb@31119
   630
  fun find_rounding d =
wenzelm@32839
   631
   let
wenzelm@32949
   632
    val _ =
wenzelm@38805
   633
      if Config.get ctxt trace
wenzelm@32949
   634
      then writeln ("Trying rounding with limit "^Rat.string_of_rat d ^ "\n")
wenzelm@32949
   635
      else ()
chaieb@31119
   636
    val vec = nice_vector d raw_vec
chaieb@31119
   637
    val blockmat = iter (1,dim vec)
chaieb@31119
   638
     (fn i => fn a => bmatrix_add (bmatrix_cmul (int_element vec i) (nth mats i)) a)
chaieb@31119
   639
     (bmatrix_neg (nth mats 0))
wenzelm@32839
   640
    val allmats = blocks blocksizes blockmat
chaieb@31119
   641
   in (vec,map diag allmats)
chaieb@31119
   642
   end
chaieb@31119
   643
  val (vec,ratdias) =
chaieb@31119
   644
    if null pvs then find_rounding rat_1
chaieb@31119
   645
    else tryfind find_rounding (map Rat.rat_of_int (1 upto 31) @
chaieb@31119
   646
                                map pow2 (5 upto 66))
chaieb@31119
   647
  val newassigs =
chaieb@31119
   648
    fold_rev (fn k => Inttriplefunc.update (nth pvs (k - 1), int_element vec k))
chaieb@31119
   649
           (1 upto dim vec) (Inttriplefunc.onefunc ((0,0,0), Rat.rat_of_int ~1))
chaieb@31119
   650
  val finalassigs =
chaieb@31119
   651
    Inttriplefunc.fold (fn (v,e) => fn a => Inttriplefunc.update(v, tri_equation_eval newassigs e) a) allassig newassigs
chaieb@31119
   652
  fun poly_of_epoly p =
Philipp@32828
   653
    FuncUtil.Monomialfunc.fold (fn (v,e) => fn a => FuncUtil.Monomialfunc.updatep iszero (v,tri_equation_eval finalassigs e) a)
Philipp@32829
   654
          p FuncUtil.Monomialfunc.empty
chaieb@31119
   655
  fun  mk_sos mons =
chaieb@31119
   656
   let fun mk_sq (c,m) =
Philipp@32828
   657
    (c,fold_rev (fn k=> fn a => FuncUtil.Monomialfunc.updatep iszero (nth mons (k - 1), int_element m k) a)
Philipp@32829
   658
                 (1 upto length mons) FuncUtil.Monomialfunc.empty)
chaieb@31119
   659
   in map mk_sq
chaieb@31119
   660
   end
chaieb@31119
   661
  val sqs = map2 mk_sos sqmonlist ratdias
chaieb@31119
   662
  val cfs = map poly_of_epoly ids
huffman@44453
   663
  val msq = filter (fn (_,b) => not (null b)) (map2 pair monoid sqs)
chaieb@31119
   664
  fun eval_sq sqs = fold_rev (fn (c,q) => poly_add (poly_cmul c (poly_mul q q))) sqs poly_0
chaieb@31119
   665
  val sanity =
huffman@44453
   666
    fold_rev (fn ((p,_),s) => poly_add (poly_mul p (eval_sq s))) msq
chaieb@31119
   667
           (fold_rev2 (fn p => fn q => poly_add (poly_mul p q)) cfs eqs
chaieb@31119
   668
                    (poly_neg pol))
chaieb@31119
   669
Philipp@32829
   670
in if not(FuncUtil.Monomialfunc.is_empty sanity) then raise Sanity else
chaieb@31119
   671
  (cfs,map (fn (a,b) => (snd a,b)) msq)
chaieb@31119
   672
 end
chaieb@31119
   673
chaieb@31119
   674
chaieb@31119
   675
(* Iterative deepening.                                                      *)
chaieb@31119
   676
wenzelm@32839
   677
fun deepen f n =
wenzelm@32949
   678
  (writeln ("Searching with depth limit " ^ string_of_int n);
wenzelm@32949
   679
    (f n handle Failure s => (writeln ("failed with message: " ^ s); deepen f (n + 1))));
chaieb@31119
   680
chaieb@31119
   681
Philipp@32645
   682
(* Map back polynomials and their composites to a positivstellensatz.        *)
chaieb@31119
   683
Philipp@32828
   684
fun cterm_of_sqterm (c,p) = RealArith.Product(RealArith.Rational_lt c,RealArith.Square p);
chaieb@31119
   685
chaieb@31119
   686
fun cterm_of_sos (pr,sqs) = if null sqs then pr
Philipp@32830
   687
  else RealArith.Product(pr,foldr1 RealArith.Sum (map cterm_of_sqterm sqs));
chaieb@31119
   688
chaieb@31119
   689
(* Interface to HOL.                                                         *)
chaieb@31119
   690
local
Philipp@32828
   691
  open Conv
Philipp@32828
   692
  val concl = Thm.dest_arg o cprop_of
wenzelm@35408
   693
  fun simple_cterm_ord t u = Term_Ord.fast_term_ord (term_of t, term_of u) = LESS
chaieb@31119
   694
in
chaieb@31119
   695
  (* FIXME: Replace tryfind by get_first !! *)
Philipp@32645
   696
fun real_nonlinear_prover proof_method ctxt =
wenzelm@32839
   697
 let
huffman@44453
   698
  val {add = _, mul = _, neg = _, pow = _,
huffman@44453
   699
       sub = _, main = real_poly_conv} =
huffman@44453
   700
      Semiring_Normalizer.semiring_normalizers_ord_wrapper ctxt
haftmann@36753
   701
      (the (Semiring_Normalizer.match ctxt @{cterm "(0::real) + 1"}))
chaieb@31119
   702
     simple_cterm_ord
wenzelm@32839
   703
  fun mainf cert_choice translator (eqs,les,lts) =
wenzelm@32839
   704
  let
Philipp@32828
   705
   val eq0 = map (poly_of_term o Thm.dest_arg1 o concl) eqs
Philipp@32828
   706
   val le0 = map (poly_of_term o Thm.dest_arg o concl) les
Philipp@32828
   707
   val lt0 = map (poly_of_term o Thm.dest_arg o concl) lts
haftmann@33063
   708
   val eqp0 = map_index (fn (i, t) => (t,RealArith.Axiom_eq i)) eq0
haftmann@33063
   709
   val lep0 = map_index (fn (i, t) => (t,RealArith.Axiom_le i)) le0
haftmann@33063
   710
   val ltp0 = map_index (fn (i, t) => (t,RealArith.Axiom_lt i)) lt0
chaieb@31119
   711
   val (keq,eq) = List.partition (fn (p,_) => multidegree p = 0) eqp0
chaieb@31119
   712
   val (klep,lep) = List.partition (fn (p,_) => multidegree p = 0) lep0
chaieb@31119
   713
   val (kltp,ltp) = List.partition (fn (p,_) => multidegree p = 0) ltp0
chaieb@31119
   714
   fun trivial_axiom (p,ax) =
chaieb@31119
   715
    case ax of
wenzelm@32839
   716
       RealArith.Axiom_eq n => if eval FuncUtil.Ctermfunc.empty p <>/ Rat.zero then nth eqs n
wenzelm@32332
   717
                     else raise Failure "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   718
     | RealArith.Axiom_le n => if eval FuncUtil.Ctermfunc.empty p </ Rat.zero then nth les n
wenzelm@32332
   719
                     else raise Failure "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   720
     | RealArith.Axiom_lt n => if eval FuncUtil.Ctermfunc.empty p <=/ Rat.zero then nth lts n
wenzelm@32332
   721
                     else raise Failure "trivial_axiom: Not a trivial axiom"
chaieb@31119
   722
     | _ => error "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   723
   in
Philipp@32645
   724
  (let val th = tryfind trivial_axiom (keq @ klep @ kltp)
Philipp@32645
   725
   in
haftmann@36751
   726
    (fconv_rule (arg_conv (arg1_conv real_poly_conv) then_conv Numeral_Simprocs.field_comp_conv) th, RealArith.Trivial)
Philipp@32645
   727
   end)
wenzelm@32839
   728
   handle Failure _ =>
Philipp@32645
   729
     (let val proof =
Philipp@32645
   730
       (case proof_method of Certificate certs =>
Philipp@32645
   731
         (* choose certificate *)
Philipp@32645
   732
         let
Philipp@32828
   733
           fun chose_cert [] (RealArith.Cert c) = c
Philipp@32828
   734
             | chose_cert (RealArith.Left::s) (RealArith.Branch (l, _)) = chose_cert s l
Philipp@32828
   735
             | chose_cert (RealArith.Right::s) (RealArith.Branch (_, r)) = chose_cert s r
Philipp@32645
   736
             | chose_cert _ _ = error "certificate tree in invalid form"
Philipp@32645
   737
         in
Philipp@32645
   738
           chose_cert cert_choice certs
Philipp@32645
   739
         end
Philipp@32645
   740
       | Prover prover =>
Philipp@32645
   741
         (* call prover *)
wenzelm@32839
   742
         let
Philipp@32645
   743
          val pol = fold_rev poly_mul (map fst ltp) (poly_const Rat.one)
Philipp@32645
   744
          val leq = lep @ ltp
Philipp@32645
   745
          fun tryall d =
Philipp@32645
   746
           let val e = multidegree pol
Philipp@32645
   747
               val k = if e = 0 then 0 else d div e
wenzelm@32839
   748
               val eq' = map fst eq
wenzelm@38805
   749
           in tryfind (fn i => (d,i,real_positivnullstellensatz_general ctxt prover false d eq' leq
Philipp@32645
   750
                                 (poly_neg(poly_pow pol i))))
Philipp@32645
   751
                   (0 upto k)
Philipp@32645
   752
           end
huffman@44453
   753
         val (_,i,(cert_ideal,cert_cone)) = deepen tryall 0
Philipp@32645
   754
         val proofs_ideal =
huffman@44453
   755
           map2 (fn q => fn (_,ax) => RealArith.Eqmul(q,ax)) cert_ideal eq
Philipp@32645
   756
         val proofs_cone = map cterm_of_sos cert_cone
Philipp@32828
   757
         val proof_ne = if null ltp then RealArith.Rational_lt Rat.one else
wenzelm@32839
   758
           let val p = foldr1 RealArith.Product (map snd ltp)
Philipp@32828
   759
           in  funpow i (fn q => RealArith.Product(p,q)) (RealArith.Rational_lt Rat.one)
Philipp@32645
   760
           end
wenzelm@32839
   761
         in
wenzelm@32839
   762
           foldr1 RealArith.Sum (proof_ne :: proofs_ideal @ proofs_cone)
Philipp@32645
   763
         end)
Philipp@32645
   764
     in
Philipp@32828
   765
        (translator (eqs,les,lts) proof, RealArith.Cert proof)
Philipp@32645
   766
     end)
chaieb@31119
   767
   end
chaieb@31119
   768
 in mainf end
chaieb@31119
   769
end
chaieb@31119
   770
chaieb@31119
   771
fun C f x y = f y x;
chaieb@31119
   772
  (* FIXME : This is very bad!!!*)
wenzelm@32839
   773
fun subst_conv eqs t =
wenzelm@32839
   774
 let
wenzelm@46497
   775
  val t' = fold (Thm.lambda o Thm.lhs_of) eqs t
wenzelm@36945
   776
 in Conv.fconv_rule (Thm.beta_conversion true) (fold (C Thm.combination) eqs (Thm.reflexive t'))
chaieb@31119
   777
 end
chaieb@31119
   778
chaieb@31119
   779
(* A wrapper that tries to substitute away variables first.                  *)
chaieb@31119
   780
chaieb@31119
   781
local
Philipp@32828
   782
 open Conv
wenzelm@35408
   783
  fun simple_cterm_ord t u = Term_Ord.fast_term_ord (term_of t, term_of u) = LESS
Philipp@32828
   784
 val concl = Thm.dest_arg o cprop_of
wenzelm@32839
   785
 val shuffle1 =
haftmann@36350
   786
   fconv_rule (rewr_conv @{lemma "(a + x == y) == (x == y - (a::real))" by (atomize (full)) (simp add: field_simps) })
chaieb@31119
   787
 val shuffle2 =
haftmann@36350
   788
    fconv_rule (rewr_conv @{lemma "(x + a == y) ==  (x == y - (a::real))" by (atomize (full)) (simp add: field_simps)})
chaieb@31119
   789
 fun substitutable_monomial fvs tm = case term_of tm of
wenzelm@32839
   790
    Free(_,@{typ real}) => if not (member (op aconvc) fvs tm) then (Rat.one,tm)
wenzelm@32332
   791
                           else raise Failure "substitutable_monomial"
huffman@44453
   792
  | @{term "op * :: real => _"}$_$(Free _) =>
Philipp@32828
   793
     if RealArith.is_ratconst (Thm.dest_arg1 tm) andalso not (member (op aconvc) fvs (Thm.dest_arg tm))
Philipp@32828
   794
         then (RealArith.dest_ratconst (Thm.dest_arg1 tm),Thm.dest_arg tm) else raise Failure "substitutable_monomial"
huffman@44453
   795
  | @{term "op + :: real => _"}$_$_ =>
Philipp@32828
   796
       (substitutable_monomial (Thm.add_cterm_frees (Thm.dest_arg tm) fvs) (Thm.dest_arg1 tm)
Philipp@32828
   797
        handle Failure _ => substitutable_monomial (Thm.add_cterm_frees (Thm.dest_arg1 tm) fvs) (Thm.dest_arg tm))
wenzelm@32332
   798
  | _ => raise Failure "substitutable_monomial"
chaieb@31119
   799
wenzelm@32839
   800
  fun isolate_variable v th =
Philipp@32828
   801
   let val w = Thm.dest_arg1 (cprop_of th)
chaieb@31119
   802
   in if v aconvc w then th
chaieb@31119
   803
      else case term_of w of
huffman@44453
   804
           @{term "op + :: real => _"}$_$_ =>
wenzelm@32839
   805
              if Thm.dest_arg1 w aconvc v then shuffle2 th
chaieb@31119
   806
              else isolate_variable v (shuffle1 th)
chaieb@31119
   807
          | _ => error "isolate variable : This should not happen?"
wenzelm@32839
   808
   end
chaieb@31119
   809
in
chaieb@31119
   810
Philipp@32268
   811
fun real_nonlinear_subst_prover prover ctxt =
wenzelm@32839
   812
 let
huffman@44453
   813
  val {add = _, mul = real_poly_mul_conv, neg = _,
huffman@44453
   814
       pow = _, sub = _, main = real_poly_conv} =
huffman@44453
   815
      Semiring_Normalizer.semiring_normalizers_ord_wrapper ctxt
haftmann@36753
   816
      (the (Semiring_Normalizer.match ctxt @{cterm "(0::real) + 1"}))
chaieb@31119
   817
     simple_cterm_ord
chaieb@31119
   818
chaieb@31119
   819
  fun make_substitution th =
wenzelm@32839
   820
   let
Philipp@32828
   821
    val (c,v) = substitutable_monomial [] (Thm.dest_arg1(concl th))
wenzelm@46497
   822
    val th1 = Drule.arg_cong_rule (Thm.apply @{cterm "op * :: real => _"} (RealArith.cterm_of_rat (Rat.inv c))) (mk_meta_eq th)
chaieb@31119
   823
    val th2 = fconv_rule (binop_conv real_poly_mul_conv) th1
chaieb@31119
   824
   in fconv_rule (arg_conv real_poly_conv) (isolate_variable v th2)
chaieb@31119
   825
   end
wenzelm@32839
   826
   fun oprconv cv ct =
chaieb@31119
   827
    let val g = Thm.dest_fun2 ct
wenzelm@32839
   828
    in if g aconvc @{cterm "op <= :: real => _"}
wenzelm@32839
   829
         orelse g aconvc @{cterm "op < :: real => _"}
chaieb@31119
   830
       then arg_conv cv ct else arg1_conv cv ct
chaieb@31119
   831
    end
Philipp@32645
   832
  fun mainf cert_choice translator =
wenzelm@32839
   833
   let
chaieb@31119
   834
    fun substfirst(eqs,les,lts) =
wenzelm@32839
   835
      ((let
chaieb@31119
   836
           val eth = tryfind make_substitution eqs
chaieb@31119
   837
           val modify = fconv_rule (arg_conv (oprconv(subst_conv [eth] then_conv real_poly_conv)))
chaieb@31119
   838
       in  substfirst
wenzelm@32839
   839
             (filter_out (fn t => (Thm.dest_arg1 o Thm.dest_arg o cprop_of) t
chaieb@31119
   840
                                   aconvc @{cterm "0::real"}) (map modify eqs),
chaieb@31119
   841
                                   map modify les,map modify lts)
chaieb@31119
   842
       end)
Philipp@32645
   843
       handle Failure  _ => real_nonlinear_prover prover ctxt cert_choice translator (rev eqs, rev les, rev lts))
chaieb@31119
   844
    in substfirst
chaieb@31119
   845
   end
chaieb@31119
   846
chaieb@31119
   847
chaieb@31119
   848
 in mainf
chaieb@31119
   849
 end
chaieb@31119
   850
chaieb@31119
   851
(* Overall function. *)
chaieb@31119
   852
Philipp@32645
   853
fun real_sos prover ctxt =
Philipp@32828
   854
  RealArith.gen_prover_real_arith ctxt (real_nonlinear_subst_prover prover ctxt)
chaieb@31119
   855
end;
chaieb@31119
   856
wenzelm@32839
   857
val known_sos_constants =
wenzelm@32839
   858
  [@{term "op ==>"}, @{term "Trueprop"},
haftmann@38795
   859
   @{term HOL.implies}, @{term HOL.conj}, @{term HOL.disj},
wenzelm@32839
   860
   @{term "Not"}, @{term "op = :: bool => _"},
wenzelm@32839
   861
   @{term "All :: (real => _) => _"}, @{term "Ex :: (real => _) => _"},
wenzelm@32839
   862
   @{term "op = :: real => _"}, @{term "op < :: real => _"},
wenzelm@32839
   863
   @{term "op <= :: real => _"},
wenzelm@32839
   864
   @{term "op + :: real => _"}, @{term "op - :: real => _"},
wenzelm@32839
   865
   @{term "op * :: real => _"}, @{term "uminus :: real => _"},
chaieb@31512
   866
   @{term "op / :: real => _"}, @{term "inverse :: real => _"},
wenzelm@32839
   867
   @{term "op ^ :: real => _"}, @{term "abs :: real => _"},
chaieb@31512
   868
   @{term "min :: real => _"}, @{term "max :: real => _"},
huffman@47108
   869
   @{term "0::real"}, @{term "1::real"},
huffman@47108
   870
   @{term "numeral :: num => nat"},
huffman@47108
   871
   @{term "numeral :: num => real"},
huffman@47108
   872
   @{term "neg_numeral :: num => real"},
huffman@47108
   873
   @{term "Num.Bit0"}, @{term "Num.Bit1"}, @{term "Num.One"}];
chaieb@31512
   874
wenzelm@32839
   875
fun check_sos kcts ct =
chaieb@31512
   876
 let
chaieb@31512
   877
  val t = term_of ct
wenzelm@32839
   878
  val _ = if not (null (Term.add_tfrees t [])
wenzelm@32839
   879
                  andalso null (Term.add_tvars t []))
chaieb@31512
   880
          then error "SOS: not sos. Additional type varables" else ()
chaieb@31512
   881
  val fs = Term.add_frees t []
wenzelm@32839
   882
  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs
chaieb@31512
   883
          then error "SOS: not sos. Variables with type not real" else ()
chaieb@31512
   884
  val vs = Term.add_vars t []
wenzelm@32839
   885
  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) vs
chaieb@31512
   886
          then error "SOS: not sos. Variables with type not real" else ()
chaieb@31512
   887
  val ukcs = subtract (fn (t,p) => Const p aconv t) kcts (Term.add_consts t [])
wenzelm@32839
   888
  val _ = if  null ukcs then ()
chaieb@31512
   889
              else error ("SOSO: Unknown constants in Subgoal:" ^ commas (map fst ukcs))
chaieb@31512
   890
in () end
chaieb@31512
   891
wenzelm@32838
   892
fun core_sos_tac print_cert prover = SUBPROOF (fn {concl, context, ...} =>
Philipp@32831
   893
  let
wenzelm@32838
   894
    val _ = check_sos known_sos_constants concl
wenzelm@32838
   895
    val (ths, certificates) = real_sos prover context (Thm.dest_arg concl)
wenzelm@32838
   896
    val _ = print_cert certificates
wenzelm@32838
   897
  in rtac ths 1 end)
chaieb@31131
   898
huffman@44453
   899
fun default_SOME _ NONE v = SOME v
huffman@44453
   900
  | default_SOME _ (SOME v) _ = SOME v;
chaieb@31131
   901
chaieb@31131
   902
fun lift_SOME f NONE a = f a
huffman@44453
   903
  | lift_SOME _ (SOME a) _ = SOME a;
chaieb@31131
   904
chaieb@31131
   905
chaieb@31131
   906
local
chaieb@31131
   907
 val is_numeral = can (HOLogic.dest_number o term_of)
chaieb@31131
   908
in
chaieb@31131
   909
fun get_denom b ct = case term_of ct of
wenzelm@32839
   910
  @{term "op / :: real => _"} $ _ $ _ =>
chaieb@31131
   911
     if is_numeral (Thm.dest_arg ct) then get_denom b (Thm.dest_arg1 ct)
chaieb@31131
   912
     else default_SOME (get_denom b) (get_denom b (Thm.dest_arg ct))   (Thm.dest_arg ct, b)
chaieb@31131
   913
 | @{term "op < :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
chaieb@31131
   914
 | @{term "op <= :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
chaieb@31131
   915
 | _ $ _ => lift_SOME (get_denom b) (get_denom b (Thm.dest_fun ct)) (Thm.dest_arg ct)
chaieb@31131
   916
 | _ => NONE
chaieb@31131
   917
end;
chaieb@31131
   918
wenzelm@32839
   919
fun elim_one_denom_tac ctxt =
wenzelm@32839
   920
CSUBGOAL (fn (P,i) =>
wenzelm@32839
   921
 case get_denom false P of
chaieb@31131
   922
   NONE => no_tac
wenzelm@32839
   923
 | SOME (d,ord) =>
wenzelm@32839
   924
     let
wenzelm@32839
   925
      val ss = simpset_of ctxt addsimps @{thms field_simps}
chaieb@31131
   926
               addsimps [@{thm nonzero_power_divide}, @{thm power_divide}]
wenzelm@32839
   927
      val th = instantiate' [] [SOME d, SOME (Thm.dest_arg P)]
chaieb@31131
   928
         (if ord then @{lemma "(d=0 --> P) & (d>0 --> P) & (d<(0::real) --> P) ==> P" by auto}
chaieb@31131
   929
          else @{lemma "(d=0 --> P) & (d ~= (0::real) --> P) ==> P" by blast})
wenzelm@32949
   930
     in rtac th i THEN Simplifier.asm_full_simp_tac ss i end);
chaieb@31131
   931
chaieb@31131
   932
fun elim_denom_tac ctxt i = REPEAT (elim_one_denom_tac ctxt i);
chaieb@31131
   933
wenzelm@32949
   934
fun sos_tac print_cert prover ctxt =
wenzelm@35625
   935
  Object_Logic.full_atomize_tac THEN'
wenzelm@32949
   936
  elim_denom_tac ctxt THEN'
wenzelm@32949
   937
  core_sos_tac print_cert prover ctxt;
chaieb@31131
   938
chaieb@31512
   939
end;