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