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