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