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