src/HOL/Tools/Sledgehammer/sledgehammer_mash.ML
author blanchet
Thu Nov 21 12:29:29 2013 +0100 (2013-11-21 ago)
changeset 54546 8b403a7a8c44
parent 54503 b490e15a5e19
child 54693 dd5874e4553f
permissions -rw-r--r--
fixed spying so that the envirnoment variables are queried at run-time not at build-time
blanchet@48380
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mash.ML
blanchet@48248
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@48248
     3
blanchet@48248
     4
Sledgehammer's machine-learning-based relevance filter (MaSh).
blanchet@48248
     5
*)
blanchet@48248
     6
blanchet@48381
     7
signature SLEDGEHAMMER_MASH =
blanchet@48248
     8
sig
blanchet@48251
     9
  type stature = ATP_Problem_Generate.stature
blanchet@51004
    10
  type raw_fact = Sledgehammer_Fact.raw_fact
blanchet@48296
    11
  type fact = Sledgehammer_Fact.fact
blanchet@48296
    12
  type fact_override = Sledgehammer_Fact.fact_override
blanchet@48251
    13
  type params = Sledgehammer_Provers.params
blanchet@48251
    14
  type prover_result = Sledgehammer_Provers.prover_result
blanchet@48251
    15
blanchet@48308
    16
  val trace : bool Config.T
blanchet@51008
    17
  val MePoN : string
blanchet@48319
    18
  val MaShN : string
blanchet@51008
    19
  val MeShN : string
blanchet@48379
    20
  val mepoN : string
blanchet@48379
    21
  val mashN : string
blanchet@48314
    22
  val meshN : string
blanchet@48392
    23
  val unlearnN : string
blanchet@48392
    24
  val learn_isarN : string
blanchet@50484
    25
  val learn_proverN : string
blanchet@48392
    26
  val relearn_isarN : string
blanchet@50484
    27
  val relearn_proverN : string
blanchet@48314
    28
  val fact_filters : string list
blanchet@50826
    29
  val encode_str : string -> string
blanchet@50826
    30
  val encode_strs : string list -> string
blanchet@50826
    31
  val unencode_str : string -> string
blanchet@50826
    32
  val unencode_strs : string -> string list
blanchet@50356
    33
  val encode_features : (string * real) list -> string
blanchet@50965
    34
  val extract_suggestions : string -> string * string list
blanchet@50632
    35
blanchet@50632
    36
  structure MaSh:
blanchet@50632
    37
  sig
blanchet@53148
    38
    val unlearn : Proof.context -> bool -> unit
blanchet@50632
    39
    val learn :
blanchet@53757
    40
      Proof.context -> bool -> bool
blanchet@53121
    41
      -> (string * string list * string list * string list) list -> unit
blanchet@50632
    42
    val relearn :
blanchet@53757
    43
      Proof.context -> bool -> bool -> (string * string list) list -> unit
blanchet@50969
    44
    val query :
blanchet@53095
    45
      Proof.context -> bool -> int
blanchet@53121
    46
      -> (string * string list * string list * string list) list
blanchet@53094
    47
         * string list * string list * (string * real) list
blanchet@53094
    48
      -> string list
blanchet@50632
    49
  end
blanchet@50632
    50
blanchet@53148
    51
  val mash_unlearn : Proof.context -> params -> unit
blanchet@53819
    52
  val is_mash_enabled : unit -> bool
blanchet@50624
    53
  val nickname_of_thm : thm -> string
blanchet@51134
    54
  val find_suggested_facts :
blanchet@51134
    55
    Proof.context -> ('b * thm) list -> string list -> ('b * thm) list
blanchet@48321
    56
  val mesh_facts :
