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