src/HOL/Tools/Sledgehammer/sledgehammer_mash.ML
author wenzelm
Sat Apr 02 23:29:05 2016 +0200 (2016-04-02 ago)
changeset 62826 eb94e570c1a4
parent 62735 23de054397e5
child 63518 ae8fd6fe63a1
permissions -rw-r--r--
prefer infix operations;
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@50632
    35
blanchet@57532
    36
  datatype mash_algorithm =
blanchet@57458
    37
    MaSh_NB
blanchet@57459
    38
  | MaSh_kNN
blanchet@57459
    39
  | MaSh_NB_kNN
blanchet@57458
    40
  | MaSh_NB_Ext
blanchet@57431
    41
  | MaSh_kNN_Ext
blanchet@57106
    42
blanchet@57120
    43
  val is_mash_enabled : unit -> bool
blanchet@57532
    44
  val the_mash_algorithm : unit -> mash_algorithm
blanchet@57557
    45
  val str_of_mash_algorithm : mash_algorithm -> string
blanchet@57120
    46
blanchet@61322
    47
  val mesh_facts : ('a list -> 'a list) -> ('a * 'a -> bool) -> int ->
blanchet@61322
    48
    (real * (('a * real) list * 'a list)) list -> 'a list
blanchet@61321
    49
  val nickname_of_thm : thm -> string
blanchet@57006
    50
  val find_suggested_facts : Proof.context -> ('b * thm) list -> string list -> ('b * thm) list
wenzelm@60641
    51
  val crude_thm_ord : Proof.context -> thm * thm -> order
blanchet@51182
    52
  val thm_less : thm * thm -> bool
blanchet@48251
    53
  val goal_of_thm : theory -> thm -> thm
blanchet@57006
    54
  val run_prover_for_mash : Proof.context -> params -> string -> string -> fact list -> thm ->
blanchet@57006
    55
    prover_result
wenzelm@60640
    56
  val features_of : Proof.context -> string -> stature -> term list -> string list
blanchet@51177
    57
  val trim_dependencies : string list -> string list option
blanchet@61321
    58
  val isar_dependencies_of : string Symtab.table * string Symtab.table -> thm -> string list option
blanchet@57006
    59
  val prover_dependencies_of : Proof.context -> params -> string -> int -> raw_fact list ->
blanchet@57006
    60
    string Symtab.table * string Symtab.table -> thm -> bool * string list
blanchet@61321
    61
  val attach_parents_to_facts : ('a * thm) list -> ('a * thm) list ->
blanchet@57006
    62
    (string list * ('a * thm)) list
blanchet@53140
    63
  val num_extra_feature_facts : int
blanchet@53141
    64
  val extra_feature_factor : real
blanchet@53140
    65
  val weight_facts_smoothly : 'a list -> ('a * real) list
blanchet@53140
    66
  val weight_facts_steeply : 'a list -> ('a * real) list
blanchet@57432
    67
  val find_mash_suggestions : Proof.context -> int -> string list -> ('a * thm) list ->
blanchet@57432
    68
    ('a * thm) list -> ('a * thm) list -> ('a * thm) list * ('a * thm) list
wenzelm@60649
    69
  val mash_suggested_facts : Proof.context -> string -> params -> int -> term list -> term ->
blanchet@57407
    70
    raw_fact list -> fact list * fact list
blanchet@57431
    71
blanchet@57431
    72
  val mash_unlearn : unit -> unit
blanchet@54503
    73
  val mash_learn_proof : Proof.context -> params -> term -> ('a * thm) list -> thm list -> unit
blanchet@57431
    74
  val mash_learn_facts : Proof.context -> params -> string -> int -> bool -> Time.time ->
blanchet@57120
    75
    raw_fact list -> string
blanchet@57006
    76
  val mash_learn : Proof.context -> params -> fact_override -> thm list -> bool -> unit
blanchet@57432
    77
  val mash_can_suggest_facts : Proof.context -> bool
blanchet@53819
    78
blanchet@57108
    79
  val generous_max_suggestions : int -> int
blanchet@50814
    80
  val mepo_weight : real
blanchet@50814
    81
  val mash_weight : real
blanchet@57006
    82
  val relevant_facts : Proof.context -> params -> string -> int -> fact_override -> term list ->
blanchet@57006
    83
    term -> raw_fact list -> (string * fact list) list
blanchet@48248
    84
end;
blanchet@48248
    85
blanchet@48381
    86
structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
blanchet@48248
    87
struct
blanchet@48249
    88
blanchet@48251
    89
open ATP_Util
blanchet@48251
    90
open ATP_Problem_Generate
blanchet@48251
    91
open Sledgehammer_Util
blanchet@48251
    92
open Sledgehammer_Fact
blanchet@55201
    93
open Sledgehammer_Prover
blanchet@55202
    94
open Sledgehammer_Prover_Minimize
blanchet@48381
    95
open Sledgehammer_MePo
blanchet@48251
    96
blanchet@61318
    97
val anonymous_proof_prefix = "."
blanchet@61318
    98
blanchet@57005
    99
val trace = Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
blanchet@57150
   100
val duplicates = Attrib.setup_config_bool @{binding sledgehammer_fact_duplicates} (K false)
blanchet@51032
   101
blanchet@48308
   102
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@48308
   103
blanchet@57150
   104
fun gen_eq_thm ctxt = if Config.get ctxt duplicates then Thm.eq_thm_strict else Thm.eq_thm_prop
blanchet@57150
   105
blanchet@51008
   106
val MePoN = "MePo"
blanchet@48319
   107
val MaShN = "MaSh"
blanchet@51008
   108
val MeShN = "MeSh"
blanchet@48319
   109
blanchet@48379
   110
val mepoN = "mepo"
blanchet@48314
   111
val mashN = "mash"
blanchet@48379
   112
val meshN = "mesh"
blanchet@48314
   113
blanchet@48379
   114
val fact_filters = [meshN, mepoN, mashN]
blanchet@48314
   115
blanchet@48392
   116
val unlearnN = "unlearn"
blanchet@48392
   117
val learn_isarN = "learn_isar"
blanchet@50484
   118
val learn_proverN = "learn_prover"
blanchet@48392
   119
val relearn_isarN = "relearn_isar"
blanchet@50484
   120
val relearn_proverN = "relearn_prover"
blanchet@48392
   121
blanchet@57368
   122
fun map_array_at ary f i = Array.update (ary, i, f (Array.sub (ary, i)))
blanchet@57368
   123
blanchet@57371
   124
type xtab = int * int Symtab.table
blanchet@57371
   125
blanchet@57371
   126
val empty_xtab = (0, Symtab.empty)
blanchet@57371
   127
blanchet@57371
   128
fun add_to_xtab key (next, tab) = (next + 1, Symtab.update_new (key, next) tab)
blanchet@57371
   129
fun maybe_add_to_xtab key = perhaps (try (add_to_xtab key))
blanchet@57371
   130
blanchet@57552
   131
fun state_file () = Path.expand (Path.explode "$ISABELLE_HOME_USER/mash_state")
blanchet@57552
   132
val remove_state_file = try File.rm o state_file
blanchet@48330
   133
blanchet@57532
   134
datatype mash_algorithm =
blanchet@57458
   135
  MaSh_NB
blanchet@57459
   136
| MaSh_kNN
blanchet@57459
   137
| MaSh_NB_kNN
blanchet@57458
   138
| MaSh_NB_Ext
blanchet@57431
   139
| MaSh_kNN_Ext
blanchet@57278
   140
blanchet@57532
   141
fun mash_algorithm () =
blanchet@61043
   142
  (case Options.default_string @{system_option MaSh} of
blanchet@61043
   143
    "yes" => SOME MaSh_NB_kNN
blanchet@61043
   144
  | "sml" => SOME MaSh_NB_kNN
blanchet@61043
   145
  | "nb" => SOME MaSh_NB
blanchet@61043
   146
  | "knn" => SOME MaSh_kNN
blanchet@61043
   147
  | "nb_knn" => SOME MaSh_NB_kNN
blanchet@61043
   148
  | "nb_ext" => SOME MaSh_NB_Ext
blanchet@61043
   149
  | "knn_ext" => SOME MaSh_kNN_Ext
blanchet@61043
   150
  | "none" => NONE
blanchet@61043
   151
  | "" => NONE
blanchet@61043
   152
  | algorithm => (warning ("Unknown MaSh algorithm: " ^ quote algorithm ^ "."); NONE))
blanchet@57018
   153
blanchet@57532
   154
val is_mash_enabled = is_some o mash_algorithm
blanchet@57532
   155
val the_mash_algorithm = the_default MaSh_NB_kNN o mash_algorithm
blanchet@57018
   156
blanchet@57557
   157
fun str_of_mash_algorithm MaSh_NB = "nb"
blanchet@57557
   158
  | str_of_mash_algorithm MaSh_kNN = "knn"
blanchet@57557
   159
  | str_of_mash_algorithm MaSh_NB_kNN = "nb_knn"
blanchet@57557
   160
  | str_of_mash_algorithm MaSh_NB_Ext = "nb_ext"
blanchet@57557
   161
  | str_of_mash_algorithm MaSh_kNN_Ext = "knn_ext"
blanchet@57557
   162
blanchet@57459
   163
fun scaled_avg [] = 0
blanchet@57459
   164
  | scaled_avg xs = Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs
blanchet@57459
   165
blanchet@57459
   166
fun avg [] = 0.0
blanchet@57459
   167
  | avg xs = fold (curry (op +)) xs 0.0 / Real.fromInt (length xs)
blanchet@57459
   168
blanchet@57459
   169
fun normalize_scores _ [] = []
blanchet@57459
   170
  | normalize_scores max_facts xs =
wenzelm@62826
   171
    map (apsnd (curry (op *) (1.0 / avg (map snd (take max_facts xs))))) xs
blanchet@57459
   172
blanchet@61322
   173
fun mesh_facts maybe_distinct _ max_facts [(_, (sels, unks))] =
blanchet@61322
   174
    map fst (take max_facts sels) @ take (max_facts - length sels) unks
blanchet@61322
   175
    |> maybe_distinct
blanchet@61322
   176
  | mesh_facts _ fact_eq max_facts mess =
blanchet@57459
   177
    let
blanchet@57459
   178
      val mess = mess |> map (apsnd (apfst (normalize_scores max_facts)))
blanchet@57459
   179
blanchet@57459
   180
      fun score_in fact (global_weight, (sels, unks)) =
blanchet@57459
   181
        let val score_at = try (nth sels) #> Option.map (fn (_, score) => global_weight * score) in
blanchet@57459
   182
          (case find_index (curry fact_eq fact o fst) sels of
blanchet@57459
   183
            ~1 => if member fact_eq unks fact then NONE else SOME 0.0
blanchet@57459
   184
          | rank => score_at rank)
blanchet@57459
   185
        end
blanchet@57459
   186
blanchet@57459
   187
      fun weight_of fact = mess |> map_filter (score_in fact) |> scaled_avg
blanchet@57459
   188
    in
blanchet@57459
   189
      fold (union fact_eq o map fst o take max_facts o fst o snd) mess []
wenzelm@59058
   190
      |> map (`weight_of) |> sort (int_ord o apply2 fst o swap)
blanchet@57459
   191
      |> map snd |> take max_facts
blanchet@57459
   192
    end
blanchet@57459
   193
blanchet@57459
   194
fun smooth_weight_of_fact rank = Math.pow (1.3, 15.5 - 0.2 * Real.fromInt rank) + 15.0 (* FUDGE *)
blanchet@57459
   195
fun steep_weight_of_fact rank = Math.pow (0.62, log2 (Real.fromInt (rank + 1))) (* FUDGE *)
blanchet@57459
   196
blanchet@57459
   197
fun weight_facts_smoothly facts = facts ~~ map smooth_weight_of_fact (0 upto length facts - 1)
blanchet@57459
   198
fun weight_facts_steeply facts = facts ~~ map steep_weight_of_fact (0 upto length facts - 1)
blanchet@57459
   199
blanchet@57660
   200
fun sort_array_suffix cmp needed a =
blanchet@57009
   201
  let
blanchet@57406
   202
    exception BOTTOM of int
blanchet@57406
   203
blanchet@57460
   204
    val al = Array.length a
blanchet@57460
   205
blanchet@57009
   206
    fun maxson l i =
blanchet@57017
   207
      let val i31 = i + i + i + 1 in
blanchet@57009
   208
        if i31 + 2 < l then
blanchet@57017
   209
          let val x = Unsynchronized.ref i31 in
blanchet@57017
   210
            if cmp (Array.sub (a, i31), Array.sub (a, i31 + 1)) = LESS then x := i31 + 1 else ();
blanchet@57017
   211
            if cmp (Array.sub (a, !x), Array.sub (a, i31 + 2)) = LESS then x := i31 + 2 else ();
blanchet@57009
   212
            !x
blanchet@57009
   213
          end
blanchet@57009
   214
        else
blanchet@57009
   215
          if i31 + 1 < l andalso cmp (Array.sub (a, i31), Array.sub (a, i31 + 1)) = LESS
blanchet@57009
   216
          then i31 + 1 else if i31 < l then i31 else raise BOTTOM i
blanchet@57009
   217
      end
blanchet@57009
   218
blanchet@57009
   219
    fun trickledown l i e =
blanchet@57029
   220
      let val j = maxson l i in
blanchet@57009
   221
        if cmp (Array.sub (a, j), e) = GREATER then
blanchet@57029
   222
          (Array.update (a, i, Array.sub (a, j)); trickledown l j e)
blanchet@57029
   223
        else
blanchet@57029
   224
          Array.update (a, i, e)
blanchet@57009
   225
      end
blanchet@57009
   226
blanchet@57009
   227
    fun trickle l i e = trickledown l i e handle BOTTOM i => Array.update (a, i, e)
blanchet@57009
   228
blanchet@57009
   229
    fun bubbledown l i =
blanchet@57029
   230
      let val j = maxson l i in
blanchet@57029
   231
        Array.update (a, i, Array.sub (a, j));
blanchet@57009
   232
        bubbledown l j
blanchet@57009
   233
      end
blanchet@57009
   234
blanchet@57009
   235
    fun bubble l i = bubbledown l i handle BOTTOM i => i
blanchet@57009
   236
blanchet@57009
   237
    fun trickleup i e =
blanchet@57029
   238
      let val father = (i - 1) div 3 in
blanchet@57009
   239
        if cmp (Array.sub (a, father), e) = LESS then
blanchet@57029
   240
          (Array.update (a, i, Array.sub (a, father));
blanchet@57029
   241
           if father > 0 then trickleup father e else Array.update (a, 0, e))
blanchet@57029
   242
        else
blanchet@57029
   243
          Array.update (a, i, e)
blanchet@57009
   244
      end
blanchet@57009
   245
blanchet@57355
   246
    fun for i = if i < 0 then () else (trickle al i (Array.sub (a, i)); for (i - 1))
blanchet@57009
   247
blanchet@57009
   248
    fun for2 i =
blanchet@57660
   249
      if i < Integer.max 2 (al - needed) then
blanchet@57029
   250
        ()
blanchet@57029
   251
      else
blanchet@57029
   252
        let val e = Array.sub (a, i) in
blanchet@57029
   253
          Array.update (a, i, Array.sub (a, 0));
blanchet@57029
   254
          trickleup (bubble i 0) e;
blanchet@57029
   255
          for2 (i - 1)
blanchet@57029
   256
        end
blanchet@57009
   257
  in
blanchet@57355
   258
    for (((al + 1) div 3) - 1);
blanchet@57355
   259
    for2 (al - 1);
blanchet@57355
   260
    if al > 1 then
blanchet@57029
   261
      let val e = Array.sub (a, 1) in
blanchet@57029
   262
        Array.update (a, 1, Array.sub (a, 0));
blanchet@57009
   263
        Array.update (a, 0, e)
blanchet@57009
   264
      end
blanchet@57029
   265
    else
blanchet@57029
   266
      ()
blanchet@57009
   267
  end
blanchet@57009
   268
blanchet@57660
   269
fun rev_sort_list_prefix cmp needed xs =
blanchet@57460
   270
  let val ary = Array.fromList xs in
blanchet@57660
   271
    sort_array_suffix cmp needed ary;
blanchet@57660
   272
    Array.foldl (op ::) [] ary
blanchet@57460
   273
  end
blanchet@57460
   274
blanchet@57460
   275
blanchet@57460
   276
(*** Isabelle-agnostic machine learning ***)
blanchet@57460
   277
blanchet@57460
   278
structure MaSh =
blanchet@57460
   279
struct
blanchet@57460
   280
blanchet@57574
   281
fun select_visible_facts (big_number : real) recommends =
blanchet@57364
   282
  List.app (fn at =>
blanchet@57364
   283
    let val (j, ov) = Array.sub (recommends, at) in
blanchet@57371
   284
      Array.update (recommends, at, (j, big_number + ov))
blanchet@57364
   285
    end)
blanchet@57364
   286
blanchet@57374
   287
fun wider_array_of_vector init vec =
blanchet@57374
   288
  let val ary = Array.array init in
blanchet@57374
   289
    Array.copyVec {src = vec, dst = ary, di = 0};
blanchet@57374
   290
    ary
blanchet@57374
   291
  end
blanchet@57374
   292
blanchet@57531
   293
val nb_def_prior_weight = 1000 (* FUDGE *)
blanchet@57095
   294
blanchet@57374
   295
fun learn_facts (tfreq0, sfreq0, dffreq0) num_facts0 num_facts num_feats depss featss =
blanchet@57354
   296
  let
blanchet@57374
   297
    val tfreq = wider_array_of_vector (num_facts, 0) tfreq0
blanchet@57374
   298
    val sfreq = wider_array_of_vector (num_facts, Inttab.empty) sfreq0
blanchet@57374
   299
    val dffreq = wider_array_of_vector (num_feats, 0) dffreq0
blanchet@57374
   300
blanchet@57374
   301
    fun learn_one th feats deps =
blanchet@57354
   302
      let
blanchet@57355
   303
        fun add_th weight t =
blanchet@57355
   304
          let
blanchet@57355
   305
            val im = Array.sub (sfreq, t)
blanchet@57374
   306
            fun fold_fn s = Inttab.map_default (s, 0) (Integer.add weight)
blanchet@57355
   307
          in
blanchet@57368
   308
            map_array_at tfreq (Integer.add weight) t;
blanchet@57355
   309
            Array.update (sfreq, t, fold fold_fn feats im)
blanchet@57355
   310
          end
blanchet@57355
   311
blanchet@57368
   312
        val add_sym = map_array_at dffreq (Integer.add 1)
blanchet@57354
   313
      in
blanchet@57355
   314
        add_th nb_def_prior_weight th;
blanchet@57355
   315
        List.app (add_th 1) deps;
blanchet@57355
   316
        List.app add_sym feats
blanchet@57354
   317
      end
blanchet@57354
   318
blanchet@57102
   319
    fun for i =
blanchet@57383
   320
      if i = num_facts then ()
blanchet@57383
   321
      else (learn_one i (Vector.sub (featss, i)) (Vector.sub (depss, i)); for (i + 1))
blanchet@57102
   322
  in
blanchet@57383
   323
    for num_facts0;
blanchet@57374
   324
    (Array.vector tfreq, Array.vector sfreq, Array.vector dffreq)
blanchet@57102
   325
  end
blanchet@57029
   326
blanchet@57376
   327
fun naive_bayes (tfreq, sfreq, dffreq) num_facts max_suggs visible_facts goal_feats =
blanchet@57278
   328
  let
blanchet@57531
   329
    val tau = 0.2 (* FUDGE *)
blanchet@57531
   330
    val pos_weight = 5.0 (* FUDGE *)
blanchet@57531
   331
    val def_val = ~18.0 (* FUDGE *)
blanchet@57531
   332
    val init_val = 30.0 (* FUDGE *)
blanchet@57124
   333
blanchet@57366
   334
    val ln_afreq = Math.ln (Real.fromInt num_facts)
blanchet@57374
   335
    val idf = Vector.map (fn i => ln_afreq - Math.ln (Real.fromInt i)) dffreq
blanchet@57366
   336
blanchet@57359
   337
    fun tfidf feat = Vector.sub (idf, feat)
blanchet@57102
   338
blanchet@57102
   339
    fun log_posterior i =
blanchet@57029
   340
      let
blanchet@57374
   341
        val tfreq = Real.fromInt (Vector.sub (tfreq, i))
blanchet@57097
   342
blanchet@57531
   343
        fun add_feat (f, fw0) (res, sfh) =
blanchet@57102
   344
          (case Inttab.lookup sfh f of
blanchet@57102
   345
            SOME sf =>
blanchet@57401
   346
            (res + fw0 * tfidf f * Math.ln (pos_weight * Real.fromInt sf / tfreq),
blanchet@57102
   347
             Inttab.delete f sfh)
blanchet@57409
   348
          | NONE => (res + fw0 * tfidf f * def_val, sfh))
blanchet@57097
   349
blanchet@57531
   350
        val (res, sfh) = fold add_feat goal_feats (init_val * Math.ln tfreq, Vector.sub (sfreq, i))
blanchet@57097
   351
blanchet@57409
   352
        fun fold_sfh (f, sf) sow =
blanchet@59476
   353
          sow + tfidf f * Math.ln (1.0 - Real.fromInt (sf - 1) / tfreq)
blanchet@57097
   354
blanchet@57102
   355
        val sum_of_weights = Inttab.fold fold_sfh sfh 0.0
blanchet@57029
   356
      in
blanchet@57278
   357
        res + tau * sum_of_weights
blanchet@57097
   358
      end
blanchet@57029
   359
blanchet@57356
   360
    val posterior = Array.tabulate (num_facts, (fn j => (j, log_posterior j)))
blanchet@57102
   361
blanchet@57364
   362
    fun ret at acc =
blanchet@57364
   363
      if at = num_facts then acc else ret (at + 1) (Array.sub (posterior, at) :: acc)
blanchet@57029
   364
  in
blanchet@57371
   365
    select_visible_facts 100000.0 posterior visible_facts;
wenzelm@59058
   366
    sort_array_suffix (Real.compare o apply2 snd) max_suggs posterior;
blanchet@57364
   367
    ret (Integer.max 0 (num_facts - max_suggs)) []
blanchet@57029
   368
  end
blanchet@57029
   369
blanchet@59477
   370
val initial_k = 0
blanchet@57458
   371
blanchet@57459
   372
fun k_nearest_neighbors dffreq num_facts num_feats depss featss max_suggs visible_facts goal_feats =
blanchet@57458
   373
  let
blanchet@57458
   374
    exception EXIT of unit
blanchet@57458
   375
blanchet@57458
   376
    val ln_afreq = Math.ln (Real.fromInt num_facts)
blanchet@57458
   377
    fun tfidf feat = ln_afreq - Math.ln (Real.fromInt (Vector.sub (dffreq, feat)))
blanchet@57458
   378
blanchet@57458
   379
    val overlaps_sqr = Array.tabulate (num_facts, rpair 0.0)
blanchet@57458
   380
blanchet@57459
   381
    val feat_facts = Array.array (num_feats, [])
blanchet@57459
   382
    val _ = Vector.foldl (fn (feats, fact) =>
blanchet@57459
   383
      (List.app (map_array_at feat_facts (cons fact)) feats; fact + 1)) 0 featss
blanchet@57459
   384
blanchet@57458
   385
    fun do_feat (s, sw0) =
blanchet@57458
   386
      let
blanchet@57458
   387
        val sw = sw0 * tfidf s
blanchet@59476
   388
        val w6 = Math.pow (sw, 6.0 (* FUDGE *))
blanchet@57458
   389
blanchet@57458
   390
        fun inc_overlap j =
blanchet@57458
   391
          let val (_, ov) = Array.sub (overlaps_sqr, j) in
blanchet@57531
   392
            Array.update (overlaps_sqr, j, (j, w6 + ov))
blanchet@57458
   393
          end
blanchet@57458
   394
      in
blanchet@57458
   395
        List.app inc_overlap (Array.sub (feat_facts, s))
blanchet@57458
   396
      end
blanchet@57458
   397
blanchet@57458
   398
    val _ = List.app do_feat goal_feats
wenzelm@59058
   399
    val _ = sort_array_suffix (Real.compare o apply2 snd) num_facts overlaps_sqr
blanchet@57458
   400
    val no_recommends = Unsynchronized.ref 0
blanchet@57458
   401
    val recommends = Array.tabulate (num_facts, rpair 0.0)
blanchet@57458
   402
    val age = Unsynchronized.ref 500000000.0
blanchet@57458
   403
blanchet@57458
   404
    fun inc_recommend v j =
blanchet@57458
   405
      let val (_, ov) = Array.sub (recommends, j) in
blanchet@57458
   406
        if ov <= 0.0 then
blanchet@57458
   407
          (no_recommends := !no_recommends + 1; Array.update (recommends, j, (j, !age + ov)))
blanchet@59476
   408
        else
blanchet@59476
   409
          Array.update (recommends, j, (j, v + ov))
blanchet@57458
   410
      end
blanchet@57458
   411
blanchet@57458
   412
    val k = Unsynchronized.ref 0
blanchet@57458
   413
    fun do_k k =
blanchet@57458
   414
      if k >= num_facts then
blanchet@57458
   415
        raise EXIT ()
blanchet@57458
   416
      else
blanchet@57458
   417
        let
blanchet@57531
   418
          val deps_factor = 2.7 (* FUDGE *)
blanchet@57458
   419
          val (j, o2) = Array.sub (overlaps_sqr, num_facts - k - 1)
blanchet@57531
   420
          val _ = inc_recommend o2 j
blanchet@57458
   421
          val ds = Vector.sub (depss, j)
blanchet@57458
   422
          val l = Real.fromInt (length ds)
blanchet@57458
   423
        in
blanchet@57531
   424
          List.app (inc_recommend (deps_factor * o2 / l)) ds
blanchet@57458
   425
        end
blanchet@57458
   426
blanchet@57458
   427
    fun while1 () =
blanchet@59477
   428
      if !k = initial_k + 1 then () else (do_k (!k); k := !k + 1; while1 ())
blanchet@57458
   429
      handle EXIT () => ()
blanchet@57458
   430
blanchet@57458
   431
    fun while2 () =
blanchet@57458
   432
      if !no_recommends >= max_suggs then ()
blanchet@57458
   433
      else (do_k (!k); k := !k + 1; age := !age - 10000.0; while2 ())
blanchet@57458
   434
      handle EXIT () => ()
blanchet@57458
   435
blanchet@57458
   436
    fun ret acc at =
blanchet@57458
   437
      if at = num_facts then acc else ret (Array.sub (recommends, at) :: acc) (at + 1)
blanchet@57458
   438
  in
blanchet@57458
   439
    while1 ();
blanchet@57458
   440
    while2 ();
blanchet@57458
   441
    select_visible_facts 1000000000.0 recommends visible_facts;
wenzelm@59058
   442
    sort_array_suffix (Real.compare o apply2 snd) max_suggs recommends;
blanchet@57458
   443
    ret [] (Integer.max 0 (num_facts - max_suggs))
blanchet@57458
   444
  end
blanchet@57458
   445
blanchet@57125
   446
(* experimental *)
blanchet@57376
   447
fun external_tool tool max_suggs learns goal_feats =
blanchet@57291
   448
  let
blanchet@57297
   449
    val ser = string_of_int (serial ()) (* poor person's attempt at thread-safety *)
blanchet@57297
   450
    val ocs = TextIO.openOut ("adv_syms" ^ ser)
blanchet@57297
   451
    val ocd = TextIO.openOut ("adv_deps" ^ ser)
blanchet@57297
   452
    val ocq = TextIO.openOut ("adv_seq" ^ ser)
blanchet@57297
   453
    val occ = TextIO.openOut ("adv_conj" ^ ser)
blanchet@57296
   454
blanchet@57291
   455
    fun os oc s = TextIO.output (oc, s)
blanchet@57296
   456
blanchet@57297
   457
    fun ol _ _ _ [] = ()
blanchet@57297
   458
      | ol _ f _ [e] = f e
blanchet@57291
   459
      | ol oc f sep (h :: t) = (f h; os oc sep; ol oc f sep t)
blanchet@57296
   460
blanchet@57294
   461
    fun do_learn (name, feats, deps) =
blanchet@57357
   462
      (os ocs name; os ocs ":"; ol ocs (os ocs o quote) ", " feats; os ocs "\n";
blanchet@57297
   463
       os ocd name; os ocd ":"; ol ocd (os ocd) " " deps; os ocd "\n"; os ocq name; os ocq "\n")
blanchet@57296
   464
blanchet@57291
   465
    fun forkexec no =
blanchet@57291
   466
      let
blanchet@57291
   467
        val cmd =
blanchet@57297
   468
          "~/misc/" ^ tool ^ " adv_syms" ^ ser ^ " adv_deps" ^ ser ^ " " ^ string_of_int no ^
blanchet@57297
   469
          " adv_seq" ^ ser ^ " < adv_conj" ^ ser
blanchet@57291
   470
      in
blanchet@57291
   471
        fst (Isabelle_System.bash_output cmd)
blanchet@57291
   472
        |> space_explode " "
blanchet@57294
   473
        |> filter_out (curry (op =) "")
blanchet@57291
   474
      end
blanchet@57291
   475
  in
blanchet@57401
   476
    (List.app do_learn learns; ol occ (os occ o quote) ", " (map fst goal_feats);
blanchet@57297
   477
     TextIO.closeOut ocs; TextIO.closeOut ocd; TextIO.closeOut ocq; TextIO.closeOut occ;
blanchet@57294
   478
     forkexec max_suggs)
blanchet@57291
   479
  end
blanchet@57291
   480
blanchet@57561
   481
fun k_nearest_neighbors_ext max_suggs =
blanchet@59477
   482
  external_tool ("newknn/knn" ^ " " ^ string_of_int initial_k) max_suggs
blanchet@57561
   483
fun naive_bayes_ext max_suggs = external_tool "predict/nbayes" max_suggs
blanchet@57374
   484
blanchet@57532
   485
fun query_external ctxt algorithm max_suggs learns goal_feats =
blanchet@57432
   486
  (trace_msg ctxt (fn () => "MaSh query external " ^ commas (map fst goal_feats));
blanchet@57532
   487
   (case algorithm of
blanchet@57458
   488
     MaSh_NB_Ext => naive_bayes_ext max_suggs learns goal_feats
blanchet@57458
   489
   | MaSh_kNN_Ext => k_nearest_neighbors_ext max_suggs learns goal_feats))
blanchet@57371
   490
blanchet@57532
   491
fun query_internal ctxt algorithm num_facts num_feats (fact_names, featss, depss)
blanchet@57378
   492
    (freqs as (_, _, dffreq)) visible_facts max_suggs goal_feats int_goal_feats =
blanchet@57459
   493
  let
blanchet@57459
   494
    fun nb () =
blanchet@57459
   495
      naive_bayes freqs num_facts max_suggs visible_facts int_goal_feats
blanchet@57459
   496
      |> map fst
blanchet@57459
   497
    fun knn () =
blanchet@57459
   498
      k_nearest_neighbors dffreq num_facts num_feats depss featss max_suggs visible_facts
blanchet@57459
   499
        int_goal_feats
blanchet@57459
   500
      |> map fst
blanchet@57459
   501
  in
blanchet@57459
   502
    (trace_msg ctxt (fn () => "MaSh query internal " ^ commas (map fst goal_feats) ^ " from {" ^
blanchet@57459
   503
       elide_string 1000 (space_implode " " (Vector.foldr (op ::) [] fact_names)) ^ "}");
blanchet@57532
   504
     (case algorithm of
blanchet@57459
   505
       MaSh_NB => nb ()
blanchet@57459
   506
     | MaSh_kNN => knn ()
blanchet@57459
   507
     | MaSh_NB_kNN =>
blanchet@61322
   508
       mesh_facts I (op =) max_suggs
blanchet@57552
   509
         [(0.5 (* FUDGE *), (weight_facts_steeply (nb ()), [])),
blanchet@57552
   510
          (0.5 (* FUDGE *), (weight_facts_steeply (knn ()), []))])
blanchet@57459
   511
     |> map (curry Vector.sub fact_names))
blanchet@57459
   512
   end
blanchet@57007
   513
blanchet@57007
   514
end;
blanchet@57007
   515
blanchet@57007
   516
blanchet@57432
   517
(*** Persistent, stringly-typed state ***)
blanchet@57432
   518
blanchet@57432
   519
fun meta_char c =
blanchet@57432
   520
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse c = #")" orelse
blanchet@57432
   521
     c = #"," then
blanchet@57432
   522
    String.str c
blanchet@57432
   523
  else
blanchet@57432
   524
    (* fixed width, in case more digits follow *)
blanchet@57432
   525
    "%" ^ stringN_of_int 3 (Char.ord c)
blanchet@57432
   526
blanchet@57432
   527
fun unmeta_chars accum [] = String.implode (rev accum)
blanchet@57432
   528
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
blanchet@57432
   529
    (case Int.fromString (String.implode [d1, d2, d3]) of
blanchet@57432
   530
      SOME n => unmeta_chars (Char.chr n :: accum) cs
blanchet@57432
   531
    | NONE => "" (* error *))
blanchet@57432
   532
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
blanchet@57432
   533
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs
blanchet@57432
   534
blanchet@57432
   535
val encode_str = String.translate meta_char
blanchet@57432
   536
val decode_str = String.explode #> unmeta_chars []
blanchet@57432
   537
blanchet@57432
   538
val encode_strs = map encode_str #> space_implode " "
blanchet@57461
   539
val decode_strs = space_explode " " #> map decode_str
blanchet@50311
   540
blanchet@57005
   541
datatype proof_kind = Isar_Proof | Automatic_Proof | Isar_Proof_wegen_Prover_Flop
blanchet@50311
   542
blanchet@50311
   543
fun str_of_proof_kind Isar_Proof = "i"
blanchet@50484
   544
  | str_of_proof_kind Automatic_Proof = "a"
blanchet@50484
   545
  | str_of_proof_kind Isar_Proof_wegen_Prover_Flop = "x"
blanchet@50311
   546
blanchet@57005
   547
fun proof_kind_of_str "a" = Automatic_Proof
blanchet@50484
   548
  | proof_kind_of_str "x" = Isar_Proof_wegen_Prover_Flop
blanchet@57005
   549
  | proof_kind_of_str _ (* "i" *) = Isar_Proof
blanchet@50311
   550
blanchet@57011
   551
fun add_edge_to name parent =
blanchet@57011
   552
  Graph.default_node (parent, (Isar_Proof, [], []))
blanchet@57011
   553
  #> Graph.add_edge (parent, name)
blanchet@57011
   554
blanchet@57661
   555
fun add_node kind name parents feats deps (accum as (access_G, (fact_xtab, feat_xtab), learns)) =
blanchet@57661
   556
  let val fact_xtab' = add_to_xtab name fact_xtab in
blanchet@57661
   557
    ((Graph.new_node (name, (kind, feats, deps)) access_G
blanchet@57661
   558
      handle Graph.DUP _ => Graph.map_node name (K (kind, feats, deps)) access_G)
blanchet@57661
   559
     |> fold (add_edge_to name) parents,
blanchet@57661
   560
     (fact_xtab', fold maybe_add_to_xtab feats feat_xtab),
blanchet@57661
   561
     (name, feats, deps) :: learns)
blanchet@57661
   562
  end
blanchet@57661
   563
  handle Symtab.DUP _ => accum (* robustness (in case the state file violates the invariant) *)
blanchet@57011
   564
blanchet@50311
   565
fun try_graph ctxt when def f =
blanchet@50311
   566
  f ()
blanchet@57005
   567
  handle
blanchet@57005
   568
    Graph.CYCLES (cycle :: _) =>
blanchet@57005
   569
    (trace_msg ctxt (fn () => "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
blanchet@57005
   570
  | Graph.DUP name =>
blanchet@57005
   571
    (trace_msg ctxt (fn () => "Duplicate fact " ^ quote name ^ " when " ^ when); def)
blanchet@57005
   572
  | Graph.UNDEF name =>
blanchet@57005
   573
    (trace_msg ctxt (fn () => "Unknown fact " ^ quote name ^ " when " ^ when); def)
blanchet@57005
   574
  | exn =>
blanchet@57005
   575
    if Exn.is_interrupt exn then
wenzelm@62505
   576
      Exn.reraise exn
blanchet@57005
   577
    else
blanchet@57005
   578
      (trace_msg ctxt (fn () => "Internal error when " ^ when ^ ":\n" ^ Runtime.exn_message exn);
blanchet@57005
   579
       def)
blanchet@50311
   580
blanchet@50311
   581
fun graph_info G =
blanchet@50311
   582
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
blanchet@57006
   583
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^ " edge(s), " ^
blanchet@50311
   584
  string_of_int (length (Graph.maximals G)) ^ " maximal"
blanchet@50311
   585
blanchet@57545
   586
type ffds = string vector * int list vector * int list vector
blanchet@57545
   587
type freqs = int vector * int Inttab.table vector * int vector
blanchet@57545
   588
blanchet@53095
   589
type mash_state =
blanchet@57358
   590
  {access_G : (proof_kind * string list * string list) Graph.T,
blanchet@57374
   591
   xtabs : xtab * xtab,
blanchet@57545
   592
   ffds : ffds,
blanchet@57545
   593
   freqs : freqs,
blanchet@57365
   594
   dirty_facts : string list option}
blanchet@50311
   595
blanchet@57378
   596
val empty_xtabs = (empty_xtab, empty_xtab)
blanchet@57545
   597
val empty_ffds = (Vector.fromList [], Vector.fromList [], Vector.fromList []) : ffds
blanchet@57545
   598
val empty_freqs = (Vector.fromList [], Vector.fromList [], Vector.fromList []) : freqs
blanchet@57378
   599
blanchet@57371
   600
val empty_state =
blanchet@57371
   601
  {access_G = Graph.empty,
blanchet@57378
   602
   xtabs = empty_xtabs,
blanchet@57378
   603
   ffds = empty_ffds,
blanchet@57378
   604
   freqs = empty_freqs,
blanchet@57371
   605
   dirty_facts = SOME []} : mash_state
blanchet@57371
   606
blanchet@57545
   607
fun recompute_ffds_freqs_from_learns (learns : (string * string list * string list) list)
blanchet@57545
   608
    ((num_facts, fact_tab), (num_feats, feat_tab)) num_facts0 (fact_names0, featss0, depss0) freqs0 =
blanchet@57379
   609
  let
blanchet@57380
   610
    val fact_names = Vector.concat [fact_names0, Vector.fromList (map #1 learns)]
blanchet@57380
   611
    val featss = Vector.concat [featss0,
blanchet@57380
   612
      Vector.fromList (map (map_filter (Symtab.lookup feat_tab) o #2) learns)]
blanchet@57380
   613
    val depss = Vector.concat [depss0,
blanchet@57380
   614
      Vector.fromList (map (map_filter (Symtab.lookup fact_tab) o #3) learns)]
blanchet@57379
   615
  in
blanchet@57379
   616
    ((fact_names, featss, depss),
blanchet@57431
   617
     MaSh.learn_facts freqs0 num_facts0 num_facts num_feats depss featss)
blanchet@57379
   618
  end
blanchet@57379
   619
blanchet@57378
   620
fun reorder_learns (num_facts, fact_tab) learns =
blanchet@57378
   621
  let val ary = Array.array (num_facts, ("", [], [])) in
blanchet@57378
   622
    List.app (fn learn as (fact, _, _) =>
blanchet@57378
   623
        Array.update (ary, the (Symtab.lookup fact_tab fact), learn))
blanchet@57378
   624
      learns;
blanchet@57378
   625
    Array.foldr (op ::) [] ary
blanchet@57378
   626
  end
blanchet@57378
   627
blanchet@57380
   628
fun recompute_ffds_freqs_from_access_G access_G (xtabs as (fact_xtab, _)) =
blanchet@57378
   629
  let
blanchet@57378
   630
    val learns =
blanchet@57378
   631
      Graph.schedule (fn _ => fn (fact, (_, feats, deps)) => (fact, feats, deps)) access_G
blanchet@57378
   632
      |> reorder_learns fact_xtab
blanchet@57378
   633
  in
blanchet@57380
   634
    recompute_ffds_freqs_from_learns learns xtabs 0 empty_ffds empty_freqs
blanchet@57378
   635
  end
blanchet@50311
   636
blanchet@50311
   637
local
blanchet@50311
   638
blanchet@61321
   639
val version = "*** MaSh version 20151004 ***"
blanchet@50357
   640
blanchet@53095
   641
exception FILE_VERSION_TOO_NEW of unit
blanchet@50311
   642
blanchet@50311
   643
fun extract_node line =
blanchet@55286
   644
  (case space_explode ":" line of
blanchet@57005
   645
    [head, tail] =>
blanchet@57005
   646
    (case (space_explode " " head, map (unprefix " ") (space_explode ";" tail)) of
blanchet@57005
   647
      ([kind, name], [parents, feats, deps]) =>
blanchet@57358
   648
      SOME (proof_kind_of_str kind, decode_str name, decode_strs parents, decode_strs feats,
blanchet@57010
   649
        decode_strs deps)
blanchet@55286
   650
    | _ => NONE)
blanchet@55286
   651
  | _ => NONE)
blanchet@50311
   652
blanchet@57431
   653
fun load_state ctxt (time_state as (memory_time, _)) =
blanchet@57552
   654
  let val path = state_file () in
wenzelm@60971
   655
    (case try OS.FileSys.modTime (File.platform_path path) of
blanchet@57076
   656
      NONE => time_state
blanchet@57076
   657
    | SOME disk_time =>
wenzelm@62826
   658
      if memory_time >= disk_time then
blanchet@57076
   659
        time_state
blanchet@57076
   660
      else
blanchet@57076
   661
        (disk_time,
blanchet@57076
   662
         (case try File.read_lines path of
blanchet@57076
   663
           SOME (version' :: node_lines) =>
blanchet@57076
   664
           let
blanchet@57076
   665
             fun extract_line_and_add_node line =
blanchet@57076
   666
               (case extract_node line of
blanchet@57076
   667
                 NONE => I (* should not happen *)
blanchet@57076
   668
               | SOME (kind, name, parents, feats, deps) => add_node kind name parents feats deps)
blanchet@57011
   669
blanchet@57379
   670
             val empty_G_etc = (Graph.empty, empty_xtabs, [])
blanchet@57379
   671
blanchet@57379
   672
             val (access_G, xtabs, rev_learns) =
blanchet@57076
   673
               (case string_ord (version', version) of
blanchet@57076
   674
                 EQUAL =>
blanchet@57379
   675
                 try_graph ctxt "loading state" empty_G_etc
blanchet@57379
   676
                   (fn () => fold extract_line_and_add_node node_lines empty_G_etc)
blanchet@57552
   677
               | LESS => (remove_state_file (); empty_G_etc) (* cannot parse old file *)
blanchet@57076
   678
               | GREATER => raise FILE_VERSION_TOO_NEW ())
blanchet@57378
   679
blanchet@57380
   680
             val (ffds, freqs) =
blanchet@57380
   681
               recompute_ffds_freqs_from_learns (rev rev_learns) xtabs 0 empty_ffds empty_freqs
blanchet@57076
   682
           in
blanchet@57076
   683
             trace_msg ctxt (fn () => "Loaded fact graph (" ^ graph_info access_G ^ ")");
blanchet@57378
   684
             {access_G = access_G, xtabs = xtabs, ffds = ffds, freqs = freqs, dirty_facts = SOME []}
blanchet@57076
   685
           end
blanchet@57076
   686
         | _ => empty_state)))
blanchet@57076
   687
  end
blanchet@50311
   688
blanchet@57005
   689
fun str_of_entry (kind, name, parents, feats, deps) =
blanchet@57005
   690
  str_of_proof_kind kind ^ " " ^ encode_str name ^ ": " ^ encode_strs parents ^ "; " ^
blanchet@57358
   691
  encode_strs feats ^ "; " ^ encode_strs deps ^ "\n"
blanchet@57005
   692
blanchet@57365
   693
fun save_state _ (time_state as (_, {dirty_facts = SOME [], ...})) = time_state
blanchet@57378
   694
  | save_state ctxt (memory_time, {access_G, xtabs, ffds, freqs, dirty_facts}) =
blanchet@50311
   695
    let
blanchet@57005
   696
      fun append_entry (name, ((kind, feats, deps), (parents, _))) =
blanchet@57005
   697
        cons (kind, name, Graph.Keys.dest parents, feats, deps)
blanchet@57005
   698
blanchet@57552
   699
      val path = state_file ()
blanchet@57365
   700
      val dirty_facts' =
wenzelm@60971
   701
        (case try OS.FileSys.modTime (File.platform_path path) of
blanchet@57076
   702
          NONE => NONE
wenzelm@62826
   703
        | SOME disk_time => if disk_time <= memory_time then dirty_facts else NONE)
blanchet@50311
   704
      val (banner, entries) =
blanchet@57365
   705
        (case dirty_facts' of
blanchet@55286
   706
          SOME names => (NONE, fold (append_entry o Graph.get_entry access_G) names [])
blanchet@55286
   707
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry access_G []))
blanchet@50311
   708
    in
blanchet@57431
   709
      (case banner of SOME s => File.write path s | NONE => ();
blanchet@57431
   710
       entries |> chunk_list 500 |> List.app (File.append path o implode o map str_of_entry))
blanchet@57431
   711
      handle IO.Io _ => ();
blanchet@50311
   712
      trace_msg ctxt (fn () =>
blanchet@57005
   713
        "Saved fact graph (" ^ graph_info access_G ^
blanchet@57365
   714
        (case dirty_facts of
blanchet@57365
   715
          SOME dirty_facts => "; " ^ string_of_int (length dirty_facts) ^ " dirty fact(s)"
blanchet@57005
   716
        | _ => "") ^  ")");
blanchet@57378
   717
      (Time.now (),
blanchet@57378
   718
       {access_G = access_G, xtabs = xtabs, ffds = ffds, freqs = freqs, dirty_facts = SOME []})
blanchet@50311
   719
    end
blanchet@50311
   720
blanchet@57365
   721
val global_state = Synchronized.var "Sledgehammer_MaSh.global_state" (Time.zeroTime, empty_state)
blanchet@50311
   722
blanchet@50311
   723
in
blanchet@50311
   724
blanchet@57431
   725
fun map_state ctxt f =
blanchet@57431
   726
  Synchronized.change global_state (load_state ctxt ##> f #> save_state ctxt)
blanchet@53095
   727
  handle FILE_VERSION_TOO_NEW () => ()
blanchet@50311
   728
blanchet@57431
   729
fun peek_state ctxt =
blanchet@57431
   730
  Synchronized.change_result global_state (perhaps (try (load_state ctxt)) #> `snd)
blanchet@50311
   731
blanchet@57431
   732
fun clear_state () =
blanchet@57552
   733
  Synchronized.change global_state (fn _ => (remove_state_file (); (Time.zeroTime, empty_state)))
blanchet@50311
   734
blanchet@50311
   735
end
blanchet@50311
   736
blanchet@50311
   737
blanchet@50311
   738
(*** Isabelle helpers ***)
blanchet@50311
   739
blanchet@61321
   740
fun crude_printed_term depth t =
blanchet@61321
   741
  let
blanchet@61321
   742
    fun term _ (res, 0) = (res, 0)
blanchet@61321
   743
      | term (t $ u) (res, depth) =
blanchet@61321
   744
        let
blanchet@61321
   745
          val (res, depth) = term t (res ^ "(", depth)
blanchet@61321
   746
          val (res, depth) = term u (res ^ " ", depth)
blanchet@61321
   747
        in
blanchet@61321
   748
          (res ^ ")", depth)
blanchet@61321
   749
        end
blanchet@61321
   750
      | term (Abs (s, _, t)) (res, depth) = term t (res ^ "%" ^ s ^ ".", depth - 1)
blanchet@61321
   751
      | term (Bound n) (res, depth) = (res ^ "#" ^ string_of_int n, depth - 1)
blanchet@61321
   752
      | term (Const (s, _)) (res, depth) = (res ^ Long_Name.base_name s, depth - 1)
blanchet@61321
   753
      | term (Free (s, _)) (res, depth) = (res ^ s, depth - 1)
blanchet@61321
   754
      | term (Var ((s, _), _)) (res, depth) = (res ^ s, depth - 1)
blanchet@61321
   755
  in
blanchet@61321
   756
    fst (term t ("", depth))
blanchet@61321
   757
  end
blanchet@48378
   758
blanchet@61321
   759
fun nickname_of_thm th =
blanchet@48394
   760
  if Thm.has_name_hint th then
blanchet@48394
   761
    let val hint = Thm.get_name_hint th in
blanchet@50722
   762
      (* There must be a better way to detect local facts. *)
wenzelm@59888
   763
      (case Long_Name.dest_local hint of
wenzelm@60641
   764
        SOME suf =>
blanchet@61321
   765
        Long_Name.implode [Thm.theory_name_of_thm th, suf, crude_printed_term 50 (Thm.prop_of th)]
blanchet@55286
   766
      | NONE => hint)
blanchet@48394
   767
    end
blanchet@48394
   768
  else
blanchet@61321
   769
    crude_printed_term 100 (Thm.prop_of th)
blanchet@48378
   770
blanchet@51134
   771
fun find_suggested_facts ctxt facts =
blanchet@48330
   772
  let
blanchet@61321
   773
    fun add (fact as (_, th)) = Symtab.default (nickname_of_thm th, fact)
blanchet@51134
   774
    val tab = fold add facts Symtab.empty
blanchet@51134
   775
    fun lookup nick =
blanchet@51134
   776
      Symtab.lookup tab nick
blanchet@57006
   777
      |> tap (fn NONE => trace_msg ctxt (fn () => "Cannot find " ^ quote nick) | _ => ())
blanchet@51134
   778
  in map_filter lookup end
blanchet@48311
   779
blanchet@57404
   780
fun free_feature_of s = "f" ^ s
blanchet@57404
   781
fun thy_feature_of s = "y" ^ s
blanchet@57404
   782
fun type_feature_of s = "t" ^ s
blanchet@57404
   783
fun class_feature_of s = "s" ^ s
blanchet@57404
   784
val local_feature = "local"
blanchet@48251
   785
wenzelm@60948
   786
fun crude_thm_ord ctxt =
wenzelm@60948
   787
  let
wenzelm@60948
   788
    val ancestor_lengths =
wenzelm@60948
   789
      fold (fn thy => Symtab.update (Context.theory_name thy, length (Context.ancestors_of thy)))
wenzelm@60948
   790
        (Theory.nodes_of (Proof_Context.theory_of ctxt)) Symtab.empty
wenzelm@60948
   791
    val ancestor_length = Symtab.lookup ancestor_lengths o Context.theory_id_name
blanchet@61321
   792
wenzelm@60948
   793
    fun crude_theory_ord p =
wenzelm@60948
   794
      if Context.eq_thy_id p then EQUAL
wenzelm@60948
   795
      else if Context.proper_subthy_id p then LESS
wenzelm@60948
   796
      else if Context.proper_subthy_id (swap p) then GREATER
wenzelm@60948
   797
      else
wenzelm@60948
   798
        (case apply2 ancestor_length p of
wenzelm@60948
   799
          (SOME m, SOME n) =>
wenzelm@60948
   800
            (case int_ord (m, n) of
wenzelm@60948
   801
              EQUAL => string_ord (apply2 Context.theory_id_name p)
wenzelm@60948
   802
            | ord => ord)
wenzelm@60948
   803
        | _ => string_ord (apply2 Context.theory_id_name p))
wenzelm@60948
   804
  in
wenzelm@60948
   805
    fn p =>
wenzelm@60948
   806
      (case crude_theory_ord (apply2 Thm.theory_id_of_thm p) of
wenzelm@60948
   807
        EQUAL =>
wenzelm@60948
   808
        (* The hack below is necessary because of odd dependencies that are not reflected in the theory
wenzelm@60948
   809
           comparison. *)
blanchet@61321
   810
        let val q = apply2 nickname_of_thm p in
wenzelm@60948
   811
          (* Hack to put "xxx_def" before "xxxI" and "xxxE" *)
wenzelm@60948
   812
          (case bool_ord (apply2 (String.isSuffix "_def") (swap q)) of
wenzelm@60948
   813
            EQUAL => string_ord q
wenzelm@60948
   814
          | ord => ord)
wenzelm@60948
   815
        end
wenzelm@60948
   816
      | ord => ord)
wenzelm@60948
   817
  end;
blanchet@48324
   818
wenzelm@60948
   819
val thm_less_eq = Context.subthy_id o apply2 Thm.theory_id_of_thm
blanchet@51136
   820
fun thm_less p = thm_less_eq p andalso not (thm_less_eq (swap p))
blanchet@51136
   821
blanchet@48392
   822
val freezeT = Type.legacy_freeze_type
blanchet@48392
   823
blanchet@48392
   824
fun freeze (t $ u) = freeze t $ freeze u
blanchet@48392
   825
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
blanchet@48392
   826
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
blanchet@48392
   827
  | freeze (Const (s, T)) = Const (s, freezeT T)
blanchet@48392
   828
  | freeze (Free (s, T)) = Free (s, freezeT T)
blanchet@48392
   829
  | freeze t = t
blanchet@48392
   830
wenzelm@59621
   831
fun goal_of_thm thy = Thm.prop_of #> freeze #> Thm.global_cterm_of thy #> Goal.init
blanchet@48392
   832
blanchet@54141
   833
fun run_prover_for_mash ctxt params prover goal_name facts goal =
blanchet@48392
   834
  let
blanchet@48392
   835
    val problem =
blanchet@54141
   836
      {comment = "Goal: " ^ goal_name, state = Proof.init ctxt, goal = goal, subgoal = 1,
blanchet@62735
   837
       subgoal_count = 1, factss = [("", facts)], found_proof = I}
blanchet@48392
   838
  in
blanchet@57735
   839
    get_minimizing_prover ctxt MaSh (K ()) prover params problem
blanchet@48392
   840
  end
blanchet@48392
   841
blanchet@48326
   842
val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]
blanchet@48326
   843
blanchet@53086
   844
val pat_tvar_prefix = "_"
blanchet@53086
   845
val pat_var_prefix = "_"
blanchet@53086
   846
blanchet@53089
   847
(* try "Long_Name.base_name" for shorter names *)
blanchet@57055
   848
fun massage_long_name s = s
blanchet@53083
   849
blanchet@57006
   850
val crude_str_of_sort = space_implode ":" o map massage_long_name o subtract (op =) @{sort type}
blanchet@53086
   851
blanchet@53086
   852
fun crude_str_of_typ (Type (s, [])) = massage_long_name s
blanchet@57006
   853
  | crude_str_of_typ (Type (s, Ts)) = massage_long_name s ^ implode (map crude_str_of_typ Ts)
blanchet@53083
   854
  | crude_str_of_typ (TFree (_, S)) = crude_str_of_sort S
blanchet@53083
   855
  | crude_str_of_typ (TVar (_, S)) = crude_str_of_sort S
blanchet@53083
   856
blanchet@53128
   857
fun maybe_singleton_str _ "" = []
blanchet@53128
   858
  | maybe_singleton_str pref s = [pref ^ s]
blanchet@53128
   859
blanchet@53148
   860
val max_pat_breadth = 10 (* FUDGE *)
blanchet@50585
   861
blanchet@57406
   862
fun term_features_of ctxt thy_name term_max_depth type_max_depth ts =
blanchet@48251
   863
  let
blanchet@50392
   864
    val thy = Proof_Context.theory_of ctxt
blanchet@53082
   865
blanchet@50393
   866
    val fixes = map snd (Variable.dest_fixes ctxt)
blanchet@50392
   867
    val classes = Sign.classes_of thy
blanchet@53082
   868
blanchet@48304
   869
    fun add_classes @{sort type} = I
blanchet@50392
   870
      | add_classes S =
blanchet@50392
   871
        fold (`(Sorts.super_classes classes)
blanchet@57006
   872
          #> swap #> op ::
blanchet@57006
   873
          #> subtract (op =) @{sort type} #> map massage_long_name
blanchet@57006
   874
          #> map class_feature_of
blanchet@57404
   875
          #> union (op =)) S
blanchet@53082
   876
blanchet@53082
   877
    fun pattify_type 0 _ = []
blanchet@53082
   878
      | pattify_type _ (Type (s, [])) =
blanchet@53086
   879
        if member (op =) bad_types s then [] else [massage_long_name s]
blanchet@53082
   880
      | pattify_type depth (Type (s, U :: Ts)) =
blanchet@53082
   881
        let
blanchet@53082
   882
          val T = Type (s, Ts)
blanchet@57055
   883
          val ps = take max_pat_breadth (pattify_type depth T)
blanchet@57055
   884
          val qs = take max_pat_breadth ("" :: pattify_type (depth - 1) U)
blanchet@57006
   885
        in
blanchet@57006
   886
          map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs
blanchet@57006
   887
        end
blanchet@57552
   888
      | pattify_type _ (TFree (_, S)) = maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@57552
   889
      | pattify_type _ (TVar (_, S)) = maybe_singleton_str pat_tvar_prefix (crude_str_of_sort S)
blanchet@57006
   890
blanchet@53082
   891
    fun add_type_pat depth T =
blanchet@57404
   892
      union (op =) (map type_feature_of (pattify_type depth T))
blanchet@57006
   893
blanchet@53082
   894
    fun add_type_pats 0 _ = I
blanchet@57404
   895
      | add_type_pats depth t = add_type_pat depth t #> add_type_pats (depth - 1) t
blanchet@57006
   896
blanchet@53083
   897
    fun add_type T =
blanchet@53083
   898
      add_type_pats type_max_depth T
blanchet@53156
   899
      #> fold_atyps_sorts (add_classes o snd) T
blanchet@57006
   900
blanchet@53084
   901
    fun add_subtypes (T as Type (_, Ts)) = add_type T #> fold add_subtypes Ts
blanchet@53084
   902
      | add_subtypes T = add_type T
blanchet@53082
   903
blanchet@57055
   904
    fun pattify_term _ 0 _ = []
blanchet@57055
   905
      | pattify_term _ _ (Const (s, _)) =
blanchet@57404
   906
        if is_widely_irrelevant_const s then [] else [massage_long_name s]
blanchet@54089
   907
      | pattify_term _ _ (Free (s, T)) =
blanchet@53128
   908
        maybe_singleton_str pat_var_prefix (crude_str_of_typ T)
blanchet@53090
   909
        |> (if member (op =) fixes s then
wenzelm@59877
   910
              cons (free_feature_of (massage_long_name (Long_Name.append thy_name s)))
blanchet@53090
   911
            else
blanchet@53090
   912
              I)
blanchet@57404
   913
      | pattify_term _ _ (Var (_, T)) = maybe_singleton_str pat_var_prefix (crude_str_of_typ T)
blanchet@54089
   914
      | pattify_term Ts _ (Bound j) =
blanchet@54695
   915
        maybe_singleton_str pat_var_prefix (crude_str_of_typ (nth Ts j))
blanchet@54089
   916
      | pattify_term Ts depth (t $ u) =
blanchet@50339
   917
        let
blanchet@57055
   918
          val ps = take max_pat_breadth (pattify_term Ts depth t)
blanchet@57404
   919
          val qs = take max_pat_breadth ("" :: pattify_term Ts (depth - 1) u)
blanchet@53130
   920
        in
blanchet@57404
   921
          map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs
blanchet@53130
   922
        end
blanchet@54089
   923
      | pattify_term _ _ _ = []
blanchet@57006
   924
blanchet@57404
   925
    fun add_term_pat Ts = union (op =) oo pattify_term Ts
blanchet@57006
   926
blanchet@53130
   927
    fun add_term_pats _ 0 _ = I
blanchet@57055
   928
      | add_term_pats Ts depth t = add_term_pat Ts depth t #> add_term_pats Ts (depth - 1) t
blanchet@57006
   929
blanchet@53130
   930
    fun add_term Ts = add_term_pats Ts term_max_depth
blanchet@57006
   931
blanchet@53085
   932
    fun add_subterms Ts t =
blanchet@55286
   933
      (case strip_comb t of
blanchet@54089
   934
        (Const (s, T), args) =>
blanchet@54089
   935
        (not (is_widely_irrelevant_const s) ? add_term Ts t)
blanchet@57404
   936
        #> add_subtypes T #> fold (add_subterms Ts) args
blanchet@50857
   937
      | (head, args) =>
blanchet@48251
   938
        (case head of
blanchet@53130
   939
           Free (_, T) => add_term Ts t #> add_subtypes T
blanchet@53084
   940
         | Var (_, T) => add_subtypes T
blanchet@53085
   941
         | Abs (_, T, body) => add_subtypes T #> add_subterms (T :: Ts) body
blanchet@48251
   942
         | _ => I)
blanchet@55286
   943
        #> fold (add_subterms Ts) args)
blanchet@57006
   944
  in
blanchet@57006
   945
    fold (add_subterms []) ts []
blanchet@57006
   946
  end
blanchet@48251
   947
blanchet@53085
   948
val term_max_depth = 2
blanchet@53155
   949
val type_max_depth = 1
blanchet@48251
   950
blanchet@48251
   951
(* TODO: Generate type classes for types? *)
wenzelm@60640
   952
fun features_of ctxt thy_name (scope, _) ts =
wenzelm@60640
   953
  thy_feature_of thy_name ::
wenzelm@60640
   954
  term_features_of ctxt thy_name term_max_depth type_max_depth ts
wenzelm@60640
   955
  |> scope <> Global ? cons local_feature
blanchet@48251
   956
blanchet@57006
   957
(* Too many dependencies is a sign that a decision procedure is at work. There is not much to learn
blanchet@57006
   958
   from such proofs. *)
blanchet@50434
   959
val max_dependencies = 20
blanchet@50484
   960
blanchet@54125
   961
val prover_default_max_facts = 25
blanchet@48251
   962
blanchet@48438
   963
(* "type_definition_xxx" facts are characterized by their use of "CollectI". *)
blanchet@61321
   964
val typedef_dep = nickname_of_thm @{thm CollectI}
blanchet@57006
   965
(* Mysterious parts of the class machinery create lots of proofs that refer exclusively to
blanchet@57006
   966
   "someI_ex" (and to some internal constructions). *)
blanchet@61321
   967
val class_some_dep = nickname_of_thm @{thm someI_ex}
blanchet@48438
   968
blanchet@50828
   969
val fundef_ths =
blanchet@57006
   970
  @{thms fundef_ex1_existence fundef_ex1_uniqueness fundef_ex1_iff fundef_default_value}
blanchet@61321
   971
  |> map nickname_of_thm
blanchet@50828
   972
blanchet@48438
   973
(* "Rep_xxx_inject", "Abs_xxx_inverse", etc., are derived using these facts. *)
blanchet@48438
   974
val typedef_ths =
blanchet@57006
   975
  @{thms type_definition.Abs_inverse type_definition.Rep_inverse type_definition.Rep
blanchet@57006
   976
      type_definition.Rep_inject type_definition.Abs_inject type_definition.Rep_cases
blanchet@57006
   977
      type_definition.Abs_cases type_definition.Rep_induct type_definition.Abs_induct
blanchet@57006
   978
      type_definition.Rep_range type_definition.Abs_image}
blanchet@61321
   979
  |> map nickname_of_thm
blanchet@48438
   980
blanchet@61321
   981
fun is_size_def [dep] th =
blanchet@55642
   982
    (case first_field ".rec" dep of
blanchet@57006
   983
      SOME (pref, _) =>
blanchet@61321
   984
      (case first_field ".size" (nickname_of_thm th) of
blanchet@57006
   985
        SOME (pref', _) => pref = pref'
blanchet@57006
   986
      | NONE => false)
blanchet@57006
   987
    | NONE => false)
blanchet@61321
   988
  | is_size_def _ _ = false
blanchet@48441
   989
blanchet@51177
   990
fun trim_dependencies deps =
blanchet@50755
   991
  if length deps > max_dependencies then NONE else SOME deps
blanchet@48251
   992
blanchet@61321
   993
fun isar_dependencies_of name_tabs th =
blanchet@57306
   994
  thms_in_proof max_dependencies (SOME name_tabs) th
blanchet@57306
   995
  |> Option.map (fn deps =>
blanchet@57006
   996
    if deps = [typedef_dep] orelse deps = [class_some_dep] orelse
blanchet@57757
   997
        exists (member (op =) fundef_ths) deps orelse exists (member (op =) typedef_ths) deps orelse
blanchet@61321
   998
        is_size_def deps th then
blanchet@50755
   999
      []
blanchet@50755
  1000
    else
blanchet@57306
  1001
      deps)
blanchet@48404
  1002
blanchet@57006
  1003
fun prover_dependencies_of ctxt (params as {verbose, max_facts, ...}) prover auto_level facts
blanchet@57006
  1004
    name_tabs th =
blanchet@61321
  1005
  (case isar_dependencies_of name_tabs th of
blanchet@57306
  1006
    SOME [] => (false, [])
blanchet@57306
  1007
  | isar_deps0 =>
blanchet@48392
  1008
    let
blanchet@57306
  1009
      val isar_deps = these isar_deps0
blanchet@48392
  1010
      val thy = Proof_Context.theory_of ctxt
blanchet@48392
  1011
      val goal = goal_of_thm thy th
blanchet@61321
  1012
      val name = nickname_of_thm th
blanchet@52196
  1013
      val (_, hyp_ts, concl_t) = ATP_Util.strip_subgoal goal 1 ctxt
blanchet@51136
  1014
      val facts = facts |> filter (fn (_, th') => thm_less (th', th))
blanchet@57006
  1015
blanchet@61321
  1016
      fun nickify ((_, stature), th) = ((nickname_of_thm th, stature), th)
blanchet@57006
  1017
blanchet@61321
  1018
      fun is_dep dep (_, th) = (nickname_of_thm th = dep)
blanchet@57006
  1019
blanchet@48392
  1020
      fun add_isar_dep facts dep accum =
blanchet@48392
  1021
        if exists (is_dep dep) accum then
blanchet@48392
  1022
          accum
blanchet@55286
  1023
        else
blanchet@55286
  1024
          (case find_first (is_dep dep) facts of
blanchet@55286
  1025
            SOME ((_, status), th) => accum @ [(("", status), th)]
blanchet@57005
  1026
          | NONE => accum (* should not happen *))
blanchet@57006
  1027
blanchet@54123
  1028
      val mepo_facts =
blanchet@50484
  1029
        facts
blanchet@54095
  1030
        |> mepo_suggested_facts ctxt params (max_facts |> the_default prover_default_max_facts) NONE
blanchet@54095
  1031
             hyp_ts concl_t
blanchet@54123
  1032
      val facts =
blanchet@54123
  1033
        mepo_facts
blanchet@50754
  1034
        |> fold (add_isar_dep facts) isar_deps
blanchet@50624
  1035
        |> map nickify
blanchet@54123
  1036
      val num_isar_deps = length isar_deps
blanchet@48392
  1037
    in
blanchet@48404
  1038
      if verbose andalso auto_level = 0 then
wenzelm@58843
  1039
        writeln ("MaSh: " ^ quote prover ^ " on " ^ quote name ^ " with " ^
blanchet@57017
  1040
          string_of_int num_isar_deps ^ " + " ^ string_of_int (length facts - num_isar_deps) ^
blanchet@57017
  1041
          " facts.")
blanchet@48392
  1042
      else
blanchet@48392
  1043
        ();
blanchet@55286
  1044
      (case run_prover_for_mash ctxt params prover name facts goal of
blanchet@48392
  1045
        {outcome = NONE, used_facts, ...} =>
blanchet@48404
  1046
        (if verbose andalso auto_level = 0 then
blanchet@48392
  1047
           let val num_facts = length used_facts in
wenzelm@58843
  1048
             writeln ("Found proof with " ^ string_of_int num_facts ^ " fact" ^
blanchet@57017
  1049
               plural_s num_facts ^ ".")
blanchet@48392
  1050
           end
blanchet@48392
  1051
         else
blanchet@48392
  1052
           ();
blanchet@50754
  1053
         (true, map fst used_facts))
blanchet@55286
  1054
      | _ => (false, isar_deps))
blanchet@55286
  1055
    end)
blanchet@48251
  1056
blanchet@48251
  1057
blanchet@48251
  1058
(*** High-level communication with MaSh ***)
blanchet@48251
  1059
blanchet@51182
  1060
(* In the following functions, chunks are risers w.r.t. "thm_less_eq". *)
blanchet@51182
  1061
blanchet@61321
  1062
fun chunks_and_parents_for chunks th =
blanchet@51181
  1063
  let
blanchet@51181
  1064
    fun insert_parent new parents =
blanchet@51181
  1065
      let val parents = parents |> filter_out (fn p => thm_less_eq (p, new)) in
blanchet@57096
  1066
        parents |> forall (fn p => not (thm_less_eq (new, p))) parents ? cons new
blanchet@51181
  1067
      end
blanchet@57006
  1068
blanchet@51181
  1069
    fun rechunk seen (rest as th' :: ths) =
blanchet@51181
  1070
      if thm_less_eq (th', th) then (rev seen, rest)
blanchet@51181
  1071
      else rechunk (th' :: seen) ths
blanchet@57006
  1072
blanchet@51181
  1073
    fun do_chunk [] accum = accum
blanchet@51181
  1074
      | do_chunk (chunk as hd_chunk :: _) (chunks, parents) =
blanchet@51181
  1075
        if thm_less_eq (hd_chunk, th) then
blanchet@51181
  1076
          (chunk :: chunks, insert_parent hd_chunk parents)
blanchet@51181
  1077
        else if thm_less_eq (List.last chunk, th) then
blanchet@51181
  1078
          let val (front, back as hd_back :: _) = rechunk [] chunk in
blanchet@51181
  1079
            (front :: back :: chunks, insert_parent hd_back parents)
blanchet@51181
  1080
          end
blanchet@51181
  1081
        else
blanchet@51181
  1082
          (chunk :: chunks, parents)
blanchet@51181
  1083
  in
blanchet@51181
  1084
    fold_rev do_chunk chunks ([], [])
blanchet@51181
  1085
    |>> cons []
blanchet@61321
  1086
    ||> map nickname_of_thm
blanchet@51181
  1087
  end
blanchet@51181
  1088
blanchet@61321
  1089
fun attach_parents_to_facts _ [] = []
blanchet@61321
  1090
  | attach_parents_to_facts old_facts (facts as (_, th) :: _) =
blanchet@51182
  1091
    let
blanchet@51182
  1092
      fun do_facts _ [] = []
blanchet@51182
  1093
        | do_facts (_, parents) [fact] = [(parents, fact)]
blanchet@51182
  1094
        | do_facts (chunks, parents)
blanchet@51182
  1095
                   ((fact as (_, th)) :: (facts as (_, th') :: _)) =
blanchet@51182
  1096
          let
blanchet@51182
  1097
            val chunks = app_hd (cons th) chunks
blanchet@51182
  1098
            val chunks_and_parents' =
wenzelm@60638
  1099
              if thm_less_eq (th, th') andalso
wenzelm@60638
  1100
                Thm.theory_name_of_thm th = Thm.theory_name_of_thm th'
blanchet@61321
  1101
              then (chunks, [nickname_of_thm th])
blanchet@61321
  1102
              else chunks_and_parents_for chunks th'
blanchet@57006
  1103
          in
blanchet@57006
  1104
            (parents, fact) :: do_facts chunks_and_parents' facts
blanchet@57006
  1105
          end
blanchet@51182
  1106
    in
blanchet@51182
  1107
      old_facts @ facts
blanchet@61321
  1108
      |> do_facts (chunks_and_parents_for [[]] th)
blanchet@51182
  1109
      |> drop (length old_facts)
blanchet@51182
  1110
    end
blanchet@51177
  1111
blanchet@61318
  1112
fun maximal_wrt_graph _ [] = []
blanchet@61318
  1113
  | maximal_wrt_graph G keys =
blanchet@61318
  1114
    if can (Graph.get_node G o the_single) keys then
blanchet@61318
  1115
      keys
blanchet@61318
  1116
    else
blanchet@61318
  1117
      let
blanchet@61318
  1118
        val tab = Symtab.empty |> fold (fn name => Symtab.default (name, ())) keys
blanchet@57006
  1119
blanchet@61318
  1120
        fun insert_new seen name = not (Symtab.defined seen name) ? insert (op =) name
blanchet@57006
  1121
blanchet@61318
  1122
        fun num_keys keys = Graph.Keys.fold (K (Integer.add 1)) keys 0
blanchet@57006
  1123
blanchet@61318
  1124
        fun find_maxes _ (maxs, []) = map snd maxs
blanchet@61318
  1125
          | find_maxes seen (maxs, new :: news) =
blanchet@61318
  1126
            find_maxes (seen |> num_keys (Graph.imm_succs G new) > 1 ? Symtab.default (new, ()))
blanchet@61318
  1127
              (if Symtab.defined tab new then
blanchet@61318
  1128
                 let
blanchet@61318
  1129
                   val newp = Graph.all_preds G [new]
blanchet@61318
  1130
                   fun is_ancestor x yp = member (op =) yp x
blanchet@61318
  1131
                   val maxs = maxs |> filter (fn (_, max) => not (is_ancestor max newp))
blanchet@61318
  1132
                 in
blanchet@61318
  1133
                   if exists (is_ancestor new o fst) maxs then (maxs, news)
blanchet@61318
  1134
                   else ((newp, new) :: filter_out (fn (_, max) => is_ancestor max newp) maxs, news)
blanchet@61318
  1135
                 end
blanchet@61318
  1136
               else
blanchet@61318
  1137
                 (maxs, Graph.Keys.fold (insert_new seen) (Graph.imm_preds G new) news))
blanchet@61318
  1138
      in
blanchet@61318
  1139
        find_maxes Symtab.empty ([],
blanchet@61318
  1140
          G |> Graph.restrict (not o String.isPrefix anonymous_proof_prefix) |> Graph.maximals)
blanchet@61318
  1141
      end
blanchet@53095
  1142
blanchet@61321
  1143
fun maximal_wrt_access_graph _ [] = []
blanchet@61321
  1144
  | maximal_wrt_access_graph access_G ((fact as (_, th)) :: facts) =
wenzelm@60948
  1145
    let val thy_id = Thm.theory_id_of_thm th in
wenzelm@60948
  1146
      fact :: filter_out (fn (_, th') =>
wenzelm@60948
  1147
        Context.proper_subthy_id (Thm.theory_id_of_thm th', thy_id)) facts
blanchet@61321
  1148
      |> map (nickname_of_thm o snd)
blanchet@57460
  1149
      |> maximal_wrt_graph access_G
blanchet@57460
  1150
    end
blanchet@53095
  1151
blanchet@61321
  1152
fun is_fact_in_graph access_G = can (Graph.get_node access_G) o nickname_of_thm
blanchet@53095
  1153
blanchet@53197
  1154
val chained_feature_factor = 0.5 (* FUDGE *)
blanchet@57405
  1155
val extra_feature_factor = 0.1 (* FUDGE *)
blanchet@57405
  1156
val num_extra_feature_facts = 10 (* FUDGE *)
blanchet@53095
  1157
blanchet@57660
  1158
val max_proximity_facts = 100 (* FUDGE *)
blanchet@53095
  1159
blanchet@54060
  1160
fun find_mash_suggestions ctxt max_facts suggs facts chained raw_unknown =
blanchet@54060
  1161
  let
blanchet@54060
  1162
    val inter_fact = inter (eq_snd Thm.eq_thm_prop)
blanchet@54060
  1163
    val raw_mash = find_suggested_facts ctxt facts suggs
blanchet@54060
  1164
    val proximate = take max_proximity_facts facts
blanchet@54060
  1165
    val unknown_chained = inter_fact raw_unknown chained
blanchet@54060
  1166
    val unknown_proximate = inter_fact raw_unknown proximate
blanchet@54060
  1167
    val mess =
blanchet@54060
  1168
      [(0.9 (* FUDGE *), (map (rpair 1.0) unknown_chained, [])),
blanchet@54060
  1169
       (0.4 (* FUDGE *), (weight_facts_smoothly unknown_proximate, [])),
blanchet@54060
  1170
       (0.1 (* FUDGE *), (weight_facts_steeply raw_mash, raw_unknown))]
blanchet@57007
  1171
    val unknown = raw_unknown
blanchet@57007
  1172
      |> fold (subtract (eq_snd Thm.eq_thm_prop)) [unknown_chained, unknown_proximate]
blanchet@57006
  1173
  in
blanchet@61322
  1174
    (mesh_facts (fact_distinct (op aconv)) (eq_snd (gen_eq_thm ctxt)) max_facts mess, unknown)
blanchet@57006
  1175
  end
blanchet@53095
  1176
wenzelm@60649
  1177
fun mash_suggested_facts ctxt thy_name ({debug, ...} : params) max_suggs hyp_ts concl_t facts =
blanchet@53095
  1178
  let
blanchet@57532
  1179
    val algorithm = the_mash_algorithm ()
blanchet@57052
  1180
blanchet@57460
  1181
    val facts = facts
wenzelm@60641
  1182
      |> rev_sort_list_prefix (crude_thm_ord ctxt o apply2 snd)
blanchet@57460
  1183
        (Int.max (num_extra_feature_facts, max_proximity_facts))
blanchet@57460
  1184
blanchet@57460
  1185
    val chained = filter (fn ((_, (scope, _)), _) => scope = Chained) facts
blanchet@54085
  1186
wenzelm@60638
  1187
    fun fact_has_right_theory (_, th) = thy_name = Thm.theory_name_of_thm th
blanchet@56995
  1188
blanchet@53141
  1189
    fun chained_or_extra_features_of factor (((_, stature), th), weight) =
wenzelm@59582
  1190
      [Thm.prop_of th]
wenzelm@60640
  1191
      |> features_of ctxt (Thm.theory_name_of_thm th) stature
blanchet@57404
  1192
      |> map (rpair (weight * factor))
blanchet@54085
  1193
blanchet@57431
  1194
    val {access_G, xtabs = ((num_facts, fact_tab), (num_feats, feat_tab)), ffds, freqs, ...} =
blanchet@57431
  1195
      peek_state ctxt
blanchet@57017
  1196
wenzelm@60640
  1197
    val goal_feats0 =
wenzelm@60649
  1198
      features_of ctxt thy_name (Local, General) (concl_t :: hyp_ts)
blanchet@57460
  1199
    val chained_feats = chained
blanchet@57460
  1200
      |> map (rpair 1.0)
blanchet@57460
  1201
      |> map (chained_or_extra_features_of chained_feature_factor)
blanchet@57460
  1202
      |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@57460
  1203
    val extra_feats = facts
blanchet@57460
  1204
      |> take (Int.max (0, num_extra_feature_facts - length chained))
blanchet@57460
  1205
      |> filter fact_has_right_theory
blanchet@57460
  1206
      |> weight_facts_steeply
blanchet@57460
  1207
      |> map (chained_or_extra_features_of extra_feature_factor)
blanchet@57460
  1208
      |> rpair [] |-> fold (union (eq_fst (op =)))
blanchet@57460
  1209
blanchet@57460
  1210
    val goal_feats =
blanchet@57460
  1211
      fold (union (eq_fst (op =))) [chained_feats, extra_feats] (map (rpair 1.0) goal_feats0)
wenzelm@59058
  1212
      |> debug ? sort (Real.compare o swap o apply2 snd)
blanchet@57460
  1213
blanchet@61321
  1214
    val parents = maximal_wrt_access_graph access_G facts
blanchet@57460
  1215
    val visible_facts = map_filter (Symtab.lookup fact_tab) (Graph.all_preds access_G parents)
blanchet@57460
  1216
blanchet@57431
  1217
    val suggs =
blanchet@57532
  1218
      if algorithm = MaSh_NB_Ext orelse algorithm = MaSh_kNN_Ext then
blanchet@57460
  1219
        let
blanchet@57460
  1220
          val learns =
blanchet@57460
  1221
            Graph.schedule (fn _ => fn (fact, (_, feats, deps)) => (fact, feats, deps)) access_G
blanchet@57460
  1222
        in
blanchet@57532
  1223
          MaSh.query_external ctxt algorithm max_suggs learns goal_feats
blanchet@57460
  1224
        end
blanchet@57460
  1225
      else
blanchet@57460
  1226
        let
blanchet@57460
  1227
          val int_goal_feats =
blanchet@57460
  1228
            map_filter (fn (s, w) => Option.map (rpair w) (Symtab.lookup feat_tab s)) goal_feats
blanchet@57460
  1229
        in
blanchet@57532
  1230
          MaSh.query_internal ctxt algorithm num_facts num_feats ffds freqs visible_facts max_suggs
blanchet@57460
  1231
            goal_feats int_goal_feats
blanchet@57460
  1232
        end
blanchet@57017
  1233
blanchet@61321
  1234
    val unknown = filter_out (is_fact_in_graph access_G o snd) facts
blanchet@53095
  1235
  in
blanchet@57431
  1236
    find_mash_suggestions ctxt max_suggs suggs facts chained unknown
wenzelm@59058
  1237
    |> apply2 (map fact_of_raw_fact)
blanchet@53095
  1238
  end
blanchet@53095
  1239
wenzelm@58843
  1240
fun mash_unlearn () = (clear_state (); writeln "Reset MaSh.")
blanchet@57431
  1241
blanchet@57661
  1242
fun learn_wrt_access_graph ctxt (name, parents, feats, deps)
blanchet@57661
  1243
    (accum as (access_G, (fact_xtab, feat_xtab))) =
blanchet@53095
  1244
  let
blanchet@57371
  1245
    fun maybe_learn_from from (accum as (parents, access_G)) =
blanchet@57013
  1246
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@57371
  1247
        (from :: parents, Graph.add_edge_acyclic (from, name) access_G))
blanchet@57371
  1248
blanchet@57371
  1249
    val access_G = access_G |> Graph.default_node (name, (Isar_Proof, feats, deps))
blanchet@57371
  1250
    val (parents, access_G) = ([], access_G) |> fold maybe_learn_from parents
blanchet@57371
  1251
    val (deps, _) = ([], access_G) |> fold maybe_learn_from deps
blanchet@57371
  1252
blanchet@57661
  1253
    val fact_xtab = add_to_xtab name fact_xtab
blanchet@57371
  1254
    val feat_xtab = fold maybe_add_to_xtab feats feat_xtab
blanchet@57006
  1255
  in
blanchet@57661
  1256
    (SOME (name, parents, feats, deps), (access_G, (fact_xtab, feat_xtab)))
blanchet@57006
  1257
  end
blanchet@57661
  1258
  handle Symtab.DUP _ => (NONE, accum) (* facts sometimes have the same name, confusingly *)
blanchet@53095
  1259
blanchet@57381
  1260
fun relearn_wrt_access_graph ctxt (name, deps) access_G =
blanchet@53095
  1261
  let
blanchet@57371
  1262
    fun maybe_relearn_from from (accum as (parents, access_G)) =
blanchet@53095
  1263
      try_graph ctxt "updating graph" accum (fn () =>
blanchet@57371
  1264
        (from :: parents, Graph.add_edge_acyclic (from, name) access_G))
blanchet@57371
  1265
    val access_G =
blanchet@57371
  1266
      access_G |> Graph.map_node name (fn (_, feats, _) => (Automatic_Proof, feats, deps))
blanchet@57371
  1267
    val (deps, _) = ([], access_G) |> fold maybe_relearn_from deps
blanchet@57006
  1268
  in
blanchet@57381
  1269
    ((name, deps), access_G)
blanchet@57006
  1270
  end
blanchet@53095
  1271
blanchet@53095
  1272
fun flop_wrt_access_graph name =
blanchet@57005
  1273
  Graph.map_node name (fn (_, feats, deps) => (Isar_Proof_wegen_Prover_Flop, feats, deps))
blanchet@53095
  1274
blanchet@57273
  1275
val learn_timeout_slack = 20.0
blanchet@53095
  1276
blanchet@53095
  1277
fun launch_thread timeout task =
blanchet@53095
  1278
  let
blanchet@53095
  1279
    val hard_timeout = time_mult learn_timeout_slack timeout
blanchet@53095
  1280
    val birth_time = Time.now ()
wenzelm@62826
  1281
    val death_time = birth_time + hard_timeout
blanchet@53095
  1282
    val desc = ("Machine learner for Sledgehammer", "")
blanchet@57006
  1283
  in
wenzelm@59471
  1284
    Async_Manager_Legacy.thread MaShN birth_time death_time desc task
blanchet@57006
  1285
  end
blanchet@53095
  1286
blanchet@61318
  1287
fun anonymous_proof_name () =
blanchet@61318
  1288
  Date.fmt (anonymous_proof_prefix ^ "%Y%m%d.%H%M%S.") (Date.fromTimeLocal (Time.now ())) ^
blanchet@61318
  1289
  serial_string ()
blanchet@57013
  1290
blanchet@57431
  1291
fun mash_learn_proof ctxt ({timeout, ...} : params) t facts used_ths =
blanchet@57387
  1292
  if not (null used_ths) andalso is_mash_enabled () then
blanchet@54816
  1293
    launch_thread timeout (fn () =>
blanchet@57006
  1294
      let
blanchet@57006
  1295
        val thy = Proof_Context.theory_of ctxt
wenzelm@60640
  1296
        val feats = features_of ctxt (Context.theory_name thy) (Local, General) [t]
wenzelm@60641
  1297
        val facts = rev_sort_list_prefix (crude_thm_ord ctxt o apply2 snd) 1 facts
blanchet@57006
  1298
      in
blanchet@57431
  1299
        map_state ctxt
blanchet@57431
  1300
          (fn {access_G, xtabs as ((num_facts0, _), _), ffds, freqs, dirty_facts} =>
blanchet@57371
  1301
             let
blanchet@61321
  1302
               val parents = maximal_wrt_access_graph access_G facts
blanchet@57371
  1303
               val deps = used_ths
blanchet@61321
  1304
                 |> filter (is_fact_in_graph access_G)
blanchet@61321
  1305
                 |> map nickname_of_thm
blanchet@57431
  1306
blanchet@61318
  1307
               val name = anonymous_proof_name ()
blanchet@57431
  1308
               val (access_G', xtabs', rev_learns) =
blanchet@57431
  1309
                 add_node Automatic_Proof name parents feats deps (access_G, xtabs, [])
blanchet@57431
  1310
blanchet@57431
  1311
               val (ffds', freqs') =
blanchet@57431
  1312
                 recompute_ffds_freqs_from_learns (rev rev_learns) xtabs' num_facts0 ffds freqs
blanchet@57371
  1313
             in
blanchet@57431
  1314
               {access_G = access_G', xtabs = xtabs', ffds = ffds', freqs = freqs',
blanchet@57431
  1315
                dirty_facts = Option.map (cons name) dirty_facts}
blanchet@57371
  1316
             end);
blanchet@57006
  1317
        (true, "")
blanchet@57006
  1318
      end)
blanchet@53819
  1319
  else
blanchet@53819
  1320
    ()
blanchet@53095
  1321
blanchet@57353
  1322
fun sendback sub = Active.sendback_markup [Markup.padding_command] (sledgehammerN ^ " " ^ sub)
blanchet@48392
  1323
blanchet@48392
  1324
val commit_timeout = seconds 30.0
blanchet@48332
  1325
blanchet@50485
  1326
(* The timeout is understood in a very relaxed fashion. *)
blanchet@57431
  1327
fun mash_learn_facts ctxt (params as {debug, verbose, ...}) prover auto_level run_prover
blanchet@57431
  1328
    learn_timeout facts =
blanchet@48304
  1329
  let
blanchet@48318
  1330
    val timer = Timer.startRealTimer ()
wenzelm@62826
  1331
    fun next_commit_time () = Timer.checkRealTimer timer + commit_timeout
blanchet@57005
  1332
blanchet@57431
  1333
    val {access_G, ...} = peek_state ctxt
blanchet@61321
  1334
    val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@51177
  1335
    val no_new_facts = forall is_in_access_G facts
blanchet@48308
  1336
  in
blanchet@51177
  1337
    if no_new_facts andalso not run_prover then
blanchet@48404
  1338
      if auto_level < 2 then
blanchet@57005
  1339
        "No new " ^ (if run_prover then "automatic" else "Isar") ^ " proofs to learn." ^
blanchet@50484
  1340
        (if auto_level = 0 andalso not run_prover then
blanchet@57005
  1341
           "\n\nHint: Try " ^ sendback learn_proverN ^ " to learn from an automatic prover."
blanchet@48404
  1342
         else
blanchet@48404
  1343
           "")
blanchet@48392
  1344
      else
blanchet@48392
  1345
        ""
blanchet@48308
  1346
    else
blanchet@48304
  1347
      let
blanchet@61321
  1348
        val name_tabs = build_name_tables nickname_of_thm facts
blanchet@57005
  1349
blanchet@48439
  1350
        fun deps_of status th =
blanchet@57017
  1351
          if status = Non_Rec_Def orelse status = Rec_Def then
blanchet@48439
  1352
            SOME []
blanchet@50484
  1353
          else if run_prover then
blanchet@57005
  1354
            prover_dependencies_of ctxt params prover auto_level facts name_tabs th
blanchet@57005
  1355
            |> (fn (false, _) => NONE | (true, deps) => trim_dependencies deps)
blanchet@48404
  1356
          else
blanchet@61321
  1357
            isar_dependencies_of name_tabs th
blanchet@57005
  1358
blanchet@48669
  1359
        fun do_commit [] [] [] state = state
blanchet@57382
  1360
          | do_commit learns relearns flops
blanchet@57382
  1361
              {access_G, xtabs as ((num_facts0, _), _), ffds, freqs, dirty_facts} =
blanchet@48392
  1362
            let
blanchet@57378
  1363
              val was_empty = Graph.is_empty access_G
blanchet@57378
  1364
blanchet@57658
  1365
              val (learns, (access_G', xtabs')) =
blanchet@57381
  1366
                fold_map (learn_wrt_access_graph ctxt) learns (access_G, xtabs)
blanchet@57661
  1367
                |>> map_filter I
blanchet@57658
  1368
              val (relearns, access_G'') =
blanchet@57658
  1369
                fold_map (relearn_wrt_access_graph ctxt) relearns access_G'
blanchet@57371
  1370
blanchet@57658
  1371
              val access_G''' = access_G'' |> fold flop_wrt_access_graph flops
blanchet@57658
  1372
              val dirty_facts' =
blanchet@57365
  1373
                (case (was_empty, dirty_facts) of
blanchet@57062
  1374
                  (false, SOME names) => SOME (map #1 learns @ map #1 relearns @ names)
blanchet@55286
  1375
                | _ => NONE)
blanchet@57378
  1376
blanchet@57382
  1377
              val (ffds', freqs') =
blanchet@57382
  1378
                if null relearns then
blanchet@57382
  1379
                  recompute_ffds_freqs_from_learns
blanchet@57658
  1380
                    (map (fn (name, _, feats, deps) => (name, feats, deps)) learns) xtabs' num_facts0
blanchet@57382
  1381
                    ffds freqs
blanchet@57382
  1382
                else
blanchet@57658
  1383
                  recompute_ffds_freqs_from_access_G access_G''' xtabs'
blanchet@48404
  1384
            in
blanchet@57658
  1385
              {access_G = access_G''', xtabs = xtabs', ffds = ffds', freqs = freqs',
blanchet@57658
  1386
               dirty_facts = dirty_facts'}
blanchet@48404
  1387
            end
blanchet@57005
  1388
blanchet@50631
  1389
        fun commit last learns relearns flops =
wenzelm@58843
  1390
          (if debug andalso auto_level = 0 then writeln "Committing..." else ();
blanchet@57431
  1391
           map_state ctxt (do_commit (rev learns) relearns flops);
blanchet@48404
  1392
           if not last andalso auto_level = 0 then
blanchet@50631
  1393
             let val num_proofs = length learns + length relearns in
wenzelm@58843
  1394
               writeln ("Learned " ^ string_of_int num_proofs ^ " " ^
blanchet@57017
  1395
                 (if run_prover then "automatic" else "Isar") ^ " proof" ^
blanchet@57017
  1396
                 plural_s num_proofs ^ " in the last " ^ string_of_time commit_timeout ^ ".")
blanchet@48392
  1397
             end
blanchet@48392
  1398
           else
blanchet@48392
  1399
             ())
blanchet@57005
  1400
blanchet@51177
  1401
        fun learn_new_fact _ (accum as (_, (_, _, true))) = accum
blanchet@51177
  1402
          | learn_new_fact (parents, ((_, stature as (_, status)), th))
blanchet@57385
  1403
              (learns, (num_nontrivial, next_commit, _)) =
blanchet@48318
  1404
            let
blanchet@61321
  1405
              val name = nickname_of_thm th
wenzelm@60640
  1406
              val feats = features_of ctxt (Thm.theory_name_of_thm th) stature [Thm.prop_of th]
blanchet@57757
  1407
              val deps = these (deps_of status th)
blanchet@57385
  1408
              val num_nontrivial = num_nontrivial |> not (null deps) ? Integer.add 1
blanchet@50631
  1409
              val learns = (name, parents, feats, deps) :: learns
blanchet@50631
  1410
              val (learns, next_commit) =
wenzelm@62826
  1411
                if Timer.checkRealTimer timer > next_commit then
blanchet@50631
  1412
                  (commit false learns [] []; ([], next_commit_time ()))
blanchet@48392
  1413
                else
blanchet@50631
  1414
                  (learns, next_commit)
wenzelm@62826
  1415
              val timed_out = Timer.checkRealTimer timer > learn_timeout
blanchet@57005
  1416
            in
blanchet@57385
  1417
              (learns, (num_nontrivial, next_commit, timed_out))
blanchet@57005
  1418
            end
blanchet@57005
  1419
blanchet@57385
  1420
        val (num_new_facts, num_nontrivial) =
blanchet@51177
  1421
          if no_new_facts then
blanchet@57385
  1422
            (0, 0)
blanchet@48404
  1423
          else
blanchet@48404
  1424
            let
blanchet@57005
  1425
              val new_facts = facts
wenzelm@60641
  1426
                |> sort (crude_thm_ord ctxt o apply2 snd)
blanchet@61321
  1427
                |> attach_parents_to_facts []
blanchet@57005
  1428
                |> filter_out (is_in_access_G o snd)
blanchet@57385
  1429
              val (learns, (num_nontrivial, _, _)) =
blanchet@51177
  1430
                ([], (0, next_commit_time (), false))
blanchet@51182
  1431
                |> fold learn_new_fact new_facts
blanchet@57005
  1432
            in
blanchet@57385
  1433
              commit true learns [] []; (length new_facts, num_nontrivial)
blanchet@57005
  1434
            end
blanchet@57005
  1435
blanchet@48404
  1436
        fun relearn_old_fact _ (accum as (_, (_, _, true))) = accum
blanchet@57385
  1437
          | relearn_old_fact ((_, (_, status)), th)
blanchet@57385
  1438
              ((relearns, flops), (num_nontrivial, next_commit, _)) =
blanchet@48404
  1439
            let
blanchet@61321
  1440
              val name = nickname_of_thm th
blanchet@57385
  1441
              val (num_nontrivial, relearns, flops) =
blanchet@55286
  1442
                (case deps_of status th of
blanchet@57385
  1443
                  SOME deps => (num_nontrivial + 1, (name, deps) :: relearns, flops)
blanchet@57385
  1444
                | NONE => (num_nontrivial, relearns, name :: flops))
blanchet@50631
  1445
              val (relearns, flops, next_commit) =
wenzelm@62826
  1446
                if Timer.checkRealTimer timer > next_commit then
blanchet@57005
  1447
                  (commit false [] relearns flops; ([], [], next_commit_time ()))
blanchet@48404
  1448
                else
blanchet@50631
  1449
                  (relearns, flops, next_commit)
wenzelm@62826
  1450
              val timed_out = Timer.checkRealTimer timer > learn_timeout
blanchet@57005
  1451
            in
blanchet@57385
  1452
              ((relearns, flops), (num_nontrivial, next_commit, timed_out))
blanchet@57005
  1453
            end
blanchet@57005
  1454
blanchet@57385
  1455
        val num_nontrivial =
blanchet@51177
  1456
          if not run_prover then
blanchet@57385
  1457
            num_nontrivial
blanchet@48404
  1458
          else
blanchet@48404
  1459
            let
blanchet@48668
  1460
              val max_isar = 1000 * max_dependencies
blanchet@57005
  1461
blanchet@57005
  1462
              fun priority_of th =
wenzelm@59172
  1463
                Random.random_range 0 max_isar +
blanchet@61321
  1464
                (case try (Graph.get_node access_G) (nickname_of_thm th) of
blanchet@57062
  1465
                  SOME (Isar_Proof, _, deps) => ~100 * length deps
blanchet@57062
  1466
                | SOME (Automatic_Proof, _, _) => 2 * max_isar
blanchet@57062
  1467
                | SOME (Isar_Proof_wegen_Prover_Flop, _, _) => max_isar
blanchet@57062
  1468
                | NONE => 0)
blanchet@57005
  1469
blanchet@57005
  1470
              val old_facts = facts
blanchet@57005
  1471
                |> filter is_in_access_G
blanchet@57005
  1472
                |> map (`(priority_of o snd))
wenzelm@59058
  1473
                |> sort (int_ord o apply2 fst)
blanchet@57005
  1474
                |> map snd
blanchet@57385
  1475
              val ((relearns, flops), (num_nontrivial, _, _)) =
blanchet@57385
  1476
                (([], []), (num_nontrivial, next_commit_time (), false))
blanchet@48404
  1477
                |> fold relearn_old_fact old_facts
blanchet@57005
  1478
            in
blanchet@57385
  1479
              commit true [] relearns flops; num_nontrivial
blanchet@57005
  1480
            end
blanchet@48318
  1481
      in
blanchet@48404
  1482
        if verbose orelse auto_level < 2 then
blanchet@57385
  1483
          "Learned " ^ string_of_int num_new_facts ^ " fact" ^ plural_s num_new_facts ^ " and " ^
blanchet@57385
  1484
          string_of_int num_nontrivial ^ " nontrivial " ^
blanchet@57385
  1485
          (if run_prover then "automatic and " else "") ^ "Isar proof" ^ plural_s num_nontrivial ^
blanchet@57006
  1486
          (if verbose then " in " ^ string_of_time (Timer.checkRealTimer timer) else "") ^ "."
blanchet@48319
  1487
        else
blanchet@48319
  1488
          ""
blanchet@48318
  1489
      end
blanchet@48308
  1490
  end
blanchet@48304
  1491
blanchet@54123
  1492
fun mash_learn ctxt (params as {provers, timeout, ...}) fact_override chained run_prover =
blanchet@48316
  1493
  let
blanchet@48396
  1494
    val css = Sledgehammer_Fact.clasimpset_rule_table_of ctxt
blanchet@48395
  1495
    val ctxt = ctxt |> Config.put instantiate_inducts false
wenzelm@58919
  1496
    val facts =
wenzelm@58919
  1497
      nearly_all_facts ctxt false fact_override Keyword.empty_keywords css chained [] @{prop True}
wenzelm@60641
  1498
      |> sort (crude_thm_ord ctxt o apply2 snd o swap)
blanchet@48404
  1499
    val num_facts = length facts
blanchet@48404
  1500
    val prover = hd provers
blanchet@57006
  1501
blanchet@50484
  1502
    fun learn auto_level run_prover =
blanchet@57431
  1503
      mash_learn_facts ctxt params prover auto_level run_prover one_year facts
wenzelm@58843
  1504
      |> writeln
blanchet@48316
  1505
  in
blanchet@50484
  1506
    if run_prover then
wenzelm@58843
  1507
      (writeln ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@57017
  1508
         plural_s num_facts ^ " for automatic proofs (" ^ quote prover ^ " timeout: " ^
blanchet@57017
  1509
         string_of_time timeout ^ ").\n\nCollecting Isar proofs first...");
blanchet@50340
  1510
       learn 1 false;
wenzelm@58843
  1511
       writeln "Now collecting automatic proofs. This may take several hours. You \
blanchet@57017
  1512
         \can safely stop the learning process at any point.";
blanchet@50340
  1513
       learn 0 true)
blanchet@50340
  1514
    else
wenzelm@58843
  1515
      (writeln ("MaShing through " ^ string_of_int num_facts ^ " fact" ^
blanchet@57006
  1516
         plural_s num_facts ^ " for Isar proofs...");
blanchet@50340
  1517
       learn 0 false)
blanchet@48316
  1518
  end
blanchet@48249
  1519
blanchet@57555
  1520
fun mash_can_suggest_facts ctxt = not (Graph.is_empty (#access_G (peek_state ctxt)))
blanchet@50311
  1521
blanchet@57274
  1522
(* Generate more suggestions than requested, because some might be thrown out later for various
blanchet@57274
  1523
   reasons (e.g., duplicates). *)
blanchet@57274
  1524
fun generous_max_suggestions max_facts = 3 * max_facts div 2 + 25
blanchet@50383
  1525
blanchet@50814
  1526
val mepo_weight = 0.5
blanchet@50814
  1527
val mash_weight = 0.5
blanchet@50814
  1528
blanchet@53152
  1529
val max_facts_to_learn_before_query = 100
blanchet@53152
  1530
blanchet@57005
  1531
(* The threshold should be large enough so that MaSh does not get activated for Auto Sledgehammer
blanchet@57005
  1532
   and Try. *)
blanchet@48318
  1533
val min_secs_for_learning = 15
blanchet@48318
  1534
blanchet@57431
  1535
fun relevant_facts ctxt (params as {verbose, learn, fact_filter, timeout, ...}) prover
blanchet@57405
  1536
    max_facts ({add, only, ...} : fact_override) hyp_ts concl_t facts =
blanchet@48314
  1537
  if not (subset (op =) (the_list fact_filter, fact_filters)) then
blanchet@48314
  1538
    error ("Unknown fact filter: " ^ quote (the fact_filter) ^ ".")
blanchet@48314
  1539
  else if only then
blanchet@57150
  1540
    [("", map fact_of_raw_fact facts)]
blanchet@48321
  1541
  else if max_facts <= 0 orelse null facts then
blanchet@51010
  1542
    [("", [])]
blanchet@48288
  1543
  else
blanchet@48288
  1544
    let
wenzelm@60649
  1545
      val thy_name = Context.theory_name (Proof_Context.theory_of ctxt)
blanchet@57407
  1546
blanchet@57555
  1547
      fun maybe_launch_thread exact min_num_facts_to_learn =
wenzelm@59471
  1548
        if not (Async_Manager_Legacy.has_running_threads MaShN) andalso
blanchet@54816
  1549
           Time.toSeconds timeout >= min_secs_for_learning then
blanchet@54816
  1550
          let val timeout = time_mult learn_timeout_slack timeout in
blanchet@57405
  1551
            (if verbose then
wenzelm@58843
  1552
               writeln ("Started MaShing through " ^
blanchet@57555
  1553
                 (if exact then "" else "at least ") ^ string_of_int min_num_facts_to_learn ^
blanchet@57555
  1554
                 " fact" ^ plural_s min_num_facts_to_learn ^ " in the background.")
blanchet@57405
  1555
             else
blanchet@57405
  1556
               ());
blanchet@54816
  1557
            launch_thread timeout
blanchet@57431
  1558
              (fn () => (true, mash_learn_facts ctxt params prover 2 false timeout facts))
blanchet@48319
  1559
          end
blanchet@48318
  1560
        else
blanchet@48318
  1561
          ()
blanchet@57018
  1562
blanchet@57555
  1563
      fun please_learn () =
blanchet@57555
  1564
        let
blanchet@57555
  1565
          val {access_G, xtabs = ((num_facts0, _), _), ...} = peek_state ctxt
blanchet@61321
  1566
          val is_in_access_G = is_fact_in_graph access_G o snd
blanchet@57555
  1567
          val min_num_facts_to_learn = length facts - num_facts0
blanchet@57555
  1568
        in
blanchet@57555
  1569
          if min_num_facts_to_learn <= max_facts_to_learn_before_query then
blanchet@57555
  1570
            (case length (filter_out is_in_access_G facts) of
blanchet@57555
  1571
              0 => ()
blanchet@57555
  1572
            | num_facts_to_learn =>
blanchet@57555
  1573
              if num_facts_to_learn <= max_facts_to_learn_before_query then
blanchet@57555
  1574
                mash_learn_facts ctxt params prover 2 false timeout facts
wenzelm@58843
  1575
                |> (fn "" => () | s => writeln (MaShN ^ ": " ^ s))
blanchet@57555
  1576
              else
blanchet@57555
  1577
                maybe_launch_thread true num_facts_to_learn)
blanchet@57555
  1578
          else
blanchet@57555
  1579
            maybe_launch_thread false min_num_facts_to_learn
blanchet@57555
  1580
        end
blanchet@57555
  1581
blanchet@57555
  1582
      val mash_enabled = is_mash_enabled ()
blanchet@57555
  1583
      val _ =
blanchet@57555
  1584
        if learn andalso mash_enabled andalso fact_filter <> SOME mepoN then please_learn () else ()
blanchet@57018
  1585
blanchet@57431
  1586
      val effective_fact_filter =
blanchet@55286
  1587
        (case fact_filter of
blanchet@57431
  1588
          SOME ff => ff
blanchet@57555
  1589
        | NONE => if mash_enabled andalso mash_can_suggest_facts ctxt then meshN else mepoN)
blanchet@54143
  1590
blanchet@54143
  1591
      val unique_facts = drop_duplicate_facts facts
blanchet@48288
  1592
      val add_ths = Attrib.eval_thms ctxt add
blanchet@54143
  1593
blanchet@51004
  1594
      fun in_add (_, th) = member Thm.eq_thm_prop add_ths th
blanchet@57018
  1595
blanchet@51003
  1596
      fun add_and_take accepts =
blanchet@51003
  1597
        (case add_ths of
blanchet@51003
  1598
           [] => accepts
blanchet@57150
  1599
         | _ =>
blanchet@57150
  1600
           (unique_facts |> filter in_add |> map fact_of_raw_fact) @ (accepts |> filter_out in_add))
blanchet@48293
  1601
        |> take max_facts
blanchet@57018
  1602
blanchet@48406
  1603
      fun mepo () =
blanchet@54143
  1604
        (mepo_suggested_facts ctxt params max_facts NONE hyp_ts concl_t unique_facts
blanchet@54091
  1605
         |> weight_facts_steeply, [])
blanchet@57018
  1606
blanchet@48314
  1607
      fun mash () =
blanchet@61322
  1608
        mash_suggested_facts ctxt thy_name params (generous_max_suggestions max_facts) hyp_ts
blanchet@61322
  1609
          concl_t facts
blanchet@53140
  1610
        |>> weight_facts_steeply
blanchet@57018
  1611
blanchet@48314
  1612
      val mess =
blanchet@51003
  1613
        (* the order is important for the "case" expression below *)
blanchet@54091
  1614
        [] |> effective_fact_filter <> mepoN ? cons (mash_weight, mash)
blanchet@54091
  1615
           |> effective_fact_filter <> mashN ? cons (mepo_weight, mepo)
blanchet@54091
  1616
           |> Par_List.map (apsnd (fn f => f ()))
blanchet@61322
  1617
      val mesh =
blanchet@61322
  1618
        mesh_facts (fact_distinct (op aconv)) (eq_snd (gen_eq_thm ctxt)) max_facts mess
blanchet@61322
  1619
        |> add_and_take
blanchet@48288
  1620
    in
blanchet@55286
  1621
      (case (fact_filter, mess) of
blanchet@51024
  1622
        (NONE, [(_, (mepo, _)), (_, (mash, _))]) =>
blanchet@57658
  1623
        [(meshN, mesh),
blanchet@57658
  1624
         (mepoN, mepo |> map fst |> add_and_take),
blanchet@51010
  1625
         (mashN, mash |> map fst |> add_and_take)]
blanchet@55286
  1626
      | _ => [(effective_fact_filter, mesh)])
blanchet@48288
  1627
    end
blanchet@48288
  1628
blanchet@48248
  1629
end;