src/HOL/Library/positivstellensatz.ML
author haftmann
Wed Oct 21 12:02:56 2009 +0200 (2009-10-21)
changeset 33042 ddf1f03a9ad9
parent 33039 5018f6a76b3f
child 33063 4d462963a7db
permissions -rw-r--r--
curried union as canonical list operation
     1 (* Title:      Library/Sum_Of_Squares/positivstellensatz
     2    Author:     Amine Chaieb, University of Cambridge
     3    Description: A generic arithmetic prover based on Positivstellensatz certificates --- 
     4     also implements Fourrier-Motzkin elimination as a special case Fourrier-Motzkin elimination.
     5 *)
     6 
     7 (* A functor for finite mappings based on Tables *)
     8 
     9 signature FUNC = 
    10 sig
    11  include TABLE
    12  val apply : 'a table -> key -> 'a
    13  val applyd :'a table -> (key -> 'a) -> key -> 'a
    14  val combine : ('a -> 'a -> 'a) -> ('a -> bool) -> 'a table -> 'a table -> 'a table
    15  val dom : 'a table -> key list
    16  val tryapplyd : 'a table -> key -> 'a -> 'a
    17  val updatep : (key * 'a -> bool) -> key * 'a -> 'a table -> 'a table
    18  val choose : 'a table -> key * 'a
    19  val onefunc : key * 'a -> 'a table
    20 end;
    21 
    22 functor FuncFun(Key: KEY) : FUNC=
    23 struct
    24 
    25 structure Tab = Table(Key);
    26 
    27 open Tab;
    28 
    29 fun dom a = sort Key.ord (Tab.keys a);
    30 fun applyd f d x = case Tab.lookup f x of 
    31    SOME y => y
    32  | NONE => d x;
    33 
    34 fun apply f x = applyd f (fn _ => raise Tab.UNDEF x) x;
    35 fun tryapplyd f a d = applyd f (K d) a;
    36 fun updatep p (k,v) t = if p (k, v) then t else update (k,v) t
    37 fun combine f z a b = 
    38  let
    39   fun h (k,v) t = case Tab.lookup t k of
    40      NONE => Tab.update (k,v) t
    41    | SOME v' => let val w = f v v'
    42      in if z w then Tab.delete k t else Tab.update (k,w) t end;
    43   in Tab.fold h a b end;
    44 
    45 fun choose f = case Tab.min_key f of 
    46    SOME k => (k, the (Tab.lookup f k))
    47  | NONE => error "FuncFun.choose : Completely empty function"
    48 
    49 fun onefunc kv = update kv empty
    50 
    51 end;
    52 
    53 (* Some standard functors and utility functions for them *)
    54 
    55 structure FuncUtil =
    56 struct
    57 
    58 structure Intfunc = FuncFun(type key = int val ord = int_ord);
    59 structure Ratfunc = FuncFun(type key = Rat.rat val ord = Rat.ord);
    60 structure Intpairfunc = FuncFun(type key = int*int val ord = prod_ord int_ord int_ord);
    61 structure Symfunc = FuncFun(type key = string val ord = fast_string_ord);
    62 structure Termfunc = FuncFun(type key = term val ord = TermOrd.fast_term_ord);
    63 
    64 val cterm_ord = TermOrd.fast_term_ord o pairself term_of
    65 
    66 structure Ctermfunc = FuncFun(type key = cterm val ord = cterm_ord);
    67 
    68 type monomial = int Ctermfunc.table;
    69 
    70 val monomial_ord = list_ord (prod_ord cterm_ord int_ord) o pairself Ctermfunc.dest
    71 
    72 structure Monomialfunc = FuncFun(type key = monomial val ord = monomial_ord)
    73 
    74 type poly = Rat.rat Monomialfunc.table;
    75 
    76 (* The ordering so we can create canonical HOL polynomials.                  *)
    77 
    78 fun dest_monomial mon = sort (cterm_ord o pairself fst) (Ctermfunc.dest mon);
    79 
    80 fun monomial_order (m1,m2) =
    81  if Ctermfunc.is_empty m2 then LESS 
    82  else if Ctermfunc.is_empty m1 then GREATER 
    83  else
    84   let val mon1 = dest_monomial m1 
    85       val mon2 = dest_monomial m2
    86       val deg1 = fold (Integer.add o snd) mon1 0
    87       val deg2 = fold (Integer.add o snd) mon2 0 
    88   in if deg1 < deg2 then GREATER else if deg1 > deg2 then LESS
    89      else list_ord (prod_ord cterm_ord int_ord) (mon1,mon2)
    90   end;
    91 
    92 end
    93 
    94 (* positivstellensatz datatype and prover generation *)
    95 
    96 signature REAL_ARITH = 
    97 sig
    98   
    99   datatype positivstellensatz =
   100    Axiom_eq of int
   101  | Axiom_le of int
   102  | Axiom_lt of int
   103  | Rational_eq of Rat.rat
   104  | Rational_le of Rat.rat
   105  | Rational_lt of Rat.rat
   106  | Square of FuncUtil.poly
   107  | Eqmul of FuncUtil.poly * positivstellensatz
   108  | Sum of positivstellensatz * positivstellensatz
   109  | Product of positivstellensatz * positivstellensatz;
   110 
   111 datatype pss_tree = Trivial | Cert of positivstellensatz | Branch of pss_tree * pss_tree
   112 
   113 datatype tree_choice = Left | Right
   114 
   115 type prover = tree_choice list -> 
   116   (thm list * thm list * thm list -> positivstellensatz -> thm) ->
   117   thm list * thm list * thm list -> thm * pss_tree
   118 type cert_conv = cterm -> thm * pss_tree
   119 
   120 val gen_gen_real_arith :
   121   Proof.context -> (Rat.rat -> cterm) * conv * conv * conv *
   122    conv * conv * conv * conv * conv * conv * prover -> cert_conv
   123 val real_linear_prover : (thm list * thm list * thm list -> positivstellensatz -> thm) ->
   124   thm list * thm list * thm list -> thm * pss_tree
   125 
   126 val gen_real_arith : Proof.context ->
   127   (Rat.rat -> cterm) * conv * conv * conv * conv * conv * conv * conv * prover -> cert_conv
   128 
   129 val gen_prover_real_arith : Proof.context -> prover -> cert_conv
   130 
   131 val is_ratconst : cterm -> bool
   132 val dest_ratconst : cterm -> Rat.rat
   133 val cterm_of_rat : Rat.rat -> cterm
   134 
   135 end
   136 
   137 structure RealArith : REAL_ARITH =
   138 struct
   139 
   140  open Conv
   141 (* ------------------------------------------------------------------------- *)
   142 (* Data structure for Positivstellensatz refutations.                        *)
   143 (* ------------------------------------------------------------------------- *)
   144 
   145 datatype positivstellensatz =
   146    Axiom_eq of int
   147  | Axiom_le of int
   148  | Axiom_lt of int
   149  | Rational_eq of Rat.rat
   150  | Rational_le of Rat.rat
   151  | Rational_lt of Rat.rat
   152  | Square of FuncUtil.poly
   153  | Eqmul of FuncUtil.poly * positivstellensatz
   154  | Sum of positivstellensatz * positivstellensatz
   155  | Product of positivstellensatz * positivstellensatz;
   156          (* Theorems used in the procedure *)
   157 
   158 datatype pss_tree = Trivial | Cert of positivstellensatz | Branch of pss_tree * pss_tree
   159 datatype tree_choice = Left | Right
   160 type prover = tree_choice list -> 
   161   (thm list * thm list * thm list -> positivstellensatz -> thm) ->
   162   thm list * thm list * thm list -> thm * pss_tree
   163 type cert_conv = cterm -> thm * pss_tree
   164 
   165 val my_eqs = Unsynchronized.ref ([] : thm list);
   166 val my_les = Unsynchronized.ref ([] : thm list);
   167 val my_lts = Unsynchronized.ref ([] : thm list);
   168 val my_proof = Unsynchronized.ref (Axiom_eq 0);
   169 val my_context = Unsynchronized.ref @{context};
   170 
   171 val my_mk_numeric = Unsynchronized.ref ((K @{cterm True}) :Rat.rat -> cterm);
   172 val my_numeric_eq_conv = Unsynchronized.ref no_conv;
   173 val my_numeric_ge_conv = Unsynchronized.ref no_conv;
   174 val my_numeric_gt_conv = Unsynchronized.ref no_conv;
   175 val my_poly_conv = Unsynchronized.ref no_conv;
   176 val my_poly_neg_conv = Unsynchronized.ref no_conv;
   177 val my_poly_add_conv = Unsynchronized.ref no_conv;
   178 val my_poly_mul_conv = Unsynchronized.ref no_conv;
   179 
   180 
   181     (* Some useful derived rules *)
   182 fun deduct_antisym_rule tha thb = 
   183     equal_intr (implies_intr (cprop_of thb) tha) 
   184      (implies_intr (cprop_of tha) thb);
   185 
   186 fun prove_hyp tha thb = 
   187   if exists (curry op aconv (concl_of tha)) (#hyps (rep_thm thb)) 
   188   then equal_elim (symmetric (deduct_antisym_rule tha thb)) tha else thb;
   189 
   190 fun conjunctions th = case try Conjunction.elim th of
   191    SOME (th1,th2) => (conjunctions th1) @ conjunctions th2
   192  | NONE => [th];
   193 
   194 val pth = @{lemma "(((x::real) < y) == (y - x > 0)) &&& ((x <= y) == (y - x >= 0)) 
   195      &&& ((x = y) == (x - y = 0)) &&& ((~(x < y)) == (x - y >= 0)) &&& ((~(x <= y)) == (x - y > 0))
   196      &&& ((~(x = y)) == (x - y > 0 | -(x - y) > 0))"
   197   by (atomize (full), auto simp add: less_diff_eq le_diff_eq not_less)} |> 
   198 conjunctions;
   199 
   200 val pth_final = @{lemma "(~p ==> False) ==> p" by blast}
   201 val pth_add = 
   202  @{lemma "(x = (0::real) ==> y = 0 ==> x + y = 0 ) &&& ( x = 0 ==> y >= 0 ==> x + y >= 0) 
   203     &&& (x = 0 ==> y > 0 ==> x + y > 0) &&& (x >= 0 ==> y = 0 ==> x + y >= 0) 
   204     &&& (x >= 0 ==> y >= 0 ==> x + y >= 0) &&& (x >= 0 ==> y > 0 ==> x + y > 0) 
   205     &&& (x > 0 ==> y = 0 ==> x + y > 0) &&& (x > 0 ==> y >= 0 ==> x + y > 0) 
   206     &&& (x > 0 ==> y > 0 ==> x + y > 0)"  by simp_all} |> conjunctions ;
   207 
   208 val pth_mul = 
   209   @{lemma "(x = (0::real) ==> y = 0 ==> x * y = 0) &&& (x = 0 ==> y >= 0 ==> x * y = 0) &&& 
   210            (x = 0 ==> y > 0 ==> x * y = 0) &&& (x >= 0 ==> y = 0 ==> x * y = 0) &&& 
   211            (x >= 0 ==> y >= 0 ==> x * y >= 0 ) &&& ( x >= 0 ==> y > 0 ==> x * y >= 0 ) &&&
   212            (x > 0 ==>  y = 0 ==> x * y = 0 ) &&& ( x > 0 ==> y >= 0 ==> x * y >= 0 ) &&&
   213            (x > 0 ==>  y > 0 ==> x * y > 0)"
   214   by (auto intro: mult_mono[where a="0::real" and b="x" and d="y" and c="0", simplified]
   215     mult_strict_mono[where b="x" and d="y" and a="0" and c="0", simplified])} |> conjunctions;
   216 
   217 val pth_emul = @{lemma "y = (0::real) ==> x * y = 0"  by simp};
   218 val pth_square = @{lemma "x * x >= (0::real)"  by simp};
   219 
   220 val weak_dnf_simps = List.take (simp_thms, 34) 
   221     @ conjunctions @{lemma "((P & (Q | R)) = ((P&Q) | (P&R))) &&& ((Q | R) & P) = ((Q&P) | (R&P)) &&& (P & Q) = (Q & P) &&& ((P | Q) = (Q | P))" by blast+};
   222 
   223 val nnfD_simps = conjunctions @{lemma "((~(P & Q)) = (~P | ~Q)) &&& ((~(P | Q)) = (~P & ~Q) ) &&& ((P --> Q) = (~P | Q) ) &&& ((P = Q) = ((P & Q) | (~P & ~ Q))) &&& ((~(P = Q)) = ((P & ~ Q) | (~P & Q)) ) &&& ((~ ~(P)) = P)" by blast+}
   224 
   225 val choice_iff = @{lemma "(ALL x. EX y. P x y) = (EX f. ALL x. P x (f x))" by metis};
   226 val prenex_simps = map (fn th => th RS sym) ([@{thm "all_conj_distrib"}, @{thm "ex_disj_distrib"}] @ @{thms "all_simps"(1-4)} @ @{thms "ex_simps"(1-4)});
   227 
   228 val real_abs_thms1 = conjunctions @{lemma
   229   "((-1 * abs(x::real) >= r) = (-1 * x >= r & 1 * x >= r)) &&&
   230   ((-1 * abs(x) + a >= r) = (a + -1 * x >= r & a + 1 * x >= r)) &&&
   231   ((a + -1 * abs(x) >= r) = (a + -1 * x >= r & a + 1 * x >= r)) &&&
   232   ((a + -1 * abs(x) + b >= r) = (a + -1 * x + b >= r & a + 1 * x + b >= r)) &&&
   233   ((a + b + -1 * abs(x) >= r) = (a + b + -1 * x >= r & a + b + 1 * x >= r)) &&&
   234   ((a + b + -1 * abs(x) + c >= r) = (a + b + -1 * x + c >= r & a + b + 1 * x + c >= r)) &&&
   235   ((-1 * max x y >= r) = (-1 * x >= r & -1 * y >= r)) &&&
   236   ((-1 * max x y + a >= r) = (a + -1 * x >= r & a + -1 * y >= r)) &&&
   237   ((a + -1 * max x y >= r) = (a + -1 * x >= r & a + -1 * y >= r)) &&&
   238   ((a + -1 * max x y + b >= r) = (a + -1 * x + b >= r & a + -1 * y  + b >= r)) &&&
   239   ((a + b + -1 * max x y >= r) = (a + b + -1 * x >= r & a + b + -1 * y >= r)) &&&
   240   ((a + b + -1 * max x y + c >= r) = (a + b + -1 * x + c >= r & a + b + -1 * y  + c >= r)) &&&
   241   ((1 * min x y >= r) = (1 * x >= r & 1 * y >= r)) &&&
   242   ((1 * min x y + a >= r) = (a + 1 * x >= r & a + 1 * y >= r)) &&&
   243   ((a + 1 * min x y >= r) = (a + 1 * x >= r & a + 1 * y >= r)) &&&
   244   ((a + 1 * min x y + b >= r) = (a + 1 * x + b >= r & a + 1 * y  + b >= r) )&&&
   245   ((a + b + 1 * min x y >= r) = (a + b + 1 * x >= r & a + b + 1 * y >= r)) &&&
   246   ((a + b + 1 * min x y + c >= r) = (a + b + 1 * x + c >= r & a + b + 1 * y  + c >= r)) &&&
   247   ((min x y >= r) = (x >= r &  y >= r)) &&&
   248   ((min x y + a >= r) = (a + x >= r & a + y >= r)) &&&
   249   ((a + min x y >= r) = (a + x >= r & a + y >= r)) &&&
   250   ((a + min x y + b >= r) = (a + x + b >= r & a + y  + b >= r)) &&&
   251   ((a + b + min x y >= r) = (a + b + x >= r & a + b + y >= r) )&&&
   252   ((a + b + min x y + c >= r) = (a + b + x + c >= r & a + b + y + c >= r)) &&&
   253   ((-1 * abs(x) > r) = (-1 * x > r & 1 * x > r)) &&&
   254   ((-1 * abs(x) + a > r) = (a + -1 * x > r & a + 1 * x > r)) &&&
   255   ((a + -1 * abs(x) > r) = (a + -1 * x > r & a + 1 * x > r)) &&&
   256   ((a + -1 * abs(x) + b > r) = (a + -1 * x + b > r & a + 1 * x + b > r)) &&&
   257   ((a + b + -1 * abs(x) > r) = (a + b + -1 * x > r & a + b + 1 * x > r)) &&&
   258   ((a + b + -1 * abs(x) + c > r) = (a + b + -1 * x + c > r & a + b + 1 * x + c > r)) &&&
   259   ((-1 * max x y > r) = ((-1 * x > r) & -1 * y > r)) &&&
   260   ((-1 * max x y + a > r) = (a + -1 * x > r & a + -1 * y > r)) &&&
   261   ((a + -1 * max x y > r) = (a + -1 * x > r & a + -1 * y > r)) &&&
   262   ((a + -1 * max x y + b > r) = (a + -1 * x + b > r & a + -1 * y  + b > r)) &&&
   263   ((a + b + -1 * max x y > r) = (a + b + -1 * x > r & a + b + -1 * y > r)) &&&
   264   ((a + b + -1 * max x y + c > r) = (a + b + -1 * x + c > r & a + b + -1 * y  + c > r)) &&&
   265   ((min x y > r) = (x > r &  y > r)) &&&
   266   ((min x y + a > r) = (a + x > r & a + y > r)) &&&
   267   ((a + min x y > r) = (a + x > r & a + y > r)) &&&
   268   ((a + min x y + b > r) = (a + x + b > r & a + y  + b > r)) &&&
   269   ((a + b + min x y > r) = (a + b + x > r & a + b + y > r)) &&&
   270   ((a + b + min x y + c > r) = (a + b + x + c > r & a + b + y + c > r))"
   271   by auto};
   272 
   273 val abs_split' = @{lemma "P (abs (x::'a::ordered_idom)) == (x >= 0 & P x | x < 0 & P (-x))"
   274   by (atomize (full)) (auto split add: abs_split)};
   275 
   276 val max_split = @{lemma "P (max x y) == ((x::'a::linorder) <= y & P y | x > y & P x)"
   277   by (atomize (full)) (cases "x <= y", auto simp add: max_def)};
   278 
   279 val min_split = @{lemma "P (min x y) == ((x::'a::linorder) <= y & P x | x > y & P y)"
   280   by (atomize (full)) (cases "x <= y", auto simp add: min_def)};
   281 
   282 
   283          (* Miscalineous *)
   284 fun literals_conv bops uops cv = 
   285  let fun h t =
   286   case (term_of t) of 
   287    b$_$_ => if member (op aconv) bops b then binop_conv h t else cv t
   288  | u$_ => if member (op aconv) uops u then arg_conv h t else cv t
   289  | _ => cv t
   290  in h end;
   291 
   292 fun cterm_of_rat x = 
   293 let val (a, b) = Rat.quotient_of_rat x
   294 in 
   295  if b = 1 then Numeral.mk_cnumber @{ctyp "real"} a
   296   else Thm.capply (Thm.capply @{cterm "op / :: real => _"} 
   297                    (Numeral.mk_cnumber @{ctyp "real"} a))
   298         (Numeral.mk_cnumber @{ctyp "real"} b)
   299 end;
   300 
   301   fun dest_ratconst t = case term_of t of
   302    Const(@{const_name divide}, _)$a$b => Rat.rat_of_quotient(HOLogic.dest_number a |> snd, HOLogic.dest_number b |> snd)
   303  | _ => Rat.rat_of_int (HOLogic.dest_number (term_of t) |> snd)
   304  fun is_ratconst t = can dest_ratconst t
   305 
   306 fun find_term p t = if p t then t else 
   307  case t of
   308   a$b => (find_term p a handle TERM _ => find_term p b)
   309  | Abs (_,_,t') => find_term p t'
   310  | _ => raise TERM ("find_term",[t]);
   311 
   312 fun find_cterm p t = if p t then t else 
   313  case term_of t of
   314   a$b => (find_cterm p (Thm.dest_fun t) handle CTERM _ => find_cterm p (Thm.dest_arg t))
   315  | Abs (_,_,t') => find_cterm p (Thm.dest_abs NONE t |> snd)
   316  | _ => raise CTERM ("find_cterm",[t]);
   317 
   318     (* Some conversions-related stuff which has been forbidden entrance into Pure/conv.ML*)
   319 fun instantiate_cterm' ty tms = Drule.cterm_rule (Drule.instantiate' ty tms)
   320 fun is_comb t = case (term_of t) of _$_ => true | _ => false;
   321 
   322 fun is_binop ct ct' = ct aconvc (Thm.dest_fun (Thm.dest_fun ct'))
   323   handle CTERM _ => false;
   324 
   325 
   326 (* Map back polynomials to HOL.                         *)
   327 
   328 fun cterm_of_varpow x k = if k = 1 then x else Thm.capply (Thm.capply @{cterm "op ^ :: real => _"} x) 
   329   (Numeral.mk_cnumber @{ctyp nat} k)
   330 
   331 fun cterm_of_monomial m = 
   332  if FuncUtil.Ctermfunc.is_empty m then @{cterm "1::real"} 
   333  else 
   334   let 
   335    val m' = FuncUtil.dest_monomial m
   336    val vps = fold_rev (fn (x,k) => cons (cterm_of_varpow x k)) m' [] 
   337   in foldr1 (fn (s, t) => Thm.capply (Thm.capply @{cterm "op * :: real => _"} s) t) vps
   338   end
   339 
   340 fun cterm_of_cmonomial (m,c) = if FuncUtil.Ctermfunc.is_empty m then cterm_of_rat c
   341     else if c = Rat.one then cterm_of_monomial m
   342     else Thm.capply (Thm.capply @{cterm "op *::real => _"} (cterm_of_rat c)) (cterm_of_monomial m);
   343 
   344 fun cterm_of_poly p = 
   345  if FuncUtil.Monomialfunc.is_empty p then @{cterm "0::real"} 
   346  else
   347   let 
   348    val cms = map cterm_of_cmonomial
   349      (sort (prod_ord FuncUtil.monomial_order (K EQUAL)) (FuncUtil.Monomialfunc.dest p))
   350   in foldr1 (fn (t1, t2) => Thm.capply(Thm.capply @{cterm "op + :: real => _"} t1) t2) cms
   351   end;
   352 
   353     (* A general real arithmetic prover *)
   354 
   355 fun gen_gen_real_arith ctxt (mk_numeric,
   356        numeric_eq_conv,numeric_ge_conv,numeric_gt_conv,
   357        poly_conv,poly_neg_conv,poly_add_conv,poly_mul_conv,
   358        absconv1,absconv2,prover) = 
   359 let
   360  val _ = my_context := ctxt 
   361  val _ = (my_mk_numeric := mk_numeric ; my_numeric_eq_conv := numeric_eq_conv ; 
   362           my_numeric_ge_conv := numeric_ge_conv; my_numeric_gt_conv := numeric_gt_conv ;
   363           my_poly_conv := poly_conv; my_poly_neg_conv := poly_neg_conv; 
   364           my_poly_add_conv := poly_add_conv; my_poly_mul_conv := poly_mul_conv)
   365  val pre_ss = HOL_basic_ss addsimps simp_thms@ ex_simps@ all_simps@[@{thm not_all},@{thm not_ex},ex_disj_distrib, all_conj_distrib, @{thm if_bool_eq_disj}]
   366  val prenex_ss = HOL_basic_ss addsimps prenex_simps
   367  val skolemize_ss = HOL_basic_ss addsimps [choice_iff]
   368  val presimp_conv = Simplifier.rewrite (Simplifier.context ctxt pre_ss)
   369  val prenex_conv = Simplifier.rewrite (Simplifier.context ctxt prenex_ss)
   370  val skolemize_conv = Simplifier.rewrite (Simplifier.context ctxt skolemize_ss)
   371  val weak_dnf_ss = HOL_basic_ss addsimps weak_dnf_simps
   372  val weak_dnf_conv = Simplifier.rewrite (Simplifier.context ctxt weak_dnf_ss)
   373  fun eqT_elim th = equal_elim (symmetric th) @{thm TrueI}
   374  fun oprconv cv ct = 
   375   let val g = Thm.dest_fun2 ct
   376   in if g aconvc @{cterm "op <= :: real => _"} 
   377        orelse g aconvc @{cterm "op < :: real => _"} 
   378      then arg_conv cv ct else arg1_conv cv ct
   379   end
   380 
   381  fun real_ineq_conv th ct =
   382   let
   383    val th' = (Thm.instantiate (Thm.match (Thm.lhs_of th, ct)) th 
   384       handle MATCH => raise CTERM ("real_ineq_conv", [ct]))
   385   in transitive th' (oprconv poly_conv (Thm.rhs_of th'))
   386   end 
   387   val [real_lt_conv, real_le_conv, real_eq_conv,
   388        real_not_lt_conv, real_not_le_conv, _] =
   389        map real_ineq_conv pth
   390   fun match_mp_rule ths ths' = 
   391    let
   392      fun f ths ths' = case ths of [] => raise THM("match_mp_rule",0,ths)
   393       | th::ths => (ths' MRS th handle THM _ => f ths ths')
   394    in f ths ths' end
   395   fun mul_rule th th' = fconv_rule (arg_conv (oprconv poly_mul_conv))
   396          (match_mp_rule pth_mul [th, th'])
   397   fun add_rule th th' = fconv_rule (arg_conv (oprconv poly_add_conv))
   398          (match_mp_rule pth_add [th, th'])
   399   fun emul_rule ct th = fconv_rule (arg_conv (oprconv poly_mul_conv)) 
   400        (instantiate' [] [SOME ct] (th RS pth_emul)) 
   401   fun square_rule t = fconv_rule (arg_conv (oprconv poly_conv))
   402        (instantiate' [] [SOME t] pth_square)
   403 
   404   fun hol_of_positivstellensatz(eqs,les,lts) proof =
   405    let 
   406     val _ = (my_eqs := eqs ; my_les := les ; my_lts := lts ; my_proof := proof)
   407     fun translate prf = case prf of
   408         Axiom_eq n => nth eqs n
   409       | Axiom_le n => nth les n
   410       | Axiom_lt n => nth lts n
   411       | Rational_eq x => eqT_elim(numeric_eq_conv(Thm.capply @{cterm Trueprop} 
   412                           (Thm.capply (Thm.capply @{cterm "op =::real => _"} (mk_numeric x)) 
   413                                @{cterm "0::real"})))
   414       | Rational_le x => eqT_elim(numeric_ge_conv(Thm.capply @{cterm Trueprop} 
   415                           (Thm.capply (Thm.capply @{cterm "op <=::real => _"} 
   416                                      @{cterm "0::real"}) (mk_numeric x))))
   417       | Rational_lt x => eqT_elim(numeric_gt_conv(Thm.capply @{cterm Trueprop} 
   418                       (Thm.capply (Thm.capply @{cterm "op <::real => _"} @{cterm "0::real"})
   419                         (mk_numeric x))))
   420       | Square pt => square_rule (cterm_of_poly pt)
   421       | Eqmul(pt,p) => emul_rule (cterm_of_poly pt) (translate p)
   422       | Sum(p1,p2) => add_rule (translate p1) (translate p2)
   423       | Product(p1,p2) => mul_rule (translate p1) (translate p2)
   424    in fconv_rule (first_conv [numeric_ge_conv, numeric_gt_conv, numeric_eq_conv, all_conv]) 
   425           (translate proof)
   426    end
   427   
   428   val init_conv = presimp_conv then_conv
   429       nnf_conv then_conv skolemize_conv then_conv prenex_conv then_conv
   430       weak_dnf_conv
   431 
   432   val concl = Thm.dest_arg o cprop_of
   433   fun is_binop opr ct = (Thm.dest_fun2 ct aconvc opr handle CTERM _ => false)
   434   val is_req = is_binop @{cterm "op =:: real => _"}
   435   val is_ge = is_binop @{cterm "op <=:: real => _"}
   436   val is_gt = is_binop @{cterm "op <:: real => _"}
   437   val is_conj = is_binop @{cterm "op &"}
   438   val is_disj = is_binop @{cterm "op |"}
   439   fun conj_pair th = (th RS @{thm conjunct1}, th RS @{thm conjunct2})
   440   fun disj_cases th th1 th2 = 
   441    let val (p,q) = Thm.dest_binop (concl th)
   442        val c = concl th1
   443        val _ = if c aconvc (concl th2) then () else error "disj_cases : conclusions not alpha convertible"
   444    in implies_elim (implies_elim
   445           (implies_elim (instantiate' [] (map SOME [p,q,c]) @{thm disjE}) th)
   446           (implies_intr (Thm.capply @{cterm Trueprop} p) th1))
   447         (implies_intr (Thm.capply @{cterm Trueprop} q) th2)
   448    end
   449  fun overall cert_choice dun ths = case ths of
   450   [] =>
   451    let 
   452     val (eq,ne) = List.partition (is_req o concl) dun
   453      val (le,nl) = List.partition (is_ge o concl) ne
   454      val lt = filter (is_gt o concl) nl 
   455     in prover (rev cert_choice) hol_of_positivstellensatz (eq,le,lt) end
   456  | th::oths =>
   457    let 
   458     val ct = concl th 
   459    in 
   460     if is_conj ct  then
   461      let 
   462       val (th1,th2) = conj_pair th in
   463       overall cert_choice dun (th1::th2::oths) end
   464     else if is_disj ct then
   465       let 
   466        val (th1, cert1) = overall (Left::cert_choice) dun (assume (Thm.capply @{cterm Trueprop} (Thm.dest_arg1 ct))::oths)
   467        val (th2, cert2) = overall (Right::cert_choice) dun (assume (Thm.capply @{cterm Trueprop} (Thm.dest_arg ct))::oths)
   468       in (disj_cases th th1 th2, Branch (cert1, cert2)) end
   469    else overall cert_choice (th::dun) oths
   470   end
   471   fun dest_binary b ct = if is_binop b ct then Thm.dest_binop ct 
   472                          else raise CTERM ("dest_binary",[b,ct])
   473   val dest_eq = dest_binary @{cterm "op = :: real => _"}
   474   val neq_th = nth pth 5
   475   fun real_not_eq_conv ct = 
   476    let 
   477     val (l,r) = dest_eq (Thm.dest_arg ct)
   478     val th = Thm.instantiate ([],[(@{cpat "?x::real"},l),(@{cpat "?y::real"},r)]) neq_th
   479     val th_p = poly_conv(Thm.dest_arg(Thm.dest_arg1(Thm.rhs_of th)))
   480     val th_x = Drule.arg_cong_rule @{cterm "uminus :: real => _"} th_p
   481     val th_n = fconv_rule (arg_conv poly_neg_conv) th_x
   482     val th' = Drule.binop_cong_rule @{cterm "op |"} 
   483      (Drule.arg_cong_rule (Thm.capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_p)
   484      (Drule.arg_cong_rule (Thm.capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_n)
   485     in transitive th th' 
   486   end
   487  fun equal_implies_1_rule PQ = 
   488   let 
   489    val P = Thm.lhs_of PQ
   490   in implies_intr P (equal_elim PQ (assume P))
   491   end
   492  (* FIXME!!! Copied from groebner.ml *)
   493  val strip_exists =
   494   let fun h (acc, t) =
   495    case (term_of t) of
   496     Const("Ex",_)$Abs(x,T,p) => h (Thm.dest_abs NONE (Thm.dest_arg t) |>> (fn v => v::acc))
   497   | _ => (acc,t)
   498   in fn t => h ([],t)
   499   end
   500   fun name_of x = case term_of x of
   501    Free(s,_) => s
   502  | Var ((s,_),_) => s
   503  | _ => "x"
   504 
   505   fun mk_forall x th = Drule.arg_cong_rule (instantiate_cterm' [SOME (ctyp_of_term x)] [] @{cpat "All :: (?'a => bool) => _" }) (abstract_rule (name_of x) x th)
   506 
   507   val specl = fold_rev (fn x => fn th => instantiate' [] [SOME x] (th RS spec));
   508 
   509  fun ext T = Drule.cterm_rule (instantiate' [SOME T] []) @{cpat Ex}
   510  fun mk_ex v t = Thm.capply (ext (ctyp_of_term v)) (Thm.cabs v t)
   511 
   512  fun choose v th th' = case concl_of th of 
   513    @{term Trueprop} $ (Const("Ex",_)$_) => 
   514     let
   515      val p = (funpow 2 Thm.dest_arg o cprop_of) th
   516      val T = (hd o Thm.dest_ctyp o ctyp_of_term) p
   517      val th0 = fconv_rule (Thm.beta_conversion true)
   518          (instantiate' [SOME T] [SOME p, (SOME o Thm.dest_arg o cprop_of) th'] exE)
   519      val pv = (Thm.rhs_of o Thm.beta_conversion true) 
   520            (Thm.capply @{cterm Trueprop} (Thm.capply p v))
   521      val th1 = forall_intr v (implies_intr pv th')
   522     in implies_elim (implies_elim th0 th) th1  end
   523  | _ => raise THM ("choose",0,[th, th'])
   524 
   525   fun simple_choose v th = 
   526      choose v (assume ((Thm.capply @{cterm Trueprop} o mk_ex v) ((Thm.dest_arg o hd o #hyps o Thm.crep_thm) th))) th
   527 
   528  val strip_forall =
   529   let fun h (acc, t) =
   530    case (term_of t) of
   531     Const("All",_)$Abs(x,T,p) => h (Thm.dest_abs NONE (Thm.dest_arg t) |>> (fn v => v::acc))
   532   | _ => (acc,t)
   533   in fn t => h ([],t)
   534   end
   535 
   536  fun f ct =
   537   let 
   538    val nnf_norm_conv' = 
   539      nnf_conv then_conv 
   540      literals_conv [@{term "op &"}, @{term "op |"}] [] 
   541      (Conv.cache_conv 
   542        (first_conv [real_lt_conv, real_le_conv, 
   543                     real_eq_conv, real_not_lt_conv, 
   544                     real_not_le_conv, real_not_eq_conv, all_conv]))
   545   fun absremover ct = (literals_conv [@{term "op &"}, @{term "op |"}] [] 
   546                   (try_conv (absconv1 then_conv binop_conv (arg_conv poly_conv))) then_conv 
   547         try_conv (absconv2 then_conv nnf_norm_conv' then_conv binop_conv absremover)) ct
   548   val nct = Thm.capply @{cterm Trueprop} (Thm.capply @{cterm "Not"} ct)
   549   val th0 = (init_conv then_conv arg_conv nnf_norm_conv') nct
   550   val tm0 = Thm.dest_arg (Thm.rhs_of th0)
   551   val (th, certificates) = if tm0 aconvc @{cterm False} then (equal_implies_1_rule th0, Trivial) else
   552    let 
   553     val (evs,bod) = strip_exists tm0
   554     val (avs,ibod) = strip_forall bod
   555     val th1 = Drule.arg_cong_rule @{cterm Trueprop} (fold mk_forall avs (absremover ibod))
   556     val (th2, certs) = overall [] [] [specl avs (assume (Thm.rhs_of th1))]
   557     val th3 = fold simple_choose evs (prove_hyp (equal_elim th1 (assume (Thm.capply @{cterm Trueprop} bod))) th2)
   558    in (Drule.implies_intr_hyps (prove_hyp (equal_elim th0 (assume nct)) th3), certs)
   559    end
   560   in (implies_elim (instantiate' [] [SOME ct] pth_final) th, certificates)
   561  end
   562 in f
   563 end;
   564 
   565 (* A linear arithmetic prover *)
   566 local
   567   val linear_add = FuncUtil.Ctermfunc.combine (curry op +/) (fn z => z =/ Rat.zero)
   568   fun linear_cmul c = FuncUtil.Ctermfunc.map (fn x => c */ x)
   569   val one_tm = @{cterm "1::real"}
   570   fun contradictory p (e,_) = ((FuncUtil.Ctermfunc.is_empty e) andalso not(p Rat.zero)) orelse
   571      ((eq_set (op aconvc) (FuncUtil.Ctermfunc.dom e, [one_tm])) andalso
   572        not(p(FuncUtil.Ctermfunc.apply e one_tm)))
   573 
   574   fun linear_ineqs vars (les,lts) = 
   575    case find_first (contradictory (fn x => x >/ Rat.zero)) lts of
   576     SOME r => r
   577   | NONE => 
   578    (case find_first (contradictory (fn x => x >/ Rat.zero)) les of
   579      SOME r => r
   580    | NONE => 
   581      if null vars then error "linear_ineqs: no contradiction" else
   582      let 
   583       val ineqs = les @ lts
   584       fun blowup v =
   585        length(filter (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) ineqs) +
   586        length(filter (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) ineqs) *
   587        length(filter (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero </ Rat.zero) ineqs)
   588       val  v = fst(hd(sort (fn ((_,i),(_,j)) => int_ord (i,j))
   589                  (map (fn v => (v,blowup v)) vars)))
   590       fun addup (e1,p1) (e2,p2) acc =
   591        let 
   592         val c1 = FuncUtil.Ctermfunc.tryapplyd e1 v Rat.zero 
   593         val c2 = FuncUtil.Ctermfunc.tryapplyd e2 v Rat.zero
   594        in if c1 */ c2 >=/ Rat.zero then acc else
   595         let 
   596          val e1' = linear_cmul (Rat.abs c2) e1
   597          val e2' = linear_cmul (Rat.abs c1) e2
   598          val p1' = Product(Rational_lt(Rat.abs c2),p1)
   599          val p2' = Product(Rational_lt(Rat.abs c1),p2)
   600         in (linear_add e1' e2',Sum(p1',p2'))::acc
   601         end
   602        end
   603       val (les0,les1) = 
   604          List.partition (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) les
   605       val (lts0,lts1) = 
   606          List.partition (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) lts
   607       val (lesp,lesn) = 
   608          List.partition (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) les1
   609       val (ltsp,ltsn) = 
   610          List.partition (fn (e,_) => FuncUtil.Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) lts1
   611       val les' = fold_rev (fn ep1 => fold_rev (addup ep1) lesp) lesn les0
   612       val lts' = fold_rev (fn ep1 => fold_rev (addup ep1) (lesp@ltsp)) ltsn
   613                       (fold_rev (fn ep1 => fold_rev (addup ep1) (lesn@ltsn)) ltsp lts0)
   614      in linear_ineqs (remove (op aconvc) v vars) (les',lts')
   615      end)
   616 
   617   fun linear_eqs(eqs,les,lts) = 
   618    case find_first (contradictory (fn x => x =/ Rat.zero)) eqs of
   619     SOME r => r
   620   | NONE => (case eqs of 
   621     [] => 
   622      let val vars = remove (op aconvc) one_tm 
   623            (fold_rev (union (op aconvc) o FuncUtil.Ctermfunc.dom o fst) (les@lts) []) 
   624      in linear_ineqs vars (les,lts) end
   625    | (e,p)::es => 
   626      if FuncUtil.Ctermfunc.is_empty e then linear_eqs (es,les,lts) else
   627      let 
   628       val (x,c) = FuncUtil.Ctermfunc.choose (FuncUtil.Ctermfunc.delete_safe one_tm e)
   629       fun xform (inp as (t,q)) =
   630        let val d = FuncUtil.Ctermfunc.tryapplyd t x Rat.zero in
   631         if d =/ Rat.zero then inp else
   632         let 
   633          val k = (Rat.neg d) */ Rat.abs c // c
   634          val e' = linear_cmul k e
   635          val t' = linear_cmul (Rat.abs c) t
   636          val p' = Eqmul(FuncUtil.Monomialfunc.onefunc (FuncUtil.Ctermfunc.empty, k),p)
   637          val q' = Product(Rational_lt(Rat.abs c),q) 
   638         in (linear_add e' t',Sum(p',q')) 
   639         end 
   640       end
   641      in linear_eqs(map xform es,map xform les,map xform lts)
   642      end)
   643 
   644   fun linear_prover (eq,le,lt) = 
   645    let 
   646     val eqs = map2 (fn p => fn n => (p,Axiom_eq n)) eq (0 upto (length eq - 1))
   647     val les = map2 (fn p => fn n => (p,Axiom_le n)) le (0 upto (length le - 1))
   648     val lts = map2 (fn p => fn n => (p,Axiom_lt n)) lt (0 upto (length lt - 1))
   649    in linear_eqs(eqs,les,lts)
   650    end 
   651   
   652   fun lin_of_hol ct = 
   653    if ct aconvc @{cterm "0::real"} then FuncUtil.Ctermfunc.empty
   654    else if not (is_comb ct) then FuncUtil.Ctermfunc.onefunc (ct, Rat.one)
   655    else if is_ratconst ct then FuncUtil.Ctermfunc.onefunc (one_tm, dest_ratconst ct)
   656    else
   657     let val (lop,r) = Thm.dest_comb ct 
   658     in if not (is_comb lop) then FuncUtil.Ctermfunc.onefunc (ct, Rat.one)
   659        else
   660         let val (opr,l) = Thm.dest_comb lop 
   661         in if opr aconvc @{cterm "op + :: real =>_"} 
   662            then linear_add (lin_of_hol l) (lin_of_hol r)
   663            else if opr aconvc @{cterm "op * :: real =>_"} 
   664                    andalso is_ratconst l then FuncUtil.Ctermfunc.onefunc (r, dest_ratconst l)
   665            else FuncUtil.Ctermfunc.onefunc (ct, Rat.one)
   666         end
   667     end
   668 
   669   fun is_alien ct = case term_of ct of 
   670    Const(@{const_name "real"}, _)$ n => 
   671      if can HOLogic.dest_number n then false else true
   672   | _ => false
   673 in 
   674 fun real_linear_prover translator (eq,le,lt) = 
   675  let 
   676   val lhs = lin_of_hol o Thm.dest_arg1 o Thm.dest_arg o cprop_of
   677   val rhs = lin_of_hol o Thm.dest_arg o Thm.dest_arg o cprop_of
   678   val eq_pols = map lhs eq
   679   val le_pols = map rhs le
   680   val lt_pols = map rhs lt 
   681   val aliens =  filter is_alien
   682       (fold_rev (union (op aconvc) o FuncUtil.Ctermfunc.dom) 
   683           (eq_pols @ le_pols @ lt_pols) [])
   684   val le_pols' = le_pols @ map (fn v => FuncUtil.Ctermfunc.onefunc (v,Rat.one)) aliens
   685   val (_,proof) = linear_prover (eq_pols,le_pols',lt_pols)
   686   val le' = le @ map (fn a => instantiate' [] [SOME (Thm.dest_arg a)] @{thm real_of_nat_ge_zero}) aliens 
   687  in ((translator (eq,le',lt) proof), Trivial)
   688  end
   689 end;
   690 
   691 (* A less general generic arithmetic prover dealing with abs,max and min*)
   692 
   693 local
   694  val absmaxmin_elim_ss1 = HOL_basic_ss addsimps real_abs_thms1
   695  fun absmaxmin_elim_conv1 ctxt = 
   696     Simplifier.rewrite (Simplifier.context ctxt absmaxmin_elim_ss1)
   697 
   698  val absmaxmin_elim_conv2 =
   699   let 
   700    val pth_abs = instantiate' [SOME @{ctyp real}] [] abs_split'
   701    val pth_max = instantiate' [SOME @{ctyp real}] [] max_split
   702    val pth_min = instantiate' [SOME @{ctyp real}] [] min_split
   703    val abs_tm = @{cterm "abs :: real => _"}
   704    val p_tm = @{cpat "?P :: real => bool"}
   705    val x_tm = @{cpat "?x :: real"}
   706    val y_tm = @{cpat "?y::real"}
   707    val is_max = is_binop @{cterm "max :: real => _"}
   708    val is_min = is_binop @{cterm "min :: real => _"} 
   709    fun is_abs t = is_comb t andalso Thm.dest_fun t aconvc abs_tm
   710    fun eliminate_construct p c tm =
   711     let 
   712      val t = find_cterm p tm
   713      val th0 = (symmetric o beta_conversion false) (Thm.capply (Thm.cabs t tm) t)
   714      val (p,ax) = (Thm.dest_comb o Thm.rhs_of) th0
   715     in fconv_rule(arg_conv(binop_conv (arg_conv (beta_conversion false))))
   716                (transitive th0 (c p ax))
   717    end
   718 
   719    val elim_abs = eliminate_construct is_abs
   720     (fn p => fn ax => 
   721        Thm.instantiate ([], [(p_tm,p), (x_tm, Thm.dest_arg ax)]) pth_abs)
   722    val elim_max = eliminate_construct is_max
   723     (fn p => fn ax => 
   724       let val (ax,y) = Thm.dest_comb ax 
   725       in  Thm.instantiate ([], [(p_tm,p), (x_tm, Thm.dest_arg ax), (y_tm,y)]) 
   726       pth_max end)
   727    val elim_min = eliminate_construct is_min
   728     (fn p => fn ax => 
   729       let val (ax,y) = Thm.dest_comb ax 
   730       in  Thm.instantiate ([], [(p_tm,p), (x_tm, Thm.dest_arg ax), (y_tm,y)]) 
   731       pth_min end)
   732    in first_conv [elim_abs, elim_max, elim_min, all_conv]
   733   end;
   734 in fun gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,prover) =
   735         gen_gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,
   736                        absmaxmin_elim_conv1 ctxt,absmaxmin_elim_conv2,prover)
   737 end;
   738 
   739 (* An instance for reals*) 
   740 
   741 fun gen_prover_real_arith ctxt prover = 
   742  let
   743   fun simple_cterm_ord t u = TermOrd.term_ord (term_of t, term_of u) = LESS
   744   val {add,mul,neg,pow,sub,main} = 
   745      Normalizer.semiring_normalizers_ord_wrapper ctxt
   746       (the (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
   747      simple_cterm_ord
   748 in gen_real_arith ctxt
   749    (cterm_of_rat, field_comp_conv, field_comp_conv,field_comp_conv,
   750     main,neg,add,mul, prover)
   751 end;
   752 
   753 end