src/Provers/Arith/fast_lin_arith.ML
author wenzelm
Tue May 07 14:26:32 2002 +0200 (2002-05-07)
changeset 13105 3d1e7a199bdc
parent 12932 3bda5306d262
child 13186 ef8ed6adcb38
permissions -rw-r--r--
use eq_thm_prop instead of slightly inadequate eq_thm;
nipkow@5982
     1
(*  Title:      Provers/Arith/fast_lin_arith.ML
nipkow@5982
     2
    ID:         $Id$
nipkow@5982
     3
    Author:     Tobias Nipkow
nipkow@5982
     4
    Copyright   1998  TU Munich
nipkow@5982
     5
nipkow@6062
     6
A generic linear arithmetic package.
nipkow@6102
     7
It provides two tactics
nipkow@6102
     8
nipkow@5982
     9
    lin_arith_tac:         int -> tactic
nipkow@5982
    10
cut_lin_arith_tac: thms -> int -> tactic
nipkow@6102
    11
nipkow@6102
    12
and a simplification procedure
nipkow@6102
    13
nipkow@6102
    14
    lin_arith_prover: Sign.sg -> thm list -> term -> thm option
nipkow@6102
    15
nipkow@6102
    16
Only take premises and conclusions into account that are already (negated)
nipkow@6102
    17
(in)equations. lin_arith_prover tries to prove or disprove the term.
nipkow@5982
    18
*)
nipkow@5982
    19
paulson@9073
    20
(* Debugging: set Fast_Arith.trace *)
nipkow@7582
    21
nipkow@5982
    22
(*** Data needed for setting up the linear arithmetic package ***)
nipkow@5982
    23
nipkow@6102
    24
signature LIN_ARITH_LOGIC =
nipkow@6102
    25
sig
nipkow@6102
    26
  val conjI:		thm
nipkow@6102
    27
  val ccontr:           thm (* (~ P ==> False) ==> P *)
nipkow@6102
    28
  val neqE:             thm (* [| m ~= n; m < n ==> P; n < m ==> P |] ==> P *)
nipkow@6102
    29
  val notI:             thm (* (P ==> False) ==> ~ P *)
nipkow@6110
    30
  val not_lessD:        thm (* ~(m < n) ==> n <= m *)
nipkow@6128
    31
  val not_leD:          thm (* ~(m <= n) ==> n < m *)
nipkow@6102
    32
  val sym:		thm (* x = y ==> y = x *)
nipkow@6102
    33
  val mk_Eq: thm -> thm
nipkow@6102
    34
  val mk_Trueprop: term -> term
nipkow@6102
    35
  val neg_prop: term -> term
nipkow@6102
    36
  val is_False: thm -> bool
nipkow@6128
    37
  val is_nat: typ list * term -> bool
nipkow@6128
    38
  val mk_nat_thm: Sign.sg -> term -> thm
nipkow@6102
    39
end;
nipkow@6102
    40
(*
nipkow@6102
    41
mk_Eq(~in) = `in == False'
nipkow@6102
    42
mk_Eq(in) = `in == True'
nipkow@6102
    43
where `in' is an (in)equality.
nipkow@6102
    44
nipkow@6102
    45
neg_prop(t) = neg if t is wrapped up in Trueprop and
nipkow@6102
    46
  nt is the (logically) negated version of t, where the negation
nipkow@6102
    47
  of a negative term is the term itself (no double negation!);
nipkow@6128
    48
nipkow@6128
    49
is_nat(parameter-types,t) =  t:nat
nipkow@6128
    50
mk_nat_thm(t) = "0 <= t"
nipkow@6102
    51
*)
nipkow@6102
    52
nipkow@5982
    53
signature LIN_ARITH_DATA =
nipkow@5982
    54
sig
nipkow@6128
    55
  val decomp:
nipkow@10691
    56
    Sign.sg -> term -> ((term*rat)list * rat * string * (term*rat)list * rat * bool)option
nipkow@10691
    57
  val number_of: int * typ -> term
nipkow@5982
    58
end;
nipkow@5982
    59
(*
nipkow@7551
    60
decomp(`x Rel y') should yield (p,i,Rel,q,j,d)
nipkow@5982
    61
   where Rel is one of "<", "~<", "<=", "~<=" and "=" and
nipkow@5982
    62
         p/q is the decomposition of the sum terms x/y into a list
nipkow@7551
    63
         of summand * multiplicity pairs and a constant summand and
nipkow@7551
    64
         d indicates if the domain is discrete.
nipkow@5982
    65
wenzelm@9420
    66
ss must reduce contradictory <= to False.
nipkow@5982
    67
   It should also cancel common summands to keep <= reduced;
nipkow@5982
    68
   otherwise <= can grow to massive proportions.
nipkow@5982
    69
*)
nipkow@5982
    70
