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