src/Provers/Arith/fast_lin_arith.ML
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 33002 f3f02f36a3e2
child 33038 8f9594c31de4
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
nipkow@5982
     1
(*  Title:      Provers/Arith/fast_lin_arith.ML
nipkow@5982
     2
    ID:         $Id$
boehmes@31510
     3
    Author:     Tobias Nipkow and Tjark Weber and Sascha Boehme
nipkow@6102
     4
wenzelm@24076
     5
A generic linear arithmetic package.  It provides two tactics
wenzelm@24076
     6
(cut_lin_arith_tac, lin_arith_tac) and a simplification procedure
wenzelm@24076
     7
(lin_arith_simproc).
nipkow@6102
     8
wenzelm@24076
     9
Only take premises and conclusions into account that are already
wenzelm@24076
    10
(negated) (in)equations. lin_arith_simproc tries to prove or disprove
wenzelm@24076
    11
the term.
nipkow@5982
    12
*)
nipkow@5982
    13
nipkow@5982
    14
(*** Data needed for setting up the linear arithmetic package ***)
nipkow@5982
    15
nipkow@6102
    16
signature LIN_ARITH_LOGIC =
nipkow@6102
    17
sig
webertj@20276
    18
  val conjI       : thm  (* P ==> Q ==> P & Q *)
webertj@20276
    19
  val ccontr      : thm  (* (~ P ==> False) ==> P *)
webertj@20276
    20
  val notI        : thm  (* (P ==> False) ==> ~ P *)
webertj@20276
    21
  val not_lessD   : thm  (* ~(m < n) ==> n <= m *)
webertj@20276
    22
  val not_leD     : thm  (* ~(m <= n) ==> n < m *)
webertj@20276
    23
  val sym         : thm  (* x = y ==> y = x *)
boehmes@31510
    24
  val trueI       : thm  (* True *)
webertj@20276
    25
  val mk_Eq       : thm -> thm
webertj@20276
    26
  val atomize     : thm -> thm list
webertj@20276
    27
  val mk_Trueprop : term -> term
webertj@20276
    28
  val neg_prop    : term -> term
webertj@20276
    29
  val is_False    : thm -> bool
webertj@20276
    30
  val is_nat      : typ list * term -> bool
webertj@20276
    31
  val mk_nat_thm  : theory -> term -> thm
nipkow@6102
    32
end;
nipkow@6102
    33
