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