1 (* Title: sum_of_squares.ML
2 Authors: Amine Chaieb, University of Cambridge
3 Philipp Meyer, TU Muenchen
5 A tactic for proving nonlinear inequalities
11 val sos_tac : (string -> string) -> Proof.context -> int -> Tactical.tactic
13 val debugging : bool ref;
15 exception Failure of string;
24 val rat_10 = Rat.rat_of_int 10;
25 val rat_1_2 = rat_1 // rat_2;
26 val max = curry IntInf.max;
27 val min = curry IntInf.min;
29 val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
30 val numerator_rat = Rat.quotient_of_rat #> fst #> Rat.rat_of_int;
32 case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
33 fun lcm_rat x y = Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
37 if i = 0 then rat_1 else
38 let val d = pow r (i div 2)
39 in d */ d */ (if i mod 2 = 0 then rat_1 else r)
41 in if i < 0 then pow (Rat.inv r) (~ i) else pow r i end;
44 let val (a,b) = Rat.quotient_of_rat (Rat.abs r)
46 val s = if r </ rat_0 then (Rat.neg o Rat.rat_of_int) else Rat.rat_of_int
47 val x2 = 2 * (a - (b * d))
48 in s (if x2 >= b then d + 1 else d) end
50 val abs_rat = Rat.abs;
51 val pow2 = rat_pow rat_2;
52 val pow10 = rat_pow rat_10;
54 val debugging = ref false;
60 exception Failure of string;
62 (* Turn a rational into a decimal string with d sig digits. *)
66 if abs_rat y </ (rat_1 // rat_10) then normalize (rat_10 */ y) - 1
67 else if abs_rat y >=/ rat_1 then normalize (y // rat_10) + 1
71 if x =/ rat_0 then "0.0" else
75 val z = pow10(~ e) */ y +/ rat_1
76 val k = int_of_rat (round_rat(pow10 d */ z))
77 in (if x </ rat_0 then "-0." else "0.") ^
78 implode(tl(explode(string_of_int k))) ^
79 (if e = 0 then "" else "e"^string_of_int e)
83 (* Iterations over numbers, and lists indexed by numbers. *)
88 | h::t => itern (k + 1) t f (f h k a);
92 else iter (m+1,n) f (f m a);
96 fun strict_ord ord (x,y) = case ord (x,y) of LESS => LESS | _ => GREATER
98 structure Intpairfunc = FuncFun(type key = int*int val ord = prod_ord int_ord int_ord);
100 type vector = int* Rat.rat Intfunc.T;
102 type matrix = (int*int)*(Rat.rat Intpairfunc.T);
104 type monomial = int Ctermfunc.T;
106 val cterm_ord = (fn (s,t) => TermOrd.fast_term_ord(term_of s, term_of t))
107 fun monomial_ord (m1,m2) = list_ord (prod_ord cterm_ord int_ord) (Ctermfunc.graph m1, Ctermfunc.graph m2)
108 structure Monomialfunc = FuncFun(type key = monomial val ord = monomial_ord)
110 type poly = Rat.rat Monomialfunc.T;
112 fun iszero (k,r) = r =/ rat_0;
114 fun fold_rev2 f l1 l2 b =
117 | (h1::t1,h2::t2) => f h1 h2 (fold_rev2 f t1 t2 b)
118 | _ => error "fold_rev2";
120 (* Vectors. Conventionally indexed 1..n. *)
122 fun vector_0 n = (n,Intfunc.undefined):vector;
124 fun dim (v:vector) = fst v;
126 fun vector_const c n =
127 if c =/ rat_0 then vector_0 n
128 else (n,fold_rev (fn k => Intfunc.update (k,c)) (1 upto n) Intfunc.undefined) :vector;
130 val vector_1 = vector_const rat_1;
132 fun vector_cmul c (v:vector) =
134 in if c =/ rat_0 then vector_0 n
135 else (n,Intfunc.mapf (fn x => c */ x) (snd v))
138 fun vector_neg (v:vector) = (fst v,Intfunc.mapf Rat.neg (snd v)) :vector;
140 fun vector_add (v1:vector) (v2:vector) =
143 in if m <> n then error "vector_add: incompatible dimensions"
144 else (n,Intfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd v1) (snd v2)) :vector
147 fun vector_sub v1 v2 = vector_add v1 (vector_neg v2);
149 fun vector_dot (v1:vector) (v2:vector) =
152 in if m <> n then error "vector_dot: incompatible dimensions"
153 else Intfunc.fold (fn (i,x) => fn a => x +/ a)
154 (Intfunc.combine (curry op */) (fn x => x =/ rat_0) (snd v1) (snd v2)) rat_0
157 fun vector_of_list l =
159 in (n,fold_rev2 (curry Intfunc.update) (1 upto n) l Intfunc.undefined) :vector
162 (* Matrices; again rows and columns indexed from 1. *)
164 fun matrix_0 (m,n) = ((m,n),Intpairfunc.undefined):matrix;
166 fun dimensions (m:matrix) = fst m;
168 fun matrix_const c (mn as (m,n)) =
169 if m <> n then error "matrix_const: needs to be square"
170 else if c =/ rat_0 then matrix_0 mn
171 else (mn,fold_rev (fn k => Intpairfunc.update ((k,k), c)) (1 upto n) Intpairfunc.undefined) :matrix;;
173 val matrix_1 = matrix_const rat_1;
175 fun matrix_cmul c (m:matrix) =
176 let val (i,j) = dimensions m
177 in if c =/ rat_0 then matrix_0 (i,j)
178 else ((i,j),Intpairfunc.mapf (fn x => c */ x) (snd m))
181 fun matrix_neg (m:matrix) =
182 (dimensions m, Intpairfunc.mapf Rat.neg (snd m)) :matrix;
184 fun matrix_add (m1:matrix) (m2:matrix) =
185 let val d1 = dimensions m1
186 val d2 = dimensions m2
188 then error "matrix_add: incompatible dimensions"
189 else (d1,Intpairfunc.combine (curry op +/) (fn x => x =/ rat_0) (snd m1) (snd m2)) :matrix
192 fun matrix_sub m1 m2 = matrix_add m1 (matrix_neg m2);
194 fun row k (m:matrix) =
195 let val (i,j) = dimensions m
197 Intpairfunc.fold (fn ((i,j), c) => fn a => if i = k then Intfunc.update (j,c) a else a) (snd m) Intfunc.undefined ) : vector
200 fun column k (m:matrix) =
201 let val (i,j) = dimensions m
203 Intpairfunc.fold (fn ((i,j), c) => fn a => if j = k then Intfunc.update (i,c) a else a) (snd m) Intfunc.undefined)
207 fun transp (m:matrix) =
208 let val (i,j) = dimensions m
210 ((j,i),Intpairfunc.fold (fn ((i,j), c) => fn a => Intpairfunc.update ((j,i), c) a) (snd m) Intpairfunc.undefined) :matrix
213 fun diagonal (v:vector) =
215 in ((n,n),Intfunc.fold (fn (i, c) => fn a => Intpairfunc.update ((i,i), c) a) (snd v) Intpairfunc.undefined) : matrix
218 fun matrix_of_list l =
220 in if m = 0 then matrix_0 (0,0) else
221 let val n = length (hd l)
222 in ((m,n),itern 1 l (fn v => fn i => itern 1 v (fn c => fn j => Intpairfunc.update ((i,j), c))) Intpairfunc.undefined)
228 fun monomial_eval assig (m:monomial) =
229 Ctermfunc.fold (fn (x, k) => fn a => a */ rat_pow (Ctermfunc.apply assig x) k)
231 val monomial_1 = (Ctermfunc.undefined:monomial);
233 fun monomial_var x = Ctermfunc.onefunc (x, 1) :monomial;
235 val (monomial_mul:monomial->monomial->monomial) =
236 Ctermfunc.combine (curry op +) (K false);
238 fun monomial_pow (m:monomial) k =
239 if k = 0 then monomial_1
240 else Ctermfunc.mapf (fn x => k * x) m;
242 fun monomial_divides (m1:monomial) (m2:monomial) =
243 Ctermfunc.fold (fn (x, k) => fn a => Ctermfunc.tryapplyd m2 x 0 >= k andalso a) m1 true;;
245 fun monomial_div (m1:monomial) (m2:monomial) =
246 let val m = Ctermfunc.combine (curry op +)
247 (fn x => x = 0) m1 (Ctermfunc.mapf (fn x => ~ x) m2)
248 in if Ctermfunc.fold (fn (x, k) => fn a => k >= 0 andalso a) m true then m
249 else error "monomial_div: non-divisible"
252 fun monomial_degree x (m:monomial) =
253 Ctermfunc.tryapplyd m x 0;;
255 fun monomial_lcm (m1:monomial) (m2:monomial) =
256 fold_rev (fn x => Ctermfunc.update (x, max (monomial_degree x m1) (monomial_degree x m2)))
257 (gen_union (is_equal o cterm_ord) (Ctermfunc.dom m1, Ctermfunc.dom m2)) (Ctermfunc.undefined :monomial);
259 fun monomial_multidegree (m:monomial) =
260 Ctermfunc.fold (fn (x, k) => fn a => k + a) m 0;;
262 fun monomial_variables m = Ctermfunc.dom m;;
266 fun eval assig (p:poly) =
267 Monomialfunc.fold (fn (m, c) => fn a => a +/ c */ monomial_eval assig m) p rat_0;
269 val poly_0 = (Monomialfunc.undefined:poly);
271 fun poly_isconst (p:poly) =
272 Monomialfunc.fold (fn (m, c) => fn a => Ctermfunc.is_undefined m andalso a) p true;
274 fun poly_var x = Monomialfunc.onefunc (monomial_var x,rat_1) :poly;
277 if c =/ rat_0 then poly_0 else Monomialfunc.onefunc(monomial_1, c);
279 fun poly_cmul c (p:poly) =
280 if c =/ rat_0 then poly_0
281 else Monomialfunc.mapf (fn x => c */ x) p;
283 fun poly_neg (p:poly) = (Monomialfunc.mapf Rat.neg p :poly);;
285 fun poly_add (p1:poly) (p2:poly) =
286 (Monomialfunc.combine (curry op +/) (fn x => x =/ rat_0) p1 p2 :poly);
288 fun poly_sub p1 p2 = poly_add p1 (poly_neg p2);
290 fun poly_cmmul (c,m) (p:poly) =
291 if c =/ rat_0 then poly_0
292 else if Ctermfunc.is_undefined m
293 then Monomialfunc.mapf (fn d => c */ d) p
294 else Monomialfunc.fold (fn (m', d) => fn a => (Monomialfunc.update (monomial_mul m m', c */ d) a)) p poly_0;
296 fun poly_mul (p1:poly) (p2:poly) =
297 Monomialfunc.fold (fn (m, c) => fn a => poly_add (poly_cmmul (c,m) p2) a) p1 poly_0;
299 fun poly_div (p1:poly) (p2:poly) =
300 if not(poly_isconst p2)
301 then error "poly_div: non-constant" else
302 let val c = eval Ctermfunc.undefined p2
303 in if c =/ rat_0 then error "poly_div: division by zero"
304 else poly_cmul (Rat.inv c) p1
307 fun poly_square p = poly_mul p p;
310 if k = 0 then poly_const rat_1
312 else let val q = poly_square(poly_pow p (k div 2)) in
313 if k mod 2 = 1 then poly_mul p q else q end;
316 if not(poly_isconst p2)
317 then error "poly_exp: not a constant"
318 else poly_pow p1 (int_of_rat (eval Ctermfunc.undefined p2));
320 fun degree x (p:poly) =
321 Monomialfunc.fold (fn (m,c) => fn a => max (monomial_degree x m) a) p 0;
323 fun multidegree (p:poly) =
324 Monomialfunc.fold (fn (m, c) => fn a => max (monomial_multidegree m) a) p 0;
326 fun poly_variables (p:poly) =
327 sort cterm_ord (Monomialfunc.fold_rev (fn (m, c) => curry (gen_union (is_equal o cterm_ord)) (monomial_variables m)) p []);;
329 (* Order monomials for human presentation. *)
331 fun cterm_ord (t,t') = TermOrd.fast_term_ord (term_of t, term_of t');
333 val humanorder_varpow = prod_ord cterm_ord (rev_order o int_ord);
336 fun ord (l1,l2) = case (l1,l2) of
340 (case humanorder_varpow (h1, h2) of
342 | EQUAL => ord (t1,t2)
343 | GREATER => GREATER)
344 in fun humanorder_monomial m1 m2 =
345 ord (sort humanorder_varpow (Ctermfunc.graph m1),
346 sort humanorder_varpow (Ctermfunc.graph m2))
349 fun fold1 f l = case l of
352 | (h::t) => f h (fold1 f t);
354 (* Conversions to strings. *)
356 fun string_of_vector min_size max_size (v:vector) =
357 let val n_raw = dim v
358 in if n_raw = 0 then "[]" else
360 val n = max min_size (min n_raw max_size)
361 val xs = map (Rat.string_of_rat o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n)
362 in "[" ^ fold1 (fn s => fn t => s ^ ", " ^ t) xs ^
363 (if n_raw > max_size then ", ...]" else "]")
367 fun string_of_matrix max_size (m:matrix) =
369 val (i_raw,j_raw) = dimensions m
370 val i = min max_size i_raw
371 val j = min max_size j_raw
372 val rstr = map (fn k => string_of_vector j j (row k m)) (1 upto i)
373 in "["^ fold1 (fn s => fn t => s^";\n "^t) rstr ^
374 (if j > max_size then "\n ...]" else "]")
377 fun string_of_term t =
379 a$b => "("^(string_of_term a)^" "^(string_of_term b)^")"
381 let val (xn, b) = Term.dest_abs x
382 in "(\\"^xn^"."^(string_of_term b)^")"
387 | _ => error "string_of_term";
389 val string_of_cterm = string_of_term o term_of;
391 fun string_of_varpow x k =
392 if k = 1 then string_of_cterm x
393 else string_of_cterm x^"^"^string_of_int k;
395 fun string_of_monomial m =
396 if Ctermfunc.is_undefined m then "1" else
397 let val vps = fold_rev (fn (x,k) => fn a => string_of_varpow x k :: a)
398 (sort humanorder_varpow (Ctermfunc.graph m)) []
399 in fold1 (fn s => fn t => s^"*"^t) vps
402 fun string_of_cmonomial (c,m) =
403 if Ctermfunc.is_undefined m then Rat.string_of_rat c
404 else if c =/ rat_1 then string_of_monomial m
405 else Rat.string_of_rat c ^ "*" ^ string_of_monomial m;;
407 fun string_of_poly (p:poly) =
408 if Monomialfunc.is_undefined p then "<<0>>" else
410 val cms = sort (fn ((m1,_),(m2,_)) => humanorder_monomial m1 m2) (Monomialfunc.graph p)
411 val s = fold (fn (m,c) => fn a =>
412 if c </ rat_0 then a ^ " - " ^ string_of_cmonomial(Rat.neg c,m)
413 else a ^ " + " ^ string_of_cmonomial(c,m))
415 val s1 = String.substring (s, 0, 3)
416 val s2 = String.substring (s, 3, String.size s - 3)
417 in "<<" ^(if s1 = " + " then s2 else "-"^s2)^">>"
420 (* Conversion from HOL term. *)
423 val neg_tm = @{cterm "uminus :: real => _"}
424 val add_tm = @{cterm "op + :: real => _"}
425 val sub_tm = @{cterm "op - :: real => _"}
426 val mul_tm = @{cterm "op * :: real => _"}
427 val inv_tm = @{cterm "inverse :: real => _"}
428 val div_tm = @{cterm "op / :: real => _"}
429 val pow_tm = @{cterm "op ^ :: real => _"}
430 val zero_tm = @{cterm "0:: real"}
431 val is_numeral = can (HOLogic.dest_number o term_of)
432 fun is_comb t = case t of _$_ => true | _ => false
433 fun poly_of_term tm =
434 if tm aconvc zero_tm then poly_0
435 else if RealArith.is_ratconst tm
436 then poly_const(RealArith.dest_ratconst tm)
438 (let val (lop,r) = Thm.dest_comb tm
439 in if lop aconvc neg_tm then poly_neg(poly_of_term r)
440 else if lop aconvc inv_tm then
441 let val p = poly_of_term r
443 then poly_const(Rat.inv (eval Ctermfunc.undefined p))
444 else error "poly_of_term: inverse of non-constant polyomial"
446 else (let val (opr,l) = Thm.dest_comb lop
448 if opr aconvc pow_tm andalso is_numeral r
449 then poly_pow (poly_of_term l) ((snd o HOLogic.dest_number o term_of) r)
450 else if opr aconvc add_tm
451 then poly_add (poly_of_term l) (poly_of_term r)
452 else if opr aconvc sub_tm
453 then poly_sub (poly_of_term l) (poly_of_term r)
454 else if opr aconvc mul_tm
455 then poly_mul (poly_of_term l) (poly_of_term r)
456 else if opr aconvc div_tm
458 val p = poly_of_term l
459 val q = poly_of_term r
460 in if poly_isconst q then poly_cmul (Rat.inv (eval Ctermfunc.undefined q)) p
461 else error "poly_of_term: division by non-constant polynomial"
466 handle CTERM ("dest_comb",_) => poly_var tm)
468 handle CTERM ("dest_comb",_) => poly_var tm)
470 val poly_of_term = fn tm =>
471 if type_of (term_of tm) = @{typ real} then poly_of_term tm
472 else error "poly_of_term: term does not have real type"
475 (* String of vector (just a list of space-separated numbers). *)
477 fun sdpa_of_vector (v:vector) =
480 val strs = map (decimalize 20 o (fn i => Intfunc.tryapplyd (snd v) i rat_0)) (1 upto n)
481 in fold1 (fn x => fn y => x ^ " " ^ y) strs ^ "\n"
484 fun increasing f ord (x,y) = ord (f x, f y);
485 fun triple_int_ord ((a,b,c),(a',b',c')) =
486 prod_ord int_ord (prod_ord int_ord int_ord)
487 ((a,(b,c)),(a',(b',c')));
488 structure Inttriplefunc = FuncFun(type key = int*int*int val ord = triple_int_ord);
490 (* String for block diagonal matrix numbered k. *)
492 fun sdpa_of_blockdiagonal k m =
494 val pfx = string_of_int k ^" "
496 Inttriplefunc.fold (fn ((b,i,j), c) => fn a => if i > j then a else ((b,i,j),c)::a) m []
497 val entss = sort (increasing fst triple_int_ord ) ents
498 in fold_rev (fn ((b,i,j),c) => fn a =>
499 pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
500 " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
503 (* String for a matrix numbered k, in SDPA sparse format. *)
505 fun sdpa_of_matrix k (m:matrix) =
507 val pfx = string_of_int k ^ " 1 "
508 val ms = Intpairfunc.fold (fn ((i,j), c) => fn a => if i > j then a else ((i,j),c)::a) (snd m) []
509 val mss = sort (increasing fst (prod_ord int_ord int_ord)) ms
510 in fold_rev (fn ((i,j),c) => fn a =>
511 pfx ^ string_of_int i ^ " " ^ string_of_int j ^
512 " " ^ decimalize 20 c ^ "\n" ^ a) mss ""
515 (* ------------------------------------------------------------------------- *)
516 (* String in SDPA sparse format for standard SDP problem: *)
518 (* X = v_1 * [M_1] + ... + v_m * [M_m] - [M_0] must be PSD *)
519 (* Minimize obj_1 * v_1 + ... obj_m * v_m *)
520 (* ------------------------------------------------------------------------- *)
522 fun sdpa_of_problem obj mats =
524 val m = length mats - 1
525 val (n,_) = dimensions (hd mats)
527 string_of_int m ^ "\n" ^
529 string_of_int n ^ "\n" ^
531 fold_rev2 (fn k => fn m => fn a => sdpa_of_matrix (k - 1) m ^ a) (1 upto length mats) mats ""
534 fun index_char str chr pos =
535 if pos >= String.size str then ~1
536 else if String.sub(str,pos) = chr then pos
537 else index_char str chr (pos + 1);
538 fun rat_of_quotient (a,b) = if b = 0 then rat_0 else Rat.rat_of_quotient (a,b);
539 fun rat_of_string s =
540 let val n = index_char s #"/" 0 in
541 if n = ~1 then s |> IntInf.fromString |> valOf |> Rat.rat_of_int
543 let val SOME numer = IntInf.fromString(String.substring(s,0,n))
544 val SOME den = IntInf.fromString (String.substring(s,n+1,String.size s - n - 1))
545 in rat_of_quotient(numer, den)
549 fun isspace x = x = " " ;
550 fun isnum x = x mem_string ["0","1","2","3","4","5","6","7","8","9"]
552 (* More parser basics. *)
557 val word = this_string
559 repeat ($$ " ") |-- word s --| repeat ($$ " ")
560 val numeral = one isnum
561 val decimalint = bulk numeral >> (rat_of_string o implode)
562 val decimalfrac = bulk numeral
563 >> (fn s => rat_of_string(implode s) // pow10 (length s))
565 decimalint -- option (Scan.$$ "." |-- decimalfrac)
566 >> (fn (h,NONE) => h | (h,SOME x) => h +/ x)
568 $$ "-" |-- prs >> Rat.neg
572 fun emptyin def xs = if null xs then (def,xs) else Scan.fail xs
574 val exponent = ($$ "e" || $$ "E") |-- signed decimalint;
576 val decimal = signed decimalsig -- (emptyin rat_0|| exponent)
577 >> (fn (h, x) => h */ pow10 (int_of_rat x));
581 let val (x,rst) = p (explode s)
582 in if null rst then x
583 else error "mkparser: unparsed input"
586 (* Parse back csdp output. *)
588 fun ignore inp = ((),[])
589 fun csdpoutput inp = ((decimal -- Scan.bulk (Scan.$$ " " |-- Scan.option decimal) >> (fn (h,to) => map_filter I ((SOME h)::to))) --| ignore >> vector_of_list) inp
590 val parse_csdpoutput = mkparser csdpoutput
592 (* Run prover on a problem in linear form. *)
594 fun run_problem prover obj mats =
595 parse_csdpoutput (prover (sdpa_of_problem obj mats))
597 (* Try some apparently sensible scaling first. Note that this is purely to *)
598 (* get a cleaner translation to floating-point, and doesn't affect any of *)
599 (* the results, in principle. In practice it seems a lot better when there *)
600 (* are extreme numbers in the original problem. *)
602 (* Version for (int*int) keys *)
604 fun max_rat x y = if x </ y then y else x
605 fun common_denominator fld amat acc =
606 fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
607 fun maximal_element fld amat acc =
608 fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc
609 fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
610 in Real.fromLargeInt a / Real.fromLargeInt b end;
613 fun pi_scale_then solver (obj:vector) mats =
615 val cd1 = fold_rev (common_denominator Intpairfunc.fold) mats (rat_1)
616 val cd2 = common_denominator Intfunc.fold (snd obj) (rat_1)
617 val mats' = map (Intpairfunc.mapf (fn x => cd1 */ x)) mats
618 val obj' = vector_cmul cd2 obj
619 val max1 = fold_rev (maximal_element Intpairfunc.fold) mats' (rat_0)
620 val max2 = maximal_element Intfunc.fold (snd obj') (rat_0)
621 val scal1 = pow2 (20 - trunc(Math.ln (float_of_rat max1) / Math.ln 2.0))
622 val scal2 = pow2 (20 - trunc(Math.ln (float_of_rat max2) / Math.ln 2.0))
623 val mats'' = map (Intpairfunc.mapf (fn x => x */ scal1)) mats'
624 val obj'' = vector_cmul scal2 obj'
625 in solver obj'' mats''
629 (* Try some apparently sensible scaling first. Note that this is purely to *)
630 (* get a cleaner translation to floating-point, and doesn't affect any of *)
631 (* the results, in principle. In practice it seems a lot better when there *)
632 (* are extreme numbers in the original problem. *)
634 (* Version for (int*int*int) keys *)
636 fun max_rat x y = if x </ y then y else x
637 fun common_denominator fld amat acc =
638 fld (fn (m,c) => fn a => lcm_rat (denominator_rat c) a) amat acc
639 fun maximal_element fld amat acc =
640 fld (fn (m,c) => fn maxa => max_rat maxa (abs_rat c)) amat acc
641 fun float_of_rat x = let val (a,b) = Rat.quotient_of_rat x
642 in Real.fromLargeInt a / Real.fromLargeInt b end;
643 fun int_of_float x = (trunc x handle Overflow => 0 | Domain => 0)
646 fun tri_scale_then solver (obj:vector) mats =
648 val cd1 = fold_rev (common_denominator Inttriplefunc.fold) mats (rat_1)
649 val cd2 = common_denominator Intfunc.fold (snd obj) (rat_1)
650 val mats' = map (Inttriplefunc.mapf (fn x => cd1 */ x)) mats
651 val obj' = vector_cmul cd2 obj
652 val max1 = fold_rev (maximal_element Inttriplefunc.fold) mats' (rat_0)
653 val max2 = maximal_element Intfunc.fold (snd obj') (rat_0)
654 val scal1 = pow2 (20 - int_of_float(Math.ln (float_of_rat max1) / Math.ln 2.0))
655 val scal2 = pow2 (20 - int_of_float(Math.ln (float_of_rat max2) / Math.ln 2.0))
656 val mats'' = map (Inttriplefunc.mapf (fn x => x */ scal1)) mats'
657 val obj'' = vector_cmul scal2 obj'
658 in solver obj'' mats''
662 (* Round a vector to "nice" rationals. *)
664 fun nice_rational n x = round_rat (n */ x) // n;;
665 fun nice_vector n ((d,v) : vector) =
666 (d, Intfunc.fold (fn (i,c) => fn a =>
667 let val y = nice_rational n c
668 in if c =/ rat_0 then a
669 else Intfunc.update (i,y) a end) v Intfunc.undefined):vector
671 fun dest_ord f x = is_equal (f x);
673 (* Stuff for "equations" ((int*int*int)->num functions). *)
675 fun tri_equation_cmul c eq =
676 if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
678 fun tri_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
680 fun tri_equation_eval assig eq =
681 let fun value v = Inttriplefunc.apply assig v
682 in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
685 (* Eliminate among linear equations: return unconstrained variables and *)
686 (* assignments for the others in terms of them. We give one pseudo-variable *)
687 (* "one" that's used for a constant term. *)
690 fun extract_first p l = case l of (* FIXME : use find_first instead *)
691 [] => error "extract_first"
692 | h::t => if p h then (h,t) else
693 let val (k,s) = extract_first p t in (k,h::s) end
694 fun eliminate vars dun eqs = case vars of
695 [] => if forall Inttriplefunc.is_undefined eqs then dun
696 else raise Unsolvable
699 val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs
700 val a = Inttriplefunc.apply eq v
701 val eq' = tri_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
703 let val b = Inttriplefunc.tryapplyd e v rat_0
704 in if b =/ rat_0 then e else
705 tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
707 in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
709 handle Failure _ => eliminate vs dun eqs)
711 fun tri_eliminate_equations one vars eqs =
713 val assig = eliminate vars Inttriplefunc.undefined eqs
714 val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
715 in (distinct (dest_ord triple_int_ord) vs, assig)
719 (* Eliminate all variables, in an essentially arbitrary order. *)
721 fun tri_eliminate_all_equations one =
723 fun choose_variable eq =
724 let val (v,_) = Inttriplefunc.choose eq
725 in if is_equal (triple_int_ord(v,one)) then
726 let val eq' = Inttriplefunc.undefine v eq
727 in if Inttriplefunc.is_undefined eq' then error "choose_variable"
728 else fst (Inttriplefunc.choose eq')
732 fun eliminate dun eqs = case eqs of
735 if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
736 let val v = choose_variable eq
737 val a = Inttriplefunc.apply eq v
738 val eq' = tri_equation_cmul ((Rat.rat_of_int ~1) // a)
739 (Inttriplefunc.undefine v eq)
741 let val b = Inttriplefunc.tryapplyd e v rat_0
742 in if b =/ rat_0 then e
743 else tri_equation_add e (tri_equation_cmul (Rat.neg b // a) eq)
745 in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun))
750 val assig = eliminate Inttriplefunc.undefined eqs
751 val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
752 in (distinct (dest_ord triple_int_ord) vs,assig)
756 (* Solve equations by assigning arbitrary numbers. *)
758 fun tri_solve_equations one eqs =
760 val (vars,assigs) = tri_eliminate_all_equations one eqs
761 val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars
762 (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
764 Inttriplefunc.combine (curry op +/) (K false)
765 (Inttriplefunc.mapf (tri_equation_eval vfn) assigs) vfn
766 in if forall (fn e => tri_equation_eval ass e =/ rat_0) eqs
767 then Inttriplefunc.undefine one ass else raise Sanity
770 (* Multiply equation-parametrized poly by regular poly and add accumulator. *)
772 fun tri_epoly_pmul p q acc =
773 Monomialfunc.fold (fn (m1, c) => fn a =>
774 Monomialfunc.fold (fn (m2,e) => fn b =>
775 let val m = monomial_mul m1 m2
776 val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined
777 in Monomialfunc.update (m,tri_equation_add (tri_equation_cmul c e) es) b
780 (* Usual operations on equation-parametrized poly. *)
782 fun tri_epoly_cmul c l =
783 if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (tri_equation_cmul c) l;;
785 val tri_epoly_neg = tri_epoly_cmul (Rat.rat_of_int ~1);
787 val tri_epoly_add = Inttriplefunc.combine tri_equation_add Inttriplefunc.is_undefined;
789 fun tri_epoly_sub p q = tri_epoly_add p (tri_epoly_neg q);;
791 (* Stuff for "equations" ((int*int)->num functions). *)
793 fun pi_equation_cmul c eq =
794 if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (fn d => c */ d) eq;
796 fun pi_equation_add eq1 eq2 = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0) eq1 eq2;
798 fun pi_equation_eval assig eq =
799 let fun value v = Inttriplefunc.apply assig v
800 in Inttriplefunc.fold (fn (v, c) => fn a => a +/ value v */ c) eq rat_0
803 (* Eliminate among linear equations: return unconstrained variables and *)
804 (* assignments for the others in terms of them. We give one pseudo-variable *)
805 (* "one" that's used for a constant term. *)
808 fun extract_first p l = case l of
809 [] => error "extract_first"
810 | h::t => if p h then (h,t) else
811 let val (k,s) = extract_first p t in (k,h::s) end
812 fun eliminate vars dun eqs = case vars of
813 [] => if forall Inttriplefunc.is_undefined eqs then dun
814 else raise Unsolvable
817 val (eq,oeqs) = extract_first (fn e => Inttriplefunc.defined e v) eqs
818 val a = Inttriplefunc.apply eq v
819 val eq' = pi_equation_cmul ((Rat.neg rat_1) // a) (Inttriplefunc.undefine v eq)
821 let val b = Inttriplefunc.tryapplyd e v rat_0
822 in if b =/ rat_0 then e else
823 pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
825 in eliminate vs (Inttriplefunc.update (v,eq') (Inttriplefunc.mapf elim dun)) (map elim oeqs)
827 handle Failure _ => eliminate vs dun eqs
829 fun pi_eliminate_equations one vars eqs =
831 val assig = eliminate vars Inttriplefunc.undefined eqs
832 val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
833 in (distinct (dest_ord triple_int_ord) vs, assig)
837 (* Eliminate all variables, in an essentially arbitrary order. *)
839 fun pi_eliminate_all_equations one =
841 fun choose_variable eq =
842 let val (v,_) = Inttriplefunc.choose eq
843 in if is_equal (triple_int_ord(v,one)) then
844 let val eq' = Inttriplefunc.undefine v eq
845 in if Inttriplefunc.is_undefined eq' then error "choose_variable"
846 else fst (Inttriplefunc.choose eq')
850 fun eliminate dun eqs = case eqs of
853 if Inttriplefunc.is_undefined eq then eliminate dun oeqs else
854 let val v = choose_variable eq
855 val a = Inttriplefunc.apply eq v
856 val eq' = pi_equation_cmul ((Rat.rat_of_int ~1) // a)
857 (Inttriplefunc.undefine v eq)
859 let val b = Inttriplefunc.tryapplyd e v rat_0
860 in if b =/ rat_0 then e
861 else pi_equation_add e (pi_equation_cmul (Rat.neg b // a) eq)
863 in eliminate (Inttriplefunc.update(v, eq') (Inttriplefunc.mapf elim dun))
868 val assig = eliminate Inttriplefunc.undefined eqs
869 val vs = Inttriplefunc.fold (fn (x, f) => fn a => remove (dest_ord triple_int_ord) one (Inttriplefunc.dom f) @ a) assig []
870 in (distinct (dest_ord triple_int_ord) vs,assig)
874 (* Solve equations by assigning arbitrary numbers. *)
876 fun pi_solve_equations one eqs =
878 val (vars,assigs) = pi_eliminate_all_equations one eqs
879 val vfn = fold_rev (fn v => Inttriplefunc.update(v,rat_0)) vars
880 (Inttriplefunc.onefunc(one, Rat.rat_of_int ~1))
882 Inttriplefunc.combine (curry op +/) (K false)
883 (Inttriplefunc.mapf (pi_equation_eval vfn) assigs) vfn
884 in if forall (fn e => pi_equation_eval ass e =/ rat_0) eqs
885 then Inttriplefunc.undefine one ass else raise Sanity
888 (* Multiply equation-parametrized poly by regular poly and add accumulator. *)
890 fun pi_epoly_pmul p q acc =
891 Monomialfunc.fold (fn (m1, c) => fn a =>
892 Monomialfunc.fold (fn (m2,e) => fn b =>
893 let val m = monomial_mul m1 m2
894 val es = Monomialfunc.tryapplyd b m Inttriplefunc.undefined
895 in Monomialfunc.update (m,pi_equation_add (pi_equation_cmul c e) es) b
898 (* Usual operations on equation-parametrized poly. *)
900 fun pi_epoly_cmul c l =
901 if c =/ rat_0 then Inttriplefunc.undefined else Inttriplefunc.mapf (pi_equation_cmul c) l;;
903 val pi_epoly_neg = pi_epoly_cmul (Rat.rat_of_int ~1);
905 val pi_epoly_add = Inttriplefunc.combine pi_equation_add Inttriplefunc.is_undefined;
907 fun pi_epoly_sub p q = pi_epoly_add p (pi_epoly_neg q);;
909 fun allpairs f l1 l2 = fold_rev (fn x => (curry (op @)) (map (f x) l2)) l1 [];
911 (* Hence produce the "relevant" monomials: those whose squares lie in the *)
912 (* Newton polytope of the monomials in the input. (This is enough according *)
913 (* to Reznik: "Extremal PSD forms with few terms", Duke Math. Journal, *)
914 (* vol 45, pp. 363--374, 1978. *)
916 (* These are ordered in sort of decreasing degree. In particular the *)
917 (* constant monomial is last; this gives an order in diagonalization of the *)
918 (* quadratic form that will tend to display constants. *)
920 (* Diagonalize (Cholesky/LDU) the matrix corresponding to a quadratic form. *)
923 fun diagonalize n i m =
924 if Intpairfunc.is_undefined (snd m) then []
926 let val a11 = Intpairfunc.tryapplyd (snd m) (i,i) rat_0
927 in if a11 </ rat_0 then raise Failure "diagonalize: not PSD"
928 else if a11 =/ rat_0 then
929 if Intfunc.is_undefined (snd (row i m)) then diagonalize n (i + 1) m
930 else raise Failure "diagonalize: not PSD ___ "
934 val v' = (fst v, Intfunc.fold (fn (i, c) => fn a =>
936 in if y = rat_0 then a else Intfunc.update (i,y) a
937 end) (snd v) Intfunc.undefined)
938 fun upt0 x y a = if y = rat_0 then a else Intpairfunc.update (x,y) a
941 iter (i+1,n) (fn j =>
942 iter (i+1,n) (fn k =>
943 (upt0 (j,k) (Intpairfunc.tryapplyd (snd m) (j,k) rat_0 -/ Intfunc.tryapplyd (snd v) j rat_0 */ Intfunc.tryapplyd (snd v') k rat_0))))
944 Intpairfunc.undefined)
945 in (a11,v')::diagonalize n (i + 1) m'
951 val nn = dimensions m
953 in if snd nn <> n then error "diagonalize: non-square matrix"
954 else diagonalize n 1 m
958 fun gcd_rat a b = Rat.rat_of_int (Integer.gcd (int_of_rat a) (int_of_rat b));
960 (* Adjust a diagonalization to collect rationals at the start. *)
961 (* FIXME : Potentially polymorphic keys, but here only: integers!! *)
963 fun upd0 x y a = if y =/ rat_0 then a else Intfunc.update(x,y) a;
965 (d, Intfunc.fold (fn (i,c) => fn a => upd0 i (f c) a) v Intfunc.undefined)
968 Intfunc.fold (fn (i,c) => fn a => lcm_rat a (denominator_rat c))
970 Intfunc.fold (fn (i,c) => fn a => gcd_rat a (numerator_rat c))
972 in ((c // (a */ a)),mapa (fn x => a */ x) l)
975 fun deration d = if null d then (rat_0,d) else
976 let val d' = map adj d
977 val a = fold (lcm_rat o denominator_rat o fst) d' rat_1 //
978 fold (gcd_rat o numerator_rat o fst) d' rat_0
979 in ((rat_1 // a),map (fn (c,l) => (a */ c,l)) d')
983 (* Enumeration of monomials with given multidegree bound. *)
985 fun enumerate_monomials d vars =
987 else if d = 0 then [Ctermfunc.undefined]
988 else if null vars then [monomial_1] else
990 map (fn k => let val oths = enumerate_monomials (d - k) (tl vars)
991 in map (fn ks => if k = 0 then ks else Ctermfunc.update (hd vars, k) ks) oths end) (0 upto d)
992 in fold1 (curry op @) alts
995 (* Enumerate products of distinct input polys with degree <= d. *)
996 (* We ignore any constant input polynomials. *)
997 (* Give the output polynomial and a record of how it was derived. *)
1002 fun enumerate_products d pols =
1003 if d = 0 then [(poly_const rat_1,Rational_lt rat_1)]
1004 else if d < 0 then [] else
1006 [] => [(poly_const rat_1,Rational_lt rat_1)]
1008 let val e = multidegree p
1009 in if e = 0 then enumerate_products d ps else
1010 enumerate_products d ps @
1011 map (fn (q,c) => (poly_mul p q,Product(b,c)))
1012 (enumerate_products (d - e) ps)
1016 (* Convert regular polynomial. Note that we treat (0,0,0) as -1. *)
1018 fun epoly_of_poly p =
1019 Monomialfunc.fold (fn (m,c) => fn a => Monomialfunc.update (m, Inttriplefunc.onefunc ((0,0,0), Rat.neg c)) a) p Monomialfunc.undefined;
1021 (* String for block diagonal matrix numbered k. *)
1023 fun sdpa_of_blockdiagonal k m =
1025 val pfx = string_of_int k ^" "
1028 (fn ((b,i,j),c) => fn a => if i > j then a else ((b,i,j),c)::a)
1030 val entss = sort (increasing fst triple_int_ord) ents
1031 in fold_rev (fn ((b,i,j),c) => fn a =>
1032 pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
1033 " " ^ decimalize 20 c ^ "\n" ^ a) entss ""
1036 (* SDPA for problem using block diagonal (i.e. multiple SDPs) *)
1038 fun sdpa_of_blockproblem nblocks blocksizes obj mats =
1039 let val m = length mats - 1
1041 string_of_int m ^ "\n" ^
1042 string_of_int nblocks ^ "\n" ^
1043 (fold1 (fn s => fn t => s^" "^t) (map string_of_int blocksizes)) ^
1045 sdpa_of_vector obj ^
1046 fold_rev2 (fn k => fn m => fn a => sdpa_of_blockdiagonal (k - 1) m ^ a)
1047 (1 upto length mats) mats ""
1050 (* Run prover on a problem in block diagonal form. *)
1052 fun run_blockproblem prover nblocks blocksizes obj mats=
1053 parse_csdpoutput (prover (sdpa_of_blockproblem nblocks blocksizes obj mats))
1055 (* 3D versions of matrix operations to consider blocks separately. *)
1057 val bmatrix_add = Inttriplefunc.combine (curry op +/) (fn x => x =/ rat_0);
1058 fun bmatrix_cmul c bm =
1059 if c =/ rat_0 then Inttriplefunc.undefined
1060 else Inttriplefunc.mapf (fn x => c */ x) bm;
1062 val bmatrix_neg = bmatrix_cmul (Rat.rat_of_int ~1);
1063 fun bmatrix_sub m1 m2 = bmatrix_add m1 (bmatrix_neg m2);;
1065 (* Smash a block matrix into components. *)
1067 fun blocks blocksizes bm =
1069 let val m = Inttriplefunc.fold
1070 (fn ((b,i,j),c) => fn a => if b = b0 then Intpairfunc.update ((i,j),c) a else a) bm Intpairfunc.undefined
1071 val d = Intpairfunc.fold (fn ((i,j),c) => fn a => max a (max i j)) m 0
1072 in (((bs,bs),m):matrix) end)
1073 (blocksizes ~~ (1 upto length blocksizes));;
1075 (* FIXME : Get rid of this !!!*)
1077 fun tryfind_with msg f [] = raise Failure msg
1078 | tryfind_with msg f (x::xs) = (f x handle Failure s => tryfind_with s f xs);
1080 fun tryfind f = tryfind_with "tryfind" f
1084 fun tryfind f [] = error "tryfind"
1085 | tryfind f (x::xs) = (f x handle ERROR _ => tryfind f xs);
1088 (* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
1094 fun real_positivnullstellensatz_general prover linf d eqs leqs pol =
1096 val vars = fold_rev (curry (gen_union (op aconvc)) o poly_variables)
1097 (pol::eqs @ map fst leqs) []
1098 val monoid = if linf then
1099 (poly_const rat_1,Rational_lt rat_1)::
1100 (filter (fn (p,c) => multidegree p <= d) leqs)
1101 else enumerate_products d leqs
1102 val nblocks = length monoid
1103 fun mk_idmultiplier k p =
1105 val e = d - multidegree p
1106 val mons = enumerate_monomials e vars
1107 val nons = mons ~~ (1 upto length mons)
1109 fold_rev (fn (m,n) => Monomialfunc.update(m,Inttriplefunc.onefunc((~k,~n,n),rat_1))) nons Monomialfunc.undefined)
1112 fun mk_sqmultiplier k (p,c) =
1114 val e = (d - multidegree p) div 2
1115 val mons = enumerate_monomials e vars
1116 val nons = mons ~~ (1 upto length mons)
1118 fold_rev (fn (m1,n1) =>
1119 fold_rev (fn (m2,n2) => fn a =>
1120 let val m = monomial_mul m1 m2
1121 in if n1 > n2 then a else
1122 let val c = if n1 = n2 then rat_1 else rat_2
1123 val e = Monomialfunc.tryapplyd a m Inttriplefunc.undefined
1124 in Monomialfunc.update(m, tri_equation_add (Inttriplefunc.onefunc((k,n1,n2), c)) e) a
1127 nons Monomialfunc.undefined)
1130 val (sqmonlist,sqs) = split_list (map2 mk_sqmultiplier (1 upto length monoid) monoid)
1131 val (idmonlist,ids) = split_list(map2 mk_idmultiplier (1 upto length eqs) eqs)
1132 val blocksizes = map length sqmonlist
1134 fold_rev2 (fn p => fn q => fn a => tri_epoly_pmul p q a) eqs ids
1135 (fold_rev2 (fn (p,c) => fn s => fn a => tri_epoly_pmul p s a) monoid sqs
1136 (epoly_of_poly(poly_neg pol)))
1137 val eqns = Monomialfunc.fold (fn (m,e) => fn a => e::a) bigsum []
1138 val (pvs,assig) = tri_eliminate_all_equations (0,0,0) eqns
1139 val qvars = (0,0,0)::pvs
1140 val allassig = fold_rev (fn v => Inttriplefunc.update(v,(Inttriplefunc.onefunc(v,rat_1)))) pvs assig
1142 Inttriplefunc.fold (fn ((b,i,j), ass) => fn m =>
1143 if b < 0 then m else
1144 let val c = Inttriplefunc.tryapplyd ass v rat_0
1145 in if c = rat_0 then m else
1146 Inttriplefunc.update ((b,j,i), c) (Inttriplefunc.update ((b,i,j), c) m)
1148 allassig Inttriplefunc.undefined
1149 val diagents = Inttriplefunc.fold
1150 (fn ((b,i,j), e) => fn a => if b > 0 andalso i = j then tri_equation_add e a else a)
1151 allassig Inttriplefunc.undefined
1153 val mats = map mk_matrix qvars
1154 val obj = (length pvs,
1155 itern 1 pvs (fn v => fn i => Intfunc.updatep iszero (i,Inttriplefunc.tryapplyd diagents v rat_0))
1157 val raw_vec = if null pvs then vector_0 0
1158 else tri_scale_then (run_blockproblem prover nblocks blocksizes) obj mats
1159 fun int_element (d,v) i = Intfunc.tryapplyd v i rat_0
1160 fun cterm_element (d,v) i = Ctermfunc.tryapplyd v i rat_0
1162 fun find_rounding d =
1164 val _ = if !debugging
1165 then writeln ("Trying rounding with limit "^Rat.string_of_rat d ^ "\n")
1167 val vec = nice_vector d raw_vec
1168 val blockmat = iter (1,dim vec)
1169 (fn i => fn a => bmatrix_add (bmatrix_cmul (int_element vec i) (nth mats i)) a)
1170 (bmatrix_neg (nth mats 0))
1171 val allmats = blocks blocksizes blockmat
1172 in (vec,map diag allmats)
1175 if null pvs then find_rounding rat_1
1176 else tryfind find_rounding (map Rat.rat_of_int (1 upto 31) @
1177 map pow2 (5 upto 66))
1179 fold_rev (fn k => Inttriplefunc.update (nth pvs (k - 1), int_element vec k))
1180 (1 upto dim vec) (Inttriplefunc.onefunc ((0,0,0), Rat.rat_of_int ~1))
1182 Inttriplefunc.fold (fn (v,e) => fn a => Inttriplefunc.update(v, tri_equation_eval newassigs e) a) allassig newassigs
1183 fun poly_of_epoly p =
1184 Monomialfunc.fold (fn (v,e) => fn a => Monomialfunc.updatep iszero (v,tri_equation_eval finalassigs e) a)
1185 p Monomialfunc.undefined
1187 let fun mk_sq (c,m) =
1188 (c,fold_rev (fn k=> fn a => Monomialfunc.updatep iszero (nth mons (k - 1), int_element m k) a)
1189 (1 upto length mons) Monomialfunc.undefined)
1192 val sqs = map2 mk_sos sqmonlist ratdias
1193 val cfs = map poly_of_epoly ids
1194 val msq = filter (fn (a,b) => not (null b)) (map2 pair monoid sqs)
1195 fun eval_sq sqs = fold_rev (fn (c,q) => poly_add (poly_cmul c (poly_mul q q))) sqs poly_0
1197 fold_rev (fn ((p,c),s) => poly_add (poly_mul p (eval_sq s))) msq
1198 (fold_rev2 (fn p => fn q => poly_add (poly_mul p q)) cfs eqs
1201 in if not(Monomialfunc.is_undefined sanity) then raise Sanity else
1202 (cfs,map (fn (a,b) => (snd a,b)) msq)
1208 (* Iterative deepening. *)
1211 (writeln ("Searching with depth limit " ^ string_of_int n) ; (f n handle Failure s => (writeln ("failed with message: " ^ s) ; deepen f (n+1))))
1213 (* The ordering so we can create canonical HOL polynomials. *)
1215 fun dest_monomial mon = sort (increasing fst cterm_ord) (Ctermfunc.graph mon);
1217 fun monomial_order (m1,m2) =
1218 if Ctermfunc.is_undefined m2 then LESS
1219 else if Ctermfunc.is_undefined m1 then GREATER
1221 let val mon1 = dest_monomial m1
1222 val mon2 = dest_monomial m2
1223 val deg1 = fold (curry op + o snd) mon1 0
1224 val deg2 = fold (curry op + o snd) mon2 0
1225 in if deg1 < deg2 then GREATER else if deg1 > deg2 then LESS
1226 else list_ord (prod_ord cterm_ord int_ord) (mon1,mon2)
1230 map (fn (m,c) => (c,dest_monomial m))
1231 (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p));
1233 (* Map back polynomials and their composites to HOL. *)
1236 open Thm Numeral RealArith
1239 fun cterm_of_varpow x k = if k = 1 then x else capply (capply @{cterm "op ^ :: real => _"} x)
1240 (mk_cnumber @{ctyp nat} k)
1242 fun cterm_of_monomial m =
1243 if Ctermfunc.is_undefined m then @{cterm "1::real"}
1246 val m' = dest_monomial m
1247 val vps = fold_rev (fn (x,k) => cons (cterm_of_varpow x k)) m' []
1248 in fold1 (fn s => fn t => capply (capply @{cterm "op * :: real => _"} s) t) vps
1251 fun cterm_of_cmonomial (m,c) = if Ctermfunc.is_undefined m then cterm_of_rat c
1252 else if c = Rat.one then cterm_of_monomial m
1253 else capply (capply @{cterm "op *::real => _"} (cterm_of_rat c)) (cterm_of_monomial m);
1255 fun cterm_of_poly p =
1256 if Monomialfunc.is_undefined p then @{cterm "0::real"}
1259 val cms = map cterm_of_cmonomial
1260 (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p))
1261 in fold1 (fn t1 => fn t2 => capply(capply @{cterm "op + :: real => _"} t1) t2) cms
1264 fun cterm_of_sqterm (c,p) = Product(Rational_lt c,Square(cterm_of_poly p));
1266 fun cterm_of_sos (pr,sqs) = if null sqs then pr
1267 else Product(pr,fold1 (fn a => fn b => Sum(a,b)) (map cterm_of_sqterm sqs));
1271 (* Interface to HOL. *)
1273 open Thm Conv RealArith
1274 val concl = dest_arg o cprop_of
1275 fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
1277 (* FIXME: Replace tryfind by get_first !! *)
1278 fun real_nonlinear_prover prover ctxt =
1280 val {add,mul,neg,pow,sub,main} = Normalizer.semiring_normalizers_ord_wrapper ctxt
1281 (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"}))
1283 val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
1284 real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
1285 fun mainf translator (eqs,les,lts) =
1287 val eq0 = map (poly_of_term o dest_arg1 o concl) eqs
1288 val le0 = map (poly_of_term o dest_arg o concl) les
1289 val lt0 = map (poly_of_term o dest_arg o concl) lts
1290 val eqp0 = map (fn (t,i) => (t,Axiom_eq i)) (eq0 ~~ (0 upto (length eq0 - 1)))
1291 val lep0 = map (fn (t,i) => (t,Axiom_le i)) (le0 ~~ (0 upto (length le0 - 1)))
1292 val ltp0 = map (fn (t,i) => (t,Axiom_lt i)) (lt0 ~~ (0 upto (length lt0 - 1)))
1293 val (keq,eq) = List.partition (fn (p,_) => multidegree p = 0) eqp0
1294 val (klep,lep) = List.partition (fn (p,_) => multidegree p = 0) lep0
1295 val (kltp,ltp) = List.partition (fn (p,_) => multidegree p = 0) ltp0
1296 fun trivial_axiom (p,ax) =
1298 Axiom_eq n => if eval Ctermfunc.undefined p <>/ Rat.zero then nth eqs n
1299 else raise Failure "trivial_axiom: Not a trivial axiom"
1300 | Axiom_le n => if eval Ctermfunc.undefined p </ Rat.zero then nth les n
1301 else raise Failure "trivial_axiom: Not a trivial axiom"
1302 | Axiom_lt n => if eval Ctermfunc.undefined p <=/ Rat.zero then nth lts n
1303 else raise Failure "trivial_axiom: Not a trivial axiom"
1304 | _ => error "trivial_axiom: Not a trivial axiom"
1306 ((let val th = tryfind trivial_axiom (keq @ klep @ kltp)
1307 in fconv_rule (arg_conv (arg1_conv real_poly_conv) then_conv field_comp_conv) th end)
1308 handle Failure _ => (
1310 val pol = fold_rev poly_mul (map fst ltp) (poly_const Rat.one)
1313 let val e = multidegree pol
1314 val k = if e = 0 then 0 else d div e
1315 val eq' = map fst eq
1316 in tryfind (fn i => (d,i,real_positivnullstellensatz_general prover false d eq' leq
1317 (poly_neg(poly_pow pol i))))
1320 val (d,i,(cert_ideal,cert_cone)) = deepen tryall 0
1322 map2 (fn q => fn (p,ax) => Eqmul(cterm_of_poly q,ax)) cert_ideal eq
1323 val proofs_cone = map cterm_of_sos cert_cone
1324 val proof_ne = if null ltp then Rational_lt Rat.one else
1325 let val p = fold1 (fn s => fn t => Product(s,t)) (map snd ltp)
1326 in funpow i (fn q => Product(p,q)) (Rational_lt Rat.one)
1328 val proof = fold1 (fn s => fn t => Sum(s,t))
1329 (proof_ne :: proofs_ideal @ proofs_cone)
1330 in writeln "Translating proof certificate to HOL";
1331 translator (eqs,les,lts) proof
1337 fun C f x y = f y x;
1338 (* FIXME : This is very bad!!!*)
1339 fun subst_conv eqs t =
1341 val t' = fold (Thm.cabs o Thm.lhs_of) eqs t
1342 in Conv.fconv_rule (Thm.beta_conversion true) (fold (C combination) eqs (reflexive t'))
1345 (* A wrapper that tries to substitute away variables first. *)
1348 open Thm Conv RealArith
1349 fun simple_cterm_ord t u = TermOrd.fast_term_ord (term_of t, term_of u) = LESS
1350 val concl = dest_arg o cprop_of
1352 fconv_rule (rewr_conv @{lemma "(a + x == y) == (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps) })
1354 fconv_rule (rewr_conv @{lemma "(x + a == y) == (x == y - (a::real))" by (atomize (full)) (simp add: ring_simps)})
1355 fun substitutable_monomial fvs tm = case term_of tm of
1356 Free(_,@{typ real}) => if not (member (op aconvc) fvs tm) then (Rat.one,tm)
1357 else raise Failure "substitutable_monomial"
1358 | @{term "op * :: real => _"}$c$(t as Free _ ) =>
1359 if is_ratconst (dest_arg1 tm) andalso not (member (op aconvc) fvs (dest_arg tm))
1360 then (dest_ratconst (dest_arg1 tm),dest_arg tm) else raise Failure "substitutable_monomial"
1361 | @{term "op + :: real => _"}$s$t =>
1362 (substitutable_monomial (add_cterm_frees (dest_arg tm) fvs) (dest_arg1 tm)
1363 handle Failure _ => substitutable_monomial (add_cterm_frees (dest_arg1 tm) fvs) (dest_arg tm))
1364 | _ => raise Failure "substitutable_monomial"
1366 fun isolate_variable v th =
1367 let val w = dest_arg1 (cprop_of th)
1368 in if v aconvc w then th
1369 else case term_of w of
1370 @{term "op + :: real => _"}$s$t =>
1371 if dest_arg1 w aconvc v then shuffle2 th
1372 else isolate_variable v (shuffle1 th)
1373 | _ => error "isolate variable : This should not happen?"
1377 fun real_nonlinear_subst_prover prover ctxt =
1379 val {add,mul,neg,pow,sub,main} = Normalizer.semiring_normalizers_ord_wrapper ctxt
1380 (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"}))
1383 val (real_poly_add_conv,real_poly_mul_conv,real_poly_neg_conv,
1384 real_poly_pow_conv,real_poly_sub_conv,real_poly_conv) = (add,mul,neg,pow,sub,main)
1386 fun make_substitution th =
1388 val (c,v) = substitutable_monomial [] (dest_arg1(concl th))
1389 val th1 = Drule.arg_cong_rule (capply @{cterm "op * :: real => _"} (cterm_of_rat (Rat.inv c))) (mk_meta_eq th)
1390 val th2 = fconv_rule (binop_conv real_poly_mul_conv) th1
1391 in fconv_rule (arg_conv real_poly_conv) (isolate_variable v th2)
1394 let val g = Thm.dest_fun2 ct
1395 in if g aconvc @{cterm "op <= :: real => _"}
1396 orelse g aconvc @{cterm "op < :: real => _"}
1397 then arg_conv cv ct else arg1_conv cv ct
1399 fun mainf translator =
1401 fun substfirst(eqs,les,lts) =
1403 val eth = tryfind make_substitution eqs
1404 val modify = fconv_rule (arg_conv (oprconv(subst_conv [eth] then_conv real_poly_conv)))
1406 (filter_out (fn t => (Thm.dest_arg1 o Thm.dest_arg o cprop_of) t
1407 aconvc @{cterm "0::real"}) (map modify eqs),
1408 map modify les,map modify lts)
1410 handle Failure _ => real_nonlinear_prover prover ctxt translator (rev eqs, rev les, rev lts))
1418 (* Overall function. *)
1420 fun real_sos prover ctxt t = gen_prover_real_arith ctxt (real_nonlinear_subst_prover prover ctxt) t;
1426 Const("all",_) $ Abs (xn,xT,p) =>
1427 let val (a,(v,t')) = (apsnd (Thm.dest_abs (SOME xn)) o Thm.dest_comb) ct
1428 in apfst (cons v) (strip_all t')
1432 fun core_sos_conv prover ctxt t = Drule.arg_cong_rule @{cterm Trueprop} (real_sos prover ctxt (Thm.dest_arg t) RS @{thm Eq_TrueI})
1434 val known_sos_constants =
1435 [@{term "op ==>"}, @{term "Trueprop"},
1436 @{term "op -->"}, @{term "op &"}, @{term "op |"},
1437 @{term "Not"}, @{term "op = :: bool => _"},
1438 @{term "All :: (real => _) => _"}, @{term "Ex :: (real => _) => _"},
1439 @{term "op = :: real => _"}, @{term "op < :: real => _"},
1440 @{term "op <= :: real => _"},
1441 @{term "op + :: real => _"}, @{term "op - :: real => _"},
1442 @{term "op * :: real => _"}, @{term "uminus :: real => _"},
1443 @{term "op / :: real => _"}, @{term "inverse :: real => _"},
1444 @{term "op ^ :: real => _"}, @{term "abs :: real => _"},
1445 @{term "min :: real => _"}, @{term "max :: real => _"},
1446 @{term "0::real"}, @{term "1::real"}, @{term "number_of :: int => real"},
1447 @{term "number_of :: int => nat"},
1448 @{term "Int.Bit0"}, @{term "Int.Bit1"},
1449 @{term "Int.Pls"}, @{term "Int.Min"}];
1451 fun check_sos kcts ct =
1454 val _ = if not (null (Term.add_tfrees t [])
1455 andalso null (Term.add_tvars t []))
1456 then error "SOS: not sos. Additional type varables" else ()
1457 val fs = Term.add_frees t []
1458 val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs
1459 then error "SOS: not sos. Variables with type not real" else ()
1460 val vs = Term.add_vars t []
1461 val _ = if exists (fn ((_,T)) => not (T = @{typ "real"})) fs
1462 then error "SOS: not sos. Variables with type not real" else ()
1463 val ukcs = subtract (fn (t,p) => Const p aconv t) kcts (Term.add_consts t [])
1464 val _ = if null ukcs then ()
1465 else error ("SOSO: Unknown constants in Subgoal:" ^ commas (map fst ukcs))
1468 fun core_sos_tac prover ctxt = CSUBGOAL (fn (ct, i) =>
1469 let val _ = check_sos known_sos_constants ct
1470 val (avs, p) = strip_all ct
1471 val th = standard (fold_rev forall_intr avs (real_sos prover ctxt (Thm.dest_arg p)))
1474 fun default_SOME f NONE v = SOME v
1475 | default_SOME f (SOME v) _ = SOME v;
1477 fun lift_SOME f NONE a = f a
1478 | lift_SOME f (SOME a) _ = SOME a;
1482 val is_numeral = can (HOLogic.dest_number o term_of)
1484 fun get_denom b ct = case term_of ct of
1485 @{term "op / :: real => _"} $ _ $ _ =>
1486 if is_numeral (Thm.dest_arg ct) then get_denom b (Thm.dest_arg1 ct)
1487 else default_SOME (get_denom b) (get_denom b (Thm.dest_arg ct)) (Thm.dest_arg ct, b)
1488 | @{term "op < :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
1489 | @{term "op <= :: real => _"} $ _ $ _ => lift_SOME (get_denom true) (get_denom true (Thm.dest_arg ct)) (Thm.dest_arg1 ct)
1490 | _ $ _ => lift_SOME (get_denom b) (get_denom b (Thm.dest_fun ct)) (Thm.dest_arg ct)
1494 fun elim_one_denom_tac ctxt =
1495 CSUBGOAL (fn (P,i) =>
1496 case get_denom false P of
1500 val ss = simpset_of ctxt addsimps @{thms field_simps}
1501 addsimps [@{thm nonzero_power_divide}, @{thm power_divide}]
1502 val th = instantiate' [] [SOME d, SOME (Thm.dest_arg P)]
1503 (if ord then @{lemma "(d=0 --> P) & (d>0 --> P) & (d<(0::real) --> P) ==> P" by auto}
1504 else @{lemma "(d=0 --> P) & (d ~= (0::real) --> P) ==> P" by blast})
1505 in (rtac th i THEN Simplifier.asm_full_simp_tac ss i) end);
1507 fun elim_denom_tac ctxt i = REPEAT (elim_one_denom_tac ctxt i);
1509 fun sos_tac prover ctxt = ObjectLogic.full_atomize_tac THEN' elim_denom_tac ctxt THEN' core_sos_tac prover ctxt