src/HOL/Tools/Sledgehammer/sledgehammer_mepo.ML
author blanchet
Wed Oct 09 15:39:34 2013 +0200 (2013-10-09 ago)
changeset 54089 b13f6731f873
parent 54088 40366d99fa39
child 54090 a28992e35032
permissions -rw-r--r--
use same relevance filter for ATP and SMT solvers -- attempting to filter out certain ground instances of polymorphic symbols like + and 0 has unexpected side-effects that lead to incompletenesses (relevant facts not being selected)
blanchet@48380
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mepo.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@39958
     4
blanchet@48380
     5
Sledgehammer's iterative relevance filter (MePo = Meng-Paulson).
wenzelm@33309
     6
*)
paulson@15452
     7
blanchet@48381
     8
signature SLEDGEHAMMER_MEPO =
wenzelm@16802
     9
sig
blanchet@46340
    10
  type stature = ATP_Problem_Generate.stature
blanchet@51004
    11
  type raw_fact = Sledgehammer_Fact.raw_fact
blanchet@48296
    12
  type fact = Sledgehammer_Fact.fact
blanchet@48288
    13
  type params = Sledgehammer_Provers.params
blanchet@48288
    14
  type relevance_fudge = Sledgehammer_Provers.relevance_fudge
blanchet@40070
    15
blanchet@42646
    16
  val trace : bool Config.T
blanchet@48219
    17
  val pseudo_abs_name : string
blanchet@48406
    18
  val mepo_suggested_facts :
blanchet@48288
    19
    Proof.context -> params -> string -> int -> relevance_fudge option
blanchet@51004
    20
    -> term list -> term -> raw_fact list -> fact list
paulson@15347
    21
end;
paulson@15347
    22
blanchet@48381
    23
structure Sledgehammer_MePo : SLEDGEHAMMER_MEPO =
paulson@15347
    24
struct
paulson@15347
    25
blanchet@46320
    26
open ATP_Problem_Generate
blanchet@50608
    27
open Sledgehammer_Util
blanchet@48296
    28
open Sledgehammer_Fact
blanchet@48288
    29
open Sledgehammer_Provers
blanchet@38652
    30
blanchet@42646
    31
val trace =
blanchet@53548
    32
  Attrib.setup_config_bool @{binding sledgehammer_mepo_trace} (K false)
blanchet@42646
    33
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@35826
    34
blanchet@37616
    35
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@48219
    36
val pseudo_abs_name = sledgehammer_prefix ^ "abs"
blanchet@38992
    37
val theory_const_suffix = Long_Name.separator ^ " 1"
blanchet@37616
    38
blanchet@46073
    39
fun order_of_type (Type (@{type_name fun}, [T1, T2])) =
blanchet@38939
    40
    Int.max (order_of_type T1 + 1, order_of_type T2)
blanchet@38939
    41
  | order_of_type (Type (_, Ts)) = fold (Integer.max o order_of_type) Ts 0
blanchet@38939
    42
  | order_of_type _ = 0
blanchet@38939
    43
blanchet@38823
    44
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
    45
datatype pattern = PVar | PApp of string * pattern list
blanchet@54087
    46
datatype ptype = PType of int * typ list
blanchet@38744
    47
blanchet@51998
    48
fun string_of_pattern PVar = "_"
blanchet@51998
    49
  | string_of_pattern (PApp (s, ps)) =
blanchet@51998
    50
    if null ps then s else s ^ string_of_patterns ps
blanchet@51998
    51
and string_of_patterns ps = "(" ^ commas (map string_of_pattern ps) ^ ")"
blanchet@54086
    52
blanchet@54087
    53
fun string_of_patternT (TVar _) = "_"
blanchet@54087
    54
  | string_of_patternT (Type (s, ps)) =
blanchet@54086
    55
    if null ps then s else s ^ string_of_patternsT ps
blanchet@54087
    56
  | string_of_patternT (TFree (s, _)) = s
blanchet@54086
    57
and string_of_patternsT ps = "(" ^ commas (map string_of_patternT ps) ^ ")"
blanchet@54086
    58
fun string_of_ptype (PType (_, ps)) = string_of_patternsT ps
paulson@24287
    59
paulson@24287
    60
(*Is the second type an instance of the first one?*)
blanchet@54087
    61
fun match_patternT (TVar _, _) = true
blanchet@54087
    62
  | match_patternT (Type (s, ps), Type (t, qs)) =
blanchet@54086
    63
    s = t andalso match_patternsT (ps, qs)
