src/HOL/Tools/ATP_Manager/atp_manager.ML
author wenzelm
Thu Oct 15 00:55:29 2009 +0200 (2009-10-15 ago)
changeset 32937 34f66c9dd8a2
parent 32936 9491bec20595
child 32938 63a364ed3f8d
permissions -rw-r--r--
structure ATP_Manager: eliminated slightly odd get/set operations in favour of Unsynchronized.ref;
uniform interpretation of ATP_Manager.atps via ATP_Manager.get_atps;
wenzelm@32327
     1
(*  Title:      HOL/Tools/ATP_Manager/atp_manager.ML
wenzelm@28477
     2
    Author:     Fabian Immler, TU Muenchen
wenzelm@28477
     3
wenzelm@28571
     4
ATP threads are registered here.
wenzelm@28571
     5
Threads with the same birth-time are seen as one group.
wenzelm@28571
     6
All threads of a group are killed when one thread of it has been successful,
wenzelm@28571
     7
or after a certain time,
wenzelm@28571
     8
or when the maximum number of threads exceeds; then the oldest thread is killed.
wenzelm@28477
     9
*)
wenzelm@28477
    10
wenzelm@28477
    11
signature ATP_MANAGER =
wenzelm@28477
    12
sig
wenzelm@32937
    13
  val atps: string Unsynchronized.ref
wenzelm@32937
    14
  val get_atps: unit -> string list
wenzelm@32937
    15
  val max_atps: int Unsynchronized.ref
wenzelm@32937
    16
  val timeout: int Unsynchronized.ref
wenzelm@32937
    17
  val full_types: bool Unsynchronized.ref
wenzelm@28586
    18
  val kill: unit -> unit
wenzelm@28586
    19
  val info: unit -> unit
wenzelm@29112
    20
  val messages: int option -> unit
wenzelm@32936
    21
  val add_prover: string * ATP_Wrapper.prover -> theory -> theory
wenzelm@28484
    22
  val print_provers: theory -> unit
wenzelm@32936
    23
  val get_prover: string -> theory -> ATP_Wrapper.prover option
wenzelm@28571
    24
  val sledgehammer: string list -> Proof.state -> unit
wenzelm@28477
    25
end;
wenzelm@28477
    26
wenzelm@32936
    27
structure ATP_Manager: ATP_MANAGER =
wenzelm@28477
    28
struct
wenzelm@28477
    29
wenzelm@28586
    30
(** preferences **)
wenzelm@28586
    31
wenzelm@29112
    32
val message_store_limit = 20;
wenzelm@29112
    33
val message_display_limit = 5;
wenzelm@29112
    34
wenzelm@32937
    35
val atps = Unsynchronized.ref "e spass remote_vampire";
wenzelm@32937
    36
fun get_atps () = String.tokens (Symbol.is_ascii_blank o String.str) (! atps);
wenzelm@28586
    37
wenzelm@32740
    38
val max_atps = Unsynchronized.ref 5;   (* ~1 means infinite number of atps *)
wenzelm@32740
    39
val timeout = Unsynchronized.ref 60;
wenzelm@32740
    40
val full_types = Unsynchronized.ref false;
wenzelm@28586
    41
wenzelm@28586
    42
val _ =
wenzelm@30982
    43
  ProofGeneralPgip.add_preference Preferences.category_proof
wenzelm@28586
    44
    (Preferences.string_pref atps
wenzelm@28589
    45
      "ATP: provers" "Default automatic provers (separated by whitespace)");
wenzelm@28586
    46
wenzelm@30982
    47
val _ =
wenzelm@30982
    48
  ProofGeneralPgip.add_preference Preferences.category_proof
wenzelm@28586
    49
    (Preferences.int_pref max_atps
wenzelm@28589
    50
      "ATP: maximum number" "How many provers may run in parallel");
wenzelm@28586
    51
wenzelm@30982
    52
val _ =
wenzelm@30982
    53
  ProofGeneralPgip.add_preference Preferences.category_proof
wenzelm@28586
    54
    (Preferences.int_pref timeout
wenzelm@28589
    55
      "ATP: timeout" "ATPs will be interrupted after this time (in seconds)");
wenzelm@28586
    56
nipkow@31791
    57
val _ =
nipkow@31791
    58
  ProofGeneralPgip.add_preference Preferences.category_proof
nipkow@31791
    59
    (Preferences.bool_pref full_types
nipkow@31791
    60
      "ATP: full types" "ATPs will use full type information");
nipkow@31791
    61
wenzelm@28586
    62
wenzelm@28586
    63
wenzelm@28586
    64
(** thread management **)
wenzelm@28586
    65
