src/HOL/Tools/Sledgehammer/sledgehammer_mash.ML
author blanchet
Fri, 18 Jan 2013 16:06:45 +0100
changeset 51984 4179fa5c79fe
parent 51982 00d87ade2294
child 52000 23bb011a5832
permissions -rw-r--r--
tuning
blanchet@49395
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mash.ML
blanchet@49263
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49263
     3
blanchet@49263
     4
Sledgehammer's machine-learning-based relevance filter (MaSh).
blanchet@49263
     5
*)
blanchet@49263
     6
blanchet@49396
     7
signature SLEDGEHAMMER_MASH =
blanchet@49263
     8
sig
blanchet@49266
     9
  type stature = ATP_Problem_Generate.stature
blanchet@49311
    10
  type fact = Sledgehammer_Fact.fact
blanchet@49311
    11
  type fact_override = Sledgehammer_Fact.fact_override
blanchet@49266
    12
  type params = Sledgehammer_Provers.params
blanchet@49303
    13
  type relevance_fudge = Sledgehammer_Provers.relevance_fudge
blanchet@49266
    14
  type prover_result = Sledgehammer_Provers.prover_result
blanchet@49266
    15
blanchet@49323
    16
  val trace : bool Config.T
blanchet@49334
    17
  val MaShN : string
blanchet@49394
    18
  val mepoN : string
blanchet@49394
    19
  val mashN : string
blanchet@49329
    20
  val meshN : string
blanchet@49407
    21
  val unlearnN : string
blanchet@49407
    22
  val learn_isarN : string
blanchet@51499
    23
  val learn_proverN : string
blanchet@49407
    24
  val relearn_isarN : string
blanchet@51499
    25
  val relearn_proverN : string
blanchet@49329
    26
  val fact_filters : string list
blanchet@51841
    27
  val encode_str : string -> string
blanchet@51841
    28
  val encode_strs : string list -> string
blanchet@51841
    29
  val unencode_str : string -> string
blanchet@51841
    30
  val unencode_strs : string -> string list
blanchet@51371
    31
  val encode_features : (string * real) list -> string
blanchet@51980
    32
  val extract_suggestions : string -> string * string list
blanchet@51647
    33
blanchet@51647
    34
  structure MaSh:
blanchet@51647
    35
  sig
blanchet@51647
    36
    val unlearn : Proof.context -> unit
blanchet@51647
    37
    val learn :
blanchet@51647
    38
      Proof.context -> bool
blanchet@51647
    39
      -> (string * string list * (string * real) list * string list) list -> unit
blanchet@51647
    40
    val relearn :
blanchet@51647
    41
      Proof.context -> bool -> (string * string list) list -> unit
blanchet@51984
    42
    val query :
blanchet@51873
    43
      Proof.context -> bool -> bool -> int
blanchet@51980
    44
      -> string list * (string * real) list * string list -> string list
blanchet@51647
    45
  end
blanchet@51647
    46
blanchet@51326
    47
  val mash_unlearn : Proof.context -> unit
blanchet@51639
    48
  val nickname_of_thm : thm -> string
blanchet@51982
    49
  val find_suggested_facts : ('b * thm) list -> string list -> ('b * thm) list
blanchet@49336
    50
  val mesh_facts :
blanchet@51829
    51
    ('a * 'a -> bool) -> int -> (real * (('a * real) list * 'a list)) list
blanchet@51829
    52
    -> 'a list
blanchet@49266
    53
  val theory_ord : theory * theory -> order
blanchet@49266
    54
  val thm_ord : thm * thm -> order
blanchet@49266
    55
  val goal_of_thm : theory -> thm -> thm
blanchet@49336
    56
  val run_prover_for_mash :
blanchet@49333
    57
    Proof.context -> params -> string -> fact list -> thm -> prover_result
blanchet@49407
    58
  val features_of :
blanchet@51371
    59
    Proof.context -> string -> theory -> stature -> term list
blanchet@51371
    60
    -> (string * real) list
blanchet@51769
    61
  val trim_dependencies : thm -> string list -> string list option
blanchet@51750
    62
  val isar_dependencies_of :
blanchet@51769
    63
    string Symtab.table * string Symtab.table -> thm -> string list
blanchet@51499
    64
  val prover_dependencies_of :
blanchet@51750
    65
    Proof.context -> params -> string -> int -> fact list
blanchet@51750
    66
    -> string Symtab.table * string Symtab.table -> thm
blanchet@51769
    67
    -> bool * string list
blanchet@51623
    68
  val weight_mash_facts : 'a list -> ('a * real) list
blanchet@51427
    69
  val find_mash_suggestions :
