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