src/HOL/Library/positivstellensatz.ML
author Philipp Meyer
Tue Sep 22 11:26:46 2009 +0200 (2009-09-22)
changeset 32646 962b4354ed90
parent 32645 1cc5b24f5a01
child 32740 9dd0a2f83429
permissions -rw-r--r--
used standard fold function and type aliases
     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 Thm FuncUtil;;
   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 = ref ([] : thm list);
   194 val my_les = ref ([] : thm list);
   195 val my_lts = ref ([] : thm list);
   196 val my_proof = ref (Axiom_eq 0);
   197 val my_context = ref @{context};
   198 
   199 val my_mk_numeric = ref ((K @{cterm True}) :Rat.rat -> cterm);
   200 val my_numeric_eq_conv = ref no_conv;
   201 val my_numeric_ge_conv = ref no_conv;
   202 val my_numeric_gt_conv = ref no_conv;
   203 val my_poly_conv = ref no_conv;
   204 val my_poly_neg_conv = ref no_conv;
   205 val my_poly_add_conv = ref no_conv;
   206 val my_poly_mul_conv = 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 local
   357  open Thm Numeral
   358 in
   359 
   360 fun cterm_of_varpow x k = if k = 1 then x else capply (capply @{cterm "op ^ :: real => _"} x) 
   361   (mk_cnumber @{ctyp nat} k)
   362 
   363 fun cterm_of_monomial m = 
   364  if Ctermfunc.is_undefined m then @{cterm "1::real"} 
   365  else 
   366   let 
   367    val m' = dest_monomial m
   368    val vps = fold_rev (fn (x,k) => cons (cterm_of_varpow x k)) m' [] 
   369   in foldr1 (fn (s, t) => capply (capply @{cterm "op * :: real => _"} s) t) vps
   370   end
   371 
   372 fun cterm_of_cmonomial (m,c) = if Ctermfunc.is_undefined m then cterm_of_rat c
   373     else if c = Rat.one then cterm_of_monomial m
   374     else capply (capply @{cterm "op *::real => _"} (cterm_of_rat c)) (cterm_of_monomial m);
   375 
   376 fun cterm_of_poly p = 
   377  if Monomialfunc.is_undefined p then @{cterm "0::real"} 
   378  else
   379   let 
   380    val cms = map cterm_of_cmonomial
   381      (sort (prod_ord monomial_order (K EQUAL)) (Monomialfunc.graph p))
   382   in foldr1 (fn (t1, t2) => capply(capply @{cterm "op + :: real => _"} t1) t2) cms
   383   end;
   384 
   385 end;
   386     (* A general real arithmetic prover *)
   387 
   388 fun gen_gen_real_arith ctxt (mk_numeric,
   389        numeric_eq_conv,numeric_ge_conv,numeric_gt_conv,
   390        poly_conv,poly_neg_conv,poly_add_conv,poly_mul_conv,
   391        absconv1,absconv2,prover) = 
   392 let
   393  open Conv Thm;
   394  val _ = my_context := ctxt 
   395  val _ = (my_mk_numeric := mk_numeric ; my_numeric_eq_conv := numeric_eq_conv ; 
   396           my_numeric_ge_conv := numeric_ge_conv; my_numeric_gt_conv := numeric_gt_conv ;
   397           my_poly_conv := poly_conv; my_poly_neg_conv := poly_neg_conv; 
   398           my_poly_add_conv := poly_add_conv; my_poly_mul_conv := poly_mul_conv)
   399  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}]
   400  val prenex_ss = HOL_basic_ss addsimps prenex_simps
   401  val skolemize_ss = HOL_basic_ss addsimps [choice_iff]
   402  val presimp_conv = Simplifier.rewrite (Simplifier.context ctxt pre_ss)
   403  val prenex_conv = Simplifier.rewrite (Simplifier.context ctxt prenex_ss)
   404  val skolemize_conv = Simplifier.rewrite (Simplifier.context ctxt skolemize_ss)
   405  val weak_dnf_ss = HOL_basic_ss addsimps weak_dnf_simps
   406  val weak_dnf_conv = Simplifier.rewrite (Simplifier.context ctxt weak_dnf_ss)
   407  fun eqT_elim th = equal_elim (symmetric th) @{thm TrueI}
   408  fun oprconv cv ct = 
   409   let val g = Thm.dest_fun2 ct
   410   in if g aconvc @{cterm "op <= :: real => _"} 
   411        orelse g aconvc @{cterm "op < :: real => _"} 
   412      then arg_conv cv ct else arg1_conv cv ct
   413   end
   414 
   415  fun real_ineq_conv th ct =
   416   let
   417    val th' = (instantiate (match (lhs_of th, ct)) th 
   418       handle MATCH => raise CTERM ("real_ineq_conv", [ct]))
   419   in transitive th' (oprconv poly_conv (Thm.rhs_of th'))
   420   end 
   421   val [real_lt_conv, real_le_conv, real_eq_conv,
   422        real_not_lt_conv, real_not_le_conv, _] =
   423        map real_ineq_conv pth
   424   fun match_mp_rule ths ths' = 
   425    let
   426      fun f ths ths' = case ths of [] => raise THM("match_mp_rule",0,ths)
   427       | th::ths => (ths' MRS th handle THM _ => f ths ths')
   428    in f ths ths' end
   429   fun mul_rule th th' = fconv_rule (arg_conv (oprconv poly_mul_conv))
   430          (match_mp_rule pth_mul [th, th'])
   431   fun add_rule th th' = fconv_rule (arg_conv (oprconv poly_add_conv))
   432          (match_mp_rule pth_add [th, th'])
   433   fun emul_rule ct th = fconv_rule (arg_conv (oprconv poly_mul_conv)) 
   434        (instantiate' [] [SOME ct] (th RS pth_emul)) 
   435   fun square_rule t = fconv_rule (arg_conv (oprconv poly_conv))
   436        (instantiate' [] [SOME t] pth_square)
   437 
   438   fun hol_of_positivstellensatz(eqs,les,lts) proof =
   439    let 
   440     val _ = (my_eqs := eqs ; my_les := les ; my_lts := lts ; my_proof := proof)
   441     fun translate prf = case prf of
   442         Axiom_eq n => nth eqs n
   443       | Axiom_le n => nth les n
   444       | Axiom_lt n => nth lts n
   445       | Rational_eq x => eqT_elim(numeric_eq_conv(capply @{cterm Trueprop} 
   446                           (capply (capply @{cterm "op =::real => _"} (mk_numeric x)) 
   447                                @{cterm "0::real"})))
   448       | Rational_le x => eqT_elim(numeric_ge_conv(capply @{cterm Trueprop} 
   449                           (capply (capply @{cterm "op <=::real => _"} 
   450                                      @{cterm "0::real"}) (mk_numeric x))))
   451       | Rational_lt x => eqT_elim(numeric_gt_conv(capply @{cterm Trueprop} 
   452                       (capply (capply @{cterm "op <::real => _"} @{cterm "0::real"})
   453                         (mk_numeric x))))
   454       | Square pt => square_rule (cterm_of_poly pt)
   455       | Eqmul(pt,p) => emul_rule (cterm_of_poly pt) (translate p)
   456       | Sum(p1,p2) => add_rule (translate p1) (translate p2)
   457       | Product(p1,p2) => mul_rule (translate p1) (translate p2)
   458    in fconv_rule (first_conv [numeric_ge_conv, numeric_gt_conv, numeric_eq_conv, all_conv]) 
   459           (translate proof)
   460    end
   461   
   462   val init_conv = presimp_conv then_conv
   463       nnf_conv then_conv skolemize_conv then_conv prenex_conv then_conv
   464       weak_dnf_conv
   465 
   466   val concl = dest_arg o cprop_of
   467   fun is_binop opr ct = (dest_fun2 ct aconvc opr handle CTERM _ => false)
   468   val is_req = is_binop @{cterm "op =:: real => _"}
   469   val is_ge = is_binop @{cterm "op <=:: real => _"}
   470   val is_gt = is_binop @{cterm "op <:: real => _"}
   471   val is_conj = is_binop @{cterm "op &"}
   472   val is_disj = is_binop @{cterm "op |"}
   473   fun conj_pair th = (th RS @{thm conjunct1}, th RS @{thm conjunct2})
   474   fun disj_cases th th1 th2 = 
   475    let val (p,q) = dest_binop (concl th)
   476        val c = concl th1
   477        val _ = if c aconvc (concl th2) then () else error "disj_cases : conclusions not alpha convertible"
   478    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)
   479    end
   480  fun overall cert_choice dun ths = case ths of
   481   [] =>
   482    let 
   483     val (eq,ne) = List.partition (is_req o concl) dun
   484      val (le,nl) = List.partition (is_ge o concl) ne
   485      val lt = filter (is_gt o concl) nl 
   486     in prover (rev cert_choice) hol_of_positivstellensatz (eq,le,lt) end
   487  | th::oths =>
   488    let 
   489     val ct = concl th 
   490    in 
   491     if is_conj ct  then
   492      let 
   493       val (th1,th2) = conj_pair th in
   494       overall cert_choice dun (th1::th2::oths) end
   495     else if is_disj ct then
   496       let 
   497        val (th1, cert1) = overall (Left::cert_choice) dun (assume (capply @{cterm Trueprop} (dest_arg1 ct))::oths)
   498        val (th2, cert2) = overall (Right::cert_choice) dun (assume (capply @{cterm Trueprop} (dest_arg ct))::oths)
   499       in (disj_cases th th1 th2, Branch (cert1, cert2)) end
   500    else overall cert_choice (th::dun) oths
   501   end
   502   fun dest_binary b ct = if is_binop b ct then dest_binop ct 
   503                          else raise CTERM ("dest_binary",[b,ct])
   504   val dest_eq = dest_binary @{cterm "op = :: real => _"}
   505   val neq_th = nth pth 5
   506   fun real_not_eq_conv ct = 
   507    let 
   508     val (l,r) = dest_eq (dest_arg ct)
   509     val th = instantiate ([],[(@{cpat "?x::real"},l),(@{cpat "?y::real"},r)]) neq_th
   510     val th_p = poly_conv(dest_arg(dest_arg1(rhs_of th)))
   511     val th_x = Drule.arg_cong_rule @{cterm "uminus :: real => _"} th_p
   512     val th_n = fconv_rule (arg_conv poly_neg_conv) th_x
   513     val th' = Drule.binop_cong_rule @{cterm "op |"} 
   514      (Drule.arg_cong_rule (capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_p)
   515      (Drule.arg_cong_rule (capply @{cterm "op <::real=>_"} @{cterm "0::real"}) th_n)
   516     in transitive th th' 
   517   end
   518  fun equal_implies_1_rule PQ = 
   519   let 
   520    val P = lhs_of PQ
   521   in implies_intr P (equal_elim PQ (assume P))
   522   end
   523  (* FIXME!!! Copied from groebner.ml *)
   524  val strip_exists =
   525   let fun h (acc, t) =
   526    case (term_of t) of
   527     Const("Ex",_)$Abs(x,T,p) => h (dest_abs NONE (dest_arg t) |>> (fn v => v::acc))
   528   | _ => (acc,t)
   529   in fn t => h ([],t)
   530   end
   531   fun name_of x = case term_of x of
   532    Free(s,_) => s
   533  | Var ((s,_),_) => s
   534  | _ => "x"
   535 
   536   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)
   537 
   538   val specl = fold_rev (fn x => fn th => instantiate' [] [SOME x] (th RS spec));
   539 
   540  fun ext T = Drule.cterm_rule (instantiate' [SOME T] []) @{cpat Ex}
   541  fun mk_ex v t = Thm.capply (ext (ctyp_of_term v)) (Thm.cabs v t)
   542 
   543  fun choose v th th' = case concl_of th of 
   544    @{term Trueprop} $ (Const("Ex",_)$_) => 
   545     let
   546      val p = (funpow 2 Thm.dest_arg o cprop_of) th
   547      val T = (hd o Thm.dest_ctyp o ctyp_of_term) p
   548      val th0 = fconv_rule (Thm.beta_conversion true)
   549          (instantiate' [SOME T] [SOME p, (SOME o Thm.dest_arg o cprop_of) th'] exE)
   550      val pv = (Thm.rhs_of o Thm.beta_conversion true) 
   551            (Thm.capply @{cterm Trueprop} (Thm.capply p v))
   552      val th1 = forall_intr v (implies_intr pv th')
   553     in implies_elim (implies_elim th0 th) th1  end
   554  | _ => raise THM ("choose",0,[th, th'])
   555 
   556   fun simple_choose v th = 
   557      choose v (assume ((Thm.capply @{cterm Trueprop} o mk_ex v) ((Thm.dest_arg o hd o #hyps o Thm.crep_thm) th))) th
   558 
   559  val strip_forall =
   560   let fun h (acc, t) =
   561    case (term_of t) of
   562     Const("All",_)$Abs(x,T,p) => h (dest_abs NONE (dest_arg t) |>> (fn v => v::acc))
   563   | _ => (acc,t)
   564   in fn t => h ([],t)
   565   end
   566 
   567  fun f ct =
   568   let 
   569    val nnf_norm_conv' = 
   570      nnf_conv then_conv 
   571      literals_conv [@{term "op &"}, @{term "op |"}] [] 
   572      (More_Conv.cache_conv 
   573        (first_conv [real_lt_conv, real_le_conv, 
   574                     real_eq_conv, real_not_lt_conv, 
   575                     real_not_le_conv, real_not_eq_conv, all_conv]))
   576   fun absremover ct = (literals_conv [@{term "op &"}, @{term "op |"}] [] 
   577                   (try_conv (absconv1 then_conv binop_conv (arg_conv poly_conv))) then_conv 
   578         try_conv (absconv2 then_conv nnf_norm_conv' then_conv binop_conv absremover)) ct
   579   val nct = capply @{cterm Trueprop} (capply @{cterm "Not"} ct)
   580   val th0 = (init_conv then_conv arg_conv nnf_norm_conv') nct
   581   val tm0 = dest_arg (rhs_of th0)
   582   val (th, certificates) = if tm0 aconvc @{cterm False} then (equal_implies_1_rule th0, Trivial) else
   583    let 
   584     val (evs,bod) = strip_exists tm0
   585     val (avs,ibod) = strip_forall bod
   586     val th1 = Drule.arg_cong_rule @{cterm Trueprop} (fold mk_forall avs (absremover ibod))
   587     val (th2, certs) = overall [] [] [specl avs (assume (rhs_of th1))]
   588     val th3 = fold simple_choose evs (prove_hyp (equal_elim th1 (assume (capply @{cterm Trueprop} bod))) th2)
   589    in (Drule.implies_intr_hyps (prove_hyp (equal_elim th0 (assume nct)) th3), certs)
   590    end
   591   in (implies_elim (instantiate' [] [SOME ct] pth_final) th, certificates)
   592  end
   593 in f
   594 end;
   595 
   596 (* A linear arithmetic prover *)
   597 local
   598   val linear_add = Ctermfunc.combine (curry op +/) (fn z => z =/ Rat.zero)
   599   fun linear_cmul c = Ctermfunc.mapf (fn x => c */ x)
   600   val one_tm = @{cterm "1::real"}
   601   fun contradictory p (e,_) = ((Ctermfunc.is_undefined e) andalso not(p Rat.zero)) orelse
   602      ((gen_eq_set (op aconvc) (Ctermfunc.dom e, [one_tm])) andalso not(p(Ctermfunc.apply e one_tm)))
   603 
   604   fun linear_ineqs vars (les,lts) = 
   605    case find_first (contradictory (fn x => x >/ Rat.zero)) lts of
   606     SOME r => r
   607   | NONE => 
   608    (case find_first (contradictory (fn x => x >/ Rat.zero)) les of
   609      SOME r => r
   610    | NONE => 
   611      if null vars then error "linear_ineqs: no contradiction" else
   612      let 
   613       val ineqs = les @ lts
   614       fun blowup v =
   615        length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) ineqs) +
   616        length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) ineqs) *
   617        length(filter (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero </ Rat.zero) ineqs)
   618       val  v = fst(hd(sort (fn ((_,i),(_,j)) => int_ord (i,j))
   619                  (map (fn v => (v,blowup v)) vars)))
   620       fun addup (e1,p1) (e2,p2) acc =
   621        let 
   622         val c1 = Ctermfunc.tryapplyd e1 v Rat.zero 
   623         val c2 = Ctermfunc.tryapplyd e2 v Rat.zero
   624        in if c1 */ c2 >=/ Rat.zero then acc else
   625         let 
   626          val e1' = linear_cmul (Rat.abs c2) e1
   627          val e2' = linear_cmul (Rat.abs c1) e2
   628          val p1' = Product(Rational_lt(Rat.abs c2),p1)
   629          val p2' = Product(Rational_lt(Rat.abs c1),p2)
   630         in (linear_add e1' e2',Sum(p1',p2'))::acc
   631         end
   632        end
   633       val (les0,les1) = 
   634          List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) les
   635       val (lts0,lts1) = 
   636          List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero =/ Rat.zero) lts
   637       val (lesp,lesn) = 
   638          List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) les1
   639       val (ltsp,ltsn) = 
   640          List.partition (fn (e,_) => Ctermfunc.tryapplyd e v Rat.zero >/ Rat.zero) lts1
   641       val les' = fold_rev (fn ep1 => fold_rev (addup ep1) lesp) lesn les0
   642       val lts' = fold_rev (fn ep1 => fold_rev (addup ep1) (lesp@ltsp)) ltsn
   643                       (fold_rev (fn ep1 => fold_rev (addup ep1) (lesn@ltsn)) ltsp lts0)
   644      in linear_ineqs (remove (op aconvc) v vars) (les',lts')
   645      end)
   646 
   647   fun linear_eqs(eqs,les,lts) = 
   648    case find_first (contradictory (fn x => x =/ Rat.zero)) eqs of
   649     SOME r => r
   650   | NONE => (case eqs of 
   651     [] => 
   652      let val vars = remove (op aconvc) one_tm 
   653            (fold_rev (curry (gen_union (op aconvc)) o Ctermfunc.dom o fst) (les@lts) []) 
   654      in linear_ineqs vars (les,lts) end
   655    | (e,p)::es => 
   656      if Ctermfunc.is_undefined e then linear_eqs (es,les,lts) else
   657      let 
   658       val (x,c) = Ctermfunc.choose (Ctermfunc.undefine one_tm e)
   659       fun xform (inp as (t,q)) =
   660        let val d = Ctermfunc.tryapplyd t x Rat.zero in
   661         if d =/ Rat.zero then inp else
   662         let 
   663          val k = (Rat.neg d) */ Rat.abs c // c
   664          val e' = linear_cmul k e
   665          val t' = linear_cmul (Rat.abs c) t
   666          val p' = Eqmul(Monomialfunc.onefunc (Ctermfunc.undefined, k),p)
   667          val q' = Product(Rational_lt(Rat.abs c),q) 
   668         in (linear_add e' t',Sum(p',q')) 
   669         end 
   670       end
   671      in linear_eqs(map xform es,map xform les,map xform lts)
   672      end)
   673 
   674   fun linear_prover (eq,le,lt) = 
   675    let 
   676     val eqs = map2 (fn p => fn n => (p,Axiom_eq n)) eq (0 upto (length eq - 1))
   677     val les = map2 (fn p => fn n => (p,Axiom_le n)) le (0 upto (length le - 1))
   678     val lts = map2 (fn p => fn n => (p,Axiom_lt n)) lt (0 upto (length lt - 1))
   679    in linear_eqs(eqs,les,lts)
   680    end 
   681   
   682   fun lin_of_hol ct = 
   683    if ct aconvc @{cterm "0::real"} then Ctermfunc.undefined
   684    else if not (is_comb ct) then Ctermfunc.onefunc (ct, Rat.one)
   685    else if is_ratconst ct then Ctermfunc.onefunc (one_tm, dest_ratconst ct)
   686    else
   687     let val (lop,r) = Thm.dest_comb ct 
   688     in if not (is_comb lop) then Ctermfunc.onefunc (ct, Rat.one)
   689        else
   690         let val (opr,l) = Thm.dest_comb lop 
   691         in if opr aconvc @{cterm "op + :: real =>_"} 
   692            then linear_add (lin_of_hol l) (lin_of_hol r)
   693            else if opr aconvc @{cterm "op * :: real =>_"} 
   694                    andalso is_ratconst l then Ctermfunc.onefunc (r, dest_ratconst l)
   695            else Ctermfunc.onefunc (ct, Rat.one)
   696         end
   697     end
   698 
   699   fun is_alien ct = case term_of ct of 
   700    Const(@{const_name "real"}, _)$ n => 
   701      if can HOLogic.dest_number n then false else true
   702   | _ => false
   703  open Thm
   704 in 
   705 fun real_linear_prover translator (eq,le,lt) = 
   706  let 
   707   val lhs = lin_of_hol o dest_arg1 o dest_arg o cprop_of
   708   val rhs = lin_of_hol o dest_arg o dest_arg o cprop_of
   709   val eq_pols = map lhs eq
   710   val le_pols = map rhs le
   711   val lt_pols = map rhs lt 
   712   val aliens =  filter is_alien
   713       (fold_rev (curry (gen_union (op aconvc)) o Ctermfunc.dom) 
   714           (eq_pols @ le_pols @ lt_pols) [])
   715   val le_pols' = le_pols @ map (fn v => Ctermfunc.onefunc (v,Rat.one)) aliens
   716   val (_,proof) = linear_prover (eq_pols,le_pols',lt_pols)
   717   val le' = le @ map (fn a => instantiate' [] [SOME (dest_arg a)] @{thm real_of_nat_ge_zero}) aliens 
   718  in ((translator (eq,le',lt) proof), Trivial)
   719  end
   720 end;
   721 
   722 (* A less general generic arithmetic prover dealing with abs,max and min*)
   723 
   724 local
   725  val absmaxmin_elim_ss1 = HOL_basic_ss addsimps real_abs_thms1
   726  fun absmaxmin_elim_conv1 ctxt = 
   727     Simplifier.rewrite (Simplifier.context ctxt absmaxmin_elim_ss1)
   728 
   729  val absmaxmin_elim_conv2 =
   730   let 
   731    val pth_abs = instantiate' [SOME @{ctyp real}] [] abs_split'
   732    val pth_max = instantiate' [SOME @{ctyp real}] [] max_split
   733    val pth_min = instantiate' [SOME @{ctyp real}] [] min_split
   734    val abs_tm = @{cterm "abs :: real => _"}
   735    val p_tm = @{cpat "?P :: real => bool"}
   736    val x_tm = @{cpat "?x :: real"}
   737    val y_tm = @{cpat "?y::real"}
   738    val is_max = is_binop @{cterm "max :: real => _"}
   739    val is_min = is_binop @{cterm "min :: real => _"} 
   740    fun is_abs t = is_comb t andalso dest_fun t aconvc abs_tm
   741    fun eliminate_construct p c tm =
   742     let 
   743      val t = find_cterm p tm
   744      val th0 = (symmetric o beta_conversion false) (capply (cabs t tm) t)
   745      val (p,ax) = (dest_comb o rhs_of) th0
   746     in fconv_rule(arg_conv(binop_conv (arg_conv (beta_conversion false))))
   747                (transitive th0 (c p ax))
   748    end
   749 
   750    val elim_abs = eliminate_construct is_abs
   751     (fn p => fn ax => 
   752        instantiate ([], [(p_tm,p), (x_tm, dest_arg ax)]) pth_abs)
   753    val elim_max = eliminate_construct is_max
   754     (fn p => fn ax => 
   755       let val (ax,y) = dest_comb ax 
   756       in  instantiate ([], [(p_tm,p), (x_tm, dest_arg ax), (y_tm,y)]) 
   757       pth_max end)
   758    val elim_min = eliminate_construct is_min
   759     (fn p => fn ax => 
   760       let val (ax,y) = dest_comb ax 
   761       in  instantiate ([], [(p_tm,p), (x_tm, dest_arg ax), (y_tm,y)]) 
   762       pth_min end)
   763    in first_conv [elim_abs, elim_max, elim_min, all_conv]
   764   end;
   765 in fun gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,prover) =
   766         gen_gen_real_arith ctxt (mkconst,eq,ge,gt,norm,neg,add,mul,
   767                        absmaxmin_elim_conv1 ctxt,absmaxmin_elim_conv2,prover)
   768 end;
   769 
   770 (* An instance for reals*) 
   771 
   772 fun gen_prover_real_arith ctxt prover = 
   773  let
   774   fun simple_cterm_ord t u = TermOrd.term_ord (term_of t, term_of u) = LESS
   775   val {add,mul,neg,pow,sub,main} = 
   776      Normalizer.semiring_normalizers_ord_wrapper ctxt
   777       (valOf (NormalizerData.match ctxt @{cterm "(0::real) + 1"})) 
   778      simple_cterm_ord
   779 in gen_real_arith ctxt
   780    (cterm_of_rat, field_comp_conv, field_comp_conv,field_comp_conv,
   781     main,neg,add,mul, prover)
   782 end;
   783 
   784 end