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