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