src/HOL/Tools/atp_manager.ML
author wenzelm
Mon Mar 30 21:42:12 2009 +0200 (2009-03-30 ago)
changeset 30800 95cbadcd47fc
parent 30798 36b41d297d65
child 30830 263064c4d0c3
permissions -rw-r--r--
tuned spacing and formatting;
wenzelm@28477
     1
(*  Title:      HOL/Tools/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@28586
    13
  val get_atps: unit -> string
wenzelm@28477
    14
  val set_atps: string -> unit
wenzelm@28586
    15
  val get_max_atps: unit -> int
wenzelm@28586
    16
  val set_max_atps: int -> unit
wenzelm@28586
    17
  val get_timeout: unit -> int
wenzelm@28477
    18
  val set_timeout: int -> unit
wenzelm@28586
    19
  val kill: unit -> unit
wenzelm@28586
    20
  val info: unit -> unit
wenzelm@29112
    21
  val messages: int option -> unit
wenzelm@30800
    22
  type prover = int -> int -> Proof.context * (thm list * thm) -> bool * string
wenzelm@28595
    23
  val add_prover: string -> prover -> theory -> theory
wenzelm@28484
    24
  val print_provers: theory -> unit
wenzelm@28571
    25
  val sledgehammer: string list -> Proof.state -> unit
wenzelm@28477
    26
end;
wenzelm@28477
    27
wenzelm@28586
    28
structure AtpManager: ATP_MANAGER =
wenzelm@28477
    29
struct
wenzelm@28477
    30
wenzelm@28586
    31
(** preferences **)
wenzelm@28586
    32
wenzelm@29112
    33
val message_store_limit = 20;
wenzelm@29112
    34
val message_display_limit = 5;
wenzelm@29112
    35
wenzelm@28586
    36
local
wenzelm@28586
    37
immler@29598
    38
val atps = ref "e remote_vampire";
wenzelm@28586
    39
val max_atps = ref 5;   (* ~1 means infinite number of atps *)
immler@29784
    40
val timeout = ref 60;
wenzelm@28586
    41
wenzelm@28586
    42
in
wenzelm@28586
    43
wenzelm@28586
    44
fun get_atps () = CRITICAL (fn () => ! atps);
wenzelm@28586
    45
fun set_atps str = CRITICAL (fn () => atps := str);
wenzelm@28586
    46
wenzelm@28586
    47
fun get_max_atps () = CRITICAL (fn () => ! max_atps);
wenzelm@28586
    48
fun set_max_atps number = CRITICAL (fn () => max_atps := number);
wenzelm@28586
    49
wenzelm@28586
    50
fun get_timeout () = CRITICAL (fn () => ! timeout);
wenzelm@28586
    51
fun set_timeout time = CRITICAL (fn () => timeout := time);
wenzelm@28586
    52
wenzelm@28586
    53
val _ =
wenzelm@28586
    54
  ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    55
    (Preferences.string_pref atps
wenzelm@28589
    56
      "ATP: provers" "Default automatic provers (separated by whitespace)");
wenzelm@28586
    57
wenzelm@28586
    58
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    59
    (Preferences.int_pref max_atps
wenzelm@28589
    60
      "ATP: maximum number" "How many provers may run in parallel");
wenzelm@28586
    61
wenzelm@28586
    62
val _ = ProofGeneralPgip.add_preference "Proof"
wenzelm@28586
    63
    (Preferences.int_pref timeout
wenzelm@28589
    64
      "ATP: timeout" "ATPs will be interrupted after this time (in seconds)");
wenzelm@28586
    65
wenzelm@28586
    66
end;
wenzelm@28586
    67
wenzelm@28586
    68
wenzelm@28586
    69
wenzelm@28586
    70
(** thread management **)
wenzelm@28586
    71
wenzelm@28582
    72
(* data structures over threads *)
wenzelm@28582
    73
wenzelm@28582
    74
structure ThreadHeap = HeapFun
wenzelm@28582
    75
(
wenzelm@28582
    76
  type elem = Time.time * Thread.thread;
wenzelm@28582
    77
  fun ord ((a, _), (b, _)) = Time.compare (a, b);
wenzelm@28595
    78
);
wenzelm@28582
    79
wenzelm@28582
    80
val lookup_thread = AList.lookup Thread.equal;
wenzelm@28582
    81
val delete_thread = AList.delete Thread.equal;
wenzelm@28582
    82
val update_thread = AList.update Thread.equal;
wenzelm@28582
    83
wenzelm@28582
    84
wenzelm@28582
    85
(* state of thread manager *)
wenzelm@28477
    86
wenzelm@28582
    87
datatype T = State of
wenzelm@28582
    88
 {timeout_heap: ThreadHeap.T,
wenzelm@28582
    89
  oldest_heap: ThreadHeap.T,
wenzelm@28582
    90
  active: (Thread.thread * (Time.time * Time.time * string)) list,
wenzelm@29112
    91
  cancelling: (Thread.thread * (Time.time * Time.time * string)) list,
immler@29620
    92
  messages: string list,
immler@29620
    93
  store: string list};
wenzelm@28582
    94
immler@29620
    95
fun make_state timeout_heap oldest_heap active cancelling messages store =
wenzelm@28582
    96
  State {timeout_heap = timeout_heap, oldest_heap = oldest_heap,
immler@29620
    97
    active = active, cancelling = cancelling, messages = messages, store = store};
wenzelm@28582
    98
immler@30798
    99
fun empty_state state =
immler@30798
   100
  let
immler@30798
   101
    val State {active = active, cancelling = cancelling, messages = messages, ...} =
immler@30798
   102
      Synchronized.value state
immler@30798
   103
  in (null active) andalso (null cancelling) andalso (null messages) end;
immler@30798
   104
immler@29620
   105
val state = Synchronized.var "atp_manager" (make_state ThreadHeap.empty ThreadHeap.empty [] [] [] []);
wenzelm@28477
   106
wenzelm@28582
   107
wenzelm@28586
   108
(* the managing thread *)
wenzelm@28582
   109
wenzelm@28582
   110
(*watches over running threads and interrupts them if required*)
wenzelm@28582
   111
val managing_thread = ref (NONE: Thread.thread option);
wenzelm@28477
   112
wenzelm@28582
   113
wenzelm@29150
   114
(* unregister thread *)
wenzelm@28582
   115
immler@29620
   116
fun unregister (success, message) thread = Synchronized.change state
immler@29620
   117
  (fn state as State {timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@29150
   118
    (case lookup_thread active thread of
wenzelm@29150
   119
      SOME (birthtime, _, description) =>
wenzelm@29150
   120
        let
wenzelm@29150
   121
          val (group, active') =
wenzelm@29150
   122
            if success then List.partition (fn (_, (tb, _, _)) => tb = birthtime) active
wenzelm@29150
   123
            else List.partition (fn (th, _) => Thread.equal (th, thread)) active
wenzelm@28582
   124
wenzelm@29150
   125
          val now = Time.now ()
wenzelm@29150
   126
          val cancelling' =
immler@29620
   127
            fold (fn (th, (tb, _, desc)) => update_thread (th, (tb, now, desc))) group cancelling
wenzelm@28582
   128
immler@29620
   129
          val message' = description ^ "\n" ^ message ^
immler@29596
   130
            (if length group <= 1 then ""
immler@29596
   131
             else "\nInterrupted " ^ string_of_int (length group - 1) ^ " other group members")
immler@29620
   132
          val store' = message' ::
immler@29620
   133
            (if length store <= message_store_limit then store
immler@29620
   134
             else #1 (chop message_store_limit store))
immler@29620
   135
        in make_state timeout_heap oldest_heap active' cancelling' (message' :: messages) store' end
wenzelm@30800
   136
    | NONE => state));
wenzelm@28582
   137
wenzelm@28582
   138
wenzelm@28595
   139
(* kill excessive atp threads *)
wenzelm@28595
   140
wenzelm@28595
   141
fun excessive_atps active =
wenzelm@28595
   142
  let val max = get_max_atps ()
wenzelm@28595
   143
  in length active > max andalso max > ~1 end;
wenzelm@28595
   144
wenzelm@28595
   145
local
wenzelm@28595
   146
wenzelm@28595
   147
fun kill_oldest () =
wenzelm@28595
   148
  let exception Unchanged in
wenzelm@29112
   149
    Synchronized.change_result state
immler@29620
   150
      (fn State {timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@28595
   151
        if ThreadHeap.is_empty oldest_heap orelse not (excessive_atps active)
wenzelm@28595
   152
        then raise Unchanged
wenzelm@28595
   153
        else
wenzelm@28595
   154
          let val ((_, oldest_thread), oldest_heap') = ThreadHeap.min_elem oldest_heap
immler@29620
   155
          in (oldest_thread, make_state timeout_heap oldest_heap' active cancelling messages store) end)
immler@29620
   156
      |> unregister (false, "Interrupted (maximum number of ATPs exceeded)")
wenzelm@28595
   157
    handle Unchanged => ()
wenzelm@28595
   158
  end;
wenzelm@28595
   159
wenzelm@28595
   160
in
wenzelm@28595
   161
wenzelm@28595
   162
fun kill_excessive () =
wenzelm@28595
   163
  let val State {active, ...} = Synchronized.value state
wenzelm@28595
   164
  in if excessive_atps active then (kill_oldest (); kill_excessive ()) else () end;
wenzelm@28595
   165
wenzelm@28595
   166
end;
wenzelm@28595
   167
immler@29620
   168
fun print_new_messages () =
immler@29620
   169
  let val to_print = Synchronized.change_result state
immler@29620
   170
    (fn State {timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@30800
   171
      (messages, make_state timeout_heap oldest_heap active cancelling [] store))
wenzelm@30800
   172
  in
wenzelm@30800
   173
    if null to_print then ()
wenzelm@30800
   174
    else priority ("Sledgehammer: " ^ space_implode "\n\n" to_print)
wenzelm@30800
   175
  end;
immler@29620
   176
wenzelm@28595
   177
wenzelm@30800
   178
(* start a watching thread -- only one may exist *)
wenzelm@28582
   179
wenzelm@28586
   180
fun check_thread_manager () = CRITICAL (fn () =>
wenzelm@28582
   181
  if (case ! managing_thread of SOME thread => Thread.isActive thread | NONE => false)
wenzelm@28582
   182
  then () else managing_thread := SOME (SimpleThread.fork false (fn () =>
wenzelm@28571
   183
    let
wenzelm@28582
   184
      val min_wait_time = Time.fromMilliseconds 300
wenzelm@28582
   185
      val max_wait_time = Time.fromSeconds 10
wenzelm@28582
   186
wenzelm@28582
   187
      (* wait for next thread to cancel, or maximum*)
wenzelm@28582
   188
      fun time_limit (State {timeout_heap, ...}) =
wenzelm@28582
   189
        (case try ThreadHeap.min timeout_heap of
wenzelm@28582
   190
          NONE => SOME (Time.+ (Time.now (), max_wait_time))
wenzelm@28582
   191
        | SOME (time, _) => SOME time)
wenzelm@28582
   192
immler@29620
   193
      (* action: find threads whose timeout is reached, and interrupt cancelling threads *)
immler@29620
   194
      fun action (State {timeout_heap, oldest_heap, active, cancelling, messages, store}) =
wenzelm@28582
   195
        let val (timeout_threads, timeout_heap') =
wenzelm@28582
   196
          ThreadHeap.upto (Time.now (), Thread.self ()) timeout_heap
wenzelm@28582
   197
        in
wenzelm@28595
   198
          if null timeout_threads andalso null cancelling andalso not (excessive_atps active)
wenzelm@28595
   199
          then NONE
wenzelm@28582
   200
          else
wenzelm@28582
   201
            let
wenzelm@28582
   202
              val _ = List.app (SimpleThread.interrupt o #1) cancelling
wenzelm@28582
   203
              val cancelling' = filter (Thread.isActive o #1) cancelling
immler@29620
   204
              val state' = make_state timeout_heap' oldest_heap active cancelling' messages store
wenzelm@28582
   205
            in SOME (map #2 timeout_threads, state') end
wenzelm@28582
   206
        end
wenzelm@28582
   207
    in
wenzelm@30800
   208
      while not (empty_state state) do
wenzelm@28595
   209
       (Synchronized.timed_access state time_limit action
wenzelm@28582
   210
        |> these
immler@29620
   211
        |> List.app (unregister (false, "Interrupted (reached timeout)"));
wenzelm@28595
   212
        kill_excessive ();
immler@29620
   213
        print_new_messages ();
wenzelm@28595
   214
        (*give threads time to respond to interrupt*)
wenzelm@28571
   215
        OS.Process.sleep min_wait_time)
wenzelm@28586
   216
    end)));
wenzelm@28582
   217
wenzelm@28582
   218
wenzelm@28582
   219
(* thread is registered here by sledgehammer *)
wenzelm@28477
   220
wenzelm@28582
   221
fun register birthtime deadtime (thread, desc) =
immler@30798
   222
 (Synchronized.change state
immler@29620
   223
    (fn State {timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@29112
   224
      let
wenzelm@29112
   225
        val timeout_heap' = ThreadHeap.insert (deadtime, thread) timeout_heap
wenzelm@29112
   226
        val oldest_heap' = ThreadHeap.insert (birthtime, thread) oldest_heap
wenzelm@29112
   227
        val active' = update_thread (thread, (birthtime, deadtime, desc)) active
immler@30798
   228
      in make_state timeout_heap' oldest_heap' active' cancelling messages store end);
immler@30798
   229
  check_thread_manager ());
wenzelm@28477
   230
wenzelm@28477
   231
wenzelm@28586
   232
wenzelm@28586
   233
(** user commands **)
wenzelm@28582
   234
wenzelm@28586
   235
(* kill: move all threads to cancelling *)
wenzelm@28586
   236
wenzelm@28586
   237
fun kill () = Synchronized.change state
immler@29620
   238
  (fn State {timeout_heap, oldest_heap, active, cancelling, messages, store} =>
wenzelm@28582
   239
    let val formerly_active = map (fn (th, (tb, _, desc)) => (th, (tb, Time.now (), desc))) active
immler@29620
   240
    in make_state timeout_heap oldest_heap [] (formerly_active @ cancelling) messages store 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
immler@30537
   282
type prover = int -> int -> Proof.context * (thm list * thm) -> bool * string;
wenzelm@28595
   283
wenzelm@28582
   284
fun err_dup_prover name = error ("Duplicate prover: " ^ quote name);
wenzelm@28477
   285
wenzelm@28582
   286
structure Provers = TheoryDataFun
wenzelm@28582
   287
(
wenzelm@28595
   288
  type T = (prover * stamp) Symtab.table
wenzelm@28582
   289
  val empty = Symtab.empty
wenzelm@28582
   290
  val copy = I
wenzelm@28582
   291
  val extend = I
wenzelm@28582
   292
  fun merge _ tabs : T = Symtab.merge (eq_snd op =) tabs
wenzelm@28589
   293
    handle Symtab.DUP dup => err_dup_prover dup
wenzelm@28582
   294
);
wenzelm@28484
   295
wenzelm@28595
   296
fun add_prover name prover thy =
wenzelm@28595
   297
  Provers.map (Symtab.update_new (name, (prover, stamp ()))) thy
wenzelm@28582
   298
    handle Symtab.DUP dup => err_dup_prover dup;
wenzelm@28582
   299
wenzelm@28582
   300
fun print_provers thy = Pretty.writeln
wenzelm@28582
   301
  (Pretty.strs ("external provers:" :: sort_strings (Symtab.keys (Provers.get thy))));
wenzelm@28571
   302
wenzelm@28586
   303
wenzelm@28595
   304
(* start prover thread *)
wenzelm@28484
   305
wenzelm@28595
   306
fun start_prover name birthtime deadtime i proof_state =
wenzelm@28595
   307
  (case Symtab.lookup (Provers.get (Proof.theory_of proof_state)) name of
wenzelm@28595
   308
    NONE => warning ("Unknown external prover: " ^ quote name)
wenzelm@28595
   309
  | SOME (prover, _) =>
wenzelm@28595
   310
      let
wenzelm@28595
   311
        val (ctxt, (_, goal)) = Proof.get_goal proof_state
wenzelm@28595
   312
        val desc =
wenzelm@28595
   313
          "external prover " ^ quote name ^ " for subgoal " ^ string_of_int i ^ ":\n" ^
wenzelm@28595
   314
            Syntax.string_of_term ctxt (Thm.term_of (Thm.cprem_of goal i))
wenzelm@28595
   315
        val _ = SimpleThread.fork true (fn () =>
wenzelm@28595
   316
          let
wenzelm@28595
   317
            val _ = register birthtime deadtime (Thread.self (), desc)
wenzelm@30800
   318
            val result = prover (get_timeout ()) i (Proof.get_goal proof_state)
wenzelm@28835
   319
              handle ResHolClause.TOO_TRIVIAL
wenzelm@28835
   320
                => (true, "Empty clause: Try this command: " ^ Markup.markup Markup.sendback "apply metis")
wenzelm@28835
   321
              | ERROR msg
wenzelm@28835
   322
                => (false, "Error: " ^ msg)
immler@29620
   323
            val _ = unregister result (Thread.self ())
wenzelm@28595
   324
          in () end handle Interrupt => ())
wenzelm@28595
   325
      in () end);
wenzelm@28582
   326
wenzelm@28582
   327
wenzelm@28582
   328
(* sledghammer for first subgoal *)
wenzelm@28582
   329
wenzelm@28582
   330
fun sledgehammer names proof_state =
wenzelm@28582
   331
  let
wenzelm@28595
   332
    val provers =
wenzelm@28586
   333
      if null names then String.tokens (Symbol.is_ascii_blank o String.str) (get_atps ())
wenzelm@28582
   334
      else names
wenzelm@28582
   335
    val birthtime = Time.now ()
wenzelm@28595
   336
    val deadtime = Time.+ (birthtime, Time.fromSeconds (get_timeout ()))
wenzelm@28595
   337
  in List.app (fn name => start_prover name birthtime deadtime 1 proof_state) provers end;
wenzelm@28582
   338
wenzelm@28582
   339
wenzelm@28586
   340
wenzelm@28586
   341
(** Isar command syntax **)
wenzelm@28582
   342
wenzelm@28582
   343
local structure K = OuterKeyword and P = OuterParse in
wenzelm@28582
   344
wenzelm@28582
   345
val _ =
wenzelm@28582
   346
  OuterSyntax.improper_command "atp_kill" "kill all managed provers" K.diag
wenzelm@28586
   347
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative kill));
wenzelm@28582
   348
wenzelm@28582
   349
val _ =
wenzelm@28582
   350
  OuterSyntax.improper_command "atp_info" "print information about managed provers" K.diag
wenzelm@28582
   351
    (Scan.succeed (Toplevel.no_timing o Toplevel.imperative info));
wenzelm@28582
   352
wenzelm@28582
   353
val _ =
wenzelm@29112
   354
  OuterSyntax.improper_command "atp_messages" "print recent messages issued by managed provers" K.diag
wenzelm@29112
   355
    (Scan.option (P.$$$ "(" |-- P.nat --| P.$$$ ")") >>
wenzelm@29112
   356
      (fn limit => Toplevel.no_timing o Toplevel.imperative (fn () => messages limit)));
wenzelm@29112
   357
wenzelm@29112
   358
val _ =
wenzelm@28582
   359
  OuterSyntax.improper_command "print_atps" "print external provers" K.diag
wenzelm@28582
   360
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_theory o
wenzelm@28582
   361
      Toplevel.keep (print_provers o Toplevel.theory_of)));
wenzelm@28582
   362
wenzelm@28582
   363
val _ =
wenzelm@28582
   364
  OuterSyntax.command "sledgehammer" "call all automatic theorem provers" K.diag
wenzelm@28582
   365
    (Scan.repeat P.xname >> (fn names => Toplevel.no_timing o Toplevel.unknown_proof o
wenzelm@30800
   366
      Toplevel.keep (sledgehammer names o Toplevel.proof_of)));
wenzelm@28582
   367
wenzelm@28582
   368
end;
wenzelm@28582
   369
wenzelm@28582
   370
end;
immler@30537
   371