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