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