src/HOL/Tools/Groebner_Basis/groebner.ML
author wenzelm
Sun Mar 07 12:19:47 2010 +0100 (2010-03-07)
changeset 35625 9c818cab0dd0
parent 35410 1ea89d2a1bd4
child 36700 9b85b9d74b83
permissions -rw-r--r--
modernized structure Object_Logic;
     1 (*  Title:      HOL/Tools/Groebner_Basis/groebner.ML
     2     Author:     Amine Chaieb, TU Muenchen
     3 *)
     4 
     5 signature GROEBNER =
     6 sig
     7   val ring_and_ideal_conv :
     8     {idom: thm list, ring: cterm list * thm list, field: cterm list * thm list,
     9      vars: cterm list, semiring: cterm list * thm list, ideal : thm list} ->
    10     (cterm -> Rat.rat) -> (Rat.rat -> cterm) ->
    11     conv ->  conv ->
    12  {ring_conv : conv, 
    13  simple_ideal: (cterm list -> cterm -> (cterm * cterm -> order) -> cterm list),
    14  multi_ideal: cterm list -> cterm list -> cterm list -> (cterm * cterm) list,
    15  poly_eq_ss: simpset, unwind_conv : conv}
    16     val ring_tac: thm list -> thm list -> Proof.context -> int -> tactic
    17     val ideal_tac: thm list -> thm list -> Proof.context -> int -> tactic
    18     val algebra_tac: thm list -> thm list -> Proof.context -> int -> tactic
    19 end
    20 
    21 structure Groebner : GROEBNER =
    22 struct
    23 
    24 open Conv Normalizer Drule Thm;
    25 
    26 fun is_comb ct =
    27   (case Thm.term_of ct of
    28     _ $ _ => true
    29   | _ => false);
    30 
    31 val concl = Thm.cprop_of #> Thm.dest_arg;
    32 
    33 fun is_binop ct ct' =
    34   (case Thm.term_of ct' of
    35     c $ _ $ _ => term_of ct aconv c
    36   | _ => false);
    37 
    38 fun dest_binary ct ct' =
    39   if is_binop ct ct' then Thm.dest_binop ct'
    40   else raise CTERM ("dest_binary: bad binop", [ct, ct'])
    41 
    42 fun inst_thm inst = Thm.instantiate ([], inst);
    43 
    44 val rat_0 = Rat.zero;
    45 val rat_1 = Rat.one;
    46 val minus_rat = Rat.neg;
    47 val denominator_rat = Rat.quotient_of_rat #> snd #> Rat.rat_of_int;
    48 fun int_of_rat a =
    49     case Rat.quotient_of_rat a of (i,1) => i | _ => error "int_of_rat: not an int";
    50 val lcm_rat = fn x => fn y => Rat.rat_of_int (Integer.lcm (int_of_rat x) (int_of_rat y));
    51 
    52 val (eqF_intr, eqF_elim) =
    53   let val [th1,th2] = thms "PFalse"
    54   in (fn th => th COMP th2, fn th => th COMP th1) end;
    55 
    56 val (PFalse, PFalse') =
    57  let val PFalse_eq = nth (thms "simp_thms") 13
    58  in (PFalse_eq RS iffD1, PFalse_eq RS iffD2) end;
    59 
    60 
    61 (* Type for recording history, i.e. how a polynomial was obtained. *)
    62 
    63 datatype history =
    64    Start of int
    65  | Mmul of (Rat.rat * int list) * history
    66  | Add of history * history;
    67 
    68 
    69 (* Monomial ordering. *)
    70 
    71 fun morder_lt m1 m2=
    72     let fun lexorder l1 l2 =
    73             case (l1,l2) of
    74                 ([],[]) => false
    75               | (x1::o1,x2::o2) => x1 > x2 orelse x1 = x2 andalso lexorder o1 o2
    76               | _ => error "morder: inconsistent monomial lengths"
    77         val n1 = Integer.sum m1
    78         val n2 = Integer.sum m2 in
    79     n1 < n2 orelse n1 = n2 andalso lexorder m1 m2
    80     end;
    81 
    82 fun morder_le m1 m2 = morder_lt m1 m2 orelse (m1 = m2);
    83 
    84 fun morder_gt m1 m2 = morder_lt m2 m1;
    85 
    86 (* Arithmetic on canonical polynomials. *)
    87 
    88 fun grob_neg l = map (fn (c,m) => (minus_rat c,m)) l;
    89 
    90 fun grob_add l1 l2 =
    91   case (l1,l2) of
    92     ([],l2) => l2
    93   | (l1,[]) => l1
    94   | ((c1,m1)::o1,(c2,m2)::o2) =>
    95         if m1 = m2 then
    96           let val c = c1+/c2 val rest = grob_add o1 o2 in
    97           if c =/ rat_0 then rest else (c,m1)::rest end
    98         else if morder_lt m2 m1 then (c1,m1)::(grob_add o1 l2)
    99         else (c2,m2)::(grob_add l1 o2);
   100 
   101 fun grob_sub l1 l2 = grob_add l1 (grob_neg l2);
   102 
   103 fun grob_mmul (c1,m1) (c2,m2) = (c1*/c2, ListPair.map (op +) (m1, m2));
   104 
   105 fun grob_cmul cm pol = map (grob_mmul cm) pol;
   106 
   107 fun grob_mul l1 l2 =
   108   case l1 of
   109     [] => []
   110   | (h1::t1) => grob_add (grob_cmul h1 l2) (grob_mul t1 l2);
   111 
   112 fun grob_inv l =
   113   case l of
   114     [(c,vs)] => if (forall (fn x => x = 0) vs) then
   115                   if (c =/ rat_0) then error "grob_inv: division by zero"
   116                   else [(rat_1 // c,vs)]
   117               else error "grob_inv: non-constant divisor polynomial"
   118   | _ => error "grob_inv: non-constant divisor polynomial";
   119 
   120 fun grob_div l1 l2 =
   121   case l2 of
   122     [(c,l)] => if (forall (fn x => x = 0) l) then
   123                  if c =/ rat_0 then error "grob_div: division by zero"
   124                  else grob_cmul (rat_1 // c,l) l1
   125              else error "grob_div: non-constant divisor polynomial"
   126   | _ => error "grob_div: non-constant divisor polynomial";
   127 
   128 fun grob_pow vars l n =
   129   if n < 0 then error "grob_pow: negative power"
   130   else if n = 0 then [(rat_1,map (fn v => 0) vars)]
   131   else grob_mul l (grob_pow vars l (n - 1));
   132 
   133 fun degree vn p =
   134  case p of
   135   [] => error "Zero polynomial"
   136 | [(c,ns)] => nth ns vn
   137 | (c,ns)::p' => Int.max (nth ns vn, degree vn p');
   138 
   139 fun head_deg vn p = let val d = degree vn p in
   140  (d,fold (fn (c,r) => fn q => grob_add q [(c, map_index (fn (i,n) => if i = vn then 0 else n) r)]) (filter (fn (c,ns) => c <>/ rat_0 andalso nth ns vn = d) p) []) end;
   141 
   142 val is_zerop = forall (fn (c,ns) => c =/ rat_0 andalso forall (curry (op =) 0) ns);
   143 val grob_pdiv =
   144  let fun pdiv_aux vn (n,a) p k s =
   145   if is_zerop s then (k,s) else
   146   let val (m,b) = head_deg vn s
   147   in if m < n then (k,s) else
   148      let val p' = grob_mul p [(rat_1, map_index (fn (i,v) => if i = vn then m - n else 0)
   149                                                 (snd (hd s)))]
   150      in if a = b then pdiv_aux vn (n,a) p k (grob_sub s p')
   151         else pdiv_aux vn (n,a) p (k + 1) (grob_sub (grob_mul a s) (grob_mul b p'))
   152      end
   153   end
   154  in fn vn => fn s => fn p => pdiv_aux vn (head_deg vn p) p 0 s
   155  end;
   156 
   157 (* Monomial division operation. *)
   158 
   159 fun mdiv (c1,m1) (c2,m2) =
   160   (c1//c2,
   161    map2 (fn n1 => fn n2 => if n1 < n2 then error "mdiv" else n1 - n2) m1 m2);
   162 
   163 (* Lowest common multiple of two monomials. *)
   164 
   165 fun mlcm (c1,m1) (c2,m2) = (rat_1, ListPair.map Int.max (m1, m2));
   166 
   167 (* Reduce monomial cm by polynomial pol, returning replacement for cm.  *)
   168 
   169 fun reduce1 cm (pol,hpol) =
   170   case pol of
   171     [] => error "reduce1"
   172   | cm1::cms => ((let val (c,m) = mdiv cm cm1 in
   173                     (grob_cmul (minus_rat c,m) cms,
   174                      Mmul((minus_rat c,m),hpol)) end)
   175                 handle  ERROR _ => error "reduce1");
   176 
   177 (* Try this for all polynomials in a basis.  *)
   178 fun tryfind f l =
   179     case l of
   180         [] => error "tryfind"
   181       | (h::t) => ((f h) handle ERROR _ => tryfind f t);
   182 
   183 fun reduceb cm basis = tryfind (fn p => reduce1 cm p) basis;
   184 
   185 (* Reduction of a polynomial (always picking largest monomial possible).     *)
   186 
   187 fun reduce basis (pol,hist) =
   188   case pol of
   189     [] => (pol,hist)
   190   | cm::ptl => ((let val (q,hnew) = reduceb cm basis in
   191                    reduce basis (grob_add q ptl,Add(hnew,hist)) end)
   192                handle (ERROR _) =>
   193                    (let val (q,hist') = reduce basis (ptl,hist) in
   194                        (cm::q,hist') end));
   195 
   196 (* Check for orthogonality w.r.t. LCM.                                       *)
   197 
   198 fun orthogonal l p1 p2 =
   199   snd l = snd(grob_mmul (hd p1) (hd p2));
   200 
   201 (* Compute S-polynomial of two polynomials.                                  *)
   202 
   203 fun spoly cm ph1 ph2 =
   204   case (ph1,ph2) of
   205     (([],h),p) => ([],h)
   206   | (p,([],h)) => ([],h)
   207   | ((cm1::ptl1,his1),(cm2::ptl2,his2)) =>
   208         (grob_sub (grob_cmul (mdiv cm cm1) ptl1)
   209                   (grob_cmul (mdiv cm cm2) ptl2),
   210          Add(Mmul(mdiv cm cm1,his1),
   211              Mmul(mdiv (minus_rat(fst cm),snd cm) cm2,his2)));
   212 
   213 (* Make a polynomial monic.                                                  *)
   214 
   215 fun monic (pol,hist) =
   216   if null pol then (pol,hist) else
   217   let val (c',m') = hd pol in
   218   (map (fn (c,m) => (c//c',m)) pol,
   219    Mmul((rat_1 // c',map (K 0) m'),hist)) end;
   220 
   221 (* The most popular heuristic is to order critical pairs by LCM monomial.    *)
   222 
   223 fun forder ((c1,m1),_) ((c2,m2),_) = morder_lt m1 m2;
   224 
   225 fun poly_lt  p q =
   226   case (p,q) of
   227     (p,[]) => false
   228   | ([],q) => true
   229   | ((c1,m1)::o1,(c2,m2)::o2) =>
   230         c1 </ c2 orelse
   231         c1 =/ c2 andalso ((morder_lt m1 m2) orelse m1 = m2 andalso poly_lt o1 o2);
   232 
   233 fun align  ((p,hp),(q,hq)) =
   234   if poly_lt p q then ((p,hp),(q,hq)) else ((q,hq),(p,hp));
   235 fun forall2 p l1 l2 =
   236   case (l1,l2) of
   237     ([],[]) => true
   238   | (h1::t1,h2::t2) => p h1 h2 andalso forall2 p t1 t2
   239   | _ => false;
   240 
   241 fun poly_eq p1 p2 =
   242   forall2 (fn (c1,m1) => fn (c2,m2) => c1 =/ c2 andalso (m1: int list) = m2) p1 p2;
   243 
   244 fun memx ((p1,h1),(p2,h2)) ppairs =
   245   not (exists (fn ((q1,_),(q2,_)) => poly_eq p1 q1 andalso poly_eq p2 q2) ppairs);
   246 
   247 (* Buchberger's second criterion.                                            *)
   248 
   249 fun criterion2 basis (lcm,((p1,h1),(p2,h2))) opairs =
   250   exists (fn g => not(poly_eq (fst g) p1) andalso not(poly_eq (fst g) p2) andalso
   251                    can (mdiv lcm) (hd(fst g)) andalso
   252                    not(memx (align (g,(p1,h1))) (map snd opairs)) andalso
   253                    not(memx (align (g,(p2,h2))) (map snd opairs))) basis;
   254 
   255 (* Test for hitting constant polynomial.                                     *)
   256 
   257 fun constant_poly p =
   258   length p = 1 andalso forall (fn x => x = 0) (snd(hd p));
   259 
   260 (* Grobner basis algorithm.                                                  *)
   261 
   262 (* FIXME: try to get rid of mergesort? *)
   263 fun merge ord l1 l2 =
   264  case l1 of
   265   [] => l2
   266  | h1::t1 =>
   267    case l2 of
   268     [] => l1
   269    | h2::t2 => if ord h1 h2 then h1::(merge ord t1 l2)
   270                else h2::(merge ord l1 t2);
   271 fun mergesort ord l =
   272  let
   273  fun mergepairs l1 l2 =
   274   case (l1,l2) of
   275    ([s],[]) => s
   276  | (l,[]) => mergepairs [] l
   277  | (l,[s1]) => mergepairs (s1::l) []
   278  | (l,(s1::s2::ss)) => mergepairs ((merge ord s1 s2)::l) ss
   279  in if null l  then []  else mergepairs [] (map (fn x => [x]) l)
   280  end;
   281 
   282 
   283 fun grobner_basis basis pairs =
   284  case pairs of
   285    [] => basis
   286  | (l,(p1,p2))::opairs =>
   287    let val (sph as (sp,hist)) = monic (reduce basis (spoly l p1 p2))
   288    in 
   289     if null sp orelse criterion2 basis (l,(p1,p2)) opairs
   290     then grobner_basis basis opairs
   291     else if constant_poly sp then grobner_basis (sph::basis) []
   292     else 
   293      let 
   294       val rawcps = map (fn p => (mlcm (hd(fst p)) (hd sp),align(p,sph)))
   295                               basis
   296       val newcps = filter (fn (l,(p,q)) => not(orthogonal l (fst p) (fst q)))
   297                         rawcps
   298      in grobner_basis (sph::basis)
   299                  (merge forder opairs (mergesort forder newcps))
   300      end
   301    end;
   302 
   303 (* Interreduce initial polynomials.                                          *)
   304 
   305 fun grobner_interreduce rpols ipols =
   306   case ipols of
   307     [] => map monic (rev rpols)
   308   | p::ps => let val p' = reduce (rpols @ ps) p in
   309              if null (fst p') then grobner_interreduce rpols ps
   310              else grobner_interreduce (p'::rpols) ps end;
   311 
   312 (* Overall function.                                                         *)
   313 
   314 fun grobner pols =
   315     let val npols = map_index (fn (n, p) => (p, Start n)) pols
   316         val phists = filter (fn (p,_) => not (null p)) npols
   317         val bas = grobner_interreduce [] (map monic phists)
   318         val prs0 = map_product pair bas bas
   319         val prs1 = filter (fn ((x,_),(y,_)) => poly_lt x y) prs0
   320         val prs2 = map (fn (p,q) => (mlcm (hd(fst p)) (hd(fst q)),(p,q))) prs1
   321         val prs3 =
   322             filter (fn (l,(p,q)) => not(orthogonal l (fst p) (fst q))) prs2 in
   323         grobner_basis bas (mergesort forder prs3) end;
   324 
   325 (* Get proof of contradiction from Grobner basis.                            *)
   326 
   327 fun find p l =
   328   case l of
   329       [] => error "find"
   330     | (h::t) => if p(h) then h else find p t;
   331 
   332 fun grobner_refute pols =
   333   let val gb = grobner pols in
   334   snd(find (fn (p,h) => length p = 1 andalso forall (fn x=> x=0) (snd(hd p))) gb)
   335   end;
   336 
   337 (* Turn proof into a certificate as sum of multipliers.                      *)
   338 (* In principle this is very inefficient: in a heavily shared proof it may   *)
   339 (* make the same calculation many times. Could put in a cache or something.  *)
   340 
   341 fun resolve_proof vars prf =
   342   case prf of
   343     Start(~1) => []
   344   | Start m => [(m,[(rat_1,map (K 0) vars)])]
   345   | Mmul(pol,lin) =>
   346         let val lis = resolve_proof vars lin in
   347             map (fn (n,p) => (n,grob_cmul pol p)) lis end
   348   | Add(lin1,lin2) =>
   349         let val lis1 = resolve_proof vars lin1
   350             val lis2 = resolve_proof vars lin2
   351             val dom = distinct (op =) (union (op =) (map fst lis1) (map fst lis2))
   352         in
   353             map (fn n => let val a = these (AList.lookup (op =) lis1 n)
   354                              val b = these (AList.lookup (op =) lis2 n)
   355                          in (n,grob_add a b) end) dom end;
   356 
   357 (* Run the procedure and produce Weak Nullstellensatz certificate.           *)
   358 
   359 fun grobner_weak vars pols =
   360     let val cert = resolve_proof vars (grobner_refute pols)
   361         val l =
   362             fold_rev (fold_rev (lcm_rat o denominator_rat o fst) o snd) cert (rat_1) in
   363         (l,map (fn (i,p) => (i,map (fn (d,m) => (l*/d,m)) p)) cert) end;
   364 
   365 (* Prove a polynomial is in ideal generated by others, using Grobner basis.  *)
   366 
   367 fun grobner_ideal vars pols pol =
   368   let val (pol',h) = reduce (grobner pols) (grob_neg pol,Start(~1)) in
   369   if not (null pol') then error "grobner_ideal: not in the ideal" else
   370   resolve_proof vars h end;
   371 
   372 (* Produce Strong Nullstellensatz certificate for a power of pol.            *)
   373 
   374 fun grobner_strong vars pols pol =
   375     let val vars' = @{cterm "True"}::vars
   376         val grob_z = [(rat_1,1::(map (fn x => 0) vars))]
   377         val grob_1 = [(rat_1,(map (fn x => 0) vars'))]
   378         fun augment p= map (fn (c,m) => (c,0::m)) p
   379         val pols' = map augment pols
   380         val pol' = augment pol
   381         val allpols = (grob_sub (grob_mul grob_z pol') grob_1)::pols'
   382         val (l,cert) = grobner_weak vars' allpols
   383         val d = fold (fold (Integer.max o hd o snd) o snd) cert 0
   384         fun transform_monomial (c,m) =
   385             grob_cmul (c,tl m) (grob_pow vars pol (d - hd m))
   386         fun transform_polynomial q = fold_rev (grob_add o transform_monomial) q []
   387         val cert' = map (fn (c,q) => (c-1,transform_polynomial q))
   388                         (filter (fn (k,_) => k <> 0) cert) in
   389         (d,l,cert') end;
   390 
   391 
   392 (* Overall parametrized universal procedure for (semi)rings.                 *)
   393 (* We return an ideal_conv and the actual ring prover.                       *)
   394 
   395 fun refute_disj rfn tm =
   396  case term_of tm of
   397   Const("op |",_)$l$r =>
   398    compose_single(refute_disj rfn (dest_arg tm),2,compose_single(refute_disj rfn (dest_arg1 tm),2,disjE))
   399   | _ => rfn tm ;
   400 
   401 val notnotD = @{thm "notnotD"};
   402 fun mk_binop ct x y = capply (capply ct x) y
   403 
   404 val mk_comb = capply;
   405 fun is_neg t =
   406     case term_of t of
   407       (Const("Not",_)$p) => true
   408     | _  => false;
   409 fun is_eq t =
   410  case term_of t of
   411  (Const("op =",_)$_$_) => true
   412 | _  => false;
   413 
   414 fun end_itlist f l =
   415   case l of
   416         []     => error "end_itlist"
   417       | [x]    => x
   418       | (h::t) => f h (end_itlist f t);
   419 
   420 val list_mk_binop = fn b => end_itlist (mk_binop b);
   421 
   422 val list_dest_binop = fn b =>
   423  let fun h acc t =
   424   ((let val (l,r) = dest_binary b t in h (h acc r) l end)
   425    handle CTERM _ => (t::acc)) (* Why had I handle _ => ? *)
   426  in h []
   427  end;
   428 
   429 val strip_exists =
   430  let fun h (acc, t) =
   431       case (term_of t) of
   432        Const("Ex",_)$Abs(x,T,p) => h (dest_abs NONE (dest_arg t) |>> (fn v => v::acc))
   433      | _ => (acc,t)
   434  in fn t => h ([],t)
   435  end;
   436 
   437 fun is_forall t =
   438  case term_of t of
   439   (Const("All",_)$Abs(_,_,_)) => true
   440 | _ => false;
   441 
   442 val mk_object_eq = fn th => th COMP meta_eq_to_obj_eq;
   443 val bool_simps = @{thms "bool_simps"};
   444 val nnf_simps = @{thms "nnf_simps"};
   445 val nnf_conv = Simplifier.rewrite (HOL_basic_ss addsimps bool_simps addsimps nnf_simps)
   446 val weak_dnf_conv = Simplifier.rewrite (HOL_basic_ss addsimps @{thms "weak_dnf_simps"});
   447 val initial_conv =
   448     Simplifier.rewrite
   449      (HOL_basic_ss addsimps nnf_simps
   450        addsimps [not_all, not_ex]
   451        addsimps map (fn th => th RS sym) (@{thms ex_simps} @ @{thms all_simps}));
   452 
   453 val specl = fold_rev (fn x => fn th => instantiate' [] [SOME x] (th RS spec));
   454 
   455 val cTrp = @{cterm "Trueprop"};
   456 val cConj = @{cterm "op &"};
   457 val (cNot,false_tm) = (@{cterm "Not"}, @{cterm "False"});
   458 val assume_Trueprop = mk_comb cTrp #> assume;
   459 val list_mk_conj = list_mk_binop cConj;
   460 val conjs = list_dest_binop cConj;
   461 val mk_neg = mk_comb cNot;
   462 
   463 fun striplist dest = 
   464  let
   465   fun h acc x = case try dest x of
   466     SOME (a,b) => h (h acc b) a
   467   | NONE => x::acc
   468  in h [] end;
   469 fun list_mk_binop b = foldr1 (fn (s,t) => Thm.capply (Thm.capply b s) t);
   470 
   471 val eq_commute = mk_meta_eq @{thm eq_commute};
   472 
   473 fun sym_conv eq = 
   474  let val (l,r) = Thm.dest_binop eq
   475  in instantiate' [SOME (ctyp_of_term l)] [SOME l, SOME r] eq_commute
   476  end;
   477 
   478   (* FIXME : copied from cqe.ML -- complex QE*)
   479 fun conjuncts ct =
   480  case term_of ct of
   481   @{term "op &"}$_$_ => (Thm.dest_arg1 ct)::(conjuncts (Thm.dest_arg ct))
   482 | _ => [ct];
   483 
   484 fun fold1 f = foldr1 (uncurry f);
   485 
   486 val list_conj = fold1 (fn c => fn c' => Thm.capply (Thm.capply @{cterm "op &"} c) c') ;
   487 
   488 fun mk_conj_tab th = 
   489  let fun h acc th = 
   490    case prop_of th of
   491    @{term "Trueprop"}$(@{term "op &"}$p$q) => 
   492      h (h acc (th RS conjunct2)) (th RS conjunct1)
   493   | @{term "Trueprop"}$p => (p,th)::acc
   494 in fold (Termtab.insert Thm.eq_thm) (h [] th) Termtab.empty end;
   495 
   496 fun is_conj (@{term "op &"}$_$_) = true
   497   | is_conj _ = false;
   498 
   499 fun prove_conj tab cjs = 
   500  case cjs of 
   501    [c] => if is_conj (term_of c) then prove_conj tab (conjuncts c) else tab c
   502  | c::cs => conjI OF [prove_conj tab [c], prove_conj tab cs];
   503 
   504 fun conj_ac_rule eq = 
   505  let 
   506   val (l,r) = Thm.dest_equals eq
   507   val ctabl = mk_conj_tab (assume (Thm.capply @{cterm Trueprop} l))
   508   val ctabr = mk_conj_tab (assume (Thm.capply @{cterm Trueprop} r))
   509   fun tabl c = the (Termtab.lookup ctabl (term_of c))
   510   fun tabr c = the (Termtab.lookup ctabr (term_of c))
   511   val thl  = prove_conj tabl (conjuncts r) |> implies_intr_hyps
   512   val thr  = prove_conj tabr (conjuncts l) |> implies_intr_hyps
   513   val eqI = instantiate' [] [SOME l, SOME r] @{thm iffI}
   514  in implies_elim (implies_elim eqI thl) thr |> mk_meta_eq end;
   515 
   516  (* END FIXME.*)
   517 
   518    (* Conversion for the equivalence of existential statements where 
   519       EX quantifiers are rearranged differently *)
   520  fun ext T = cterm_rule (instantiate' [SOME T] []) @{cpat Ex}
   521  fun mk_ex v t = Thm.capply (ext (ctyp_of_term v)) (Thm.cabs v t)
   522 
   523 fun choose v th th' = case concl_of th of 
   524   @{term Trueprop} $ (Const("Ex",_)$_) => 
   525    let
   526     val p = (funpow 2 Thm.dest_arg o cprop_of) th
   527     val T = (hd o Thm.dest_ctyp o ctyp_of_term) p
   528     val th0 = fconv_rule (Thm.beta_conversion true)
   529         (instantiate' [SOME T] [SOME p, (SOME o Thm.dest_arg o cprop_of) th'] exE)
   530     val pv = (Thm.rhs_of o Thm.beta_conversion true) 
   531           (Thm.capply @{cterm Trueprop} (Thm.capply p v))
   532     val th1 = forall_intr v (implies_intr pv th')
   533    in implies_elim (implies_elim th0 th) th1  end
   534 | _ => error ""
   535 
   536 fun simple_choose v th = 
   537    choose v (assume ((Thm.capply @{cterm Trueprop} o mk_ex v) ((Thm.dest_arg o hd o #hyps o Thm.crep_thm) th))) th
   538 
   539 
   540  fun mkexi v th = 
   541   let 
   542    val p = Thm.cabs v (Thm.dest_arg (Thm.cprop_of th))
   543   in implies_elim 
   544     (fconv_rule (Thm.beta_conversion true) (instantiate' [SOME (ctyp_of_term v)] [SOME p, SOME v] @{thm exI}))
   545       th
   546   end
   547  fun ex_eq_conv t = 
   548   let 
   549   val (p0,q0) = Thm.dest_binop t
   550   val (vs',P) = strip_exists p0 
   551   val (vs,_) = strip_exists q0 
   552    val th = assume (Thm.capply @{cterm Trueprop} P)
   553    val th1 =  implies_intr_hyps (fold simple_choose vs' (fold mkexi vs th))
   554    val th2 =  implies_intr_hyps (fold simple_choose vs (fold mkexi vs' th))
   555    val p = (Thm.dest_arg o Thm.dest_arg1 o cprop_of) th1
   556    val q = (Thm.dest_arg o Thm.dest_arg o cprop_of) th1
   557   in implies_elim (implies_elim (instantiate' [] [SOME p, SOME q] iffI) th1) th2
   558      |> mk_meta_eq
   559   end;
   560 
   561 
   562  fun getname v = case term_of v of 
   563   Free(s,_) => s
   564  | Var ((s,_),_) => s
   565  | _ => "x"
   566  fun mk_eq s t = Thm.capply (Thm.capply @{cterm "op == :: bool => _"} s) t
   567  fun mkeq s t = Thm.capply @{cterm Trueprop} (Thm.capply (Thm.capply @{cterm "op = :: bool => _"} s) t)
   568  fun mk_exists v th = arg_cong_rule (ext (ctyp_of_term v))
   569    (Thm.abstract_rule (getname v) v th)
   570  val simp_ex_conv = 
   571      Simplifier.rewrite (HOL_basic_ss addsimps @{thms simp_thms(39)})
   572 
   573 fun frees t = Thm.add_cterm_frees t [];
   574 fun free_in v t = member op aconvc (frees t) v;
   575 
   576 val vsubst = let
   577  fun vsubst (t,v) tm =  
   578    (Thm.rhs_of o Thm.beta_conversion false) (Thm.capply (Thm.cabs v tm) t)
   579 in fold vsubst end;
   580 
   581 
   582 (** main **)
   583 
   584 fun ring_and_ideal_conv
   585   {vars, semiring = (sr_ops, sr_rules), ring = (r_ops, r_rules), 
   586    field = (f_ops, f_rules), idom, ideal}
   587   dest_const mk_const ring_eq_conv ring_normalize_conv =
   588 let
   589   val [add_pat, mul_pat, pow_pat, zero_tm, one_tm] = sr_ops;
   590   val [ring_add_tm, ring_mul_tm, ring_pow_tm] =
   591     map dest_fun2 [add_pat, mul_pat, pow_pat];
   592 
   593   val (ring_sub_tm, ring_neg_tm) =
   594     (case r_ops of
   595      [sub_pat, neg_pat] => (dest_fun2 sub_pat, dest_fun neg_pat)
   596     |_  => (@{cterm "True"}, @{cterm "True"}));
   597 
   598   val (field_div_tm, field_inv_tm) =
   599     (case f_ops of
   600        [div_pat, inv_pat] => (dest_fun2 div_pat, dest_fun inv_pat)
   601      | _ => (@{cterm "True"}, @{cterm "True"}));
   602 
   603   val [idom_thm, neq_thm] = idom;
   604   val [idl_sub, idl_add0] = 
   605      if length ideal = 2 then ideal else [eq_commute, eq_commute]
   606   fun ring_dest_neg t =
   607     let val (l,r) = dest_comb t 
   608     in if Term.could_unify(term_of l,term_of ring_neg_tm) then r 
   609        else raise CTERM ("ring_dest_neg", [t])
   610     end
   611 
   612  val ring_mk_neg = fn tm => mk_comb (ring_neg_tm) (tm);
   613  fun field_dest_inv t =
   614     let val (l,r) = dest_comb t in
   615         if Term.could_unify(term_of l, term_of field_inv_tm) then r 
   616         else raise CTERM ("field_dest_inv", [t])
   617     end
   618  val ring_dest_add = dest_binary ring_add_tm;
   619  val ring_mk_add = mk_binop ring_add_tm;
   620  val ring_dest_sub = dest_binary ring_sub_tm;
   621  val ring_mk_sub = mk_binop ring_sub_tm;
   622  val ring_dest_mul = dest_binary ring_mul_tm;
   623  val ring_mk_mul = mk_binop ring_mul_tm;
   624  val field_dest_div = dest_binary field_div_tm;
   625  val field_mk_div = mk_binop field_div_tm;
   626  val ring_dest_pow = dest_binary ring_pow_tm;
   627  val ring_mk_pow = mk_binop ring_pow_tm ;
   628  fun grobvars tm acc =
   629     if can dest_const tm then acc
   630     else if can ring_dest_neg tm then grobvars (dest_arg tm) acc
   631     else if can ring_dest_pow tm then grobvars (dest_arg1 tm) acc
   632     else if can ring_dest_add tm orelse can ring_dest_sub tm
   633             orelse can ring_dest_mul tm
   634     then grobvars (dest_arg1 tm) (grobvars (dest_arg tm) acc)
   635     else if can field_dest_inv tm
   636          then
   637           let val gvs = grobvars (dest_arg tm) [] 
   638           in if null gvs then acc else tm::acc
   639           end
   640     else if can field_dest_div tm then
   641          let val lvs = grobvars (dest_arg1 tm) acc
   642              val gvs = grobvars (dest_arg tm) []
   643           in if null gvs then lvs else tm::acc
   644           end 
   645     else tm::acc ;
   646 
   647 fun grobify_term vars tm =
   648 ((if not (member (op aconvc) vars tm) then raise CTERM ("Not a variable", [tm]) else
   649      [(rat_1,map (fn i => if i aconvc tm then 1 else 0) vars)])
   650 handle  CTERM _ =>
   651  ((let val x = dest_const tm
   652  in if x =/ rat_0 then [] else [(x,map (fn v => 0) vars)]
   653  end)
   654  handle ERROR _ =>
   655   ((grob_neg(grobify_term vars (ring_dest_neg tm)))
   656   handle CTERM _ =>
   657    (
   658    (grob_inv(grobify_term vars (field_dest_inv tm)))
   659    handle CTERM _ => 
   660     ((let val (l,r) = ring_dest_add tm
   661     in grob_add (grobify_term vars l) (grobify_term vars r)
   662     end)
   663     handle CTERM _ =>
   664      ((let val (l,r) = ring_dest_sub tm
   665      in grob_sub (grobify_term vars l) (grobify_term vars r)
   666      end)
   667      handle  CTERM _ =>
   668       ((let val (l,r) = ring_dest_mul tm
   669       in grob_mul (grobify_term vars l) (grobify_term vars r)
   670       end)
   671        handle CTERM _ =>
   672         (  (let val (l,r) = field_dest_div tm
   673           in grob_div (grobify_term vars l) (grobify_term vars r)
   674           end)
   675          handle CTERM _ =>
   676           ((let val (l,r) = ring_dest_pow tm
   677           in grob_pow vars (grobify_term vars l) ((term_of #> HOLogic.dest_number #> snd) r)
   678           end)
   679            handle CTERM _ => error "grobify_term: unknown or invalid term")))))))));
   680 val eq_tm = idom_thm |> concl |> dest_arg |> dest_arg |> dest_fun2;
   681 val dest_eq = dest_binary eq_tm;
   682 
   683 fun grobify_equation vars tm =
   684     let val (l,r) = dest_binary eq_tm tm
   685     in grob_sub (grobify_term vars l) (grobify_term vars r)
   686     end;
   687 
   688 fun grobify_equations tm =
   689  let
   690   val cjs = conjs tm
   691   val  rawvars = fold_rev (fn eq => fn a =>
   692                                        grobvars (dest_arg1 eq) (grobvars (dest_arg eq) a)) cjs []
   693   val vars = sort (fn (x, y) => Term_Ord.term_ord(term_of x,term_of y))
   694                   (distinct (op aconvc) rawvars)
   695  in (vars,map (grobify_equation vars) cjs)
   696  end;
   697 
   698 val holify_polynomial =
   699  let fun holify_varpow (v,n) =
   700   if n = 1 then v else ring_mk_pow v (Numeral.mk_cnumber @{ctyp "nat"} n)  (* FIXME *)
   701  fun holify_monomial vars (c,m) =
   702   let val xps = map holify_varpow (filter (fn (_,n) => n <> 0) (vars ~~ m))
   703    in end_itlist ring_mk_mul (mk_const c :: xps)
   704   end
   705  fun holify_polynomial vars p =
   706      if null p then mk_const (rat_0)
   707      else end_itlist ring_mk_add (map (holify_monomial vars) p)
   708  in holify_polynomial
   709  end ;
   710 val idom_rule = simplify (HOL_basic_ss addsimps [idom_thm]);
   711 fun prove_nz n = eqF_elim
   712                  (ring_eq_conv(mk_binop eq_tm (mk_const n) (mk_const(rat_0))));
   713 val neq_01 = prove_nz (rat_1);
   714 fun neq_rule n th = [prove_nz n, th] MRS neq_thm;
   715 fun mk_add th1 = combination(arg_cong_rule ring_add_tm th1);
   716 
   717 fun refute tm =
   718  if tm aconvc false_tm then assume_Trueprop tm else
   719  ((let
   720    val (nths0,eths0) = List.partition (is_neg o concl) (HOLogic.conj_elims (assume_Trueprop tm))
   721    val  nths = filter (is_eq o dest_arg o concl) nths0
   722    val eths = filter (is_eq o concl) eths0
   723   in
   724    if null eths then
   725     let
   726       val th1 = end_itlist (fn th1 => fn th2 => idom_rule(HOLogic.conj_intr th1 th2)) nths
   727       val th2 = Conv.fconv_rule
   728                 ((arg_conv #> arg_conv)
   729                      (binop_conv ring_normalize_conv)) th1
   730       val conc = th2 |> concl |> dest_arg
   731       val (l,r) = conc |> dest_eq
   732     in implies_intr (mk_comb cTrp tm)
   733                     (equal_elim (arg_cong_rule cTrp (eqF_intr th2))
   734                            (reflexive l |> mk_object_eq))
   735     end
   736    else
   737    let
   738     val (vars,l,cert,noteqth) =(
   739      if null nths then
   740       let val (vars,pols) = grobify_equations(list_mk_conj(map concl eths))
   741           val (l,cert) = grobner_weak vars pols
   742       in (vars,l,cert,neq_01)
   743       end
   744      else
   745       let
   746        val nth = end_itlist (fn th1 => fn th2 => idom_rule(HOLogic.conj_intr th1 th2)) nths
   747        val (vars,pol::pols) =
   748           grobify_equations(list_mk_conj(dest_arg(concl nth)::map concl eths))
   749        val (deg,l,cert) = grobner_strong vars pols pol
   750        val th1 = Conv.fconv_rule((arg_conv o arg_conv)(binop_conv ring_normalize_conv)) nth
   751        val th2 = funpow deg (idom_rule o HOLogic.conj_intr th1) neq_01
   752       in (vars,l,cert,th2)
   753       end)
   754     val cert_pos = map (fn (i,p) => (i,filter (fn (c,m) => c >/ rat_0) p)) cert
   755     val cert_neg = map (fn (i,p) => (i,map (fn (c,m) => (minus_rat c,m))
   756                                             (filter (fn (c,m) => c </ rat_0) p))) cert
   757     val  herts_pos = map (fn (i,p) => (i,holify_polynomial vars p)) cert_pos
   758     val  herts_neg = map (fn (i,p) => (i,holify_polynomial vars p)) cert_neg
   759     fun thm_fn pols =
   760         if null pols then reflexive(mk_const rat_0) else
   761         end_itlist mk_add
   762             (map (fn (i,p) => arg_cong_rule (mk_comb ring_mul_tm p)
   763               (nth eths i |> mk_meta_eq)) pols)
   764     val th1 = thm_fn herts_pos
   765     val th2 = thm_fn herts_neg
   766     val th3 = HOLogic.conj_intr(mk_add (symmetric th1) th2 |> mk_object_eq) noteqth
   767     val th4 = Conv.fconv_rule ((arg_conv o arg_conv o binop_conv) ring_normalize_conv)
   768                                (neq_rule l th3)
   769     val (l,r) = dest_eq(dest_arg(concl th4))
   770    in implies_intr (mk_comb cTrp tm)
   771                         (equal_elim (arg_cong_rule cTrp (eqF_intr th4))
   772                    (reflexive l |> mk_object_eq))
   773    end
   774   end) handle ERROR _ => raise CTERM ("Gorbner-refute: unable to refute",[tm]))
   775 
   776 fun ring tm =
   777  let
   778   fun mk_forall x p =
   779       mk_comb (cterm_rule (instantiate' [SOME (ctyp_of_term x)] []) @{cpat "All:: (?'a => bool) => _"}) (cabs x p)
   780   val avs = add_cterm_frees tm []
   781   val P' = fold mk_forall avs tm
   782   val th1 = initial_conv(mk_neg P')
   783   val (evs,bod) = strip_exists(concl th1) in
   784    if is_forall bod then raise CTERM("ring: non-universal formula",[tm])
   785    else
   786    let
   787     val th1a = weak_dnf_conv bod
   788     val boda = concl th1a
   789     val th2a = refute_disj refute boda
   790     val th2b = [mk_object_eq th1a, (th2a COMP notI) COMP PFalse'] MRS trans
   791     val th2 = fold (fn v => fn th => (forall_intr v th) COMP allI) evs (th2b RS PFalse)
   792     val th3 = equal_elim
   793                 (Simplifier.rewrite (HOL_basic_ss addsimps [not_ex RS sym])
   794                           (th2 |> cprop_of)) th2
   795     in specl avs
   796              ([[[mk_object_eq th1, th3 RS PFalse'] MRS trans] MRS PFalse] MRS notnotD)
   797    end
   798  end
   799 fun ideal tms tm ord =
   800  let
   801   val rawvars = fold_rev grobvars (tm::tms) []
   802   val vars = sort ord (distinct (fn (x,y) => (term_of x) aconv (term_of y)) rawvars)
   803   val pols = map (grobify_term vars) tms
   804   val pol = grobify_term vars tm
   805   val cert = grobner_ideal vars pols pol
   806  in map_range (fn n => these (AList.lookup (op =) cert n) |> holify_polynomial vars)
   807    (length pols)
   808  end
   809 
   810 fun poly_eq_conv t = 
   811  let val (a,b) = Thm.dest_binop t
   812  in fconv_rule (arg_conv (arg1_conv ring_normalize_conv)) 
   813      (instantiate' [] [SOME a, SOME b] idl_sub)
   814  end
   815  val poly_eq_simproc = 
   816   let 
   817    fun proc phi  ss t = 
   818     let val th = poly_eq_conv t
   819     in if Thm.is_reflexive th then NONE else SOME th
   820     end
   821    in make_simproc {lhss = [Thm.lhs_of idl_sub], 
   822                 name = "poly_eq_simproc", proc = proc, identifier = []}
   823    end;
   824   val poly_eq_ss = HOL_basic_ss addsimps @{thms simp_thms}
   825                         addsimprocs [poly_eq_simproc]
   826 
   827  local
   828   fun is_defined v t =
   829   let 
   830    val mons = striplist(dest_binary ring_add_tm) t 
   831   in member (op aconvc) mons v andalso 
   832     forall (fn m => v aconvc m 
   833           orelse not(member (op aconvc) (Thm.add_cterm_frees m []) v)) mons
   834   end
   835 
   836   fun isolate_variable vars tm =
   837   let 
   838    val th = poly_eq_conv tm
   839    val th' = (sym_conv then_conv poly_eq_conv) tm
   840    val (v,th1) = 
   841    case find_first(fn v=> is_defined v (Thm.dest_arg1 (Thm.rhs_of th))) vars of
   842     SOME v => (v,th')
   843    | NONE => (the (find_first 
   844           (fn v => is_defined v (Thm.dest_arg1 (Thm.rhs_of th'))) vars) ,th)
   845    val th2 = transitive th1 
   846         (instantiate' []  [(SOME o Thm.dest_arg1 o Thm.rhs_of) th1, SOME v] 
   847           idl_add0)
   848    in fconv_rule(funpow 2 arg_conv ring_normalize_conv) th2
   849    end
   850  in
   851  fun unwind_polys_conv tm =
   852  let 
   853   val (vars,bod) = strip_exists tm
   854   val cjs = striplist (dest_binary @{cterm "op &"}) bod
   855   val th1 = (the (get_first (try (isolate_variable vars)) cjs) 
   856              handle Option => raise CTERM ("unwind_polys_conv",[tm]))
   857   val eq = Thm.lhs_of th1
   858   val bod' = list_mk_binop @{cterm "op &"} (eq::(remove op aconvc eq cjs))
   859   val th2 = conj_ac_rule (mk_eq bod bod')
   860   val th3 = transitive th2 
   861          (Drule.binop_cong_rule @{cterm "op &"} th1 
   862                 (reflexive (Thm.dest_arg (Thm.rhs_of th2))))
   863   val v = Thm.dest_arg1(Thm.dest_arg1(Thm.rhs_of th3))
   864   val vars' = (remove op aconvc v vars) @ [v]
   865   val th4 = fconv_rule (arg_conv simp_ex_conv) (mk_exists v th3)
   866   val th5 = ex_eq_conv (mk_eq tm (fold mk_ex (remove op aconvc v vars) (Thm.lhs_of th4)))
   867  in transitive th5 (fold mk_exists (remove op aconvc v vars) th4)
   868  end;
   869 end
   870 
   871 local
   872  fun scrub_var v m =
   873   let 
   874    val ps = striplist ring_dest_mul m 
   875    val ps' = remove op aconvc v ps
   876   in if null ps' then one_tm else fold1 ring_mk_mul ps'
   877   end
   878  fun find_multipliers v mons =
   879   let 
   880    val mons1 = filter (fn m => free_in v m) mons 
   881    val mons2 = map (scrub_var v) mons1 
   882    in  if null mons2 then zero_tm else fold1 ring_mk_add mons2
   883   end
   884 
   885  fun isolate_monomials vars tm =
   886  let 
   887   val (cmons,vmons) =
   888     List.partition (fn m => null (inter (op aconvc) vars (frees m)))
   889                    (striplist ring_dest_add tm)
   890   val cofactors = map (fn v => find_multipliers v vmons) vars
   891   val cnc = if null cmons then zero_tm
   892              else Thm.capply ring_neg_tm
   893                     (list_mk_binop ring_add_tm cmons) 
   894   in (cofactors,cnc)
   895   end;
   896 
   897 fun isolate_variables evs ps eq =
   898  let 
   899   val vars = filter (fn v => free_in v eq) evs
   900   val (qs,p) = isolate_monomials vars eq
   901   val rs = ideal (qs @ ps) p 
   902               (fn (s,t) => Term_Ord.term_ord (term_of s, term_of t))
   903  in (eq, take (length qs) rs ~~ vars)
   904  end;
   905  fun subst_in_poly i p = Thm.rhs_of (ring_normalize_conv (vsubst i p));
   906 in
   907  fun solve_idealism evs ps eqs =
   908   if null evs then [] else
   909   let 
   910    val (eq,cfs) = get_first (try (isolate_variables evs ps)) eqs |> the
   911    val evs' = subtract op aconvc evs (map snd cfs)
   912    val eqs' = map (subst_in_poly cfs) (remove op aconvc eq eqs)
   913   in cfs @ solve_idealism evs' ps eqs'
   914   end;
   915 end;
   916 
   917 
   918 in {ring_conv = ring, simple_ideal = ideal, multi_ideal = solve_idealism, 
   919     poly_eq_ss = poly_eq_ss, unwind_conv = unwind_polys_conv}
   920 end;
   921 
   922 
   923 fun find_term bounds tm =
   924   (case term_of tm of
   925     Const ("op =", T) $ _ $ _ =>
   926       if domain_type T = HOLogic.boolT then find_args bounds tm
   927       else dest_arg tm
   928   | Const ("Not", _) $ _ => find_term bounds (dest_arg tm)
   929   | Const ("All", _) $ _ => find_body bounds (dest_arg tm)
   930   | Const ("Ex", _) $ _ => find_body bounds (dest_arg tm)
   931   | Const ("op &", _) $ _ $ _ => find_args bounds tm
   932   | Const ("op |", _) $ _ $ _ => find_args bounds tm
   933   | Const ("op -->", _) $ _ $ _ => find_args bounds tm
   934   | @{term "op ==>"} $_$_ => find_args bounds tm
   935   | Const("op ==",_)$_$_ => find_args bounds tm
   936   | @{term Trueprop}$_ => find_term bounds (dest_arg tm)
   937   | _ => raise TERM ("find_term", []))
   938 and find_args bounds tm =
   939   let val (t, u) = Thm.dest_binop tm
   940   in (find_term bounds t handle TERM _ => find_term bounds u) end
   941 and find_body bounds b =
   942   let val (_, b') = dest_abs (SOME (Name.bound bounds)) b
   943   in find_term (bounds + 1) b' end;
   944 
   945 
   946 fun get_ring_ideal_convs ctxt form = 
   947  case try (find_term 0) form of
   948   NONE => NONE
   949 | SOME tm =>
   950   (case NormalizerData.match ctxt tm of
   951     NONE => NONE
   952   | SOME (res as (theory, {is_const, dest_const, 
   953           mk_const, conv = ring_eq_conv})) =>
   954      SOME (ring_and_ideal_conv theory
   955           dest_const (mk_const (ctyp_of_term tm)) (ring_eq_conv ctxt)
   956           (semiring_normalize_wrapper ctxt res)))
   957 
   958 fun ring_solve ctxt form =
   959   (case try (find_term 0 (* FIXME !? *)) form of
   960     NONE => reflexive form
   961   | SOME tm =>
   962       (case NormalizerData.match ctxt tm of
   963         NONE => reflexive form
   964       | SOME (res as (theory, {is_const, dest_const, mk_const, conv = ring_eq_conv})) =>
   965         #ring_conv (ring_and_ideal_conv theory
   966           dest_const (mk_const (ctyp_of_term tm)) (ring_eq_conv ctxt)
   967           (semiring_normalize_wrapper ctxt res)) form));
   968 
   969 fun ring_tac add_ths del_ths ctxt =
   970   Object_Logic.full_atomize_tac
   971   THEN' asm_full_simp_tac
   972     (Simplifier.context ctxt (fst (NormalizerData.get ctxt)) delsimps del_ths addsimps add_ths)
   973   THEN' CSUBGOAL (fn (p, i) =>
   974     rtac (let val form = Object_Logic.dest_judgment p
   975           in case get_ring_ideal_convs ctxt form of
   976            NONE => reflexive form
   977           | SOME thy => #ring_conv thy form
   978           end) i
   979       handle TERM _ => no_tac
   980         | CTERM _ => no_tac
   981         | THM _ => no_tac);
   982 
   983 local
   984  fun lhs t = case term_of t of
   985   Const("op =",_)$_$_ => Thm.dest_arg1 t
   986  | _=> raise CTERM ("ideal_tac - lhs",[t])
   987  fun exitac NONE = no_tac
   988    | exitac (SOME y) = rtac (instantiate' [SOME (ctyp_of_term y)] [NONE,SOME y] exI) 1
   989 in 
   990 fun ideal_tac add_ths del_ths ctxt = 
   991   asm_full_simp_tac 
   992    (Simplifier.context ctxt (fst (NormalizerData.get ctxt)) delsimps del_ths addsimps add_ths) 
   993  THEN'
   994  CSUBGOAL (fn (p, i) =>
   995   case get_ring_ideal_convs ctxt p of
   996    NONE => no_tac
   997  | SOME thy => 
   998   let
   999    fun poly_exists_tac {asms = asms, concl = concl, prems = prems,
  1000             params = params, context = ctxt, schematics = scs} = 
  1001     let
  1002      val (evs,bod) = strip_exists (Thm.dest_arg concl)
  1003      val ps = map_filter (try (lhs o Thm.dest_arg)) asms 
  1004      val cfs = (map swap o #multi_ideal thy evs ps) 
  1005                    (map Thm.dest_arg1 (conjuncts bod))
  1006      val ws = map (exitac o AList.lookup op aconvc cfs) evs
  1007     in EVERY (rev ws) THEN Method.insert_tac prems 1 
  1008         THEN ring_tac add_ths del_ths ctxt 1
  1009    end
  1010   in  
  1011      clarify_tac @{claset} i 
  1012      THEN Object_Logic.full_atomize_tac i 
  1013      THEN asm_full_simp_tac (Simplifier.context ctxt (#poly_eq_ss thy)) i 
  1014      THEN clarify_tac @{claset} i 
  1015      THEN (REPEAT (CONVERSION (#unwind_conv thy) i))
  1016      THEN SUBPROOF poly_exists_tac ctxt i
  1017   end
  1018  handle TERM _ => no_tac
  1019      | CTERM _ => no_tac
  1020      | THM _ => no_tac); 
  1021 end;
  1022 
  1023 fun algebra_tac add_ths del_ths ctxt i = 
  1024  ring_tac add_ths del_ths ctxt i ORELSE ideal_tac add_ths del_ths ctxt i
  1025  
  1026  
  1027 
  1028 end;