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