nipkow@6062
    71
signature FAST_LIN_ARITH =
nipkow@6062
    72
sig
wenzelm@9420
    73
  val setup: (theory -> theory) list
nipkow@10691
    74
  val map_data: ({add_mono_thms: thm list, mult_mono_thms: (thm*cterm)list, inj_thms: thm list,
nipkow@10575
    75
                 lessD: thm list, simpset: Simplifier.simpset}
nipkow@10691
    76
                 -> {add_mono_thms: thm list, mult_mono_thms: (thm*cterm)list, inj_thms: thm list,
nipkow@10575
    77
                     lessD: thm list, simpset: Simplifier.simpset})
nipkow@10575
    78
                -> theory -> theory
paulson@9073
    79
  val trace           : bool ref
nipkow@6074
    80
  val lin_arith_prover: Sign.sg -> thm list -> term -> thm option
nipkow@6062
    81
  val     lin_arith_tac:             int -> tactic
nipkow@6062
    82
  val cut_lin_arith_tac: thm list -> int -> tactic
nipkow@6062
    83
end;
nipkow@6062
    84
nipkow@6102
    85
functor Fast_Lin_Arith(structure LA_Logic:LIN_ARITH_LOGIC 
nipkow@6102
    86
                       and       LA_Data:LIN_ARITH_DATA) : FAST_LIN_ARITH =
nipkow@5982
    87
struct
nipkow@5982
    88
wenzelm@9420
    89
wenzelm@9420
    90
(** theory data **)
wenzelm@9420
    91
wenzelm@9420
    92
(* data kind 'Provers/fast_lin_arith' *)
wenzelm@9420
    93
wenzelm@9420
    94
structure DataArgs =
wenzelm@9420
    95
struct
wenzelm@9420
    96
  val name = "Provers/fast_lin_arith";
nipkow@10691
    97
  type T = {add_mono_thms: thm list, mult_mono_thms: (thm*cterm)list, inj_thms: thm list,
nipkow@10575
    98
            lessD: thm list, simpset: Simplifier.simpset};
wenzelm@9420
    99
nipkow@10691
   100
  val empty = {add_mono_thms = [], mult_mono_thms = [], inj_thms = [],
nipkow@10575
   101
               lessD = [], simpset = Simplifier.empty_ss};
wenzelm@9420
   102
  val copy = I;
wenzelm@9420
   103
  val prep_ext = I;
wenzelm@9420
   104
nipkow@10691
   105
  fun merge ({add_mono_thms= add_mono_thms1, mult_mono_thms= mult_mono_thms1, inj_thms= inj_thms1,
nipkow@10575
   106
              lessD = lessD1, simpset = simpset1},
nipkow@10691
   107
             {add_mono_thms= add_mono_thms2, mult_mono_thms= mult_mono_thms2, inj_thms= inj_thms2,
nipkow@10575
   108
              lessD = lessD2, simpset = simpset2}) =
wenzelm@9420
   109
    {add_mono_thms = Drule.merge_rules (add_mono_thms1, add_mono_thms2),
wenzelm@13105
   110
     mult_mono_thms = gen_merge_lists' (Drule.eq_thm_prop o pairself fst)
wenzelm@13105
   111
       mult_mono_thms1 mult_mono_thms2,
nipkow@10575
   112
     inj_thms = Drule.merge_rules (inj_thms1, inj_thms2),
nipkow@10575
   113
     lessD = Drule.merge_rules (lessD1, lessD2),
nipkow@10575
   114
     simpset = Simplifier.merge_ss (simpset1, simpset2)};
wenzelm@9420
   115
wenzelm@9420
   116
  fun print _ _ = ();
wenzelm@9420
   117
end;
wenzelm@9420
   118
wenzelm@9420
   119
structure Data = TheoryDataFun(DataArgs);
wenzelm@9420
   120
val map_data = Data.map;
wenzelm@9420
   121
val setup = [Data.init];
wenzelm@9420
   122
wenzelm@9420
   123
wenzelm@9420
   124
nipkow@5982
   125
(*** A fast decision procedure ***)
nipkow@5982
   126
(*** Code ported from HOL Light ***)
nipkow@6056
   127
(* possible optimizations:
nipkow@6056
   128
   use (var,coeff) rep or vector rep  tp save space;
nipkow@6056
   129
   treat non-negative atoms separately rather than adding 0 <= atom
nipkow@6056
   130
*)
nipkow@5982
   131
paulson@9073
   132
val trace = ref false;
paulson@9073
   133
nipkow@5982
   134
datatype lineq_type = Eq | Le | Lt;
nipkow@5982
   135