wenzelm@28582
    66
(* data structures over threads *)
wenzelm@28582
    67
wenzelm@28582
    68
structure ThreadHeap = HeapFun
wenzelm@28582
    69
(
wenzelm@28582
    70
  type elem = Time.time * Thread.thread;
wenzelm@28582
    71
  fun ord ((a, _), (b, _)) = Time.compare (a, b);
wenzelm@28595
    72
);
wenzelm@28582
    73
wenzelm@31368
    74
fun lookup_thread xs = AList.lookup Thread.equal xs;
wenzelm@31368
    75
fun update_thread xs = AList.update Thread.equal xs;
wenzelm@28582
    76
wenzelm@28582
    77
wenzelm@28582
    78
(* state of thread manager *)
wenzelm@28477
    79
wenzelm@28582
    80
datatype T = State of
immler@30830
    81
 {managing_thread: Thread.thread option,
immler@30830
    82
  timeout_heap: ThreadHeap.T,
wenzelm@28582
    83
  oldest_heap: ThreadHeap.T,
wenzelm@28582
    84
  active: (Thread.thread * (Time.time * Time.time * string)) list,
wenzelm@29112
    85
  cancelling: (Thread.thread * (Time.time * Time.time * string)) list,
immler@29620
    86
  messages: string list,
immler@29620
    87
  store: string list};
wenzelm@28582
    88
immler@30830
    89
fun make_state managing_thread timeout_heap oldest_heap active cancelling messages store =
immler@30830
    90
  State {managing_thread = managing_thread, timeout_heap = timeout_heap, oldest_heap = oldest_heap,
immler@29620
    91
    active = active, cancelling = cancelling, messages = messages, store = store};
wenzelm@28582
    92
immler@30830
    93
val state = Synchronized.var "atp_manager"
immler@30830
    94
  (make_state NONE ThreadHeap.empty ThreadHeap.empty [] [] [] []);
wenzelm@28582
    95
wenzelm@31368
    96
wenzelm@29150
    97
(* unregister thread *)
wenzelm@28582
    98
immler@29620
    99
