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