nipkow@6056
   136
datatype injust = Asm of int
nipkow@6056
   137
                | Nat of int (* index of atom *)
nipkow@6128
   138
                | LessD of injust
nipkow@6128
   139
                | NotLessD of injust
nipkow@6128
   140
                | NotLeD of injust
nipkow@7551
   141
                | NotLeDD of injust
nipkow@5982
   142
                | Multiplied of int * injust
nipkow@10691
   143
                | Multiplied2 of int * injust
nipkow@5982
   144
                | Added of injust * injust;
nipkow@5982
   145
nipkow@5982
   146
datatype lineq = Lineq of int * lineq_type * int list * injust;
nipkow@5982
   147
nipkow@5982
   148
(* ------------------------------------------------------------------------- *)
nipkow@5982
   149
(* Calculate new (in)equality type after addition.                           *)
nipkow@5982
   150
(* ------------------------------------------------------------------------- *)
nipkow@5982
   151
nipkow@5982
   152
fun find_add_type(Eq,x) = x
nipkow@5982
   153
  | find_add_type(x,Eq) = x
nipkow@5982
   154
  | find_add_type(_,Lt) = Lt
nipkow@5982
   155
  | find_add_type(Lt,_) = Lt
nipkow@5982
   156
  | find_add_type(Le,Le) = Le;
nipkow@5982
   157
nipkow@5982
   158
(* ------------------------------------------------------------------------- *)
nipkow@5982
   159
(* Multiply out an (in)equation.                                             *)
nipkow@5982
   160
(* ------------------------------------------------------------------------- *)
nipkow@5982
   161
nipkow@5982
   162
fun multiply_ineq n (i as Lineq(k,ty,l,just)) =
nipkow@5982
   163
  if n = 1 then i
nipkow@5982
   164
  else if n = 0 andalso ty = Lt then sys_error "multiply_ineq"
nipkow@5982
   165
  else if n < 0 andalso (ty=Le orelse ty=Lt) then sys_error "multiply_ineq"
nipkow@5982
   166
  else Lineq(n * k,ty,map (apl(n,op * )) l,Multiplied(n,just));
nipkow@5982
   167
nipkow@5982
   168
(* ------------------------------------------------------------------------- *)
nipkow@5982
   169
(* Add together (in)equations.                                               *)
nipkow@5982
   170
(* ------------------------------------------------------------------------- *)
nipkow@5982
   171
nipkow@5982
   172
