src/Provers/Arith/fast_lin_arith.ML
author webertj
Mon Jul 31 15:29:36 2006 +0200 (2006-07-31)
changeset 20268 1fe9aed8fcac
parent 20254 58b71535ed00
child 20276 d94dc40673b1
permissions -rw-r--r--
code reformatted
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
wenzelm@16458
    14
    lin_arith_prover: theory -> simpset -> 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
webertj@20217
    26
  val conjI:            thm (* P ==> Q ==> P & Q *)
nipkow@6102
    27
  val ccontr:           thm (* (~ P ==> False) ==> P *)
nipkow@6102
    28
  val notI:             thm (* (P ==> False) ==> ~ P *)
nipkow@6110
    29
  val not_lessD:        thm (* ~(m < n) ==> n <= m *)
nipkow@6128
    30
  val not_leD:          thm (* ~(m <= n) ==> n < m *)
webertj@20217
    31
  val sym:              thm (* x = y ==> y = x *)
nipkow@6102
    32
  val mk_Eq: thm -> thm
nipkow@16735
    33
  val atomize: thm -> thm list
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
wenzelm@16458
    38
  val mk_nat_thm: theory -> 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
webertj@19318
    45
neg_prop(t) = neg  if t is wrapped up in Trueprop and
webertj@19318
    46
  neg 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
webertj@20268
    55
  (* internal representation of linear (in-)equations: *)
webertj@20268
    56
  type decompT = (term * Rat.rat) list * Rat.rat * string * (term * Rat.rat) list * Rat.rat * bool
webertj@20217
    57
  val decomp: theory -> term -> decompT option
webertj@20268
    58
  (* preprocessing, performed on a representation of subgoals as list of premises: *)
webertj@20268
    59
  val pre_decomp: theory -> typ list * term list -> (typ list * term list) list
webertj@20268
    60
  (* preprocessing, performed on the goal -- must do the same as 'pre_decomp': *)
webertj@20268
    61
  val pre_tac   : int -> Tactical.tactic
nipkow@16358
    62
  val number_of: IntInf.int * typ -> term
nipkow@5982
    63
end;
nipkow@5982
    64