(*
nipkow@6102
    34
mk_Eq(~in) = `in == False'
nipkow@6102
    35
mk_Eq(in) = `in == True'
nipkow@6102
    36
where `in' is an (in)equality.
nipkow@6102
    37
webertj@23190
    38
neg_prop(t) = neg  if t is wrapped up in Trueprop and neg is the
webertj@23190
    39
  (logically) negated version of t (again wrapped up in Trueprop),
webertj@23190
    40
  where the negation of a negative term is the term itself (no
webertj@23190
    41
  double negation!); raises TERM ("neg_prop", [t]) if t is not of
webertj@23190
    42
  the form 'Trueprop $ _'
nipkow@6128
    43
nipkow@6128
    44
is_nat(parameter-types,t) =  t:nat
nipkow@6128
    45
mk_nat_thm(t) = "0 <= t"
nipkow@6102
    46
*)
nipkow@6102
    47
nipkow@5982
    48
signature LIN_ARITH_DATA =
nipkow@5982
    49
sig
wenzelm@24076
    50
  (*internal representation of linear (in-)equations:*)
wenzelm@26945
    51
  type decomp = (term * Rat.rat) list * Rat.rat * string * (term * Rat.rat) list * Rat.rat * bool
wenzelm@26945
    52
  val decomp: Proof.context -> term -> decomp option
wenzelm@24076
    53
  val domain_is_nat: term -> bool
wenzelm@24076
    54
wenzelm@24076
    55
  (*preprocessing, performed on a representation of subgoals as list of premises:*)
wenzelm@24076
    56
  val pre_decomp: Proof.context -> typ list * term list -> (typ list * term list) list
wenzelm@24076
    57
wenzelm@24076
    58
  (*preprocessing, performed on the goal -- must do the same as 'pre_decomp':*)
wenzelm@24076
    59
  val pre_tac: Proof.context -> int -> tactic
wenzelm@24076
    60
wenzelm@24076
    61
  (*the limit on the number of ~= allowed; because each ~= is split
wenzelm@24076
    62
    into two cases, this can lead to an explosion*)
wenzelm@24112
    63
  val fast_arith_neq_limit: int Config.T
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
haftmann@31102
    89
  val cut_lin_arith_tac: simpset -> int -> tactic
haftmann@31102
    90
  val lin_arith_tac: Proof.context -> bool -> int -> tactic
haftmann@31102
    91
  val lin_arith_simproc: simpset -> term -> thm option
nipkow@15184
    92
  val map_data: ({add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
boehmes@31510
    93
                 lessD: thm list, neqE: thm list, simpset: Simplifier.simpset,
boehmes@31510
    94
                 number_of : serial * (theory -> typ -> int -> cterm)}
nipkow@15184
    95
                 -> {add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
boehmes@31510
    96
                     lessD: thm list, neqE: thm list, simpset: Simplifier.simpset,
boehmes@31510
    97
                     number_of : serial * (theory -> typ -> int -> cterm)})
wenzelm@24076
    98
                -> Context.generic -> Context.generic
wenzelm@32740
    99
  val trace: bool Unsynchronized.ref
wenzelm@32740
   100
  val warning_count: int Unsynchronized.ref;
nipkow@6062
   101
end;
nipkow@6062
   102
wenzelm@24076
   103
functor Fast_Lin_Arith
wenzelm@24076
   104
  (structure LA_Logic: LIN_ARITH_LOGIC and LA_Data: LIN_ARITH_DATA): FAST_LIN_ARITH =
nipkow@5982
   105
struct
nipkow@5982
   106
wenzelm@9420
   107
wenzelm@9420
   108
(** theory data **)
wenzelm@9420
   109
boehmes@31510
   110
fun no_number_of _ _ _ = raise CTERM ("number_of", [])
boehmes@31510
   111
wenzelm@24076
   112
structure Data = GenericDataFun
wenzelm@22846
   113
(
wenzelm@24076
   114
  type T =
wenzelm@24076
   115
   {add_mono_thms: thm list,
wenzelm@24076
   116
    mult_mono_thms: thm list,
wenzelm@24076
   117
    inj_thms: thm list,
wenzelm@24076
   118
    lessD: thm list,
wenzelm@24076
   119
    neqE: thm list,
boehmes@31510
   120
    simpset: Simplifier.simpset,
boehmes@31510
   121
    number_of : serial * (theory -> typ -> int -> cterm)};
wenzelm@9420
   122
nipkow@10691
   123
  val empty = {add_mono_thms = [], mult_mono_thms = [], inj_thms = [],
boehmes@31510
   124
               lessD = [], neqE = [], simpset = Simplifier.empty_ss,
haftmann@31638
   125
               number_of = (serial (), no_number_of) } : T;
wenzelm@16458
   126
  val extend = I;
wenzelm@16458
   127
  fun merge _
wenzelm@16458
   128
    ({add_mono_thms= add_mono_thms1, mult_mono_thms= mult_mono_thms1, inj_thms= inj_thms1,
boehmes@31510
   129
      lessD = lessD1, neqE=neqE1, simpset = simpset1,
boehmes@31510
   130
      number_of = (number_of1 as (s1, _))},
wenzelm@16458
   131
     {add_mono_thms= add_mono_thms2, mult_mono_thms= mult_mono_thms2, inj_thms= inj_thms2,
boehmes@31510
   132
      lessD = lessD2, neqE=neqE2, simpset = simpset2,
boehmes@31510
   133
      number_of = (number_of2 as (s2, _))}) =
wenzelm@24039
   134
    {add_mono_thms = Thm.merge_thms (add_mono_thms1, add_mono_thms2),
wenzelm@24039
   135
     mult_mono_thms = Thm.merge_thms (mult_mono_thms1, mult_mono_thms2),
wenzelm@24039
   136
     inj_thms = Thm.merge_thms (inj_thms1, inj_thms2),
wenzelm@24039
   137
     lessD = Thm.merge_thms (lessD1, lessD2),
wenzelm@24039
   138
     neqE = Thm.merge_thms (neqE1, neqE2),
boehmes@31510
   139
     simpset = Simplifier.merge_ss (simpset1, simpset2),
boehmes@31510
   140
     number_of = if s1 > s2 then number_of1 else number_of2};
wenzelm@22846
   141
);
wenzelm@9420
   142
wenzelm@9420
   143
val map_data = Data.map;
wenzelm@24076
   144
val get_data = Data.get o Context.Proof;
wenzelm@9420
   145
wenzelm@9420
   146
wenzelm@9420
   147
nipkow@5982
   148
(*** A fast decision procedure ***)
nipkow@5982
   149
(*** Code ported from HOL Light ***)
nipkow@6056
   150
(* possible optimizations:
nipkow@6056
   151
   use (var,coeff) rep or vector rep  tp save space;
nipkow@6056
   152
   treat non-negative atoms separately rather than adding 0 <= atom
nipkow@6056
   153
*)
nipkow@5982
   154
wenzelm@32740
   155
val trace = Unsynchronized.ref false;
paulson@9073
   156
nipkow@5982
   157
datatype lineq_type = Eq | Le | Lt;
nipkow@5982
   158
nipkow@6056
   159
datatype injust = Asm of int
nipkow@6056
   160
                | Nat of int (* index of atom *)
nipkow@6128
   161
                | LessD of injust
nipkow@6128
   162
                | NotLessD of injust
nipkow@6128
   163
                | NotLeD of injust
nipkow@7551
   164
                | NotLeDD of injust
wenzelm@24630
   165
                | Multiplied of int * injust
nipkow@5982
   166
                | Added of injust * injust;
nipkow@5982
   167
wenzelm@24630
   168
datatype lineq = Lineq of int * lineq_type * int list * injust;
nipkow@5982
   169
nipkow@13498
   170
(* ------------------------------------------------------------------------- *)
nipkow@13498
   171
(* Finding a (counter) example from the trace of a failed elimination        *)
nipkow@13498
   172
(* ------------------------------------------------------------------------- *)
nipkow@13498
   173
(* Examples are represented as rational numbers,                             *)
nipkow@13498
   174
(* Dont blame John Harrison for this code - it is entirely mine. TN          *)
nipkow@13498
   175
nipkow@13498
   176
exception NoEx;
nipkow@13498
   177
nipkow@14372
   178
(* Coding: (i,true,cs) means i <= cs and (i,false,cs) means i < cs.
nipkow@14372
   179
   In general, true means the bound is included, false means it is excluded.
nipkow@14372
   180
   Need to know if it is a lower or upper bound for unambiguous interpretation!
nipkow@14372
   181
*)
nipkow@14372
   182
haftmann@22950
   183
fun elim_eqns (Lineq (i, Le, cs, _)) = [(i, true, cs)]
haftmann@22950
   184
  | elim_eqns (Lineq (i, Eq, cs, _)) = [(i, true, cs),(~i, true, map ~ cs)]
haftmann@22950
   185
  | elim_eqns (Lineq (i, Lt, cs, _)) = [(i, false, cs)];
nipkow@13498
   186
nipkow@13498
   187
(* PRE: ex[v] must be 0! *)
wenzelm@24630
   188
fun eval ex v (a, le, cs) =
haftmann@22950
   189
  let
haftmann@22950
   190
    val rs = map Rat.rat_of_int cs;
haftmann@22950
   191
    val rsum = fold2 (Rat.add oo Rat.mult) rs ex Rat.zero;
haftmann@23063
   192
  in (Rat.mult (Rat.add (Rat.rat_of_int a) (Rat.neg rsum)) (Rat.inv (nth rs v)), le) end;
haftmann@23063
   193
(* If nth rs v < 0, le should be negated.
nipkow@14372
   194
   Instead this swap is taken into account in ratrelmin2.
nipkow@14372
   195
*)
nipkow@13498
   196
haftmann@22950
   197
fun ratrelmin2 (x as (r, ler), y as (s, les)) =
haftmann@23520
   198
  case Rat.ord (r, s)
haftmann@22950
   199
   of EQUAL => (r, (not ler) andalso (not les))
haftmann@22950
   200
    | LESS => x
haftmann@22950
   201
    | GREATER => y;
haftmann@22950
   202
haftmann@22950
   203
fun ratrelmax2 (x as (r, ler), y as (s, les)) =
haftmann@23520
   204
  case Rat.ord (r, s)
haftmann@22950
   205
   of EQUAL => (r, ler andalso les)
haftmann@22950
   206
    | LESS => y
haftmann@22950
   207
    | GREATER => x;
nipkow@13498
   208
nipkow@14372
   209
val ratrelmin = foldr1 ratrelmin2;
nipkow@14372
   210
val ratrelmax = foldr1 ratrelmax2;
nipkow@13498
   211
haftmann@22950
   212
fun ratexact up (r, exact) =
nipkow@14372
   213
  if exact then r else
haftmann@22950
   214
  let
haftmann@22950
   215
    val (p, q) = Rat.quotient_of_rat r;
haftmann@22950
   216
    val nth = Rat.inv (Rat.rat_of_int q);
haftmann@22950
   217
  in Rat.add r (if up then nth else Rat.neg nth) end;
nipkow@14372
   218
haftmann@22950
   219
fun ratmiddle (r, s) = Rat.mult (Rat.add r s) (Rat.inv Rat.two);
nipkow@14372
   220
webertj@20217
   221
fun choose2 d ((lb, exactl), (ub, exactu)) =
haftmann@23520
   222
  let val ord = Rat.sign lb in
haftmann@22950
   223
  if (ord = LESS orelse exactl) andalso (ord = GREATER orelse exactu)
haftmann@22950
   224
    then Rat.zero
haftmann@22950
   225
    else if not d then
haftmann@22950
   226
      if ord = GREATER
webertj@20217
   227
        then if exactl then lb else ratmiddle (lb, ub)
haftmann@22950
   228
        else if exactu then ub else ratmiddle (lb, ub)
haftmann@22950
   229
      else (*discrete domain, both bounds must be exact*)
haftmann@23025
   230
      if ord = GREATER
haftmann@22950
   231
        then let val lb' = Rat.roundup lb in
haftmann@22950
   232
          if Rat.le lb' ub then lb' else raise NoEx end
haftmann@22950
   233
        else let val ub' = Rat.rounddown ub in
haftmann@22950
   234
          if Rat.le lb ub' then ub' else raise NoEx end
haftmann@22950
   235
  end;
nipkow@13498
   236
haftmann@22950
   237
fun findex1 discr (v, lineqs) ex =
haftmann@22950
   238
  let
haftmann@23063
   239
    val nz = filter (fn (Lineq (_, _, cs, _)) => nth cs v <> 0) lineqs;
haftmann@22950
   240
    val ineqs = maps elim_eqns nz;
haftmann@23063
   241
    val (ge, le) = List.partition (fn (_,_,cs) => nth cs v > 0) ineqs
haftmann@22950
   242
    val lb = ratrelmax (map (eval ex v) ge)
haftmann@22950
   243
    val ub = ratrelmin (map (eval ex v) le)
haftmann@21109
   244
  in nth_map v (K (choose2 (nth discr v) (lb, ub))) ex end;
nipkow@13498
   245
nipkow@13498
   246
fun elim1 v x =
haftmann@23063
   247
  map (fn (a,le,bs) => (Rat.add a (Rat.neg (Rat.mult (nth bs v) x)), le,
haftmann@21109
   248
                        nth_map v (K Rat.zero) bs));
nipkow@13498
   249
haftmann@23520
   250
fun single_var v (_, _, cs) = case filter_out (curry (op =) EQUAL o Rat.sign) cs
haftmann@23063
   251
 of [x] => x =/ nth cs v
haftmann@23063
   252
  | _ => false;
nipkow@13498
   253
nipkow@13498
   254
(* The base case:
nipkow@13498
   255
   all variables occur only with positive or only with negative coefficients *)
nipkow@13498
   256
fun pick_vars discr (ineqs,ex) =
haftmann@23520
   257
  let val nz = filter_out (fn (_,_,cs) => forall (curry (op =) EQUAL o Rat.sign) cs) ineqs
nipkow@14372
   258
  in case nz of [] => ex
nipkow@14372
   259
     | (_,_,cs) :: _ =>
haftmann@23520
   260
       let val v = find_index (not o curry (op =) EQUAL o Rat.sign) cs
haftmann@22950
   261
           val d = nth discr v;
haftmann@23520
   262
           val pos = not (Rat.sign (nth cs v) = LESS);
haftmann@22950
   263
           val sv = filter (single_var v) nz;
nipkow@14372
   264
           val minmax =
haftmann@17951
   265
             if pos then if d then Rat.roundup o fst o ratrelmax
nipkow@14372
   266
                         else ratexact true o ratrelmax
haftmann@17951
   267
                    else if d then Rat.rounddown o fst o ratrelmin
nipkow@14372
   268
                         else ratexact false o ratrelmin
haftmann@23063
   269
           val bnds = map (fn (a,le,bs) => (Rat.mult a (Rat.inv (nth bs v)), le)) sv
haftmann@17951
   270
           val x = minmax((Rat.zero,if pos then true else false)::bnds)
nipkow@14372
   271
           val ineqs' = elim1 v x nz
haftmann@21109
   272
           val ex' = nth_map v (K x) ex
nipkow@14372
   273
       in pick_vars discr (ineqs',ex') end
nipkow@13498
   274
  end;
nipkow@13498
   275
nipkow@13498
   276
fun findex0 discr n lineqs =
haftmann@22950
   277
  let val ineqs = maps elim_eqns lineqs
haftmann@22950
   278
      val rineqs = map (fn (a,le,cs) => (Rat.rat_of_int a, le, map Rat.rat_of_int cs))
nipkow@14372
   279
                       ineqs
haftmann@17951
   280
  in pick_vars discr (rineqs,replicate n Rat.zero) end;
nipkow@13498
   281
nipkow@13498
   282
(* ------------------------------------------------------------------------- *)
webertj@23197
   283
(* End of counterexample finder. The actual decision procedure starts here.  *)
nipkow@13498
   284
(* ------------------------------------------------------------------------- *)
nipkow@13498
   285
nipkow@5982
   286
(* ------------------------------------------------------------------------- *)
nipkow@5982
   287
(* Calculate new (in)equality type after addition.                           *)
nipkow@5982
   288
(* ------------------------------------------------------------------------- *)
nipkow@5982
   289
nipkow@5982
   290
fun find_add_type(Eq,x) = x
nipkow@5982
   291
  | find_add_type(x,Eq) = x
nipkow@5982
   292
  | find_add_type(_,Lt) = Lt
nipkow@5982
   293
  | find_add_type(Lt,_) = Lt
nipkow@5982
   294
  | find_add_type(Le,Le) = Le;
nipkow@5982
   295
nipkow@5982
   296
(* ------------------------------------------------------------------------- *)
nipkow@5982
   297
(* Multiply out an (in)equation.                                             *)
nipkow@5982
   298
(* ------------------------------------------------------------------------- *)
nipkow@5982
   299
nipkow@5982
   300
fun multiply_ineq n (i as Lineq(k,ty,l,just)) =
nipkow@5982
   301
  if n = 1 then i
nipkow@5982
   302
  else if n = 0 andalso ty = Lt then sys_error "multiply_ineq"
nipkow@5982
   303
  else if n < 0 andalso (ty=Le orelse ty=Lt) then sys_error "multiply_ineq"
wenzelm@33002
   304
  else Lineq (n * k, ty, map (Integer.mult n) l, Multiplied (n, just));
nipkow@5982
   305
nipkow@5982
   306
(* ------------------------------------------------------------------------- *)
nipkow@5982
   307
(* Add together (in)equations.                                               *)
nipkow@5982
   308
(* ------------------------------------------------------------------------- *)
nipkow@5982
   309
nipkow@5982
   310
fun add_ineq (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
wenzelm@33002
   311
  let val l = map2 Integer.add l1 l2
nipkow@5982
   312
  in Lineq(k1+k2,find_add_type(ty1,ty2),l,Added(just1,just2)) end;
nipkow@5982
   313
nipkow@5982
   314
(* ------------------------------------------------------------------------- *)
nipkow@5982
   315
(* Elimination of variable between a single pair of (in)equations.           *)
nipkow@5982
   316
(* If they're both inequalities, 1st coefficient must be +ve, 2nd -ve.       *)
nipkow@5982
   317
(* ------------------------------------------------------------------------- *)
nipkow@5982
   318
nipkow@5982
   319
fun elim_var v (i1 as Lineq(k1,ty1,l1,just1)) (i2 as Lineq(k2,ty2,l2,just2)) =
haftmann@23063
   320
  let val c1 = nth l1 v and c2 = nth l2 v
haftmann@23261
   321
      val m = Integer.lcm (abs c1) (abs c2)
nipkow@5982
   322
      val m1 = m div (abs c1) and m2 = m div (abs c2)
nipkow@5982
   323
      val (n1,n2) =
nipkow@5982
   324
        if (c1 >= 0) = (c2 >= 0)
nipkow@5982
   325
        then if ty1 = Eq then (~m1,m2)
nipkow@5982
   326
             else if ty2 = Eq then (m1,~m2)
nipkow@5982
   327
                  else sys_error "elim_var"
nipkow@5982
   328
        else (m1,m2)
nipkow@5982
   329
      val (p1,p2) = if ty1=Eq andalso ty2=Eq andalso (n1 = ~1 orelse n2 = ~1)
nipkow@5982
   330
                    then (~n1,~n2) else (n1,n2)
boehmes@31510
   331
  in add_ineq (multiply_ineq p1 i1) (multiply_ineq p2 i2) end;
nipkow@5982
   332
nipkow@5982
   333
(* ------------------------------------------------------------------------- *)
nipkow@5982
   334
(* The main refutation-finding code.                                         *)
nipkow@5982
   335
(* ------------------------------------------------------------------------- *)
nipkow@5982
   336
nipkow@5982
   337
fun is_trivial (Lineq(_,_,l,_)) = forall (fn i => i=0) l;
nipkow@5982
   338
boehmes@31510
   339
fun is_contradictory (ans as Lineq(k,ty,l,_)) =
nipkow@5982
   340
  case ty  of Eq => k <> 0 | Le => k > 0 | Lt => k >= 0;
nipkow@5982
   341
wenzelm@24630
   342
fun calc_blowup l =
haftmann@17496
   343
  let val (p,n) = List.partition (curry (op <) 0) (List.filter (curry (op <>) 0) l)
wenzelm@24630
   344
  in length p * length n end;
nipkow@5982
   345
nipkow@5982
   346
(* ------------------------------------------------------------------------- *)
nipkow@5982
   347
(* Main elimination code:                                                    *)
nipkow@5982
   348
(*                                                                           *)
nipkow@5982
   349
(* (1) Looks for immediate solutions (false assertions with no variables).   *)
nipkow@5982
   350
(*                                                                           *)
nipkow@5982
   351
(* (2) If there are any equations, picks a variable with the lowest absolute *)
nipkow@5982
   352
(* coefficient in any of them, and uses it to eliminate.                     *)
nipkow@5982
   353
(*                                                                           *)
nipkow@5982
   354
(* (3) Otherwise, chooses a variable in the inequality to minimize the       *)
nipkow@5982
   355
(* blowup (number of consequences generated) and eliminates it.              *)
nipkow@5982
   356
(* ------------------------------------------------------------------------- *)
nipkow@5982
   357
nipkow@5982
   358
fun extract_first p =
boehmes@31510
   359
  let
boehmes@31510
   360
    fun extract xs (y::ys) = if p y then (y, xs @ ys) else extract (y::xs) ys
boehmes@31510
   361
      | extract xs [] = raise Empty
nipkow@5982
   362
  in extract [] end;
nipkow@5982
   363
nipkow@6056
   364
fun print_ineqs ineqs =
paulson@9073
   365
  if !trace then
wenzelm@12262
   366
     tracing(cat_lines(""::map (fn Lineq(c,t,l,_) =>
wenzelm@24630
   367
       string_of_int c ^
paulson@9073
   368
       (case t of Eq => " =  " | Lt=> " <  " | Le => " <= ") ^
wenzelm@24630
   369
       commas(map string_of_int l)) ineqs))
paulson@9073
   370
  else ();
nipkow@6056
   371
nipkow@13498
   372
type history = (int * lineq list) list;
nipkow@13498
   373
datatype result = Success of injust | Failure of history;
nipkow@13498
   374
webertj@20217
   375
fun elim (ineqs, hist) =
boehmes@31510
   376
  let val _ = print_ineqs ineqs
webertj@20217
   377
      val (triv, nontriv) = List.partition is_trivial ineqs in
webertj@20217
   378
  if not (null triv)
boehmes@31510
   379
  then case Library.find_first is_contradictory triv of
webertj@20217
   380
         NONE => elim (nontriv, hist)
skalberg@15531
   381
       | SOME(Lineq(_,_,_,j)) => Success j
nipkow@5982
   382
  else
webertj@20217
   383
  if null nontriv then Failure hist
nipkow@13498
   384
  else
webertj@20217
   385
  let val (eqs, noneqs) = List.partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
webertj@20217
   386
  if not (null eqs) then
boehmes@31510
   387
     let val c =
haftmann@33037
   388
           fold (fn Lineq(_,_,l,_) => fn cs => gen_union (op =) (l, cs)) eqs []
boehmes@31510
   389
           |> filter (fn i => i <> 0)
boehmes@31510
   390
           |> sort (int_ord o pairself abs)
boehmes@31510
   391
           |> hd
boehmes@31510
   392
         val (eq as Lineq(_,_,ceq,_),othereqs) =
nipkow@5982
   393
               extract_first (fn Lineq(_,_,l,_) => c mem l) eqs
haftmann@31986
   394
         val v = find_index (fn v => v = c) ceq
haftmann@23063
   395
         val (ioth,roth) = List.partition (fn (Lineq(_,_,l,_)) => nth l v = 0)
nipkow@5982
   396
                                     (othereqs @ noneqs)
nipkow@5982
   397
         val others = map (elim_var v eq) roth @ ioth
nipkow@13498
   398
     in elim(others,(v,nontriv)::hist) end
nipkow@5982
   399
  else
nipkow@5982
   400
  let val lists = map (fn (Lineq(_,_,l,_)) => l) noneqs
haftmann@23063
   401
      val numlist = 0 upto (length (hd lists) - 1)
haftmann@23063
   402
      val coeffs = map (fn i => map (fn xs => nth xs i) lists) numlist
nipkow@5982
   403
      val blows = map calc_blowup coeffs
nipkow@5982
   404
      val iblows = blows ~~ numlist
haftmann@23063
   405
      val nziblows = filter_out (fn (i, _) => i = 0) iblows
nipkow@13498
   406
  in if null nziblows then Failure((~1,nontriv)::hist)
nipkow@13498
   407
     else
nipkow@5982
   408
     let val (c,v) = hd(sort (fn (x,y) => int_ord(fst(x),fst(y))) nziblows)
haftmann@23063
   409
         val (no,yes) = List.partition (fn (Lineq(_,_,l,_)) => nth l v = 0) ineqs
haftmann@23063
   410
         val (pos,neg) = List.partition(fn (Lineq(_,_,l,_)) => nth l v > 0) yes
boehmes@31510
   411
     in elim(no @ map_product (elim_var v) pos neg, (v,nontriv)::hist) end
nipkow@5982
   412
  end
nipkow@5982
   413
  end
nipkow@5982
   414
  end;
nipkow@5982
   415
nipkow@5982
   416
(* ------------------------------------------------------------------------- *)
nipkow@5982
   417
(* Translate back a proof.                                                   *)
nipkow@5982
   418
(* ------------------------------------------------------------------------- *)
nipkow@5982
   419
wenzelm@32091
   420
fun trace_thm ctxt msg th =
wenzelm@32091
   421
  (if !trace then (tracing msg; tracing (Display.string_of_thm ctxt th)) else (); th);
paulson@9073
   422
wenzelm@24076
   423
fun trace_term ctxt msg t =
wenzelm@24920
   424
  (if !trace then tracing (cat_lines [msg, Syntax.string_of_term ctxt t]) else (); t)
wenzelm@24076
   425
wenzelm@24076
   426
fun trace_msg msg =
wenzelm@24076
   427
  if !trace then tracing msg else ();
paulson@9073
   428
wenzelm@32740
   429
val warning_count = Unsynchronized.ref 0;
wenzelm@27020
   430
val warning_count_max = 10;
wenzelm@27020
   431
berghofe@26835
   432
val union_term = curry (gen_union Pattern.aeconv);
berghofe@26835
   433
val union_bterm = curry (gen_union
berghofe@26835
   434
  (fn ((b:bool, t), (b', t')) => b = b' andalso Pattern.aeconv (t, t')));
berghofe@26835
   435
boehmes@31510
   436
fun add_atoms (lhs, _, _, rhs, _, _) =
boehmes@31510
   437
  union_term (map fst lhs) o union_term (map fst rhs);
nipkow@6056
   438
boehmes@31510
   439
fun atoms_of ds = fold add_atoms ds [];
boehmes@31510
   440
boehmes@31510
   441
(*
nipkow@6056
   442
Simplification may detect a contradiction 'prematurely' due to type
nipkow@6056
   443
information: n+1 <= 0 is simplified to False and does not need to be crossed
nipkow@6056
   444
with 0 <= n.
nipkow@6056
   445
*)
nipkow@6056
   446
local
wenzelm@24076
   447
  exception FalseE of thm
nipkow@6056
   448
in
wenzelm@27020
   449
wenzelm@24076
   450
fun mkthm ss asms (just: injust) =
wenzelm@24076
   451
  let
wenzelm@24076
   452
    val ctxt = Simplifier.the_context ss;
wenzelm@24076
   453
    val thy = ProofContext.theory_of ctxt;
boehmes@31510
   454
    val {add_mono_thms, mult_mono_thms, inj_thms, lessD, simpset,
boehmes@31510
   455
      number_of = (_, num_of), ...} = get_data ctxt;
wenzelm@24076
   456
    val simpset' = Simplifier.inherit_context ss simpset;
boehmes@31510
   457
    fun only_concl f thm =
boehmes@31510
   458
      if Thm.no_prems thm then f (Thm.concl_of thm) else NONE;
boehmes@31510
   459
    val atoms = atoms_of (map_filter (only_concl (LA_Data.decomp ctxt)) asms);
boehmes@31510
   460
boehmes@31510
   461
    fun use_first rules thm =
boehmes@31510
   462
      get_first (fn th => SOME (thm RS th) handle THM _ => NONE) rules
boehmes@31510
   463
boehmes@31510
   464
    fun add2 thm1 thm2 =
boehmes@31510
   465
      use_first add_mono_thms (thm1 RS (thm2 RS LA_Logic.conjI));
boehmes@31510
   466
    fun try_add thms thm = get_first (fn th => add2 th thm) thms;
nipkow@6056
   467
boehmes@31510
   468
    fun add_thms thm1 thm2 =
boehmes@31510
   469
      (case add2 thm1 thm2 of
boehmes@31510
   470
        NONE =>
boehmes@31510
   471
          (case try_add ([thm1] RL inj_thms) thm2 of
boehmes@31510
   472
            NONE =>
boehmes@31510
   473
              (the (try_add ([thm2] RL inj_thms) thm1)
boehmes@31510
   474
                handle Option =>
wenzelm@32091
   475
                  (trace_thm ctxt "" thm1; trace_thm ctxt "" thm2;
boehmes@31510
   476
                   sys_error "Linear arithmetic: failed to add thms"))
boehmes@31510
   477
          | SOME thm => thm)
boehmes@31510
   478
      | SOME thm => thm);
boehmes@31510
   479
boehmes@31510
   480
    fun mult_by_add n thm =
boehmes@31510
   481
      let fun mul i th = if i = 1 then th else mul (i - 1) (add_thms thm th)
boehmes@31510
   482
      in mul n thm end;
nipkow@10575
   483
boehmes@31510
   484
    val rewr = Simplifier.rewrite simpset';
boehmes@31510
   485
    val rewrite_concl = Conv.fconv_rule (Conv.concl_conv ~1 (Conv.arg_conv
boehmes@31510
   486
      (Conv.binop_conv rewr)));
boehmes@31510
   487
    fun discharge_prem thm = if Thm.nprems_of thm = 0 then thm else
boehmes@31510
   488
      let val cv = Conv.arg1_conv (Conv.arg_conv rewr)
boehmes@31510
   489
      in Thm.implies_elim (Conv.fconv_rule cv thm) LA_Logic.trueI end
webertj@20217
   490
boehmes@31510
   491
    fun mult n thm =
boehmes@31510
   492
      (case use_first mult_mono_thms thm of
boehmes@31510
   493
        NONE => mult_by_add n thm
boehmes@31510
   494
      | SOME mth =>
boehmes@31510
   495
          let
boehmes@31510
   496
            val cv = mth |> Thm.cprop_of |> Drule.strip_imp_concl
boehmes@31510
   497
              |> Thm.dest_arg |> Thm.dest_arg1 |> Thm.dest_arg1
boehmes@31510
   498
            val T = #T (Thm.rep_cterm cv)
boehmes@31510
   499
          in
boehmes@31510
   500
            mth
boehmes@31510
   501
            |> Thm.instantiate ([], [(cv, num_of thy T n)])
boehmes@31510
   502
            |> rewrite_concl
boehmes@31510
   503
            |> discharge_prem
boehmes@31510
   504
            handle CTERM _ => mult_by_add n thm
boehmes@31510
   505
                 | THM _ => mult_by_add n thm
boehmes@31510
   506
          end);
nipkow@10691
   507
boehmes@31510
   508
    fun mult_thm (n, thm) =
boehmes@31510
   509
      if n = ~1 then thm RS LA_Logic.sym
boehmes@31510
   510
      else if n < 0 then mult (~n) thm RS LA_Logic.sym
boehmes@31510
   511
      else mult n thm;
boehmes@31510
   512
boehmes@31510
   513
    fun simp thm =
wenzelm@32091
   514
      let val thm' = trace_thm ctxt "Simplified:" (full_simplify simpset' thm)
boehmes@31510
   515
      in if LA_Logic.is_False thm' then raise FalseE thm' else thm' end;
nipkow@6056
   516
wenzelm@32091
   517
    fun mk (Asm i) = trace_thm ctxt ("Asm " ^ string_of_int i) (nth asms i)
wenzelm@32091
   518
      | mk (Nat i) = trace_thm ctxt ("Nat " ^ string_of_int i) (LA_Logic.mk_nat_thm thy (nth atoms i))
wenzelm@32091
   519
      | mk (LessD j) = trace_thm ctxt "L" (hd ([mk j] RL lessD))
wenzelm@32091
   520
      | mk (NotLeD j) = trace_thm ctxt "NLe" (mk j RS LA_Logic.not_leD)
wenzelm@32091
   521
      | mk (NotLeDD j) = trace_thm ctxt "NLeD" (hd ([mk j RS LA_Logic.not_leD] RL lessD))
wenzelm@32091
   522
      | mk (NotLessD j) = trace_thm ctxt "NL" (mk j RS LA_Logic.not_lessD)
wenzelm@32091
   523
      | mk (Added (j1, j2)) = simp (trace_thm ctxt "+" (add_thms (mk j1) (mk j2)))
wenzelm@32091
   524
      | mk (Multiplied (n, j)) =
wenzelm@32091
   525
          (trace_msg ("*" ^ string_of_int n); trace_thm ctxt "*" (mult_thm (n, mk j)))
nipkow@5982
   526
wenzelm@27020
   527
  in
wenzelm@27020
   528
    let
wenzelm@27020
   529
      val _ = trace_msg "mkthm";
wenzelm@32091
   530
      val thm = trace_thm ctxt "Final thm:" (mk just);
wenzelm@27020
   531
      val fls = simplify simpset' thm;
wenzelm@32091
   532
      val _ = trace_thm ctxt "After simplification:" fls;
wenzelm@27020
   533
      val _ =
wenzelm@27020
   534
        if LA_Logic.is_False fls then ()
wenzelm@27020
   535
        else
wenzelm@32740
   536
          let val count = CRITICAL (fn () => Unsynchronized.inc warning_count) in
wenzelm@27020
   537
            if count > warning_count_max then ()
wenzelm@27020
   538
            else
wenzelm@27020
   539
              (tracing (cat_lines
wenzelm@32091
   540
                (["Assumptions:"] @ map (Display.string_of_thm ctxt) asms @ [""] @
wenzelm@32091
   541
                 ["Proved:", Display.string_of_thm ctxt fls, ""] @
wenzelm@27020
   542
                 (if count <> warning_count_max then []
wenzelm@27020
   543
                  else ["\n(Reached maximal message count -- disabling future warnings)"])));
wenzelm@27020
   544
                warning "Linear arithmetic should have refuted the assumptions.\n\
wenzelm@27020
   545
                  \Please inform Tobias Nipkow (nipkow@in.tum.de).")
wenzelm@27020
   546
          end;
wenzelm@27020
   547
    in fls end
wenzelm@32091
   548
    handle FalseE thm => trace_thm ctxt "False reached early:" thm
wenzelm@27020
   549
  end;
wenzelm@27020
   550
nipkow@6056
   551
end;
nipkow@5982
   552
haftmann@23261
   553
fun coeff poly atom =
berghofe@26835
   554
  AList.lookup Pattern.aeconv poly atom |> the_default 0;
nipkow@10691
   555
nipkow@10691
   556
fun integ(rlhs,r,rel,rrhs,s,d) =
haftmann@17951
   557
let val (rn,rd) = Rat.quotient_of_rat r and (sn,sd) = Rat.quotient_of_rat s
wenzelm@24630
   558
    val m = Integer.lcms(map (abs o snd o Rat.quotient_of_rat) (r :: s :: map snd rlhs @ map snd rrhs))
wenzelm@22846
   559
    fun mult(t,r) =
haftmann@17951
   560
        let val (i,j) = Rat.quotient_of_rat r
paulson@15965
   561
        in (t,i * (m div j)) end
nipkow@12932
   562
in (m,(map mult rlhs, rn*(m div rd), rel, map mult rrhs, sn*(m div sd), d)) end
nipkow@10691
   563
nipkow@13498
   564
fun mklineq n atoms =
webertj@20217
   565
  fn (item, k) =>
webertj@20217
   566
  let val (m, (lhs,i,rel,rhs,j,discrete)) = integ item
nipkow@13498
   567
      val lhsa = map (coeff lhs) atoms
nipkow@13498
   568
      and rhsa = map (coeff rhs) atoms
haftmann@18330
   569
      val diff = map2 (curry (op -)) rhsa lhsa
nipkow@13498
   570
      val c = i-j
nipkow@13498
   571
      val just = Asm k
boehmes@31511
   572
      fun lineq(c,le,cs,j) = Lineq(c,le,cs, if m=1 then j else Multiplied(m,j))
nipkow@13498
   573
  in case rel of
nipkow@13498
   574
      "<="   => lineq(c,Le,diff,just)
nipkow@13498
   575
     | "~<=" => if discrete
nipkow@13498
   576
                then lineq(1-c,Le,map (op ~) diff,NotLeDD(just))
nipkow@13498
   577
                else lineq(~c,Lt,map (op ~) diff,NotLeD(just))
nipkow@13498
   578
     | "<"   => if discrete
nipkow@13498
   579
                then lineq(c+1,Le,diff,LessD(just))
nipkow@13498
   580
                else lineq(c,Lt,diff,just)
nipkow@13498
   581
     | "~<"  => lineq(~c,Le,map (op~) diff,NotLessD(just))
nipkow@13498
   582
     | "="   => lineq(c,Eq,diff,just)
wenzelm@22846
   583
     | _     => sys_error("mklineq" ^ rel)
nipkow@5982
   584
  end;
nipkow@5982
   585
nipkow@13498
   586
(* ------------------------------------------------------------------------- *)
nipkow@13498
   587
(* Print (counter) example                                                   *)
nipkow@13498
   588
(* ------------------------------------------------------------------------- *)
nipkow@13498
   589
nipkow@13498
   590
fun print_atom((a,d),r) =
haftmann@17951
   591
  let val (p,q) = Rat.quotient_of_rat r
wenzelm@24630
   592
      val s = if d then string_of_int p else
nipkow@13498
   593
              if p = 0 then "0"
wenzelm@24630
   594
              else string_of_int p ^ "/" ^ string_of_int q
nipkow@13498
   595
  in a ^ " = " ^ s end;
nipkow@13498
   596
wenzelm@19049
   597
fun produce_ex sds =
haftmann@17496
   598
  curry (op ~~) sds
haftmann@17496
   599
  #> map print_atom
haftmann@17496
   600
  #> commas
webertj@23197
   601
  #> curry (op ^) "Counterexample (possibly spurious):\n";
nipkow@13498
   602
wenzelm@24076
   603
fun trace_ex ctxt params atoms discr n (hist: history) =
webertj@20217
   604
  case hist of
webertj@20217
   605
    [] => ()
webertj@20217
   606
  | (v, lineqs) :: hist' =>
wenzelm@24076
   607
      let
wenzelm@24076
   608
        val frees = map Free params
wenzelm@24920
   609
        fun show_term t = Syntax.string_of_term ctxt (subst_bounds (frees, t))
wenzelm@24076
   610
        val start =
wenzelm@24076
   611
          if v = ~1 then (hist', findex0 discr n lineqs)
haftmann@22950
   612
          else (hist, replicate n Rat.zero)
wenzelm@24076
   613
        val ex = SOME (produce_ex (map show_term atoms ~~ discr)
wenzelm@24076
   614
            (uncurry (fold (findex1 discr)) start))
webertj@20217
   615
          handle NoEx => NONE
wenzelm@24076
   616
      in
wenzelm@24076
   617
        case ex of
haftmann@30687
   618
          SOME s => (warning "Linear arithmetic failed - see trace for a counterexample."; tracing s)
haftmann@30687
   619
        | NONE => warning "Linear arithmetic failed"
wenzelm@24076
   620
      end;
nipkow@13498
   621
webertj@20217
   622
(* ------------------------------------------------------------------------- *)
webertj@20217
   623
webertj@20268
   624
fun mknat (pTs : typ list) (ixs : int list) (atom : term, i : int) : lineq option =
webertj@20217
   625
  if LA_Logic.is_nat (pTs, atom)
nipkow@6056
   626
  then let val l = map (fn j => if j=i then 1 else 0) ixs
webertj@20217
   627
       in SOME (Lineq (0, Le, l, Nat i)) end
webertj@20217
   628
  else NONE;
nipkow@6056
   629
nipkow@13186
   630
(* This code is tricky. It takes a list of premises in the order they occur
skalberg@15531
   631
in the subgoal. Numerical premises are coded as SOME(tuple), non-numerical
skalberg@15531
   632
ones as NONE. Going through the premises, each numeric one is converted into
nipkow@13186
   633
a Lineq. The tricky bit is to convert ~= which is split into two cases < and
nipkow@13498
   634
>. Thus split_items returns a list of equation systems. This may blow up if
nipkow@13186
   635
there are many ~=, but in practice it does not seem to happen. The really
nipkow@13186
   636
tricky bit is to arrange the order of the cases such that they coincide with
nipkow@13186
   637
the order in which the cases are in the end generated by the tactic that
nipkow@13186
   638
applies the generated refutation thms (see function 'refute_tac').
nipkow@13186
   639
nipkow@13186
   640
For variables n of type nat, a constraint 0 <= n is added.
nipkow@13186
   641
*)
webertj@20217
   642
webertj@20217
   643
(* FIXME: To optimize, the splitting of cases and the search for refutations *)
webertj@20276
   644
(*        could be intertwined: separate the first (fully split) case,       *)
webertj@20217
   645
(*        refute it, continue with splitting and refuting.  Terminate with   *)
webertj@20217
   646
(*        failure as soon as a case could not be refuted; i.e. delay further *)
webertj@20217
   647
(*        splitting until after a refutation for other cases has been found. *)
webertj@20217
   648
webertj@30406
   649
fun split_items ctxt do_pre split_neq (Ts, terms) : (typ list * (LA_Data.decomp * int) list) list =
webertj@20276
   650
let
webertj@20276
   651
  (* splits inequalities '~=' into '<' and '>'; this corresponds to *)
webertj@20276
   652
  (* 'REPEAT_DETERM (eresolve_tac neqE i)' at the theorem/tactic    *)
webertj@20276
   653
  (* level                                                          *)
webertj@20276
   654
  (* FIXME: this is currently sensitive to the order of theorems in *)
webertj@20276
   655
  (*        neqE:  The theorem for type "nat" must come first.  A   *)
webertj@20276
   656
  (*        better (i.e. less likely to break when neqE changes)    *)
webertj@20276
   657
  (*        implementation should *test* which theorem from neqE    *)
webertj@20276
   658
  (*        can be applied, and split the premise accordingly.      *)
wenzelm@26945
   659
  fun elim_neq (ineqs : (LA_Data.decomp option * bool) list) :
wenzelm@26945
   660
               (LA_Data.decomp option * bool) list list =
webertj@20276
   661
  let
wenzelm@26945
   662
    fun elim_neq' nat_only ([] : (LA_Data.decomp option * bool) list) :
wenzelm@26945
   663
                  (LA_Data.decomp option * bool) list list =
webertj@20276
   664
          [[]]
webertj@20276
   665
      | elim_neq' nat_only ((NONE, is_nat) :: ineqs) =
webertj@20276
   666
          map (cons (NONE, is_nat)) (elim_neq' nat_only ineqs)
webertj@20276
   667
      | elim_neq' nat_only ((ineq as (SOME (l, i, rel, r, j, d), is_nat)) :: ineqs) =
webertj@20276
   668
          if rel = "~=" andalso (not nat_only orelse is_nat) then
webertj@20276
   669
            (* [| ?l ~= ?r; ?l < ?r ==> ?R; ?r < ?l ==> ?R |] ==> ?R *)
webertj@20276
   670
            elim_neq' nat_only (ineqs @ [(SOME (l, i, "<", r, j, d), is_nat)]) @
webertj@20276
   671
            elim_neq' nat_only (ineqs @ [(SOME (r, j, "<", l, i, d), is_nat)])
webertj@20276
   672
          else
webertj@20276
   673
            map (cons ineq) (elim_neq' nat_only ineqs)
webertj@20276
   674
  in
webertj@20276
   675
    ineqs |> elim_neq' true
wenzelm@26945
   676
          |> maps (elim_neq' false)
webertj@20276
   677
  end
nipkow@13464
   678
webertj@30406
   679
  fun ignore_neq (NONE, bool) = (NONE, bool)
webertj@30406
   680
    | ignore_neq (ineq as SOME (_, _, rel, _, _, _), bool) =
webertj@30406
   681
      if rel = "~=" then (NONE, bool) else (ineq, bool)
webertj@30406
   682
webertj@20276
   683
  fun number_hyps _ []             = []
webertj@20276
   684
    | number_hyps n (NONE::xs)     = number_hyps (n+1) xs
webertj@20276
   685
    | number_hyps n ((SOME x)::xs) = (x, n) :: number_hyps (n+1) xs
webertj@20276
   686
webertj@20276
   687
  val result = (Ts, terms)
webertj@20276
   688
    |> (* user-defined preprocessing of the subgoal *)
wenzelm@24076
   689
       (if do_pre then LA_Data.pre_decomp ctxt else Library.single)
webertj@23195
   690
    |> tap (fn subgoals => trace_msg ("Preprocessing yields " ^
webertj@23195
   691
         string_of_int (length subgoals) ^ " subgoal(s) total."))
wenzelm@22846
   692
    |> (* produce the internal encoding of (in-)equalities *)
wenzelm@24076
   693
       map (apsnd (map (fn t => (LA_Data.decomp ctxt t, LA_Data.domain_is_nat t))))
webertj@20276
   694
    |> (* splitting of inequalities *)
webertj@30406
   695
       map (apsnd (if split_neq then elim_neq else
webertj@30406
   696
                     Library.single o map ignore_neq))
wenzelm@22846
   697
    |> maps (fn (Ts, subgoals) => map (pair Ts o map fst) subgoals)
webertj@20276
   698
    |> (* numbering of hypotheses, ignoring irrelevant ones *)
webertj@20276
   699
       map (apsnd (number_hyps 0))
webertj@23195
   700
in
webertj@23195
   701
  trace_msg ("Splitting of inequalities yields " ^
webertj@23195
   702
    string_of_int (length result) ^ " subgoal(s) total.");
webertj@23195
   703
  result
webertj@23195
   704
end;
nipkow@13464
   705
wenzelm@26945
   706
fun add_datoms (dats : (bool * term) list, ((lhs,_,_,rhs,_,d) : LA_Data.decomp, _)) :
webertj@20268
   707
  (bool * term) list =
berghofe@26835
   708
  union_bterm (map (pair d o fst) lhs) (union_bterm (map (pair d o fst) rhs) dats);
nipkow@13498
   709
wenzelm@26945
   710
fun discr (initems : (LA_Data.decomp * int) list) : bool list =
webertj@20268
   711
  map fst (Library.foldl add_datoms ([],initems));
webertj@20217
   712
wenzelm@24076
   713
fun refutes ctxt params show_ex :
wenzelm@26945
   714
    (typ list * (LA_Data.decomp * int) list) list -> injust list -> injust list option =
wenzelm@26945
   715
  let
wenzelm@26945
   716
    fun refute ((Ts, initems : (LA_Data.decomp * int) list) :: initemss) (js: injust list) =
wenzelm@26945
   717
          let
boehmes@31510
   718
            val atoms = atoms_of (map fst initems)
wenzelm@26945
   719
            val n = length atoms
wenzelm@26945
   720
            val mkleq = mklineq n atoms
wenzelm@26945
   721
            val ixs = 0 upto (n - 1)
wenzelm@26945
   722
            val iatoms = atoms ~~ ixs
wenzelm@32952
   723
            val natlineqs = map_filter (mknat Ts ixs) iatoms
wenzelm@26945
   724
            val ineqs = map mkleq initems @ natlineqs
wenzelm@26945
   725
          in case elim (ineqs, []) of
wenzelm@26945
   726
               Success j =>
wenzelm@26945
   727
                 (trace_msg ("Contradiction! (" ^ string_of_int (length js + 1) ^ ")");
wenzelm@26945
   728
                  refute initemss (js @ [j]))
wenzelm@26945
   729
             | Failure hist =>
wenzelm@26945
   730
                 (if not show_ex then ()
wenzelm@26945
   731
                  else
wenzelm@26945
   732
                    let
wenzelm@26945
   733
                      val (param_names, ctxt') = ctxt |> Variable.variant_fixes (map fst params)
wenzelm@26945
   734
                      val (more_names, ctxt'') = ctxt' |> Variable.variant_fixes
wenzelm@26945
   735
                        (Name.invents (Variable.names_of ctxt') Name.uu (length Ts - length params))
wenzelm@26945
   736
                      val params' = (more_names @ param_names) ~~ Ts
wenzelm@26945
   737
                    in
wenzelm@26945
   738
                      trace_ex ctxt'' params' atoms (discr initems) n hist
wenzelm@26945
   739
                    end; NONE)
wenzelm@26945
   740
          end
wenzelm@26945
   741
      | refute [] js = SOME js
wenzelm@26945
   742
  in refute end;
nipkow@5982
   743
webertj@30406
   744
fun refute ctxt params show_ex do_pre split_neq terms : injust list option =
webertj@30406
   745
  refutes ctxt params show_ex (split_items ctxt do_pre split_neq
webertj@30406
   746
    (map snd params, terms)) [];
webertj@20254
   747
haftmann@22950
   748
fun count P xs = length (filter P xs);
webertj@20254
   749
webertj@30406
   750
fun prove ctxt params show_ex do_pre Hs concl : bool * injust list option =
webertj@20254
   751
  let
webertj@23190
   752
    val _ = trace_msg "prove:"
webertj@20254
   753
    (* append the negated conclusion to 'Hs' -- this corresponds to     *)
webertj@20254
   754
    (* 'DETERM (resolve_tac [LA_Logic.notI, LA_Logic.ccontr] i)' at the *)
webertj@20254
   755
    (* theorem/tactic level                                             *)
webertj@20254
   756
    val Hs' = Hs @ [LA_Logic.neg_prop concl]
webertj@20254
   757
    fun is_neq NONE                 = false
webertj@20254
   758
      | is_neq (SOME (_,_,r,_,_,_)) = (r = "~=")
webertj@30406
   759
    val neq_limit = Config.get ctxt LA_Data.fast_arith_neq_limit
webertj@30406
   760
    val split_neq = count is_neq (map (LA_Data.decomp ctxt) Hs') <= neq_limit
webertj@20254
   761
  in
webertj@30406
   762
    if split_neq then ()
wenzelm@24076
   763
    else
webertj@30406
   764
      trace_msg ("fast_arith_neq_limit exceeded (current value is " ^
webertj@30406
   765
        string_of_int neq_limit ^ "), ignoring all inequalities");
webertj@30406
   766
    (split_neq, refute ctxt params show_ex do_pre split_neq Hs')
webertj@23190
   767
  end handle TERM ("neg_prop", _) =>
webertj@23190
   768
    (* since no meta-logic negation is available, we can only fail if   *)
webertj@23190
   769
    (* the conclusion is not of the form 'Trueprop $ _' (simply         *)
webertj@23190
   770
    (* dropping the conclusion doesn't work either, because even        *)
webertj@23190
   771
    (* 'False' does not imply arbitrary 'concl::prop')                  *)
webertj@30406
   772
    (trace_msg "prove failed (cannot negate conclusion).";
webertj@30406
   773
      (false, NONE));
webertj@20217
   774
webertj@30406
   775
fun refute_tac ss (i, split_neq, justs) =
nipkow@6074
   776
  fn state =>
wenzelm@24076
   777
    let
wenzelm@24076
   778
      val ctxt = Simplifier.the_context ss;
wenzelm@32091
   779
      val _ = trace_thm ctxt
wenzelm@32091
   780
        ("refute_tac (on subgoal " ^ string_of_int i ^ ", with " ^
wenzelm@32091
   781
          string_of_int (length justs) ^ " justification(s)):") state
wenzelm@24076
   782
      val {neqE, ...} = get_data ctxt;
wenzelm@24076
   783
      fun just1 j =
wenzelm@24076
   784
        (* eliminate inequalities *)
webertj@30406
   785
        (if split_neq then
webertj@30406
   786
          REPEAT_DETERM (eresolve_tac neqE i)
webertj@30406
   787
        else
webertj@30406
   788
          all_tac) THEN
wenzelm@32091
   789
          PRIMITIVE (trace_thm ctxt "State after neqE:") THEN
wenzelm@24076
   790
          (* use theorems generated from the actual justifications *)
wenzelm@32283
   791
          Subgoal.FOCUS (fn {prems, ...} => rtac (mkthm ss prems j) 1) ctxt i
wenzelm@24076
   792
    in
wenzelm@24076
   793
      (* rewrite "[| A1; ...; An |] ==> B" to "[| A1; ...; An; ~B |] ==> False" *)
wenzelm@24076
   794
      DETERM (resolve_tac [LA_Logic.notI, LA_Logic.ccontr] i) THEN
wenzelm@24076
   795
      (* user-defined preprocessing of the subgoal *)
wenzelm@24076
   796
      DETERM (LA_Data.pre_tac ctxt i) THEN
wenzelm@32091
   797
      PRIMITIVE (trace_thm ctxt "State after pre_tac:") THEN
wenzelm@24076
   798
      (* prove every resulting subgoal, using its justification *)
wenzelm@24076
   799
      EVERY (map just1 justs)
webertj@20217
   800
    end  state;
nipkow@6074
   801
nipkow@5982
   802
(*
nipkow@5982
   803
Fast but very incomplete decider. Only premises and conclusions
nipkow@5982
   804
that are already (negated) (in)equations are taken into account.
nipkow@5982
   805
*)
wenzelm@24076
   806
fun simpset_lin_arith_tac ss show_ex = SUBGOAL (fn (A, i) =>
wenzelm@24076
   807
  let
wenzelm@24076
   808
    val ctxt = Simplifier.the_context ss
wenzelm@24076
   809
    val params = rev (Logic.strip_params A)
wenzelm@24076
   810
    val Hs = Logic.strip_assums_hyp A
wenzelm@24076
   811
    val concl = Logic.strip_assums_concl A
wenzelm@24076
   812
    val _ = trace_term ctxt ("Trying to refute subgoal " ^ string_of_int i) A
wenzelm@24076
   813
  in
wenzelm@24076
   814
    case prove ctxt params show_ex true Hs concl of
webertj@30406
   815
      (_, NONE) => (trace_msg "Refutation failed."; no_tac)
webertj@30406
   816
    | (split_neq, SOME js) => (trace_msg "Refutation succeeded.";
webertj@30406
   817
                               refute_tac ss (i, split_neq, js))
wenzelm@24076
   818
  end);
nipkow@5982
   819
wenzelm@24076
   820
fun cut_lin_arith_tac ss =
wenzelm@24076
   821
  cut_facts_tac (Simplifier.prems_of_ss ss) THEN'
wenzelm@24076
   822
  simpset_lin_arith_tac ss false;
wenzelm@17613
   823
wenzelm@24076
   824
fun lin_arith_tac ctxt =
wenzelm@24076
   825
  simpset_lin_arith_tac (Simplifier.context ctxt Simplifier.empty_ss);
wenzelm@24076
   826
wenzelm@24076
   827
nipkow@5982
   828
nipkow@13186
   829
(** Forward proof from theorems **)
nipkow@13186
   830
webertj@20433
   831
(* More tricky code. Needs to arrange the proofs of the multiple cases (due
webertj@20433
   832
to splits of ~= premises) such that it coincides with the order of the cases
webertj@20433
   833
generated by function split_items. *)
webertj@20433
   834
webertj@20433
   835
datatype splittree = Tip of thm list
webertj@20433
   836
                   | Spl of thm * cterm * splittree * cterm * splittree;
webertj@20433
   837
webertj@20433
   838
(* "(ct1 ==> ?R) ==> (ct2 ==> ?R) ==> ?R" is taken to (ct1, ct2) *)
webertj@20433
   839
webertj@20433
   840
fun extract (imp : cterm) : cterm * cterm =
webertj@20433
   841
let val (Il, r)    = Thm.dest_comb imp
webertj@20433
   842
    val (_, imp1)  = Thm.dest_comb Il
webertj@20433
   843
    val (Ict1, _)  = Thm.dest_comb imp1
webertj@20433
   844
    val (_, ct1)   = Thm.dest_comb Ict1
webertj@20433
   845
    val (Ir, _)    = Thm.dest_comb r
webertj@20433
   846
    val (_, Ict2r) = Thm.dest_comb Ir
webertj@20433
   847
    val (Ict2, _)  = Thm.dest_comb Ict2r
webertj@20433
   848
    val (_, ct2)   = Thm.dest_comb Ict2
webertj@20433
   849
in (ct1, ct2) end;
webertj@20433
   850
wenzelm@24076
   851
fun splitasms ctxt (asms : thm list) : splittree =
wenzelm@24076
   852
let val {neqE, ...} = get_data ctxt
webertj@20433
   853
    fun elim_neq (asms', []) = Tip (rev asms')
webertj@20433
   854
      | elim_neq (asms', asm::asms) =
webertj@20433
   855
      (case get_first (fn th => SOME (asm COMP th) handle THM _ => NONE) neqE of
webertj@20433
   856
        SOME spl =>
webertj@20433
   857
          let val (ct1, ct2) = extract (cprop_of spl)
webertj@20433
   858
              val thm1 = assume ct1
webertj@20433
   859
              val thm2 = assume ct2
webertj@20433
   860
          in Spl (spl, ct1, elim_neq (asms', asms@[thm1]), ct2, elim_neq (asms', asms@[thm2]))
webertj@20433
   861
          end
webertj@20433
   862
      | NONE => elim_neq (asm::asms', asms))
webertj@20433
   863
in elim_neq ([], asms) end;
webertj@20433
   864
wenzelm@24076
   865
fun fwdproof ss (Tip asms : splittree) (j::js : injust list) = (mkthm ss asms j, js)
wenzelm@24076
   866
  | fwdproof ss (Spl (thm, ct1, tree1, ct2, tree2)) js =
wenzelm@24076
   867
      let
wenzelm@24076
   868
        val (thm1, js1) = fwdproof ss tree1 js
wenzelm@24076
   869
        val (thm2, js2) = fwdproof ss tree2 js1
webertj@20433
   870
        val thm1' = implies_intr ct1 thm1
webertj@20433
   871
        val thm2' = implies_intr ct2 thm2
wenzelm@24076
   872
      in (thm2' COMP (thm1' COMP thm), js2) end;
wenzelm@24076
   873
      (* FIXME needs handle THM _ => NONE ? *)
webertj@20433
   874
webertj@30406
   875
fun prover ss thms Tconcl (js : injust list) split_neq pos : thm option =
wenzelm@24076
   876
  let
wenzelm@24076
   877
    val ctxt = Simplifier.the_context ss
wenzelm@24076
   878
    val thy = ProofContext.theory_of ctxt
wenzelm@24076
   879
    val nTconcl = LA_Logic.neg_prop Tconcl
wenzelm@24076
   880
    val cnTconcl = cterm_of thy nTconcl
wenzelm@24076
   881
    val nTconclthm = assume cnTconcl
webertj@30406
   882
    val tree = (if split_neq then splitasms ctxt else Tip) (thms @ [nTconclthm])
wenzelm@24076
   883
    val (Falsethm, _) = fwdproof ss tree js
wenzelm@24076
   884
    val contr = if pos then LA_Logic.ccontr else LA_Logic.notI
wenzelm@24076
   885
    val concl = implies_intr cnTconcl Falsethm COMP contr
wenzelm@32091
   886
  in SOME (trace_thm ctxt "Proved by lin. arith. prover:" (LA_Logic.mk_Eq concl)) end
wenzelm@24076
   887
  (*in case concl contains ?-var, which makes assume fail:*)   (* FIXME Variable.import_terms *)
wenzelm@24076
   888
  handle THM _ => NONE;
nipkow@13186
   889
nipkow@13186
   890
(* PRE: concl is not negated!
nipkow@13186
   891
   This assumption is OK because
wenzelm@24076
   892
   1. lin_arith_simproc tries both to prove and disprove concl and
wenzelm@24076
   893
   2. lin_arith_simproc is applied by the Simplifier which
nipkow@13186
   894
      dives into terms and will thus try the non-negated concl anyway.
nipkow@13186
   895
*)
wenzelm@24076
   896
fun lin_arith_simproc ss concl =
wenzelm@24076
   897
  let
wenzelm@24076
   898
    val ctxt = Simplifier.the_context ss
wenzelm@26945
   899
    val thms = maps LA_Logic.atomize (Simplifier.prems_of_ss ss)
wenzelm@24076
   900
    val Hs = map Thm.prop_of thms
nipkow@6102
   901
    val Tconcl = LA_Logic.mk_Trueprop concl
wenzelm@24076
   902
  in
wenzelm@24076
   903
    case prove ctxt [] false false Hs Tconcl of (* concl provable? *)
webertj@30406
   904
      (split_neq, SOME js) => prover ss thms Tconcl js split_neq true
webertj@30406
   905
    | (_, NONE) =>
wenzelm@24076
   906
        let val nTconcl = LA_Logic.neg_prop Tconcl in
wenzelm@24076
   907
          case prove ctxt [] false false Hs nTconcl of (* ~concl provable? *)
webertj@30406
   908
            (split_neq, SOME js) => prover ss thms nTconcl js split_neq false
webertj@30406
   909
          | (_, NONE) => NONE
wenzelm@24076
   910
        end
wenzelm@24076
   911
  end;
nipkow@6074
   912
nipkow@6074
   913
end;