src/HOL/Tools/Sledgehammer/sledgehammer_mash.ML
author blanchet
Thu, 26 Jun 2014 13:36:00 +0200
changeset 58714 24738b4f8c6b
parent 58713 0b2bce982afd
child 58715 e9d47cd3239b
permissions -rw-r--r--
removed experimental machine learning engine
blanchet@49395
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mash.ML
blanchet@49263
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@58351
     3
    Author:     Cezary Kaliszyk, University of Innsbruck
blanchet@49263
     4
blanchet@49263
     5
Sledgehammer's machine-learning-based relevance filter (MaSh).
blanchet@49263
     6
*)
blanchet@49263
     7
blanchet@49396
     8
signature SLEDGEHAMMER_MASH =
blanchet@49263
     9
sig
blanchet@49266
    10
  type stature = ATP_Problem_Generate.stature
blanchet@52186
    11
  type raw_fact = Sledgehammer_Fact.raw_fact
blanchet@49311
    12
  type fact = Sledgehammer_Fact.fact
blanchet@49311
    13
  type fact_override = Sledgehammer_Fact.fact_override
blanchet@56543
    14
  type params = Sledgehammer_Prover.params
blanchet@56543
    15
  type prover_result = Sledgehammer_Prover.prover_result
blanchet@49266
    16
blanchet@49323
    17
  val trace : bool Config.T
blanchet@58492
    18
  val duplicates : bool Config.T
blanchet@52190
    19
  val MePoN : string
blanchet@49334
    20
  val MaShN : string
blanchet@52190
    21
  val MeShN : string
blanchet@49394
    22
  val mepoN : string
blanchet@49394
    23
  val mashN : string
blanchet@49329
    24
  val meshN : string
blanchet@49407
    25
  val unlearnN : string
blanchet@49407
    26
  val learn_isarN : string
blanchet@51499
    27
  val learn_proverN : string
blanchet@49407
    28
  val relearn_isarN : string
blanchet@51499
    29
  val relearn_proverN : string
blanchet@49329
    30
  val fact_filters : string list
blanchet@51841
    31
  val encode_str : string -> string
blanchet@51841
    32
  val encode_strs : string list -> string
blanchet@58347
    33
  val decode_str : string -> string
blanchet@58347
    34
  val decode_strs : string -> string list
blanchet@58397
    35
  val encode_features : (string * real) list -> string
blanchet@58467
    36
  val extract_suggestions : string -> string * (string * real) list
blanchet@51647
    37
blanchet@58620
    38
  datatype mash_engine =
blanchet@58620
    39
    MaSh_Py
blanchet@58620
    40
  | MaSh_SML_kNN
blanchet@58633
    41
  | MaSh_SML_kNN_Cpp
blanchet@58704
    42
  | MaSh_SML_NB
blanchet@58639
    43
  | MaSh_SML_NB_Cpp
blanchet@58448
    44
blanchet@58462
    45
  val is_mash_enabled : unit -> bool
blanchet@58462
    46
  val the_mash_engine : unit -> mash_engine
blanchet@58462
    47
blanchet@54285
    48
  val mash_unlearn : Proof.context -> params -> unit
blanchet@51639
    49
  val nickname_of_thm : thm -> string
blanchet@58348
    50
  val find_suggested_facts : Proof.context -> ('b * thm) list -> string list -> ('b * thm) list