blanchet@54087
    64
  | match_patternT (TFree (s, _), TFree (t, _)) = s = t
blanchet@54087
    65
  | match_patternT (_, _) = false
blanchet@54086
    66
and match_patternsT (_, []) = true
blanchet@54086
    67
  | match_patternsT ([], _) = false
blanchet@54086
    68
  | match_patternsT (p :: ps, q :: qs) =
blanchet@54086
    69
    match_patternT (p, q) andalso match_patternsT (ps, qs)
blanchet@54086
    70
fun match_ptype (PType (_, ps), PType (_, qs)) = match_patternsT (ps, qs)
paulson@24287
    71
blanchet@38823
    72
(* Is there a unifiable constant? *)
blanchet@38827
    73
fun pconst_mem f consts (s, ps) =
blanchet@38939
    74
  exists (curry (match_ptype o f) ps)
blanchet@38827
    75
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
    76
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38939
    77
  exists (curry (match_ptype o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
    78
blanchet@38744
    79
(* Pairs a constant with the list of its type instantiations. *)
blanchet@41204
    80
fun ptype thy const x =
blanchet@54087
    81
  (if const then these (try (Sign.const_typargs thy) x) else [])
blanchet@41204
    82
fun rich_ptype thy const (s, T) =
blanchet@41204
    83
  PType (order_of_type T, ptype thy const (s, T))
blanchet@41204
    84
fun rich_pconst thy const (s, T) = (s, rich_ptype thy const (s, T))
paulson@24287
    85
blanchet@51998
    86
fun string_of_hyper_pconst (s, ps) =
blanchet@51998
    87
  s ^ "{" ^ commas (map string_of_ptype ps) ^ "}"
paulson@24287
    88
blanchet@54087
    89
fun patternT_eq (TVar _, TVar _) = true
blanchet@54087
    90
  | patternT_eq (Type (s, Ts), Type (t, Us)) = s = t andalso patternsT_eq (Ts, Us)
blanchet@54087
    91
  | patternT_eq (TFree (s, _), TFree (t, _)) = (s = t)
blanchet@54087
    92
  | patternT_eq _ = false
blanchet@54087
    93
and patternsT_eq ([], []) = true
blanchet@54087
    94
  | patternsT_eq ([], _) = false
blanchet@54087
    95
  | patternsT_eq (_, []) = false
blanchet@54087
    96
  | patternsT_eq (T :: Ts, U :: Us) = patternT_eq (T, U) andalso patternsT_eq (Ts, Us)
blanchet@54087
    97
fun ptype_eq (PType (m, Ts), PType (n, Us)) = m = n andalso patternsT_eq (Ts, Us)
blanchet@54087
    98
blanchet@54087
    99
 (* Add a pconstant to the table, but a [] entry means a standard connective,
blanchet@54087
   100
    which we ignore. *)
blanchet@54087
   101
fun add_pconst_to_table (s, p) = Symtab.map_default (s, [p]) (insert ptype_eq p)
blanchet@38819
   102
blanchet@47933
   103
(* Set constants tend to pull in too many irrelevant facts. We limit the damage
blanchet@47933
   104
   by treating them more or less as if they were built-in but add their
blanchet@47933
   105
   axiomatization at the end. *)
blanchet@47933
   106
val set_consts = [@{const_name Collect}, @{const_name Set.member}]
blanchet@47939
   107
val set_thms = @{thms Collect_mem_eq mem_Collect_eq Collect_cong}
blanchet@47933
   108
blanchet@54089
   109
fun add_pconsts_in_term thy =
blanchet@37505
   110
  let
blanchet@54089
   111
    fun do_const const (x as (s, _)) ts =
blanchet@54089
   112
      if member (op =) set_consts s then
blanchet@54089
   113
        fold (do_term false) ts
blanchet@54089
   114
      else
blanchet@54089
   115
        (not (is_irrelevant_const s) ? add_pconst_to_table (rich_pconst thy const x))
blanchet@54089
   116
        #> fold (do_term false) ts
blanchet@42741
   117
    and do_term ext_arg t =
blanchet@38827
   118
      case strip_comb t of
blanchet@54089
   119
        (Const x, ts) => do_const true x ts
blanchet@54089
   120
      | (Free x, ts) => do_const false x ts
blanchet@38939
   121
      | (Abs (_, T, t'), ts) =>
blanchet@42741
   122
        ((null ts andalso not ext_arg)
blanchet@42741
   123
         (* Since lambdas on the right-hand side of equalities are usually
blanchet@47953
   124
            extensionalized later by "abs_extensionalize_term", we don't
blanchet@47953
   125
            penalize them here. *)
blanchet@53550
   126
         ? add_pconst_to_table (pseudo_abs_name,
blanchet@53550
   127
                                PType (order_of_type T + 1, [])))
blanchet@42735
   128
        #> fold (do_term false) (t' :: ts)
blanchet@42735
   129
      | (_, ts) => fold (do_term false) ts
blanchet@42741
   130
    and do_term_or_formula ext_arg T =
blanchet@53551
   131
      if T = HOLogic.boolT then do_formula else do_term ext_arg
blanchet@53551
   132
    and do_formula t =
blanchet@37537
   133
      case t of
blanchet@54089
   134
        Const (@{const_name all}, _) $ Abs (_, _, t') => do_formula t'
blanchet@53551
   135
      | @{const "==>"} $ t1 $ t2 => do_formula t1 #> do_formula t2
blanchet@37537
   136
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@42741
   137
        do_term_or_formula false T t1 #> do_term_or_formula true T t2
blanchet@53551
   138
      | @{const Trueprop} $ t1 => do_formula t1
blanchet@41140
   139
      | @{const False} => I
blanchet@41140
   140
      | @{const True} => I
blanchet@53551
   141
      | @{const Not} $ t1 => do_formula t1
blanchet@54089
   142
      | Const (@{const_name All}, _) $ Abs (_, _, t') => do_formula t'
blanchet@54089
   143
      | Const (@{const_name Ex}, _) $ Abs (_, _, t') => do_formula t'
blanchet@53551
   144
      | @{const HOL.conj} $ t1 $ t2 => do_formula t1 #> do_formula t2
blanchet@53551
   145
      | @{const HOL.disj} $ t1 $ t2 => do_formula t1 #> do_formula t2
blanchet@53551
   146
      | @{const HOL.implies} $ t1 $ t2 => do_formula t1 #> do_formula t2
haftmann@38864
   147
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@42741
   148
        do_term_or_formula false T t1 #> do_term_or_formula true T t2
blanchet@38587
   149
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   150
        $ t1 $ t2 $ t3 =>
blanchet@53551
   151
        do_formula t1 #> fold (do_term_or_formula false T) [t2, t3]
blanchet@54089
   152
      | Const (@{const_name Ex1}, _) $ Abs (_, _, t') => do_formula t'
blanchet@54089
   153
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, t') =>
blanchet@53551
   154
        do_formula (t1 $ Bound ~1) #> do_formula t'
blanchet@54089
   155
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, t') =>
blanchet@53551
   156
        do_formula (t1 $ Bound ~1) #> do_formula t'
blanchet@37537
   157
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@53551
   158
        do_term false t0 #> do_formula t1  (* theory constant *)
blanchet@42735
   159
      | _ => do_term false t
blanchet@53551
   160
  in do_formula end
paulson@24287
   161
blanchet@54089
   162
fun pconsts_in_fact thy t =
blanchet@48227
   163
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@54089
   164
              (Symtab.empty |> add_pconsts_in_term thy t) []
blanchet@48227
   165
blanchet@48227
   166
(* Inserts a dummy "constant" referring to the theory name, so that relevance
blanchet@48227
   167
   takes the given theory into account. *)
blanchet@41200
   168
fun theory_constify ({theory_const_rel_weight, theory_const_irrel_weight, ...}
blanchet@41200
   169
                     : relevance_fudge) thy_name t =
blanchet@40070
   170
  if exists (curry (op <) 0.0) [theory_const_rel_weight,
blanchet@40070
   171
                                theory_const_irrel_weight] then
blanchet@41200
   172
    Const (thy_name ^ theory_const_suffix, @{typ bool}) $ t
blanchet@37505
   173
  else
blanchet@41200
   174
    t
blanchet@41200
   175
blanchet@41200
   176
fun theory_const_prop_of fudge th =
blanchet@41200
   177
  theory_constify fudge (Context.theory_name (theory_of_thm th)) (prop_of th)
blanchet@37505
   178
blanchet@54089
   179
fun pair_consts_fact thy fudge fact =
blanchet@48227
   180
  case fact |> snd |> theory_const_prop_of fudge
blanchet@54089
   181
            |> pconsts_in_fact thy of
blanchet@48227
   182
    [] => NONE
blanchet@48227
   183
  | consts => SOME ((fact, consts), NONE)
blanchet@48227
   184
blanchet@38743
   185
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   186
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   187
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   188
blanchet@54086
   189
fun patternT_ord p =
blanchet@38743
   190
  case p of
blanchet@54088
   191
    (Type (s, ps), Type (t, qs)) =>
blanchet@54088
   192
    (case fast_string_ord (s, t) of
blanchet@54088
   193
      EQUAL => dict_ord patternT_ord (ps, qs)
blanchet@54088
   194
    | ord => ord)
blanchet@54088
   195
  | (TVar _, TVar _) => EQUAL
blanchet@54089
   196
  | (TVar _, _) => LESS
blanchet@54087
   197
  | (Type _, TVar _) => GREATER
blanchet@54087
   198
  | (Type _, TFree _) => LESS
blanchet@54087
   199
  | (TFree (s, _), TFree (t, _)) => fast_string_ord (s, t)
blanchet@54089
   200
  | (TFree _, _) => GREATER
blanchet@54088
   201
fun ptype_ord (PType (m, ps), PType (n, qs)) =
blanchet@54088
   202
  (case dict_ord patternT_ord (ps, qs) of
blanchet@54088
   203
    EQUAL => int_ord (m, n)
blanchet@54088
   204
  | ord => ord)
paulson@24287
   205
blanchet@38939
   206
structure PType_Tab = Table(type key = ptype val ord = ptype_ord)
paulson@24287
   207
blanchet@40204
   208
fun count_fact_consts thy fudge =
blanchet@37503
   209
  let
blanchet@38827
   210
    fun do_const const (s, T) ts =
blanchet@38827
   211
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@41204
   212
      PType_Tab.map_default (rich_ptype thy const (s, T), 0) (Integer.add 1)
blanchet@38939
   213
      |> Symtab.map_default (s, PType_Tab.empty)
blanchet@38827
   214
      #> fold do_term ts
blanchet@38827
   215
    and do_term t =
blanchet@38827
   216
      case strip_comb t of
blanchet@38827
   217
        (Const x, ts) => do_const true x ts
blanchet@38827
   218
      | (Free x, ts) => do_const false x ts
blanchet@38827
   219
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   220
      | (_, ts) => fold do_term ts
blanchet@40070
   221
  in do_term o theory_const_prop_of fudge o snd end
paulson@24287
   222
blanchet@39367
   223
fun pow_int _ 0 = 1.0
blanchet@38939
   224
  | pow_int x 1 = x
blanchet@38939
   225
  | pow_int x n = if n > 0 then x * pow_int x (n - 1) else pow_int x (n + 1) / x
blanchet@38939
   226
paulson@24287
   227
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   228
fun pconst_freq match const_tab (c, ps) =
blanchet@38939
   229
  PType_Tab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38939
   230
                 (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   231
paulson@24287
   232
blanchet@38085
   233
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   234
   These include all induction rules, and other general theorems. *)
blanchet@37503
   235
blanchet@37503
   236
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@38938
   237
   frequencies. Rare constants give more points if they are relevant than less
blanchet@38938
   238
   rare ones. *)
blanchet@39367
   239
fun rel_weight_for _ freq = 1.0 + 2.0 / Math.ln (Real.fromInt freq + 1.0)
blanchet@38938
   240
blanchet@38938
   241
(* Irrelevant constants are treated differently. We associate lower penalties to
blanchet@38938
   242
   very rare constants and very common ones -- the former because they can't
blanchet@38938
   243
   lead to the inclusion of too many new facts, and the latter because they are
blanchet@38938
   244
   so common as to be of little interest. *)
blanchet@40070
   245
fun irrel_weight_for ({worse_irrel_freq, higher_order_irrel_weight, ...}
blanchet@40070
   246
                      : relevance_fudge) order freq =
blanchet@40070
   247
  let val (k, x) = worse_irrel_freq |> `Real.ceil in
blanchet@38939
   248
    (if freq < k then Math.ln (Real.fromInt (freq + 1)) / Math.ln x
blanchet@38939
   249
     else rel_weight_for order freq / rel_weight_for order k)
blanchet@40070
   250
    * pow_int higher_order_irrel_weight (order - 1)
blanchet@38938
   251
  end
blanchet@37503
   252
blanchet@51998
   253
fun multiplier_of_const_name local_const_multiplier s =
blanchet@41790
   254
  if String.isSubstring "." s then 1.0 else local_const_multiplier
blanchet@38821
   255
blanchet@41790
   256
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@53551
   257
fun generic_pconst_weight local_const_multiplier abs_weight theory_const_weight
blanchet@53551
   258
        chained_const_weight weight_for f const_tab chained_const_tab
blanchet@53551
   259
        (c as (s, PType (m, _))) =
blanchet@48219
   260
  if s = pseudo_abs_name then
blanchet@41790
   261
    abs_weight
blanchet@41790
   262
  else if String.isSuffix theory_const_suffix s then
blanchet@41790
   263
    theory_const_weight
blanchet@41790
   264
  else
blanchet@51998
   265
    multiplier_of_const_name local_const_multiplier s
blanchet@41790
   266
    * weight_for m (pconst_freq (match_ptype o f) const_tab c)
blanchet@42735
   267
    |> (if chained_const_weight < 1.0 andalso
blanchet@42735
   268
           pconst_hyper_mem I chained_const_tab c then
blanchet@42735
   269
          curry (op *) chained_const_weight
blanchet@42735
   270
        else
blanchet@42735
   271
          I)
blanchet@41790
   272
blanchet@41790
   273
fun rel_pconst_weight ({local_const_multiplier, abs_rel_weight,
blanchet@41790
   274
                        theory_const_rel_weight, ...} : relevance_fudge)
blanchet@41790
   275
                      const_tab =
blanchet@53551
   276
  generic_pconst_weight local_const_multiplier abs_rel_weight
blanchet@42735
   277
                        theory_const_rel_weight 0.0 rel_weight_for I const_tab
blanchet@42735
   278
                        Symtab.empty
blanchet@42735
   279
blanchet@41790
   280
fun irrel_pconst_weight (fudge as {local_const_multiplier, abs_irrel_weight,
blanchet@42735
   281
                                   theory_const_irrel_weight,
blanchet@42735
   282
                                   chained_const_irrel_weight, ...})
blanchet@42735
   283
                        const_tab chained_const_tab =
blanchet@41790
   284
  generic_pconst_weight local_const_multiplier abs_irrel_weight
blanchet@53551
   285
                        theory_const_irrel_weight chained_const_irrel_weight
blanchet@53551
   286
                        (irrel_weight_for fudge) swap const_tab
blanchet@53551
   287
                        chained_const_tab
paulson@24287
   288
blanchet@46340
   289
fun stature_bonus ({intro_bonus, ...} : relevance_fudge) (_, Intro) =
blanchet@46340
   290
    intro_bonus
blanchet@46340
   291
  | stature_bonus {elim_bonus, ...} (_, Elim) = elim_bonus
blanchet@46340
   292
  | stature_bonus {simp_bonus, ...} (_, Simp) = simp_bonus
blanchet@46340
   293
  | stature_bonus {local_bonus, ...} (Local, _) = local_bonus
blanchet@46340
   294
  | stature_bonus {assum_bonus, ...} (Assum, _) = assum_bonus
blanchet@46340
   295
  | stature_bonus {chained_bonus, ...} (Chained, _) = chained_bonus
blanchet@46340
   296
  | stature_bonus _ _ = 0.0
blanchet@38751
   297
blanchet@40418
   298
fun is_odd_const_name s =
blanchet@53550
   299
  s = pseudo_abs_name orelse String.isSuffix theory_const_suffix s
blanchet@40418
   300
blanchet@53516
   301
fun fact_weight fudge stature const_tab rel_const_tab chained_const_tab
blanchet@53516
   302
                fact_consts =
blanchet@53158
   303
  case fact_consts |> List.partition (pconst_hyper_mem I rel_const_tab)
blanchet@53158
   304
                   ||> filter_out (pconst_hyper_mem swap rel_const_tab) of
blanchet@38827
   305
    ([], _) => 0.0
blanchet@38744
   306
  | (rel, irrel) =>
blanchet@40418
   307
    if forall (forall (is_odd_const_name o fst)) [rel, irrel] then
blanchet@40371
   308
      0.0
blanchet@40371
   309
    else
blanchet@40371
   310
      let
blanchet@42735
   311
        val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@40371
   312
        val rel_weight =
blanchet@40371
   313
          0.0 |> fold (curry (op +) o rel_pconst_weight fudge const_tab) rel
blanchet@40371
   314
        val irrel_weight =
blanchet@46340
   315
          ~ (stature_bonus fudge stature)
blanchet@42735
   316
          |> fold (curry (op +)
blanchet@53158
   317
                   o irrel_pconst_weight fudge const_tab chained_const_tab)
blanchet@53158
   318
                  irrel
blanchet@40371
   319
        val res = rel_weight / (rel_weight + irrel_weight)
blanchet@40371
   320
      in if Real.isFinite res then res else 0.0 end
blanchet@38747
   321
blanchet@48293
   322
fun take_most_relevant ctxt max_facts remaining_max
blanchet@42728
   323
        ({max_imperfect, max_imperfect_exp, ...} : relevance_fudge)
blanchet@51004
   324
        (candidates : ((raw_fact * (string * ptype) list) * real) list) =
blanchet@38744
   325
  let
blanchet@38747
   326
    val max_imperfect =
blanchet@40070
   327
      Real.ceil (Math.pow (max_imperfect,
blanchet@38904
   328
                    Math.pow (Real.fromInt remaining_max
blanchet@48293
   329
                              / Real.fromInt max_facts, max_imperfect_exp)))
blanchet@38747
   330
    val (perfect, imperfect) =
blanchet@38889
   331
      candidates |> sort (Real.compare o swap o pairself snd)
blanchet@38889
   332
                 |> take_prefix (fn (_, w) => w > 0.99999)
blanchet@38747
   333
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   334
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   335
  in
blanchet@42646
   336
    trace_msg ctxt (fn () =>
wenzelm@41491
   337
        "Actually passed (" ^ string_of_int (length accepts) ^ " of " ^
wenzelm@41491
   338
        string_of_int (length candidates) ^ "): " ^
blanchet@38889
   339
        (accepts |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   340
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   341
                 |> commas));
blanchet@38747
   342
    (accepts, more_rejects @ rejects)
blanchet@38744
   343
  end
paulson@24287
   344
blanchet@54089
   345
fun if_empty_replace_with_scope thy facts sc tab =
blanchet@38819
   346
  if Symtab.is_empty tab then
blanchet@42732
   347
    Symtab.empty
blanchet@54089
   348
    |> fold (add_pconsts_in_term thy)
blanchet@46340
   349
            (map_filter (fn ((_, (sc', _)), th) =>
blanchet@46340
   350
                            if sc' = sc then SOME (prop_of th) else NONE) facts)
blanchet@38819
   351
  else
blanchet@38819
   352
    tab
blanchet@38819
   353
blanchet@54089
   354
fun consider_arities th =
blanchet@41158
   355
  let
blanchet@41158
   356
    fun aux _ _ NONE = NONE
blanchet@41158
   357
      | aux t args (SOME tab) =
blanchet@41158
   358
        case t of
blanchet@41158
   359
          t1 $ t2 => SOME tab |> aux t1 (t2 :: args) |> aux t2 []
blanchet@54089
   360
        | Const (s, _) =>
blanchet@54089
   361
          (if is_widely_irrelevant_const s then
blanchet@41158
   362
             SOME tab
blanchet@41158
   363
           else case Symtab.lookup tab s of
blanchet@41158
   364
             NONE => SOME (Symtab.update (s, length args) tab)
blanchet@41158
   365
           | SOME n => if n = length args then SOME tab else NONE)
blanchet@41158
   366
        | _ => SOME tab
blanchet@41158
   367
  in aux (prop_of th) [] end
blanchet@41158
   368
blanchet@44785
   369
(* FIXME: This is currently only useful for polymorphic type encodings. *)
blanchet@54089
   370
fun could_benefit_from_ext facts =
blanchet@54089
   371
  fold (consider_arities o snd) facts (SOME Symtab.empty) |> is_none
blanchet@41158
   372
blanchet@43492
   373
(* High enough so that it isn't wrongly considered as very relevant (e.g., for E
blanchet@43492
   374
   weights), but low enough so that it is unlikely to be truncated away if few
blanchet@43492
   375
   facts are included. *)
blanchet@53546
   376
val special_fact_index = 45 (* FUDGE *)
blanchet@53546
   377
blanchet@54087
   378
fun eq_prod eqx eqy ((x1, y1), (x2, y2)) = eqx (x1, x2) andalso eqy (y1, y2)
blanchet@54087
   379
blanchet@53546
   380
val really_hopeless_get_kicked_out_iter = 5 (* FUDGE *)
blanchet@43492
   381
blanchet@54089
   382
fun relevance_filter ctxt thres0 decay max_facts
blanchet@54089
   383
        (fudge as {threshold_divisor, ridiculous_threshold, ...}) facts hyp_ts concl_t =
blanchet@38739
   384
  let
wenzelm@42361
   385
    val thy = Proof_Context.theory_of ctxt
blanchet@40204
   386
    val const_tab = fold (count_fact_consts thy fudge) facts Symtab.empty
blanchet@54089
   387
    val add_pconsts = add_pconsts_in_term thy
blanchet@48292
   388
    val chained_ts =
blanchet@48292
   389
      facts |> map_filter (fn ((_, (Chained, _)), th) => SOME (prop_of th)
blanchet@48292
   390
                            | _ => NONE)
blanchet@53551
   391
    val chained_const_tab = Symtab.empty |> fold add_pconsts chained_ts
blanchet@38819
   392
    val goal_const_tab =
blanchet@53158
   393
      Symtab.empty
blanchet@53551
   394
      |> fold add_pconsts hyp_ts
blanchet@53551
   395
      |> add_pconsts concl_t
blanchet@42732
   396
      |> (fn tab => if Symtab.is_empty tab then chained_const_tab else tab)
blanchet@54089
   397
      |> fold (if_empty_replace_with_scope thy facts) [Chained, Assum, Local]
blanchet@53516
   398
    fun iter j remaining_max thres rel_const_tab hopeless hopeful =
blanchet@38739
   399
      let
blanchet@53546
   400
        val hopeless =
blanchet@53546
   401
          hopeless |> j = really_hopeless_get_kicked_out_iter
blanchet@53546
   402
                      ? filter_out (fn (_, w) => w < 0.001)
blanchet@40191
   403
        fun relevant [] _ [] =
blanchet@38747
   404
            (* Nothing has been added this iteration. *)
blanchet@48288
   405
            if j = 0 andalso thres >= ridiculous_threshold then
blanchet@38747
   406
              (* First iteration? Try again. *)
blanchet@48293
   407
              iter 0 max_facts (thres / threshold_divisor) rel_const_tab
blanchet@53516
   408
                   hopeless hopeful
blanchet@38744
   409
            else
blanchet@40191
   410
              []
blanchet@38889
   411
          | relevant candidates rejects [] =
blanchet@38739
   412
            let
blanchet@38747
   413
              val (accepts, more_rejects) =
blanchet@48293
   414
                take_most_relevant ctxt max_facts remaining_max fudge candidates
blanchet@53546
   415
              val sps = maps (snd o fst) accepts
blanchet@38739
   416
              val rel_const_tab' =
blanchet@53550
   417
                rel_const_tab |> fold add_pconst_to_table sps
blanchet@53158
   418
              fun is_dirty (s, _) =
blanchet@53158
   419
                Symtab.lookup rel_const_tab' s <> Symtab.lookup rel_const_tab s
blanchet@38745
   420
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   421
                 (rejects @ hopeless, ([], []))
blanchet@38745
   422
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   423
                              if exists is_dirty consts then
blanchet@38745
   424
                                apfst (cons (ax, NONE))
blanchet@38745
   425
                              else
blanchet@38745
   426
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   427
                 |>> append (more_rejects
blanchet@38745
   428
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   429
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   430
                                             else SOME old_weight)))
blanchet@48288
   431
              val thres =
blanchet@48288
   432
                1.0 - (1.0 - thres)
blanchet@38822
   433
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   434
              val remaining_max = remaining_max - length accepts
blanchet@38739
   435
            in
blanchet@42646
   436
              trace_msg ctxt (fn () => "New or updated constants: " ^
blanchet@53158
   437
                  commas (rel_const_tab'
blanchet@53158
   438
                          |> Symtab.dest
blanchet@54087
   439
                          |> subtract (eq_prod (op =) (eq_list ptype_eq))
blanchet@54087
   440
                                      (rel_const_tab |> Symtab.dest)
blanchet@51998
   441
                          |> map string_of_hyper_pconst));
blanchet@38745
   442
              map (fst o fst) accepts @
blanchet@38747
   443
              (if remaining_max = 0 then
blanchet@40191
   444
                 []
blanchet@38745
   445
               else
blanchet@48288
   446
                 iter (j + 1) remaining_max thres rel_const_tab'
blanchet@53516
   447
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   448
            end
blanchet@38889
   449
          | relevant candidates rejects
blanchet@46340
   450
                     (((ax as (((_, stature), _), fact_consts)), cached_weight)
blanchet@38747
   451
                      :: hopeful) =
blanchet@38739
   452
            let
blanchet@38739
   453
              val weight =
blanchet@38739
   454
                case cached_weight of
blanchet@38739
   455
                  SOME w => w
blanchet@53158
   456
                | NONE =>
blanchet@53158
   457
                  fact_weight fudge stature const_tab rel_const_tab
blanchet@53516
   458
                              chained_const_tab fact_consts
blanchet@38739
   459
            in
blanchet@48288
   460
              if weight >= thres then
blanchet@38889
   461
                relevant ((ax, weight) :: candidates) rejects hopeful
blanchet@38739
   462
              else
blanchet@38889
   463
                relevant candidates ((ax, weight) :: rejects) hopeful
blanchet@38739
   464
            end
blanchet@38739
   465
        in
blanchet@42646
   466
          trace_msg ctxt (fn () =>
blanchet@38744
   467
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@48288
   468
              Real.toString thres ^ ", constants: " ^
blanchet@53158
   469
              commas (rel_const_tab
blanchet@53158
   470
                      |> Symtab.dest
blanchet@38744
   471
                      |> filter (curry (op <>) [] o snd)
blanchet@51998
   472
                      |> map string_of_hyper_pconst));
blanchet@38889
   473
          relevant [] [] hopeful
blanchet@38739
   474
        end
blanchet@47933
   475
    fun uses_const s t =
blanchet@47933
   476
      fold_aterms (curry (fn (Const (s', _), false) => s' = s | (_, b) => b)) t
blanchet@47933
   477
                  false
blanchet@47933
   478
    fun uses_const_anywhere accepts s =
blanchet@47933
   479
      exists (uses_const s o prop_of o snd) accepts orelse
blanchet@47933
   480
      exists (uses_const s) (concl_t :: hyp_ts)
blanchet@47933
   481
    fun add_set_const_thms accepts =
blanchet@47933
   482
      exists (uses_const_anywhere accepts) set_consts ? append set_thms
blanchet@43492
   483
    fun insert_into_facts accepts [] = accepts
blanchet@43492
   484
      | insert_into_facts accepts ths =
blanchet@43492
   485
        let
blanchet@43492
   486
          val add = facts |> filter (member Thm.eq_thm_prop ths o snd)
blanchet@43492
   487
          val (bef, after) =
blanchet@43492
   488
            accepts |> filter_out (member Thm.eq_thm_prop ths o snd)
blanchet@48293
   489
                    |> take (max_facts - length add)
blanchet@43492
   490
                    |> chop special_fact_index
blanchet@43492
   491
        in bef @ add @ after end
blanchet@43492
   492
    fun insert_special_facts accepts =
blanchet@51026
   493
      (* FIXME: get rid of "ext" here once it is treated as a helper *)
blanchet@54089
   494
      [] |> could_benefit_from_ext accepts ? cons @{thm ext}
blanchet@51026
   495
         |> add_set_const_thms accepts
blanchet@51026
   496
         |> insert_into_facts accepts
blanchet@38739
   497
  in
blanchet@54089
   498
    facts |> map_filter (pair_consts_fact thy fudge)
blanchet@53516
   499
          |> iter 0 max_facts thres0 goal_const_tab []
blanchet@43492
   500
          |> insert_special_facts
blanchet@42646
   501
          |> tap (fn accepts => trace_msg ctxt (fn () =>
wenzelm@41491
   502
                      "Total relevant: " ^ string_of_int (length accepts)))
blanchet@38739
   503
  end
paulson@24287
   504
blanchet@48406
   505
fun mepo_suggested_facts ctxt
blanchet@48293
   506
        ({fact_thresholds = (thres0, thres1), ...} : params) prover
blanchet@48293
   507
        max_facts fudge hyp_ts concl_t facts =
blanchet@37538
   508
  let
wenzelm@42361
   509
    val thy = Proof_Context.theory_of ctxt
blanchet@48288
   510
    val fudge =
blanchet@48288
   511
      case fudge of
blanchet@48288
   512
        SOME fudge => fudge
blanchet@51998
   513
      | NONE => Sledgehammer_Provers.relevance_fudge_of_prover ctxt prover
blanchet@48288
   514
    val decay = Math.pow ((1.0 - thres1) / (1.0 - thres0),
blanchet@48293
   515
                          1.0 / Real.fromInt (max_facts + 1))
blanchet@37538
   516
  in
blanchet@54089
   517
    trace_msg ctxt (fn () => "Considering " ^ string_of_int (length facts) ^ " facts");
blanchet@48288
   518
    (if thres1 < 0.0 then
blanchet@40204
   519
       facts
blanchet@48288
   520
     else if thres0 > 1.0 orelse thres0 > thres1 then
blanchet@38739
   521
       []
blanchet@38739
   522
     else
blanchet@54089
   523
       relevance_filter ctxt thres0 decay max_facts fudge facts hyp_ts
blanchet@54089
   524
         (concl_t |> theory_constify fudge (Context.theory_name thy)))
blanchet@51004
   525
    |> map fact_of_raw_fact
blanchet@37538
   526
  end
immler@30536
   527
paulson@15347
   528
end;