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