fun add_ineq (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
nipkow@5982
   173
  let val l = map2 (op +) (l1,l2)
nipkow@5982
   174
  in Lineq(k1+k2,find_add_type(ty1,ty2),l,Added(just1,just2)) end;
nipkow@5982
   175
nipkow@5982
   176
(* ------------------------------------------------------------------------- *)
nipkow@5982
   177
(* Elimination of variable between a single pair of (in)equations.           *)
nipkow@5982
   178
(* If they're both inequalities, 1st coefficient must be +ve, 2nd -ve.       *)
nipkow@5982
   179
(* ------------------------------------------------------------------------- *)
nipkow@5982
   180
nipkow@5982
   181
fun el 0 (h::_) = h
nipkow@5982
   182
  | el n (_::t) = el (n - 1) t
nipkow@5982
   183
  | el _ _  = sys_error "el";
nipkow@5982
   184
nipkow@5982
   185
fun elim_var v (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
nipkow@5982
   186
  let val c1 = el v l1 and c2 = el v l2
nipkow@10691
   187
      val m = lcm(abs c1,abs c2)
nipkow@5982
   188
      val m1 = m div (abs c1) and m2 = m div (abs c2)
nipkow@5982
   189
      val (n1,n2) =
nipkow@5982
   190
        if (c1 >= 0) = (c2 >= 0)
nipkow@5982
   191
        then if ty1 = Eq then (~m1,m2)
nipkow@5982
   192
             else if ty2 = Eq then (m1,~m2)
nipkow@5982
   193
                  else sys_error "elim_var"
nipkow@5982
   194
        else (m1,m2)
nipkow@5982
   195
      val (p1,p2) = if ty1=Eq andalso ty2=Eq andalso (n1 = ~1 orelse n2 = ~1)
nipkow@5982
   196
                    then (~n1,~n2) else (n1,n2)
nipkow@5982
   197
  in add_ineq (multiply_ineq n1 i1) (multiply_ineq n2 i2) end;
nipkow@5982
   198
nipkow@5982
   199
(* ------------------------------------------------------------------------- *)
nipkow@5982
   200
(* The main refutation-finding code.                                         *)
nipkow@5982
   201
(* ------------------------------------------------------------------------- *)
nipkow@5982
   202
nipkow@5982
   203
fun is_trivial (Lineq(_,_,l,_)) = forall (fn i => i=0) l;
nipkow@5982
   204
nipkow@5982
   205
fun is_answer (ans as Lineq(k,ty,l,_)) =
nipkow@5982
   206
  case ty  of Eq => k <> 0 | Le => k > 0 | Lt => k >= 0;
nipkow@5982
   207
nipkow@5982
   208
fun calc_blowup l =
nipkow@5982
   209
  let val (p,n) = partition (apl(0,op<)) (filter (apl(0,op<>)) l)
nipkow@5982
   210
  in (length p) * (length n) end;
nipkow@5982
   211
nipkow@5982
   212
(* ------------------------------------------------------------------------- *)
nipkow@5982
   213
(* Main elimination code:                                                    *)
nipkow@5982
   214
(*                                                                           *)
nipkow@5982
   215
(* (1) Looks for immediate solutions (false assertions with no variables).   *)
nipkow@5982
   216
(*                                                                           *)
nipkow@5982
   217
(* (2) If there are any equations, picks a variable with the lowest absolute *)
nipkow@5982
   218
(* coefficient in any of them, and uses it to eliminate.                     *)
nipkow@5982
   219
(*                                                                           *)
nipkow@5982
   220
(* (3) Otherwise, chooses a variable in the inequality to minimize the       *)
nipkow@5982
   221
(* blowup (number of consequences generated) and eliminates it.              *)
nipkow@5982
   222
(* ------------------------------------------------------------------------- *)
nipkow@5982
   223
nipkow@5982
   224
fun allpairs f xs ys =
nipkow@5982
   225
  flat(map (fn x => map (fn y => f x y) ys) xs);
nipkow@5982
   226
nipkow@5982
   227
fun extract_first p =
nipkow@5982
   228
  let fun extract xs (y::ys) = if p y then (Some y,xs@ys)
nipkow@5982
   229
                               else extract (y::xs) ys
nipkow@5982
   230
        | extract xs []      = (None,xs)
nipkow@5982
   231
  in extract [] end;
nipkow@5982
   232
nipkow@6056
   233
fun print_ineqs ineqs =
paulson@9073
   234
  if !trace then
wenzelm@12262
   235
     tracing(cat_lines(""::map (fn Lineq(c,t,l,_) =>
paulson@9073
   236
       string_of_int c ^
paulson@9073
   237
       (case t of Eq => " =  " | Lt=> " <  " | Le => " <= ") ^
paulson@9073
   238
       commas(map string_of_int l)) ineqs))
paulson@9073
   239
  else ();
nipkow@6056
   240
nipkow@5982
   241
fun elim ineqs =
paulson@9073
   242
  let val dummy = print_ineqs ineqs;
nipkow@6056
   243
      val (triv,nontriv) = partition is_trivial ineqs in
nipkow@5982
   244
  if not(null triv)
nipkow@5982
   245
  then case find_first is_answer triv of
nipkow@5982
   246
         None => elim nontriv | some => some
nipkow@5982
   247
  else
nipkow@5982
   248
  if null nontriv then None else
nipkow@5982
   249
  let val (eqs,noneqs) = partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
nipkow@5982
   250
  if not(null eqs) then
nipkow@5982
   251
     let val clist = foldl (fn (cs,Lineq(_,_,l,_)) => l union cs) ([],eqs)
nipkow@5982
   252
         val sclist = sort (fn (x,y) => int_ord(abs(x),abs(y)))
nipkow@5982
   253
                           (filter (fn i => i<>0) clist)
nipkow@5982
   254
         val c = hd sclist
nipkow@5982
   255
         val (Some(eq as Lineq(_,_,ceq,_)),othereqs) =
nipkow@5982
   256
               extract_first (fn Lineq(_,_,l,_) => c mem l) eqs
nipkow@5982
   257
         val v = find_index (fn k => k=c) ceq
nipkow@5982
   258
         val (ioth,roth) = partition (fn (Lineq(_,_,l,_)) => el v l = 0)
nipkow@5982
   259
                                     (othereqs @ noneqs)
nipkow@5982
   260
         val others = map (elim_var v eq) roth @ ioth
nipkow@5982
   261
     in elim others end
nipkow@5982
   262
  else
nipkow@5982
   263
  let val lists = map (fn (Lineq(_,_,l,_)) => l) noneqs
nipkow@5982
   264
      val numlist = 0 upto (length(hd lists) - 1)
nipkow@5982
   265
      val coeffs = map (fn i => map (el i) lists) numlist
nipkow@5982
   266
      val blows = map calc_blowup coeffs
nipkow@5982
   267
      val iblows = blows ~~ numlist
nipkow@5982
   268
      val nziblows = filter (fn (i,_) => i<>0) iblows
nipkow@5982
   269
  in if null nziblows then None else
nipkow@5982
   270
     let val (c,v) = hd(sort (fn (x,y) => int_ord(fst(x),fst(y))) nziblows)
nipkow@5982
   271
         val (no,yes) = partition (fn (Lineq(_,_,l,_)) => el v l = 0) ineqs
nipkow@5982
   272
         val (pos,neg) = partition(fn (Lineq(_,_,l,_)) => el v l > 0) yes
nipkow@5982
   273
     in elim (no @ allpairs (elim_var v) pos neg) end
nipkow@5982
   274
  end
nipkow@5982
   275
  end
nipkow@5982
   276
  end;
nipkow@5982
   277
nipkow@5982
   278
(* ------------------------------------------------------------------------- *)
nipkow@5982
   279
(* Translate back a proof.                                                   *)
nipkow@5982
   280
(* ------------------------------------------------------------------------- *)
nipkow@5982
   281
paulson@9073
   282
fun trace_thm msg th = 
wenzelm@12262
   283
    if !trace then (tracing msg; tracing (Display.string_of_thm th); th) else th;
paulson@9073
   284
paulson@9073
   285
fun trace_msg msg = 
wenzelm@12262
   286
    if !trace then tracing msg else ();
paulson@9073
   287
nipkow@6056
   288
(* FIXME OPTIMIZE!!!!
nipkow@6056
   289
   Addition/Multiplication need i*t representation rather than t+t+...
nipkow@10691
   290
   Get rid of Mulitplied(2). For Nat LA_Data.number_of should return Suc^n
nipkow@10691
   291
   because Numerals are not known early enough.
nipkow@6056
   292
nipkow@6056
   293
Simplification may detect a contradiction 'prematurely' due to type
nipkow@6056
   294
information: n+1 <= 0 is simplified to False and does not need to be crossed
nipkow@6056
   295
with 0 <= n.
nipkow@6056
   296
*)
nipkow@6056
   297
local
nipkow@6056
   298
 exception FalseE of thm
nipkow@6056
   299
in
nipkow@6074
   300
fun mkthm sg asms just =
nipkow@10691
   301
  let val {add_mono_thms, mult_mono_thms, inj_thms, lessD, simpset} = Data.get_sg sg;
wenzelm@9420
   302
      val atoms = foldl (fn (ats,(lhs,_,_,rhs,_,_)) =>
nipkow@6056
   303
                            map fst lhs  union  (map fst rhs  union  ats))
wenzelm@9420
   304
                        ([], mapfilter (LA_Data.decomp sg o concl_of) asms)
nipkow@6056
   305
nipkow@10575
   306
      fun add2 thm1 thm2 =
nipkow@6102
   307
        let val conj = thm1 RS (thm2 RS LA_Logic.conjI)
nipkow@10575
   308
        in get_first (fn th => Some(conj RS th) handle _ => None) add_mono_thms
nipkow@5982
   309
        end;
nipkow@5982
   310
nipkow@10575
   311
      fun try_add [] _ = None
nipkow@10575
   312
        | try_add (thm1::thm1s) thm2 = case add2 thm1 thm2 of
nipkow@10575
   313
             None => try_add thm1s thm2 | some => some;
nipkow@10575
   314
nipkow@10575
   315
      fun addthms thm1 thm2 =
nipkow@10575
   316
        case add2 thm1 thm2 of
nipkow@10575
   317
          None => (case try_add ([thm1] RL inj_thms) thm2 of
nipkow@10575
   318
                     None => the(try_add ([thm2] RL inj_thms) thm1)
nipkow@10575
   319
                   | Some thm => thm)
nipkow@10575
   320
        | Some thm => thm;
nipkow@10575
   321
nipkow@5982
   322
      fun multn(n,thm) =
nipkow@5982
   323
        let fun mul(i,th) = if i=1 then th else mul(i-1, addthms thm th)
nipkow@6102
   324
        in if n < 0 then mul(~n,thm) RS LA_Logic.sym else mul(n,thm) end;
nipkow@5982
   325
nipkow@10691
   326
      fun multn2(n,thm) =
nipkow@10691
   327
        let val Some(mth,cv) =
nipkow@10691
   328
              get_first (fn (th,cv) => Some(thm RS th,cv) handle _ => None) mult_mono_thms
nipkow@10691
   329
            val ct = cterm_of sg (LA_Data.number_of(n,#T(rep_cterm cv)))
nipkow@10691
   330
        in instantiate ([],[(cv,ct)]) mth end
nipkow@10691
   331
nipkow@6056
   332
      fun simp thm =
nipkow@12932
   333
        let val thm' = trace_thm "Simplified:" (full_simplify simpset thm)
nipkow@6102
   334
        in if LA_Logic.is_False thm' then raise FalseE thm' else thm' end
nipkow@6056
   335
paulson@9073
   336
      fun mk(Asm i) = trace_thm "Asm" (nth_elem(i,asms))
paulson@9073
   337
        | mk(Nat(i)) = (trace_msg "Nat";
paulson@9073
   338
			LA_Logic.mk_nat_thm sg (nth_elem(i,atoms)))
wenzelm@9420
   339
        | mk(LessD(j)) = trace_thm "L" (hd([mk j] RL lessD))
paulson@9073
   340
        | mk(NotLeD(j)) = trace_thm "NLe" (mk j RS LA_Logic.not_leD)
wenzelm@9420
   341
        | mk(NotLeDD(j)) = trace_thm "NLeD" (hd([mk j RS LA_Logic.not_leD] RL lessD))
paulson@9073
   342
        | mk(NotLessD(j)) = trace_thm "NL" (mk j RS LA_Logic.not_lessD)
paulson@9073
   343
        | mk(Added(j1,j2)) = simp (trace_thm "+" (addthms (mk j1) (mk j2)))
nipkow@10717
   344
        | mk(Multiplied(n,j)) = (trace_msg("*"^string_of_int n); trace_thm "*" (multn(n,mk j)))
nipkow@10717
   345
        | mk(Multiplied2(n,j)) = simp (trace_msg("**"^string_of_int n); trace_thm "**" (multn2(n,mk j)))
nipkow@5982
   346
paulson@9073
   347
  in trace_msg "mkthm";
nipkow@12932
   348
     let val thm = trace_thm "Final thm:" (mk just)
nipkow@12932
   349
     in let val fls = simplify simpset thm
nipkow@12932
   350
        in trace_thm "After simplification:" fls; fls
nipkow@12932
   351
        end
nipkow@12932
   352
     end handle FalseE thm => (trace_thm "False reached early:" thm; thm)
nipkow@12932
   353
  end
nipkow@6056
   354
end;
nipkow@5982
   355
nipkow@5982
   356
fun coeff poly atom = case assoc(poly,atom) of None => 0 | Some i => i;
nipkow@5982
   357
nipkow@10691
   358
fun lcms is = foldl lcm (1,is);
nipkow@10691
   359
nipkow@10691
   360
fun integ(rlhs,r,rel,rrhs,s,d) =
nipkow@10691
   361
let val (rn,rd) = rep_rat r and (sn,sd) = rep_rat s
nipkow@10691
   362
    val m = lcms(map (abs o snd o rep_rat) (r :: s :: map snd rlhs @ map snd rrhs))
nipkow@10691
   363
    fun mult(t,r) = let val (i,j) = rep_rat r in (t,i * (m div j)) end
nipkow@12932
   364
in (m,(map mult rlhs, rn*(m div rd), rel, map mult rrhs, sn*(m div sd), d)) end
nipkow@10691
   365
nipkow@5982
   366
fun mklineq atoms =
nipkow@5982
   367
  let val n = length atoms in
nipkow@10691
   368
    fn (item,k) =>
nipkow@10691
   369
    let val (m,(lhs,i,rel,rhs,j,discrete)) = integ item
nipkow@10691
   370
        val lhsa = map (coeff lhs) atoms
nipkow@5982
   371
        and rhsa = map (coeff rhs) atoms
nipkow@5982
   372
        val diff = map2 (op -) (rhsa,lhsa)
nipkow@5982
   373
        val c = i-j
nipkow@6056
   374
        val just = Asm k
nipkow@10691
   375
        fun lineq(c,le,cs,j) = Some(Lineq(c,le,cs, if m=1 then j else Multiplied2(m,j)))
nipkow@5982
   376
    in case rel of
nipkow@10691
   377
        "<="   => lineq(c,Le,diff,just)
nipkow@7551
   378
       | "~<=" => if discrete
nipkow@10691
   379
                  then lineq(1-c,Le,map (op ~) diff,NotLeDD(just))
nipkow@10691
   380
                  else lineq(~c,Lt,map (op ~) diff,NotLeD(just))
nipkow@7551
   381
       | "<"   => if discrete
nipkow@10691
   382
                  then lineq(c+1,Le,diff,LessD(just))
nipkow@10691
   383
                  else lineq(c,Lt,diff,just)
nipkow@10691
   384
       | "~<"  => lineq(~c,Le,map (op~) diff,NotLessD(just))
nipkow@10691
   385
       | "="   => lineq(c,Eq,diff,just)
nipkow@5982
   386
       | "~="  => None
nipkow@5982
   387
       | _     => sys_error("mklineq" ^ rel)   
nipkow@5982
   388
    end
nipkow@5982
   389
  end;
nipkow@5982
   390
nipkow@6056
   391
fun mknat pTs ixs (atom,i) =
nipkow@6128
   392
  if LA_Logic.is_nat(pTs,atom)
nipkow@6056
   393
  then let val l = map (fn j => if j=i then 1 else 0) ixs
nipkow@6056
   394
       in Some(Lineq(0,Le,l,Nat(i))) end
nipkow@6056
   395
  else None
nipkow@6056
   396
nipkow@6056
   397
fun abstract pTs items =
nipkow@7551
   398
  let val atoms = foldl (fn (ats,((lhs,_,_,rhs,_,_),_)) =>
nipkow@5982
   399
                            (map fst lhs) union ((map fst rhs) union ats))
nipkow@5982
   400
                        ([],items)
nipkow@6056
   401
      val ixs = 0 upto (length(atoms)-1)
nipkow@6056
   402
      val iatoms = atoms ~~ ixs
nipkow@6056
   403
  in mapfilter (mklineq atoms) items @ mapfilter (mknat pTs ixs) iatoms end;
nipkow@5982
   404
nipkow@5982
   405
(* Ordinary refutation *)
nipkow@6074
   406
fun refute1(pTs,items) =
nipkow@6074
   407
  (case elim (abstract pTs items) of
nipkow@6074
   408
       None => []
nipkow@6074
   409
     | Some(Lineq(_,_,_,j)) => [j]);
nipkow@6074
   410
nipkow@6074
   411
fun refute1_tac(i,just) =
nipkow@6074
   412
  fn state =>
nipkow@6074
   413
    let val sg = #sign(rep_thm state)
nipkow@6102
   414
    in resolve_tac [LA_Logic.notI,LA_Logic.ccontr] i THEN
nipkow@6074
   415
       METAHYPS (fn asms => rtac (mkthm sg asms just) 1) i
nipkow@6074
   416
    end
nipkow@6074
   417
    state;
nipkow@5982
   418
nipkow@5982
   419
(* Double refutation caused by equality in conclusion *)
nipkow@7551
   420
fun refute2(pTs,items, (rhs,i,_,lhs,j,d), nHs) =
nipkow@7551
   421
  (case elim (abstract pTs (items@[((rhs,i,"<",lhs,j,d),nHs)])) of
nipkow@6074
   422
    None => []
nipkow@5982
   423
  | Some(Lineq(_,_,_,j1)) =>
nipkow@7551
   424
      (case elim (abstract pTs (items@[((lhs,j,"<",rhs,i,d),nHs)])) of
nipkow@6074
   425
        None => []
nipkow@6074
   426
      | Some(Lineq(_,_,_,j2)) => [j1,j2]));
nipkow@6074
   427
nipkow@6074
   428
fun refute2_tac(i,just1,just2) =
nipkow@6074
   429
  fn state => 
nipkow@6074
   430
    let val sg = #sign(rep_thm state)
nipkow@6102
   431
    in rtac LA_Logic.ccontr i THEN rotate_tac ~1 i THEN etac LA_Logic.neqE i THEN
nipkow@6074
   432
       METAHYPS (fn asms => rtac (mkthm sg asms just1) 1) i THEN
nipkow@6074
   433
       METAHYPS (fn asms => rtac (mkthm sg asms just2) 1) i
nipkow@6074
   434
    end
nipkow@6074
   435
    state;
nipkow@6074
   436
wenzelm@9420
   437
fun prove sg (pTs,Hs,concl) =
nipkow@6074
   438
let val nHs = length Hs
nipkow@6074
   439
    val ixHs = Hs ~~ (0 upto (nHs-1))
wenzelm@9420
   440
    val Hitems = mapfilter (fn (h,i) => case LA_Data.decomp sg h of
nipkow@6074
   441
                                 None => None | Some(it) => Some(it,i)) ixHs
wenzelm@9420
   442
in case LA_Data.decomp sg concl of
nipkow@6074
   443
     None => if null Hitems then [] else refute1(pTs,Hitems)
nipkow@7551
   444
   | Some(citem as (r,i,rel,l,j,d)) =>
nipkow@6074
   445
       if rel = "="
nipkow@6074
   446
       then refute2(pTs,Hitems,citem,nHs)
nipkow@6074
   447
       else let val neg::rel0 = explode rel
nipkow@6074
   448
                val nrel = if neg = "~" then implode rel0 else "~"^rel
nipkow@7551
   449
            in refute1(pTs, Hitems@[((r,i,nrel,l,j,d),nHs)]) end
nipkow@6074
   450
end;
nipkow@5982
   451
nipkow@5982
   452
(*
nipkow@5982
   453
Fast but very incomplete decider. Only premises and conclusions
nipkow@5982
   454
that are already (negated) (in)equations are taken into account.
nipkow@5982
   455
*)
wenzelm@9420
   456
fun lin_arith_tac i st = SUBGOAL (fn (A,n) =>
nipkow@6056
   457
  let val pTs = rev(map snd (Logic.strip_params A))
nipkow@6056
   458
      val Hs = Logic.strip_assums_hyp A
nipkow@6074
   459
      val concl = Logic.strip_assums_concl A
nipkow@12932
   460
  in trace_thm ("Trying to refute subgoal " ^ string_of_int i) st;
nipkow@12932
   461
     case prove (Thm.sign_of_thm st) (pTs,Hs,concl) of
nipkow@6074
   462
       [j] => refute1_tac(n,j)
nipkow@6074
   463
     | [j1,j2] => refute2_tac(n,j1,j2)
nipkow@6074
   464
     | _ => no_tac
wenzelm@9420
   465
  end) i st;
nipkow@5982
   466
nipkow@5982
   467
fun cut_lin_arith_tac thms i = cut_facts_tac thms i THEN lin_arith_tac i;
nipkow@5982
   468
nipkow@6079
   469
fun prover1(just,sg,thms,concl,pos) =
nipkow@6102
   470
let val nconcl = LA_Logic.neg_prop concl
nipkow@6074
   471
    val cnconcl = cterm_of sg nconcl
nipkow@6074
   472
    val Fthm = mkthm sg (thms @ [assume cnconcl]) just
nipkow@6102
   473
    val contr = if pos then LA_Logic.ccontr else LA_Logic.notI
nipkow@6102
   474
in Some(LA_Logic.mk_Eq ((implies_intr cnconcl Fthm) COMP contr)) end
nipkow@6074
   475
handle _ => None;
nipkow@6074
   476
nipkow@6074
   477
(* handle thm with equality conclusion *)
nipkow@6074
   478
fun prover2(just1,just2,sg,thms,concl) =
nipkow@6102
   479
let val nconcl = LA_Logic.neg_prop concl (* m ~= n *)
nipkow@6074
   480
    val cnconcl = cterm_of sg nconcl
nipkow@6074
   481
    val neqthm = assume cnconcl
nipkow@6102
   482
    val casethm = neqthm COMP LA_Logic.neqE (* [|m<n ==> R; n<m ==> R|] ==> R *)
nipkow@6074
   483
    val [lessimp1,lessimp2] = prems_of casethm
nipkow@6074
   484
    val less1 = fst(Logic.dest_implies lessimp1) (* m<n *)
nipkow@6074
   485
    and less2 = fst(Logic.dest_implies lessimp2) (* n<m *)
nipkow@6074
   486
    val cless1 = cterm_of sg less1 and cless2 = cterm_of sg less2
nipkow@6074
   487
    val thm1 = mkthm sg (thms @ [assume cless1]) just1
nipkow@6074
   488
    and thm2 = mkthm sg (thms @ [assume cless2]) just2
nipkow@6074
   489
    val dthm1 = implies_intr cless1 thm1 and dthm2 = implies_intr cless2 thm2
nipkow@6074
   490
    val thm = dthm2 COMP (dthm1 COMP casethm)
nipkow@6102
   491
in Some(LA_Logic.mk_Eq ((implies_intr cnconcl thm) COMP LA_Logic.ccontr)) end
nipkow@6074
   492
handle _ => None;
nipkow@6074
   493
nipkow@6079
   494
(* PRE: concl is not negated! *)
nipkow@6074
   495
fun lin_arith_prover sg thms concl =
nipkow@6074
   496
let val Hs = map (#prop o rep_thm) thms
nipkow@6102
   497
    val Tconcl = LA_Logic.mk_Trueprop concl
wenzelm@9420
   498
in case prove sg ([],Hs,Tconcl) of
nipkow@6079
   499
     [j] => prover1(j,sg,thms,Tconcl,true)
nipkow@6074
   500
   | [j1,j2] => prover2(j1,j2,sg,thms,Tconcl)
nipkow@6102
   501
   | _ => let val nTconcl = LA_Logic.neg_prop Tconcl
wenzelm@9420
   502
          in case prove sg ([],Hs,nTconcl) of
nipkow@6079
   503
               [j] => prover1(j,sg,thms,nTconcl,false)
nipkow@6079
   504
               (* [_,_] impossible because of negation *)
nipkow@6079
   505
             | _ => None
nipkow@6079
   506
          end
nipkow@5982
   507
end;
nipkow@6074
   508
nipkow@6074
   509
end;