fun unregister (success, message) thread = Synchronized.change state
wenzelm@32863
   100
  (fn state as
wenzelm@32863
   101
      State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@29150
   102
    (case lookup_thread active thread of
wenzelm@29150
   103
      SOME (birthtime, _, description) =>
wenzelm@29150
   104
        let
wenzelm@29150
   105
          val (group, active') =
wenzelm@29150
   106
            if success then List.partition (fn (_, (tb, _, _)) => tb = birthtime) active
wenzelm@29150
   107
            else List.partition (fn (th, _) => Thread.equal (th, thread)) active
wenzelm@28582
   108
wenzelm@29150
   109
          val now = Time.now ()
wenzelm@29150
   110
          val cancelling' =
immler@29620
   111
            fold (fn (th, (tb, _, desc)) => update_thread (th, (tb, now, desc))) group cancelling
wenzelm@28582
   112
immler@29620
   113
          val message' = description ^ "\n" ^ message ^
immler@29596
   114
            (if length group <= 1 then ""
immler@29596
   115
             else "\nInterrupted " ^ string_of_int (length group - 1) ^ " other group members")
immler@29620
   116
          val store' = message' ::
immler@29620
   117
            (if length store <= message_store_limit then store
immler@29620
   118
             else #1 (chop message_store_limit store))
immler@30830
   119
        in make_state
immler@30830
   120
          managing_thread timeout_heap oldest_heap active' cancelling' (message' :: messages) store'
immler@30830
   121
        end
wenzelm@30800
   122
    | NONE => state));
wenzelm@28582
   123
wenzelm@28582
   124
wenzelm@28595
   125
(* kill excessive atp threads *)
wenzelm@28595
   126
wenzelm@28595
   127
fun excessive_atps active =
wenzelm@32937
   128
  let val max = ! max_atps
wenzelm@28595
   129
  in length active > max andalso max > ~1 end;
wenzelm@28595
   130
wenzelm@28595
   131
local
wenzelm@28595
   132
wenzelm@28595
   133
fun kill_oldest () =
wenzelm@28595
   134
  let exception Unchanged in
wenzelm@29112
   135
    Synchronized.change_result state
immler@30830
   136
      (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@28595
   137
        if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
wenzelm@28595
   138
        then raise Unchanged
wenzelm@28595
   139
        else
wenzelm@28595
   140
          let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
immler@30830
   141
          in (oldest_thread,
immler@30830
   142
          make_state managing_thread timeout_heap oldest_heap' active cancelling messages store) end)
immler@29620
   143
      |> unregister (false, "Interrupted (maximum number of ATPs exceeded)")
wenzelm@28595
   144
    handle Unchanged => ()
wenzelm@28595
   145
  end;
wenzelm@28595
   146
wenzelm@28595
   147
in
wenzelm@28595
   148
wenzelm@28595
   149
fun kill_excessive () =
wenzelm@28595
   150
  let val State {active, ...} = Synchronized.value state
wenzelm@28595
   151
  in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
wenzelm@28595
   152
wenzelm@28595
   153
end;
wenzelm@28595
   154
immler@29620
   155
fun print_new_messages () =
immler@29620
   156
  let val to_print = Synchronized.change_result state
immler@30830
   157
    (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
immler@30830
   158
      (messages, make_state managing_thread timeout_heap oldest_heap active cancelling [] store))
wenzelm@30800
   159
  in
wenzelm@30800
   160
    if null to_print then ()
wenzelm@30800
   161
    else priority ("Sledgehammer: " ^ space_implode "\n\n" to_print)
wenzelm@30800
   162
  end;
immler@29620
   163
wenzelm@28595
   164
wenzelm@30800
   165
(* start a watching thread -- only one may exist *)
wenzelm@28582
   166
immler@30830
   167
fun check_thread_manager () = Synchronized.change state
immler@30830
   168
  (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
immler@30830
   169
    if (case managing_thread of SOME thread => Thread.isActive thread | NONE => false)
immler@30830
   170
    then make_state managing_thread timeout_heap oldest_heap active cancelling messages store
immler@30830
   171
    else let val managing_thread = SOME (SimpleThread.fork false (fn () =>
immler@30830
   172
      let
immler@30830
   173
        val min_wait_time = Time.fromMilliseconds 300
immler@30830
   174
        val max_wait_time = Time.fromSeconds 10
wenzelm@28582
   175
immler@30830
   176
        (* wait for next thread to cancel, or maximum*)
immler@30830
   177
        fun time_limit (State {timeout_heap, ...}) =
immler@30830
   178
          (case try ThreadHeap.min timeout_heap of
immler@30830
   179
            NONE => SOME (Time.+ (Time.now (), max_wait_time))
immler@30830
   180
          | SOME (time, _) => SOME time)
wenzelm@28582
   181
immler@30830
   182
        (* action: find threads whose timeout is reached, and interrupt cancelling threads *)
immler@30830
   183
        fun action (State {managing_thread, timeout_heap, oldest_heap, active, cancelling,
immler@30830
   184
                           messages, store}) =
immler@30830
   185
          let val (timeout_threads, timeout_heap') =
immler@30830
   186
            ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
immler@30830
   187
          in
immler@30830
   188
            if null timeout_threads andalso null cancelling andalso not (excessive_atps active)
immler@30830
   189
            then NONE
immler@30830
   190
            else
immler@30830
   191
              let
immler@30830
   192
                val _ = List.app (SimpleThread.interrupt o #1) cancelling
immler@30830
   193
                val cancelling' = filter (Thread.isActive o #1) cancelling
immler@30830
   194
                val state' = make_state
immler@30830
   195
                  managing_thread timeout_heap' oldest_heap active cancelling' messages store
immler@30830
   196
              in SOME (map #2 timeout_threads, state') end
immler@30830
   197
          end
immler@30830
   198
      in
immler@30830
   199
        while Synchronized.change_result state
immler@30830
   200
          (fn st as
immler@30830
   201
            State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
immler@30830
   202
            if (null active) andalso (null cancelling) andalso (null messages)
immler@30830
   203
            then (false, make_state NONE timeout_heap oldest_heap active cancelling messages store)
immler@30830
   204
            else (true, st))
immler@30830
   205
        do
immler@30830
   206
          (Synchronized.timed_access state time_limit action
immler@30830
   207
            |> these
immler@30830
   208
            |> List.app (unregister (false, "Interrupted (reached timeout)"));
immler@30830
   209
            kill_excessive ();
immler@30830
   210
            print_new_messages ();
immler@30830
   211
            (*give threads time to respond to interrupt*)
immler@30830
   212
            OS.Process.sleep min_wait_time)
immler@30830
   213
      end))
immler@30830
   214
    in make_state managing_thread timeout_heap oldest_heap active cancelling messages store end);
wenzelm@28582
   215
wenzelm@28582
   216
wenzelm@28582
   217
(* thread is registered here by sledgehammer *)
wenzelm@28477
   218
wenzelm@28582
   219
fun register birthtime deadtime (thread, desc) =
immler@30798
   220
 (Synchronized.change state
immler@30830
   221
    (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@29112
   222
      let
wenzelm@29112
   223
        val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
wenzelm@29112
   224
        val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
wenzelm@29112
   225
        val active' = update_thread (thread, (birthtime, deadtime, desc)) active
immler@30830
   226
      in make_state managing_thread timeout_heap' oldest_heap' active' cancelling messages store end);
immler@30798
   227
  check_thread_manager ());
wenzelm@28477
   228
wenzelm@28477
   229
wenzelm@28586
   230
wenzelm@28586
   231
(** user commands **)
wenzelm@28582
   232
wenzelm@28586
   233
(* kill: move all threads to cancelling *)
wenzelm@28586
   234
wenzelm@28586
   235
fun kill () = Synchronized.change state
immler@30830
   236
  (fn State {managing_thread, timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@28582
   237
    let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
immler@30830
   238
    in make_state
immler@30830
   239
      managing_thread timeout_heap oldest_heap [] (formerly_active @ cancelling) messages store
immler@30830
   240
    end);
wenzelm@28582
   241
wenzelm@28582
   242
wenzelm@29112
   243
(* ATP info *)
wenzelm@28582
   244
wenzelm@28582
   245
fun info () =
wenzelm@28582
   246
  let
wenzelm@29112
   247
    val State {active, cancelling, ...} = Synchronized.value state
wenzelm@29112
   248
wenzelm@28571
   249
    fun running_info (_, (birth_time, dead_time, desc)) = "Running: "
wenzelm@28589
   250
        ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), birth_time))
wenzelm@28477
   251
        ^ " s  --  "
wenzelm@28589
   252
        ^ (string_of_int o Time.toSeconds) (Time.- (dead_time, Time.now ()))
wenzelm@28571
   253
        ^ " s to live:\n" ^ desc
wenzelm@28571
   254
    fun cancelling_info (_, (_, dead_time, desc)) = "Trying to interrupt thread since "
wenzelm@28586
   255
        ^ (string_of_int o Time.toSeconds) (Time.- (Time.now (), dead_time))
wenzelm@28571
   256
        ^ " s:\n" ^ desc
wenzelm@29112
   257
wenzelm@28589
   258
    val running =
wenzelm@28589
   259
      if null active then "No ATPs running."
wenzelm@28589
   260
      else space_implode "\n\n" ("Running ATPs:" :: map running_info active)
wenzelm@28589
   261
    val interrupting =
wenzelm@28589
   262
      if null cancelling then ""
wenzelm@28589
   263
      else space_implode "\n\n"
wenzelm@28589
   264
        ("Trying to interrupt the following ATPs:" :: map cancelling_info cancelling)
wenzelm@29112
   265
wenzelm@28582
   266
  in writeln (running ^ "\n" ^ interrupting) end;
wenzelm@28582
   267
wenzelm@29112
   268
fun messages opt_limit =
wenzelm@29112
   269
  let
wenzelm@29112
   270
    val limit = the_default message_display_limit opt_limit;
immler@29620
   271
    val State {store = msgs, ...} = Synchronized.value state
wenzelm@29112
   272
    val header = "Recent ATP messages" ^
wenzelm@29112
   273
      (if length msgs <= limit then ":" else " (" ^ string_of_int limit ^ " displayed):");
wenzelm@29116
   274
  in writeln (space_implode "\n\n" (header :: #1 (chop limit msgs))) end;
wenzelm@29112
   275
wenzelm@28582
   276
wenzelm@28477
   277
wenzelm@28586
   278
(** The Sledgehammer **)
wenzelm@28477
   279
wenzelm@28582
   280
(* named provers *)
wenzelm@28484
   281
wenzelm@28582
   282
fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
wenzelm@28477
   283
wenzelm@28582
   284
structure Provers = TheoryDataFun
wenzelm@28582
   285
(
wenzelm@32936
   286
  type T = (ATP_Wrapper.prover * stamp) Symtab.table
wenzelm@28582
   287
  val empty = Symtab.empty
wenzelm@28582
   288
  val copy = I
wenzelm@28582
   289
  val extend = I
wenzelm@28582
   290
  fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
wenzelm@28589
   291
    handle Symtab.DUP dup => err_dup_prover dup
wenzelm@28582
   292
);
wenzelm@28484
   293
boehmes@32864
   294
fun add_prover (name, prover) thy =
wenzelm@28595
   295
  Provers.map (Symtab.update_new (name, (prover, stamp ()))) thy
wenzelm@28582
   296
    handle Symtab.DUP dup => err_dup_prover dup;
wenzelm@28582
   297
wenzelm@28582
   298
fun print_provers thy = Pretty.writeln
wenzelm@28582
   299
  (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
wenzelm@28571
   300
wenzelm@32863
   301
fun get_prover name thy =
wenzelm@32863
   302
  (case Symtab.lookup (Provers.get thy) name of
wenzelm@32863
   303
    NONE => NONE
wenzelm@32863
   304
  | SOME (prover, _) => SOME prover);
wenzelm@32863
   305
wenzelm@28586
   306
wenzelm@28595
   307
(* start prover thread *)
wenzelm@28484
   308
wenzelm@28595
   309
fun start_prover name birthtime deadtime i proof_state =
immler@31037
   310
  (case get_prover name (Proof.theory_of proof_state) of
wenzelm@28595
   311
    NONE => warning ("Unknown external prover: " ^ quote name)
immler@31037
   312
  | SOME prover =>
wenzelm@28595
   313
      let
wenzelm@28595
   314
        val (ctxt, (_, goal)) = Proof.get_goal proof_state
wenzelm@28595
   315
        val desc =
wenzelm@28595
   316
          "external prover " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
wenzelm@28595
   317
            Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i))
wenzelm@28595
   318
        val _ = SimpleThread.fork true (fn () =>
wenzelm@28595
   319
          let
wenzelm@28595
   320
            val _ = register birthtime deadtime (Thread.self (), desc)
wenzelm@32937
   321
            val problem =
wenzelm@32937
   322
              ATP_Wrapper.atp_problem_of_goal (! full_types) i (Proof.get_goal proof_state)
immler@31037
   323
            val result =
wenzelm@32936
   324
              let val ATP_Wrapper.Prover_Result {success, message, ...} =
wenzelm@32937
   325
                prover problem (! timeout)
immler@31037
   326
              in (success, message) end
wenzelm@32937
   327
              handle ResHolClause.TOO_TRIVIAL =>   (* FIXME !? *)
wenzelm@32937
   328
                  (true, "Empty clause: Try this command: " ^
wenzelm@32937
   329
                    Markup.markup Markup.sendback "apply metis")
wenzelm@32937
   330
                | ERROR msg => (false, "Error: " ^ msg)
immler@29620
   331
            val _ = unregister result (Thread.self ())
wenzelm@28595
   332
          in () end handle Interrupt => ())
wenzelm@28595
   333
      in () end);
wenzelm@28582
   334
wenzelm@28582
   335
wenzelm@28582
   336
(* sledghammer for first subgoal *)
wenzelm@28582
   337
wenzelm@28582
   338
fun sledgehammer names proof_state =
wenzelm@28582
   339
  let
wenzelm@32937
   340
    val provers = if null names then get_atps () else names
wenzelm@28582
   341
    val birthtime = Time.now ()
wenzelm@32937
   342
    val deadtime = Time.+ (birthtime, Time.fromSeconds (! timeout))
wenzelm@28595
   343
  in List.app (fn name => start_prover name birthtime deadtime 1 proof_state) provers end;
wenzelm@28582
   344
wenzelm@28582
   345
wenzelm@28586
   346
wenzelm@28586
   347
(** Isar command syntax **)
wenzelm@28582
   348
wenzelm@28582
   349
local structure K = OuterKeyword and P = OuterParse in
wenzelm@28582
   350
wenzelm@28582
   351
val _ =
wenzelm@28582
   352
  OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
wenzelm@28586
   353
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
wenzelm@28582
   354
wenzelm@28582
   355
val _ =
wenzelm@28582
   356
  OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
wenzelm@28582
   357
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
wenzelm@28582
   358
wenzelm@28582
   359
val _ =
wenzelm@29112
   360
  OuterSyntax.improper_command "atp_messages" "print recent messages issued by managed provers" K.diag
wenzelm@29112
   361
    (Scan.option (P.$$$ "(" |-- P.nat --| P.$$$ ")") >>
wenzelm@29112
   362
      (fn limit => Toplevel.no_timing o Toplevel.imperative (fn () => messages limit)));
wenzelm@29112
   363
wenzelm@29112
   364
val _ =
wenzelm@28582
   365
  OuterSyntax.improper_command "print_atps" "print external provers" K.diag
wenzelm@28582
   366
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
wenzelm@28582
   367
      Toplevel.keep (print_provers o Toplevel.theory_of)));
wenzelm@28582
   368
wenzelm@28582
   369
val _ =
wenzelm@28582
   370
  OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
wenzelm@28582
   371
    (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
wenzelm@30800
   372
      Toplevel.keep (sledgehammer names o Toplevel.proof_of)));
wenzelm@28582
   373
wenzelm@28582
   374
end;
wenzelm@28582
   375
wenzelm@28582
   376
end;
immler@30537
   377