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