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