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