blanchet@51980
    70
    int -> string list -> ('b * thm) list -> ('b * thm) list -> ('b * thm) list
blanchet@51980
    71
    -> ('b * thm) list * ('b * thm) list
blanchet@49421
    72
  val mash_suggested_facts :
blanchet@51398
    73
    Proof.context -> params -> string -> int -> term list -> term -> fact list
blanchet@51455
    74
    -> fact list * fact list
blanchet@49398
    75
  val mash_learn_proof :
blanchet@49399
    76
    Proof.context -> params -> string -> term -> ('a * thm) list -> thm list
blanchet@49399
    77
    -> unit
blanchet@49410
    78
  val mash_learn :
blanchet@49410
    79
    Proof.context -> params -> fact_override -> thm list -> bool -> unit
blanchet@51326
    80
  val is_mash_enabled : unit -> bool
blanchet@51326
    81
  val mash_can_suggest_facts : Proof.context -> bool
blanchet@51427
    82
  val generous_max_facts : int -> int
blanchet@51829
    83
  val mepo_weight : real
blanchet@51829
    84
  val mash_weight : real
blanchet@49303
    85
  val relevant_facts :
blanchet@49307
    86
    Proof.context -> params -> string -> int -> fact_override -> term list
blanchet@49311
    87
    -> term -> fact list -> fact list
blanchet@49334
    88
  val kill_learners : unit -> unit
blanchet@49334
    89
  val running_learners : unit -> unit
blanchet@49263
    90
end;
blanchet@49263
    91
blanchet@49396
    92
structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
blanchet@49263
    93
struct
blanchet@49264
    94
blanchet@49266
    95
open ATP_Util
blanchet@49266
    96
open ATP_Problem_Generate
blanchet@49266
    97
open Sledgehammer_Util
blanchet@49266
    98
open Sledgehammer_Fact
blanchet@49266
    99
open Sledgehammer_Provers
blanchet@49333
   100
open Sledgehammer_Minimize
blanchet@49396
   101
open Sledgehammer_MePo
blanchet@49266
   102
blanchet@49323
   103
val trace =
blanchet@49395
   104
  Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
blanchet@49323
   105
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@49323
   106
blanchet@49334
   107
val MaShN = "MaSh"
blanchet@49334
   108
blanchet@49394
   109
val mepoN = "mepo"
blanchet@49394
   110
val mashN = "mash"
blanchet@49329
   111
val meshN = "mesh"
blanchet@49329
   112
blanchet@49394
   113
val fact_filters = [meshN, mepoN, mashN]
blanchet@49329
   114
blanchet@49407
   115
val unlearnN = "unlearn"
blanchet@49407
   116
val learn_isarN = "learn_isar"
blanchet@51499
   117
val learn_proverN = "learn_prover"
blanchet@49407
   118
val relearn_isarN = "relearn_isar"
blanchet@51499
   119
val relearn_proverN = "relearn_prover"
blanchet@49407
   120
blanchet@49409
   121
fun mash_model_dir () =
blanchet@51355
   122
  Path.explode "$ISABELLE_HOME_USER/mash" |> tap Isabelle_System.mkdir
blanchet@49409
   123
val mash_state_dir = mash_model_dir
blanchet@51325
   124
fun mash_state_file () = Path.append (mash_state_dir ()) (Path.explode "state")
blanchet@49266
   125
blanchet@49345
   126
blanchet@51326
   127
(*** Low-level communication with MaSh ***)
blanchet@51326
   128
blanchet@51326
   129
fun wipe_out_file file = (try (File.rm o Path.explode) file; ())
blanchet@51326
   130
blanchet@51350
   131
fun write_file banner (xs, f) path =
blanchet@51350
   132
  (case banner of SOME s => File.write path s | NONE => ();
blanchet@51350
   133
   xs |> chunk_list 500
blanchet@51350
   134
      |> List.app (File.append path o space_implode "" o map f))
blanchet@51334
   135
  handle IO.Io _ => ()
blanchet@51326
   136
blanchet@51326
   137
fun run_mash_tool ctxt overlord save max_suggs write_cmds read_suggs =
blanchet@51326
   138
  let
blanchet@51326
   139
    val (temp_dir, serial) =
blanchet@51326
   140
      if overlord then (getenv "ISABELLE_HOME_USER", "")
blanchet@51326
   141
      else (getenv "ISABELLE_TMP", serial_string ())
blanchet@51326
   142
    val log_file = if overlord then temp_dir ^ "/mash_log" else "/dev/null"
blanchet@51326
   143
    val err_file = temp_dir ^ "/mash_err" ^ serial
blanchet@51326
   144
    val sugg_file = temp_dir ^ "/mash_suggs" ^ serial
blanchet@51350
   145
    val sugg_path = Path.explode sugg_file
blanchet@51326
   146
    val cmd_file = temp_dir ^ "/mash_commands" ^ serial
blanchet@51350
   147
    val cmd_path = Path.explode cmd_file
blanchet@51326
   148
    val core =
blanchet@51326
   149
      "--inputFile " ^ cmd_file ^ " --predictions " ^ sugg_file ^
blanchet@51326
   150
      " --numberOfPredictions " ^ string_of_int max_suggs ^
blanchet@51966
   151
      (* " --learnTheories" ^ *) (if save then " --saveModel" else "")
blanchet@51326
   152
    val command =
blanchet@51350
   153
      "\"$ISABELLE_SLEDGEHAMMER_MASH/src/mash.py\" --quiet --outputDir " ^
blanchet@51350
   154
      File.shell_path (mash_model_dir ()) ^ " --log " ^ log_file ^ " " ^ core ^
blanchet@51326
   155
      " >& " ^ err_file
blanchet@51326
   156
    fun run_on () =
blanchet@51765
   157
      (Isabelle_System.bash command
blanchet@51765
   158
       |> tap (fn _ => trace_msg ctxt (fn () =>
blanchet@51765
   159
              case try File.read (Path.explode err_file) of
blanchet@51765
   160
                NONE => "Done"
blanchet@51765
   161
              | SOME "" => "Done"
blanchet@51765
   162
              | SOME s => "Error: " ^ elide_string 1000 s));
blanchet@51350
   163
       read_suggs (fn () => try File.read_lines sugg_path |> these))
blanchet@51326
   164
    fun clean_up () =
blanchet@51326
   165
      if overlord then ()
blanchet@51326
   166
      else List.app wipe_out_file [err_file, sugg_file, cmd_file]
blanchet@51326
   167
  in
blanchet@51350
   168
    write_file (SOME "") ([], K "") sugg_path;
blanchet@51350
   169
    write_file (SOME "") write_cmds cmd_path;
blanchet@51326
   170
    trace_msg ctxt (fn () => "Running " ^ command);
blanchet@51326
   171
    with_cleanup clean_up run_on ()
blanchet@51326
   172
  end
blanchet@49266
   173
blanchet@49323
   174
fun meta_char c =
blanchet@49266
   175
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse
blanchet@49266
   176
     c = #")" orelse c = #"," then
blanchet@49266
   177
    String.str c
blanchet@49266
   178
  else
blanchet@49266
   179
    (* fixed width, in case more digits follow *)
blanchet@49410
   180
    "%" ^ stringN_of_int 3 (Char.ord c)
blanchet@49266
   181
blanchet@49323
   182
fun unmeta_chars accum [] = String.implode (rev accum)
blanchet@49410
   183
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
blanchet@49323
   184
    (case Int.fromString (String.implode [d1, d2, d3]) of
blanchet@49323
   185
       SOME n => unmeta_chars (Char.chr n :: accum) cs
blanchet@49323
   186
     | NONE => "" (* error *))
blanchet@49410
   187
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
blanchet@49323
   188
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs
blanchet@49323
   189
blanchet@51841
   190
val encode_str = String.translate meta_char
blanchet@51841
   191
val encode_strs = map encode_str #> space_implode " "
blanchet@51841
   192
val unencode_str = String.explode #> unmeta_chars []
blanchet@51841
   193
val unencode_strs =
blanchet@51841
   194
  space_explode " " #> filter_out (curry (op =) "") #> map unencode_str
blanchet@49266
   195
blanchet@51873
   196
fun freshish_name () =
blanchet@51873
   197
  Date.fmt ".%Y%m%d_%H%M%S__" (Date.fromTimeLocal (Time.now ())) ^
blanchet@51873
   198
  serial_string ()
blanchet@51873
   199
blanchet@51371
   200
fun encode_feature (name, weight) =
blanchet@51841
   201
  encode_str name ^
blanchet@51404
   202
  (if Real.== (weight, 1.0) then "" else "=" ^ Real.toString weight)
blanchet@51371
   203
blanchet@51371
   204
val encode_features = map encode_feature #> space_implode " "
blanchet@51371
   205
blanchet@51646
   206
fun str_of_learn (name, parents, feats, deps) =
blanchet@51841
   207
  "! " ^ encode_str name ^ ": " ^ encode_strs parents ^ "; " ^
blanchet@51841
   208
  encode_features feats ^ "; " ^ encode_strs deps ^ "\n"
blanchet@49684
   209
blanchet@51646
   210
fun str_of_relearn (name, deps) =
blanchet@51841
   211
  "p " ^ encode_str name ^ ": " ^ encode_strs deps ^ "\n"
blanchet@49684
   212
blanchet@51873
   213
fun str_of_query learn_hints (parents, feats, hints) =
blanchet@51873
   214
  (if not learn_hints orelse null hints then ""
blanchet@51873
   215
   else str_of_learn (freshish_name (), parents, feats, hints)) ^
blanchet@51841
   216
  "? " ^ encode_strs parents ^ "; " ^ encode_features feats ^
blanchet@51873
   217
  (if learn_hints orelse null hints then "" else "; " ^ encode_strs hints) ^
blanchet@51873
   218
  "\n"
blanchet@49421
   219
blanchet@51980
   220
(* The weights currently returned by "mash.py" are too spaced out to make any
blanchet@51980
   221
   sense. *)
blanchet@49421
   222
fun extract_suggestion sugg =
blanchet@49421
   223
  case space_explode "=" sugg of
blanchet@49421
   224
    [name, weight] =>
blanchet@51980
   225
    SOME (unencode_str name (* , Real.fromString weight |> the_default 1.0 *))
blanchet@51980
   226
  | [name] => SOME (unencode_str name (* , 1.0 *))
blanchet@49421
   227
  | _ => NONE
blanchet@49421
   228
blanchet@51648
   229
fun extract_suggestions line =
blanchet@49326
   230
  case space_explode ":" line of
blanchet@49421
   231
    [goal, suggs] =>
blanchet@51841
   232
    (unencode_str goal, map_filter extract_suggestion (space_explode " " suggs))
blanchet@49327
   233
  | _ => ("", [])
blanchet@49326
   234
blanchet@51647
   235
structure MaSh =
blanchet@51647
   236
struct
blanchet@51647
   237
blanchet@51647
   238
fun unlearn ctxt =
blanchet@51326
   239
  let val path = mash_model_dir () in
blanchet@51647
   240
    trace_msg ctxt (K "MaSh unlearn");
blanchet@51334
   241
    try (File.fold_dir (fn file => fn _ =>
blanchet@51334
   242
                           try File.rm (Path.append path (Path.basic file)))
blanchet@51334
   243
                       path) NONE;
blanchet@51326
   244
    ()
blanchet@51326
   245
  end
blanchet@51326
   246
blanchet@51647
   247
fun learn _ _ [] = ()
blanchet@51647
   248
  | learn ctxt overlord learns =
blanchet@51647
   249
    (trace_msg ctxt (fn () => "MaSh learn " ^
blanchet@51646
   250
         elide_string 1000 (space_implode " " (map #1 learns)));
blanchet@51646
   251
     run_mash_tool ctxt overlord true 0 (learns, str_of_learn) (K ()))
blanchet@51326
   252
blanchet@51647
   253
fun relearn _ _ [] = ()
blanchet@51647
   254
  | relearn ctxt overlord relearns =
blanchet@51647
   255
    (trace_msg ctxt (fn () => "MaSh relearn " ^
blanchet@51646
   256
         elide_string 1000 (space_implode " " (map #1 relearns)));
blanchet@51646
   257
     run_mash_tool ctxt overlord true 0 (relearns, str_of_relearn) (K ()))
blanchet@51326
   258
blanchet@51984
   259
fun query ctxt overlord learn_hints max_suggs (query as (_, feats, hints)) =
blanchet@51984
   260
  (trace_msg ctxt (fn () => "MaSh query " ^ encode_features feats);
blanchet@51873
   261
   run_mash_tool ctxt overlord (learn_hints andalso not (null hints))
blanchet@51873
   262
       max_suggs ([query], str_of_query learn_hints)
blanchet@51326
   263
       (fn suggs =>
blanchet@51326
   264
           case suggs () of
blanchet@51326
   265
             [] => []
blanchet@51648
   266
           | suggs => snd (extract_suggestions (List.last suggs)))
blanchet@51326
   267
   handle List.Empty => [])
blanchet@51326
   268
blanchet@51647
   269
end;
blanchet@51647
   270
blanchet@51326
   271
blanchet@51326
   272
(*** Middle-level communication with MaSh ***)
blanchet@51326
   273
blanchet@51499
   274
datatype proof_kind =
blanchet@51499
   275
  Isar_Proof | Automatic_Proof | Isar_Proof_wegen_Prover_Flop
blanchet@51326
   276
blanchet@51326
   277
fun str_of_proof_kind Isar_Proof = "i"
blanchet@51499
   278
  | str_of_proof_kind Automatic_Proof = "a"
blanchet@51499
   279
  | str_of_proof_kind Isar_Proof_wegen_Prover_Flop = "x"
blanchet@51326
   280
blanchet@51326
   281
fun proof_kind_of_str "i" = Isar_Proof
blanchet@51499
   282
  | proof_kind_of_str "a" = Automatic_Proof
blanchet@51499
   283
  | proof_kind_of_str "x" = Isar_Proof_wegen_Prover_Flop
blanchet@51326
   284
blanchet@51326
   285
(* FIXME: Here a "Graph.update_node" function would be useful *)
blanchet@51625
   286
fun update_access_graph_node (name, kind) =
blanchet@51326
   287
  Graph.default_node (name, Isar_Proof)
blanchet@51326
   288
  #> kind <> Isar_Proof ? Graph.map_node name (K kind)
blanchet@51326
   289
blanchet@51326
   290
fun try_graph ctxt when def f =
blanchet@51326
   291
  f ()
blanchet@51326
   292
  handle Graph.CYCLES (cycle :: _) =>
blanchet@51326
   293
         (trace_msg ctxt (fn () =>
blanchet@51326
   294
              "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
blanchet@51326
   295
       | Graph.DUP name =>
blanchet@51326
   296
         (trace_msg ctxt (fn () =>
blanchet@51326
   297
              "Duplicate fact " ^ quote name ^ " when " ^ when); def)
blanchet@51326
   298
       | Graph.UNDEF name =>
blanchet@51326
   299
         (trace_msg ctxt (fn () =>
blanchet@51326
   300
              "Unknown fact " ^ quote name ^ " when " ^ when); def)
blanchet@51326
   301
       | exn =>
blanchet@51326
   302
         if Exn.is_interrupt exn then
blanchet@51326
   303
           reraise exn
blanchet@51326
   304
         else
blanchet@51326
   305
           (trace_msg ctxt (fn () =>
blanchet@51326
   306
                "Internal error when " ^ when ^ ":\n" ^
blanchet@51326
   307
                ML_Compiler.exn_message exn); def)
blanchet@51326
   308
blanchet@51326
   309
fun graph_info G =
blanchet@51326
   310
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
blanchet@51326
   311
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^
blanchet@51326
   312
  " edge(s), " ^
blanchet@51326
   313
  string_of_int (length (Graph.minimals G)) ^ " minimal, " ^
blanchet@51326
   314
  string_of_int (length (Graph.maximals G)) ^ " maximal"
blanchet@51326
   315
blanchet@51625
   316
type mash_state = {access_G : unit Graph.T, dirty : string list option}
blanchet@51326
   317
blanchet@51625
   318
val empty_state = {access_G = Graph.empty, dirty = SOME []}
blanchet@51326
   319
blanchet@51326
   320
local
blanchet@51326
   321
blanchet@51889
   322
val version = "*** MaSh version 20130113a ***"
blanchet@51372
   323
blanchet@51372
   324
exception Too_New of unit
blanchet@51326
   325
blanchet@51326
   326
fun extract_node line =
blanchet@51326
   327
  case space_explode ":" line of
blanchet@51326
   328
    [head, parents] =>
blanchet@51326
   329
    (case space_explode " " head of
blanchet@51326
   330
       [kind, name] =>
blanchet@51841
   331
       SOME (unencode_str name, unencode_strs parents,
blanchet@51326
   332
             try proof_kind_of_str kind |> the_default Isar_Proof)
blanchet@51326
   333
     | _ => NONE)
blanchet@51326
   334
  | _ => NONE
blanchet@51326
   335
blanchet@51326
   336
fun load _ (state as (true, _)) = state
blanchet@51326
   337
  | load ctxt _ =
blanchet@51326
   338
    let val path = mash_state_file () in
blanchet@51326
   339
      (true,
blanchet@51326
   340
       case try File.read_lines path of
blanchet@51326
   341
         SOME (version' :: node_lines) =>
blanchet@51326
   342
         let
blanchet@51326
   343
           fun add_edge_to name parent =
blanchet@51326
   344
             Graph.default_node (parent, Isar_Proof)
blanchet@51326
   345
             #> Graph.add_edge (parent, name)
blanchet@51326
   346
           fun add_node line =
blanchet@51326
   347
             case extract_node line of
blanchet@51326
   348
               NONE => I (* shouldn't happen *)
blanchet@51326
   349
             | SOME (name, parents, kind) =>
blanchet@51625
   350
               update_access_graph_node (name, kind)
blanchet@51326
   351
               #> fold (add_edge_to name) parents
blanchet@51625
   352
           val access_G =
blanchet@51372
   353
             case string_ord (version', version) of
blanchet@51372
   354
               EQUAL =>
blanchet@51372
   355
               try_graph ctxt "loading state" Graph.empty (fn () =>
blanchet@51372
   356
                   fold add_node node_lines Graph.empty)
blanchet@51875
   357
             | LESS =>
blanchet@51875
   358
               (MaSh.unlearn ctxt; Graph.empty) (* can't parse old file *)
blanchet@51372
   359
             | GREATER => raise Too_New ()
blanchet@51326
   360
         in
blanchet@51326
   361
           trace_msg ctxt (fn () =>
blanchet@51625
   362
               "Loaded fact graph (" ^ graph_info access_G ^ ")");
blanchet@51625
   363
           {access_G = access_G, dirty = SOME []}
blanchet@51326
   364
         end
blanchet@51326
   365
       | _ => empty_state)
blanchet@51326
   366
    end
blanchet@51326
   367
blanchet@51326
   368
fun save _ (state as {dirty = SOME [], ...}) = state
blanchet@51625
   369
  | save ctxt {access_G, dirty} =
blanchet@51326
   370
    let
blanchet@51326
   371
      fun str_of_entry (name, parents, kind) =
blanchet@51841
   372
        str_of_proof_kind kind ^ " " ^ encode_str name ^ ": " ^
blanchet@51841
   373
        encode_strs parents ^ "\n"
blanchet@51326
   374
      fun append_entry (name, (kind, (parents, _))) =
blanchet@51326
   375
        cons (name, Graph.Keys.dest parents, kind)
blanchet@51326
   376
      val (banner, entries) =
blanchet@51326
   377
        case dirty of
blanchet@51326
   378
          SOME names =>
blanchet@51625
   379
          (NONE, fold (append_entry o Graph.get_entry access_G) names [])
blanchet@51625
   380
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry access_G [])
blanchet@51326
   381
    in
blanchet@51350
   382
      write_file banner (entries, str_of_entry) (mash_state_file ());
blanchet@51326
   383
      trace_msg ctxt (fn () =>
blanchet@51625
   384
          "Saved fact graph (" ^ graph_info access_G ^
blanchet@51326
   385
          (case dirty of
blanchet@51326
   386
             SOME dirty =>
blanchet@51326
   387
             "; " ^ string_of_int (length dirty) ^ " dirty fact(s)"
blanchet@51326
   388
           | _ => "") ^  ")");
blanchet@51625
   389
      {access_G = access_G, dirty = SOME []}
blanchet@51326
   390
    end
blanchet@51326
   391
blanchet@51326
   392
val global_state =
blanchet@51326
   393
  Synchronized.var "Sledgehammer_MaSh.global_state" (false, empty_state)
blanchet@51326
   394
blanchet@51326
   395
in
blanchet@51326
   396
blanchet@51585
   397
fun map_state ctxt f =
blanchet@51326
   398
  Synchronized.change global_state (load ctxt ##> (f #> save ctxt))
blanchet@51372
   399
  handle Too_New () => ()
blanchet@51326
   400
blanchet@51585
   401
fun peek_state ctxt f =
blanchet@51372
   402
  Synchronized.change_result global_state
blanchet@51372
   403
      (perhaps (try (load ctxt)) #> `snd #>> f)
blanchet@51326
   404
blanchet@51585
   405
fun clear_state ctxt =
blanchet@51326
   406
  Synchronized.change global_state (fn _ =>
blanchet@51647
   407
      (MaSh.unlearn ctxt; (* also removes the state file *)
blanchet@51326
   408
       (true, empty_state)))
blanchet@51326
   409
blanchet@51326
   410
end
blanchet@51326
   411
blanchet@51585
   412
val mash_unlearn = clear_state
blanchet@51585
   413
blanchet@51326
   414
blanchet@51326
   415
(*** Isabelle helpers ***)
blanchet@51326
   416
blanchet@51737
   417
val local_prefix = "local" ^ Long_Name.separator
blanchet@49393
   418
blanchet@51737
   419
fun elided_backquote_thm threshold th =
blanchet@51737
   420
  elide_string threshold
blanchet@51737
   421
    (backquote_thm (Proof_Context.init_global (Thm.theory_of_thm th)) th)
blanchet@49393
   422
blanchet@51639
   423
fun nickname_of_thm th =
blanchet@49409
   424
  if Thm.has_name_hint th then
blanchet@49409
   425
    let val hint = Thm.get_name_hint th in
blanchet@51737
   426
      (* There must be a better way to detect local facts. *)
blanchet@49409
   427
      case try (unprefix local_prefix) hint of
blanchet@49409
   428
        SOME suf =>
blanchet@51747
   429
        Context.theory_name (Thm.theory_of_thm th) ^ Long_Name.separator ^ suf ^
blanchet@51747
   430
        Long_Name.separator ^ elided_backquote_thm 50 th
blanchet@49409
   431
      | NONE => hint
blanchet@49409
   432
    end
blanchet@49409
   433
  else
blanchet@51737
   434
    elided_backquote_thm 200 th
blanchet@49393
   435
blanchet@51982
   436
fun find_suggested_facts facts =
blanchet@49345
   437
  let
blanchet@51639
   438
    fun add_fact (fact as (_, th)) = Symtab.default (nickname_of_thm th, fact)
blanchet@51980
   439
    val tab = fold add_fact facts Symtab.empty
blanchet@51982
   440
  in map_filter (Symtab.lookup tab) end
blanchet@49326
   441
blanchet@51398
   442
fun scaled_avg [] = 0
blanchet@51398
   443
  | scaled_avg xs =
blanchet@49422
   444
    Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs
blanchet@49343
   445
blanchet@51398
   446
fun avg [] = 0.0
blanchet@51398
   447
  | avg xs = fold (curry (op +)) xs 0.0 / Real.fromInt (length xs)
blanchet@49328
   448
blanchet@51398
   449
fun normalize_scores _ [] = []
blanchet@51398
   450
  | normalize_scores max_facts xs =
blanchet@51398
   451
    let val avg = avg (map snd (take max_facts xs)) in
blanchet@51398
   452
      map (apsnd (curry Real.* (1.0 / avg))) xs
blanchet@51398
   453
    end
blanchet@51398
   454
blanchet@51829
   455
fun mesh_facts _ max_facts [(_, (sels, unks))] =
blanchet@49421
   456
    map fst (take max_facts sels) @ take (max_facts - length sels) unks
blanchet@51876
   457
  | mesh_facts fact_eq max_facts mess =
blanchet@49329
   458
    let
blanchet@51398
   459
      val mess =
blanchet@51398
   460
        mess |> map (apsnd (apfst (normalize_scores max_facts #> `length)))
blanchet@51398
   461
      fun score_in fact (global_weight, ((sel_len, sels), unks)) =
blanchet@51398
   462
        let
blanchet@51398
   463
          fun score_at j =
blanchet@51398
   464
            case try (nth sels) j of
blanchet@51398
   465
              SOME (_, score) => SOME (global_weight * score)
blanchet@51398
   466
            | NONE => NONE
blanchet@51398
   467
        in
blanchet@51398
   468
          case find_index (curry fact_eq fact o fst) sels of
blanchet@51398
   469
            ~1 => (case find_index (curry fact_eq fact) unks of
blanchet@51876
   470
                     ~1 => SOME 0.0
blanchet@51398
   471
                   | _ => NONE)
blanchet@51398
   472
          | rank => score_at rank
blanchet@51398
   473
        end
blanchet@51398
   474
      fun weight_of fact = mess |> map_filter (score_in fact) |> scaled_avg
blanchet@49421
   475
      val facts =
blanchet@51398
   476
        fold (union fact_eq o map fst o take max_facts o snd o fst o snd) mess
blanchet@51398
   477
             []
blanchet@49329
   478
    in
blanchet@49421
   479
      facts |> map (`weight_of) |> sort (int_ord o swap o pairself fst)
blanchet@49343
   480
            |> map snd |> take max_facts
blanchet@49329
   481
    end
blanchet@49327
   482
blanchet@51889
   483
fun thy_feature_of s = ("y" ^ s, 8.0 (* FUDGE *))
blanchet@51889
   484
fun const_feature_of s = ("c" ^ s, 32.0 (* FUDGE *))
blanchet@51889
   485
fun free_feature_of s = ("f" ^ s, 40.0 (* FUDGE *))
blanchet@51889
   486
fun type_feature_of s = ("t" ^ s, 4.0 (* FUDGE *))
blanchet@51599
   487
fun class_feature_of s = ("s" ^ s, 1.0 (* FUDGE *))
blanchet@51599
   488
fun status_feature_of status = (string_of_status status, 2.0 (* FUDGE *))
blanchet@51599
   489
val local_feature = ("local", 8.0 (* FUDGE *))
blanchet@51599
   490
val lams_feature = ("lams", 2.0 (* FUDGE *))
blanchet@51599
   491
val skos_feature = ("skos", 2.0 (* FUDGE *))
blanchet@49266
   492
blanchet@49339
   493
fun theory_ord p =
blanchet@51737
   494
  if Theory.subthy p then
blanchet@51737
   495
    if Theory.eq_thy p then EQUAL else LESS
blanchet@49339
   496
  else if Theory.subthy (swap p) then
blanchet@49339
   497
    GREATER
blanchet@49339
   498
  else case int_ord (pairself (length o Theory.ancestors_of) p) of
blanchet@49339
   499
    EQUAL => string_ord (pairself Context.theory_name p)
blanchet@49339
   500
  | order => order
blanchet@49339
   501
blanchet@51397
   502
fun thm_ord p =
blanchet@51397
   503
  case theory_ord (pairself theory_of_thm p) of
blanchet@51374
   504
    EQUAL =>
blanchet@51639
   505
    let val q = pairself nickname_of_thm p in
blanchet@51639
   506
      (* Hack to put "xxx_def" before "xxxI" and "xxxE" *)
blanchet@51639
   507
      case bool_ord (pairself (String.isSuffix "_def") (swap q)) of
blanchet@51639
   508
        EQUAL => string_ord q
blanchet@51639
   509
      | ord => ord
blanchet@51639
   510
    end
blanchet@51374
   511
  | ord => ord
blanchet@49339
   512
blanchet@49407
   513
val freezeT = Type.legacy_freeze_type
blanchet@49407
   514
blanchet@49407
   515
fun freeze (t $ u) = freeze t $ freeze u
blanchet@49407
   516
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
blanchet@49407
   517
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
blanchet@49407
   518
  | freeze (Const (s, T)) = Const (s, freezeT T)
blanchet@49407
   519
  | freeze (Free (s, T)) = Free (s, freezeT T)
blanchet@49407
   520
  | freeze t = t
blanchet@49407
   521
blanchet@49407
   522
fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init
blanchet@49407
   523
blanchet@49407
   524
fun run_prover_for_mash ctxt params prover facts goal =
blanchet@49407
   525
  let
blanchet@49407
   526
    val problem =
blanchet@49407
   527
      {state = Proof.init ctxt, goal = goal, subgoal = 1, subgoal_count = 1,
blanchet@49407
   528
       facts = facts |> map (apfst (apfst (fn name => name ())))
blanchet@49407
   529
                     |> map Untranslated_Fact}
blanchet@49407
   530
  in
blanchet@51683
   531
    get_minimizing_isar_prover ctxt MaSh (K (K ())) prover params (K (K (K "")))
blanchet@51683
   532
                               problem
blanchet@49407
   533
  end
blanchet@49407
   534
blanchet@49341
   535
val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]
blanchet@49341
   536
blanchet@49413
   537
val logical_consts =
blanchet@49413
   538
  [@{const_name prop}, @{const_name Pure.conjunction}] @ atp_logical_consts
blanchet@49413
   539
blanchet@51600
   540
val max_pattern_breadth = 10
blanchet@51600
   541
blanchet@51856
   542
fun term_features_of ctxt prover thy_name term_max_depth type_max_depth ts =
blanchet@49266
   543
  let
blanchet@51407
   544
    val thy = Proof_Context.theory_of ctxt
blanchet@51872
   545
    fun is_built_in (x as (s, _)) args =
blanchet@51872
   546
      if member (op =) logical_consts s then (true, args)
blanchet@51872
   547
      else is_built_in_const_for_prover ctxt prover x args
blanchet@51408
   548
    val fixes = map snd (Variable.dest_fixes ctxt)
blanchet@51407
   549
    val classes = Sign.classes_of thy
blanchet@49319
   550
    fun add_classes @{sort type} = I
blanchet@51407
   551
      | add_classes S =
blanchet@51407
   552
        fold (`(Sorts.super_classes classes)
blanchet@51407
   553
              #> swap #> op ::
blanchet@51407
   554
              #> subtract (op =) @{sort type}
blanchet@51407
   555
              #> map class_feature_of
blanchet@51407
   556
              #> union (op = o pairself fst)) S
blanchet@49266
   557
    fun do_add_type (Type (s, Ts)) =
blanchet@51371
   558
        (not (member (op =) bad_types s)
blanchet@51371
   559
         ? insert (op = o pairself fst) (type_feature_of s))
blanchet@49266
   560
        #> fold do_add_type Ts
blanchet@49319
   561
      | do_add_type (TFree (_, S)) = add_classes S
blanchet@49319
   562
      | do_add_type (TVar (_, S)) = add_classes S
blanchet@49266
   563
    fun add_type T = type_max_depth >= 0 ? do_add_type T
blanchet@51872
   564
    fun patternify_term _ 0 _ = []
blanchet@51354
   565
      | patternify_term args _ (Const (x as (s, _))) =
blanchet@51872
   566
        if fst (is_built_in x args) then [] else [s]
blanchet@51872
   567
      | patternify_term _ depth (Free (s, _)) =
blanchet@51872
   568
        if depth = term_max_depth andalso member (op =) fixes s then
blanchet@51872
   569
          [thy_name ^ Long_Name.separator ^ s]
blanchet@51872
   570
        else
blanchet@51872
   571
          []
blanchet@51354
   572
      | patternify_term args depth (t $ u) =
blanchet@51354
   573
        let
blanchet@51872
   574
          val ps =
blanchet@51872
   575
            take max_pattern_breadth (patternify_term (u :: args) depth t)
blanchet@51872
   576
          val qs =
blanchet@51872
   577
            take max_pattern_breadth ("" :: patternify_term [] (depth - 1) u)
blanchet@51872
   578
        in map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs end
blanchet@51872
   579
      | patternify_term _ _ _ = []
blanchet@51408
   580
    fun add_term_pattern feature_of =
blanchet@51872
   581
      union (op = o pairself fst) o map feature_of oo patternify_term []
blanchet@51598
   582
    fun add_term_patterns _ 0 _ = I
blanchet@51408
   583
      | add_term_patterns feature_of depth t =
blanchet@51408
   584
        add_term_pattern feature_of depth t
blanchet@51408
   585
        #> add_term_patterns feature_of (depth - 1) t
blanchet@51408
   586
    fun add_term feature_of = add_term_patterns feature_of term_max_depth
blanchet@49266
   587
    fun add_patterns t =
blanchet@51872
   588
      case strip_comb t of
blanchet@51872
   589
        (Const (x as (_, T)), args) =>
blanchet@51872
   590
        let val (built_in, args) = is_built_in x args in
blanchet@51872
   591
          (not built_in ? add_term const_feature_of t)
blanchet@51872
   592
          #> add_type T
blanchet@51872
   593
          #> fold add_patterns args
blanchet@51872
   594
        end
blanchet@51872
   595
      | (head, args) =>
blanchet@49266
   596
        (case head of
blanchet@51408
   597
           Const (_, T) => add_term const_feature_of t #> add_type T
blanchet@51408
   598
         | Free (_, T) => add_term free_feature_of t #> add_type T
blanchet@49266
   599
         | Var (_, T) => add_type T
blanchet@49266
   600
         | Abs (_, T, body) => add_type T #> add_patterns body
blanchet@49266
   601
         | _ => I)
blanchet@49266
   602
        #> fold add_patterns args
blanchet@49341
   603
  in [] |> fold add_patterns ts end
blanchet@49266
   604
blanchet@49266
   605
fun is_exists (s, _) = (s = @{const_name Ex} orelse s = @{const_name Ex1})
blanchet@49266
   606
blanchet@51598
   607
val term_max_depth = 2
blanchet@51598
   608
val type_max_depth = 2
blanchet@49266
   609
blanchet@49266
   610
(* TODO: Generate type classes for types? *)
blanchet@49400
   611
fun features_of ctxt prover thy (scope, status) ts =
blanchet@51408
   612
  let val thy_name = Context.theory_name thy in
blanchet@51408
   613
    thy_feature_of thy_name ::
blanchet@51856
   614
    term_features_of ctxt prover thy_name term_max_depth type_max_depth ts
blanchet@51408
   615
    |> status <> General ? cons (status_feature_of status)
blanchet@51408
   616
    |> scope <> Global ? cons local_feature
blanchet@51408
   617
    |> exists (not o is_lambda_free) ts ? cons lams_feature
blanchet@51408
   618
    |> exists (exists_Const is_exists) ts ? cons skos_feature
blanchet@51408
   619
  end
blanchet@49266
   620
blanchet@51449
   621
(* Too many dependencies is a sign that a decision procedure is at work. There
blanchet@51449
   622
   isn't much to learn from such proofs. *)
blanchet@51449
   623
val max_dependencies = 20
blanchet@51499
   624
blanchet@51499
   625
val prover_dependency_default_max_facts = 50
blanchet@49266
   626
blanchet@49453
   627
(* "type_definition_xxx" facts are characterized by their use of "CollectI". *)
blanchet@51770
   628
val typedef_dep = nickname_of_thm @{thm CollectI}
blanchet@51770
   629
(* Mysterious parts of the class machinery create lots of proofs that refer
blanchet@51770
   630
   exclusively to "someI_e" (and to some internal constructions). *)
blanchet@51770
   631
val class_some_dep = nickname_of_thm @{thm someI_ex}
blanchet@49453
   632
blanchet@51843
   633
val fundef_ths =
blanchet@51843
   634
  @{thms fundef_ex1_existence fundef_ex1_uniqueness fundef_ex1_iff
blanchet@51843
   635
         fundef_default_value}
blanchet@51843
   636
  |> map nickname_of_thm
blanchet@51843
   637
blanchet@49453
   638
(* "Rep_xxx_inject", "Abs_xxx_inverse", etc., are derived using these facts. *)
blanchet@49453
   639
val typedef_ths =
blanchet@49453
   640
  @{thms type_definition.Abs_inverse type_definition.Rep_inverse
blanchet@49453
   641
         type_definition.Rep type_definition.Rep_inject
blanchet@49453
   642
         type_definition.Abs_inject type_definition.Rep_cases
blanchet@49453
   643
         type_definition.Abs_cases type_definition.Rep_induct
blanchet@49453
   644
         type_definition.Abs_induct type_definition.Rep_range
blanchet@49453
   645
         type_definition.Abs_image}
blanchet@51639
   646
  |> map nickname_of_thm
blanchet@49453
   647
blanchet@49456
   648
fun is_size_def [dep] th =
blanchet@49456
   649
    (case first_field ".recs" dep of
blanchet@49456
   650
       SOME (pref, _) =>
blanchet@51639
   651
       (case first_field ".size" (nickname_of_thm th) of
blanchet@49456
   652
          SOME (pref', _) => pref = pref'
blanchet@49456
   653
        | NONE => false)
blanchet@49456
   654
     | NONE => false)
blanchet@49456
   655
  | is_size_def _ _ = false
blanchet@49456
   656
blanchet@49456
   657
fun trim_dependencies th deps =
blanchet@51770
   658
  if length deps > max_dependencies then NONE else SOME deps
blanchet@49266
   659
blanchet@51770
   660
fun isar_dependencies_of name_tabs th =
blanchet@51770
   661
  let
blanchet@51770
   662
    val deps = thms_in_proof (SOME name_tabs) th
blanchet@51770
   663
  in
blanchet@51843
   664
    if deps = [typedef_dep] orelse
blanchet@51843
   665
       deps = [class_some_dep] orelse
blanchet@51843
   666
       exists (member (op =) fundef_ths) deps orelse
blanchet@51843
   667
       exists (member (op =) typedef_ths) deps orelse
blanchet@51843
   668
       is_size_def deps th then
blanchet@51770
   669
      []
blanchet@51770
   670
    else
blanchet@51770
   671
      deps
blanchet@51770
   672
  end
blanchet@49419
   673
blanchet@51499
   674
fun prover_dependencies_of ctxt (params as {verbose, max_facts, ...}) prover
blanchet@51750
   675
                           auto_level facts name_tabs th =
blanchet@51750
   676
  case isar_dependencies_of name_tabs th of
blanchet@51769
   677
    [] => (false, [])
blanchet@49407
   678
  | isar_deps =>
blanchet@49407
   679
    let
blanchet@49407
   680
      val thy = Proof_Context.theory_of ctxt
blanchet@49407
   681
      val goal = goal_of_thm thy th
blanchet@49407
   682
      val (_, hyp_ts, concl_t) = ATP_Util.strip_subgoal ctxt goal 1
blanchet@49407
   683
      val facts = facts |> filter (fn (_, th') => thm_ord (th', th) = LESS)
blanchet@51639
   684
      fun nickify ((_, stature), th) =
blanchet@51639
   685
        ((fn () => nickname_of_thm th, stature), th)
blanchet@51639
   686
      fun is_dep dep (_, th) = nickname_of_thm th = dep
blanchet@49407
   687
      fun add_isar_dep facts dep accum =
blanchet@49407
   688
        if exists (is_dep dep) accum then
blanchet@49407
   689
          accum
blanchet@49407
   690
        else case find_first (is_dep dep) facts of
blanchet@49407
   691
          SOME ((name, status), th) => accum @ [((name, status), th)]
blanchet@49407
   692
        | NONE => accum (* shouldn't happen *)
blanchet@49407
   693
      val facts =
blanchet@51499
   694
        facts
blanchet@51499
   695
        |> mepo_suggested_facts ctxt params prover
blanchet@51499
   696
               (max_facts |> the_default prover_dependency_default_max_facts)
blanchet@51499
   697
               NONE hyp_ts concl_t
blanchet@51769
   698
        |> fold (add_isar_dep facts) isar_deps
blanchet@51639
   699
        |> map nickify
blanchet@49407
   700
    in
blanchet@49419
   701
      if verbose andalso auto_level = 0 then
blanchet@49407
   702
        let val num_facts = length facts in
blanchet@51639
   703
          "MaSh: " ^ quote prover ^ " on " ^ quote (nickname_of_thm th) ^
blanchet@49407
   704
          " with " ^ string_of_int num_facts ^ " fact" ^ plural_s num_facts ^
blanchet@49407
   705
          "."
blanchet@49407
   706
          |> Output.urgent_message
blanchet@49407
   707
        end
blanchet@49407
   708
      else
blanchet@49407
   709
        ();
blanchet@49407
   710
      case run_prover_for_mash ctxt params prover facts goal of
blanchet@49407
   711
        {outcome = NONE, used_facts, ...} =>
blanchet@49419
   712
        (if verbose andalso auto_level = 0 then
blanchet@49407
   713
           let val num_facts = length used_facts in
blanchet@49407
   714
             "Found proof with " ^ string_of_int num_facts ^ " fact" ^
blanchet@49407
   715
             plural_s num_facts ^ "."
blanchet@49407
   716
             |> Output.urgent_message
blanchet@49407
   717
           end
blanchet@49407
   718
         else
blanchet@49407
   719
           ();
blanchet@51769
   720
         (true, map fst used_facts))
blanchet@49680
   721
      | _ => (false, isar_deps)
blanchet@49407
   722
    end
blanchet@49266
   723
blanchet@49266
   724
blanchet@49266
   725
(*** High-level communication with MaSh ***)
blanchet@49266
   726
blanchet@49422
   727
fun num_keys keys = Graph.Keys.fold (K (Integer.add 1)) keys 0
blanchet@49415
   728
blanchet@51625
   729
fun maximal_in_graph access_G facts =
blanchet@49331
   730
  let
blanchet@51639
   731
    val facts = [] |> fold (cons o nickname_of_thm o snd) facts
blanchet@49422
   732
    val tab = Symtab.empty |> fold (fn name => Symtab.default (name, ())) facts
blanchet@49422
   733
    fun insert_new seen name =
blanchet@49422
   734
      not (Symtab.defined seen name) ? insert (op =) name
blanchet@49422
   735
    fun find_maxes _ (maxs, []) = map snd maxs
blanchet@49422
   736
      | find_maxes seen (maxs, new :: news) =
blanchet@49422
   737
        find_maxes
blanchet@51625
   738
            (seen |> num_keys (Graph.imm_succs access_G new) > 1
blanchet@49422
   739
                     ? Symtab.default (new, ()))
blanchet@49422
   740
            (if Symtab.defined tab new then
blanchet@49422
   741
               let
blanchet@51625
   742
                 val newp = Graph.all_preds access_G [new]
blanchet@49422
   743
                 fun is_ancestor x yp = member (op =) yp x
blanchet@49422
   744
                 val maxs =
blanchet@49422
   745
                   maxs |> filter (fn (_, max) => not (is_ancestor max newp))
blanchet@49422
   746
               in
blanchet@49422
   747
                 if exists (is_ancestor new o fst) maxs then
blanchet@49422
   748
                   (maxs, news)
blanchet@49422
   749
                 else
blanchet@49422
   750
                   ((newp, new)
blanchet@49422
   751
                    :: filter_out (fn (_, max) => is_ancestor max newp) maxs,
blanchet@49422
   752
                    news)
blanchet@49422
   753
               end
blanchet@49422
   754
             else
blanchet@49422
   755
               (maxs, Graph.Keys.fold (insert_new seen)
blanchet@51625
   756
                                      (Graph.imm_preds access_G new) news))
blanchet@51625
   757
  in find_maxes Symtab.empty ([], Graph.maximals access_G) end
blanchet@49331
   758
blanchet@51876
   759
fun is_fact_in_graph access_G get_th fact =
blanchet@51876
   760
  can (Graph.get_node access_G) (nickname_of_thm (get_th fact))
blanchet@49335
   761
blanchet@51398
   762
val weight_raw_mash_facts = weight_mepo_facts
blanchet@51398
   763
val weight_mash_facts = weight_raw_mash_facts
blanchet@51398
   764
blanchet@51398
   765
(* FUDGE *)
blanchet@51398
   766
fun weight_of_proximity_fact rank =
blanchet@51413
   767
  Math.pow (1.3, 15.5 - 0.2 * Real.fromInt rank) + 15.0
blanchet@51398
   768
blanchet@51398
   769
fun weight_proximity_facts facts =
blanchet@51398
   770
  facts ~~ map weight_of_proximity_fact (0 upto length facts - 1)
blanchet@51397
   771
blanchet@51455
   772
val max_proximity_facts = 100
blanchet@51455
   773
blanchet@51967
   774
fun find_mash_suggestions _ [] _ _ raw_unknown = ([], raw_unknown)
blanchet@51967
   775
  | find_mash_suggestions max_facts suggs facts chained raw_unknown =
blanchet@51967
   776
    let
blanchet@51982
   777
      val raw_mash = find_suggested_facts facts suggs
blanchet@51967
   778
      val unknown_chained =
blanchet@51967
   779
        inter (Thm.eq_thm_prop o pairself snd) chained raw_unknown
blanchet@51967
   780
      val proximity =
blanchet@51967
   781
        facts |> sort (thm_ord o pairself snd o swap)
blanchet@51967
   782
              |> take max_proximity_facts
blanchet@51967
   783
      val mess =
blanchet@51967
   784
        [(0.90 (* FUDGE *), (map (rpair 1.0) unknown_chained, [])),
blanchet@51967
   785
         (0.08 (* FUDGE *), (weight_raw_mash_facts raw_mash, raw_unknown)),
blanchet@51967
   786
         (0.02 (* FUDGE *), (weight_proximity_facts proximity, []))]
blanchet@51967
   787
      val unknown =
blanchet@51967
   788
        raw_unknown
blanchet@51967
   789
        |> fold (subtract (Thm.eq_thm_prop o pairself snd))
blanchet@51967
   790
                [unknown_chained, proximity]
blanchet@51967
   791
    in (mesh_facts (Thm.eq_thm_prop o pairself snd) max_facts mess, unknown) end
blanchet@51427
   792
blanchet@51873
   793
fun mash_suggested_facts ctxt ({overlord, learn, ...} : params) prover max_facts
blanchet@51873
   794
                         hyp_ts concl_t facts =
blanchet@49316
   795
  let
blanchet@49317
   796
    val thy = Proof_Context.theory_of ctxt
blanchet@51841
   797
    val chained = facts |> filter (fn ((_, (scope, _)), _) => scope = Chained)
blanchet@51625
   798
    val (access_G, suggs) =
blanchet@51625
   799
      peek_state ctxt (fn {access_G, ...} =>
blanchet@51625
   800
          if Graph.is_empty access_G then
blanchet@51625
   801
            (access_G, [])
blanchet@49449
   802
          else
blanchet@49449
   803
            let
blanchet@51625
   804
              val parents = maximal_in_graph access_G facts
blanchet@49449
   805
              val feats =
blanchet@49449
   806
                features_of ctxt prover thy (Local, General) (concl_t :: hyp_ts)
blanchet@51876
   807
              val hints =
blanchet@51876
   808
                chained |> filter (is_fact_in_graph access_G snd)
blanchet@51876
   809
                        |> map (nickname_of_thm o snd)
blanchet@49449
   810
            in
blanchet@51984
   811
              (access_G, MaSh.query ctxt overlord learn max_facts
blanchet@51984
   812
                                    (parents, feats, hints))
blanchet@49449
   813
            end)
blanchet@51876
   814
    val unknown = facts |> filter_out (is_fact_in_graph access_G snd)
blanchet@51427
   815
  in find_mash_suggestions max_facts suggs facts chained unknown end
blanchet@49264
   816
blanchet@51646
   817
fun learn_wrt_access_graph ctxt (name, parents, feats, deps) (learns, graph) =
blanchet@49331
   818
  let
blanchet@51646
   819
    fun maybe_learn_from from (accum as (parents, graph)) =
blanchet@49336
   820
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@49336
   821
          (from :: parents, Graph.add_edge_acyclic (from, name) graph))
blanchet@49684
   822
    val graph = graph |> Graph.default_node (name, Isar_Proof)
blanchet@51646
   823
    val (parents, graph) = ([], graph) |> fold maybe_learn_from parents
blanchet@51646
   824
    val (deps, _) = ([], graph) |> fold maybe_learn_from deps
blanchet@51646
   825
  in ((name, parents, feats, deps) :: learns, graph) end
blanchet@49321
   826
blanchet@51646
   827
fun relearn_wrt_access_graph ctxt (name, deps) (relearns, graph) =
blanchet@49683
   828
  let
blanchet@51646
   829
    fun maybe_relearn_from from (accum as (parents, graph)) =
blanchet@49683
   830
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@49683
   831
          (from :: parents, Graph.add_edge_acyclic (from, name) graph))
blanchet@51625
   832
    val graph = graph |> update_access_graph_node (name, Automatic_Proof)
blanchet@51646
   833
    val (deps, _) = ([], graph) |> fold maybe_relearn_from deps
blanchet@51646
   834
  in ((name, deps) :: relearns, graph) end
blanchet@49683
   835
blanchet@51625
   836
fun flop_wrt_access_graph name =
blanchet@51625
   837
  update_access_graph_node (name, Isar_Proof_wegen_Prover_Flop)
blanchet@49684
   838
blanchet@49399
   839
val learn_timeout_slack = 2.0
blanchet@49333
   840
blanchet@49399
   841
fun launch_thread timeout task =
blanchet@49398
   842
  let
blanchet@49399
   843
    val hard_timeout = time_mult learn_timeout_slack timeout
blanchet@49399
   844
    val birth_time = Time.now ()
blanchet@49399
   845
    val death_time = Time.+ (birth_time, hard_timeout)
blanchet@49457
   846
    val desc = ("Machine learner for Sledgehammer", "")
blanchet@49399
   847
  in Async_Manager.launch MaShN birth_time death_time desc task end
blanchet@49399
   848
blanchet@49399
   849
fun mash_learn_proof ctxt ({overlord, timeout, ...} : params) prover t facts
blanchet@49399
   850
                     used_ths =
blanchet@51876
   851
  launch_thread (timeout |> the_default one_day) (fn () =>
blanchet@51876
   852
      let
blanchet@51876
   853
        val thy = Proof_Context.theory_of ctxt
blanchet@51876
   854
        val name = freshish_name ()
blanchet@51876
   855
        val feats = features_of ctxt prover thy (Local, General) [t]
blanchet@51876
   856
      in
blanchet@51876
   857
        peek_state ctxt (fn {access_G, ...} =>
blanchet@51876
   858
            let
blanchet@51876
   859
              val parents = maximal_in_graph access_G facts
blanchet@51876
   860
              val deps =
blanchet@51876
   861
                used_ths |> filter (is_fact_in_graph access_G I)
blanchet@51876
   862
                         |> map nickname_of_thm
blanchet@51876
   863
            in
blanchet@51876
   864
              MaSh.learn ctxt overlord [(name, parents, feats, deps)]
blanchet@51876
   865
            end);
blanchet@51876
   866
        (true, "")
blanchet@51876
   867
      end)
blanchet@49398
   868
wenzelm@51465
   869
fun sendback sub = Active.sendback_markup (sledgehammerN ^ " " ^ sub)
blanchet@49407
   870
blanchet@49407
   871
val commit_timeout = seconds 30.0
blanchet@49347
   872
blanchet@51500
   873
(* The timeout is understood in a very relaxed fashion. *)
blanchet@49419
   874
fun mash_learn_facts ctxt (params as {debug, verbose, overlord, ...}) prover
blanchet@51499
   875
                     auto_level run_prover learn_timeout facts =
blanchet@49319
   876
  let
blanchet@49333
   877
    val timer = Timer.startRealTimer ()
blanchet@49407
   878
    fun next_commit_time () =
blanchet@49407
   879
      Time.+ (Timer.checkRealTimer timer, commit_timeout)
blanchet@51625
   880
    val {access_G, ...} = peek_state ctxt I
blanchet@51500
   881
    val facts = facts |> sort (thm_ord o pairself snd)
blanchet@49415
   882
    val (old_facts, new_facts) =
blanchet@51876
   883
      facts |> List.partition (is_fact_in_graph access_G snd)
blanchet@49323
   884
  in
blanchet@51499
   885
    if null new_facts andalso (not run_prover orelse null old_facts) then
blanchet@49419
   886
      if auto_level < 2 then
blanchet@51499
   887
        "No new " ^ (if run_prover then "automatic" else "Isar") ^
blanchet@51499
   888
        " proofs to learn." ^
blanchet@51499
   889
        (if auto_level = 0 andalso not run_prover then
blanchet@51499
   890
           "\n\nHint: Try " ^ sendback learn_proverN ^
blanchet@51766
   891
           " to learn from an automatic prover."
blanchet@49419
   892
         else
blanchet@49419
   893
           "")
blanchet@49407
   894
      else
blanchet@49407
   895
        ""
blanchet@49323
   896
    else
blanchet@49319
   897
      let
blanchet@51750
   898
        val name_tabs = build_name_tables nickname_of_thm facts
blanchet@49454
   899
        fun deps_of status th =
blanchet@49454
   900
          if status = Non_Rec_Def orelse status = Rec_Def then
blanchet@49454
   901
            SOME []
blanchet@51499
   902
          else if run_prover then
blanchet@51750
   903
            prover_dependencies_of ctxt params prover auto_level facts name_tabs
blanchet@51499
   904
                                   th
blanchet@51769
   905
            |> (fn (false, _) => NONE
blanchet@51769
   906
                 | (true, deps) => trim_dependencies th deps)
blanchet@49419
   907
          else
blanchet@51750
   908
            isar_dependencies_of name_tabs th
blanchet@51769
   909
            |> trim_dependencies th
blanchet@49684
   910
        fun do_commit [] [] [] state = state
blanchet@51646
   911
          | do_commit learns relearns flops {access_G, dirty} =
blanchet@49407
   912
            let
blanchet@51625
   913
              val was_empty = Graph.is_empty access_G
blanchet@51646
   914
              val (learns, access_G) =
blanchet@51646
   915
                ([], access_G) |> fold (learn_wrt_access_graph ctxt) learns
blanchet@51646
   916
              val (relearns, access_G) =
blanchet@51646
   917
                ([], access_G) |> fold (relearn_wrt_access_graph ctxt) relearns
blanchet@51625
   918
              val access_G = access_G |> fold flop_wrt_access_graph flops
blanchet@49714
   919
              val dirty =
blanchet@51646
   920
                case (was_empty, dirty, relearns) of
blanchet@51646
   921
                  (false, SOME names, []) => SOME (map #1 learns @ names)
blanchet@49714
   922
                | _ => NONE
blanchet@49419
   923
            in
blanchet@51647
   924
              MaSh.learn ctxt overlord (rev learns);
blanchet@51647
   925
              MaSh.relearn ctxt overlord relearns;
blanchet@51625
   926
              {access_G = access_G, dirty = dirty}
blanchet@49419
   927
            end
blanchet@51646
   928
        fun commit last learns relearns flops =
blanchet@49419
   929
          (if debug andalso auto_level = 0 then
blanchet@49419
   930
             Output.urgent_message "Committing..."
blanchet@49419
   931
           else
blanchet@49419
   932
             ();
blanchet@51646
   933
           map_state ctxt (do_commit (rev learns) relearns flops);
blanchet@49419
   934
           if not last andalso auto_level = 0 then
blanchet@51646
   935
             let val num_proofs = length learns + length relearns in
blanchet@49419
   936
               "Learned " ^ string_of_int num_proofs ^ " " ^
blanchet@51499
   937
               (if run_prover then "automatic" else "Isar") ^ " proof" ^
blanchet@49419
   938
               plural_s num_proofs ^ " in the last " ^
blanchet@49407
   939
               string_from_time commit_timeout ^ "."
blanchet@49407
   940
               |> Output.urgent_message
blanchet@49407
   941
             end
blanchet@49407
   942
           else
blanchet@49407
   943
             ())
blanchet@49419
   944
        fun learn_new_fact _ (accum as (_, (_, _, _, true))) = accum
blanchet@49454
   945
          | learn_new_fact ((_, stature as (_, status)), th)
blanchet@51646
   946
                           (learns, (parents, n, next_commit, _)) =
blanchet@49333
   947
            let
blanchet@51639
   948
              val name = nickname_of_thm th
blanchet@49347
   949
              val feats =
blanchet@49400
   950
                features_of ctxt prover (theory_of_thm th) stature [prop_of th]
blanchet@49454
   951
              val deps = deps_of status th |> these
blanchet@49409
   952
              val n = n |> not (null deps) ? Integer.add 1
blanchet@51646
   953
              val learns = (name, parents, feats, deps) :: learns
blanchet@51646
   954
              val (learns, next_commit) =
blanchet@49407
   955
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@51646
   956
                  (commit false learns [] []; ([], next_commit_time ()))
blanchet@49407
   957
                else
blanchet@51646
   958
                  (learns, next_commit)
blanchet@51572
   959
              val timed_out =
blanchet@51572
   960
                case learn_timeout of
blanchet@51572
   961
                  SOME timeout => Time.> (Timer.checkRealTimer timer, timeout)
blanchet@51572
   962
                | NONE => false
blanchet@51646
   963
            in (learns, ([name], n, next_commit, timed_out)) end
blanchet@49419
   964
        val n =
blanchet@49419
   965
          if null new_facts then
blanchet@49419
   966
            0
blanchet@49419
   967
          else
blanchet@49419
   968
            let
blanchet@49419
   969
              val last_th = new_facts |> List.last |> snd
blanchet@49419
   970
              (* crude approximation *)
blanchet@49419
   971
              val ancestors =
blanchet@49419
   972
                old_facts
blanchet@49419
   973
                |> filter (fn (_, th) => thm_ord (th, last_th) <> GREATER)
blanchet@51625
   974
              val parents = maximal_in_graph access_G ancestors
blanchet@51646
   975
              val (learns, (_, n, _, _)) =
blanchet@49419
   976
                ([], (parents, 0, next_commit_time (), false))
blanchet@49419
   977
                |> fold learn_new_fact new_facts
blanchet@51646
   978
            in commit true learns [] []; n end
blanchet@49419
   979
        fun relearn_old_fact _ (accum as (_, (_, _, true))) = accum
blanchet@49454
   980
          | relearn_old_fact ((_, (_, status)), th)
blanchet@51646
   981
                             ((relearns, flops), (n, next_commit, _)) =
blanchet@49419
   982
            let
blanchet@51639
   983
              val name = nickname_of_thm th
blanchet@51646
   984
              val (n, relearns, flops) =
blanchet@49454
   985
                case deps_of status th of
blanchet@51646
   986
                  SOME deps => (n + 1, (name, deps) :: relearns, flops)
blanchet@51646
   987
                | NONE => (n, relearns, name :: flops)
blanchet@51646
   988
              val (relearns, flops, next_commit) =
blanchet@49419
   989
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@51646
   990
                  (commit false [] relearns flops;
blanchet@51646
   991
                   ([], [], next_commit_time ()))
blanchet@49419
   992
                else
blanchet@51646
   993
                  (relearns, flops, next_commit)
blanchet@51572
   994
              val timed_out =
blanchet@51572
   995
                case learn_timeout of
blanchet@51572
   996
                  SOME timeout => Time.> (Timer.checkRealTimer timer, timeout)
blanchet@51572
   997
                | NONE => false
blanchet@51646
   998
            in ((relearns, flops), (n, next_commit, timed_out)) end
blanchet@49419
   999
        val n =
blanchet@51499
  1000
          if not run_prover orelse null old_facts then
blanchet@49419
  1001
            n
blanchet@49419
  1002
          else
blanchet@49419
  1003
            let
blanchet@49683
  1004
              val max_isar = 1000 * max_dependencies
blanchet@49684
  1005
              fun kind_of_proof th =
blanchet@51639
  1006
                try (Graph.get_node access_G) (nickname_of_thm th)
blanchet@49684
  1007
                |> the_default Isar_Proof
blanchet@49421
  1008
              fun priority_of (_, th) =
blanchet@49683
  1009
                random_range 0 max_isar
blanchet@49684
  1010
                + (case kind_of_proof th of
blanchet@49684
  1011
                     Isar_Proof => 0
blanchet@51499
  1012
                   | Automatic_Proof => 2 * max_isar
blanchet@51499
  1013
                   | Isar_Proof_wegen_Prover_Flop => max_isar)
blanchet@51769
  1014
                - 500 * length (isar_dependencies_of name_tabs th)
blanchet@49419
  1015
              val old_facts =
blanchet@49421
  1016
                old_facts |> map (`priority_of)
blanchet@49419
  1017
                          |> sort (int_ord o pairself fst)
blanchet@49419
  1018
                          |> map snd
blanchet@51646
  1019
              val ((relearns, flops), (n, _, _)) =
blanchet@49684
  1020
                (([], []), (n, next_commit_time (), false))
blanchet@49419
  1021
                |> fold relearn_old_fact old_facts
blanchet@51646
  1022
            in commit true [] relearns flops; n end
blanchet@49333
  1023
      in
blanchet@49419
  1024
        if verbose orelse auto_level < 2 then
blanchet@49419
  1025
          "Learned " ^ string_of_int n ^ " nontrivial " ^
blanchet@51499
  1026
          (if run_prover then "automatic" else "Isar") ^ " proof" ^ plural_s n ^
blanchet@49334
  1027
          (if verbose then
blanchet@49334
  1028
             " in " ^ string_from_time (Timer.checkRealTimer timer)
blanchet@49334
  1029
           else
blanchet@49334
  1030
             "") ^ "."
blanchet@49334
  1031
        else
blanchet@49334
  1032
          ""
blanchet@49333
  1033
      end
blanchet@49323
  1034
  end
blanchet@49319
  1035
blanchet@49419
  1036
fun mash_learn ctxt (params as {provers, timeout, ...}) fact_override chained
blanchet@51499
  1037
               run_prover =
blanchet@49331
  1038
  let
blanchet@49411
  1039
    val css = Sledgehammer_Fact.clasimpset_rule_table_of ctxt
blanchet@49410
  1040
    val ctxt = ctxt |> Config.put instantiate_inducts false
blanchet@49410
  1041
    val facts =
blanchet@49411
  1042
      nearly_all_facts ctxt false fact_override Symtab.empty css chained []
blanchet@49411
  1043
                       @{prop True}
blanchet@49419
  1044
    val num_facts = length facts
blanchet@49419
  1045
    val prover = hd provers
blanchet@51499
  1046
    fun learn auto_level run_prover =
blanchet@51572
  1047
      mash_learn_facts ctxt params prover auto_level run_prover NONE facts
blanchet@49419
  1048
      |> Output.urgent_message
blanchet@49331
  1049
  in
blanchet@51499
  1050
    if run_prover then
blanchet@51355
  1051
      ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@51499
  1052
       plural_s num_facts ^ " for automatic proofs (" ^ quote prover ^
blanchet@51572
  1053
       (case timeout of
blanchet@51572
  1054
          SOME timeout => " timeout: " ^ string_from_time timeout
blanchet@51572
  1055
        | NONE => "") ^ ").\n\nCollecting Isar proofs first..."
blanchet@51355
  1056
       |> Output.urgent_message;
blanchet@51355
  1057
       learn 1 false;
blanchet@51499
  1058
       "Now collecting automatic proofs. This may take several hours. You can \
blanchet@51355
  1059
       \safely stop the learning process at any point."
blanchet@51355
  1060
       |> Output.urgent_message;
blanchet@51355
  1061
       learn 0 true)
blanchet@51355
  1062
    else
blanchet@51355
  1063
      ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@51355
  1064
       plural_s num_facts ^ " for Isar proofs..."
blanchet@51355
  1065
       |> Output.urgent_message;
blanchet@51355
  1066
       learn 0 false)
blanchet@49331
  1067
  end
blanchet@49264
  1068
blanchet@51326
  1069
fun is_mash_enabled () = (getenv "MASH" = "yes")
blanchet@51585
  1070
fun mash_can_suggest_facts ctxt =
blanchet@51625
  1071
  not (Graph.is_empty (#access_G (peek_state ctxt I)))
blanchet@51326
  1072
blanchet@51398
  1073
(* Generate more suggestions than requested, because some might be thrown out
blanchet@51398
  1074
   later for various reasons. *)
blanchet@51980
  1075
fun generous_max_facts max_facts = max_facts + Int.min (50, max_facts)
blanchet@51398
  1076
blanchet@51829
  1077
val mepo_weight = 0.5
blanchet@51829
  1078
val mash_weight = 0.5
blanchet@51829
  1079
blanchet@49333
  1080
(* The threshold should be large enough so that MaSh doesn't kick in for Auto
blanchet@49333
  1081
   Sledgehammer and Try. *)
blanchet@49333
  1082
val min_secs_for_learning = 15
blanchet@49333
  1083
blanchet@49336
  1084
fun relevant_facts ctxt (params as {learn, fact_filter, timeout, ...}) prover
blanchet@49336
  1085
        max_facts ({add, only, ...} : fact_override) hyp_ts concl_t facts =
blanchet@49329
  1086
  if not (subset (op =) (the_list fact_filter, fact_filters)) then
blanchet@49329
  1087
    error ("Unknown fact filter: " ^ quote (the fact_filter) ^ ".")
blanchet@49329
  1088
  else if only then
blanchet@49304
  1089
    facts
blanchet@49336
  1090
  else if max_facts <= 0 orelse null facts then
blanchet@49303
  1091
    []
blanchet@49303
  1092
  else
blanchet@49303
  1093
    let
blanchet@49342
  1094
      fun maybe_learn () =
blanchet@49399
  1095
        if learn andalso not (Async_Manager.has_running_threads MaShN) andalso
blanchet@51572
  1096
           (timeout = NONE orelse
blanchet@51572
  1097
            Time.toSeconds (the timeout) >= min_secs_for_learning) then
blanchet@51572
  1098
          let
blanchet@51572
  1099
            val timeout = Option.map (time_mult learn_timeout_slack) timeout
blanchet@51572
  1100
          in
blanchet@51572
  1101
            launch_thread (timeout |> the_default one_day)
blanchet@49419
  1102
                (fn () => (true, mash_learn_facts ctxt params prover 2 false
blanchet@49407
  1103
                                                  timeout facts))
blanchet@49334
  1104
          end
blanchet@49333
  1105
        else
blanchet@49333
  1106
          ()
blanchet@49329
  1107
      val fact_filter =
blanchet@49329
  1108
        case fact_filter of
blanchet@49394
  1109
          SOME ff => (() |> ff <> mepoN ? maybe_learn; ff)
blanchet@49333
  1110
        | NONE =>
blanchet@49422
  1111
          if is_smt_prover ctxt prover then
blanchet@49422
  1112
            mepoN
blanchet@51244
  1113
          else if is_mash_enabled () then
blanchet@49422
  1114
            (maybe_learn ();
blanchet@49422
  1115
             if mash_can_suggest_facts ctxt then meshN else mepoN)
blanchet@49422
  1116
          else
blanchet@49422
  1117
            mepoN
blanchet@49303
  1118
      val add_ths = Attrib.eval_thms ctxt add
blanchet@49307
  1119
      fun prepend_facts ths accepts =
blanchet@49303
  1120
        ((facts |> filter (member Thm.eq_thm_prop ths o snd)) @
blanchet@49307
  1121
         (accepts |> filter_out (member Thm.eq_thm_prop ths o snd)))
blanchet@49308
  1122
        |> take max_facts
blanchet@49421
  1123
      fun mepo () =
blanchet@51397
  1124
        mepo_suggested_facts ctxt params prover max_facts NONE hyp_ts concl_t
blanchet@51397
  1125
                             facts
blanchet@51397
  1126
        |> weight_mepo_facts
blanchet@49329
  1127
      fun mash () =
blanchet@51398
  1128
        mash_suggested_facts ctxt params prover (generous_max_facts max_facts)
blanchet@51398
  1129
            hyp_ts concl_t facts
blanchet@51455
  1130
        |>> weight_mash_facts
blanchet@49329
  1131
      val mess =
blanchet@51829
  1132
        [] |> (if fact_filter <> mashN then cons (mepo_weight, (mepo (), []))
blanchet@51829
  1133
               else I)
blanchet@51829
  1134
           |> (if fact_filter <> mepoN then cons (mash_weight, (mash ()))
blanchet@51829
  1135
               else I)
blanchet@49303
  1136
    in
blanchet@51840
  1137
      mesh_facts (Thm.eq_thm_prop o pairself snd) max_facts mess
blanchet@49303
  1138
      |> not (null add_ths) ? prepend_facts add_ths
blanchet@49303
  1139
    end
blanchet@49303
  1140
blanchet@49334
  1141
fun kill_learners () = Async_Manager.kill_threads MaShN "learner"
blanchet@49334
  1142
fun running_learners () = Async_Manager.running_threads MaShN "learner"
blanchet@49334
  1143
blanchet@49263
  1144
end;