blanchet@58348
    51
  val mesh_facts : ('a * 'a -> bool) -> int -> (real * (('a * real) list * 'a list)) list -> 'a list
blanchet@52272
    52
  val crude_thm_ord : thm * thm -> order
blanchet@52319
    53
  val thm_less : thm * thm -> bool
blanchet@49266
    54
  val goal_of_thm : theory -> thm -> thm
blanchet@58348
    55
  val run_prover_for_mash : Proof.context -> params -> string -> string -> fact list -> thm ->
blanchet@58348
    56
    prover_result
blanchet@58397
    57
  val features_of : Proof.context -> theory -> int -> int Symtab.table -> stature -> term list ->
blanchet@58397
    58
    (string * real) list
blanchet@52314
    59
  val trim_dependencies : string list -> string list option
blanchet@58648
    60
  val isar_dependencies_of : string Symtab.table * string Symtab.table -> thm -> string list option
blanchet@58348
    61
  val prover_dependencies_of : Proof.context -> params -> string -> int -> raw_fact list ->
blanchet@58348
    62
    string Symtab.table * string Symtab.table -> thm -> bool * string list
blanchet@58348
    63
  val attach_parents_to_facts : ('a * thm) list -> ('a * thm) list ->
blanchet@58348
    64
    (string list * ('a * thm)) list
blanchet@54277
    65
  val num_extra_feature_facts : int
blanchet@54278
    66
  val extra_feature_factor : real
blanchet@54277
    67
  val weight_facts_smoothly : 'a list -> ('a * real) list
blanchet@54277
    68
  val weight_facts_steeply : 'a list -> ('a * real) list
blanchet@58348
    69
  val find_mash_suggestions : Proof.context -> int -> string list -> ('b * thm) list ->
blanchet@58348
    70
    ('b * thm) list -> ('b * thm) list -> ('b * thm) list * ('b * thm) list
blanchet@54264
    71
  val add_const_counts : term -> int Symtab.table -> int Symtab.table
blanchet@58348
    72
  val mash_suggested_facts : Proof.context -> params -> int -> term list -> term -> raw_fact list ->
blanchet@58348
    73
    fact list * fact list
blanchet@55876
    74
  val mash_learn_proof : Proof.context -> params -> term -> ('a * thm) list -> thm list -> unit
blanchet@58462
    75
  val mash_learn_facts : Proof.context -> params -> string -> bool -> int -> bool -> Time.time ->
blanchet@58462
    76
    raw_fact list -> string
blanchet@58348
    77
  val mash_learn : Proof.context -> params -> fact_override -> thm list -> bool -> unit
blanchet@54956
    78
blanchet@54285
    79
  val mash_can_suggest_facts : Proof.context -> bool -> bool
blanchet@58450
    80
  val generous_max_suggestions : int -> int
blanchet@51829
    81
  val mepo_weight : real
blanchet@51829
    82
  val mash_weight : real
blanchet@58348
    83
  val relevant_facts : Proof.context -> params -> string -> int -> fact_override -> term list ->
blanchet@58348
    84
    term -> raw_fact list -> (string * fact list) list
blanchet@54285
    85
  val kill_learners : Proof.context -> params -> unit
blanchet@49334
    86
  val running_learners : unit -> unit
blanchet@49263
    87
end;
blanchet@49263
    88
blanchet@49396
    89
structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
blanchet@49263
    90
struct
blanchet@49264
    91
blanchet@49266
    92
open ATP_Util
blanchet@49266
    93
open ATP_Problem_Generate
blanchet@49266
    94
open Sledgehammer_Util
blanchet@49266
    95
open Sledgehammer_Fact
blanchet@56543
    96
open Sledgehammer_Prover
blanchet@56544
    97
open Sledgehammer_Prover_Minimize
blanchet@49396
    98
open Sledgehammer_MePo
blanchet@49266
    99
blanchet@58347
   100
val trace = Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
blanchet@58492
   101
val duplicates = Attrib.setup_config_bool @{binding sledgehammer_fact_duplicates} (K false)
blanchet@52214
   102
blanchet@49323
   103
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@49323
   104
blanchet@58492
   105
fun gen_eq_thm ctxt = if Config.get ctxt duplicates then Thm.eq_thm_strict else Thm.eq_thm_prop
blanchet@58492
   106
blanchet@52190
   107
val MePoN = "MePo"
blanchet@49334
   108
val MaShN = "MaSh"
blanchet@52190
   109
val MeShN = "MeSh"
blanchet@49334
   110
blanchet@49394
   111
val mepoN = "mepo"
blanchet@49394
   112
val mashN = "mash"
blanchet@49329
   113
val meshN = "mesh"
blanchet@49329
   114
blanchet@49394
   115
val fact_filters = [meshN, mepoN, mashN]
blanchet@49329
   116
blanchet@49407
   117
val unlearnN = "unlearn"
blanchet@49407
   118
val learn_isarN = "learn_isar"
blanchet@51499
   119
val learn_proverN = "learn_prover"
blanchet@49407
   120
val relearn_isarN = "relearn_isar"
blanchet@51499
   121
val relearn_proverN = "relearn_prover"
blanchet@49407
   122
blanchet@58713
   123
val hintsN = ".hints"
blanchet@58713
   124
blanchet@58710
   125
fun map_array_at ary f i = Array.update (ary, i, f (Array.sub (ary, i)))
blanchet@58710
   126
blanchet@58713
   127
type xtab = int * int Symtab.table
blanchet@58713
   128
blanchet@58713
   129
val empty_xtab = (0, Symtab.empty)
blanchet@58713
   130
blanchet@58713
   131
fun add_to_xtab key (next, tab) = (next + 1, Symtab.update_new (key, next) tab)
blanchet@58713
   132
fun maybe_add_to_xtab key = perhaps (try (add_to_xtab key))
blanchet@58713
   133
blanchet@58349
   134
fun mash_state_dir () = Path.explode "$ISABELLE_HOME_USER/mash" |> tap Isabelle_System.mkdir
blanchet@51325
   135
fun mash_state_file () = Path.append (mash_state_dir ()) (Path.explode "state")
blanchet@49266
   136
blanchet@58349
   137
fun wipe_out_mash_state_dir () =
blanchet@58349
   138
  let val path = mash_state_dir () in
blanchet@58349
   139
    try (File.fold_dir (fn file => fn _ => try File.rm (Path.append path (Path.basic file))) path)
blanchet@58349
   140
      NONE;
blanchet@58349
   141
    ()
blanchet@58349
   142
  end
blanchet@49345
   143
blanchet@58620
   144
datatype mash_engine =
blanchet@58620
   145
  MaSh_Py
blanchet@58620
   146
| MaSh_SML_kNN
blanchet@58633
   147
| MaSh_SML_kNN_Cpp
blanchet@58704
   148
| MaSh_SML_NB
blanchet@58639
   149
| MaSh_SML_NB_Cpp
blanchet@58620
   150
blanchet@58370
   151
fun mash_engine () =
blanchet@58431
   152
  let val flag1 = Options.default_string @{system_option MaSh} in
blanchet@58370
   153
    (case if flag1 <> "none" (* default *) then flag1 else getenv "MASH" of
blanchet@58704
   154
      "yes" => SOME MaSh_SML_NB
blanchet@58370
   155
    | "py" => SOME MaSh_Py
blanchet@58704
   156
    | "sml" => SOME MaSh_SML_NB
blanchet@58371
   157
    | "sml_knn" => SOME MaSh_SML_kNN
blanchet@58633
   158
    | "sml_knn_cpp" => SOME MaSh_SML_kNN_Cpp
blanchet@58704
   159
    | "sml_nb" => SOME MaSh_SML_NB
blanchet@58639
   160
    | "sml_nb_cpp" => SOME MaSh_SML_NB_Cpp
blanchet@58370
   161
    | _ => NONE)
blanchet@58370
   162
  end
blanchet@58360
   163
blanchet@58370
   164
val is_mash_enabled = is_some o mash_engine
blanchet@58704
   165
val the_mash_engine = the_default MaSh_SML_NB o mash_engine
blanchet@58360
   166
blanchet@58349
   167
blanchet@58449
   168
(*** Low-level communication with the Python version of MaSh ***)
blanchet@51326
   169
blanchet@54254
   170
val save_models_arg = "--saveModels"
blanchet@54254
   171
val shutdown_server_arg = "--shutdownServer"
blanchet@54254
   172
blanchet@58464
   173
fun wipe_out_file file = ignore (try (File.rm o Path.explode) file)
blanchet@51326
   174
blanchet@51350
   175
fun write_file banner (xs, f) path =
blanchet@51350
   176
  (case banner of SOME s => File.write path s | NONE => ();
blanchet@54231
   177
   xs |> chunk_list 500 |> List.app (File.append path o implode o map f))
blanchet@51334
   178
  handle IO.Io _ => ()
blanchet@51326
   179
blanchet@54289
   180
fun run_mash_tool ctxt overlord extra_args background write_cmds read_suggs =
blanchet@51326
   181
  let
blanchet@51326
   182
    val (temp_dir, serial) =
blanchet@51326
   183
      if overlord then (getenv "ISABELLE_HOME_USER", "")
blanchet@51326
   184
      else (getenv "ISABELLE_TMP", serial_string ())
blanchet@54266
   185
    val log_file = temp_dir ^ "/mash_log" ^ serial
blanchet@51326
   186
    val err_file = temp_dir ^ "/mash_err" ^ serial
blanchet@51326
   187
    val sugg_file = temp_dir ^ "/mash_suggs" ^ serial
blanchet@51350
   188
    val sugg_path = Path.explode sugg_file
blanchet@51326
   189
    val cmd_file = temp_dir ^ "/mash_commands" ^ serial
blanchet@51350
   190
    val cmd_path = Path.explode cmd_file
blanchet@58349
   191
    val model_dir = File.shell_path (mash_state_dir ())
blanchet@58472
   192
blanchet@51326
   193
    val command =
blanchet@54693
   194
      "cd \"$ISABELLE_SLEDGEHAMMER_MASH\"/src; \
blanchet@54927
   195
      \PYTHONDONTWRITEBYTECODE=y ./mash.py\
blanchet@54927
   196
      \ --quiet\
blanchet@54927
   197
      \ --port=$MASH_PORT\
blanchet@54693
   198
      \ --outputDir " ^ model_dir ^
blanchet@54693
   199
      " --modelFile=" ^ model_dir ^ "/model.pickle\
blanchet@54693
   200
      \ --dictsFile=" ^ model_dir ^ "/dict.pickle\
blanchet@54927
   201
      \ --log " ^ log_file ^
blanchet@54927
   202
      " --inputFile " ^ cmd_file ^
blanchet@54927
   203
      " --predictions " ^ sugg_file ^
blanchet@58347
   204
      (if extra_args = [] then "" else " " ^ space_implode " " extra_args) ^ " >& " ^ err_file ^
blanchet@54289
   205
      (if background then " &" else "")
blanchet@58472
   206
blanchet@51326
   207
    fun run_on () =
blanchet@51765
   208
      (Isabelle_System.bash command
blanchet@55552
   209
       |> tap (fn _ =>
blanchet@58348
   210
         (case try File.read (Path.explode err_file) |> the_default "" of
blanchet@58348
   211
           "" => trace_msg ctxt (K "Done")
blanchet@58348
   212
         | s => warning ("MaSh error: " ^ elide_string 1000 s)));
blanchet@51350
   213
       read_suggs (fn () => try File.read_lines sugg_path |> these))
blanchet@58472
   214
blanchet@51326
   215
    fun clean_up () =
blanchet@58347
   216
      if overlord then () else List.app wipe_out_file [err_file, sugg_file, cmd_file]
blanchet@51326
   217
  in
blanchet@51350
   218
    write_file (SOME "") ([], K "") sugg_path;
blanchet@51350
   219
    write_file (SOME "") write_cmds cmd_path;
blanchet@51326
   220
    trace_msg ctxt (fn () => "Running " ^ command);
blanchet@51326
   221
    with_cleanup clean_up run_on ()
blanchet@51326
   222
  end
blanchet@49266
   223
blanchet@49323
   224
fun meta_char c =
blanchet@58348
   225
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse c = #")" orelse
blanchet@58348
   226
     c = #"," then
blanchet@49266
   227
    String.str c
blanchet@49266
   228
  else
blanchet@49266
   229
    (* fixed width, in case more digits follow *)
blanchet@49410
   230
    "%" ^ stringN_of_int 3 (Char.ord c)
blanchet@49266
   231
blanchet@49323
   232
fun unmeta_chars accum [] = String.implode (rev accum)
blanchet@49410
   233
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
blanchet@49323
   234
    (case Int.fromString (String.implode [d1, d2, d3]) of
blanchet@58347
   235
      SOME n => unmeta_chars (Char.chr n :: accum) cs
blanchet@58347
   236
    | NONE => "" (* error *))
blanchet@49410
   237
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
blanchet@49323
   238
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs
blanchet@49323
   239
blanchet@51841
   240
val encode_str = String.translate meta_char
blanchet@58347
   241
val decode_str = String.explode #> unmeta_chars []
blanchet@58347
   242
blanchet@51841
   243
val encode_strs = map encode_str #> space_implode " "
blanchet@58347
   244
val decode_strs = space_explode " " #> filter_out (curry (op =) "") #> map decode_str
blanchet@49266
   245
blanchet@54695
   246
(* Avoid scientific notation *)
blanchet@54695
   247
fun safe_str_of_real r =
blanchet@54695
   248
  if r < 0.00001 then "0.00001"
blanchet@54695
   249
  else if r >= 1000000.0 then "1000000"
blanchet@54695
   250
  else Markup.print_real r
blanchet@54695
   251
blanchet@56037
   252
fun encode_feature (names, weight) =
blanchet@58397
   253
  encode_str names ^ (if Real.== (weight, 1.0) then "" else "=" ^ safe_str_of_real weight)
blanchet@56037
   254
blanchet@51371
   255
val encode_features = map encode_feature #> space_implode " "
blanchet@51371
   256
blanchet@58347
   257
fun str_of_learn (name, parents, feats, deps) =
blanchet@58397
   258
  "! " ^ encode_str name ^ ": " ^ encode_strs parents ^ "; " ^ encode_strs feats ^ "; " ^
blanchet@58397
   259
  encode_strs deps ^ "\n"
blanchet@49684
   260
blanchet@58347
   261
fun str_of_relearn (name, deps) = "p " ^ encode_str name ^ ": " ^ encode_strs deps ^ "\n"
blanchet@49684
   262
blanchet@54236
   263
fun str_of_query max_suggs (learns, hints, parents, feats) =
blanchet@54232
   264
  implode (map str_of_learn learns) ^
blanchet@58347
   265
  "? " ^ string_of_int max_suggs ^ " # " ^ encode_strs parents ^ "; " ^ encode_features feats ^
blanchet@54232
   266
  (if null hints then "" else "; " ^ encode_strs hints) ^ "\n"
blanchet@49421
   267
blanchet@58347
   268
(* The suggested weights do not make much sense. *)
blanchet@49421
   269
fun extract_suggestion sugg =
blanchet@56628
   270
  (case space_explode "=" sugg of
blanchet@58467
   271
    [name, weight] => SOME (decode_str name, Real.fromString weight |> the_default 1.0)
blanchet@58467
   272
  | [name] => SOME (decode_str name, 1.0)
blanchet@56628
   273
  | _ => NONE)
blanchet@49421
   274
blanchet@51648
   275
fun extract_suggestions line =
blanchet@56628
   276
  (case space_explode ":" line of
blanchet@58347
   277
    [goal, suggs] => (decode_str goal, map_filter extract_suggestion (space_explode " " suggs))
blanchet@56628
   278
  | _ => ("", []))
blanchet@49326
   279
blanchet@58349
   280
structure MaSh_Py =
blanchet@51647
   281
struct
blanchet@51647
   282
blanchet@54285
   283
fun shutdown ctxt overlord =
blanchet@58349
   284
  (trace_msg ctxt (K "MaSh_Py shutdown");
blanchet@54893
   285
   run_mash_tool ctxt overlord [shutdown_server_arg] false ([], K "") (K ()))
blanchet@54289
   286
blanchet@54289
   287
fun save ctxt overlord =
blanchet@58349
   288
  (trace_msg ctxt (K "MaSh_Py save");
blanchet@54290
   289
   run_mash_tool ctxt overlord [save_models_arg] true ([], K "") (K ()))
blanchet@54279
   290
blanchet@54285
   291
fun unlearn ctxt overlord =
blanchet@58349
   292
  (trace_msg ctxt (K "MaSh_Py unlearn");
blanchet@58349
   293
   shutdown ctxt overlord;
blanchet@58349
   294
   wipe_out_mash_state_dir ())
blanchet@51326
   295
blanchet@54894
   296
fun learn _ _ _ [] = ()
blanchet@58348
   297
  | learn ctxt overlord save learns =
blanchet@58349
   298
    (trace_msg ctxt (fn () =>
blanchet@58351
   299
       "MaSh_Py learn {" ^ elide_string 1000 (space_implode " " (map #1 learns)) ^ "}");
blanchet@58349
   300
     run_mash_tool ctxt overlord ([] |> save ? cons save_models_arg) false (learns, str_of_learn)
blanchet@58349
   301
       (K ()))
blanchet@51326
   302
blanchet@54894
   303
fun relearn _ _ _ [] = ()
blanchet@54894
   304
  | relearn ctxt overlord save relearns =
blanchet@58349
   305
    (trace_msg ctxt (fn () => "MaSh_Py relearn " ^
blanchet@58348
   306
       elide_string 1000 (space_implode " " (map #1 relearns)));
blanchet@54894
   307
     run_mash_tool ctxt overlord ([] |> save ? cons save_models_arg) false
blanchet@58348
   308
       (relearns, str_of_relearn) (K ()))
blanchet@51326
   309
blanchet@54254
   310
fun query ctxt overlord max_suggs (query as (_, _, _, feats)) =
blanchet@58349
   311
  (trace_msg ctxt (fn () => "MaSh_Py query " ^ encode_features feats);
blanchet@56628
   312
   run_mash_tool ctxt overlord [] false ([query], str_of_query max_suggs) (fn suggs =>
blanchet@58349
   313
     (case suggs () of [] => [] | suggs => snd (extract_suggestions (List.last suggs))))
blanchet@51326
   314
   handle List.Empty => [])
blanchet@51326
   315
blanchet@51647
   316
end;
blanchet@51647
   317
blanchet@51326
   318
blanchet@58349
   319
(*** Standard ML version of MaSh ***)
blanchet@58349
   320
blanchet@58349
   321
structure MaSh_SML =
blanchet@58349
   322
struct
blanchet@58349
   323
blanchet@58351
   324
exception BOTTOM of int
blanchet@58351
   325
blanchet@58697
   326
fun heap cmp bnd al a =
blanchet@58351
   327
  let
blanchet@58351
   328
    fun maxson l i =
blanchet@58359
   329
      let val i31 = i + i + i + 1 in
blanchet@58351
   330
        if i31 + 2 < l then
blanchet@58359
   331
          let val x = Unsynchronized.ref i31 in
blanchet@58359
   332
            if cmp (Array.sub (a, i31), Array.sub (a, i31 + 1)) = LESS then x := i31 + 1 else ();
blanchet@58359
   333
            if cmp (Array.sub (a, !x), Array.sub (a, i31 + 2)) = LESS then x := i31 + 2 else ();
blanchet@58351
   334
            !x
blanchet@58351
   335
          end
blanchet@58351
   336
        else
blanchet@58351
   337
          if i31 + 1 < l andalso cmp (Array.sub (a, i31), Array.sub (a, i31 + 1)) = LESS
blanchet@58351
   338
          then i31 + 1 else if i31 < l then i31 else raise BOTTOM i
blanchet@58351
   339
      end
blanchet@58351
   340
blanchet@58351
   341
    fun trickledown l i e =
blanchet@58371
   342
      let val j = maxson l i in
blanchet@58351
   343
        if cmp (Array.sub (a, j), e) = GREATER then
blanchet@58371
   344
          (Array.update (a, i, Array.sub (a, j)); trickledown l j e)
blanchet@58371
   345
        else
blanchet@58371
   346
          Array.update (a, i, e)
blanchet@58351
   347
      end
blanchet@58351
   348
blanchet@58351
   349
    fun trickle l i e = trickledown l i e handle BOTTOM i => Array.update (a, i, e)
blanchet@58351
   350
blanchet@58351
   351
    fun bubbledown l i =
blanchet@58371
   352
      let val j = maxson l i in
blanchet@58371
   353
        Array.update (a, i, Array.sub (a, j));
blanchet@58351
   354
        bubbledown l j
blanchet@58351
   355
      end
blanchet@58351
   356
blanchet@58351
   357
    fun bubble l i = bubbledown l i handle BOTTOM i => i
blanchet@58351
   358
blanchet@58351
   359
    fun trickleup i e =
blanchet@58371
   360
      let val father = (i - 1) div 3 in
blanchet@58351
   361
        if cmp (Array.sub (a, father), e) = LESS then
blanchet@58371
   362
          (Array.update (a, i, Array.sub (a, father));
blanchet@58371
   363
           if father > 0 then trickleup father e else Array.update (a, 0, e))
blanchet@58371
   364
        else
blanchet@58371
   365
          Array.update (a, i, e)
blanchet@58351
   366
      end
blanchet@58351
   367
blanchet@58697
   368
    fun for i = if i < 0 then () else (trickle al i (Array.sub (a, i)); for (i - 1))
blanchet@58351
   369
blanchet@58351
   370
    fun for2 i =
blanchet@58697
   371
      if i < Integer.max 2 (al - bnd) then
blanchet@58371
   372
        ()
blanchet@58371
   373
      else
blanchet@58371
   374
        let val e = Array.sub (a, i) in
blanchet@58371
   375
          Array.update (a, i, Array.sub (a, 0));
blanchet@58371
   376
          trickleup (bubble i 0) e;
blanchet@58371
   377
          for2 (i - 1)
blanchet@58371
   378
        end
blanchet@58351
   379
  in
blanchet@58697
   380
    for (((al + 1) div 3) - 1);
blanchet@58697
   381
    for2 (al - 1);
blanchet@58697
   382
    if al > 1 then
blanchet@58371
   383
      let val e = Array.sub (a, 1) in
blanchet@58371
   384
        Array.update (a, 1, Array.sub (a, 0));
blanchet@58351
   385
        Array.update (a, 0, e)
blanchet@58351
   386
      end
blanchet@58371
   387
    else
blanchet@58371
   388
      ()
blanchet@58351
   389
  end
blanchet@58351
   390
blanchet@58695
   391
val number_of_nearest_neighbors = 10 (* FUDGE *)
blanchet@58695
   392
blanchet@58713
   393
fun select_visible_facts big_number recommends =
blanchet@58706
   394
  List.app (fn at =>
blanchet@58706
   395
    let val (j, ov) = Array.sub (recommends, at) in
blanchet@58713
   396
      Array.update (recommends, at, (j, big_number + ov))
blanchet@58706
   397
    end)
blanchet@58706
   398
blanchet@58695
   399
exception EXIT of unit
blanchet@58695
   400
blanchet@58699
   401
fun k_nearest_neighbors num_facts get_deps get_sym_ths max_suggs visible_facts num_feats feats =
blanchet@58351
   402
  let
blanchet@58699
   403
    val dffreq = Array.array (num_feats, 0)
blanchet@58699
   404
blanchet@58710
   405
    val add_sym = map_array_at dffreq (Integer.add 1)
blanchet@58699
   406
    fun for1 i =
blanchet@58699
   407
      if i = num_feats then () else
blanchet@58699
   408
      (List.app (fn _ => add_sym i) (get_sym_ths i); for1 (i + 1))
blanchet@58699
   409
    val _ = for1 0
blanchet@58699
   410
blanchet@58699
   411
    val ln_afreq = Math.ln (Real.fromInt num_facts)
blanchet@58701
   412
    fun tfidf feat = ln_afreq - Math.ln (Real.fromInt (Array.sub (dffreq, feat)))
blanchet@58359
   413
blanchet@58444
   414
    val overlaps_sqr = Array.tabulate (num_facts, rpair 0.0)
blanchet@58359
   415
blanchet@58351
   416
    fun inc_overlap j v =
blanchet@58703
   417
      let val ov = snd (Array.sub (overlaps_sqr, j)) in
blanchet@58351
   418
        Array.update (overlaps_sqr, j, (j, v + ov))
blanchet@58359
   419
      end
blanchet@58359
   420
blanchet@58699
   421
    fun do_feat s =
blanchet@58351
   422
      let
blanchet@58699
   423
        val sw = tfidf s
blanchet@58699
   424
        val w2 = sw * sw
blanchet@58699
   425
        fun do_th j = if j < num_facts then inc_overlap j w2 else ()
blanchet@58351
   426
      in
blanchet@58359
   427
        List.app do_th (get_sym_ths s)
blanchet@58359
   428
      end
blanchet@58359
   429
blanchet@58444
   430
    val _ = List.app do_feat feats
blanchet@58697
   431
    val _ = heap (Real.compare o pairself snd) num_facts num_facts overlaps_sqr
blanchet@58695
   432
    val no_recommends = Unsynchronized.ref 0
blanchet@58698
   433
    val recommends = Array.tabulate (num_facts, rpair 0.0)
blanchet@58705
   434
    val age = Unsynchronized.ref 500000000.0
blanchet@58359
   435
blanchet@58351
   436
    fun inc_recommend j v =
blanchet@58695
   437
      let val ov = snd (Array.sub (recommends, j)) in
blanchet@58699
   438
      if ov <= 0.0 then (no_recommends := !no_recommends + 1; Array.update (recommends, j, (j, !age + ov)))
blanchet@58699
   439
      else (if ov < !age + 1000.0 then Array.update (recommends, j, (j, v + ov)) else ()) end
blanchet@58359
   440
blanchet@58695
   441
    val k = Unsynchronized.ref 0
blanchet@58695
   442
    fun do_k k =
blanchet@58698
   443
      if k >= num_facts then
blanchet@58695
   444
        raise EXIT ()
blanchet@58359
   445
      else
blanchet@58359
   446
        let
blanchet@58444
   447
          val (j, o2) = Array.sub (overlaps_sqr, num_facts - k - 1)
blanchet@58359
   448
          val o1 = Math.sqrt o2
blanchet@58359
   449
          val _ = inc_recommend j o1
blanchet@58359
   450
          val ds = get_deps j
blanchet@58359
   451
          val l = Real.fromInt (length ds)
blanchet@58359
   452
        in
blanchet@58695
   453
          List.app (fn d => inc_recommend d (o1 / l)) ds
blanchet@58359
   454
        end
blanchet@58359
   455
blanchet@58695
   456
    fun while1 () =
blanchet@58703
   457
      if !k = number_of_nearest_neighbors then () else (do_k (!k); k := !k + 1; while1 ())
blanchet@58695
   458
      handle EXIT () => ()
blanchet@58695
   459
blanchet@58695
   460
    fun while2 () =
blanchet@58703
   461
      if !no_recommends >= max_suggs then ()
blanchet@58703
   462
      else (do_k (!k); k := !k + 1; age := !age - 10000.0; while2 ())
blanchet@58695
   463
      handle EXIT () => ()
blanchet@58695
   464
blanchet@58351
   465
    fun ret acc at =
blanchet@58705
   466
      if at = num_facts then acc else ret (Array.sub (recommends, at) :: acc) (at + 1)
blanchet@58351
   467
  in
blanchet@58706
   468
    while1 ();
blanchet@58706
   469
    while2 ();
blanchet@58713
   470
    select_visible_facts 1000000000.0 recommends visible_facts;
blanchet@58698
   471
    heap (Real.compare o pairself snd) max_suggs num_facts recommends;
blanchet@58698
   472
    ret [] (Integer.max 0 (num_facts - max_suggs))
blanchet@58351
   473
  end
blanchet@58351
   474
blanchet@58474
   475
val nb_def_prior_weight = 21 (* FUDGE *)
blanchet@58437
   476
blanchet@58711
   477
fun learn_facts tfreq sfreq dffreq num_facts get_deps get_feats =
blanchet@58696
   478
  let
blanchet@58697
   479
    fun learn_fact th feats deps =
blanchet@58696
   480
      let
blanchet@58697
   481
        fun add_th weight t =
blanchet@58697
   482
          let
blanchet@58697
   483
            val im = Array.sub (sfreq, t)
blanchet@58697
   484
            fun fold_fn s sf = Inttab.map_default (s, 0) (Integer.add weight) sf
blanchet@58697
   485
          in
blanchet@58710
   486
            map_array_at tfreq (Integer.add weight) t;
blanchet@58697
   487
            Array.update (sfreq, t, fold fold_fn feats im)
blanchet@58697
   488
          end
blanchet@58697
   489
blanchet@58710
   490
        val add_sym = map_array_at dffreq (Integer.add 1)
blanchet@58696
   491
      in
blanchet@58697
   492
        add_th nb_def_prior_weight th;
blanchet@58697
   493
        List.app (add_th 1) deps;
blanchet@58697
   494
        List.app add_sym feats
blanchet@58696
   495
      end
blanchet@58696
   496
blanchet@58444
   497
    fun for i =
blanchet@58697
   498
      if i = num_facts then () else (learn_fact i (get_feats i) (get_deps i); for (i + 1))
blanchet@58444
   499
  in
blanchet@58641
   500
    for 0;
blanchet@58708
   501
    (Array.vector tfreq, Array.vector sfreq, Array.vector dffreq)
blanchet@58444
   502
  end
blanchet@58371
   503
blanchet@58697
   504
fun learn num_facts get_deps get_feats num_feats =
blanchet@58697
   505
  let
blanchet@58697
   506
    val tfreq = Array.array (num_facts, 0)
blanchet@58697
   507
    val sfreq = Array.array (num_facts, Inttab.empty)
blanchet@58697
   508
    val dffreq = Array.array (num_feats, 0)
blanchet@58697
   509
  in
blanchet@58711
   510
    learn_facts tfreq sfreq dffreq num_facts get_deps get_feats
blanchet@58697
   511
  end
blanchet@58697
   512
blanchet@58708
   513
fun naive_bayes_query num_facts max_suggs visible_facts feats (tfreq, sfreq, dffreq) =
blanchet@58620
   514
  let
blanchet@58704
   515
    val tau = 0.05 (* FUDGE *)
blanchet@58704
   516
    val pos_weight = 10.0 (* FUDGE *)
blanchet@58620
   517
    val def_val = ~15.0 (* FUDGE *)
blanchet@58466
   518
blanchet@58708
   519
    val ln_afreq = Math.ln (Real.fromInt num_facts)
blanchet@58708
   520
    val idf = Vector.map (fn i => ln_afreq - Math.ln (Real.fromInt i)) dffreq
blanchet@58708
   521
blanchet@58701
   522
    fun tfidf feat = Vector.sub (idf, feat)
blanchet@58444
   523
blanchet@58444
   524
    fun log_posterior i =
blanchet@58371
   525
      let
blanchet@58444
   526
        val tfreq = Real.fromInt (Vector.sub (tfreq, i))
blanchet@58439
   527
blanchet@58699
   528
        fun fold_feats f (res, sfh) =
blanchet@58444
   529
          (case Inttab.lookup sfh f of
blanchet@58444
   530
            SOME sf =>
blanchet@58640
   531
            (res + tfidf f * Math.ln (pos_weight * Real.fromInt sf / tfreq),
blanchet@58444
   532
             Inttab.delete f sfh)
blanchet@58640
   533
          | NONE => (res + tfidf f * def_val, sfh))
blanchet@58439
   534
blanchet@58444
   535
        val (res, sfh) = fold fold_feats feats (Math.ln tfreq, Vector.sub (sfreq, i))
blanchet@58439
   536
blanchet@58704
   537
        fun fold_sfh (f, sf) sow = sow + tfidf f * Math.ln (1.0 + (1.0 - Real.fromInt sf) / tfreq)
blanchet@58439
   538
blanchet@58444
   539
        val sum_of_weights = Inttab.fold fold_sfh sfh 0.0
blanchet@58371
   540
      in
blanchet@58620
   541
        res + tau * sum_of_weights
blanchet@58439
   542
      end
blanchet@58371
   543
blanchet@58698
   544
    val posterior = Array.tabulate (num_facts, (fn j => (j, log_posterior j)))
blanchet@58444
   545
blanchet@58706
   546
    fun ret at acc =
blanchet@58706
   547
      if at = num_facts then acc else ret (at + 1) (Array.sub (posterior, at) :: acc)
blanchet@58371
   548
  in
blanchet@58713
   549
    select_visible_facts 100000.0 posterior visible_facts;
blanchet@58698
   550
    heap (Real.compare o pairself snd) max_suggs num_facts posterior;
blanchet@58706
   551
    ret (Integer.max 0 (num_facts - max_suggs)) []
blanchet@58371
   552
  end
blanchet@58371
   553
blanchet@58704
   554
fun naive_bayes num_facts get_deps get_feats num_feats max_suggs visible_facts feats =
blanchet@58697
   555
  learn num_facts get_deps get_feats num_feats
blanchet@58704
   556
  |> naive_bayes_query num_facts max_suggs visible_facts feats
blanchet@58444
   557
blanchet@58467
   558
(* experimental *)
blanchet@58711
   559
fun naive_bayes_py ctxt overlord num_facts get_deps get_feats max_suggs feats =
blanchet@58467
   560
  let
blanchet@58467
   561
    fun name_of_fact j = "f" ^ string_of_int j
blanchet@58467
   562
    fun fact_of_name s = the (Int.fromString (unprefix "f" s))
blanchet@58467
   563
    fun name_of_feature j = "F" ^ string_of_int j
blanchet@58467
   564
    fun parents_of j = if j = 0 then [] else [name_of_fact (j - 1)]
blanchet@58467
   565
blanchet@58467
   566
    val learns = map (fn j => (name_of_fact j, parents_of j, map name_of_feature (get_feats j),
blanchet@58467
   567
      map name_of_fact (get_deps j))) (0 upto num_facts - 1)
blanchet@58698
   568
    val parents' = parents_of num_facts
blanchet@58699
   569
    val feats' = map (rpair 1.0 o name_of_feature) feats
blanchet@58467
   570
  in
blanchet@58467
   571
    MaSh_Py.unlearn ctxt overlord;
blanchet@58472
   572
    OS.Process.sleep (seconds 2.0); (* hack *)
blanchet@58467
   573
    MaSh_Py.query ctxt overlord max_suggs (learns, [], parents', feats')
blanchet@58467
   574
    |> map (apfst fact_of_name)
blanchet@58467
   575
  end
blanchet@58467
   576
blanchet@58633
   577
(* experimental *)
blanchet@58639
   578
fun c_plus_plus_tool tool max_suggs learns cfeats =
blanchet@58633
   579
  let
blanchet@58639
   580
    val ser = string_of_int (serial ()) (* poor person's attempt at thread-safety *)
blanchet@58639
   581
    val ocs = TextIO.openOut ("adv_syms" ^ ser)
blanchet@58639
   582
    val ocd = TextIO.openOut ("adv_deps" ^ ser)
blanchet@58639
   583
    val ocq = TextIO.openOut ("adv_seq" ^ ser)
blanchet@58639
   584
    val occ = TextIO.openOut ("adv_conj" ^ ser)
blanchet@58638
   585
blanchet@58633
   586
    fun os oc s = TextIO.output (oc, s)
blanchet@58638
   587
blanchet@58639
   588
    fun ol _ _ _ [] = ()
blanchet@58639
   589
      | ol _ f _ [e] = f e
blanchet@58633
   590
      | ol oc f sep (h :: t) = (f h; os oc sep; ol oc f sep t)
blanchet@58638
   591
blanchet@58636
   592
    fun do_learn (name, feats, deps) =
blanchet@58699
   593
      (os ocs name; os ocs ":"; ol ocs (os ocs o quote) ", " feats; os ocs "\n";
blanchet@58639
   594
       os ocd name; os ocd ":"; ol ocd (os ocd) " " deps; os ocd "\n"; os ocq name; os ocq "\n")
blanchet@58638
   595
blanchet@58633
   596
    fun forkexec no =
blanchet@58633
   597
      let
blanchet@58633
   598
        val cmd =
blanchet@58639
   599
          "~/misc/" ^ tool ^ " adv_syms" ^ ser ^ " adv_deps" ^ ser ^ " " ^ string_of_int no ^
blanchet@58639
   600
          " adv_seq" ^ ser ^ " < adv_conj" ^ ser
blanchet@58633
   601
      in
blanchet@58633
   602
        fst (Isabelle_System.bash_output cmd)
blanchet@58633
   603
        |> space_explode " "
blanchet@58636
   604
        |> filter_out (curry (op =) "")
blanchet@58633
   605
      end
blanchet@58633
   606
  in
blanchet@58699
   607
    (List.app do_learn learns; ol occ (os occ o quote) ", " cfeats;
blanchet@58639
   608
     TextIO.closeOut ocs; TextIO.closeOut ocd; TextIO.closeOut ocq; TextIO.closeOut occ;
blanchet@58636
   609
     forkexec max_suggs)
blanchet@58633
   610
  end
blanchet@58633
   611
blanchet@58639
   612
val k_nearest_neighbors_cpp =
blanchet@58695
   613
  c_plus_plus_tool ("newknn/knn" ^ " " ^ string_of_int number_of_nearest_neighbors)
blanchet@58639
   614
val naive_bayes_cpp = c_plus_plus_tool "predict/nbayes"
blanchet@58639
   615
blanchet@58714
   616
fun query ctxt engine (num_facts, fact_tab) (num_feats, feat_tab) visible_facts max_suggs learns0
blanchet@58714
   617
    conj_feats =
blanchet@58711
   618
  if engine = MaSh_SML_kNN_Cpp then
blanchet@58713
   619
    k_nearest_neighbors_cpp max_suggs learns0 conj_feats
blanchet@58711
   620
  else if engine = MaSh_SML_NB_Cpp then
blanchet@58713
   621
    naive_bayes_cpp max_suggs learns0 conj_feats
blanchet@58711
   622
  else
blanchet@58711
   623
    let
blanchet@58713
   624
      val learn_ary = Array.array (num_facts, ("", [], []))
blanchet@58713
   625
      val _ =
blanchet@58713
   626
        List.app (fn entry as (fact, _, _) =>
blanchet@58713
   627
            Array.update (learn_ary, the (Symtab.lookup fact_tab fact), entry))
blanchet@58713
   628
          learns0
blanchet@58713
   629
      val learns = Array.foldr (op ::) [] learn_ary
blanchet@58713
   630
blanchet@58711
   631
      val facts = map #1 learns
blanchet@58711
   632
      val featss = map (map_filter (Symtab.lookup feat_tab) o #2) learns
blanchet@58711
   633
      val depss = map (map_filter (Symtab.lookup fact_tab) o #3) learns
blanchet@58709
   634
blanchet@58711
   635
      val fact_vec = Vector.fromList facts
blanchet@58711
   636
      val deps_vec = Vector.fromList depss
blanchet@58351
   637
blanchet@58711
   638
      val get_deps = curry Vector.sub deps_vec
blanchet@58355
   639
blanchet@58711
   640
      val int_visible_facts = map_filter (Symtab.lookup fact_tab) visible_facts
blanchet@58711
   641
      val int_conj_feats = map_filter (Symtab.lookup feat_tab) conj_feats
blanchet@58711
   642
    in
blanchet@58711
   643
      trace_msg ctxt (fn () => "MaSh_SML query " ^ encode_strs conj_feats ^ " from {" ^
blanchet@58711
   644
        elide_string 1000 (space_implode " " (take num_facts facts)) ^ "}");
blanchet@58714
   645
      (case engine of
blanchet@58714
   646
        MaSh_SML_kNN =>
blanchet@58714
   647
        let
blanchet@58714
   648
          val facts_ary = Array.array (num_feats, [])
blanchet@58714
   649
          val _ =
blanchet@58714
   650
            fold (fn feats => fn fact =>
blanchet@58714
   651
                (List.app (map_array_at facts_ary (cons fact)) feats; fact + 1))
blanchet@58714
   652
              featss 0
blanchet@58714
   653
          val get_facts = curry Array.sub facts_ary
blanchet@58714
   654
        in
blanchet@58714
   655
          k_nearest_neighbors num_facts get_deps get_facts max_suggs int_visible_facts num_feats
blanchet@58714
   656
            int_conj_feats
blanchet@58714
   657
        end
blanchet@58714
   658
      | MaSh_SML_NB =>
blanchet@58714
   659
        let
blanchet@58714
   660
          val feats_ary = Vector.fromList featss
blanchet@58714
   661
          val get_feats = curry Vector.sub feats_ary
blanchet@58714
   662
        in
blanchet@58714
   663
          naive_bayes num_facts get_deps get_feats num_feats max_suggs int_visible_facts
blanchet@58714
   664
            int_conj_feats
blanchet@58714
   665
        end)
blanchet@58711
   666
      |> map (curry Vector.sub fact_vec o fst)
blanchet@58711
   667
    end
blanchet@58349
   668
blanchet@58349
   669
end;
blanchet@58349
   670
blanchet@58349
   671
blanchet@51326
   672
(*** Middle-level communication with MaSh ***)
blanchet@51326
   673
blanchet@58347
   674
datatype proof_kind = Isar_Proof | Automatic_Proof | Isar_Proof_wegen_Prover_Flop
blanchet@51326
   675
blanchet@51326
   676
fun str_of_proof_kind Isar_Proof = "i"
blanchet@51499
   677
  | str_of_proof_kind Automatic_Proof = "a"
blanchet@51499
   678
  | str_of_proof_kind Isar_Proof_wegen_Prover_Flop = "x"
blanchet@51326
   679
blanchet@58347
   680
fun proof_kind_of_str "a" = Automatic_Proof
blanchet@51499
   681
  | proof_kind_of_str "x" = Isar_Proof_wegen_Prover_Flop
blanchet@58347
   682
  | proof_kind_of_str _ (* "i" *) = Isar_Proof
blanchet@51326
   683
blanchet@58353
   684
fun add_edge_to name parent =
blanchet@58353
   685
  Graph.default_node (parent, (Isar_Proof, [], []))
blanchet@58353
   686
  #> Graph.add_edge (parent, name)
blanchet@58353
   687
blanchet@58713
   688
fun add_node kind name parents feats deps (access_G, fact_xtab, feat_xtab) =
blanchet@58713
   689
  ((Graph.new_node (name, (kind, feats, deps)) access_G
blanchet@58713
   690
    handle Graph.DUP _ => Graph.map_node name (K (kind, feats, deps)) access_G)
blanchet@58713
   691
   |> fold (add_edge_to name) parents,
blanchet@58713
   692
  maybe_add_to_xtab name fact_xtab,
blanchet@58713
   693
  fold maybe_add_to_xtab feats feat_xtab)
blanchet@58353
   694
blanchet@51326
   695
fun try_graph ctxt when def f =
blanchet@51326
   696
  f ()
blanchet@58347
   697
  handle
blanchet@58347
   698
    Graph.CYCLES (cycle :: _) =>
blanchet@58347
   699
    (trace_msg ctxt (fn () => "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
blanchet@58347
   700
  | Graph.DUP name =>
blanchet@58347
   701
    (trace_msg ctxt (fn () => "Duplicate fact " ^ quote name ^ " when " ^ when); def)
blanchet@58347
   702
  | Graph.UNDEF name =>
blanchet@58347
   703
    (trace_msg ctxt (fn () => "Unknown fact " ^ quote name ^ " when " ^ when); def)
blanchet@58347
   704
  | exn =>
blanchet@58347
   705
    if Exn.is_interrupt exn then
blanchet@58347
   706
      reraise exn
blanchet@58347
   707
    else
blanchet@58347
   708
      (trace_msg ctxt (fn () => "Internal error when " ^ when ^ ":\n" ^ Runtime.exn_message exn);
blanchet@58347
   709
       def)
blanchet@51326
   710
blanchet@51326
   711
fun graph_info G =
blanchet@51326
   712
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
blanchet@58348
   713
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^ " edge(s), " ^
blanchet@51326
   714
  string_of_int (length (Graph.maximals G)) ^ " maximal"
blanchet@51326
   715
blanchet@54232
   716
type mash_state =
blanchet@58700
   717
  {access_G : (proof_kind * string list * string list) Graph.T,
blanchet@58713
   718
   fact_xtab : xtab,
blanchet@58713
   719
   feat_xtab : xtab,
blanchet@58713
   720
   num_known_facts : int, (* ### FIXME: kill *)
blanchet@58707
   721
   dirty_facts : string list option}
blanchet@51326
   722
blanchet@58713
   723
val empty_state =
blanchet@58713
   724
  {access_G = Graph.empty,
blanchet@58713
   725
   fact_xtab = empty_xtab,
blanchet@58713
   726
   feat_xtab = empty_xtab,
blanchet@58713
   727
   num_known_facts = 0,
blanchet@58713
   728
   dirty_facts = SOME []} : mash_state
blanchet@58713
   729
blanchet@58713
   730
val empty_graphxx = (Graph.empty, empty_xtab, empty_xtab)
blanchet@51326
   731
blanchet@51326
   732
local
blanchet@51326
   733
blanchet@58700
   734
val version = "*** MaSh version 20140625 ***"
blanchet@51372
   735
blanchet@54232
   736
exception FILE_VERSION_TOO_NEW of unit
blanchet@51326
   737
blanchet@51326
   738
fun extract_node line =
blanchet@56628
   739
  (case space_explode ":" line of
blanchet@58347
   740
    [head, tail] =>
blanchet@58347
   741
    (case (space_explode " " head, map (unprefix " ") (space_explode ";" tail)) of
blanchet@58347
   742
      ([kind, name], [parents, feats, deps]) =>
blanchet@58700
   743
      SOME (proof_kind_of_str kind, decode_str name, decode_strs parents, decode_strs feats,
blanchet@58352
   744
        decode_strs deps)
blanchet@56628
   745
    | _ => NONE)
blanchet@56628
   746
  | _ => NONE)
blanchet@51326
   747
blanchet@58418
   748
fun load_state ctxt overlord (time_state as (memory_time, _)) =
blanchet@58418
   749
  let val path = mash_state_file () in
blanchet@58418
   750
    (case try OS.FileSys.modTime (Path.implode (Path.expand path)) of
blanchet@58418
   751
      NONE => time_state
blanchet@58418
   752
    | SOME disk_time =>
blanchet@58418
   753
      if Time.>= (memory_time, disk_time) then
blanchet@58418
   754
        time_state
blanchet@58418
   755
      else
blanchet@58418
   756
        (disk_time,
blanchet@58418
   757
         (case try File.read_lines path of
blanchet@58418
   758
           SOME (version' :: node_lines) =>
blanchet@58418
   759
           let
blanchet@58418
   760
             fun extract_line_and_add_node line =
blanchet@58418
   761
               (case extract_node line of
blanchet@58418
   762
                 NONE => I (* should not happen *)
blanchet@58418
   763
               | SOME (kind, name, parents, feats, deps) => add_node kind name parents feats deps)
blanchet@58353
   764
blanchet@58713
   765
             val ((access_G, fact_xtab, feat_xtab), num_known_facts) =
blanchet@58418
   766
               (case string_ord (version', version) of
blanchet@58418
   767
                 EQUAL =>
blanchet@58713
   768
                 (try_graph ctxt "loading state" empty_graphxx (fn () =>
blanchet@58713
   769
                    fold extract_line_and_add_node node_lines empty_graphxx),
blanchet@58418
   770
                  length node_lines)
blanchet@58418
   771
               | LESS =>
blanchet@58418
   772
                 (* cannot parse old file *)
blanchet@58418
   773
                 (if the_mash_engine () = MaSh_Py then MaSh_Py.unlearn ctxt overlord
blanchet@58418
   774
                  else wipe_out_mash_state_dir ();
blanchet@58713
   775
                  (empty_graphxx, 0))
blanchet@58418
   776
               | GREATER => raise FILE_VERSION_TOO_NEW ())
blanchet@58418
   777
           in
blanchet@58418
   778
             trace_msg ctxt (fn () => "Loaded fact graph (" ^ graph_info access_G ^ ")");
blanchet@58713
   779
             {access_G = access_G, fact_xtab = fact_xtab, feat_xtab = feat_xtab,
blanchet@58713
   780
              num_known_facts = num_known_facts, dirty_facts = SOME []}
blanchet@58418
   781
           end
blanchet@58418
   782
         | _ => empty_state)))
blanchet@58418
   783
  end
blanchet@51326
   784
blanchet@58347
   785
fun str_of_entry (kind, name, parents, feats, deps) =
blanchet@58347
   786
  str_of_proof_kind kind ^ " " ^ encode_str name ^ ": " ^ encode_strs parents ^ "; " ^
blanchet@58700
   787
  encode_strs feats ^ "; " ^ encode_strs deps ^ "\n"
blanchet@58347
   788
blanchet@58707
   789
fun save_state _ (time_state as (_, {dirty_facts = SOME [], ...})) = time_state
blanchet@58713
   790
  | save_state ctxt (memory_time, {access_G, fact_xtab, feat_xtab, num_known_facts, dirty_facts}) =
blanchet@51326
   791
    let
blanchet@58347
   792
      fun append_entry (name, ((kind, feats, deps), (parents, _))) =
blanchet@58347
   793
        cons (kind, name, Graph.Keys.dest parents, feats, deps)
blanchet@58347
   794
blanchet@58418
   795
      val path = mash_state_file ()
blanchet@58707
   796
      val dirty_facts' =
blanchet@58418
   797
        (case try OS.FileSys.modTime (Path.implode path) of
blanchet@58418
   798
          NONE => NONE
blanchet@58707
   799
        | SOME disk_time => if Time.< (disk_time, memory_time) then dirty_facts else NONE)
blanchet@51326
   800
      val (banner, entries) =
blanchet@58707
   801
        (case dirty_facts' of
blanchet@56628
   802
          SOME names => (NONE, fold (append_entry o Graph.get_entry access_G) names [])
blanchet@56628
   803
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry access_G []))
blanchet@51326
   804
    in
blanchet@58418
   805
      write_file banner (entries, str_of_entry) path;
blanchet@51326
   806
      trace_msg ctxt (fn () =>
blanchet@58347
   807
        "Saved fact graph (" ^ graph_info access_G ^
blanchet@58707
   808
        (case dirty_facts of
blanchet@58707
   809
          SOME dirty_facts => "; " ^ string_of_int (length dirty_facts) ^ " dirty fact(s)"
blanchet@58347
   810
        | _ => "") ^  ")");
blanchet@58713
   811
      (Time.now (),
blanchet@58713
   812
       {access_G = access_G, fact_xtab = fact_xtab, feat_xtab = feat_xtab,
blanchet@58713
   813
        num_known_facts = num_known_facts, dirty_facts = SOME []})
blanchet@51326
   814
    end
blanchet@51326
   815
blanchet@58707
   816
val global_state = Synchronized.var "Sledgehammer_MaSh.global_state" (Time.zeroTime, empty_state)
blanchet@51326
   817
blanchet@51326
   818
in
blanchet@51326
   819
blanchet@54285
   820
fun map_state ctxt overlord f =
blanchet@58418
   821
  Synchronized.change global_state (load_state ctxt overlord ##> f #> save_state ctxt)
blanchet@54232
   822
  handle FILE_VERSION_TOO_NEW () => ()
blanchet@51326
   823
blanchet@54285
   824
fun peek_state ctxt overlord f =
blanchet@58347
   825
  Synchronized.change_result global_state (perhaps (try (load_state ctxt overlord)) #> `snd #>> f)
blanchet@51326
   826
blanchet@54285
   827
fun clear_state ctxt overlord =
blanchet@58359
   828
  (* "MaSh_Py.unlearn" also removes the state file *)
blanchet@58349
   829
  Synchronized.change global_state (fn _ =>
blanchet@58371
   830
    (if the_mash_engine () = MaSh_Py then MaSh_Py.unlearn ctxt overlord
blanchet@58371
   831
     else wipe_out_mash_state_dir ();
blanchet@58418
   832
     (Time.zeroTime, empty_state)))
blanchet@51326
   833
blanchet@51326
   834
end
blanchet@51326
   835
blanchet@54695
   836
fun mash_unlearn ctxt ({overlord, ...} : params) =
blanchet@54696
   837
  (clear_state ctxt overlord; Output.urgent_message "Reset MaSh.")
blanchet@51585
   838
blanchet@51326
   839
blanchet@51326
   840
(*** Isabelle helpers ***)
blanchet@51326
   841
blanchet@51737
   842
val local_prefix = "local" ^ Long_Name.separator
blanchet@49393
   843
blanchet@51737
   844
fun elided_backquote_thm threshold th =
blanchet@58348
   845
  elide_string threshold (backquote_thm (Proof_Context.init_global (Thm.theory_of_thm th)) th)
blanchet@49393
   846
blanchet@52318
   847
val thy_name_of_thm = Context.theory_name o Thm.theory_of_thm
blanchet@52318
   848
blanchet@51639
   849
fun nickname_of_thm th =
blanchet@49409
   850
  if Thm.has_name_hint th then
blanchet@49409
   851
    let val hint = Thm.get_name_hint th in
blanchet@51737
   852
      (* There must be a better way to detect local facts. *)
blanchet@56628
   853
      (case try (unprefix local_prefix) hint of
blanchet@49409
   854
        SOME suf =>
blanchet@56628
   855
        thy_name_of_thm th ^ Long_Name.separator ^ suf ^ Long_Name.separator ^
blanchet@56628
   856
        elided_backquote_thm 50 th
blanchet@56628
   857
      | NONE => hint)
blanchet@49409
   858
    end
blanchet@49409
   859
  else
blanchet@51737
   860
    elided_backquote_thm 200 th
blanchet@49393
   861
blanchet@52271
   862
fun find_suggested_facts ctxt facts =
blanchet@49345
   863
  let
blanchet@52271
   864
    fun add (fact as (_, th)) = Symtab.default (nickname_of_thm th, fact)
blanchet@52271
   865
    val tab = fold add facts Symtab.empty
blanchet@52271
   866
    fun lookup nick =
blanchet@52271
   867
      Symtab.lookup tab nick
blanchet@58348
   868
      |> tap (fn NONE => trace_msg ctxt (fn () => "Cannot find " ^ quote nick) | _ => ())
blanchet@52271
   869
  in map_filter lookup end
blanchet@49326
   870
blanchet@51398
   871
fun scaled_avg [] = 0
blanchet@58348
   872
  | scaled_avg xs = Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs
blanchet@49343
   873
blanchet@51398
   874
fun avg [] = 0.0
blanchet@51398
   875
  | avg xs = fold (curry (op +)) xs 0.0 / Real.fromInt (length xs)
blanchet@49328
   876
blanchet@51398
   877
fun normalize_scores _ [] = []
blanchet@51398
   878
  | normalize_scores max_facts xs =
blanchet@58348
   879
    map (apsnd (curry Real.* (1.0 / avg (map snd (take max_facts xs))))) xs
blanchet@51398
   880
blanchet@58438
   881
fun mesh_facts fact_eq max_facts [(_, (sels, unks))] =
blanchet@58438
   882
    distinct fact_eq (map fst (take max_facts sels) @ take (max_facts - length sels) unks)
blanchet@51876
   883
  | mesh_facts fact_eq max_facts mess =
blanchet@49329
   884
    let
blanchet@52211
   885
      val mess = mess |> map (apsnd (apfst (normalize_scores max_facts)))
blanchet@58348
   886
blanchet@52211
   887
      fun score_in fact (global_weight, (sels, unks)) =
blanchet@58348
   888
        let val score_at = try (nth sels) #> Option.map (fn (_, score) => global_weight * score) in
blanchet@56628
   889
          (case find_index (curry fact_eq fact o fst) sels of
blanchet@55541
   890
            ~1 => if member fact_eq unks fact then NONE else SOME 0.0
blanchet@56628
   891
          | rank => score_at rank)
blanchet@51398
   892
        end
blanchet@58348
   893
blanchet@51398
   894
      fun weight_of fact = mess |> map_filter (score_in fact) |> scaled_avg
blanchet@49329
   895
    in
blanchet@58348
   896
      fold (union fact_eq o map fst o take max_facts o fst o snd) mess []
blanchet@58348
   897
      |> map (`weight_of) |> sort (int_ord o swap o pairself fst)
blanchet@58348
   898
      |> map snd |> take max_facts
blanchet@49329
   899
    end
blanchet@49327
   900
blanchet@56035
   901
val default_weight = 1.0
blanchet@58397
   902
fun free_feature_of s = ("f" ^ s, 40.0 (* FUDGE *))
blanchet@58397
   903
fun thy_feature_of s = ("y" ^ s, 8.0 (* FUDGE *))
blanchet@58397
   904
fun type_feature_of s = ("t" ^ s, 4.0 (* FUDGE *))
blanchet@58397
   905
fun class_feature_of s = ("s" ^ s, 1.0 (* FUDGE *))
blanchet@58397
   906
val local_feature = ("local", 16.0 (* FUDGE *))
blanchet@49266
   907
blanchet@52272
   908
fun crude_theory_ord p =
blanchet@51737
   909
  if Theory.subthy p then
blanchet@51737
   910
    if Theory.eq_thy p then EQUAL else LESS
blanchet@49339
   911
  else if Theory.subthy (swap p) then
blanchet@49339
   912
    GREATER
blanchet@56628
   913
  else
blanchet@56628
   914
    (case int_ord (pairself (length o Theory.ancestors_of) p) of
blanchet@56628
   915
      EQUAL => string_ord (pairself Context.theory_name p)
blanchet@56628
   916
    | order => order)
blanchet@49339
   917
blanchet@52272
   918
fun crude_thm_ord p =
blanchet@56628
   919
  (case crude_theory_ord (pairself theory_of_thm p) of
blanchet@51374
   920
    EQUAL =>
blanchet@58381
   921
    (* The hack below is necessary because of odd dependencies that are not reflected in the theory
blanchet@58381
   922
       comparison. *)
blanchet@51639
   923
    let val q = pairself nickname_of_thm p in
blanchet@51639
   924
      (* Hack to put "xxx_def" before "xxxI" and "xxxE" *)
blanchet@56628
   925
      (case bool_ord (pairself (String.isSuffix "_def") (swap q)) of
blanchet@51639
   926
        EQUAL => string_ord q
blanchet@56628
   927
      | ord => ord)
blanchet@51639
   928
    end
blanchet@56628
   929
  | ord => ord)
blanchet@49339
   930
blanchet@52273
   931
val thm_less_eq = Theory.subthy o pairself theory_of_thm
blanchet@52273
   932
fun thm_less p = thm_less_eq p andalso not (thm_less_eq (swap p))
blanchet@52273
   933
blanchet@49407
   934
val freezeT = Type.legacy_freeze_type
blanchet@49407
   935
blanchet@49407
   936
fun freeze (t $ u) = freeze t $ freeze u
blanchet@49407
   937
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
blanchet@49407
   938
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
blanchet@49407
   939
  | freeze (Const (s, T)) = Const (s, freezeT T)
blanchet@49407
   940
  | freeze (Free (s, T)) = Free (s, freezeT T)
blanchet@49407
   941
  | freeze t = t
blanchet@49407
   942
blanchet@49407
   943
fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init
blanchet@49407
   944
blanchet@55593
   945
fun run_prover_for_mash ctxt params prover goal_name facts goal =
blanchet@49407
   946
  let
blanchet@49407
   947
    val problem =
blanchet@55593
   948
      {comment = "Goal: " ^ goal_name, state = Proof.init ctxt, goal = goal, subgoal = 1,
blanchet@55593
   949
       subgoal_count = 1, factss = [("", facts)]}
blanchet@49407
   950
  in
blanchet@55876
   951
    get_minimizing_prover ctxt MaSh (K ()) prover params (K (K (K ""))) problem
blanchet@49407
   952
  end
blanchet@49407
   953
blanchet@49341
   954
val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]
blanchet@49341
   955
blanchet@54223
   956
val pat_tvar_prefix = "_"
blanchet@54223
   957
val pat_var_prefix = "_"
blanchet@54220
   958
blanchet@54226
   959
(* try "Long_Name.base_name" for shorter names *)
blanchet@58397
   960
fun massage_long_name s = s
blanchet@54223
   961
blanchet@58348
   962
val crude_str_of_sort = space_implode ":" o map massage_long_name o subtract (op =) @{sort type}
blanchet@54223
   963
blanchet@54223
   964
fun crude_str_of_typ (Type (s, [])) = massage_long_name s
blanchet@58348
   965
  | crude_str_of_typ (Type (s, Ts)) = massage_long_name s ^ implode (map crude_str_of_typ Ts)
blanchet@54220
   966
  | crude_str_of_typ (TFree (_, S)) = crude_str_of_sort S
blanchet@54220
   967
  | crude_str_of_typ (TVar (_, S)) = crude_str_of_sort S
blanchet@54220
   968
blanchet@54265
   969
fun maybe_singleton_str _ "" = []
blanchet@54265
   970
  | maybe_singleton_str pref s = [pref ^ s]
blanchet@54265
   971
blanchet@54285
   972
val max_pat_breadth = 10 (* FUDGE *)
blanchet@51600
   973
blanchet@58397
   974
fun term_features_of ctxt thy_name num_facts const_tab term_max_depth type_max_depth ts =
blanchet@49266
   975
  let
blanchet@51407
   976
    val thy = Proof_Context.theory_of ctxt
blanchet@54219
   977
blanchet@51408
   978
    val fixes = map snd (Variable.dest_fixes ctxt)
blanchet@51407
   979
    val classes = Sign.classes_of thy
blanchet@54219
   980
blanchet@49319
   981
    fun add_classes @{sort type} = I
blanchet@51407
   982
      | add_classes S =
blanchet@51407
   983
        fold (`(Sorts.super_classes classes)
blanchet@58348
   984
          #> swap #> op ::
blanchet@58348
   985
          #> subtract (op =) @{sort type} #> map massage_long_name
blanchet@58348
   986
          #> map class_feature_of
blanchet@58348
   987
          #> union (eq_fst (op =))) S
blanchet@54219
   988
blanchet@54219
   989
    fun pattify_type 0 _ = []
blanchet@54219
   990
      | pattify_type _ (Type (s, [])) =
blanchet@54223
   991
        if member (op =) bad_types s then [] else [massage_long_name s]
blanchet@54219
   992
      | pattify_type depth (Type (s, U :: Ts)) =
blanchet@54219
   993
        let
blanchet@54219
   994
          val T = Type (s, Ts)
blanchet@58397
   995
          val ps = take max_pat_breadth (pattify_type depth T)
blanchet@58397
   996
          val qs = take max_pat_breadth ("" :: pattify_type (depth - 1) U)
blanchet@58348
   997
        in
blanchet@58348
   998
          map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs
blanchet@58348
   999
        end
blanchet@54265
  1000
      | pattify_type _ (TFree (_, S)) =
blanchet@54265
  1001
        maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@54265
  1002
      | pattify_type _ (TVar (_, S)) =
blanchet@54265
  1003
        maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@58348
  1004
blanchet@54219
  1005
    fun add_type_pat depth T =
blanchet@54296
  1006
      union (eq_fst (op =)) (map type_feature_of (pattify_type depth T))
blanchet@58348
  1007
blanchet@54219
  1008
    fun add_type_pats 0 _ = I
blanchet@54219
  1009
      | add_type_pats depth t =
blanchet@54219
  1010
        add_type_pat depth t #> add_type_pats (depth - 1) t
blanchet@58348
  1011
blanchet@54220
  1012
    fun add_type T =
blanchet@54220
  1013
      add_type_pats type_max_depth T
blanchet@54293
  1014
      #> fold_atyps_sorts (add_classes o snd) T
blanchet@58348
  1015
blanchet@54221
  1016
    fun add_subtypes (T as Type (_, Ts)) = add_type T #> fold add_subtypes Ts
blanchet@54221
  1017
      | add_subtypes T = add_type T
blanchet@54219
  1018
blanchet@58441
  1019
    val base_weight_of_const = 16.0 (* FUDGE *)
blanchet@58441
  1020
    val weight_of_const =
blanchet@58441
  1021
      (if num_facts = 0 orelse Symtab.is_empty const_tab then
blanchet@58441
  1022
         K base_weight_of_const
blanchet@54267
  1023
       else
blanchet@58441
  1024
         fn s =>
blanchet@54267
  1025
         let val count = Symtab.lookup const_tab s |> the_default 1 in
blanchet@58441
  1026
           base_weight_of_const + Real.fromInt num_facts / Real.fromInt count
blanchet@54267
  1027
         end)
blanchet@58348
  1028
blanchet@58397
  1029
    fun pattify_term _ 0 _ = []
blanchet@58397
  1030
      | pattify_term _ _ (Const (s, _)) =
blanchet@58397
  1031
        if is_widely_irrelevant_const s then [] else [(massage_long_name s, weight_of_const s)]
blanchet@55541
  1032
      | pattify_term _ _ (Free (s, T)) =
blanchet@54265
  1033
        maybe_singleton_str pat_var_prefix (crude_str_of_typ T)
blanchet@58397
  1034
        |> map (rpair 1.0)
blanchet@54227
  1035
        |> (if member (op =) fixes s then
blanchet@58397
  1036
              cons (free_feature_of (massage_long_name
blanchet@58397
  1037
                  (thy_name ^ Long_Name.separator ^ s)))
blanchet@54227
  1038
            else
blanchet@54227
  1039
              I)
blanchet@55541
  1040
      | pattify_term _ _ (Var (_, T)) =
blanchet@58397
  1041
        maybe_singleton_str pat_var_prefix (crude_str_of_typ T) |> map (rpair default_weight)
blanchet@55541
  1042
      | pattify_term Ts _ (Bound j) =
blanchet@56037
  1043
        maybe_singleton_str pat_var_prefix (crude_str_of_typ (nth Ts j))
blanchet@58397
  1044
        |> map (rpair default_weight)
blanchet@55541
  1045
      | pattify_term Ts depth (t $ u) =
blanchet@51354
  1046
        let
blanchet@58397
  1047
          val ps = take max_pat_breadth (pattify_term Ts depth t)
blanchet@58397
  1048
          val qs = take max_pat_breadth (("", default_weight) :: pattify_term Ts (depth - 1) u)
blanchet@54267
  1049
        in
blanchet@58397
  1050
          map_product (fn ppw as (p, pw) =>
blanchet@58397
  1051
            fn ("", _) => ppw
blanchet@58397
  1052
             | (q, qw) => (p ^ "(" ^ q ^ ")", pw + qw)) ps qs
blanchet@54267
  1053
        end
blanchet@55541
  1054
      | pattify_term _ _ _ = []
blanchet@58348
  1055
blanchet@55541
  1056
    fun add_term_pat Ts = union (eq_fst (op =)) oo pattify_term Ts
blanchet@58348
  1057
blanchet@54267
  1058
    fun add_term_pats _ 0 _ = I
blanchet@58397
  1059
      | add_term_pats Ts depth t = add_term_pat Ts depth t #> add_term_pats Ts (depth - 1) t
blanchet@58348
  1060
blanchet@54267
  1061
    fun add_term Ts = add_term_pats Ts term_max_depth
blanchet@58348
  1062
blanchet@54222
  1063
    fun add_subterms Ts t =
blanchet@56628
  1064
      (case strip_comb t of
blanchet@55541
  1065
        (Const (s, T), args) =>
blanchet@55541
  1066
        (not (is_widely_irrelevant_const s) ? add_term Ts t)
blanchet@55541
  1067
        #> add_subtypes T
blanchet@55541
  1068
        #> fold (add_subterms Ts) args
blanchet@51872
  1069
      | (head, args) =>
blanchet@49266
  1070
        (case head of
blanchet@54267
  1071
           Free (_, T) => add_term Ts t #> add_subtypes T
blanchet@54221
  1072
         | Var (_, T) => add_subtypes T
blanchet@54222
  1073
         | Abs (_, T, body) => add_subtypes T #> add_subterms (T :: Ts) body
blanchet@49266
  1074
         | _ => I)
blanchet@56628
  1075
        #> fold (add_subterms Ts) args)
blanchet@58348
  1076
  in
blanchet@58348
  1077
    fold (add_subterms []) ts []
blanchet@58348
  1078
  end
blanchet@49266
  1079
blanchet@54222
  1080
val term_max_depth = 2
blanchet@54292
  1081
val type_max_depth = 1
blanchet@49266
  1082
blanchet@49266
  1083
(* TODO: Generate type classes for types? *)
blanchet@58397
  1084
fun features_of ctxt thy num_facts const_tab (scope, _) ts =
blanchet@51408
  1085
  let val thy_name = Context.theory_name thy in
blanchet@51408
  1086
    thy_feature_of thy_name ::
blanchet@58397
  1087
    term_features_of ctxt thy_name num_facts const_tab term_max_depth type_max_depth ts
blanchet@51408
  1088
    |> scope <> Global ? cons local_feature
blanchet@51408
  1089
  end
blanchet@49266
  1090
blanchet@58348
  1091
(* Too many dependencies is a sign that a decision procedure is at work. There is not much to learn
blanchet@58348
  1092
   from such proofs. *)
blanchet@51449
  1093
val max_dependencies = 20
blanchet@51499
  1094
blanchet@55577
  1095
val prover_default_max_facts = 25
blanchet@49266
  1096
blanchet@49453
  1097
(* "type_definition_xxx" facts are characterized by their use of "CollectI". *)
blanchet@51770
  1098
val typedef_dep = nickname_of_thm @{thm CollectI}
blanchet@58348
  1099
(* Mysterious parts of the class machinery create lots of proofs that refer exclusively to
blanchet@58348
  1100
   "someI_ex" (and to some internal constructions). *)
blanchet@51770
  1101
val class_some_dep = nickname_of_thm @{thm someI_ex}
blanchet@49453
  1102
blanchet@51843
  1103
val fundef_ths =
blanchet@58348
  1104
  @{thms fundef_ex1_existence fundef_ex1_uniqueness fundef_ex1_iff fundef_default_value}
blanchet@51843
  1105
  |> map nickname_of_thm
blanchet@51843
  1106
blanchet@49453
  1107
(* "Rep_xxx_inject", "Abs_xxx_inverse", etc., are derived using these facts. *)
blanchet@49453
  1108
val typedef_ths =
blanchet@58348
  1109
  @{thms type_definition.Abs_inverse type_definition.Rep_inverse type_definition.Rep
blanchet@58348
  1110
      type_definition.Rep_inject type_definition.Abs_inject type_definition.Rep_cases
blanchet@58348
  1111
      type_definition.Abs_cases type_definition.Rep_induct type_definition.Abs_induct
blanchet@58348
  1112
      type_definition.Rep_range type_definition.Abs_image}
blanchet@51639
  1113
  |> map nickname_of_thm
blanchet@49453
  1114
blanchet@49456
  1115
fun is_size_def [dep] th =
blanchet@56984
  1116
    (case first_field ".rec" dep of
blanchet@58348
  1117
      SOME (pref, _) =>
blanchet@58348
  1118
      (case first_field ".size" (nickname_of_thm th) of
blanchet@58348
  1119
        SOME (pref', _) => pref = pref'
blanchet@58348
  1120
      | NONE => false)
blanchet@58348
  1121
    | NONE => false)
blanchet@49456
  1122
  | is_size_def _ _ = false
blanchet@49456
  1123
blanchet@52314
  1124
fun trim_dependencies deps =
blanchet@51770
  1125
  if length deps > max_dependencies then NONE else SOME deps
blanchet@49266
  1126
blanchet@51770
  1127
fun isar_dependencies_of name_tabs th =
blanchet@58648
  1128
  thms_in_proof max_dependencies (SOME name_tabs) th
blanchet@58648
  1129
  |> Option.map (fn deps =>
blanchet@58348
  1130
    if deps = [typedef_dep] orelse deps = [class_some_dep] orelse
blanchet@58348
  1131
       exists (member (op =) fundef_ths) deps orelse exists (member (op =) typedef_ths) deps orelse
blanchet@51843
  1132
       is_size_def deps th then
blanchet@51770
  1133
      []
blanchet@51770
  1134
    else
blanchet@58648
  1135
      deps)
blanchet@49419
  1136
blanchet@58348
  1137
fun prover_dependencies_of ctxt (params as {verbose, max_facts, ...}) prover auto_level facts
blanchet@58348
  1138
    name_tabs th =
blanchet@56628
  1139
  (case isar_dependencies_of name_tabs th of
blanchet@58648
  1140
    SOME [] => (false, [])
blanchet@58648
  1141
  | isar_deps0 =>
blanchet@49407
  1142
    let
blanchet@58648
  1143
      val isar_deps = these isar_deps0
blanchet@49407
  1144
      val thy = Proof_Context.theory_of ctxt
blanchet@49407
  1145
      val goal = goal_of_thm thy th
blanchet@55593
  1146
      val name = nickname_of_thm th
blanchet@53333
  1147
      val (_, hyp_ts, concl_t) = ATP_Util.strip_subgoal goal 1 ctxt
blanchet@52273
  1148
      val facts = facts |> filter (fn (_, th') => thm_less (th', th))
blanchet@58348
  1149
blanchet@52186
  1150
      fun nickify ((_, stature), th) = ((nickname_of_thm th, stature), th)
blanchet@58348
  1151
blanchet@51639
  1152
      fun is_dep dep (_, th) = nickname_of_thm th = dep
blanchet@58348
  1153
blanchet@49407
  1154
      fun add_isar_dep facts dep accum =
blanchet@49407
  1155
        if exists (is_dep dep) accum then
blanchet@49407
  1156
          accum
blanchet@56628
  1157
        else
blanchet@56628
  1158
          (case find_first (is_dep dep) facts of
blanchet@56628
  1159
            SOME ((_, status), th) => accum @ [(("", status), th)]
blanchet@58347
  1160
          | NONE => accum (* should not happen *))
blanchet@58348
  1161
blanchet@55575
  1162
      val mepo_facts =
blanchet@51499
  1163
        facts
blanchet@55547
  1164
        |> mepo_suggested_facts ctxt params (max_facts |> the_default prover_default_max_facts) NONE
blanchet@55547
  1165
             hyp_ts concl_t
blanchet@55575
  1166
      val facts =
blanchet@55575
  1167
        mepo_facts
blanchet@51769
  1168
        |> fold (add_isar_dep facts) isar_deps
blanchet@51639
  1169
        |> map nickify
blanchet@55575
  1170
      val num_isar_deps = length isar_deps
blanchet@49407
  1171
    in
blanchet@49419
  1172
      if verbose andalso auto_level = 0 then
blanchet@58359
  1173
        Output.urgent_message ("MaSh: " ^ quote prover ^ " on " ^ quote name ^ " with " ^
blanchet@58359
  1174
          string_of_int num_isar_deps ^ " + " ^ string_of_int (length facts - num_isar_deps) ^
blanchet@58359
  1175
          " facts.")
blanchet@49407
  1176
      else
blanchet@49407
  1177
        ();
blanchet@56628
  1178
      (case run_prover_for_mash ctxt params prover name facts goal of
blanchet@49407
  1179
        {outcome = NONE, used_facts, ...} =>
blanchet@49419
  1180
        (if verbose andalso auto_level = 0 then
blanchet@49407
  1181
           let val num_facts = length used_facts in
blanchet@58359
  1182
             Output.urgent_message ("Found proof with " ^ string_of_int num_facts ^ " fact" ^
blanchet@58359
  1183
               plural_s num_facts ^ ".")
blanchet@49407
  1184
           end
blanchet@49407
  1185
         else
blanchet@49407
  1186
           ();
blanchet@51769
  1187
         (true, map fst used_facts))
blanchet@56628
  1188
      | _ => (false, isar_deps))
blanchet@56628
  1189
    end)
blanchet@49266
  1190
blanchet@49266
  1191
blanchet@49266
  1192
(*** High-level communication with MaSh ***)
blanchet@49266
  1193
blanchet@52319
  1194
(* In the following functions, chunks are risers w.r.t. "thm_less_eq". *)
blanchet@52319
  1195
blanchet@52318
  1196
fun chunks_and_parents_for chunks th =
blanchet@52318
  1197
  let
blanchet@52318
  1198
    fun insert_parent new parents =
blanchet@52318
  1199
      let val parents = parents |> filter_out (fn p => thm_less_eq (p, new)) in
blanchet@58438
  1200
        parents |> forall (fn p => not (thm_less_eq (new, p))) parents ? cons new
blanchet@52318
  1201
      end
blanchet@58348
  1202
blanchet@52318
  1203
    fun rechunk seen (rest as th' :: ths) =
blanchet@52318
  1204
      if thm_less_eq (th', th) then (rev seen, rest)
blanchet@52318
  1205
      else rechunk (th' :: seen) ths
blanchet@58348
  1206
blanchet@52318
  1207
    fun do_chunk [] accum = accum
blanchet@52318
  1208
      | do_chunk (chunk as hd_chunk :: _) (chunks, parents) =
blanchet@52318
  1209
        if thm_less_eq (hd_chunk, th) then
blanchet@52318
  1210
          (chunk :: chunks, insert_parent hd_chunk parents)
blanchet@52318
  1211
        else if thm_less_eq (List.last chunk, th) then
blanchet@52318
  1212
          let val (front, back as hd_back :: _) = rechunk [] chunk in
blanchet@52318
  1213
            (front :: back :: chunks, insert_parent hd_back parents)
blanchet@52318
  1214
          end
blanchet@52318
  1215
        else
blanchet@52318
  1216
          (chunk :: chunks, parents)
blanchet@52318
  1217
  in
blanchet@52318
  1218
    fold_rev do_chunk chunks ([], [])
blanchet@52318
  1219
    |>> cons []
blanchet@52319
  1220
    ||> map nickname_of_thm
blanchet@52318
  1221
  end
blanchet@52318
  1222
blanchet@52319
  1223
fun attach_parents_to_facts _ [] = []
blanchet@52319
  1224
  | attach_parents_to_facts old_facts (facts as (_, th) :: _) =
blanchet@52319
  1225
    let
blanchet@52319
  1226
      fun do_facts _ [] = []
blanchet@52319
  1227
        | do_facts (_, parents) [fact] = [(parents, fact)]
blanchet@52319
  1228
        | do_facts (chunks, parents)
blanchet@52319
  1229
                   ((fact as (_, th)) :: (facts as (_, th') :: _)) =
blanchet@52319
  1230
          let
blanchet@52319
  1231
            val chunks = app_hd (cons th) chunks
blanchet@52319
  1232
            val chunks_and_parents' =
blanchet@58712
  1233
              if thm_less_eq (th, th') andalso thy_name_of_thm th = thy_name_of_thm th' then
blanchet@52319
  1234
                (chunks, [nickname_of_thm th])
blanchet@52319
  1235
              else
blanchet@52319
  1236
                chunks_and_parents_for chunks th'
blanchet@58348
  1237
          in
blanchet@58348
  1238
            (parents, fact) :: do_facts chunks_and_parents' facts
blanchet@58348
  1239
          end
blanchet@52319
  1240
    in
blanchet@52319
  1241
      old_facts @ facts
blanchet@52319
  1242
      |> do_facts (chunks_and_parents_for [[]] th)
blanchet@52319
  1243
      |> drop (length old_facts)
blanchet@52319
  1244
    end
blanchet@52314
  1245
blanchet@54232
  1246
fun maximal_wrt_graph G keys =
blanchet@54232
  1247
  let
blanchet@54232
  1248
    val tab = Symtab.empty |> fold (fn name => Symtab.default (name, ())) keys
blanchet@58348
  1249
blanchet@58354
  1250
    fun insert_new seen name = not (Symtab.defined seen name) ? insert (op =) name
blanchet@58348
  1251
blanchet@54232
  1252
    fun num_keys keys = Graph.Keys.fold (K (Integer.add 1)) keys 0
blanchet@58348
  1253
blanchet@54232
  1254
    fun find_maxes _ (maxs, []) = map snd maxs
blanchet@54232
  1255
      | find_maxes seen (maxs, new :: news) =
blanchet@58354
  1256
        find_maxes (seen |> num_keys (Graph.imm_succs G new) > 1 ? Symtab.default (new, ()))
blanchet@58354
  1257
          (if Symtab.defined tab new then
blanchet@58354
  1258
             let
blanchet@58354
  1259
               val newp = Graph.all_preds G [new]
blanchet@58354
  1260
               fun is_ancestor x yp = member (op =) yp x
blanchet@58354
  1261
               val maxs = maxs |> filter (fn (_, max) => not (is_ancestor max newp))
blanchet@58354
  1262
             in
blanchet@58354
  1263
               if exists (is_ancestor new o fst) maxs then (maxs, news)
blanchet@58354
  1264
               else ((newp, new) :: filter_out (fn (_, max) => is_ancestor max newp) maxs, news)
blanchet@58354
  1265
             end
blanchet@58354
  1266
           else
blanchet@58354
  1267
             (maxs, Graph.Keys.fold (insert_new seen) (Graph.imm_preds G new) news))
blanchet@58348
  1268
  in
blanchet@58348
  1269
    find_maxes Symtab.empty ([], Graph.maximals G)
blanchet@58348
  1270
  end
blanchet@54232
  1271
blanchet@58354
  1272
fun maximal_wrt_access_graph access_G facts =
blanchet@58355
  1273
  map (nickname_of_thm o snd) facts
blanchet@58354
  1274
  |> maximal_wrt_graph access_G
blanchet@54232
  1275
blanchet@54232
  1276
fun is_fact_in_graph access_G = can (Graph.get_node access_G) o nickname_of_thm
blanchet@54232
  1277
blanchet@54334
  1278
val chained_feature_factor = 0.5 (* FUDGE *)
blanchet@54334
  1279
val extra_feature_factor = 0.1 (* FUDGE *)
blanchet@58712
  1280
val num_extra_feature_facts = 0 (* FUDGE *) (* TODO: keep or eliminate? *)
blanchet@54232
  1281
blanchet@54232
  1282
(* FUDGE *)
blanchet@54232
  1283
fun weight_of_proximity_fact rank =
blanchet@54232
  1284
  Math.pow (1.3, 15.5 - 0.2 * Real.fromInt rank) + 15.0
blanchet@54232
  1285
blanchet@54277
  1286
fun weight_facts_smoothly facts =
blanchet@54232
  1287
  facts ~~ map weight_of_proximity_fact (0 upto length facts - 1)
blanchet@54232
  1288
blanchet@54277
  1289
(* FUDGE *)
blanchet@54277
  1290
fun steep_weight_of_fact rank =
blanchet@54277
  1291
  Math.pow (0.62, log2 (Real.fromInt (rank + 1)))
blanchet@54277
  1292
blanchet@54277
  1293
fun weight_facts_steeply facts =
blanchet@54277
  1294
  facts ~~ map steep_weight_of_fact (0 upto length facts - 1)
blanchet@54277
  1295
blanchet@54232
  1296
val max_proximity_facts = 100
blanchet@54232
  1297
blanchet@55512
  1298
fun find_mash_suggestions ctxt max_facts suggs facts chained raw_unknown =
blanchet@55512
  1299
  let
blanchet@55512
  1300
    val inter_fact = inter (eq_snd Thm.eq_thm_prop)
blanchet@55512
  1301
    val raw_mash = find_suggested_facts ctxt facts suggs
blanchet@55512
  1302
    val proximate = take max_proximity_facts facts
blanchet@55512
  1303
    val unknown_chained = inter_fact raw_unknown chained
blanchet@55512
  1304
    val unknown_proximate = inter_fact raw_unknown proximate
blanchet@55512
  1305
    val mess =
blanchet@55512
  1306
      [(0.9 (* FUDGE *), (map (rpair 1.0) unknown_chained, [])),
blanchet@55512
  1307
       (0.4 (* FUDGE *), (weight_facts_smoothly unknown_proximate, [])),
blanchet@55512
  1308
       (0.1 (* FUDGE *), (weight_facts_steeply raw_mash, raw_unknown))]
blanchet@58349
  1309
    val unknown = raw_unknown
blanchet@58349
  1310
      |> fold (subtract (eq_snd Thm.eq_thm_prop)) [unknown_chained, unknown_proximate]
blanchet@58348
  1311
  in
blanchet@58492
  1312
    (mesh_facts (eq_snd (gen_eq_thm ctxt)) max_facts mess, unknown)
blanchet@58348
  1313
  end
blanchet@54232
  1314
blanchet@54264
  1315
fun add_const_counts t =
blanchet@58348
  1316
  fold (fn s => Symtab.map_default (s, 0) (Integer.add 1)) (Term.add_const_names t [])
blanchet@54232
  1317
blanchet@55876
  1318
fun mash_suggested_facts ctxt ({debug, overlord, ...} : params) max_facts hyp_ts concl_t facts =
blanchet@54232
  1319
  let
blanchet@54232
  1320
    val thy = Proof_Context.theory_of ctxt
blanchet@54696
  1321
    val thy_name = Context.theory_name thy
blanchet@58394
  1322
    val engine = the_mash_engine ()
blanchet@58394
  1323
blanchet@54278
  1324
    val facts = facts |> sort (crude_thm_ord o pairself snd o swap)
blanchet@54232
  1325
    val chained = facts |> filter (fn ((_, (scope, _)), _) => scope = Chained)
blanchet@54278
  1326
    val num_facts = length facts
blanchet@58402
  1327
blanchet@58438
  1328
    (* Weights appear to hurt kNN more than they help. *)
blanchet@58446
  1329
    val const_tab = Symtab.empty |> engine <> MaSh_SML_kNN
blanchet@58446
  1330
      ? fold (add_const_counts o prop_of o snd) facts
blanchet@55537
  1331
blanchet@54696
  1332
    fun fact_has_right_theory (_, th) =
blanchet@54696
  1333
      thy_name = Context.theory_name (theory_of_thm th)
blanchet@58337
  1334
blanchet@54278
  1335
    fun chained_or_extra_features_of factor (((_, stature), th), weight) =
blanchet@54278
  1336
      [prop_of th]
blanchet@58397
  1337
      |> features_of ctxt (theory_of_thm th) num_facts const_tab stature
blanchet@54278
  1338
      |> map (apsnd (fn r => weight * factor * r))
blanchet@55537
  1339
blanchet@58359
  1340
    fun query_args access_G =
blanchet@58359
  1341
      let
blanchet@58359
  1342
        val parents = maximal_wrt_access_graph access_G facts
blanchet@58359
  1343
        val hints = chained
blanchet@58359
  1344
          |> filter (is_fact_in_graph access_G o snd)
blanchet@58359
  1345
          |> map (nickname_of_thm o snd)
blanchet@58359
  1346
blanchet@58359
  1347
        val goal_feats =
blanchet@58397
  1348
          features_of ctxt thy num_facts const_tab (Local, General) (concl_t :: hyp_ts)
blanchet@58359
  1349
        val chained_feats = chained
blanchet@58359
  1350
          |> map (rpair 1.0)
blanchet@58359
  1351
          |> map (chained_or_extra_features_of chained_feature_factor)
blanchet@58359
  1352
          |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@58394
  1353
        val extra_feats =
blanchet@58437
  1354
          facts
blanchet@58437
  1355
          |> take (Int.max (0, num_extra_feature_facts - length chained))
blanchet@58437
  1356
          |> filter fact_has_right_theory
blanchet@58437
  1357
          |> weight_facts_steeply
blanchet@58437
  1358
          |> map (chained_or_extra_features_of extra_feature_factor)
blanchet@58437
  1359
          |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@58359
  1360
        val feats = fold (union (eq_fst (op =))) [chained_feats, extra_feats] goal_feats
blanchet@58359
  1361
          |> debug ? sort (Real.compare o swap o pairself snd)
blanchet@58359
  1362
      in
blanchet@58359
  1363
        (parents, hints, feats)
blanchet@58359
  1364
      end
blanchet@58359
  1365
blanchet@58713
  1366
    val ((access_G, fact_xtab, feat_xtab), py_suggs) =
blanchet@58713
  1367
      peek_state ctxt overlord (fn {access_G, fact_xtab, feat_xtab, ...} =>
blanchet@58713
  1368
        ((access_G, fact_xtab, feat_xtab),
blanchet@58713
  1369
         if Graph.is_empty access_G then
blanchet@58713
  1370
           (trace_msg ctxt (K "Nothing has been learned yet"); [])
blanchet@58713
  1371
         else if engine = MaSh_Py then
blanchet@58713
  1372
           let val (parents, hints, feats) = query_args access_G in
blanchet@58713
  1373
             MaSh_Py.query ctxt overlord max_facts ([], hints, parents, feats)
blanchet@58713
  1374
             |> map fst
blanchet@58713
  1375
           end
blanchet@58713
  1376
         else
blanchet@58713
  1377
           []))
blanchet@58359
  1378
blanchet@58359
  1379
    val sml_suggs =
blanchet@58371
  1380
      if engine = MaSh_Py then
blanchet@58371
  1381
        []
blanchet@58371
  1382
      else
blanchet@58445
  1383
        let
blanchet@58711
  1384
          val (parents, hints, feats0) = query_args access_G
blanchet@58711
  1385
          val feats = map fst feats0
blanchet@58445
  1386
          val visible_facts = Graph.all_preds access_G parents
blanchet@58445
  1387
          val learns =
blanchet@58713
  1388
            (if null hints then [] else [(hintsN, feats, hints)]) @ (* ### FIXME *)
blanchet@58713
  1389
            Graph.schedule (fn _ => fn (fact, (_, feats, deps)) => (fact, feats, deps)) access_G
blanchet@58445
  1390
        in
blanchet@58714
  1391
          MaSh_SML.query ctxt engine fact_xtab feat_xtab visible_facts max_facts learns feats
blanchet@58359
  1392
        end
blanchet@58359
  1393
blanchet@58347
  1394
    val unknown = filter_out (is_fact_in_graph access_G o snd) facts
blanchet@54232
  1395
  in
blanchet@58359
  1396
    find_mash_suggestions ctxt max_facts (py_suggs @ sml_suggs) facts chained unknown
blanchet@54232
  1397
    |> pairself (map fact_of_raw_fact)
blanchet@54232
  1398
  end
blanchet@54232
  1399
blanchet@58713
  1400
fun learn_wrt_access_graph ctxt (name, parents, feats, deps)
blanchet@58713
  1401
    (learns, (access_G, fact_xtab, feat_xtab)) =
blanchet@54232
  1402
  let
blanchet@58713
  1403
    fun maybe_learn_from from (accum as (parents, access_G)) =
blanchet@58355
  1404
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@58713
  1405
        (from :: parents, Graph.add_edge_acyclic (from, name) access_G))
blanchet@58713
  1406
blanchet@58713
  1407
    val access_G = access_G |> Graph.default_node (name, (Isar_Proof, feats, deps))
blanchet@58713
  1408
    val (parents, access_G) = ([], access_G) |> fold maybe_learn_from parents
blanchet@58713
  1409
    val (deps, _) = ([], access_G) |> fold maybe_learn_from deps
blanchet@58713
  1410
blanchet@58713
  1411
    val fact_xtab = maybe_add_to_xtab name fact_xtab
blanchet@58713
  1412
    val feat_xtab = fold maybe_add_to_xtab feats feat_xtab
blanchet@58348
  1413
  in
blanchet@58713
  1414
    ((name, parents, feats, deps) :: learns, (access_G, fact_xtab, feat_xtab))
blanchet@58348
  1415
  end
blanchet@54232
  1416
blanchet@58713
  1417
fun relearn_wrt_access_graph ctxt (name, deps) (relearns, access_G) =
blanchet@54232
  1418
  let
blanchet@58713
  1419
    fun maybe_relearn_from from (accum as (parents, access_G)) =
blanchet@54232
  1420
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@58713
  1421
        (from :: parents, Graph.add_edge_acyclic (from, name) access_G))
blanchet@58713
  1422
    val access_G =
blanchet@58713
  1423
      access_G |> Graph.map_node name (fn (_, feats, _) => (Automatic_Proof, feats, deps))
blanchet@58713
  1424
    val (deps, _) = ([], access_G) |> fold maybe_relearn_from deps
blanchet@58348
  1425
  in
blanchet@58713
  1426
    ((name, deps) :: relearns, access_G)
blanchet@58348
  1427
  end
blanchet@54232
  1428
blanchet@54232
  1429
fun flop_wrt_access_graph name =
blanchet@58347
  1430
  Graph.map_node name (fn (_, feats, deps) => (Isar_Proof_wegen_Prover_Flop, feats, deps))
blanchet@54232
  1431
blanchet@58615
  1432
val learn_timeout_slack = 20.0
blanchet@54232
  1433
blanchet@54232
  1434
fun launch_thread timeout task =
blanchet@54232
  1435
  let
blanchet@54232
  1436
    val hard_timeout = time_mult learn_timeout_slack timeout
blanchet@54232
  1437
    val birth_time = Time.now ()
blanchet@54232
  1438
    val death_time = Time.+ (birth_time, hard_timeout)
blanchet@54232
  1439
    val desc = ("Machine learner for Sledgehammer", "")
blanchet@58348
  1440
  in
blanchet@58348
  1441
    Async_Manager.thread MaShN birth_time death_time desc task
blanchet@58348
  1442
  end
blanchet@54232
  1443
blanchet@58355
  1444
fun learned_proof_name () =
blanchet@58355
  1445
  Date.fmt ".%Y%m%d.%H%M%S." (Date.fromTimeLocal (Time.now ())) ^ serial_string ()
blanchet@58355
  1446
blanchet@55876
  1447
fun mash_learn_proof ctxt ({overlord, timeout, ...} : params) t facts used_ths =
blanchet@54956
  1448
  if is_mash_enabled () then
blanchet@56158
  1449
    launch_thread timeout (fn () =>
blanchet@58348
  1450
      let
blanchet@58348
  1451
        val thy = Proof_Context.theory_of ctxt
blanchet@58700
  1452
        val feats = map fst (features_of ctxt thy 0 Symtab.empty (Local, General) [t])
blanchet@58348
  1453
      in
blanchet@58713
  1454
        map_state ctxt overlord
blanchet@58713
  1455
          (fn state as {access_G, fact_xtab, feat_xtab, num_known_facts, dirty_facts} =>
blanchet@58713
  1456
             let
blanchet@58713
  1457
               val parents = maximal_wrt_access_graph access_G facts
blanchet@58713
  1458
               val deps = used_ths
blanchet@58713
  1459
                 |> filter (is_fact_in_graph access_G)
blanchet@58713
  1460
                 |> map nickname_of_thm
blanchet@58713
  1461
             in
blanchet@58713
  1462
               if the_mash_engine () = MaSh_Py then
blanchet@58713
  1463
                 (MaSh_Py.learn ctxt overlord true [("", parents, feats, deps)]; state)
blanchet@58713
  1464
               else
blanchet@58713
  1465
                 let
blanchet@58713
  1466
                   val name = learned_proof_name ()
blanchet@58713
  1467
                   val (access_G, fact_xtab, feat_xtab) =
blanchet@58713
  1468
                     add_node Automatic_Proof name parents feats deps
blanchet@58713
  1469
                       (access_G, fact_xtab, feat_xtab)
blanchet@58713
  1470
                 in
blanchet@58713
  1471
                   {access_G = access_G, fact_xtab = fact_xtab, feat_xtab = feat_xtab,
blanchet@58713
  1472
                    num_known_facts = num_known_facts + 1,
blanchet@58713
  1473
                    dirty_facts = Option.map (cons name) dirty_facts}
blanchet@58713
  1474
                 end
blanchet@58713
  1475
             end);
blanchet@58348
  1476
        (true, "")
blanchet@58348
  1477
      end)
blanchet@54956
  1478
  else
blanchet@54956
  1479
    ()
blanchet@54232
  1480
blanchet@58695
  1481
fun sendback sub = Active.sendback_markup [Markup.padding_command] (sledgehammerN ^ " " ^ sub)
blanchet@49407
  1482
blanchet@49407
  1483
val commit_timeout = seconds 30.0
blanchet@49347
  1484
blanchet@51500
  1485
(* The timeout is understood in a very relaxed fashion. *)
blanchet@56158
  1486
fun mash_learn_facts ctxt (params as {debug, verbose, overlord, ...}) prover save auto_level
blanchet@56158
  1487
    run_prover learn_timeout facts =
blanchet@49319
  1488
  let
blanchet@49333
  1489
    val timer = Timer.startRealTimer ()
blanchet@56158
  1490
    fun next_commit_time () = Time.+ (Timer.checkRealTimer timer, commit_timeout)
blanchet@58347
  1491
blanchet@58371
  1492
    val engine = the_mash_engine ()
blanchet@58714
  1493
    val {access_G, ...} = peek_state ctxt overlord I
blanchet@54232
  1494
    val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@52314
  1495
    val no_new_facts = forall is_in_access_G facts
blanchet@49323
  1496
  in
blanchet@52314
  1497
    if no_new_facts andalso not run_prover then
blanchet@49419
  1498
      if auto_level < 2 then
blanchet@58347
  1499
        "No new " ^ (if run_prover then "automatic" else "Isar") ^ " proofs to learn." ^
blanchet@51499
  1500
        (if auto_level = 0 andalso not run_prover then
blanchet@58347
  1501
           "\n\nHint: Try " ^ sendback learn_proverN ^ " to learn from an automatic prover."
blanchet@49419
  1502
         else
blanchet@49419
  1503
           "")
blanchet@49407
  1504
      else
blanchet@49407
  1505
        ""
blanchet@49323
  1506
    else
blanchet@49319
  1507
      let
blanchet@51750
  1508
        val name_tabs = build_name_tables nickname_of_thm facts
blanchet@58347
  1509
blanchet@49454
  1510
        fun deps_of status th =
blanchet@58359
  1511
          if status = Non_Rec_Def orelse status = Rec_Def then
blanchet@49454
  1512
            SOME []
blanchet@51499
  1513
          else if run_prover then
blanchet@58347
  1514
            prover_dependencies_of ctxt params prover auto_level facts name_tabs th
blanchet@58347
  1515
            |> (fn (false, _) => NONE | (true, deps) => trim_dependencies deps)
blanchet@49419
  1516
          else
blanchet@51750
  1517
            isar_dependencies_of name_tabs th
blanchet@58347
  1518
blanchet@49684
  1519
        fun do_commit [] [] [] state = state
blanchet@58713
  1520
          | do_commit learns relearns flops
blanchet@58713
  1521
              {access_G, fact_xtab, feat_xtab, num_known_facts, dirty_facts} =
blanchet@49407
  1522
            let
blanchet@58713
  1523
              val (learns, (access_G, fact_xtab, feat_xtab)) =
blanchet@58713
  1524
                fold (learn_wrt_access_graph ctxt) learns ([], (access_G, fact_xtab, feat_xtab))
blanchet@58713
  1525
              val (relearns, access_G) =
blanchet@58713
  1526
                fold (relearn_wrt_access_graph ctxt) relearns ([], access_G)
blanchet@58713
  1527
blanchet@51625
  1528
              val was_empty = Graph.is_empty access_G
blanchet@51625
  1529
              val access_G = access_G |> fold flop_wrt_access_graph flops
blanchet@54232
  1530
              val num_known_facts = num_known_facts + length learns
blanchet@58707
  1531
              val dirty_facts =
blanchet@58707
  1532
                (case (was_empty, dirty_facts) of
blanchet@58404
  1533
                  (false, SOME names) => SOME (map #1 learns @ map #1 relearns @ names)
blanchet@56628
  1534
                | _ => NONE)
blanchet@49419
  1535
            in
blanchet@58371
  1536
              if engine = MaSh_Py then
blanchet@58371
  1537
                (MaSh_Py.learn ctxt overlord (save andalso null relearns) (rev learns);
blanchet@58371
  1538
                 MaSh_Py.relearn ctxt overlord save relearns)
blanchet@58349
  1539
              else
blanchet@58371
  1540
                ();
blanchet@58713
  1541
              {access_G = access_G, fact_xtab = fact_xtab, feat_xtab = feat_xtab,
blanchet@58713
  1542
               num_known_facts = num_known_facts, dirty_facts = dirty_facts}
blanchet@49419
  1543
            end
blanchet@58347
  1544
blanchet@51646
  1545
        fun commit last learns relearns flops =
blanchet@58359
  1546
          (if debug andalso auto_level = 0 then Output.urgent_message "Committing..." else ();
blanchet@54285
  1547
           map_state ctxt overlord (do_commit (rev learns) relearns flops);
blanchet@49419
  1548
           if not last andalso auto_level = 0 then
blanchet@51646
  1549
             let val num_proofs = length learns + length relearns in
blanchet@58359
  1550
               Output.urgent_message ("Learned " ^ string_of_int num_proofs ^ " " ^
blanchet@58359
  1551
                 (if run_prover then "automatic" else "Isar") ^ " proof" ^
blanchet@58359
  1552
                 plural_s num_proofs ^ " in the last " ^ string_of_time commit_timeout ^ ".")
blanchet@49407
  1553
             end
blanchet@49407
  1554
           else
blanchet@49407
  1555
             ())
blanchet@58347
  1556
blanchet@52314
  1557
        fun learn_new_fact _ (accum as (_, (_, _, true))) = accum
blanchet@52314
  1558
          | learn_new_fact (parents, ((_, stature as (_, status)), th))
blanchet@58347
  1559
              (learns, (n, next_commit, _)) =
blanchet@49333
  1560
            let
blanchet@51639
  1561
              val name = nickname_of_thm th
blanchet@58700
  1562
              val feats =
blanchet@58700
  1563
                map fst (features_of ctxt (theory_of_thm th) 0 Symtab.empty stature [prop_of th])
blanchet@49454
  1564
              val deps = deps_of status th |> these
blanchet@49409
  1565
              val n = n |> not (null deps) ? Integer.add 1
blanchet@51646
  1566
              val learns = (name, parents, feats, deps) :: learns
blanchet@51646
  1567
              val (learns, next_commit) =
blanchet@49407
  1568
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@51646
  1569
                  (commit false learns [] []; ([], next_commit_time ()))
blanchet@49407
  1570
                else
blanchet@51646
  1571
                  (learns, next_commit)
blanchet@56158
  1572
              val timed_out = Time.> (Timer.checkRealTimer timer, learn_timeout)
blanchet@58347
  1573
            in
blanchet@58347
  1574
              (learns, (n, next_commit, timed_out))
blanchet@58347
  1575
            end
blanchet@58347
  1576
blanchet@49419
  1577
        val n =
blanchet@52314
  1578
          if no_new_facts then
blanchet@49419
  1579
            0
blanchet@49419
  1580
          else
blanchet@49419
  1581
            let
blanchet@58347
  1582
              val new_facts = facts
blanchet@58347
  1583
                |> sort (crude_thm_ord o pairself snd)
blanchet@58347
  1584
                |> attach_parents_to_facts []
blanchet@58347
  1585
                |> filter_out (is_in_access_G o snd)
blanchet@52314
  1586
              val (learns, (n, _, _)) =
blanchet@52314
  1587
                ([], (0, next_commit_time (), false))
blanchet@52319
  1588
                |> fold learn_new_fact new_facts
blanchet@58347
  1589
            in
blanchet@58347
  1590
              commit true learns [] []; n
blanchet@58347
  1591
            end
blanchet@58347
  1592
blanchet@49419
  1593
        fun relearn_old_fact _ (accum as (_, (_, _, true))) = accum
blanchet@58347
  1594
          | relearn_old_fact ((_, (_, status)), th) ((relearns, flops), (n, next_commit, _)) =
blanchet@49419
  1595
            let
blanchet@51639
  1596
              val name = nickname_of_thm th
blanchet@51646
  1597
              val (n, relearns, flops) =
blanchet@56628
  1598
                (case deps_of status th of
blanchet@51646
  1599
                  SOME deps => (n + 1, (name, deps) :: relearns, flops)
blanchet@56628
  1600
                | NONE => (n, relearns, name :: flops))
blanchet@51646
  1601
              val (relearns, flops, next_commit) =
blanchet@49419
  1602
                if Time.> (Timer.checkRealTimer timer, next_commit) then
blanchet@58347
  1603
                  (commit false [] relearns flops; ([], [], next_commit_time ()))
blanchet@49419
  1604
                else
blanchet@51646
  1605
                  (relearns, flops, next_commit)
blanchet@56158
  1606
              val timed_out = Time.> (Timer.checkRealTimer timer, learn_timeout)
blanchet@58347
  1607
            in
blanchet@58347
  1608
              ((relearns, flops), (n, next_commit, timed_out))
blanchet@58347
  1609
            end
blanchet@58347
  1610
blanchet@49419
  1611
        val n =
blanchet@52314
  1612
          if not run_prover then
blanchet@49419
  1613
            n
blanchet@49419
  1614
          else
blanchet@49419
  1615
            let
blanchet@49683
  1616
              val max_isar = 1000 * max_dependencies
blanchet@58347
  1617
blanchet@58347
  1618
              fun priority_of th =
blanchet@58404
  1619
                random_range 0 max_isar +
blanchet@58404
  1620
                (case try (Graph.get_node access_G) (nickname_of_thm th) of
blanchet@58404
  1621
                  SOME (Isar_Proof, _, deps) => ~100 * length deps
blanchet@58404
  1622
                | SOME (Automatic_Proof, _, _) => 2 * max_isar
blanchet@58404
  1623
                | SOME (Isar_Proof_wegen_Prover_Flop, _, _) => max_isar
blanchet@58404
  1624
                | NONE => 0)
blanchet@58347
  1625
blanchet@58347
  1626
              val old_facts = facts
blanchet@58347
  1627
                |> filter is_in_access_G
blanchet@58347
  1628
                |> map (`(priority_of o snd))
blanchet@58347
  1629
                |> sort (int_ord o pairself fst)
blanchet@58347
  1630
                |> map snd
blanchet@51646
  1631
              val ((relearns, flops), (n, _, _)) =
blanchet@49684
  1632
                (([], []), (n, next_commit_time (), false))
blanchet@49419
  1633
                |> fold relearn_old_fact old_facts
blanchet@58347
  1634
            in
blanchet@58347
  1635
              commit true [] relearns flops; n
blanchet@58347
  1636
            end
blanchet@49333
  1637
      in
blanchet@49419
  1638
        if verbose orelse auto_level < 2 then
blanchet@49419
  1639
          "Learned " ^ string_of_int n ^ " nontrivial " ^
blanchet@55592
  1640
          (if run_prover then "automatic and " else "") ^ "Isar proof" ^ plural_s n ^
blanchet@58348
  1641
          (if verbose then " in " ^ string_of_time (Timer.checkRealTimer timer) else "") ^ "."
blanchet@49334
  1642
        else
blanchet@49334
  1643
          ""
blanchet@49333
  1644
      end
blanchet@49323
  1645
  end
blanchet@49319
  1646
blanchet@55575
  1647
fun mash_learn ctxt (params as {provers, timeout, ...}) fact_override chained run_prover =
blanchet@49331
  1648
  let
blanchet@49411
  1649
    val css = Sledgehammer_Fact.clasimpset_rule_table_of ctxt
blanchet@49410
  1650
    val ctxt = ctxt |> Config.put instantiate_inducts false
blanchet@58348
  1651
    val facts = nearly_all_facts ctxt false fact_override Symtab.empty css chained [] @{prop True}
blanchet@55567
  1652
      |> sort (crude_thm_ord o pairself snd o swap)
blanchet@49419
  1653
    val num_facts = length facts
blanchet@49419
  1654
    val prover = hd provers
blanchet@58348
  1655
blanchet@51499
  1656
    fun learn auto_level run_prover =
blanchet@56158
  1657
      mash_learn_facts ctxt params prover true auto_level run_prover one_year facts
blanchet@49419
  1658
      |> Output.urgent_message
blanchet@49331
  1659
  in
blanchet@51499
  1660
    if run_prover then
blanchet@58359
  1661
      (Output.urgent_message ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@58359
  1662
         plural_s num_facts ^ " for automatic proofs (" ^ quote prover ^ " timeout: " ^
blanchet@58359
  1663
         string_of_time timeout ^ ").\n\nCollecting Isar proofs first...");
blanchet@51355
  1664
       learn 1 false;
blanchet@58359
  1665
       Output.urgent_message "Now collecting automatic proofs. This may take several hours. You \
blanchet@58359
  1666
         \can safely stop the learning process at any point.";
blanchet@51355
  1667
       learn 0 true)
blanchet@51355
  1668
    else
blanchet@58348
  1669
      (Output.urgent_message ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@58348
  1670
         plural_s num_facts ^ " for Isar proofs...");
blanchet@51355
  1671
       learn 0 false)
blanchet@49331
  1672
  end
blanchet@49264
  1673
blanchet@54285
  1674
fun mash_can_suggest_facts ctxt overlord =
blanchet@54285
  1675
  not (Graph.is_empty (#access_G (peek_state ctxt overlord I)))
blanchet@51326
  1676
blanchet@58616
  1677
(* Generate more suggestions than requested, because some might be thrown out later for various
blanchet@58616
  1678
   reasons (e.g., duplicates). *)
blanchet@58616
  1679
fun generous_max_suggestions max_facts = 3 * max_facts div 2 + 25
blanchet@51398
  1680
blanchet@51829
  1681
val mepo_weight = 0.5
blanchet@51829
  1682
val mash_weight = 0.5
blanchet@51829
  1683
blanchet@54289
  1684
val max_facts_to_learn_before_query = 100
blanchet@54289
  1685
blanchet@58347
  1686
(* The threshold should be large enough so that MaSh does not get activated for Auto Sledgehammer
blanchet@58347
  1687
   and Try. *)
blanchet@49333
  1688
val min_secs_for_learning = 15
blanchet@49333
  1689
blanchet@58703
  1690
fun relevant_facts ctxt (params as {overlord, learn, fact_filter, timeout, ...}) prover max_facts
blanchet@58703
  1691
    ({add, only, ...} : fact_override) hyp_ts concl_t facts =
blanchet@49329
  1692
  if not (subset (op =) (the_list fact_filter, fact_filters)) then
blanchet@49329
  1693
    error ("Unknown fact filter: " ^ quote (the fact_filter) ^ ".")
blanchet@49329
  1694
  else if only then
blanchet@58492
  1695
    [("", map fact_of_raw_fact facts)]
blanchet@49336
  1696
  else if max_facts <= 0 orelse null facts then
blanchet@52192
  1697
    [("", [])]
blanchet@49303
  1698
  else
blanchet@49303
  1699
    let
blanchet@54289
  1700
      fun maybe_launch_thread () =
blanchet@58615
  1701
        if not (Async_Manager.has_running_threads MaShN) andalso
blanchet@56158
  1702
           Time.toSeconds timeout >= min_secs_for_learning then
blanchet@56158
  1703
          let val timeout = time_mult learn_timeout_slack timeout in
blanchet@56158
  1704
            launch_thread timeout
blanchet@56158
  1705
              (fn () => (true, mash_learn_facts ctxt params prover true 2 false timeout facts))
blanchet@49334
  1706
          end
blanchet@49333
  1707
        else
blanchet@49333
  1708
          ()
blanchet@58360
  1709
blanchet@54289
  1710
      fun maybe_learn () =
blanchet@54956
  1711
        if is_mash_enabled () andalso learn then
blanchet@54289
  1712
          let
blanchet@54289
  1713
            val {access_G, num_known_facts, ...} = peek_state ctxt overlord I
blanchet@54289
  1714
            val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@54289
  1715
          in
blanchet@58353
  1716
            if length facts - num_known_facts <= max_facts_to_learn_before_query then
blanchet@56628
  1717
              (case length (filter_out is_in_access_G facts) of
blanchet@55149
  1718
                0 => false
blanchet@55149
  1719
              | num_facts_to_learn =>
blanchet@55149
  1720
                if num_facts_to_learn <= max_facts_to_learn_before_query then
blanchet@55149
  1721
                  (mash_learn_facts ctxt params prover false 2 false timeout facts
blanchet@55149
  1722
                   |> (fn "" => () | s => Output.urgent_message (MaShN ^ ": " ^ s));
blanchet@55149
  1723
                   true)
blanchet@55149
  1724
                else
blanchet@56628
  1725
                  (maybe_launch_thread (); false))
blanchet@54289
  1726
            else
blanchet@54289
  1727
              (maybe_launch_thread (); false)
blanchet@54289
  1728
          end
blanchet@54289
  1729
        else
blanchet@54289
  1730
          false
blanchet@58360
  1731
blanchet@54289
  1732
      val (save, effective_fact_filter) =
blanchet@56628
  1733
        (case fact_filter of
blanchet@54289
  1734
          SOME ff => (ff <> mepoN andalso maybe_learn (), ff)
blanchet@49333
  1735
        | NONE =>
blanchet@52206
  1736
          if is_mash_enabled () then
blanchet@58449
  1737
            (maybe_learn (), if mash_can_suggest_facts ctxt overlord then meshN else mepoN)
blanchet@49422
  1738
          else
blanchet@56628
  1739
            (false, mepoN))
blanchet@55595
  1740
blanchet@55595
  1741
      val unique_facts = drop_duplicate_facts facts
blanchet@49303
  1742
      val add_ths = Attrib.eval_thms ctxt add
blanchet@55595
  1743
blanchet@52186
  1744
      fun in_add (_, th) = member Thm.eq_thm_prop add_ths th
blanchet@58360
  1745
blanchet@52185
  1746
      fun add_and_take accepts =
blanchet@52185
  1747
        (case add_ths of
blanchet@52185
  1748
           [] => accepts
blanchet@58492
  1749
         | _ =>
blanchet@58492
  1750
           (unique_facts |> filter in_add |> map fact_of_raw_fact) @ (accepts |> filter_out in_add))
blanchet@49308
  1751
        |> take max_facts
blanchet@58360
  1752
blanchet@49421
  1753
      fun mepo () =
blanchet@55595
  1754
        (mepo_suggested_facts ctxt params max_facts NONE hyp_ts concl_t unique_facts
blanchet@55543
  1755
         |> weight_facts_steeply, [])
blanchet@58360
  1756
blanchet@49329
  1757
      fun mash () =
blanchet@58450
  1758
        mash_suggested_facts ctxt params (generous_max_suggestions max_facts) hyp_ts concl_t facts
blanchet@54277
  1759
        |>> weight_facts_steeply
blanchet@58360
  1760
blanchet@49329
  1761
      val mess =
blanchet@52185
  1762
        (* the order is important for the "case" expression below *)
blanchet@55543
  1763
        [] |> effective_fact_filter <> mepoN ? cons (mash_weight, mash)
blanchet@55543
  1764
           |> effective_fact_filter <> mashN ? cons (mepo_weight, mepo)
blanchet@55543
  1765
           |> Par_List.map (apsnd (fn f => f ()))
blanchet@58492
  1766
      val mesh = mesh_facts (eq_snd (gen_eq_thm ctxt)) max_facts mess |> add_and_take
blanchet@49303
  1767
    in
blanchet@58371
  1768
      if the_mash_engine () = MaSh_Py andalso save then MaSh_Py.save ctxt overlord else ();
blanchet@56628
  1769
      (case (fact_filter, mess) of
blanchet@52206
  1770
        (NONE, [(_, (mepo, _)), (_, (mash, _))]) =>
blanchet@52192
  1771
        [(meshN, mesh), (mepoN, mepo |> map fst |> add_and_take),
blanchet@52192
  1772
         (mashN, mash |> map fst |> add_and_take)]
blanchet@56628
  1773
      | _ => [(effective_fact_filter, mesh)])
blanchet@49303
  1774
    end
blanchet@49303
  1775
blanchet@54285
  1776
fun kill_learners ctxt ({overlord, ...} : params) =
blanchet@58349
  1777
  (Async_Manager.kill_threads MaShN "learner";
blanchet@58371
  1778
   if the_mash_engine () = MaSh_Py then MaSh_Py.shutdown ctxt overlord else ())
blanchet@58347
  1779
blanchet@49334
  1780
fun running_learners () = Async_Manager.running_threads MaShN "learner"
blanchet@49334
  1781
blanchet@49263
  1782
end;