blanchet@50814
    57
    ('a * 'a -> bool) -> int -> (real * (('a * real) list * 'a list)) list
blanchet@50814
    58
    -> 'a list
blanchet@51135
    59
  val crude_thm_ord : thm * thm -> order
blanchet@51182
    60
  val thm_less : thm * thm -> bool
blanchet@48251
    61
  val goal_of_thm : theory -> thm -> thm
blanchet@48321
    62
  val run_prover_for_mash :
blanchet@54141
    63
    Proof.context -> params -> string -> string -> fact list -> thm -> prover_result
blanchet@48392
    64
  val features_of :
blanchet@54089
    65
    Proof.context -> theory -> int -> int Symtab.table -> stature -> term list ->
blanchet@54089
    66
    (string * real) list
blanchet@51177
    67
  val trim_dependencies : string list -> string list option
blanchet@50735
    68
  val isar_dependencies_of :
blanchet@50754
    69
    string Symtab.table * string Symtab.table -> thm -> string list
blanchet@50484
    70
  val prover_dependencies_of :
blanchet@51004
    71
    Proof.context -> params -> string -> int -> raw_fact list
blanchet@50735
    72
    -> string Symtab.table * string Symtab.table -> thm
blanchet@50754
    73
    -> bool * string list
blanchet@53095
    74
  val attach_parents_to_facts :
blanchet@53095
    75
    ('a * thm) list -> ('a * thm) list -> (string list * ('a * thm)) list
blanchet@53140
    76
  val num_extra_feature_facts : int
blanchet@53141
    77
  val extra_feature_factor : real
blanchet@53140
    78
  val weight_facts_smoothly : 'a list -> ('a * real) list
blanchet@53140
    79
  val weight_facts_steeply : 'a list -> ('a * real) list
blanchet@50412
    80
  val find_mash_suggestions :
blanchet@51134
    81
    Proof.context -> int -> string list -> ('b * thm) list -> ('b * thm) list
blanchet@51134
    82
    -> ('b * thm) list -> ('b * thm) list * ('b * thm) list
blanchet@53127
    83
  val add_const_counts : term -> int Symtab.table -> int Symtab.table
blanchet@48406
    84
  val mash_suggested_facts :
blanchet@54503
    85
    Proof.context -> params -> int -> term list -> term -> raw_fact list -> fact list * fact list
blanchet@54503
    86
  val mash_learn_proof : Proof.context -> params -> term -> ('a * thm) list -> thm list -> unit
blanchet@48395
    87
  val mash_learn :
blanchet@48395
    88
    Proof.context -> params -> fact_override -> thm list -> bool -> unit
blanchet@53819
    89
blanchet@53148
    90
  val mash_can_suggest_facts : Proof.context -> bool -> bool
blanchet@50412
    91
  val generous_max_facts : int -> int
blanchet@50814
    92
  val mepo_weight : real
blanchet@50814
    93
  val mash_weight : real
blanchet@48288
    94
  val relevant_facts :
blanchet@48292
    95
    Proof.context -> params -> string -> int -> fact_override -> term list
blanchet@51010
    96
    -> term -> raw_fact list -> (string * fact list) list
blanchet@53148
    97
  val kill_learners : Proof.context -> params -> unit
blanchet@48319
    98
  val running_learners : unit -> unit
blanchet@48248
    99
end;
blanchet@48248
   100
blanchet@48381
   101
structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
blanchet@48248
   102
struct
blanchet@48249
   103
blanchet@48251
   104
open ATP_Util
blanchet@48251
   105
open ATP_Problem_Generate
blanchet@48251
   106
open Sledgehammer_Util
blanchet@48251
   107
open Sledgehammer_Fact
blanchet@48251
   108
open Sledgehammer_Provers
blanchet@48318
   109
open Sledgehammer_Minimize
blanchet@48381
   110
open Sledgehammer_MePo
blanchet@48251
   111
blanchet@48308
   112
val trace =
blanchet@48380
   113
  Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
blanchet@51032
   114
blanchet@48308
   115
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@48308
   116
blanchet@51008
   117
val MePoN = "MePo"
blanchet@48319
   118
val MaShN = "MaSh"
blanchet@51008
   119
val MeShN = "MeSh"
blanchet@48319
   120
blanchet@48379
   121
val mepoN = "mepo"
blanchet@48314
   122
val mashN = "mash"
blanchet@48379
   123
val meshN = "mesh"
blanchet@48314
   124
blanchet@48379
   125
val fact_filters = [meshN, mepoN, mashN]
blanchet@48314
   126
blanchet@48392
   127
val unlearnN = "unlearn"
blanchet@48392
   128
val learn_isarN = "learn_isar"
blanchet@50484
   129
val learn_proverN = "learn_prover"
blanchet@48392
   130
val relearn_isarN = "relearn_isar"
blanchet@50484
   131
val relearn_proverN = "relearn_prover"
blanchet@48392
   132
blanchet@48394
   133
fun mash_model_dir () =
blanchet@50340
   134
  Path.explode "$ISABELLE_HOME_USER/mash" |> tap Isabelle_System.mkdir
blanchet@48394
   135
val mash_state_dir = mash_model_dir
blanchet@50310
   136
fun mash_state_file () = Path.append (mash_state_dir ()) (Path.explode "state")
blanchet@48251
   137
blanchet@48330
   138
blanchet@50311
   139
(*** Low-level communication with MaSh ***)
blanchet@50311
   140
blanchet@53117
   141
val save_models_arg = "--saveModels"
blanchet@53117
   142
val shutdown_server_arg = "--shutdownServer"
blanchet@53117
   143
blanchet@50311
   144
fun wipe_out_file file = (try (File.rm o Path.explode) file; ())
blanchet@50311
   145
blanchet@50335
   146
fun write_file banner (xs, f) path =
blanchet@50335
   147
  (case banner of SOME s => File.write path s | NONE => ();
blanchet@53094
   148
   xs |> chunk_list 500 |> List.app (File.append path o implode o map f))
blanchet@50319
   149
  handle IO.Io _ => ()
blanchet@50311
   150
blanchet@53152
   151
fun run_mash_tool ctxt overlord extra_args background write_cmds read_suggs =
blanchet@50311
   152
  let
blanchet@50311
   153
    val (temp_dir, serial) =
blanchet@50311
   154
      if overlord then (getenv "ISABELLE_HOME_USER", "")
blanchet@50311
   155
      else (getenv "ISABELLE_TMP", serial_string ())
blanchet@53129
   156
    val log_file = temp_dir ^ "/mash_log" ^ serial
blanchet@50311
   157
    val err_file = temp_dir ^ "/mash_err" ^ serial
blanchet@50311
   158
    val sugg_file = temp_dir ^ "/mash_suggs" ^ serial
blanchet@50335
   159
    val sugg_path = Path.explode sugg_file
blanchet@50311
   160
    val cmd_file = temp_dir ^ "/mash_commands" ^ serial
blanchet@50335
   161
    val cmd_path = Path.explode cmd_file
blanchet@51001
   162
    val model_dir = File.shell_path (mash_model_dir ())
blanchet@50311
   163
    val command =
blanchet@53556
   164
      "cd \"$ISABELLE_SLEDGEHAMMER_MASH\"/src; \
blanchet@53790
   165
      \PYTHONDONTWRITEBYTECODE=y ./mash.py\
blanchet@53790
   166
      \ --quiet\
blanchet@53790
   167
      \ --port=$MASH_PORT\
blanchet@53556
   168
      \ --outputDir " ^ model_dir ^
blanchet@53556
   169
      " --modelFile=" ^ model_dir ^ "/model.pickle\
blanchet@53556
   170
      \ --dictsFile=" ^ model_dir ^ "/dict.pickle\
blanchet@53790
   171
      \ --log " ^ log_file ^
blanchet@53790
   172
      " --inputFile " ^ cmd_file ^
blanchet@53790
   173
      " --predictions " ^ sugg_file ^
blanchet@53117
   174
      (if extra_args = [] then "" else " " ^ space_implode " " extra_args) ^
blanchet@53152
   175
      " >& " ^ err_file ^
blanchet@53152
   176
      (if background then " &" else "")
blanchet@50311
   177
    fun run_on () =
blanchet@50750
   178
      (Isabelle_System.bash command
blanchet@54100
   179
       |> tap (fn _ =>
blanchet@54100
   180
            case try File.read (Path.explode err_file) |> the_default "" of
blanchet@54100
   181
              "" => trace_msg ctxt (K "Done")
blanchet@54100
   182
            | s => warning ("MaSh error: " ^ elide_string 1000 s));
blanchet@50335
   183
       read_suggs (fn () => try File.read_lines sugg_path |> these))
blanchet@50311
   184
    fun clean_up () =
blanchet@50311
   185
      if overlord then ()
blanchet@50311
   186
      else List.app wipe_out_file [err_file, sugg_file, cmd_file]
blanchet@50311
   187
  in
blanchet@50335
   188
    write_file (SOME "") ([], K "") sugg_path;
blanchet@50335
   189
    write_file (SOME "") write_cmds cmd_path;
blanchet@50311
   190
    trace_msg ctxt (fn () => "Running " ^ command);
blanchet@50311
   191
    with_cleanup clean_up run_on ()
blanchet@50311
   192
  end
blanchet@48251
   193
blanchet@48308
   194
fun meta_char c =
blanchet@48251
   195
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse
blanchet@48251
   196
     c = #")" orelse c = #"," then
blanchet@48251
   197
    String.str c
blanchet@48251
   198
  else
blanchet@48251
   199
    (* fixed width, in case more digits follow *)
blanchet@48395
   200
    "%" ^ stringN_of_int 3 (Char.ord c)
blanchet@48251
   201
blanchet@48308
   202
fun unmeta_chars accum [] = String.implode (rev accum)
blanchet@48395
   203
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
blanchet@48308
   204
    (case Int.fromString (String.implode [d1, d2, d3]) of
blanchet@48308
   205
       SOME n => unmeta_chars (Char.chr n :: accum) cs
blanchet@48308
   206
     | NONE => "" (* error *))
blanchet@48395
   207
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
blanchet@48308
   208
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs
blanchet@48308
   209
blanchet@50826
   210
val encode_str = String.translate meta_char
blanchet@50826
   211
val encode_strs = map encode_str #> space_implode " "
blanchet@50826
   212
val unencode_str = String.explode #> unmeta_chars []
blanchet@50826
   213
val unencode_strs =
blanchet@50826
   214
  space_explode " " #> filter_out (curry (op =) "") #> map unencode_str
blanchet@48251
   215
blanchet@53558
   216
(* Avoid scientific notation *)
blanchet@53558
   217
fun safe_str_of_real r =
blanchet@53558
   218
  if r < 0.00001 then "0.00001"
blanchet@53558
   219
  else if r >= 1000000.0 then "1000000"
blanchet@53558
   220
  else Markup.print_real r
blanchet@53558
   221
blanchet@50356
   222
fun encode_feature (name, weight) =
blanchet@50826
   223
  encode_str name ^
blanchet@53558
   224
  (if Real.== (weight, 1.0) then "" else "=" ^ safe_str_of_real weight)
blanchet@50356
   225
blanchet@50356
   226
val encode_features = map encode_feature #> space_implode " "
blanchet@50356
   227
blanchet@50631
   228
fun str_of_learn (name, parents, feats, deps) =
blanchet@50826
   229
  "! " ^ encode_str name ^ ": " ^ encode_strs parents ^ "; " ^
blanchet@53121
   230
  encode_strs feats ^ "; " ^ encode_strs deps ^ "\n"
blanchet@48669
   231
blanchet@50631
   232
fun str_of_relearn (name, deps) =
blanchet@50826
   233
  "p " ^ encode_str name ^ ": " ^ encode_strs deps ^ "\n"
blanchet@50311
   234
blanchet@53099
   235
fun str_of_query max_suggs (learns, hints, parents, feats) =
blanchet@53095
   236
  implode (map str_of_learn learns) ^
blanchet@53099
   237
  "? " ^ string_of_int max_suggs ^ " # " ^ encode_strs parents ^ "; " ^
blanchet@53099
   238
  encode_features feats ^
blanchet@53095
   239
  (if null hints then "" else "; " ^ encode_strs hints) ^ "\n"
blanchet@48406
   240
blanchet@53098
   241
(* The suggested weights don't make much sense. *)
blanchet@48406
   242
fun extract_suggestion sugg =
blanchet@48406
   243
  case space_explode "=" sugg of
blanchet@51177
   244
    [name, _ (* weight *)] =>
blanchet@50965
   245
    SOME (unencode_str name (* , Real.fromString weight |> the_default 1.0 *))
blanchet@50965
   246
  | [name] => SOME (unencode_str name (* , 1.0 *))
blanchet@48406
   247
  | _ => NONE
blanchet@48406
   248
blanchet@50633
   249
fun extract_suggestions line =
blanchet@48311
   250
  case space_explode ":" line of
blanchet@48406
   251
    [goal, suggs] =>
blanchet@50826
   252
    (unencode_str goal, map_filter extract_suggestion (space_explode " " suggs))
blanchet@48312
   253
  | _ => ("", [])
blanchet@48311
   254
blanchet@50632
   255
structure MaSh =
blanchet@50632
   256
struct
blanchet@50632
   257
blanchet@53148
   258
fun shutdown ctxt overlord =
blanchet@53153
   259
  (trace_msg ctxt (K "MaSh shutdown");
blanchet@53756
   260
   run_mash_tool ctxt overlord [shutdown_server_arg] false ([], K "") (K ()))
blanchet@53152
   261
blanchet@53152
   262
fun save ctxt overlord =
blanchet@53153
   263
  (trace_msg ctxt (K "MaSh save");
blanchet@53153
   264
   run_mash_tool ctxt overlord [save_models_arg] true ([], K "") (K ()))
blanchet@53142
   265
blanchet@53148
   266
fun unlearn ctxt overlord =
blanchet@50311
   267
  let val path = mash_model_dir () in
blanchet@50632
   268
    trace_msg ctxt (K "MaSh unlearn");
blanchet@53148
   269
    shutdown ctxt overlord;
blanchet@50319
   270
    try (File.fold_dir (fn file => fn _ =>
blanchet@50319
   271
                           try File.rm (Path.append path (Path.basic file)))
blanchet@50319
   272
                       path) NONE;
blanchet@50311
   273
    ()
blanchet@50311
   274
  end
blanchet@50311
   275
blanchet@53757
   276
fun learn _ _ _ [] = ()
blanchet@53757
   277
  | learn ctxt overlord save learns =
blanchet@54432
   278
    let val names = elide_string 1000 (space_implode " " (map #1 learns)) in
blanchet@54432
   279
      (trace_msg ctxt (fn () => "MaSh learn" ^ (if names = "" then "" else " " ^ names));
blanchet@54432
   280
       run_mash_tool ctxt overlord ([] |> save ? cons save_models_arg) false
blanchet@54432
   281
                     (learns, str_of_learn) (K ()))
blanchet@54432
   282
    end
blanchet@50311
   283
blanchet@53757
   284
fun relearn _ _ _ [] = ()
blanchet@53757
   285
  | relearn ctxt overlord save relearns =
blanchet@50632
   286
    (trace_msg ctxt (fn () => "MaSh relearn " ^
blanchet@50631
   287
         elide_string 1000 (space_implode " " (map #1 relearns)));
blanchet@53757
   288
     run_mash_tool ctxt overlord ([] |> save ? cons save_models_arg) false
blanchet@53757
   289
                   (relearns, str_of_relearn) (K ()))
blanchet@50311
   290
blanchet@53117
   291
fun query ctxt overlord max_suggs (query as (_, _, _, feats)) =
blanchet@50969
   292
  (trace_msg ctxt (fn () => "MaSh query " ^ encode_features feats);
blanchet@53152
   293
   run_mash_tool ctxt overlord [] false ([query], str_of_query max_suggs)
blanchet@50311
   294
       (fn suggs =>
blanchet@50311
   295
           case suggs () of
blanchet@50311
   296
             [] => []
blanchet@50633
   297
           | suggs => snd (extract_suggestions (List.last suggs)))
blanchet@50311
   298
   handle List.Empty => [])
blanchet@50311
   299
blanchet@50632
   300
end;
blanchet@50632
   301
blanchet@50311
   302
blanchet@50311
   303
(*** Middle-level communication with MaSh ***)
blanchet@50311
   304
blanchet@50484
   305
datatype proof_kind =
blanchet@50484
   306
  Isar_Proof | Automatic_Proof | Isar_Proof_wegen_Prover_Flop
blanchet@50311
   307
blanchet@50311
   308
fun str_of_proof_kind Isar_Proof = "i"
blanchet@50484
   309
  | str_of_proof_kind Automatic_Proof = "a"
blanchet@50484
   310
  | str_of_proof_kind Isar_Proof_wegen_Prover_Flop = "x"
blanchet@50311
   311
blanchet@50311
   312
fun proof_kind_of_str "i" = Isar_Proof
blanchet@50484
   313
  | proof_kind_of_str "a" = Automatic_Proof
blanchet@50484
   314
  | proof_kind_of_str "x" = Isar_Proof_wegen_Prover_Flop
blanchet@50311
   315
blanchet@50311
   316
(* FIXME: Here a "Graph.update_node" function would be useful *)
blanchet@50610
   317
fun update_access_graph_node (name, kind) =
blanchet@50311
   318
  Graph.default_node (name, Isar_Proof)
blanchet@50311
   319
  #> kind <> Isar_Proof ? Graph.map_node name (K kind)
blanchet@50311
   320
blanchet@50311
   321
fun try_graph ctxt when def f =
blanchet@50311
   322
  f ()
blanchet@50311
   323
  handle Graph.CYCLES (cycle :: _) =>
blanchet@50311
   324
         (trace_msg ctxt (fn () =>
blanchet@50311
   325
              "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
blanchet@50311
   326
       | Graph.DUP name =>
blanchet@50311
   327
         (trace_msg ctxt (fn () =>
blanchet@50311
   328
              "Duplicate fact " ^ quote name ^ " when " ^ when); def)
blanchet@50311
   329
       | Graph.UNDEF name =>
blanchet@50311
   330
         (trace_msg ctxt (fn () =>
blanchet@50311
   331
              "Unknown fact " ^ quote name ^ " when " ^ when); def)
blanchet@50311
   332
       | exn =>
blanchet@50311
   333
         if Exn.is_interrupt exn then
blanchet@50311
   334
           reraise exn
blanchet@50311
   335
         else
blanchet@50311
   336
           (trace_msg ctxt (fn () =>
blanchet@50311
   337
                "Internal error when " ^ when ^ ":\n" ^
blanchet@50311
   338
                ML_Compiler.exn_message exn); def)
blanchet@50311
   339
blanchet@50311
   340
fun graph_info G =
blanchet@50311
   341
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
blanchet@50311
   342
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^
blanchet@50311
   343
  " edge(s), " ^
blanchet@50311
   344
  string_of_int (length (Graph.minimals G)) ^ " minimal, " ^
blanchet@50311
   345
  string_of_int (length (Graph.maximals G)) ^ " maximal"
blanchet@50311
   346
blanchet@53095
   347
type mash_state =
blanchet@53095
   348
  {access_G : unit Graph.T,
blanchet@53095
   349
   num_known_facts : int,
blanchet@53095
   350
   dirty : string list option}
blanchet@50311
   351
blanchet@53095
   352
val empty_state = {access_G = Graph.empty, num_known_facts = 0, dirty = SOME []}
blanchet@50311
   353
blanchet@50311
   354
local
blanchet@50311
   355
blanchet@53095
   356
val version = "*** MaSh version 20130820 ***"
blanchet@50357
   357
blanchet@53095
   358
exception FILE_VERSION_TOO_NEW of unit
blanchet@50311
   359
blanchet@50311
   360
fun extract_node line =
blanchet@50311
   361
  case space_explode ":" line of
blanchet@50311
   362
    [head, parents] =>
blanchet@50311
   363
    (case space_explode " " head of
blanchet@50311
   364
       [kind, name] =>
blanchet@50826
   365
       SOME (unencode_str name, unencode_strs parents,
blanchet@50311
   366
             try proof_kind_of_str kind |> the_default Isar_Proof)
blanchet@50311
   367
     | _ => NONE)
blanchet@50311
   368
  | _ => NONE
blanchet@50311
   369
blanchet@53152
   370
fun load_state _ _ (state as (true, _)) = state
blanchet@53152
   371
  | load_state ctxt overlord _ =
blanchet@50311
   372
    let val path = mash_state_file () in
blanchet@50311
   373
      (true,
blanchet@50311
   374
       case try File.read_lines path of
blanchet@50311
   375
         SOME (version' :: node_lines) =>
blanchet@50311
   376
         let
blanchet@50311
   377
           fun add_edge_to name parent =
blanchet@50311
   378
             Graph.default_node (parent, Isar_Proof)
blanchet@50311
   379
             #> Graph.add_edge (parent, name)
blanchet@50311
   380
           fun add_node line =
blanchet@50311
   381
             case extract_node line of
blanchet@50311
   382
               NONE => I (* shouldn't happen *)
blanchet@50311
   383
             | SOME (name, parents, kind) =>
blanchet@50610
   384
               update_access_graph_node (name, kind)
blanchet@50311
   385
               #> fold (add_edge_to name) parents
blanchet@53095
   386
           val (access_G, num_known_facts) =
blanchet@50357
   387
             case string_ord (version', version) of
blanchet@50357
   388
               EQUAL =>
blanchet@53095
   389
               (try_graph ctxt "loading state" Graph.empty (fn () =>
blanchet@53095
   390
                    fold add_node node_lines Graph.empty),
blanchet@53095
   391
                length node_lines)
blanchet@50860
   392
             | LESS =>
blanchet@53095
   393
               (* can't parse old file *)
blanchet@53148
   394
               (MaSh.unlearn ctxt overlord; (Graph.empty, 0))
blanchet@53095
   395
             | GREATER => raise FILE_VERSION_TOO_NEW ()
blanchet@50311
   396
         in
blanchet@50311
   397
           trace_msg ctxt (fn () =>
blanchet@50610
   398
               "Loaded fact graph (" ^ graph_info access_G ^ ")");
blanchet@53095
   399
           {access_G = access_G, num_known_facts = num_known_facts,
blanchet@53095
   400
            dirty = SOME []}
blanchet@50311
   401
         end
blanchet@50311
   402
       | _ => empty_state)
blanchet@50311
   403
    end
blanchet@50311
   404
blanchet@53152
   405
fun save_state _ (state as {dirty = SOME [], ...}) = state
blanchet@53152
   406
  | save_state ctxt {access_G, num_known_facts, dirty} =
blanchet@50311
   407
    let
blanchet@50311
   408
      fun str_of_entry (name, parents, kind) =
blanchet@50826
   409
        str_of_proof_kind kind ^ " " ^ encode_str name ^ ": " ^
blanchet@50826
   410
        encode_strs parents ^ "\n"
blanchet@50311
   411
      fun append_entry (name, (kind, (parents, _))) =
blanchet@50311
   412
        cons (name, Graph.Keys.dest parents, kind)
blanchet@50311
   413
      val (banner, entries) =
blanchet@50311
   414
        case dirty of
blanchet@50311
   415
          SOME names =>
blanchet@50610
   416
          (NONE, fold (append_entry o Graph.get_entry access_G) names [])
blanchet@50610
   417
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry access_G [])
blanchet@50311
   418
    in
blanchet@50335
   419
      write_file banner (entries, str_of_entry) (mash_state_file ());
blanchet@50311
   420
      trace_msg ctxt (fn () =>
blanchet@50610
   421
          "Saved fact graph (" ^ graph_info access_G ^
blanchet@50311
   422
          (case dirty of
blanchet@50311
   423
             SOME dirty =>
blanchet@50311
   424
             "; " ^ string_of_int (length dirty) ^ " dirty fact(s)"
blanchet@50311
   425
           | _ => "") ^  ")");
blanchet@53095
   426
      {access_G = access_G, num_known_facts = num_known_facts, dirty = SOME []}
blanchet@50311
   427
    end
blanchet@50311
   428
blanchet@50311
   429
val global_state =
blanchet@50311
   430
  Synchronized.var "Sledgehammer_MaSh.global_state" (false, empty_state)
blanchet@50311
   431
blanchet@50311
   432
in
blanchet@50311
   433
blanchet@53148
   434
fun map_state ctxt overlord f =
blanchet@53152
   435
  Synchronized.change global_state
blanchet@53152
   436
                      (load_state ctxt overlord ##> (f #> save_state ctxt))
blanchet@53095
   437
  handle FILE_VERSION_TOO_NEW () => ()
blanchet@50311
   438
blanchet@53148
   439
fun peek_state ctxt overlord f =
blanchet@50357
   440
  Synchronized.change_result global_state
blanchet@53152
   441
      (perhaps (try (load_state ctxt overlord)) #> `snd #>> f)
blanchet@50311
   442
blanchet@53148
   443
fun clear_state ctxt overlord =
blanchet@50311
   444
  Synchronized.change global_state (fn _ =>
blanchet@53148
   445
      (MaSh.unlearn ctxt overlord; (* also removes the state file *)
blanchet@53142
   446
       (false, empty_state)))
blanchet@50311
   447
blanchet@50311
   448
end
blanchet@50311
   449
blanchet@53558
   450
fun mash_unlearn ctxt ({overlord, ...} : params) =
blanchet@53559
   451
  (clear_state ctxt overlord; Output.urgent_message "Reset MaSh.")
blanchet@50570
   452
blanchet@50311
   453
blanchet@50311
   454
(*** Isabelle helpers ***)
blanchet@50311
   455
blanchet@53819
   456
fun is_mash_enabled () = (getenv "MASH" = "yes")
blanchet@53819
   457
blanchet@50722
   458
val local_prefix = "local" ^ Long_Name.separator
blanchet@48378
   459
blanchet@50722
   460
fun elided_backquote_thm threshold th =
blanchet@50722
   461
  elide_string threshold
blanchet@50722
   462
    (backquote_thm (Proof_Context.init_global (Thm.theory_of_thm th)) th)
blanchet@48378
   463
blanchet@51181
   464
val thy_name_of_thm = Context.theory_name o Thm.theory_of_thm
blanchet@51181
   465
blanchet@50624
   466
fun nickname_of_thm th =
blanchet@48394
   467
  if Thm.has_name_hint th then
blanchet@48394
   468
    let val hint = Thm.get_name_hint th in
blanchet@50722
   469
      (* There must be a better way to detect local facts. *)
blanchet@48394
   470
      case try (unprefix local_prefix) hint of
blanchet@48394
   471
        SOME suf =>
blanchet@51181
   472
        thy_name_of_thm th ^ Long_Name.separator ^ suf ^
blanchet@50732
   473
        Long_Name.separator ^ elided_backquote_thm 50 th
blanchet@48394
   474
      | NONE => hint
blanchet@48394
   475
    end
blanchet@48394
   476
  else
blanchet@50722
   477
    elided_backquote_thm 200 th
blanchet@48378
   478
blanchet@51134
   479
fun find_suggested_facts ctxt facts =
blanchet@48330
   480
  let
blanchet@51134
   481
    fun add (fact as (_, th)) = Symtab.default (nickname_of_thm th, fact)
blanchet@51134
   482
    val tab = fold add facts Symtab.empty
blanchet@51134
   483
    fun lookup nick =
blanchet@51134
   484
      Symtab.lookup tab nick
blanchet@51134
   485
      |> tap (fn NONE => trace_msg ctxt (fn () => "Cannot find " ^ quote nick)
blanchet@51134
   486
               | _ => ())
blanchet@51134
   487
  in map_filter lookup end
blanchet@48311
   488
blanchet@50383
   489
fun scaled_avg [] = 0
blanchet@50383
   490
  | scaled_avg xs =
blanchet@48407
   491
    Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs
blanchet@48328
   492
blanchet@50383
   493
fun avg [] = 0.0
blanchet@50383
   494
  | avg xs = fold (curry (op +)) xs 0.0 / Real.fromInt (length xs)
blanchet@48313
   495
blanchet@50383
   496
fun normalize_scores _ [] = []
blanchet@50383
   497
  | normalize_scores max_facts xs =
blanchet@50383
   498
    let val avg = avg (map snd (take max_facts xs)) in
blanchet@50383
   499
      map (apsnd (curry Real.* (1.0 / avg))) xs
blanchet@50383
   500
    end
blanchet@50383
   501
blanchet@50814
   502
fun mesh_facts _ max_facts [(_, (sels, unks))] =
blanchet@48406
   503
    map fst (take max_facts sels) @ take (max_facts - length sels) unks
blanchet@50861
   504
  | mesh_facts fact_eq max_facts mess =
blanchet@48314
   505
    let
blanchet@51029
   506
      val mess = mess |> map (apsnd (apfst (normalize_scores max_facts)))
blanchet@51029
   507
      fun score_in fact (global_weight, (sels, unks)) =
blanchet@50383
   508
        let
blanchet@54089
   509
          val score_at = try (nth sels) #> Option.map (fn (_, score) => global_weight * score)
blanchet@50383
   510
        in
blanchet@50383
   511
          case find_index (curry fact_eq fact o fst) sels of
blanchet@54089
   512
            ~1 => if member fact_eq unks fact then NONE else SOME 0.0
blanchet@50383
   513
          | rank => score_at rank
blanchet@50383
   514
        end
blanchet@50383
   515
      fun weight_of fact = mess |> map_filter (score_in fact) |> scaled_avg
blanchet@54089
   516
      val facts = fold (union fact_eq o map fst o take max_facts o fst o snd) mess []
blanchet@48314
   517
    in
blanchet@48406
   518
      facts |> map (`weight_of) |> sort (int_ord o swap o pairself fst)
blanchet@48328
   519
            |> map snd |> take max_facts
blanchet@48314
   520
    end
blanchet@48312
   521
blanchet@53155
   522
fun free_feature_of s = ("f" ^ s, 40.0 (* FUDGE *))
blanchet@50874
   523
fun thy_feature_of s = ("y" ^ s, 8.0 (* FUDGE *))
blanchet@50874
   524
fun type_feature_of s = ("t" ^ s, 4.0 (* FUDGE *))
blanchet@50584
   525
fun class_feature_of s = ("s" ^ s, 1.0 (* FUDGE *))
blanchet@53155
   526
val local_feature = ("local", 16.0 (* FUDGE *))
blanchet@48251
   527
blanchet@51135
   528
fun crude_theory_ord p =
blanchet@50722
   529
  if Theory.subthy p then
blanchet@50722
   530
    if Theory.eq_thy p then EQUAL else LESS
blanchet@48324
   531
  else if Theory.subthy (swap p) then
blanchet@48324
   532
    GREATER
blanchet@48324
   533
  else case int_ord (pairself (length o Theory.ancestors_of) p) of
blanchet@48324
   534
    EQUAL => string_ord (pairself Context.theory_name p)
blanchet@48324
   535
  | order => order
blanchet@48324
   536
blanchet@51135
   537
fun crude_thm_ord p =
blanchet@51135
   538
  case crude_theory_ord (pairself theory_of_thm p) of
blanchet@50359
   539
    EQUAL =>
blanchet@50624
   540
    let val q = pairself nickname_of_thm p in
blanchet@50624
   541
      (* Hack to put "xxx_def" before "xxxI" and "xxxE" *)
blanchet@50624
   542
      case bool_ord (pairself (String.isSuffix "_def") (swap q)) of
blanchet@50624
   543
        EQUAL => string_ord q
blanchet@50624
   544
      | ord => ord
blanchet@50624
   545
    end
blanchet@50359
   546
  | ord => ord
blanchet@48324
   547
blanchet@51136
   548
val thm_less_eq = Theory.subthy o pairself theory_of_thm
blanchet@51136
   549
fun thm_less p = thm_less_eq p andalso not (thm_less_eq (swap p))
blanchet@51136
   550
blanchet@48392
   551
val freezeT = Type.legacy_freeze_type
blanchet@48392
   552
blanchet@48392
   553
fun freeze (t $ u) = freeze t $ freeze u
blanchet@48392
   554
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
blanchet@48392
   555
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
blanchet@48392
   556
  | freeze (Const (s, T)) = Const (s, freezeT T)
blanchet@48392
   557
  | freeze (Free (s, T)) = Free (s, freezeT T)
blanchet@48392
   558
  | freeze t = t
blanchet@48392
   559
blanchet@48392
   560
fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init
blanchet@48392
   561
blanchet@54141
   562
fun run_prover_for_mash ctxt params prover goal_name facts goal =
blanchet@48392
   563
  let
blanchet@48392
   564
    val problem =
blanchet@54141
   565
      {comment = "Goal: " ^ goal_name, state = Proof.init ctxt, goal = goal, subgoal = 1,
blanchet@54141
   566
       subgoal_count = 1, factss = [("", facts)]}
blanchet@48392
   567
  in
blanchet@54503
   568
    get_minimizing_prover ctxt MaSh (K ()) prover params (K (K (K ""))) problem
blanchet@48392
   569
  end
blanchet@48392
   570
blanchet@48326
   571
val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]
blanchet@48326
   572
blanchet@53086
   573
val pat_tvar_prefix = "_"
blanchet@53086
   574
val pat_var_prefix = "_"
blanchet@53086
   575
blanchet@53089
   576
(* try "Long_Name.base_name" for shorter names *)
blanchet@53089
   577
fun massage_long_name s = s
blanchet@53083
   578
blanchet@53086
   579
val crude_str_of_sort =
blanchet@53086
   580
  space_implode ":" o map massage_long_name o subtract (op =) @{sort type}
blanchet@53086
   581
blanchet@53086
   582
fun crude_str_of_typ (Type (s, [])) = massage_long_name s
blanchet@53083
   583
  | crude_str_of_typ (Type (s, Ts)) =
blanchet@53128
   584
    massage_long_name s ^ implode (map crude_str_of_typ Ts)
blanchet@53083
   585
  | crude_str_of_typ (TFree (_, S)) = crude_str_of_sort S
blanchet@53083
   586
  | crude_str_of_typ (TVar (_, S)) = crude_str_of_sort S
blanchet@53083
   587
blanchet@53128
   588
fun maybe_singleton_str _ "" = []
blanchet@53128
   589
  | maybe_singleton_str pref s = [pref ^ s]
blanchet@53128
   590
blanchet@53148
   591
val max_pat_breadth = 10 (* FUDGE *)
blanchet@50585
   592
blanchet@54089
   593
fun term_features_of ctxt thy_name num_facts const_tab term_max_depth type_max_depth ts =
blanchet@48251
   594
  let
blanchet@50392
   595
    val thy = Proof_Context.theory_of ctxt
blanchet@53082
   596
blanchet@50393
   597
    val fixes = map snd (Variable.dest_fixes ctxt)
blanchet@50392
   598
    val classes = Sign.classes_of thy
blanchet@53082
   599
blanchet@48304
   600
    fun add_classes @{sort type} = I
blanchet@50392
   601
      | add_classes S =
blanchet@50392
   602
        fold (`(Sorts.super_classes classes)
blanchet@50392
   603
              #> swap #> op ::
blanchet@53086
   604
              #> subtract (op =) @{sort type} #> map massage_long_name
blanchet@50392
   605
              #> map class_feature_of
blanchet@53159
   606
              #> union (eq_fst (op =))) S
blanchet@53082
   607
blanchet@53082
   608
    fun pattify_type 0 _ = []
blanchet@53082
   609
      | pattify_type _ (Type (s, [])) =
blanchet@53086
   610
        if member (op =) bad_types s then [] else [massage_long_name s]
blanchet@53082
   611
      | pattify_type depth (Type (s, U :: Ts)) =
blanchet@53082
   612
        let
blanchet@53082
   613
          val T = Type (s, Ts)
blanchet@53082
   614
          val ps = take max_pat_breadth (pattify_type depth T)
blanchet@53082
   615
          val qs = take max_pat_breadth ("" :: pattify_type (depth - 1) U)
blanchet@53130
   616
        in map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs end
blanchet@53128
   617
      | pattify_type _ (TFree (_, S)) =
blanchet@53128
   618
        maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@53128
   619
      | pattify_type _ (TVar (_, S)) =
blanchet@53128
   620
        maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@53082
   621
    fun add_type_pat depth T =
blanchet@53159
   622
      union (eq_fst (op =)) (map type_feature_of (pattify_type depth T))
blanchet@53082
   623
    fun add_type_pats 0 _ = I
blanchet@53082
   624
      | add_type_pats depth t =
blanchet@53082
   625
        add_type_pat depth t #> add_type_pats (depth - 1) t
blanchet@53083
   626
    fun add_type T =
blanchet@53083
   627
      add_type_pats type_max_depth T
blanchet@53156
   628
      #> fold_atyps_sorts (add_classes o snd) T
blanchet@53084
   629
    fun add_subtypes (T as Type (_, Ts)) = add_type T #> fold add_subtypes Ts
blanchet@53084
   630
      | add_subtypes T = add_type T
blanchet@53082
   631
blanchet@53130
   632
    fun weight_of_const s =
blanchet@53130
   633
      16.0 +
blanchet@53130
   634
      (if num_facts = 0 then
blanchet@53130
   635
         0.0
blanchet@53130
   636
       else
blanchet@53130
   637
         let val count = Symtab.lookup const_tab s |> the_default 1 in
blanchet@53148
   638
           Real.fromInt num_facts / Real.fromInt count (* FUDGE *)
blanchet@53130
   639
         end)
blanchet@54089
   640
    fun pattify_term _ 0 _ = []
blanchet@54089
   641
      | pattify_term _ _ (Const (s, _)) =
blanchet@54089
   642
        if is_widely_irrelevant_const s then [] else [(massage_long_name s, weight_of_const s)]
blanchet@54089
   643
      | pattify_term _ _ (Free (s, T)) =
blanchet@53128
   644
        maybe_singleton_str pat_var_prefix (crude_str_of_typ T)
blanchet@53130
   645
        |> map (rpair 0.0)
blanchet@53090
   646
        |> (if member (op =) fixes s then
blanchet@53130
   647
              cons (free_feature_of (massage_long_name
blanchet@53130
   648
                  (thy_name ^ Long_Name.separator ^ s)))
blanchet@53090
   649
            else
blanchet@53090
   650
              I)
blanchet@54089
   651
      | pattify_term _ _ (Var (_, T)) =
blanchet@54089
   652
        maybe_singleton_str pat_var_prefix (crude_str_of_typ T) |> map (rpair 0.0)
blanchet@54089
   653
      | pattify_term Ts _ (Bound j) =
blanchet@54089
   654
        maybe_singleton_str pat_var_prefix (crude_str_of_typ (nth Ts j)) |> map (rpair 0.0)
blanchet@54089
   655
      | pattify_term Ts depth (t $ u) =
blanchet@50339
   656
        let
blanchet@54089
   657
          val ps = take max_pat_breadth (pattify_term Ts depth t)
blanchet@54089
   658
          val qs = take max_pat_breadth (("", 0.0) :: pattify_term Ts (depth - 1) u)
blanchet@53130
   659
        in
blanchet@53130
   660
          map_product (fn ppw as (p, pw) =>
blanchet@53130
   661
              fn ("", _) => ppw
blanchet@53130
   662
               | (q, qw) => (p ^ "(" ^ q ^ ")", pw + qw)) ps qs
blanchet@53130
   663
        end
blanchet@54089
   664
      | pattify_term _ _ _ = []
blanchet@54089
   665
    fun add_term_pat Ts = union (eq_fst (op =)) oo pattify_term Ts
blanchet@53130
   666
    fun add_term_pats _ 0 _ = I
blanchet@53130
   667
      | add_term_pats Ts depth t =
blanchet@53130
   668
        add_term_pat Ts depth t #> add_term_pats Ts (depth - 1) t
blanchet@53130
   669
    fun add_term Ts = add_term_pats Ts term_max_depth
blanchet@53085
   670
    fun add_subterms Ts t =
blanchet@50857
   671
      case strip_comb t of
blanchet@54089
   672
        (Const (s, T), args) =>
blanchet@54089
   673
        (not (is_widely_irrelevant_const s) ? add_term Ts t)
blanchet@54089
   674
        #> add_subtypes T
blanchet@54089
   675
        #> fold (add_subterms Ts) args
blanchet@50857
   676
      | (head, args) =>
blanchet@48251
   677
        (case head of
blanchet@53130
   678
           Free (_, T) => add_term Ts t #> add_subtypes T
blanchet@53084
   679
         | Var (_, T) => add_subtypes T
blanchet@53085
   680
         | Abs (_, T, body) => add_subtypes T #> add_subterms (T :: Ts) body
blanchet@48251
   681
         | _ => I)
blanchet@53085
   682
        #> fold (add_subterms Ts) args
blanchet@53085
   683
  in [] |> fold (add_subterms []) ts end
blanchet@48251
   684
blanchet@53085
   685
val term_max_depth = 2
blanchet@53155
   686
val type_max_depth = 1
blanchet@48251
   687
blanchet@48251
   688
(* TODO: Generate type classes for types? *)
blanchet@54089
   689
fun features_of ctxt thy num_facts const_tab (scope, _) ts =
blanchet@50393
   690
  let val thy_name = Context.theory_name thy in
blanchet@50393
   691
    thy_feature_of thy_name ::
blanchet@54089
   692
    term_features_of ctxt thy_name num_facts const_tab term_max_depth type_max_depth ts
blanchet@50393
   693
    |> scope <> Global ? cons local_feature
blanchet@50393
   694
  end
blanchet@48251
   695
blanchet@50434
   696
(* Too many dependencies is a sign that a decision procedure is at work. There
blanchet@50434
   697
   isn't much to learn from such proofs. *)
blanchet@50434
   698
val max_dependencies = 20
blanchet@50484
   699
blanchet@54125
   700
val prover_default_max_facts = 25
blanchet@48251
   701
blanchet@48438
   702
(* "type_definition_xxx" facts are characterized by their use of "CollectI". *)
blanchet@50755
   703
val typedef_dep = nickname_of_thm @{thm CollectI}
blanchet@50755
   704
(* Mysterious parts of the class machinery create lots of proofs that refer
blanchet@52071
   705
   exclusively to "someI_ex" (and to some internal constructions). *)
blanchet@50755
   706
val class_some_dep = nickname_of_thm @{thm someI_ex}
blanchet@48438
   707
blanchet@50828
   708
val fundef_ths =
blanchet@50828
   709
  @{thms fundef_ex1_existence fundef_ex1_uniqueness fundef_ex1_iff
blanchet@50828
   710
         fundef_default_value}
blanchet@50828
   711
  |> map nickname_of_thm
blanchet@50828
   712
blanchet@48438
   713
(* "Rep_xxx_inject", "Abs_xxx_inverse", etc., are derived using these facts. *)
blanchet@48438
   714
val typedef_ths =
blanchet@48438
   715
  @{thms type_definition.Abs_inverse type_definition.Rep_inverse
blanchet@48438
   716
         type_definition.Rep type_definition.Rep_inject
blanchet@48438
   717
         type_definition.Abs_inject type_definition.Rep_cases
blanchet@48438
   718
         type_definition.Abs_cases type_definition.Rep_induct
blanchet@48438
   719
         type_definition.Abs_induct type_definition.Rep_range
blanchet@48438
   720
         type_definition.Abs_image}
blanchet@50624
   721
  |> map nickname_of_thm
blanchet@48438
   722
blanchet@48441
   723
fun is_size_def [dep] th =
blanchet@48441
   724
    (case first_field ".recs" dep of
blanchet@48441
   725
       SOME (pref, _) =>
blanchet@50624
   726
       (case first_field ".size" (nickname_of_thm th) of
blanchet@48441
   727
          SOME (pref', _) => pref = pref'
blanchet@48441
   728
        | NONE => false)
blanchet@48441
   729
     | NONE => false)
blanchet@48441
   730
  | is_size_def _ _ = false
blanchet@48441
   731
blanchet@53095
   732
fun no_dependencies_for_status status =
blanchet@53095
   733
  status = Non_Rec_Def orelse status = Rec_Def
blanchet@53095
   734
blanchet@51177
   735
fun trim_dependencies deps =
blanchet@50755
   736
  if length deps > max_dependencies then NONE else SOME deps
blanchet@48251
   737
blanchet@50755
   738
fun isar_dependencies_of name_tabs th =
blanchet@51020
   739
  let val deps = thms_in_proof (SOME name_tabs) th in
blanchet@50828
   740
    if deps = [typedef_dep] orelse
blanchet@50828
   741
       deps = [class_some_dep] orelse
blanchet@50828
   742
       exists (member (op =) fundef_ths) deps orelse
blanchet@50828
   743
       exists (member (op =) typedef_ths) deps orelse
blanchet@50828
   744
       is_size_def deps th then
blanchet@50755
   745
      []
blanchet@50755
   746
    else
blanchet@50755
   747
      deps
blanchet@50755
   748
  end
blanchet@48404
   749
blanchet@50484
   750
fun prover_dependencies_of ctxt (params as {verbose, max_facts, ...}) prover
blanchet@50735
   751
                           auto_level facts name_tabs th =
blanchet@50735
   752
  case isar_dependencies_of name_tabs th of
blanchet@50754
   753
    [] => (false, [])
blanchet@48392
   754
  | isar_deps =>
blanchet@48392
   755
    let
blanchet@48392
   756
      val thy = Proof_Context.theory_of ctxt
blanchet@48392
   757
      val goal = goal_of_thm thy th
blanchet@54141
   758
      val name = nickname_of_thm th
blanchet@52196
   759
      val (_, hyp_ts, concl_t) = ATP_Util.strip_subgoal goal 1 ctxt
blanchet@51136
   760
      val facts = facts |> filter (fn (_, th') => thm_less (th', th))
blanchet@51004
   761
      fun nickify ((_, stature), th) = ((nickname_of_thm th, stature), th)
blanchet@50624
   762
      fun is_dep dep (_, th) = nickname_of_thm th = dep
blanchet@48392
   763
      fun add_isar_dep facts dep accum =
blanchet@48392
   764
        if exists (is_dep dep) accum then
blanchet@48392
   765
          accum
blanchet@48392
   766
        else case find_first (is_dep dep) facts of
blanchet@51004
   767
          SOME ((_, status), th) => accum @ [(("", status), th)]
blanchet@48392
   768
        | NONE => accum (* shouldn't happen *)
blanchet@54123
   769
      val mepo_facts =
blanchet@50484
   770
        facts
blanchet@54095
   771
        |> mepo_suggested_facts ctxt params (max_facts |> the_default prover_default_max_facts) NONE
blanchet@54095
   772
             hyp_ts concl_t
blanchet@54123
   773
      val facts =
blanchet@54123
   774
        mepo_facts
blanchet@50754
   775
        |> fold (add_isar_dep facts) isar_deps
blanchet@50624
   776
        |> map nickify
blanchet@54123
   777
      val num_isar_deps = length isar_deps
blanchet@48392
   778
    in
blanchet@48404
   779
      if verbose andalso auto_level = 0 then
blanchet@54141
   780
        "MaSh: " ^ quote prover ^ " on " ^ quote name ^ " with " ^ string_of_int num_isar_deps ^
blanchet@54141
   781
        " + " ^ string_of_int (length facts - num_isar_deps) ^ " facts."
blanchet@54123
   782
        |> Output.urgent_message
blanchet@48392
   783
      else
blanchet@48392
   784
        ();
blanchet@54141
   785
      case run_prover_for_mash ctxt params prover name facts goal of
blanchet@48392
   786
        {outcome = NONE, used_facts, ...} =>
blanchet@48404
   787
        (if verbose andalso auto_level = 0 then
blanchet@48392
   788
           let val num_facts = length used_facts in
blanchet@48392
   789
             "Found proof with " ^ string_of_int num_facts ^ " fact" ^
blanchet@48392
   790
             plural_s num_facts ^ "."
blanchet@48392
   791
             |> Output.urgent_message
blanchet@48392
   792
           end
blanchet@48392
   793
         else
blanchet@48392
   794
           ();
blanchet@50754
   795
         (true, map fst used_facts))
blanchet@48665
   796
      | _ => (false, isar_deps)
blanchet@48392
   797
    end
blanchet@48251
   798
blanchet@48251
   799
blanchet@48251
   800
(*** High-level communication with MaSh ***)
blanchet@48251
   801
blanchet@51182
   802
(* In the following functions, chunks are risers w.r.t. "thm_less_eq". *)
blanchet@51182
   803
blanchet@51181
   804
fun chunks_and_parents_for chunks th =
blanchet@51181
   805
  let
blanchet@51181
   806
    fun insert_parent new parents =
blanchet@51181
   807
      let val parents = parents |> filter_out (fn p => thm_less_eq (p, new)) in
blanchet@51181
   808
        parents |> forall (fn p => not (thm_less_eq (new, p))) parents
blanchet@51181
   809
                   ? cons new
blanchet@51181
   810
      end
blanchet@51181
   811
    fun rechunk seen (rest as th' :: ths) =
blanchet@51181
   812
      if thm_less_eq (th', th) then (rev seen, rest)
blanchet@51181
   813
      else rechunk (th' :: seen) ths
blanchet@51181
   814
    fun do_chunk [] accum = accum
blanchet@51181
   815
      | do_chunk (chunk as hd_chunk :: _) (chunks, parents) =
blanchet@51181
   816
        if thm_less_eq (hd_chunk, th) then
blanchet@51181
   817
          (chunk :: chunks, insert_parent hd_chunk parents)
blanchet@51181
   818
        else if thm_less_eq (List.last chunk, th) then
blanchet@51181
   819
          let val (front, back as hd_back :: _) = rechunk [] chunk in
blanchet@51181
   820
            (front :: back :: chunks, insert_parent hd_back parents)
blanchet@51181
   821
          end
blanchet@51181
   822
        else
blanchet@51181
   823
          (chunk :: chunks, parents)
blanchet@51181
   824
  in
blanchet@51181
   825
    fold_rev do_chunk chunks ([], [])
blanchet@51181
   826
    |>> cons []
blanchet@51182
   827
    ||> map nickname_of_thm
blanchet@51181
   828
  end
blanchet@51181
   829
blanchet@51182
   830
fun attach_parents_to_facts _ [] = []
blanchet@51182
   831
  | attach_parents_to_facts old_facts (facts as (_, th) :: _) =
blanchet@51182
   832
    let
blanchet@51182
   833
      fun do_facts _ [] = []
blanchet@51182
   834
        | do_facts (_, parents) [fact] = [(parents, fact)]
blanchet@51182
   835
        | do_facts (chunks, parents)
blanchet@51182
   836
                   ((fact as (_, th)) :: (facts as (_, th') :: _)) =
blanchet@51182
   837
          let
blanchet@51182
   838
            val chunks = app_hd (cons th) chunks
blanchet@51182
   839
            val chunks_and_parents' =
blanchet@51182
   840
              if thm_less_eq (th, th') andalso
blanchet@51182
   841
                 thy_name_of_thm th = thy_name_of_thm th' then
blanchet@51182
   842
                (chunks, [nickname_of_thm th])
blanchet@51182
   843
              else
blanchet@51182
   844
                chunks_and_parents_for chunks th'
blanchet@51182
   845
          in (parents, fact) :: do_facts chunks_and_parents' facts end
blanchet@51182
   846
    in
blanchet@51182
   847
      old_facts @ facts
blanchet@51182
   848
      |> do_facts (chunks_and_parents_for [[]] th)
blanchet@51182
   849
      |> drop (length old_facts)
blanchet@51182
   850
    end
blanchet@51177
   851
blanchet@53095
   852
fun maximal_wrt_graph G keys =
blanchet@53095
   853
  let
blanchet@53095
   854
    val tab = Symtab.empty |> fold (fn name => Symtab.default (name, ())) keys
blanchet@53095
   855
    fun insert_new seen name =
blanchet@53095
   856
      not (Symtab.defined seen name) ? insert (op =) name
blanchet@53095
   857
    fun num_keys keys = Graph.Keys.fold (K (Integer.add 1)) keys 0
blanchet@53095
   858
    fun find_maxes _ (maxs, []) = map snd maxs
blanchet@53095
   859
      | find_maxes seen (maxs, new :: news) =
blanchet@53095
   860
        find_maxes
blanchet@53095
   861
            (seen |> num_keys (Graph.imm_succs G new) > 1
blanchet@53095
   862
                     ? Symtab.default (new, ()))
blanchet@53095
   863
            (if Symtab.defined tab new then
blanchet@53095
   864
               let
blanchet@53095
   865
                 val newp = Graph.all_preds G [new]
blanchet@53095
   866
                 fun is_ancestor x yp = member (op =) yp x
blanchet@53095
   867
                 val maxs =
blanchet@53095
   868
                   maxs |> filter (fn (_, max) => not (is_ancestor max newp))
blanchet@53095
   869
               in
blanchet@53095
   870
                 if exists (is_ancestor new o fst) maxs then
blanchet@53095
   871
                   (maxs, news)
blanchet@53095
   872
                 else
blanchet@53095
   873
                   ((newp, new)
blanchet@53095
   874
                    :: filter_out (fn (_, max) => is_ancestor max newp) maxs,
blanchet@53095
   875
                    news)
blanchet@53095
   876
               end
blanchet@53095
   877
             else
blanchet@53095
   878
               (maxs, Graph.Keys.fold (insert_new seen)
blanchet@53095
   879
                                      (Graph.imm_preds G new) news))
blanchet@53095
   880
  in find_maxes Symtab.empty ([], Graph.maximals G) end
blanchet@53095
   881
blanchet@53095
   882
fun maximal_wrt_access_graph access_G =
blanchet@53095
   883
  map (nickname_of_thm o snd)
blanchet@53095
   884
  #> maximal_wrt_graph access_G
blanchet@53095
   885
blanchet@53095
   886
fun is_fact_in_graph access_G = can (Graph.get_node access_G) o nickname_of_thm
blanchet@53095
   887
blanchet@53197
   888
val chained_feature_factor = 0.5 (* FUDGE *)
blanchet@53197
   889
val extra_feature_factor = 0.1 (* FUDGE *)
blanchet@53201
   890
val num_extra_feature_facts = 10 (* FUDGE *)
blanchet@53095
   891
blanchet@53095
   892
(* FUDGE *)
blanchet@53095
   893
fun weight_of_proximity_fact rank =
blanchet@53095
   894
  Math.pow (1.3, 15.5 - 0.2 * Real.fromInt rank) + 15.0
blanchet@53095
   895
blanchet@53140
   896
fun weight_facts_smoothly facts =
blanchet@53095
   897
  facts ~~ map weight_of_proximity_fact (0 upto length facts - 1)
blanchet@53095
   898
blanchet@53140
   899
(* FUDGE *)
blanchet@53140
   900
fun steep_weight_of_fact rank =
blanchet@53140
   901
  Math.pow (0.62, log2 (Real.fromInt (rank + 1)))
blanchet@53140
   902
blanchet@53140
   903
fun weight_facts_steeply facts =
blanchet@53140
   904
  facts ~~ map steep_weight_of_fact (0 upto length facts - 1)
blanchet@53140
   905
blanchet@53095
   906
val max_proximity_facts = 100
blanchet@53095
   907
blanchet@54060
   908
fun find_mash_suggestions ctxt max_facts suggs facts chained raw_unknown =
blanchet@54060
   909
  let
blanchet@54060
   910
    val inter_fact = inter (eq_snd Thm.eq_thm_prop)
blanchet@54060
   911
    val raw_mash = find_suggested_facts ctxt facts suggs
blanchet@54060
   912
    val proximate = take max_proximity_facts facts
blanchet@54060
   913
    val unknown_chained = inter_fact raw_unknown chained
blanchet@54060
   914
    val unknown_proximate = inter_fact raw_unknown proximate
blanchet@54060
   915
    val mess =
blanchet@54060
   916
      [(0.9 (* FUDGE *), (map (rpair 1.0) unknown_chained, [])),
blanchet@54060
   917
       (0.4 (* FUDGE *), (weight_facts_smoothly unknown_proximate, [])),
blanchet@54060
   918
       (0.1 (* FUDGE *), (weight_facts_steeply raw_mash, raw_unknown))]
blanchet@54060
   919
    val unknown =
blanchet@54060
   920
      raw_unknown
blanchet@54060
   921
      |> fold (subtract (eq_snd Thm.eq_thm_prop))
blanchet@54060
   922
              [unknown_chained, unknown_proximate]
blanchet@54060
   923
  in (mesh_facts (eq_snd Thm.eq_thm_prop) max_facts mess, unknown) end
blanchet@53095
   924
blanchet@53127
   925
fun add_const_counts t =
blanchet@53130
   926
  fold (fn s => Symtab.map_default (s, 0) (Integer.add 1))
blanchet@53127
   927
       (Term.add_const_names t [])
blanchet@53095
   928
blanchet@54503
   929
fun mash_suggested_facts ctxt ({debug, overlord, ...} : params) max_facts hyp_ts concl_t facts =
blanchet@53095
   930
  let
blanchet@53095
   931
    val thy = Proof_Context.theory_of ctxt
blanchet@53559
   932
    val thy_name = Context.theory_name thy
blanchet@53141
   933
    val facts = facts |> sort (crude_thm_ord o pairself snd o swap)
blanchet@53095
   934
    val chained = facts |> filter (fn ((_, (scope, _)), _) => scope = Chained)
blanchet@53141
   935
    val num_facts = length facts
blanchet@53127
   936
    val const_tab = fold (add_const_counts o prop_of o snd) facts Symtab.empty
blanchet@54085
   937
blanchet@53559
   938
    fun fact_has_right_theory (_, th) =
blanchet@53559
   939
      thy_name = Context.theory_name (theory_of_thm th)
blanchet@53141
   940
    fun chained_or_extra_features_of factor (((_, stature), th), weight) =
blanchet@53141
   941
      [prop_of th]
blanchet@54089
   942
      |> features_of ctxt (theory_of_thm th) num_facts const_tab stature
blanchet@53141
   943
      |> map (apsnd (fn r => weight * factor * r))
blanchet@54085
   944
blanchet@53095
   945
    val (access_G, suggs) =
blanchet@53148
   946
      peek_state ctxt overlord (fn {access_G, ...} =>
blanchet@53095
   947
          if Graph.is_empty access_G then
blanchet@54064
   948
            (trace_msg ctxt (K "Nothing has been learned yet"); (access_G, []))
blanchet@53095
   949
          else
blanchet@53095
   950
            let
blanchet@53095
   951
              val parents = maximal_wrt_access_graph access_G facts
blanchet@53141
   952
              val goal_feats =
blanchet@54089
   953
                features_of ctxt thy num_facts const_tab (Local, General) (concl_t :: hyp_ts)
blanchet@53141
   954
              val chained_feats =
blanchet@53141
   955
                chained
blanchet@53141
   956
                |> map (rpair 1.0)
blanchet@53141
   957
                |> map (chained_or_extra_features_of chained_feature_factor)
blanchet@53159
   958
                |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@53141
   959
              val extra_feats =
blanchet@53141
   960
                facts
blanchet@53148
   961
                |> take (Int.max (0, num_extra_feature_facts - length chained))
blanchet@53559
   962
                |> filter fact_has_right_theory
blanchet@53141
   963
                |> weight_facts_steeply
blanchet@53141
   964
                |> map (chained_or_extra_features_of extra_feature_factor)
blanchet@53159
   965
                |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@53095
   966
              val feats =
blanchet@53159
   967
                fold (union (eq_fst (op =))) [chained_feats, extra_feats]
blanchet@53141
   968
                     goal_feats
blanchet@53559
   969
                |> debug ? sort (Real.compare o swap o pairself snd)
blanchet@53095
   970
              val hints =
blanchet@53095
   971
                chained |> filter (is_fact_in_graph access_G o snd)
blanchet@53095
   972
                        |> map (nickname_of_thm o snd)
blanchet@53095
   973
            in
blanchet@53095
   974
              (access_G, MaSh.query ctxt overlord max_facts
blanchet@53118
   975
                                    ([], hints, parents, feats))
blanchet@53095
   976
            end)
blanchet@53095
   977
    val unknown = facts |> filter_out (is_fact_in_graph access_G o snd)
blanchet@53095
   978
  in
blanchet@53095
   979
    find_mash_suggestions ctxt max_facts suggs facts chained unknown
blanchet@53095
   980
    |> pairself (map fact_of_raw_fact)
blanchet@53095
   981
  end
blanchet@53095
   982
blanchet@53095
   983
fun learn_wrt_access_graph ctxt (name, parents, feats, deps) (learns, graph) =
blanchet@53095
   984
  let
blanchet@53095
   985
    fun maybe_learn_from from (accum as (parents, graph)) =
blanchet@53095
   986
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@53095
   987
          (from :: parents, Graph.add_edge_acyclic (from, name) graph))
blanchet@53095
   988
    val graph = graph |> Graph.default_node (name, Isar_Proof)
blanchet@53095
   989
    val (parents, graph) = ([], graph) |> fold maybe_learn_from parents
blanchet@53095
   990
    val (deps, _) = ([], graph) |> fold maybe_learn_from deps
blanchet@53095
   991
  in ((name, parents, feats, deps) :: learns, graph) end
blanchet@53095
   992
blanchet@53095
   993
fun relearn_wrt_access_graph ctxt (name, deps) (relearns, graph) =
blanchet@53095
   994
  let
blanchet@53095
   995
    fun maybe_relearn_from from (accum as (parents, graph)) =
blanchet@53095
   996
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@53095
   997
          (from :: parents, Graph.add_edge_acyclic (from, name) graph))
blanchet@53095
   998
    val graph = graph |> update_access_graph_node (name, Automatic_Proof)
blanchet@53095
   999
    val (deps, _) = ([], graph) |> fold maybe_relearn_from deps
blanchet@53095
  1000
  in ((name, deps) :: relearns, graph) end
blanchet@53095
  1001
blanchet@53095
  1002
fun flop_wrt_access_graph name =
blanchet@53095
  1003
  update_access_graph_node (name, Isar_Proof_wegen_Prover_Flop)
blanchet@53095
  1004
blanchet@53095
  1005
val learn_timeout_slack = 2.0
blanchet@53095
  1006
blanchet@53095
  1007
fun launch_thread timeout task =
blanchet@53095
  1008
  let
blanchet@53095
  1009
    val hard_timeout = time_mult learn_timeout_slack timeout
blanchet@53095
  1010
    val birth_time = Time.now ()
blanchet@53095
  1011
    val death_time = Time.+ (birth_time, hard_timeout)
blanchet@53095
  1012
    val desc = ("Machine learner for Sledgehammer", "")
blanchet@53095
  1013
  in Async_Manager.thread MaShN birth_time death_time desc task end
blanchet@53095
  1014
blanchet@54503
  1015
fun mash_learn_proof ctxt ({overlord, timeout, ...} : params) t facts used_ths =
blanchet@53819
  1016
  if is_mash_enabled () then
blanchet@53819
  1017
    launch_thread (timeout |> the_default one_day) (fn () =>
blanchet@53819
  1018
        let
blanchet@53819
  1019
          val thy = Proof_Context.theory_of ctxt
blanchet@54089
  1020
          val feats = features_of ctxt thy 0 Symtab.empty (Local, General) [t] |> map fst
blanchet@53819
  1021
        in
blanchet@53819
  1022
          peek_state ctxt overlord (fn {access_G, ...} =>
blanchet@53819
  1023
              let
blanchet@53819
  1024
                val parents = maximal_wrt_access_graph access_G facts
blanchet@53819
  1025
                val deps =
blanchet@53819
  1026
                  used_ths |> filter (is_fact_in_graph access_G)
blanchet@53819
  1027
                           |> map nickname_of_thm
blanchet@53819
  1028
              in
blanchet@54432
  1029
                MaSh.learn ctxt overlord true [("", parents, feats, deps)]
blanchet@53819
  1030
              end);
blanchet@53819
  1031
          (true, "")
blanchet@53819
  1032
        end)
blanchet@53819
  1033
  else
blanchet@53819
  1034
    ()
blanchet@53095
  1035
wenzelm@52697
  1036
fun sendback sub =
wenzelm@52697
  1037
  Active.sendback_markup [Markup.padding_command] (sledgehammerN ^ " " ^ sub)
blanchet@48392
  1038
blanchet@48392
  1039
val commit_timeout = seconds 30.0
blanchet@48332
  1040
blanchet@50485
  1041
(* The timeout is understood in a very relaxed fashion. *)
blanchet@48404
  1042
fun mash_learn_facts ctxt (params as {debug, verbose, overlord, ...}) prover
blanchet@53152
  1043
                     save auto_level run_prover learn_timeout facts =
blanchet@48304
  1044
  let
blanchet@48318
  1045
    val timer = Timer.startRealTimer ()
blanchet@48392
  1046
    fun next_commit_time () =
blanchet@48392
  1047
      Time.+ (Timer.checkRealTimer timer, commit_timeout)
blanchet@53148
  1048
    val {access_G, ...} = peek_state ctxt overlord I
blanchet@53095
  1049
    val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@51177
  1050
    val no_new_facts = forall is_in_access_G facts
blanchet@48308
  1051
  in
blanchet@51177
  1052
    if no_new_facts andalso not run_prover then
blanchet@48404
  1053
      if auto_level < 2 then
blanchet@50484
  1054
        "No new " ^ (if run_prover then "automatic" else "Isar") ^
blanchet@50484
  1055
        " proofs to learn." ^
blanchet@50484
  1056
        (if auto_level = 0 andalso not run_prover then
blanchet@50484
  1057
           "\n\nHint: Try " ^ sendback learn_proverN ^
blanchet@50751
  1058
           " to learn from an automatic prover."
blanchet@48404
  1059
         else
blanchet@48404
  1060
           "")
blanchet@48392
  1061
      else
blanchet@48392
  1062
        ""
blanchet@48308
  1063
    else
blanchet@48304
  1064
      let
blanchet@50735
  1065
        val name_tabs = build_name_tables nickname_of_thm facts
blanchet@48439
  1066
        fun deps_of status th =
blanchet@53095
  1067
          if no_dependencies_for_status status then
blanchet@48439
  1068
            SOME []
blanchet@50484
  1069
          else if run_prover then
blanchet@50735
  1070
            prover_dependencies_of ctxt params prover auto_level facts name_tabs
blanchet@50484
  1071
                                   th
blanchet@50754
  1072
            |> (fn (false, _) => NONE
blanchet@51177
  1073
                 | (true, deps) => trim_dependencies deps)
blanchet@48404
  1074
          else
blanchet@50735
  1075
            isar_dependencies_of name_tabs th
blanchet@51177
  1076
            |> trim_dependencies
blanchet@48669
  1077
        fun do_commit [] [] [] state = state
blanchet@53095
  1078
          | do_commit learns relearns flops {access_G, num_known_facts, dirty} =
blanchet@48392
  1079
            let
blanchet@50610
  1080
              val was_empty = Graph.is_empty access_G
blanchet@50631
  1081
              val (learns, access_G) =
blanchet@50631
  1082
                ([], access_G) |> fold (learn_wrt_access_graph ctxt) learns
blanchet@50631
  1083
              val (relearns, access_G) =
blanchet@50631
  1084
                ([], access_G) |> fold (relearn_wrt_access_graph ctxt) relearns
blanchet@50610
  1085
              val access_G = access_G |> fold flop_wrt_access_graph flops
blanchet@53095
  1086
              val num_known_facts = num_known_facts + length learns
blanchet@48699
  1087
              val dirty =
blanchet@50631
  1088
                case (was_empty, dirty, relearns) of
blanchet@50631
  1089
                  (false, SOME names, []) => SOME (map #1 learns @ names)
blanchet@48699
  1090
                | _ => NONE
blanchet@48404
  1091
            in
blanchet@53757
  1092
              MaSh.learn ctxt overlord (save andalso null relearns) (rev learns);
blanchet@53757
  1093
              MaSh.relearn ctxt overlord save relearns;
blanchet@53095
  1094
              {access_G = access_G, num_known_facts = num_known_facts,
blanchet@53095
  1095
               dirty = dirty}
blanchet@48404
  1096
            end
blanchet@50631
  1097
        fun commit last learns relearns flops =
blanchet@48404
  1098
          (if debug andalso auto_level = 0 then
blanchet@48404
  1099
             Output.urgent_message "Committing..."
blanchet@48404
  1100
           else
blanchet@48404
  1101
             ();
blanchet@53148
  1102
           map_state ctxt overlord (do_commit (rev learns) relearns flops);
blanchet@48404
  1103
           if not last andalso auto_level = 0 then
blanchet@50631
  1104
             let val num_proofs = length learns + length relearns in
blanchet@48404
  1105
               "Learned " ^ string_of_int num_proofs ^ " " ^
blanchet@50484
  1106
               (if run_prover then "automatic" else "Isar") ^ " proof" ^
blanchet@48404
  1107
               plural_s num_proofs ^ " in the last " ^
blanchet@52031
  1108
               string_of_time commit_timeout ^ "."
blanchet@48392
  1109
               |> Output.urgent_message
blanchet@48392
  1110
             end
blanchet@48392
  1111
           else
blanchet@48392
  1112
             ())
blanchet@51177
  1113
        fun learn_new_fact _ (accum as (_, (_, _, true))) = accum
blanchet@51177
  1114
          | learn_new_fact (parents, ((_, stature as (_, status)), th))
blanchet@51177
  1115
                           (learns, (n, next_commit, _)) =
blanchet@48318
  1116
            let
blanchet@50624
  1117
              val name = nickname_of_thm th
blanchet@48332
  1118
              val feats =
blanchet@54089
  1119
                features_of ctxt (theory_of_thm th) 0 Symtab.empty stature [prop_of th] |> map fst
blanchet@48439
  1120
              val deps = deps_of status th |> these
blanchet@48394
  1121
              val n = n |> not (null deps) ? Integer.add 1
blanchet@50631
  1122
              val learns = (name, parents, feats, deps) :: learns
blanchet@50631
  1123
              val (learns, next_commit) =
blanchet@48392
  1124
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@50631
  1125
                  (commit false learns [] []; ([], next_commit_time ()))
blanchet@48392
  1126
                else
blanchet@50631
  1127
                  (learns, next_commit)
blanchet@50557
  1128
              val timed_out =
blanchet@50557
  1129
                case learn_timeout of
blanchet@50557
  1130
                  SOME timeout => Time.> (Timer.checkRealTimer timer, timeout)
blanchet@50557
  1131
                | NONE => false
blanchet@51177
  1132
            in (learns, (n, next_commit, timed_out)) end
blanchet@48404
  1133
        val n =
blanchet@51177
  1134
          if no_new_facts then
blanchet@48404
  1135
            0
blanchet@48404
  1136
          else
blanchet@48404
  1137
            let
blanchet@51182
  1138
              val new_facts =
blanchet@51184
  1139
                facts |> sort (crude_thm_ord o pairself snd)
blanchet@51184
  1140
                      |> attach_parents_to_facts []
blanchet@51177
  1141
                      |> filter_out (is_in_access_G o snd)
blanchet@51177
  1142
              val (learns, (n, _, _)) =
blanchet@51177
  1143
                ([], (0, next_commit_time (), false))
blanchet@51182
  1144
                |> fold learn_new_fact new_facts
blanchet@50631
  1145
            in commit true learns [] []; n end
blanchet@48404
  1146
        fun relearn_old_fact _ (accum as (_, (_, _, true))) = accum
blanchet@48439
  1147
          | relearn_old_fact ((_, (_, status)), th)
blanchet@50631
  1148
                             ((relearns, flops), (n, next_commit, _)) =
blanchet@48404
  1149
            let
blanchet@50624
  1150
              val name = nickname_of_thm th
blanchet@50631
  1151
              val (n, relearns, flops) =
blanchet@48439
  1152
                case deps_of status th of
blanchet@50631
  1153
                  SOME deps => (n + 1, (name, deps) :: relearns, flops)
blanchet@50631
  1154
                | NONE => (n, relearns, name :: flops)
blanchet@50631
  1155
              val (relearns, flops, next_commit) =
blanchet@48404
  1156
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@50631
  1157
                  (commit false [] relearns flops;
blanchet@50631
  1158
                   ([], [], next_commit_time ()))
blanchet@48404
  1159
                else
blanchet@50631
  1160
                  (relearns, flops, next_commit)
blanchet@50557
  1161
              val timed_out =
blanchet@50557
  1162
                case learn_timeout of
blanchet@50557
  1163
                  SOME timeout => Time.> (Timer.checkRealTimer timer, timeout)
blanchet@50557
  1164
                | NONE => false
blanchet@50631
  1165
            in ((relearns, flops), (n, next_commit, timed_out)) end
blanchet@48404
  1166
        val n =
blanchet@51177
  1167
          if not run_prover then
blanchet@48404
  1168
            n
blanchet@48404
  1169
          else
blanchet@48404
  1170
            let
blanchet@48668
  1171
              val max_isar = 1000 * max_dependencies
blanchet@48669
  1172
              fun kind_of_proof th =
blanchet@50624
  1173
                try (Graph.get_node access_G) (nickname_of_thm th)
blanchet@48669
  1174
                |> the_default Isar_Proof
blanchet@48406
  1175
              fun priority_of (_, th) =
blanchet@48668
  1176
                random_range 0 max_isar
blanchet@48669
  1177
                + (case kind_of_proof th of
blanchet@48669
  1178
                     Isar_Proof => 0
blanchet@50484
  1179
                   | Automatic_Proof => 2 * max_isar
blanchet@50484
  1180
                   | Isar_Proof_wegen_Prover_Flop => max_isar)
blanchet@54131
  1181
                - 100 * length (isar_dependencies_of name_tabs th)
blanchet@48404
  1182
              val old_facts =
blanchet@51177
  1183
                facts |> filter is_in_access_G
blanchet@51177
  1184
                      |> map (`priority_of)
blanchet@51177
  1185
                      |> sort (int_ord o pairself fst)
blanchet@51177
  1186
                      |> map snd
blanchet@50631
  1187
              val ((relearns, flops), (n, _, _)) =
blanchet@48669
  1188
                (([], []), (n, next_commit_time (), false))
blanchet@48404
  1189
                |> fold relearn_old_fact old_facts
blanchet@50631
  1190
            in commit true [] relearns flops; n end
blanchet@48318
  1191
      in
blanchet@48404
  1192
        if verbose orelse auto_level < 2 then
blanchet@48404
  1193
          "Learned " ^ string_of_int n ^ " nontrivial " ^
blanchet@54140
  1194
          (if run_prover then "automatic and " else "") ^ "Isar proof" ^ plural_s n ^
blanchet@52031
  1195
          (if verbose then " in " ^ string_of_time (Timer.checkRealTimer timer)
blanchet@52031
  1196
           else "") ^ "."
blanchet@48319
  1197
        else
blanchet@48319
  1198
          ""
blanchet@48318
  1199
      end
blanchet@48308
  1200
  end
blanchet@48304
  1201
blanchet@54123
  1202
fun mash_learn ctxt (params as {provers, timeout, ...}) fact_override chained run_prover =
blanchet@48316
  1203
  let
blanchet@48396
  1204
    val css = Sledgehammer_Fact.clasimpset_rule_table_of ctxt
blanchet@48395
  1205
    val ctxt = ctxt |> Config.put instantiate_inducts false
blanchet@48395
  1206
    val facts =
blanchet@48396
  1207
      nearly_all_facts ctxt false fact_override Symtab.empty css chained []
blanchet@48396
  1208
                       @{prop True}
blanchet@54115
  1209
      |> sort (crude_thm_ord o pairself snd o swap)
blanchet@48404
  1210
    val num_facts = length facts
blanchet@48404
  1211
    val prover = hd provers
blanchet@50484
  1212
    fun learn auto_level run_prover =
blanchet@53152
  1213
      mash_learn_facts ctxt params prover true auto_level run_prover NONE facts
blanchet@48404
  1214
      |> Output.urgent_message
blanchet@48316
  1215
  in
blanchet@50484
  1216
    if run_prover then
blanchet@50340
  1217
      ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@50484
  1218
       plural_s num_facts ^ " for automatic proofs (" ^ quote prover ^
blanchet@50557
  1219
       (case timeout of
blanchet@52031
  1220
          SOME timeout => " timeout: " ^ string_of_time timeout
blanchet@50557
  1221
        | NONE => "") ^ ").\n\nCollecting Isar proofs first..."
blanchet@50340
  1222
       |> Output.urgent_message;
blanchet@50340
  1223
       learn 1 false;
blanchet@50484
  1224
       "Now collecting automatic proofs. This may take several hours. You can \
blanchet@50340
  1225
       \safely stop the learning process at any point."
blanchet@50340
  1226
       |> Output.urgent_message;
blanchet@50340
  1227
       learn 0 true)
blanchet@50340
  1228
    else
blanchet@50340
  1229
      ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@50340
  1230
       plural_s num_facts ^ " for Isar proofs..."
blanchet@50340
  1231
       |> Output.urgent_message;
blanchet@50340
  1232
       learn 0 false)
blanchet@48316
  1233
  end
blanchet@48249
  1234
blanchet@53148
  1235
fun mash_can_suggest_facts ctxt overlord =
blanchet@53148
  1236
  not (Graph.is_empty (#access_G (peek_state ctxt overlord I)))
blanchet@50311
  1237
blanchet@50383
  1238
(* Generate more suggestions than requested, because some might be thrown out
blanchet@50383
  1239
   later for various reasons. *)
blanchet@50965
  1240
fun generous_max_facts max_facts = max_facts + Int.min (50, max_facts)
blanchet@50383
  1241
blanchet@50814
  1242
val mepo_weight = 0.5
blanchet@50814
  1243
val mash_weight = 0.5
blanchet@50814
  1244
blanchet@53152
  1245
val max_facts_to_learn_before_query = 100
blanchet@53152
  1246
blanchet@48318
  1247
(* The threshold should be large enough so that MaSh doesn't kick in for Auto
blanchet@48318
  1248
   Sledgehammer and Try. *)
blanchet@48318
  1249
val min_secs_for_learning = 15
blanchet@48318
  1250
blanchet@53153
  1251
fun relevant_facts ctxt
blanchet@53153
  1252
        (params as {overlord, blocking, learn, fact_filter, timeout, ...})
blanchet@53148
  1253
        prover max_facts ({add, only, ...} : fact_override) hyp_ts concl_t
blanchet@53148
  1254
        facts =
blanchet@48314
  1255
  if not (subset (op =) (the_list fact_filter, fact_filters)) then
blanchet@48314
  1256
    error ("Unknown fact filter: " ^ quote (the fact_filter) ^ ".")
blanchet@48314
  1257
  else if only then
blanchet@51004
  1258
    let val facts = facts |> map fact_of_raw_fact in
blanchet@51010
  1259
      [("", facts)]
blanchet@51004
  1260
    end
blanchet@48321
  1261
  else if max_facts <= 0 orelse null facts then
blanchet@51010
  1262
    [("", [])]
blanchet@48288
  1263
  else
blanchet@48288
  1264
    let
blanchet@53152
  1265
      fun maybe_launch_thread () =
blanchet@53153
  1266
        if not blocking andalso
blanchet@53153
  1267
           not (Async_Manager.has_running_threads MaShN) andalso
blanchet@50557
  1268
           (timeout = NONE orelse
blanchet@50557
  1269
            Time.toSeconds (the timeout) >= min_secs_for_learning) then
blanchet@50557
  1270
          let
blanchet@50557
  1271
            val timeout = Option.map (time_mult learn_timeout_slack) timeout
blanchet@50557
  1272
          in
blanchet@50557
  1273
            launch_thread (timeout |> the_default one_day)
blanchet@53152
  1274
                (fn () => (true, mash_learn_facts ctxt params prover true 2
blanchet@53152
  1275
                                                  false timeout facts))
blanchet@48319
  1276
          end
blanchet@48318
  1277
        else
blanchet@48318
  1278
          ()
blanchet@53152
  1279
      fun maybe_learn () =
blanchet@53819
  1280
        if is_mash_enabled () andalso learn then
blanchet@53152
  1281
          let
blanchet@53152
  1282
            val {access_G, num_known_facts, ...} = peek_state ctxt overlord I
blanchet@53152
  1283
            val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@53152
  1284
          in
blanchet@54012
  1285
            if length facts - num_known_facts
blanchet@54012
  1286
               <= max_facts_to_learn_before_query then
blanchet@54012
  1287
              case length (filter_out is_in_access_G facts) of
blanchet@54012
  1288
                0 => false
blanchet@54012
  1289
              | num_facts_to_learn =>
blanchet@54012
  1290
                if num_facts_to_learn <= max_facts_to_learn_before_query then
blanchet@54012
  1291
                  (mash_learn_facts ctxt params prover false 2 false timeout facts
blanchet@54012
  1292
                   |> (fn "" => () | s => Output.urgent_message (MaShN ^ ": " ^ s));
blanchet@54012
  1293
                   true)
blanchet@54012
  1294
                else
blanchet@54012
  1295
                  (maybe_launch_thread (); false)
blanchet@53152
  1296
            else
blanchet@53152
  1297
              (maybe_launch_thread (); false)
blanchet@53152
  1298
          end
blanchet@53152
  1299
        else
blanchet@53152
  1300
          false
blanchet@53152
  1301
      val (save, effective_fact_filter) =
blanchet@48314
  1302
        case fact_filter of
blanchet@53152
  1303
          SOME ff => (ff <> mepoN andalso maybe_learn (), ff)
blanchet@48318
  1304
        | NONE =>
blanchet@51024
  1305
          if is_mash_enabled () then
blanchet@53152
  1306
            (maybe_learn (),
blanchet@53148
  1307
             if mash_can_suggest_facts ctxt overlord then meshN else mepoN)
blanchet@48407
  1308
          else
blanchet@53152
  1309
            (false, mepoN)
blanchet@54143
  1310
blanchet@54143
  1311
      val unique_facts = drop_duplicate_facts facts
blanchet@48288
  1312
      val add_ths = Attrib.eval_thms ctxt add
blanchet@54143
  1313
blanchet@51004
  1314
      fun in_add (_, th) = member Thm.eq_thm_prop add_ths th
blanchet@51003
  1315
      fun add_and_take accepts =
blanchet@51003
  1316
        (case add_ths of
blanchet@51003
  1317
           [] => accepts
blanchet@54143
  1318
         | _ => (unique_facts |> filter in_add |> map fact_of_raw_fact) @
blanchet@51004
  1319
                (accepts |> filter_out in_add))
blanchet@48293
  1320
        |> take max_facts
blanchet@48406
  1321
      fun mepo () =
blanchet@54143
  1322
        (mepo_suggested_facts ctxt params max_facts NONE hyp_ts concl_t unique_facts
blanchet@54091
  1323
         |> weight_facts_steeply, [])
blanchet@48314
  1324
      fun mash () =
blanchet@54503
  1325
        mash_suggested_facts ctxt params (generous_max_facts max_facts) hyp_ts concl_t facts
blanchet@53140
  1326
        |>> weight_facts_steeply
blanchet@48314
  1327
      val mess =
blanchet@51003
  1328
        (* the order is important for the "case" expression below *)
blanchet@54091
  1329
        [] |> effective_fact_filter <> mepoN ? cons (mash_weight, mash)
blanchet@54091
  1330
           |> effective_fact_filter <> mashN ? cons (mepo_weight, mepo)
blanchet@54091
  1331
           |> Par_List.map (apsnd (fn f => f ()))
blanchet@54091
  1332
      val mesh = mesh_facts (eq_snd Thm.eq_thm_prop) max_facts mess |> add_and_take
blanchet@48288
  1333
    in
blanchet@53152
  1334
      if save then MaSh.save ctxt overlord else ();
blanchet@51024
  1335
      case (fact_filter, mess) of
blanchet@51024
  1336
        (NONE, [(_, (mepo, _)), (_, (mash, _))]) =>
blanchet@51010
  1337
        [(meshN, mesh), (mepoN, mepo |> map fst |> add_and_take),
blanchet@51010
  1338
         (mashN, mash |> map fst |> add_and_take)]
blanchet@54096
  1339
      | _ => [(effective_fact_filter, mesh)]
blanchet@48288
  1340
    end
blanchet@48288
  1341
blanchet@53148
  1342
fun kill_learners ctxt ({overlord, ...} : params) =
blanchet@53148
  1343
  (Async_Manager.kill_threads MaShN "learner"; MaSh.shutdown ctxt overlord)
blanchet@48319
  1344
fun running_learners () = Async_Manager.running_threads MaShN "learner"
blanchet@48319
  1345
blanchet@48248
  1346
end;