(*
nipkow@7551
    65
decomp(`x Rel y') should yield (p,i,Rel,q,j,d)
nipkow@5982
    66
   where Rel is one of "<", "~<", "<=", "~<=" and "=" and
webertj@20217
    67
         p (q, respectively) is the decomposition of the sum term x
webertj@20217
    68
         (y, respectively) into a list of summand * multiplicity
webertj@20217
    69
         pairs and a constant summand and d indicates if the domain
webertj@20217
    70
         is discrete.
webertj@20217
    71
webertj@20217
    72
The relationship between pre_decomp and pre_tac is somewhat tricky.  The
webertj@20217
    73
internal representation of a subgoal and the corresponding theorem must
webertj@20217
    74
be modified by pre_decomp (pre_tac, resp.) in a corresponding way.  See
webertj@20217
    75
the comment for split_items below.  (This is even necessary for eta- and
webertj@20217
    76
beta-equivalent modifications, as some of the lin. arith. code is not
webertj@20217
    77
insensitive to them.)
nipkow@5982
    78
wenzelm@9420
    79
ss must reduce contradictory <= to False.
nipkow@5982
    80
   It should also cancel common summands to keep <= reduced;
nipkow@5982
    81
   otherwise <= can grow to massive proportions.
nipkow@5982
    82
*)
nipkow@5982
    83
nipkow@6062
    84
signature FAST_LIN_ARITH =
nipkow@6062
    85
sig
wenzelm@18708
    86
  val setup: theory -> theory
nipkow@15184
    87
  val map_data: ({add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
nipkow@15922
    88
                 lessD: thm list, neqE: thm list, simpset: Simplifier.simpset}
nipkow@15184
    89
                 -> {add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
nipkow@15922
    90
                     lessD: thm list, neqE: thm list, simpset: Simplifier.simpset})
nipkow@10575
    91
                -> theory -> theory
webertj@19314
    92
  val trace: bool ref
nipkow@14510
    93
  val fast_arith_neq_limit: int ref
wenzelm@16458
    94
  val lin_arith_prover: theory -> simpset -> term -> thm option
wenzelm@17892
    95
  val     lin_arith_tac:    bool -> int -> tactic
wenzelm@17613
    96
  val cut_lin_arith_tac: simpset -> int -> tactic
nipkow@6062
    97
end;
nipkow@6062
    98
nipkow@6102
    99
functor Fast_Lin_Arith(structure LA_Logic:LIN_ARITH_LOGIC 
nipkow@6102
   100
                       and       LA_Data:LIN_ARITH_DATA) : FAST_LIN_ARITH =
nipkow@5982
   101
struct
nipkow@5982
   102
wenzelm@9420
   103
wenzelm@9420
   104
(** theory data **)
wenzelm@9420
   105
wenzelm@9420
   106
(* data kind 'Provers/fast_lin_arith' *)
wenzelm@9420
   107
wenzelm@16458
   108
structure Data = TheoryDataFun
wenzelm@16458
   109
(struct
wenzelm@9420
   110
  val name = "Provers/fast_lin_arith";
nipkow@15184
   111
  type T = {add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
nipkow@15922
   112
            lessD: thm list, neqE: thm list, simpset: Simplifier.simpset};
wenzelm@9420
   113
nipkow@10691
   114
  val empty = {add_mono_thms = [], mult_mono_thms = [], inj_thms = [],
nipkow@15922
   115
               lessD = [], neqE = [], simpset = Simplifier.empty_ss};
wenzelm@9420
   116
  val copy = I;
wenzelm@16458
   117
  val extend = I;
wenzelm@9420
   118
wenzelm@16458
   119
  fun merge _
wenzelm@16458
   120
    ({add_mono_thms= add_mono_thms1, mult_mono_thms= mult_mono_thms1, inj_thms= inj_thms1,
wenzelm@16458
   121
      lessD = lessD1, neqE=neqE1, simpset = simpset1},
wenzelm@16458
   122
     {add_mono_thms= add_mono_thms2, mult_mono_thms= mult_mono_thms2, inj_thms= inj_thms2,
wenzelm@16458
   123
      lessD = lessD2, neqE=neqE2, simpset = simpset2}) =
wenzelm@9420
   124
    {add_mono_thms = Drule.merge_rules (add_mono_thms1, add_mono_thms2),
nipkow@15184
   125
     mult_mono_thms = Drule.merge_rules (mult_mono_thms1, mult_mono_thms2),
nipkow@10575
   126
     inj_thms = Drule.merge_rules (inj_thms1, inj_thms2),
nipkow@10575
   127
     lessD = Drule.merge_rules (lessD1, lessD2),
nipkow@15922
   128
     neqE = Drule.merge_rules (neqE1, neqE2),
nipkow@10575
   129
     simpset = Simplifier.merge_ss (simpset1, simpset2)};
wenzelm@9420
   130
wenzelm@9420
   131
  fun print _ _ = ();
wenzelm@16458
   132
end);
wenzelm@9420
   133
wenzelm@9420
   134
val map_data = Data.map;
wenzelm@18708
   135
val setup = Data.init;
wenzelm@9420
   136
wenzelm@9420
   137
wenzelm@9420
   138
nipkow@5982
   139
(*** A fast decision procedure ***)
nipkow@5982
   140
(*** Code ported from HOL Light ***)
nipkow@6056
   141
(* possible optimizations:
nipkow@6056
   142
   use (var,coeff) rep or vector rep  tp save space;
nipkow@6056
   143
   treat non-negative atoms separately rather than adding 0 <= atom
nipkow@6056
   144
*)
nipkow@5982
   145
paulson@9073
   146
val trace = ref false;
paulson@9073
   147
nipkow@5982
   148
datatype lineq_type = Eq | Le | Lt;
nipkow@5982
   149
nipkow@6056
   150
datatype injust = Asm of int
nipkow@6056
   151
                | Nat of int (* index of atom *)
nipkow@6128
   152
                | LessD of injust
nipkow@6128
   153
                | NotLessD of injust
nipkow@6128
   154
                | NotLeD of injust
nipkow@7551
   155
                | NotLeDD of injust
nipkow@16358
   156
                | Multiplied of IntInf.int * injust
nipkow@16358
   157
                | Multiplied2 of IntInf.int * injust
nipkow@5982
   158
                | Added of injust * injust;
nipkow@5982
   159
nipkow@16358
   160
datatype lineq = Lineq of IntInf.int * lineq_type * IntInf.int list * injust;
nipkow@5982
   161
nipkow@13498
   162
fun el 0 (h::_) = h
nipkow@13498
   163
  | el n (_::t) = el (n - 1) t
nipkow@13498
   164
  | el _ _  = sys_error "el";
nipkow@13498
   165
nipkow@13498
   166
(* ------------------------------------------------------------------------- *)
nipkow@13498
   167
(* Finding a (counter) example from the trace of a failed elimination        *)
nipkow@13498
   168
(* ------------------------------------------------------------------------- *)
nipkow@13498
   169
(* Examples are represented as rational numbers,                             *)
nipkow@13498
   170
(* Dont blame John Harrison for this code - it is entirely mine. TN          *)
nipkow@13498
   171
nipkow@13498
   172
exception NoEx;
nipkow@13498
   173
nipkow@14372
   174
(* Coding: (i,true,cs) means i <= cs and (i,false,cs) means i < cs.
nipkow@14372
   175
   In general, true means the bound is included, false means it is excluded.
nipkow@14372
   176
   Need to know if it is a lower or upper bound for unambiguous interpretation!
nipkow@14372
   177
*)
nipkow@14372
   178
nipkow@14372
   179
fun elim_eqns(ineqs,Lineq(i,Le,cs,_)) = (i,true,cs)::ineqs
nipkow@14372
   180
  | elim_eqns(ineqs,Lineq(i,Eq,cs,_)) = (i,true,cs)::(~i,true,map ~ cs)::ineqs
nipkow@14372
   181
  | elim_eqns(ineqs,Lineq(i,Lt,cs,_)) = (i,false,cs)::ineqs;
nipkow@13498
   182
nipkow@13498
   183
(* PRE: ex[v] must be 0! *)
haftmann@17951
   184
fun eval (ex:Rat.rat list) v (a:IntInf.int,le,cs:IntInf.int list) =
haftmann@17951
   185
  let val rs = map Rat.rat_of_intinf cs
haftmann@17951
   186
      val rsum = Library.foldl Rat.add (Rat.zero, map Rat.mult (rs ~~ ex))
haftmann@17951
   187
  in (Rat.mult (Rat.add(Rat.rat_of_intinf a,Rat.neg rsum), Rat.inv(el v rs)), le) end;
nipkow@14372
   188
(* If el v rs < 0, le should be negated.
nipkow@14372
   189
   Instead this swap is taken into account in ratrelmin2.
nipkow@14372
   190
*)
nipkow@13498
   191
nipkow@14372
   192
fun ratrelmin2(x as (r,ler),y as (s,les)) =
haftmann@17951
   193
  if r=s then (r, (not ler) andalso (not les)) else if Rat.le(r,s) then x else y;
nipkow@14372
   194
fun ratrelmax2(x as (r,ler),y as (s,les)) =
haftmann@17951
   195
  if r=s then (r,ler andalso les) else if Rat.le(r,s) then y else x;
nipkow@13498
   196
nipkow@14372
   197
val ratrelmin = foldr1 ratrelmin2;
nipkow@14372
   198
val ratrelmax = foldr1 ratrelmax2;
nipkow@13498
   199
nipkow@14372
   200
fun ratexact up (r,exact) =
nipkow@14372
   201
  if exact then r else
haftmann@17951
   202
  let val (p,q) = Rat.quotient_of_rat r
haftmann@17951
   203
      val nth = Rat.inv(Rat.rat_of_intinf q)
haftmann@17951
   204
  in Rat.add(r,if up then nth else Rat.neg nth) end;
nipkow@14372
   205
haftmann@17951
   206
fun ratmiddle(r,s) = Rat.mult(Rat.add(r,s),Rat.inv(Rat.rat_of_int 2));
nipkow@14372
   207
webertj@20217
   208
fun choose2 d ((lb, exactl), (ub, exactu)) =
webertj@20217
   209
  if Rat.le (lb, Rat.zero) andalso (lb <> Rat.zero orelse exactl) andalso
webertj@20217
   210
     Rat.le (Rat.zero, ub) andalso (ub <> Rat.zero orelse exactu)
haftmann@17951
   211
  then Rat.zero else
nipkow@14372
   212
  if not d
haftmann@17951
   213
  then (if Rat.ge0 lb
webertj@20217
   214
        then if exactl then lb else ratmiddle (lb, ub)
webertj@20217
   215
        else if exactu then ub else ratmiddle (lb, ub))
nipkow@14372
   216
  else (* discrete domain, both bounds must be exact *)
haftmann@17951
   217
  if Rat.ge0 lb then let val lb' = Rat.roundup lb
webertj@20217
   218
                    in if Rat.le (lb', ub) then lb' else raise NoEx end
haftmann@17951
   219
               else let val ub' = Rat.rounddown ub
webertj@20217
   220
                    in if Rat.le (lb, ub') then ub' else raise NoEx end;
nipkow@13498
   221
webertj@20217
   222
fun findex1 discr (ex, (v, lineqs)) =
skalberg@15570
   223
  let val nz = List.filter (fn (Lineq(_,_,cs,_)) => el v cs <> 0) lineqs;
skalberg@15570
   224
      val ineqs = Library.foldl elim_eqns ([],nz)
skalberg@15570
   225
      val (ge,le) = List.partition (fn (_,_,cs) => el v cs > 0) ineqs
webertj@20217
   226
      val lb = ratrelmax (map (eval ex v) ge)
webertj@20217
   227
      val ub = ratrelmin (map (eval ex v) le)
haftmann@18011
   228
  in nth_update (v, choose2 (nth discr v) (lb, ub)) ex end;
nipkow@13498
   229
skalberg@15570
   230
fun findex discr = Library.foldl (findex1 discr);
nipkow@13498
   231
nipkow@13498
   232
fun elim1 v x =
webertj@20217
   233
  map (fn (a,le,bs) => (Rat.add (a, Rat.neg (Rat.mult (el v bs, x))), le,
haftmann@18011
   234
                        nth_update (v, Rat.zero) bs));
nipkow@13498
   235
haftmann@17951
   236
fun single_var v (_,_,cs) = (filter_out (equal Rat.zero) cs = [el v cs]);
nipkow@13498
   237
nipkow@13498
   238
(* The base case:
nipkow@13498
   239
   all variables occur only with positive or only with negative coefficients *)
nipkow@13498
   240
fun pick_vars discr (ineqs,ex) =
haftmann@17951
   241
  let val nz = filter_out (fn (_,_,cs) => forall (equal Rat.zero) cs) ineqs
nipkow@14372
   242
  in case nz of [] => ex
nipkow@14372
   243
     | (_,_,cs) :: _ =>
haftmann@17951
   244
       let val v = find_index (not o equal Rat.zero) cs
haftmann@18011
   245
           val d = nth discr v
haftmann@17951
   246
           val pos = Rat.ge0(el v cs)
skalberg@15570
   247
           val sv = List.filter (single_var v) nz
nipkow@14372
   248
           val minmax =
haftmann@17951
   249
             if pos then if d then Rat.roundup o fst o ratrelmax
nipkow@14372
   250
                         else ratexact true o ratrelmax
haftmann@17951
   251
                    else if d then Rat.rounddown o fst o ratrelmin
nipkow@14372
   252
                         else ratexact false o ratrelmin
haftmann@17951
   253
           val bnds = map (fn (a,le,bs) => (Rat.mult(a,Rat.inv(el v bs)),le)) sv
haftmann@17951
   254
           val x = minmax((Rat.zero,if pos then true else false)::bnds)
nipkow@14372
   255
           val ineqs' = elim1 v x nz
haftmann@18011
   256
           val ex' = nth_update (v, x) ex
nipkow@14372
   257
       in pick_vars discr (ineqs',ex') end
nipkow@13498
   258
  end;
nipkow@13498
   259
nipkow@13498
   260
fun findex0 discr n lineqs =
skalberg@15570
   261
  let val ineqs = Library.foldl elim_eqns ([],lineqs)
haftmann@17951
   262
      val rineqs = map (fn (a,le,cs) => (Rat.rat_of_intinf a, le, map Rat.rat_of_intinf cs))
nipkow@14372
   263
                       ineqs
haftmann@17951
   264
  in pick_vars discr (rineqs,replicate n Rat.zero) end;
nipkow@13498
   265
nipkow@13498
   266
(* ------------------------------------------------------------------------- *)
nipkow@13498
   267
(* End of counter example finder. The actual decision procedure starts here. *)
nipkow@13498
   268
(* ------------------------------------------------------------------------- *)
nipkow@13498
   269
nipkow@5982
   270
(* ------------------------------------------------------------------------- *)
nipkow@5982
   271
(* Calculate new (in)equality type after addition.                           *)
nipkow@5982
   272
(* ------------------------------------------------------------------------- *)
nipkow@5982
   273
nipkow@5982
   274
fun find_add_type(Eq,x) = x
nipkow@5982
   275
  | find_add_type(x,Eq) = x
nipkow@5982
   276
  | find_add_type(_,Lt) = Lt
nipkow@5982
   277
  | find_add_type(Lt,_) = Lt
nipkow@5982
   278
  | find_add_type(Le,Le) = Le;
nipkow@5982
   279
nipkow@5982
   280
(* ------------------------------------------------------------------------- *)
nipkow@5982
   281
(* Multiply out an (in)equation.                                             *)
nipkow@5982
   282
(* ------------------------------------------------------------------------- *)
nipkow@5982
   283
nipkow@5982
   284
fun multiply_ineq n (i as Lineq(k,ty,l,just)) =
nipkow@5982
   285
  if n = 1 then i
nipkow@5982
   286
  else if n = 0 andalso ty = Lt then sys_error "multiply_ineq"
nipkow@5982
   287
  else if n < 0 andalso (ty=Le orelse ty=Lt) then sys_error "multiply_ineq"
paulson@17524
   288
  else Lineq (n * k, ty, map (curry op* n) l, Multiplied (n, just));
nipkow@5982
   289
nipkow@5982
   290
(* ------------------------------------------------------------------------- *)
nipkow@5982
   291
(* Add together (in)equations.                                               *)
nipkow@5982
   292
(* ------------------------------------------------------------------------- *)
nipkow@5982
   293
nipkow@5982
   294
fun add_ineq (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
haftmann@18330
   295
  let val l = map2 (curry (op +)) l1 l2
nipkow@5982
   296
  in Lineq(k1+k2,find_add_type(ty1,ty2),l,Added(just1,just2)) end;
nipkow@5982
   297
nipkow@5982
   298
(* ------------------------------------------------------------------------- *)
nipkow@5982
   299
(* Elimination of variable between a single pair of (in)equations.           *)
nipkow@5982
   300
(* If they're both inequalities, 1st coefficient must be +ve, 2nd -ve.       *)
nipkow@5982
   301
(* ------------------------------------------------------------------------- *)
nipkow@5982
   302
nipkow@5982
   303
fun elim_var v (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
nipkow@5982
   304
  let val c1 = el v l1 and c2 = el v l2
nipkow@16358
   305
      val m = lcm(abs c1, abs c2)
nipkow@5982
   306
      val m1 = m div (abs c1) and m2 = m div (abs c2)
nipkow@5982
   307
      val (n1,n2) =
nipkow@5982
   308
        if (c1 >= 0) = (c2 >= 0)
nipkow@5982
   309
        then if ty1 = Eq then (~m1,m2)
nipkow@5982
   310
             else if ty2 = Eq then (m1,~m2)
nipkow@5982
   311
                  else sys_error "elim_var"
nipkow@5982
   312
        else (m1,m2)
nipkow@5982
   313
      val (p1,p2) = if ty1=Eq andalso ty2=Eq andalso (n1 = ~1 orelse n2 = ~1)
nipkow@5982
   314
                    then (~n1,~n2) else (n1,n2)
nipkow@5982
   315
  in add_ineq (multiply_ineq n1 i1) (multiply_ineq n2 i2) end;
nipkow@5982
   316
nipkow@5982
   317
(* ------------------------------------------------------------------------- *)
nipkow@5982
   318
(* The main refutation-finding code.                                         *)
nipkow@5982
   319
(* ------------------------------------------------------------------------- *)
nipkow@5982
   320
nipkow@5982
   321
fun is_trivial (Lineq(_,_,l,_)) = forall (fn i => i=0) l;
nipkow@5982
   322
nipkow@5982
   323
fun is_answer (ans as Lineq(k,ty,l,_)) =
nipkow@5982
   324
  case ty  of Eq => k <> 0 | Le => k > 0 | Lt => k >= 0;
nipkow@5982
   325
nipkow@16358
   326
fun calc_blowup (l:IntInf.int list) =
haftmann@17496
   327
  let val (p,n) = List.partition (curry (op <) 0) (List.filter (curry (op <>) 0) l)
nipkow@5982
   328
  in (length p) * (length n) end;
nipkow@5982
   329
nipkow@5982
   330
(* ------------------------------------------------------------------------- *)
nipkow@5982
   331
(* Main elimination code:                                                    *)
nipkow@5982
   332
(*                                                                           *)
nipkow@5982
   333
(* (1) Looks for immediate solutions (false assertions with no variables).   *)
nipkow@5982
   334
(*                                                                           *)
nipkow@5982
   335
(* (2) If there are any equations, picks a variable with the lowest absolute *)
nipkow@5982
   336
(* coefficient in any of them, and uses it to eliminate.                     *)
nipkow@5982
   337
(*                                                                           *)
nipkow@5982
   338
(* (3) Otherwise, chooses a variable in the inequality to minimize the       *)
nipkow@5982
   339
(* blowup (number of consequences generated) and eliminates it.              *)
nipkow@5982
   340
(* ------------------------------------------------------------------------- *)
nipkow@5982
   341
nipkow@5982
   342
fun allpairs f xs ys =
webertj@20217
   343
  List.concat (map (fn x => map (fn y => f x y) ys) xs);
nipkow@5982
   344
nipkow@5982
   345
fun extract_first p =
skalberg@15531
   346
  let fun extract xs (y::ys) = if p y then (SOME y,xs@ys)
nipkow@5982
   347
                               else extract (y::xs) ys
skalberg@15531
   348
        | extract xs []      = (NONE,xs)
nipkow@5982
   349
  in extract [] end;
nipkow@5982
   350
nipkow@6056
   351
fun print_ineqs ineqs =
paulson@9073
   352
  if !trace then
wenzelm@12262
   353
     tracing(cat_lines(""::map (fn Lineq(c,t,l,_) =>
nipkow@16358
   354
       IntInf.toString c ^
paulson@9073
   355
       (case t of Eq => " =  " | Lt=> " <  " | Le => " <= ") ^
nipkow@16358
   356
       commas(map IntInf.toString l)) ineqs))
paulson@9073
   357
  else ();
nipkow@6056
   358
nipkow@13498
   359
type history = (int * lineq list) list;
nipkow@13498
   360
datatype result = Success of injust | Failure of history;
nipkow@13498
   361
webertj@20217
   362
fun elim (ineqs, hist) =
webertj@20217
   363
  let val dummy = print_ineqs ineqs
webertj@20217
   364
      val (triv, nontriv) = List.partition is_trivial ineqs in
webertj@20217
   365
  if not (null triv)
nipkow@13186
   366
  then case Library.find_first is_answer triv of
webertj@20217
   367
         NONE => elim (nontriv, hist)
skalberg@15531
   368
       | SOME(Lineq(_,_,_,j)) => Success j
nipkow@5982
   369
  else
webertj@20217
   370
  if null nontriv then Failure hist
nipkow@13498
   371
  else
webertj@20217
   372
  let val (eqs, noneqs) = List.partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
webertj@20217
   373
  if not (null eqs) then
skalberg@15570
   374
     let val clist = Library.foldl (fn (cs,Lineq(_,_,l,_)) => l union cs) ([],eqs)
nipkow@16358
   375
         val sclist = sort (fn (x,y) => IntInf.compare(abs(x),abs(y)))
skalberg@15570
   376
                           (List.filter (fn i => i<>0) clist)
nipkow@5982
   377
         val c = hd sclist
skalberg@15531
   378
         val (SOME(eq as Lineq(_,_,ceq,_)),othereqs) =
nipkow@5982
   379
               extract_first (fn Lineq(_,_,l,_) => c mem l) eqs
webertj@20217
   380
         val v = find_index_eq c ceq
skalberg@15570
   381
         val (ioth,roth) = List.partition (fn (Lineq(_,_,l,_)) => el v l = 0)
nipkow@5982
   382
                                     (othereqs @ noneqs)
nipkow@5982
   383
         val others = map (elim_var v eq) roth @ ioth
nipkow@13498
   384
     in elim(others,(v,nontriv)::hist) end
nipkow@5982
   385
  else
nipkow@5982
   386
  let val lists = map (fn (Lineq(_,_,l,_)) => l) noneqs
nipkow@5982
   387
      val numlist = 0 upto (length(hd lists) - 1)
nipkow@5982
   388
      val coeffs = map (fn i => map (el i) lists) numlist
nipkow@5982
   389
      val blows = map calc_blowup coeffs
nipkow@5982
   390
      val iblows = blows ~~ numlist
skalberg@15570
   391
      val nziblows = List.filter (fn (i,_) => i<>0) iblows
nipkow@13498
   392
  in if null nziblows then Failure((~1,nontriv)::hist)
nipkow@13498
   393
     else
nipkow@5982
   394
     let val (c,v) = hd(sort (fn (x,y) => int_ord(fst(x),fst(y))) nziblows)
skalberg@15570
   395
         val (no,yes) = List.partition (fn (Lineq(_,_,l,_)) => el v l = 0) ineqs
skalberg@15570
   396
         val (pos,neg) = List.partition(fn (Lineq(_,_,l,_)) => el v l > 0) yes
nipkow@13498
   397
     in elim(no @ allpairs (elim_var v) pos neg, (v,nontriv)::hist) end
nipkow@5982
   398
  end
nipkow@5982
   399
  end
nipkow@5982
   400
  end;
nipkow@5982
   401
nipkow@5982
   402
(* ------------------------------------------------------------------------- *)
nipkow@5982
   403
(* Translate back a proof.                                                   *)
nipkow@5982
   404
(* ------------------------------------------------------------------------- *)
nipkow@5982
   405
webertj@20268
   406
fun trace_thm (msg : string) (th : thm) : thm =
webertj@20217
   407
    (if !trace then (tracing msg; tracing (Display.string_of_thm th)) else (); th);
paulson@9073
   408
webertj@20268
   409
fun trace_msg (msg : string) : unit =
wenzelm@12262
   410
    if !trace then tracing msg else ();
paulson@9073
   411
nipkow@13498
   412
(* FIXME OPTIMIZE!!!! (partly done already)
nipkow@6056
   413
   Addition/Multiplication need i*t representation rather than t+t+...
nipkow@10691
   414
   Get rid of Mulitplied(2). For Nat LA_Data.number_of should return Suc^n
nipkow@10691
   415
   because Numerals are not known early enough.
nipkow@6056
   416
nipkow@6056
   417
Simplification may detect a contradiction 'prematurely' due to type
nipkow@6056
   418
information: n+1 <= 0 is simplified to False and does not need to be crossed
nipkow@6056
   419
with 0 <= n.
nipkow@6056
   420
*)
nipkow@6056
   421
local
nipkow@6056
   422
 exception FalseE of thm
nipkow@6056
   423
in
webertj@20268
   424
fun mkthm (sg:theory, ss:simpset) (asms:thm list) (just:injust) : thm =
nipkow@15922
   425
  let val {add_mono_thms, mult_mono_thms, inj_thms, lessD, simpset, ...} =
wenzelm@16458
   426
          Data.get sg;
wenzelm@17877
   427
      val simpset' = Simplifier.inherit_context ss simpset;
webertj@20217
   428
      val atoms = Library.foldl (fn (ats, (lhs,_,_,rhs,_,_)) =>
nipkow@6056
   429
                            map fst lhs  union  (map fst rhs  union  ats))
webertj@20217
   430
                        ([], List.mapPartial (fn thm => if Thm.no_prems thm
webertj@20217
   431
                                              then LA_Data.decomp sg (concl_of thm)
webertj@20217
   432
                                              else NONE) asms)
nipkow@6056
   433
nipkow@10575
   434
      fun add2 thm1 thm2 =
nipkow@6102
   435
        let val conj = thm1 RS (thm2 RS LA_Logic.conjI)
skalberg@15531
   436
        in get_first (fn th => SOME(conj RS th) handle THM _ => NONE) add_mono_thms
nipkow@5982
   437
        end;
skalberg@15531
   438
      fun try_add [] _ = NONE
nipkow@10575
   439
        | try_add (thm1::thm1s) thm2 = case add2 thm1 thm2 of
skalberg@15531
   440
             NONE => try_add thm1s thm2 | some => some;
nipkow@10575
   441
nipkow@10575
   442
      fun addthms thm1 thm2 =
nipkow@10575
   443
        case add2 thm1 thm2 of
skalberg@15531
   444
          NONE => (case try_add ([thm1] RL inj_thms) thm2 of
webertj@20217
   445
                     NONE => ( the (try_add ([thm2] RL inj_thms) thm1)
wenzelm@15660
   446
                               handle Option =>
nipkow@14360
   447
                               (trace_thm "" thm1; trace_thm "" thm2;
webertj@20217
   448
                                sys_error "Lin.arith. failed to add thms")
webertj@20217
   449
                             )
skalberg@15531
   450
                   | SOME thm => thm)
skalberg@15531
   451
        | SOME thm => thm;
nipkow@10575
   452
nipkow@5982
   453
      fun multn(n,thm) =
nipkow@5982
   454
        let fun mul(i,th) = if i=1 then th else mul(i-1, addthms thm th)
nipkow@6102
   455
        in if n < 0 then mul(~n,thm) RS LA_Logic.sym else mul(n,thm) end;
webertj@20217
   456
nipkow@15184
   457
      fun multn2(n,thm) =
skalberg@15531
   458
        let val SOME(mth) =
skalberg@15531
   459
              get_first (fn th => SOME(thm RS th) handle THM _ => NONE) mult_mono_thms
nipkow@15184
   460
            fun cvar(th,_ $ (_ $ _ $ var)) = cterm_of (#sign(rep_thm th)) var;
nipkow@15184
   461
            val cv = cvar(mth, hd(prems_of mth));
nipkow@15184
   462
            val ct = cterm_of sg (LA_Data.number_of(n,#T(rep_cterm cv)))
nipkow@15184
   463
        in instantiate ([],[(cv,ct)]) mth end
nipkow@10691
   464
nipkow@6056
   465
      fun simp thm =
wenzelm@17515
   466
        let val thm' = trace_thm "Simplified:" (full_simplify simpset' thm)
nipkow@6102
   467
        in if LA_Logic.is_False thm' then raise FalseE thm' else thm' end
nipkow@6056
   468
webertj@20254
   469
      fun mk (Asm i)              = trace_thm "Asm" (nth asms i)
webertj@20254
   470
        | mk (Nat i)              = trace_thm "Nat" (LA_Logic.mk_nat_thm sg (nth atoms i))
webertj@20254
   471
        | mk (LessD j)            = trace_thm "L" (hd ([mk j] RL lessD))
webertj@20254
   472
        | mk (NotLeD j)           = trace_thm "NLe" (mk j RS LA_Logic.not_leD)
webertj@20254
   473
        | mk (NotLeDD j)          = trace_thm "NLeD" (hd ([mk j RS LA_Logic.not_leD] RL lessD))
webertj@20254
   474
        | mk (NotLessD j)         = trace_thm "NL" (mk j RS LA_Logic.not_lessD)
webertj@20254
   475
        | mk (Added (j1, j2))     = simp (trace_thm "+" (addthms (mk j1) (mk j2)))
webertj@20254
   476
        | mk (Multiplied (n, j))  = (trace_msg ("*" ^ IntInf.toString n); trace_thm "*" (multn (n, mk j)))
webertj@20254
   477
        | mk (Multiplied2 (n, j)) = simp (trace_msg ("**" ^ IntInf.toString n); trace_thm "**" (multn2 (n, mk j)))
nipkow@5982
   478
paulson@9073
   479
  in trace_msg "mkthm";
nipkow@12932
   480
     let val thm = trace_thm "Final thm:" (mk just)
wenzelm@17515
   481
     in let val fls = simplify simpset' thm
nipkow@13186
   482
        in trace_thm "After simplification:" fls;
nipkow@13186
   483
           if LA_Logic.is_False fls then fls
nipkow@13186
   484
           else
webertj@20217
   485
            (tracing "Assumptions:"; List.app (tracing o Display.string_of_thm) asms;
webertj@20217
   486
             tracing "Proved:"; tracing (Display.string_of_thm fls);
nipkow@13186
   487
             warning "Linear arithmetic should have refuted the assumptions.\n\
nipkow@13186
   488
                     \Please inform Tobias Nipkow (nipkow@in.tum.de).";
nipkow@13186
   489
             fls)
nipkow@12932
   490
        end
webertj@20217
   491
     end handle FalseE thm => trace_thm "False reached early:" thm
nipkow@12932
   492
  end
nipkow@6056
   493
end;
nipkow@5982
   494
nipkow@16358
   495
fun coeff poly atom : IntInf.int =
haftmann@17325
   496
  AList.lookup (op =) poly atom |> the_default 0;
nipkow@5982
   497
webertj@20268
   498
fun lcms (is:int list) : int = Library.foldl lcm (1, is);
nipkow@10691
   499
nipkow@10691
   500
fun integ(rlhs,r,rel,rrhs,s,d) =
haftmann@17951
   501
let val (rn,rd) = Rat.quotient_of_rat r and (sn,sd) = Rat.quotient_of_rat s
haftmann@17951
   502
    val m = lcms(map (abs o snd o Rat.quotient_of_rat) (r :: s :: map snd rlhs @ map snd rrhs))
paulson@15965
   503
    fun mult(t,r) = 
haftmann@17951
   504
        let val (i,j) = Rat.quotient_of_rat r
paulson@15965
   505
        in (t,i * (m div j)) end
nipkow@12932
   506
in (m,(map mult rlhs, rn*(m div rd), rel, map mult rrhs, sn*(m div sd), d)) end
nipkow@10691
   507
nipkow@13498
   508
fun mklineq n atoms =
webertj@20217
   509
  fn (item, k) =>
webertj@20217
   510
  let val (m, (lhs,i,rel,rhs,j,discrete)) = integ item
nipkow@13498
   511
      val lhsa = map (coeff lhs) atoms
nipkow@13498
   512
      and rhsa = map (coeff rhs) atoms
haftmann@18330
   513
      val diff = map2 (curry (op -)) rhsa lhsa
nipkow@13498
   514
      val c = i-j
nipkow@13498
   515
      val just = Asm k
nipkow@13498
   516
      fun lineq(c,le,cs,j) = Lineq(c,le,cs, if m=1 then j else Multiplied2(m,j))
nipkow@13498
   517
  in case rel of
nipkow@13498
   518
      "<="   => lineq(c,Le,diff,just)
nipkow@13498
   519
     | "~<=" => if discrete
nipkow@13498
   520
                then lineq(1-c,Le,map (op ~) diff,NotLeDD(just))
nipkow@13498
   521
                else lineq(~c,Lt,map (op ~) diff,NotLeD(just))
nipkow@13498
   522
     | "<"   => if discrete
nipkow@13498
   523
                then lineq(c+1,Le,diff,LessD(just))
nipkow@13498
   524
                else lineq(c,Lt,diff,just)
nipkow@13498
   525
     | "~<"  => lineq(~c,Le,map (op~) diff,NotLessD(just))
nipkow@13498
   526
     | "="   => lineq(c,Eq,diff,just)
nipkow@13498
   527
     | _     => sys_error("mklineq" ^ rel)   
nipkow@5982
   528
  end;
nipkow@5982
   529
nipkow@13498
   530
(* ------------------------------------------------------------------------- *)
nipkow@13498
   531
(* Print (counter) example                                                   *)
nipkow@13498
   532
(* ------------------------------------------------------------------------- *)
nipkow@13498
   533
nipkow@13498
   534
fun print_atom((a,d),r) =
haftmann@17951
   535
  let val (p,q) = Rat.quotient_of_rat r
paulson@15965
   536
      val s = if d then IntInf.toString p else
nipkow@13498
   537
              if p = 0 then "0"
paulson@15965
   538
              else IntInf.toString p ^ "/" ^ IntInf.toString q
nipkow@13498
   539
  in a ^ " = " ^ s end;
nipkow@13498
   540
wenzelm@19049
   541
fun produce_ex sds =
haftmann@17496
   542
  curry (op ~~) sds
haftmann@17496
   543
  #> map print_atom
haftmann@17496
   544
  #> commas
webertj@20217
   545
  #> curry (op ^) "Counter example (possibly spurious):\n";
nipkow@13498
   546
webertj@20217
   547
fun trace_ex (sg, params, atoms, discr, n, hist : history) =
webertj@20217
   548
  case hist of
webertj@20217
   549
    [] => ()
webertj@20217
   550
  | (v, lineqs) :: hist' =>
webertj@20217
   551
    let val frees = map Free params
webertj@20217
   552
        fun s_of_t t = Sign.string_of_term sg (subst_bounds (frees, t))
webertj@20217
   553
        val start = if v = ~1 then (findex0 discr n lineqs, hist')
webertj@20217
   554
                    else (replicate n Rat.zero, hist)
webertj@20217
   555
        val ex = SOME (produce_ex ((map s_of_t atoms) ~~ discr) (findex discr start))
webertj@20217
   556
          handle NoEx => NONE
webertj@20217
   557
    in
webertj@20217
   558
      case ex of
webertj@20217
   559
        SOME s => (warning "arith failed - see trace for a counter example"; tracing s)
webertj@20217
   560
      | NONE => warning "arith failed"
webertj@20217
   561
    end;
nipkow@13498
   562
webertj@20217
   563
(* ------------------------------------------------------------------------- *)
webertj@20217
   564
webertj@20268
   565
fun mknat (pTs : typ list) (ixs : int list) (atom : term, i : int) : lineq option =
webertj@20217
   566
  if LA_Logic.is_nat (pTs, atom)
nipkow@6056
   567
  then let val l = map (fn j => if j=i then 1 else 0) ixs
webertj@20217
   568
       in SOME (Lineq (0, Le, l, Nat i)) end
webertj@20217
   569
  else NONE;
nipkow@6056
   570
nipkow@13186
   571
(* This code is tricky. It takes a list of premises in the order they occur
skalberg@15531
   572
in the subgoal. Numerical premises are coded as SOME(tuple), non-numerical
skalberg@15531
   573
ones as NONE. Going through the premises, each numeric one is converted into
nipkow@13186
   574
a Lineq. The tricky bit is to convert ~= which is split into two cases < and
nipkow@13498
   575
>. Thus split_items returns a list of equation systems. This may blow up if
nipkow@13186
   576
there are many ~=, but in practice it does not seem to happen. The really
nipkow@13186
   577
tricky bit is to arrange the order of the cases such that they coincide with
nipkow@13186
   578
the order in which the cases are in the end generated by the tactic that
nipkow@13186
   579
applies the generated refutation thms (see function 'refute_tac').
nipkow@13186
   580
nipkow@13186
   581
For variables n of type nat, a constraint 0 <= n is added.
nipkow@13186
   582
*)
webertj@20217
   583
webertj@20217
   584
(* FIXME: To optimize, the splitting of cases and the search for refutations *)
webertj@20217
   585
(*        should be intertwined: separate the first (fully split) case,      *)
webertj@20217
   586
(*        refute it, continue with splitting and refuting.  Terminate with   *)
webertj@20217
   587
(*        failure as soon as a case could not be refuted; i.e. delay further *)
webertj@20217
   588
(*        splitting until after a refutation for other cases has been found. *)
webertj@20217
   589
webertj@20268
   590
fun split_items sg (Ts : typ list, terms : term list) : (typ list * (LA_Data.decompT * int) list) list =
webertj@20217
   591
  let
webertj@20217
   592
(*
webertj@20254
   593
      val _ = trace_msg ("split_items: Ts    = " ^ string_of_list (Sign.string_of_typ sg) Ts ^ "\n" ^
webertj@20254
   594
                         "             terms = " ^ string_of_list (Sign.string_of_term sg) terms)
webertj@20217
   595
*)
webertj@20217
   596
      (* splits inequalities '~=' into '<' and '>'; this corresponds to *)
webertj@20217
   597
      (* 'REPEAT_DETERM (eresolve_tac neqE i)' at the theorem/tactic    *)
webertj@20217
   598
      (* level                                                          *)
webertj@20217
   599
      fun elim_neq []              = [[]]
webertj@20217
   600
        | elim_neq (NONE :: ineqs) = map (cons NONE) (elim_neq ineqs)
webertj@20217
   601
        | elim_neq (SOME(ineq as (l,i,rel,r,j,d)) :: ineqs) =
webertj@20217
   602
          if rel = "~=" then elim_neq (ineqs @ [SOME (l, i, "<", r, j, d)]) @
webertj@20217
   603
                             elim_neq (ineqs @ [SOME (r, j, "<", l, i, d)])
webertj@20217
   604
          else map (cons (SOME ineq)) (elim_neq ineqs)
webertj@20268
   605
webertj@20217
   606
      fun number_hyps _ []             = []
webertj@20217
   607
        | number_hyps n (NONE::xs)     = number_hyps (n+1) xs
webertj@20217
   608
        | number_hyps n ((SOME x)::xs) = (x, n) :: number_hyps (n+1) xs
nipkow@13464
   609
webertj@20217
   610
      val result = (Ts, terms) |> (* user-defined preprocessing of the subgoal *)
webertj@20254
   611
                                  LA_Data.pre_decomp sg
webertj@20217
   612
                               |> (* compute the internal encoding of (in-)equalities *)
webertj@20217
   613
                                  map (apsnd (map (LA_Data.decomp sg)))
webertj@20217
   614
                               |> (* splitting of inequalities *)
webertj@20217
   615
                                  map (fn (Ts, items) => map (pair Ts) (elim_neq items))
webertj@20217
   616
                               |> (* combine the list of lists of subgoals into a single list *)
webertj@20217
   617
                                  List.concat
webertj@20217
   618
                               |> (* numbering of hypotheses, ignoring irrelevant ones *)
webertj@20217
   619
                                  map (apsnd (number_hyps 0))
webertj@20217
   620
(*
webertj@20268
   621
      val _ = trace_msg ("split_items: result has " ^ Int.toString (length result) ^
webertj@20268
   622
                " subgoal(s)" ^ "\n" ^ (cat_lines o fst) (fold_map (fn (Ts, items) => fn n =>
webertj@20268
   623
                        ("  " ^ Int.toString n ^ ". Ts    = " ^
webertj@20268
   624
                           string_of_list (Sign.string_of_typ sg) Ts ^ "\n" ^
webertj@20268
   625
                         "    items = " ^ string_of_list (string_of_pair 
webertj@20268
   626
                           (fn (l, i, rel, r, j, d) => enclose "(" ")" (commas
webertj@20268
   627
                             [string_of_list
webertj@20268
   628
                                (string_of_pair (Sign.string_of_term sg) Rat.string_of_rat) l,
webertj@20268
   629
                              Rat.string_of_rat i,
webertj@20268
   630
                              rel,
webertj@20268
   631
                              string_of_list
webertj@20268
   632
                                (string_of_pair (Sign.string_of_term sg) Rat.string_of_rat) r,
webertj@20268
   633
                              Rat.string_of_rat j,
webertj@20268
   634
                              Bool.toString d]))
webertj@20268
   635
                           Int.toString) items, n+1)) result 1))
webertj@20217
   636
*)
webertj@20217
   637
  in result end;
nipkow@13464
   638
webertj@20268
   639
fun add_atoms (ats : term list, ((lhs,_,_,rhs,_,_) : LA_Data.decompT, _)) : term list =
webertj@20217
   640
    (map fst lhs) union ((map fst rhs) union ats);
webertj@20217
   641
webertj@20268
   642
fun add_datoms (dats : (bool * term) list, ((lhs,_,_,rhs,_,d) : LA_Data.decompT, _)) :
webertj@20268
   643
  (bool * term) list =
webertj@20268
   644
  (map (pair d o fst) lhs) union ((map (pair d o fst) rhs) union dats);
nipkow@13498
   645
webertj@20268
   646
fun discr (initems : (LA_Data.decompT * int) list) : bool list =
webertj@20268
   647
  map fst (Library.foldl add_datoms ([],initems));
webertj@20217
   648
webertj@20268
   649
fun refutes (sg : theory) (params : (string * typ) list) (show_ex : bool) :
webertj@20268
   650
  (typ list * (LA_Data.decompT * int) list) list -> injust list -> injust list option =
nipkow@13498
   651
let
webertj@20268
   652
  fun refute ((Ts : typ list, initems : (LA_Data.decompT * int) list)::initemss)
webertj@20268
   653
             (js : injust list) : injust list option =
webertj@20217
   654
    let val atoms = Library.foldl add_atoms ([], initems)
nipkow@13498
   655
        val n = length atoms
nipkow@13498
   656
        val mkleq = mklineq n atoms
nipkow@13498
   657
        val ixs = 0 upto (n-1)
nipkow@13498
   658
        val iatoms = atoms ~~ ixs
webertj@20217
   659
        val natlineqs = List.mapPartial (mknat Ts ixs) iatoms
nipkow@13498
   660
        val ineqs = map mkleq initems @ natlineqs
webertj@20217
   661
    in case elim (ineqs, []) of
webertj@20217
   662
         Success j =>
webertj@20268
   663
           (trace_msg ("Contradiction! (" ^ Int.toString (length js + 1) ^ ")");
webertj@20268
   664
            refute initemss (js@[j]))
webertj@20217
   665
       | Failure hist =>
webertj@20217
   666
           (if not show_ex then
webertj@20217
   667
              ()
webertj@20217
   668
            else let
webertj@20217
   669
              (* invent names for bound variables that are new, i.e. in Ts, but not in params *)
webertj@20217
   670
              (* we assume that Ts still contains (map snd params) as a suffix                *)
webertj@20217
   671
              val new_count = length Ts - length params - 1
webertj@20217
   672
              val new_names = map Name.bound (0 upto new_count)
webertj@20217
   673
              val params'   = (new_names @ map fst params) ~~ Ts
webertj@20217
   674
            in
webertj@20217
   675
              trace_ex (sg, params', atoms, discr initems, n, hist)
webertj@20217
   676
            end; NONE)
nipkow@13498
   677
    end
skalberg@15531
   678
    | refute [] js = SOME js
nipkow@13498
   679
in refute end;
nipkow@5982
   680
webertj@20268
   681
fun refute (sg : theory) (params : (string * Term.typ) list) (show_ex : bool) (terms : term list) :
webertj@20268
   682
  injust list option =
webertj@20254
   683
  refutes sg params show_ex (split_items sg (map snd params, terms)) [];
webertj@20254
   684
webertj@20268
   685
fun count (P : 'a -> bool) (xs : 'a list) : int = length (List.filter P xs);
webertj@20254
   686
webertj@20254
   687
(* The limit on the number of ~= allowed.
webertj@20254
   688
   Because each ~= is split into two cases, this can lead to an explosion.
webertj@20254
   689
*)
webertj@20254
   690
val fast_arith_neq_limit = ref 9;
webertj@20254
   691
webertj@20268
   692
fun prove (sg : theory) (params : (string * Term.typ) list) (show_ex : bool) (Hs : term list)
webertj@20268
   693
          (concl : term) : injust list option =
webertj@20254
   694
  let
webertj@20254
   695
    (* append the negated conclusion to 'Hs' -- this corresponds to     *)
webertj@20254
   696
    (* 'DETERM (resolve_tac [LA_Logic.notI, LA_Logic.ccontr] i)' at the *)
webertj@20254
   697
    (* theorem/tactic level                                             *)
webertj@20254
   698
    val Hs' = Hs @ [LA_Logic.neg_prop concl]
webertj@20254
   699
    fun is_neq NONE                 = false
webertj@20254
   700
      | is_neq (SOME (_,_,r,_,_,_)) = (r = "~=")
webertj@20254
   701
  in
webertj@20254
   702
    trace_msg "prove";
webertj@20254
   703
    if count is_neq (map (LA_Data.decomp sg) Hs')
webertj@20254
   704
      > !fast_arith_neq_limit then (
webertj@20268
   705
      trace_msg ("fast_arith_neq_limit exceeded (current value is " ^
webertj@20268
   706
                   string_of_int (!fast_arith_neq_limit) ^ ")");
webertj@20254
   707
      NONE
webertj@20254
   708
    ) else
webertj@20254
   709
      refute sg params show_ex Hs'
webertj@20254
   710
  end;
webertj@20217
   711
webertj@20268
   712
fun refute_tac (ss : simpset) (i : int, justs : injust list) : tactic =
nipkow@6074
   713
  fn state =>
webertj@20268
   714
    let val _ = trace_thm ("refute_tac (on subgoal " ^ Int.toString i ^ ", with " ^
webertj@20268
   715
                             Int.toString (length justs) ^ " justification(s)):") state
webertj@20217
   716
        val sg          = theory_of_thm state
webertj@20217
   717
        val {neqE, ...} = Data.get sg
webertj@20217
   718
        fun just1 j =
webertj@20268
   719
          (* eliminate inequalities *)
webertj@20268
   720
          REPEAT_DETERM (eresolve_tac neqE i) THEN
webertj@20268
   721
            (* use theorems generated from the actual justifications *)
webertj@20268
   722
            METAHYPS (fn asms => rtac (mkthm (sg, ss) asms j) 1) i
webertj@20268
   723
    in (* rewrite "[| A1; ...; An |] ==> B" to "[| A1; ...; An; ~B |] ==> False" *)
webertj@20268
   724
       DETERM (resolve_tac [LA_Logic.notI, LA_Logic.ccontr] i) THEN
webertj@20268
   725
       (* user-defined preprocessing of the subgoal *)
webertj@20268
   726
       DETERM (LA_Data.pre_tac i) THEN
webertj@20217
   727
       PRIMITIVE (trace_thm "State after pre_tac:") THEN
webertj@20268
   728
       (* prove every resulting subgoal, using its justification *)
webertj@20268
   729
       EVERY (map just1 justs)
webertj@20217
   730
    end  state;
nipkow@6074
   731
nipkow@5982
   732
(*
nipkow@5982
   733
Fast but very incomplete decider. Only premises and conclusions
nipkow@5982
   734
that are already (negated) (in)equations are taken into account.
nipkow@5982
   735
*)
webertj@20268
   736
fun simpset_lin_arith_tac (ss : simpset) (show_ex : bool) (i : int) (st : thm) =
webertj@20268
   737
  SUBGOAL (fn (A,_) =>
webertj@20217
   738
  let val params = rev (Logic.strip_params A)
webertj@20217
   739
      val Hs     = Logic.strip_assums_hyp A
webertj@20217
   740
      val concl  = Logic.strip_assums_concl A
nipkow@12932
   741
  in trace_thm ("Trying to refute subgoal " ^ string_of_int i) st;
webertj@20254
   742
     case prove (Thm.sign_of_thm st) params show_ex Hs concl of
skalberg@15531
   743
       NONE => (trace_msg "Refutation failed."; no_tac)
webertj@20217
   744
     | SOME js => (trace_msg "Refutation succeeded."; refute_tac ss (i, js))
wenzelm@9420
   745
  end) i st;
nipkow@5982
   746
webertj@20268
   747
fun lin_arith_tac (show_ex : bool) (i : int) (st : thm) =
wenzelm@17892
   748
  simpset_lin_arith_tac (Simplifier.theory_context (Thm.theory_of_thm st) Simplifier.empty_ss)
webertj@20217
   749
    show_ex i st;
wenzelm@17613
   750
webertj@20268
   751
fun cut_lin_arith_tac (ss : simpset) (i : int) =
wenzelm@17613
   752
  cut_facts_tac (Simplifier.prems_of_ss ss) i THEN
wenzelm@17613
   753
  simpset_lin_arith_tac ss false i;
nipkow@5982
   754
nipkow@13186
   755
(** Forward proof from theorems **)
nipkow@13186
   756
webertj@20268
   757
fun prover (ctxt as (sg, ss)) thms (Tconcl : term) (js : injust list) (pos : bool) : thm option =
webertj@20254
   758
let
webertj@20217
   759
    (* There is no "forward version" of 'pre_tac'.  Therefore we combine the     *)
webertj@20217
   760
    (* available theorems into a single proof state and perform "backward proof" *)
webertj@20217
   761
    (* using 'refute_tac'.                                                       *)
webertj@20217
   762
    val Hs    = map prop_of thms
webertj@20217
   763
    val Prop  = fold (curry Logic.mk_implies) (rev Hs) Tconcl
webertj@20217
   764
    val cProp = cterm_of sg Prop
webertj@20217
   765
    val concl = Goal.init cProp
webertj@20217
   766
                  |> refute_tac ss (1, js)
webertj@20217
   767
                  |> Seq.hd
webertj@20217
   768
                  |> Goal.finish
webertj@20217
   769
                  |> fold (fn thA => fn thAB => implies_elim thAB thA) thms
webertj@20217
   770
in SOME (trace_thm "Proved by lin. arith. prover:"
webertj@20217
   771
          (LA_Logic.mk_Eq concl)) end
nipkow@13186
   772
(* in case concl contains ?-var, which makes assume fail: *)
skalberg@15531
   773
handle THM _ => NONE;
nipkow@13186
   774
nipkow@13186
   775
(* PRE: concl is not negated!
nipkow@13186
   776
   This assumption is OK because
nipkow@13186
   777
   1. lin_arith_prover tries both to prove and disprove concl and
nipkow@13186
   778
   2. lin_arith_prover is applied by the simplifier which
nipkow@13186
   779
      dives into terms and will thus try the non-negated concl anyway.
nipkow@13186
   780
*)
webertj@20217
   781
webertj@20268
   782
fun lin_arith_prover sg ss (concl : term) : thm option =
webertj@20217
   783
let val thms = List.concat (map LA_Logic.atomize (prems_of_ss ss));
webertj@20217
   784
    val Hs = map prop_of thms
nipkow@6102
   785
    val Tconcl = LA_Logic.mk_Trueprop concl
webertj@20217
   786
(*
webertj@20217
   787
    val _ = trace_msg "lin_arith_prover"
webertj@20217
   788
    val _ = map (trace_thm "thms:") thms
webertj@20217
   789
    val _ = trace_msg ("concl:" ^ Sign.string_of_term sg concl)
webertj@20217
   790
*)
webertj@20254
   791
in case prove sg [] false Hs Tconcl of (* concl provable? *)
wenzelm@17515
   792
     SOME js => prover (sg, ss) thms Tconcl js true
skalberg@15531
   793
   | NONE => let val nTconcl = LA_Logic.neg_prop Tconcl
webertj@20254
   794
          in case prove sg [] false Hs nTconcl of (* ~concl provable? *)
wenzelm@17515
   795
               SOME js => prover (sg, ss) thms nTconcl js false
skalberg@15531
   796
             | NONE => NONE
nipkow@6079
   797
          end
nipkow@5982
   798
end;
nipkow@6074
   799
nipkow@6074
   800
end;