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