src/HOL/Library/Sum_of_Squares/sum_of_squares.ML
author wenzelm
Sat Dec 14 17:28:05 2013 +0100 (2013-12-14)
changeset 54742 7a86358a3c0b
parent 54489 03ff4d1e6784
child 55508 90c42b130652
permissions -rw-r--r--
proper context for basic Simplifier operations: rewrite_rule, rewrite_goals_rule, rewrite_goals_tac etc.;
clarified tool context in some boundary cases;
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
wenzelm@53975
   278
haftmann@36692
   279
fun isnum x = member (op =) ["0","1","2","3","4","5","6","7","8","9"] x;
chaieb@31119
   280
wenzelm@53975
   281
(* More parser basics. *)
wenzelm@53975
   282
(* FIXME improper use of parser combinators ahead *)
chaieb@31119
   283
Philipp@32828
   284
 val numeral = Scan.one isnum
Philipp@33906
   285
 val decimalint = Scan.repeat1 numeral >> (rat_of_string o implode)
Philipp@33906
   286
 val decimalfrac = Scan.repeat1 numeral
chaieb@31119
   287
    >> (fn s => rat_of_string(implode s) // pow10 (length s))
chaieb@31119
   288
 val decimalsig =
Philipp@32828
   289
    decimalint -- Scan.option (Scan.$$ "." |-- decimalfrac)
chaieb@31119
   290
    >> (fn (h,NONE) => h | (h,SOME x) => h +/ x)
chaieb@31119
   291
 fun signed prs =
wenzelm@32839
   292
       $$ "-" |-- prs >> Rat.neg
chaieb@31119
   293
    || $$ "+" |-- prs
chaieb@31119
   294
    || prs;
chaieb@31119
   295
chaieb@31119
   296
fun emptyin def xs = if null xs then (def,xs) else Scan.fail xs
chaieb@31119
   297
chaieb@31119
   298
 val exponent = ($$ "e" || $$ "E") |-- signed decimalint;
chaieb@31119
   299
chaieb@31119
   300
 val decimal = signed decimalsig -- (emptyin rat_0|| exponent)
chaieb@31119
   301
    >> (fn (h, x) => h */ pow10 (int_of_rat x));
chaieb@31119
   302
wenzelm@53975
   303
 fun mkparser p s =
wenzelm@53975
   304
  let val (x,rst) = p (raw_explode s)
wenzelm@53975
   305
  in if null rst then x
wenzelm@53975
   306
     else error "mkparser: unparsed input"
wenzelm@53975
   307
  end;;
wenzelm@53975
   308
wenzelm@32332
   309
(* Parse back csdp output.                                                      *)
wenzelm@53975
   310
(* FIXME improper use of parser combinators ahead *)
chaieb@31119
   311
huffman@44453
   312
 fun ignore _ = ((),[])
wenzelm@33067
   313
 fun csdpoutput inp =
wenzelm@33067
   314
   ((decimal -- Scan.repeat (Scan.$$ " " |-- Scan.option decimal) >>
wenzelm@33067
   315
    (fn (h,to) => map_filter I ((SOME h)::to))) --| ignore >> vector_of_list) inp
wenzelm@53975
   316
 val parse_csdpoutput = mkparser csdpoutput
chaieb@31119
   317
chaieb@31119
   318
(* Try some apparently sensible scaling first. Note that this is purely to   *)
chaieb@31119
   319
(* get a cleaner translation to floating-point, and doesn't affect any of    *)
chaieb@31119
   320
(* the results, in principle. In practice it seems a lot better when there   *)
chaieb@31119
   321
(* are extreme numbers in the original problem.                              *)
chaieb@31119
   322
chaieb@31119
   323
  (* Version for (int*int*int) keys *)
chaieb@31119
   324
local
chaieb@31119
   325
  fun max_rat x y = if x </ y then y else x
chaieb@31119
   326
  fun common_denominator fld amat acc =
huffman@44453
   327
      fld (fn (_,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
chaieb@31119
   328
  fun maximal_element fld amat acc =
huffman@44453
   329
    fld (fn (_,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc
chaieb@31119
   330
fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
wenzelm@41490
   331
                     in Real.fromInt a / Real.fromInt b end;
chaieb@31119
   332
fun int_of_float x = (trunc x handle Overflow => 0 | Domain => 0)
chaieb@31119
   333
in
chaieb@31119
   334
chaieb@31119
   335
fun tri_scale_then solver (obj:vector)  mats =
wenzelm@32839
   336
 let
chaieb@31119
   337
  val cd1 = fold_rev (common_denominator Inttriplefunc.fold) mats (rat_1)
wenzelm@32839
   338
  val cd2 = common_denominator FuncUtil.Intfunc.fold (snd obj)  (rat_1)
haftmann@39027
   339
  val mats' = map (Inttriplefunc.map (fn _ => fn x => cd1 */ x)) mats
chaieb@31119
   340
  val obj' = vector_cmul cd2 obj
chaieb@31119
   341
  val max1 = fold_rev (maximal_element Inttriplefunc.fold) mats' (rat_0)
wenzelm@32839
   342
  val max2 = maximal_element FuncUtil.Intfunc.fold (snd obj') (rat_0)
chaieb@31119
   343
  val scal1 = pow2 (20 - int_of_float(Math.ln (float_of_rat max1) / Math.ln 2.0))
wenzelm@32839
   344
  val scal2 = pow2 (20 - int_of_float(Math.ln (float_of_rat max2) / Math.ln 2.0))
haftmann@39027
   345
  val mats'' = map (Inttriplefunc.map (fn _ => fn x => x */ scal1)) mats'
wenzelm@32839
   346
  val obj'' = vector_cmul scal2 obj'
chaieb@31119
   347
 in solver obj'' mats''
chaieb@31119
   348
  end
chaieb@31119
   349
end;
chaieb@31119
   350
chaieb@31119
   351
(* Round a vector to "nice" rationals.                                       *)
chaieb@31119
   352
chaieb@31119
   353
fun nice_rational n x = round_rat (n */ x) // n;;
wenzelm@32839
   354
fun nice_vector n ((d,v) : vector) =
wenzelm@32839
   355
 (d, FuncUtil.Intfunc.fold (fn (i,c) => fn a =>
wenzelm@32839
   356
   let val y = nice_rational n c
wenzelm@32839
   357
   in if c =/ rat_0 then a
Philipp@32829
   358
      else FuncUtil.Intfunc.update (i,y) a end) v FuncUtil.Intfunc.empty):vector
chaieb@31119
   359
chaieb@31119
   360
fun dest_ord f x = is_equal (f x);
chaieb@31119
   361
chaieb@31119
   362
(* Stuff for "equations" ((int*int*int)->num functions).                         *)
chaieb@31119
   363
chaieb@31119
   364
fun tri_equation_cmul c eq =
haftmann@39027
   365
  if c =/ rat_0 then Inttriplefunc.empty else Inttriplefunc.map (fn _ => fn d => c */ d) eq;
chaieb@31119
   366
chaieb@31119
   367
fun tri_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
chaieb@31119
   368
chaieb@31119
   369
fun tri_equation_eval assig eq =
wenzelm@32839
   370
 let fun value v = Inttriplefunc.apply assig v
chaieb@31119
   371
 in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
chaieb@31119
   372
 end;
chaieb@31119
   373
chaieb@31119
   374
(* Eliminate all variables, in an essentially arbitrary order.               *)
chaieb@31119
   375
chaieb@31119
   376
fun tri_eliminate_all_equations one =
wenzelm@32839
   377
 let
chaieb@31119
   378
  fun choose_variable eq =
wenzelm@32839
   379
   let val (v,_) = Inttriplefunc.choose eq
chaieb@31119
   380
   in if is_equal (triple_int_ord(v,one)) then
wenzelm@32839
   381
      let val eq' = Inttriplefunc.delete_safe v eq
wenzelm@32839
   382
      in if Inttriplefunc.is_empty eq' then error "choose_variable"
chaieb@31119
   383
         else fst (Inttriplefunc.choose eq')
chaieb@31119
   384
      end
wenzelm@32839
   385
    else v
chaieb@31119
   386
   end
wenzelm@32839
   387
  fun eliminate dun eqs = case eqs of
chaieb@31119
   388
    [] => dun
chaieb@31119
   389
  | eq::oeqs =>
Philipp@32829
   390
    if Inttriplefunc.is_empty eq then eliminate dun oeqs else
chaieb@31119
   391
    let val v = choose_variable eq
chaieb@31119
   392
        val a = Inttriplefunc.apply eq v
wenzelm@32839
   393
        val eq' = tri_equation_cmul ((Rat.rat_of_int ~1) // a)
Philipp@32829
   394
                   (Inttriplefunc.delete_safe v eq)
chaieb@31119
   395
        fun elim e =
wenzelm@32839
   396
         let val b = Inttriplefunc.tryapplyd e v rat_0
wenzelm@32839
   397
         in if b =/ rat_0 then e
chaieb@31119
   398
            else tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
chaieb@31119
   399
         end
haftmann@39027
   400
    in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.map (K elim) dun))
wenzelm@32839
   401
                 (map elim oeqs)
chaieb@31119
   402
    end
chaieb@31119
   403
in fn eqs =>
wenzelm@32839
   404
 let
Philipp@32829
   405
  val assig = eliminate Inttriplefunc.empty eqs
huffman@44453
   406
  val vs = Inttriplefunc.fold (fn (_, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
chaieb@31119
   407
 in (distinct (dest_ord triple_int_ord) vs,assig)
chaieb@31119
   408
 end
chaieb@31119
   409
end;
wenzelm@32839
   410
chaieb@31119
   411
(* Multiply equation-parametrized poly by regular poly and add accumulator.  *)
chaieb@31119
   412
chaieb@31119
   413
fun tri_epoly_pmul p q acc =
Philipp@32828
   414
 FuncUtil.Monomialfunc.fold (fn (m1, c) => fn a =>
Philipp@32828
   415
  FuncUtil.Monomialfunc.fold (fn (m2,e) => fn b =>
chaieb@31119
   416
   let val m =  monomial_mul m1 m2
wenzelm@32839
   417
       val es = FuncUtil.Monomialfunc.tryapplyd b m Inttriplefunc.empty
wenzelm@32839
   418
   in FuncUtil.Monomialfunc.update (m,tri_equation_add (tri_equation_cmul c e) es) b
chaieb@31119
   419
   end) q a) p acc ;
chaieb@31119
   420
chaieb@31119
   421
(* Hence produce the "relevant" monomials: those whose squares lie in the    *)
chaieb@31119
   422
(* Newton polytope of the monomials in the input. (This is enough according  *)
chaieb@31119
   423
(* to Reznik: "Extremal PSD forms with few terms", Duke Math. Journal,       *)
chaieb@31119
   424
(* vol 45, pp. 363--374, 1978.                                               *)
chaieb@31119
   425
(*                                                                           *)
chaieb@31119
   426
(* These are ordered in sort of decreasing degree. In particular the         *)
chaieb@31119
   427
(* constant monomial is last; this gives an order in diagonalization of the  *)
chaieb@31119
   428
(* quadratic form that will tend to display constants.                       *)
chaieb@31119
   429
chaieb@31119
   430
(* Diagonalize (Cholesky/LDU) the matrix corresponding to a quadratic form.  *)
chaieb@31119
   431
chaieb@31119
   432
local
chaieb@31119
   433
fun diagonalize n i m =
wenzelm@32839
   434
 if FuncUtil.Intpairfunc.is_empty (snd m) then []
chaieb@31119
   435
 else
wenzelm@32839
   436
  let val a11 = FuncUtil.Intpairfunc.tryapplyd (snd m) (i,i) rat_0
wenzelm@32332
   437
  in if a11 </ rat_0 then raise Failure "diagonalize: not PSD"
chaieb@31119
   438
    else if a11 =/ rat_0 then
Philipp@32829
   439
          if FuncUtil.Intfunc.is_empty (snd (row i m)) then diagonalize n (i + 1) m
wenzelm@32332
   440
          else raise Failure "diagonalize: not PSD ___ "
chaieb@31119
   441
    else
wenzelm@32839
   442
     let
chaieb@31119
   443
      val v = row i m
wenzelm@32839
   444
      val v' = (fst v, FuncUtil.Intfunc.fold (fn (i, c) => fn a =>
wenzelm@32839
   445
       let val y = c // a11
wenzelm@32839
   446
       in if y = rat_0 then a else FuncUtil.Intfunc.update (i,y) a
Philipp@32829
   447
       end)  (snd v) FuncUtil.Intfunc.empty)
Philipp@32828
   448
      fun upt0 x y a = if y = rat_0 then a else FuncUtil.Intpairfunc.update (x,y) a
chaieb@31119
   449
      val m' =
chaieb@31119
   450
      ((n,n),
chaieb@31119
   451
      iter (i+1,n) (fn j =>
chaieb@31119
   452
          iter (i+1,n) (fn k =>
Philipp@32828
   453
              (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
   454
          FuncUtil.Intpairfunc.empty)
wenzelm@32839
   455
     in (a11,v')::diagonalize n (i + 1) m'
chaieb@31119
   456
     end
chaieb@31119
   457
  end
chaieb@31119
   458
in
chaieb@31119
   459
fun diag m =
wenzelm@32839
   460
 let
wenzelm@32839
   461
   val nn = dimensions m
wenzelm@32839
   462
   val n = fst nn
wenzelm@32839
   463
 in if snd nn <> n then error "diagonalize: non-square matrix"
chaieb@31119
   464
    else diagonalize n 1 m
chaieb@31119
   465
 end
chaieb@31119
   466
end;
chaieb@31119
   467
chaieb@31119
   468
(* Enumeration of monomials with given multidegree bound.                    *)
chaieb@31119
   469
wenzelm@32839
   470
fun enumerate_monomials d vars =
chaieb@31119
   471
 if d < 0 then []
Philipp@32829
   472
 else if d = 0 then [FuncUtil.Ctermfunc.empty]
chaieb@31119
   473
 else if null vars then [monomial_1] else
chaieb@31119
   474
 let val alts =
haftmann@33063
   475
  map_range (fn k => let val oths = enumerate_monomials (d - k) (tl vars)
haftmann@33063
   476
               in map (fn ks => if k = 0 then ks else FuncUtil.Ctermfunc.update (hd vars, k) ks) oths end) (d + 1)
Philipp@32830
   477
 in flat alts
chaieb@31119
   478
 end;
chaieb@31119
   479
chaieb@31119
   480
(* Enumerate products of distinct input polys with degree <= d.              *)
chaieb@31119
   481
(* We ignore any constant input polynomials.                                 *)
chaieb@31119
   482
(* Give the output polynomial and a record of how it was derived.            *)
chaieb@31119
   483
chaieb@31119
   484
fun enumerate_products d pols =
wenzelm@32839
   485
if d = 0 then [(poly_const rat_1,RealArith.Rational_lt rat_1)]
chaieb@31119
   486
else if d < 0 then [] else
wenzelm@32839
   487
case pols of
Philipp@32828
   488
   [] => [(poly_const rat_1,RealArith.Rational_lt rat_1)]
wenzelm@32839
   489
 | (p,b)::ps =>
wenzelm@32839
   490
    let val e = multidegree p
chaieb@31119
   491
    in if e = 0 then enumerate_products d ps else
chaieb@31119
   492
       enumerate_products d ps @
Philipp@32828
   493
       map (fn (q,c) => (poly_mul p q,RealArith.Product(b,c)))
chaieb@31119
   494
         (enumerate_products (d - e) ps)
chaieb@31119
   495
    end
chaieb@31119
   496
chaieb@31119
   497
(* Convert regular polynomial. Note that we treat (0,0,0) as -1.             *)
chaieb@31119
   498
chaieb@31119
   499
fun epoly_of_poly p =
Philipp@32829
   500
  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
   501
chaieb@31119
   502
(* String for block diagonal matrix numbered k.                              *)
chaieb@31119
   503
chaieb@31119
   504
fun sdpa_of_blockdiagonal k m =
wenzelm@32839
   505
 let
chaieb@31119
   506
  val pfx = string_of_int k ^" "
chaieb@31119
   507
  val ents =
wenzelm@32839
   508
    Inttriplefunc.fold
wenzelm@32839
   509
      (fn ((b,i,j),c) => fn a => if i > j then a else ((b,i,j),c)::a)
wenzelm@32839
   510
      m []
wenzelm@32839
   511
  val entss = sort (triple_int_ord o pairself fst) ents
chaieb@31119
   512
 in fold_rev (fn ((b,i,j),c) => fn a =>
chaieb@31119
   513
     pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
chaieb@31119
   514
     " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
chaieb@31119
   515
 end;
chaieb@31119
   516
chaieb@31119
   517
(* SDPA for problem using block diagonal (i.e. multiple SDPs)                *)
chaieb@31119
   518
Philipp@32268
   519
fun sdpa_of_blockproblem nblocks blocksizes obj mats =
wenzelm@32839
   520
 let val m = length mats - 1
Philipp@32268
   521
 in
chaieb@31119
   522
  string_of_int m ^ "\n" ^
chaieb@31119
   523
  string_of_int nblocks ^ "\n" ^
Philipp@32830
   524
  (space_implode " " (map string_of_int blocksizes)) ^
chaieb@31119
   525
  "\n" ^
chaieb@31119
   526
  sdpa_of_vector obj ^
chaieb@31119
   527
  fold_rev2 (fn k => fn m => fn a => sdpa_of_blockdiagonal (k - 1) m ^ a)
chaieb@31119
   528
    (1 upto length mats) mats ""
chaieb@31119
   529
 end;
chaieb@31119
   530
Philipp@32268
   531
(* Run prover on a problem in block diagonal form.                       *)
Philipp@32268
   532
Philipp@32268
   533
fun run_blockproblem prover nblocks blocksizes obj mats=
Philipp@32268
   534
  parse_csdpoutput (prover (sdpa_of_blockproblem nblocks blocksizes obj mats))
Philipp@32268
   535
chaieb@31119
   536
(* 3D versions of matrix operations to consider blocks separately.           *)
chaieb@31119
   537
chaieb@31119
   538
val bmatrix_add = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0);
chaieb@31119
   539
fun bmatrix_cmul c bm =
Philipp@32829
   540
  if c =/ rat_0 then Inttriplefunc.empty
haftmann@39027
   541
  else Inttriplefunc.map (fn _ => fn x => c */ x) bm;
chaieb@31119
   542
chaieb@31119
   543
val bmatrix_neg = bmatrix_cmul (Rat.rat_of_int ~1);
chaieb@31119
   544
chaieb@31119
   545
(* Smash a block matrix into components.                                     *)
chaieb@31119
   546
chaieb@31119
   547
fun blocks blocksizes bm =
chaieb@31119
   548
 map (fn (bs,b0) =>
chaieb@31119
   549
      let val m = Inttriplefunc.fold
Philipp@32829
   550
          (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
   551
          val _ = FuncUtil.Intpairfunc.fold (fn ((i,j),_) => fn a => max a (max i j)) m 0
chaieb@31119
   552
      in (((bs,bs),m):matrix) end)
chaieb@31119
   553
 (blocksizes ~~ (1 upto length blocksizes));;
chaieb@31119
   554
chaieb@31119
   555
(* FIXME : Get rid of this !!!*)
Philipp@32268
   556
local
huffman@44453
   557
  fun tryfind_with msg _ [] = raise Failure msg
huffman@44453
   558
    | tryfind_with _ f (x::xs) = (f x handle Failure s => tryfind_with s f xs);
wenzelm@32839
   559
in
Philipp@32268
   560
  fun tryfind f = tryfind_with "tryfind" f
Philipp@32268
   561
end
Philipp@32268
   562
chaieb@31119
   563
(* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
chaieb@31119
   564
wenzelm@32839
   565
wenzelm@38805
   566
fun real_positivnullstellensatz_general ctxt prover linf d eqs leqs pol =
wenzelm@32839
   567
let
haftmann@33042
   568
 val vars = fold_rev (union (op aconvc) o poly_variables)
haftmann@33042
   569
   (pol :: eqs @ map fst leqs) []
wenzelm@32839
   570
 val monoid = if linf then
Philipp@32828
   571
      (poly_const rat_1,RealArith.Rational_lt rat_1)::
huffman@44453
   572
      (filter (fn (p,_) => multidegree p <= d) leqs)
chaieb@31119
   573
    else enumerate_products d leqs
chaieb@31119
   574
 val nblocks = length monoid
chaieb@31119
   575
 fun mk_idmultiplier k p =
wenzelm@32839
   576
  let
chaieb@31119
   577
   val e = d - multidegree p
chaieb@31119
   578
   val mons = enumerate_monomials e vars
wenzelm@32839
   579
   val nons = mons ~~ (1 upto length mons)
chaieb@31119
   580
  in (mons,
Philipp@32829
   581
      fold_rev (fn (m,n) => FuncUtil.Monomialfunc.update(m,Inttriplefunc.onefunc((~k,~n,n),rat_1))) nons FuncUtil.Monomialfunc.empty)
chaieb@31119
   582
  end
chaieb@31119
   583
huffman@44453
   584
 fun mk_sqmultiplier k (p,_) =
wenzelm@32839
   585
  let
chaieb@31119
   586
   val e = (d - multidegree p) div 2
chaieb@31119
   587
   val mons = enumerate_monomials e vars
wenzelm@32839
   588
   val nons = mons ~~ (1 upto length mons)
wenzelm@32839
   589
  in (mons,
chaieb@31119
   590
      fold_rev (fn (m1,n1) =>
chaieb@31119
   591
       fold_rev (fn (m2,n2) => fn  a =>
wenzelm@32839
   592
        let val m = monomial_mul m1 m2
chaieb@31119
   593
        in if n1 > n2 then a else
chaieb@31119
   594
          let val c = if n1 = n2 then rat_1 else rat_2
wenzelm@32839
   595
              val e = FuncUtil.Monomialfunc.tryapplyd a m Inttriplefunc.empty
Philipp@32828
   596
          in FuncUtil.Monomialfunc.update(m, tri_equation_add (Inttriplefunc.onefunc((k,n1,n2), c)) e) a
chaieb@31119
   597
          end
chaieb@31119
   598
        end)  nons)
Philipp@32829
   599
       nons FuncUtil.Monomialfunc.empty)
chaieb@31119
   600
  end
chaieb@31119
   601
chaieb@31119
   602
  val (sqmonlist,sqs) = split_list (map2 mk_sqmultiplier (1 upto length monoid) monoid)
huffman@44453
   603
  val (_(*idmonlist*),ids) =  split_list(map2 mk_idmultiplier (1 upto length eqs) eqs)
chaieb@31119
   604
  val blocksizes = map length sqmonlist
chaieb@31119
   605
  val bigsum =
chaieb@31119
   606
    fold_rev2 (fn p => fn q => fn a => tri_epoly_pmul p q a) eqs ids
huffman@44453
   607
            (fold_rev2 (fn (p,_) => fn s => fn a => tri_epoly_pmul p s a) monoid sqs
chaieb@31119
   608
                     (epoly_of_poly(poly_neg pol)))
huffman@44453
   609
  val eqns = FuncUtil.Monomialfunc.fold (fn (_,e) => fn a => e::a) bigsum []
chaieb@31119
   610
  val (pvs,assig) = tri_eliminate_all_equations (0,0,0) eqns
chaieb@31119
   611
  val qvars = (0,0,0)::pvs
chaieb@31119
   612
  val allassig = fold_rev (fn v => Inttriplefunc.update(v,(Inttriplefunc.onefunc(v,rat_1)))) pvs assig
chaieb@31119
   613
  fun mk_matrix v =
wenzelm@32839
   614
    Inttriplefunc.fold (fn ((b,i,j), ass) => fn m =>
chaieb@31119
   615
        if b < 0 then m else
chaieb@31119
   616
         let val c = Inttriplefunc.tryapplyd ass v rat_0
chaieb@31119
   617
         in if c = rat_0 then m else
chaieb@31119
   618
            Inttriplefunc.update ((b,j,i), c) (Inttriplefunc.update ((b,i,j), c) m)
chaieb@31119
   619
         end)
Philipp@32829
   620
          allassig Inttriplefunc.empty
chaieb@31119
   621
  val diagents = Inttriplefunc.fold
chaieb@31119
   622
    (fn ((b,i,j), e) => fn a => if b > 0 andalso i = j then tri_equation_add e a else a)
Philipp@32829
   623
    allassig Inttriplefunc.empty
chaieb@31119
   624
chaieb@31119
   625
  val mats = map mk_matrix qvars
chaieb@31119
   626
  val obj = (length pvs,
Philipp@32828
   627
            itern 1 pvs (fn v => fn i => FuncUtil.Intfunc.updatep iszero (i,Inttriplefunc.tryapplyd diagents v rat_0))
Philipp@32829
   628
                        FuncUtil.Intfunc.empty)
chaieb@31119
   629
  val raw_vec = if null pvs then vector_0 0
Philipp@32268
   630
                else tri_scale_then (run_blockproblem prover nblocks blocksizes) obj mats
huffman@44453
   631
  fun int_element (_,v) i = FuncUtil.Intfunc.tryapplyd v i rat_0
chaieb@31119
   632
chaieb@31119
   633
  fun find_rounding d =
wenzelm@32839
   634
   let
wenzelm@32949
   635
    val _ =
wenzelm@38805
   636
      if Config.get ctxt trace
wenzelm@32949
   637
      then writeln ("Trying rounding with limit "^Rat.string_of_rat d ^ "\n")
wenzelm@32949
   638
      else ()
chaieb@31119
   639
    val vec = nice_vector d raw_vec
chaieb@31119
   640
    val blockmat = iter (1,dim vec)
chaieb@31119
   641
     (fn i => fn a => bmatrix_add (bmatrix_cmul (int_element vec i) (nth mats i)) a)
chaieb@31119
   642
     (bmatrix_neg (nth mats 0))
wenzelm@32839
   643
    val allmats = blocks blocksizes blockmat
chaieb@31119
   644
   in (vec,map diag allmats)
chaieb@31119
   645
   end
chaieb@31119
   646
  val (vec,ratdias) =
chaieb@31119
   647
    if null pvs then find_rounding rat_1
chaieb@31119
   648
    else tryfind find_rounding (map Rat.rat_of_int (1 upto 31) @
chaieb@31119
   649
                                map pow2 (5 upto 66))
chaieb@31119
   650
  val newassigs =
chaieb@31119
   651
    fold_rev (fn k => Inttriplefunc.update (nth pvs (k - 1), int_element vec k))
chaieb@31119
   652
           (1 upto dim vec) (Inttriplefunc.onefunc ((0,0,0), Rat.rat_of_int ~1))
chaieb@31119
   653
  val finalassigs =
chaieb@31119
   654
    Inttriplefunc.fold (fn (v,e) => fn a => Inttriplefunc.update(v, tri_equation_eval newassigs e) a) allassig newassigs
chaieb@31119
   655
  fun poly_of_epoly p =
Philipp@32828
   656
    FuncUtil.Monomialfunc.fold (fn (v,e) => fn a => FuncUtil.Monomialfunc.updatep iszero (v,tri_equation_eval finalassigs e) a)
Philipp@32829
   657
          p FuncUtil.Monomialfunc.empty
chaieb@31119
   658
  fun  mk_sos mons =
chaieb@31119
   659
   let fun mk_sq (c,m) =
Philipp@32828
   660
    (c,fold_rev (fn k=> fn a => FuncUtil.Monomialfunc.updatep iszero (nth mons (k - 1), int_element m k) a)
Philipp@32829
   661
                 (1 upto length mons) FuncUtil.Monomialfunc.empty)
chaieb@31119
   662
   in map mk_sq
chaieb@31119
   663
   end
chaieb@31119
   664
  val sqs = map2 mk_sos sqmonlist ratdias
chaieb@31119
   665
  val cfs = map poly_of_epoly ids
huffman@44453
   666
  val msq = filter (fn (_,b) => not (null b)) (map2 pair monoid sqs)
chaieb@31119
   667
  fun eval_sq sqs = fold_rev (fn (c,q) => poly_add (poly_cmul c (poly_mul q q))) sqs poly_0
chaieb@31119
   668
  val sanity =
huffman@44453
   669
    fold_rev (fn ((p,_),s) => poly_add (poly_mul p (eval_sq s))) msq
chaieb@31119
   670
           (fold_rev2 (fn p => fn q => poly_add (poly_mul p q)) cfs eqs
chaieb@31119
   671
                    (poly_neg pol))
chaieb@31119
   672
Philipp@32829
   673
in if not(FuncUtil.Monomialfunc.is_empty sanity) then raise Sanity else
chaieb@31119
   674
  (cfs,map (fn (a,b) => (snd a,b)) msq)
chaieb@31119
   675
 end
chaieb@31119
   676
chaieb@31119
   677
chaieb@31119
   678
(* Iterative deepening.                                                      *)
chaieb@31119
   679
wenzelm@32839
   680
fun deepen f n =
wenzelm@32949
   681
  (writeln ("Searching with depth limit " ^ string_of_int n);
wenzelm@32949
   682
    (f n handle Failure s => (writeln ("failed with message: " ^ s); deepen f (n + 1))));
chaieb@31119
   683
chaieb@31119
   684
Philipp@32645
   685
(* Map back polynomials and their composites to a positivstellensatz.        *)
chaieb@31119
   686
Philipp@32828
   687
fun cterm_of_sqterm (c,p) = RealArith.Product(RealArith.Rational_lt c,RealArith.Square p);
chaieb@31119
   688
chaieb@31119
   689
fun cterm_of_sos (pr,sqs) = if null sqs then pr
Philipp@32830
   690
  else RealArith.Product(pr,foldr1 RealArith.Sum (map cterm_of_sqterm sqs));
chaieb@31119
   691
chaieb@31119
   692
(* Interface to HOL.                                                         *)
chaieb@31119
   693
local
Philipp@32828
   694
  open Conv
Philipp@32828
   695
  val concl = Thm.dest_arg o cprop_of
wenzelm@35408
   696
  fun simple_cterm_ord t u = Term_Ord.fast_term_ord (term_of t, term_of u) = LESS
chaieb@31119
   697
in
chaieb@31119
   698
  (* FIXME: Replace tryfind by get_first !! *)
Philipp@32645
   699
fun real_nonlinear_prover proof_method ctxt =
wenzelm@32839
   700
 let
huffman@44453
   701
  val {add = _, mul = _, neg = _, pow = _,
huffman@44453
   702
       sub = _, main = real_poly_conv} =
huffman@44453
   703
      Semiring_Normalizer.semiring_normalizers_ord_wrapper ctxt
haftmann@36753
   704
      (the (Semiring_Normalizer.match ctxt @{cterm "(0::real) + 1"}))
chaieb@31119
   705
     simple_cterm_ord
wenzelm@32839
   706
  fun mainf cert_choice translator (eqs,les,lts) =
wenzelm@32839
   707
  let
Philipp@32828
   708
   val eq0 = map (poly_of_term o Thm.dest_arg1 o concl) eqs
Philipp@32828
   709
   val le0 = map (poly_of_term o Thm.dest_arg o concl) les
Philipp@32828
   710
   val lt0 = map (poly_of_term o Thm.dest_arg o concl) lts
haftmann@33063
   711
   val eqp0 = map_index (fn (i, t) => (t,RealArith.Axiom_eq i)) eq0
haftmann@33063
   712
   val lep0 = map_index (fn (i, t) => (t,RealArith.Axiom_le i)) le0
haftmann@33063
   713
   val ltp0 = map_index (fn (i, t) => (t,RealArith.Axiom_lt i)) lt0
chaieb@31119
   714
   val (keq,eq) = List.partition (fn (p,_) => multidegree p = 0) eqp0
chaieb@31119
   715
   val (klep,lep) = List.partition (fn (p,_) => multidegree p = 0) lep0
chaieb@31119
   716
   val (kltp,ltp) = List.partition (fn (p,_) => multidegree p = 0) ltp0
chaieb@31119
   717
   fun trivial_axiom (p,ax) =
chaieb@31119
   718
    case ax of
wenzelm@32839
   719
       RealArith.Axiom_eq n => if eval FuncUtil.Ctermfunc.empty p <>/ Rat.zero then nth eqs n
wenzelm@32332
   720
                     else raise Failure "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   721
     | RealArith.Axiom_le n => if eval FuncUtil.Ctermfunc.empty p </ Rat.zero then nth les n
wenzelm@32332
   722
                     else raise Failure "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   723
     | RealArith.Axiom_lt n => if eval FuncUtil.Ctermfunc.empty p <=/ Rat.zero then nth lts n
wenzelm@32332
   724
                     else raise Failure "trivial_axiom: Not a trivial axiom"
chaieb@31119
   725
     | _ => error "trivial_axiom: Not a trivial axiom"
wenzelm@32839
   726
   in
Philipp@32645
   727
  (let val th = tryfind trivial_axiom (keq @ klep @ kltp)
Philipp@32645
   728
   in
wenzelm@51717
   729
    (fconv_rule (arg_conv (arg1_conv (real_poly_conv ctxt))
wenzelm@51717
   730
      then_conv Numeral_Simprocs.field_comp_conv ctxt) th,
wenzelm@51717
   731
      RealArith.Trivial)
Philipp@32645
   732
   end)
wenzelm@32839
   733
   handle Failure _ =>
Philipp@32645
   734
     (let val proof =
Philipp@32645
   735
       (case proof_method of Certificate certs =>
Philipp@32645
   736
         (* choose certificate *)
Philipp@32645
   737
         let
Philipp@32828
   738
           fun chose_cert [] (RealArith.Cert c) = c
Philipp@32828
   739
             | chose_cert (RealArith.Left::s) (RealArith.Branch (l, _)) = chose_cert s l
Philipp@32828
   740
             | chose_cert (RealArith.Right::s) (RealArith.Branch (_, r)) = chose_cert s r
Philipp@32645
   741
             | chose_cert _ _ = error "certificate tree in invalid form"
Philipp@32645
   742
         in
Philipp@32645
   743
           chose_cert cert_choice certs
Philipp@32645
   744
         end
Philipp@32645
   745
       | Prover prover =>
Philipp@32645
   746
         (* call prover *)
wenzelm@32839
   747
         let
Philipp@32645
   748
          val pol = fold_rev poly_mul (map fst ltp) (poly_const Rat.one)
Philipp@32645
   749
          val leq = lep @ ltp
Philipp@32645
   750
          fun tryall d =
Philipp@32645
   751
           let val e = multidegree pol
Philipp@32645
   752
               val k = if e = 0 then 0 else d div e
wenzelm@32839
   753
               val eq' = map fst eq
wenzelm@38805
   754
           in tryfind (fn i => (d,i,real_positivnullstellensatz_general ctxt prover false d eq' leq
Philipp@32645
   755
                                 (poly_neg(poly_pow pol i))))
Philipp@32645
   756
                   (0 upto k)
Philipp@32645
   757
           end
huffman@44453
   758
         val (_,i,(cert_ideal,cert_cone)) = deepen tryall 0
Philipp@32645
   759
         val proofs_ideal =
huffman@44453
   760
           map2 (fn q => fn (_,ax) => RealArith.Eqmul(q,ax)) cert_ideal eq
Philipp@32645
   761
         val proofs_cone = map cterm_of_sos cert_cone
Philipp@32828
   762
         val proof_ne = if null ltp then RealArith.Rational_lt Rat.one else
wenzelm@32839
   763
           let val p = foldr1 RealArith.Product (map snd ltp)
Philipp@32828
   764
           in  funpow i (fn q => RealArith.Product(p,q)) (RealArith.Rational_lt Rat.one)
Philipp@32645
   765
           end
wenzelm@32839
   766
         in
wenzelm@32839
   767
           foldr1 RealArith.Sum (proof_ne :: proofs_ideal @ proofs_cone)
Philipp@32645
   768
         end)
Philipp@32645
   769
     in
Philipp@32828
   770
        (translator (eqs,les,lts) proof, RealArith.Cert proof)
Philipp@32645
   771
     end)
chaieb@31119
   772
   end
chaieb@31119
   773
 in mainf end
chaieb@31119
   774
end
chaieb@31119
   775
chaieb@31119
   776
fun C f x y = f y x;
chaieb@31119
   777
  (* FIXME : This is very bad!!!*)
wenzelm@32839
   778
fun subst_conv eqs t =
wenzelm@32839
   779
 let
wenzelm@46497
   780
  val t' = fold (Thm.lambda o Thm.lhs_of) eqs t
wenzelm@36945
   781
 in Conv.fconv_rule (Thm.beta_conversion true) (fold (C Thm.combination) eqs (Thm.reflexive t'))
chaieb@31119
   782
 end
chaieb@31119
   783
chaieb@31119
   784
(* A wrapper that tries to substitute away variables first.                  *)
chaieb@31119
   785
chaieb@31119
   786
local
Philipp@32828
   787
 open Conv
wenzelm@35408
   788
  fun simple_cterm_ord t u = Term_Ord.fast_term_ord (term_of t, term_of u) = LESS
Philipp@32828
   789
 val concl = Thm.dest_arg o cprop_of
wenzelm@32839
   790
 val shuffle1 =
haftmann@36350
   791
   fconv_rule (rewr_conv @{lemma "(a + x == y) == (x == y - (a::real))" by (atomize (full)) (simp add: field_simps) })
chaieb@31119
   792
 val shuffle2 =
haftmann@36350
   793
    fconv_rule (rewr_conv @{lemma "(x + a == y) ==  (x == y - (a::real))" by (atomize (full)) (simp add: field_simps)})
chaieb@31119
   794
 fun substitutable_monomial fvs tm = case term_of tm of
wenzelm@32839
   795
    Free(_,@{typ real}) => if not (member (op aconvc) fvs tm) then (Rat.one,tm)
wenzelm@32332
   796
                           else raise Failure "substitutable_monomial"
huffman@44453
   797
  | @{term "op * :: real => _"}$_$(Free _) =>
Philipp@32828
   798
     if RealArith.is_ratconst (Thm.dest_arg1 tm) andalso not (member (op aconvc) fvs (Thm.dest_arg tm))
Philipp@32828
   799
         then (RealArith.dest_ratconst (Thm.dest_arg1 tm),Thm.dest_arg tm) else raise Failure "substitutable_monomial"
huffman@44453
   800
  | @{term "op + :: real => _"}$_$_ =>
Philipp@32828
   801
       (substitutable_monomial (Thm.add_cterm_frees (Thm.dest_arg tm) fvs) (Thm.dest_arg1 tm)
Philipp@32828
   802
        handle Failure _ => substitutable_monomial (Thm.add_cterm_frees (Thm.dest_arg1 tm) fvs) (Thm.dest_arg tm))
wenzelm@32332
   803
  | _ => raise Failure "substitutable_monomial"
chaieb@31119
   804
wenzelm@32839
   805
  fun isolate_variable v th =
Philipp@32828
   806
   let val w = Thm.dest_arg1 (cprop_of th)
chaieb@31119
   807
   in if v aconvc w then th
chaieb@31119
   808
      else case term_of w of
huffman@44453
   809
           @{term "op + :: real => _"}$_$_ =>
wenzelm@32839
   810
              if Thm.dest_arg1 w aconvc v then shuffle2 th
chaieb@31119
   811
              else isolate_variable v (shuffle1 th)
chaieb@31119
   812
          | _ => error "isolate variable : This should not happen?"
wenzelm@32839
   813
   end
chaieb@31119
   814
in
chaieb@31119
   815
Philipp@32268
   816
fun real_nonlinear_subst_prover prover ctxt =
wenzelm@32839
   817
 let
huffman@44453
   818
  val {add = _, mul = real_poly_mul_conv, neg = _,
huffman@44453
   819
       pow = _, sub = _, main = real_poly_conv} =
huffman@44453
   820
      Semiring_Normalizer.semiring_normalizers_ord_wrapper ctxt
haftmann@36753
   821
      (the (Semiring_Normalizer.match ctxt @{cterm "(0::real) + 1"}))
chaieb@31119
   822
     simple_cterm_ord
chaieb@31119
   823
chaieb@31119
   824
  fun make_substitution th =
wenzelm@32839
   825
   let
Philipp@32828
   826
    val (c,v) = substitutable_monomial [] (Thm.dest_arg1(concl th))
wenzelm@46497
   827
    val th1 = Drule.arg_cong_rule (Thm.apply @{cterm "op * :: real => _"} (RealArith.cterm_of_rat (Rat.inv c))) (mk_meta_eq th)
wenzelm@51717
   828
    val th2 = fconv_rule (binop_conv (real_poly_mul_conv ctxt)) th1
wenzelm@51717
   829
   in fconv_rule (arg_conv (real_poly_conv ctxt)) (isolate_variable v th2)
chaieb@31119
   830
   end
wenzelm@32839
   831
   fun oprconv cv ct =
chaieb@31119
   832
    let val g = Thm.dest_fun2 ct
wenzelm@32839
   833
    in if g aconvc @{cterm "op <= :: real => _"}
wenzelm@32839
   834
         orelse g aconvc @{cterm "op < :: real => _"}
chaieb@31119
   835
       then arg_conv cv ct else arg1_conv cv ct
chaieb@31119
   836
    end
Philipp@32645
   837
  fun mainf cert_choice translator =
wenzelm@32839
   838
   let
chaieb@31119
   839
    fun substfirst(eqs,les,lts) =
wenzelm@32839
   840
      ((let
chaieb@31119
   841
           val eth = tryfind make_substitution eqs
wenzelm@51717
   842
           val modify =
wenzelm@51717
   843
            fconv_rule (arg_conv (oprconv(subst_conv [eth] then_conv (real_poly_conv ctxt))))
chaieb@31119
   844
       in  substfirst
wenzelm@32839
   845
             (filter_out (fn t => (Thm.dest_arg1 o Thm.dest_arg o cprop_of) t
chaieb@31119
   846
                                   aconvc @{cterm "0::real"}) (map modify eqs),
chaieb@31119
   847
                                   map modify les,map modify lts)
chaieb@31119
   848
       end)
Philipp@32645
   849
       handle Failure  _ => real_nonlinear_prover prover ctxt cert_choice translator (rev eqs, rev les, rev lts))
chaieb@31119
   850
    in substfirst
chaieb@31119
   851
   end
chaieb@31119
   852
chaieb@31119
   853
chaieb@31119
   854
 in mainf
chaieb@31119
   855
 end
chaieb@31119
   856
chaieb@31119
   857
(* Overall function. *)
chaieb@31119
   858
Philipp@32645
   859
fun real_sos prover ctxt =
Philipp@32828
   860
  RealArith.gen_prover_real_arith ctxt (real_nonlinear_subst_prover prover ctxt)
chaieb@31119
   861
end;
chaieb@31119
   862
wenzelm@32839
   863
val known_sos_constants =
wenzelm@32839
   864
  [@{term "op ==>"}, @{term "Trueprop"},
haftmann@38795
   865
   @{term HOL.implies}, @{term HOL.conj}, @{term HOL.disj},
wenzelm@32839
   866
   @{term "Not"}, @{term "op = :: bool => _"},
wenzelm@32839
   867
   @{term "All :: (real => _) => _"}, @{term "Ex :: (real => _) => _"},
wenzelm@32839
   868
   @{term "op = :: real => _"}, @{term "op < :: real => _"},
wenzelm@32839
   869
   @{term "op <= :: real => _"},
wenzelm@32839
   870
   @{term "op + :: real => _"}, @{term "op - :: real => _"},
wenzelm@32839
   871
   @{term "op * :: real => _"}, @{term "uminus :: real => _"},
chaieb@31512
   872
   @{term "op / :: real => _"}, @{term "inverse :: real => _"},
wenzelm@32839
   873
   @{term "op ^ :: real => _"}, @{term "abs :: real => _"},
chaieb@31512
   874
   @{term "min :: real => _"}, @{term "max :: real => _"},
huffman@47108
   875
   @{term "0::real"}, @{term "1::real"},
huffman@47108
   876
   @{term "numeral :: num => nat"},
huffman@47108
   877
   @{term "numeral :: num => real"},
huffman@47108
   878
   @{term "Num.Bit0"}, @{term "Num.Bit1"}, @{term "Num.One"}];
chaieb@31512
   879
wenzelm@32839
   880
fun check_sos kcts ct =
chaieb@31512
   881
 let
chaieb@31512
   882
  val t = term_of ct
wenzelm@32839
   883
  val _ = if not (null (Term.add_tfrees t [])
wenzelm@32839
   884
                  andalso null (Term.add_tvars t []))
chaieb@31512
   885
          then error "SOS: not sos. Additional type varables" else ()
chaieb@31512
   886
  val fs = Term.add_frees t []
wenzelm@32839
   887
  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs
chaieb@31512
   888
          then error "SOS: not sos. Variables with type not real" else ()
chaieb@31512
   889
  val vs = Term.add_vars t []
wenzelm@32839
   890
  val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) vs
chaieb@31512
   891
          then error "SOS: not sos. Variables with type not real" else ()
chaieb@31512
   892
  val ukcs = subtract (fn (t,p) => Const p aconv t) kcts (Term.add_consts t [])
wenzelm@32839
   893
  val _ = if  null ukcs then ()
chaieb@31512
   894
              else error ("SOSO: Unknown constants in Subgoal:" ^ commas (map fst ukcs))
chaieb@31512
   895
in () end
chaieb@31512
   896
wenzelm@32838
   897
fun core_sos_tac print_cert prover = SUBPROOF (fn {concl, context, ...} =>
Philipp@32831
   898
  let
wenzelm@32838
   899
    val _ = check_sos known_sos_constants concl
wenzelm@32838
   900
    val (ths, certificates) = real_sos prover context (Thm.dest_arg concl)
wenzelm@32838
   901
    val _ = print_cert certificates
wenzelm@32838
   902
  in rtac ths 1 end)
chaieb@31131
   903
huffman@44453
   904
fun default_SOME _ NONE v = SOME v
huffman@44453
   905
  | default_SOME _ (SOME v) _ = SOME v;
chaieb@31131
   906
chaieb@31131
   907
fun lift_SOME f NONE a = f a
huffman@44453
   908
  | lift_SOME _ (SOME a) _ = SOME a;
chaieb@31131
   909
chaieb@31131
   910
chaieb@31131
   911
local
chaieb@31131
   912
 val is_numeral = can (HOLogic.dest_number o term_of)
chaieb@31131
   913
in
chaieb@31131
   914
fun get_denom b ct = case term_of ct of
wenzelm@32839
   915
  @{term "op / :: real => _"} $ _ $ _ =>
chaieb@31131
   916
     if is_numeral (Thm.dest_arg ct) then get_denom b (Thm.dest_arg1 ct)
chaieb@31131
   917
     else default_SOME (get_denom b) (get_denom b (Thm.dest_arg ct))   (Thm.dest_arg ct, b)
chaieb@31131
   918
 | @{term "op < :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
chaieb@31131
   919
 | @{term "op <= :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
chaieb@31131
   920
 | _ $ _ => lift_SOME (get_denom b) (get_denom b (Thm.dest_fun ct)) (Thm.dest_arg ct)
chaieb@31131
   921
 | _ => NONE
chaieb@31131
   922
end;
chaieb@31131
   923
wenzelm@32839
   924
fun elim_one_denom_tac ctxt =
wenzelm@32839
   925
CSUBGOAL (fn (P,i) =>
wenzelm@32839
   926
 case get_denom false P of
chaieb@31131
   927
   NONE => no_tac
wenzelm@32839
   928
 | SOME (d,ord) =>
wenzelm@32839
   929
     let
wenzelm@51717
   930
      val simp_ctxt =
wenzelm@51717
   931
        ctxt addsimps @{thms field_simps}
wenzelm@51717
   932
        addsimps [@{thm nonzero_power_divide}, @{thm power_divide}]
wenzelm@32839
   933
      val th = instantiate' [] [SOME d, SOME (Thm.dest_arg P)]
chaieb@31131
   934
         (if ord then @{lemma "(d=0 --> P) & (d>0 --> P) & (d<(0::real) --> P) ==> P" by auto}
chaieb@31131
   935
          else @{lemma "(d=0 --> P) & (d ~= (0::real) --> P) ==> P" by blast})
wenzelm@51717
   936
     in rtac th i THEN Simplifier.asm_full_simp_tac simp_ctxt i end);
chaieb@31131
   937
chaieb@31131
   938
fun elim_denom_tac ctxt i = REPEAT (elim_one_denom_tac ctxt i);
chaieb@31131
   939
wenzelm@32949
   940
fun sos_tac print_cert prover ctxt =
wenzelm@54742
   941
  Object_Logic.full_atomize_tac ctxt THEN'
wenzelm@32949
   942
  elim_denom_tac ctxt THEN'
wenzelm@32949
   943
  core_sos_tac print_cert prover ctxt;
chaieb@31131
   944
chaieb@31512
   945
end;