src/HOL/Tools/ATP_Manager/atp_systems.ML
author blanchet
Tue Jun 22 14:48:46 2010 +0200 (2010-06-22 ago)
changeset 37499 5ff37037fbec
parent 37498 b426cbdb5a23
child 37506 32a1ee39c49b
permissions -rw-r--r--
merge "generic_prover" and "generic_tptp_prover"
     1 (*  Title:      HOL/Tools/ATP_Manager/atp_systems.ML
     2     Author:     Fabian Immler, TU Muenchen
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 Setup for supported ATPs.
     6 *)
     7 
     8 signature ATP_SYSTEMS =
     9 sig
    10   type prover = ATP_Manager.prover
    11 
    12   (* hooks for problem files *)
    13   val dest_dir : string Config.T
    14   val problem_prefix : string Config.T
    15   val measure_runtime : bool Config.T
    16 
    17   val refresh_systems_on_tptp : unit -> unit
    18   val default_atps_param_value : unit -> string
    19   val setup : theory -> theory
    20 end;
    21 
    22 structure ATP_Systems : ATP_SYSTEMS =
    23 struct
    24 
    25 open Sledgehammer_Util
    26 open Sledgehammer_Fact_Preprocessor
    27 open Sledgehammer_HOL_Clause
    28 open Sledgehammer_Fact_Filter
    29 open Sledgehammer_Proof_Reconstruct
    30 open ATP_Manager
    31 
    32 (** generic ATP **)
    33 
    34 (* external problem files *)
    35 
    36 val (dest_dir, dest_dir_setup) = Attrib.config_string "atp_dest_dir" (K "");
    37   (*Empty string means create files in Isabelle's temporary files directory.*)
    38 
    39 val (problem_prefix, problem_prefix_setup) =
    40   Attrib.config_string "atp_problem_prefix" (K "prob");
    41 
    42 val (measure_runtime, measure_runtime_setup) =
    43   Attrib.config_bool "atp_measure_runtime" (K false);
    44 
    45 
    46 (* prover configuration *)
    47 
    48 type prover_config =
    49   {home_var: string,
    50    executable: string,
    51    arguments: Time.time -> string,
    52    proof_delims: (string * string) list,
    53    known_failures: (failure * string) list,
    54    max_axiom_clauses: int,
    55    prefers_theory_relevant: bool};
    56 
    57 
    58 (* basic template *)
    59 
    60 val remotify = prefix "remote_"
    61 
    62 fun with_path cleanup after f path =
    63   Exn.capture f path
    64   |> tap (fn _ => cleanup path)
    65   |> Exn.release
    66   |> tap (after path)
    67 
    68 (* Splits by the first possible of a list of delimiters. *)
    69 fun extract_proof delims output =
    70   case pairself (find_first (fn s => String.isSubstring s output))
    71                 (ListPair.unzip delims) of
    72     (SOME begin_delim, SOME end_delim) =>
    73     (output |> first_field begin_delim |> the |> snd
    74             |> first_field end_delim |> the |> fst
    75             |> first_field "\n" |> the |> snd
    76      handle Option.Option => "")
    77   | _ => ""
    78 
    79 fun extract_proof_and_outcome res_code proof_delims known_failures output =
    80   case map_filter (fn (failure, pattern) =>
    81                       if String.isSubstring pattern output then SOME failure
    82                       else NONE) known_failures of
    83     [] => (case extract_proof proof_delims output of
    84              "" => ("", SOME UnknownError)
    85            | proof => if res_code = 0 then (proof, NONE)
    86                       else ("", SOME UnknownError))
    87   | (failure :: _) => ("", SOME failure)
    88 
    89 fun string_for_failure Unprovable = "The ATP problem is unprovable."
    90   | string_for_failure IncompleteUnprovable =
    91     "The ATP cannot prove the problem."
    92   | string_for_failure TimedOut = "Timed out."
    93   | string_for_failure OutOfResources = "The ATP ran out of resources."
    94   | string_for_failure OldSpass =
    95     (* FIXME: Change the error message below to point to the Isabelle download
    96        page once the package is there (around the Isabelle2010 release). *)
    97     "Warning: Sledgehammer requires a more recent version of SPASS with \
    98     \support for the TPTP syntax. To install it, download and untar the \
    99     \package \"http://isabelle.in.tum.de/~blanchet/spass-3.7.tgz\" and add the \
   100     \\"spass-3.7\" directory's full path to \"" ^
   101     Path.implode (Path.expand (Path.appends
   102         (Path.variable "ISABELLE_HOME_USER" ::
   103          map Path.basic ["etc", "components"]))) ^
   104     "\" on a line of its own."
   105   | string_for_failure MalformedInput =
   106     "Internal Sledgehammer error: The ATP problem is malformed. Please report \
   107     \this to the Isabelle developers."
   108   | string_for_failure MalformedOutput = "Error: The ATP output is malformed."
   109   | string_for_failure UnknownError = "Error: An unknown ATP error occurred."
   110 
   111 fun shape_of_clauses _ [] = []
   112   | shape_of_clauses j ([] :: clauses) = [] :: shape_of_clauses j clauses
   113   | shape_of_clauses j ((_ :: lits) :: clauses) =
   114     let val shape = shape_of_clauses (j + 1) (lits :: clauses) in
   115       (j :: hd shape) :: tl shape
   116     end
   117 
   118 (* generic TPTP-based provers *)
   119 
   120 fun generic_tptp_prover
   121         (name, {home_var, executable, arguments, proof_delims, known_failures,
   122                 max_axiom_clauses, prefers_theory_relevant})
   123         ({debug, overlord, full_types, explicit_apply, respect_no_atp,
   124           relevance_threshold, relevance_convergence, theory_relevant,
   125           defs_relevant, isar_proof, isar_shrink_factor, ...} : params)
   126         minimize_command timeout
   127         ({subgoal, goal, relevance_override, axiom_clauses, filtered_clauses}
   128          : problem) =
   129   let
   130     (* get clauses and prepare them for writing *)
   131     val (ctxt, (_, th)) = goal;
   132     val thy = ProofContext.theory_of ctxt;
   133     val goal_clss = #1 (neg_conjecture_clauses ctxt th subgoal)
   134     val goal_cls = List.concat goal_clss
   135     val the_filtered_clauses =
   136       (case filtered_clauses of
   137         NONE => relevant_facts full_types respect_no_atp relevance_threshold
   138                     relevance_convergence defs_relevant max_axiom_clauses
   139                     (the_default prefers_theory_relevant theory_relevant)
   140                     relevance_override goal goal_cls
   141       | SOME fcls => fcls);
   142     val the_axiom_clauses =
   143       (case axiom_clauses of
   144         NONE => the_filtered_clauses
   145       | SOME axcls => axcls);
   146     val (internal_thm_names, clauses) =
   147       prepare_clauses full_types goal_cls the_axiom_clauses the_filtered_clauses
   148                       thy
   149 
   150     (* path to unique problem file *)
   151     val the_dest_dir = if overlord then getenv "ISABELLE_HOME_USER"
   152                        else Config.get ctxt dest_dir;
   153     val the_problem_prefix = Config.get ctxt problem_prefix;
   154     fun prob_pathname nr =
   155       let
   156         val probfile =
   157           Path.basic ((if overlord then "prob_" ^ name
   158                        else the_problem_prefix ^ serial_string ())
   159                       ^ "_" ^ string_of_int nr)
   160       in
   161         if the_dest_dir = "" then File.tmp_path probfile
   162         else if File.exists (Path.explode the_dest_dir)
   163         then Path.append (Path.explode the_dest_dir) probfile
   164         else error ("No such directory: " ^ the_dest_dir ^ ".")
   165       end;
   166 
   167     val home = getenv home_var
   168     val command = Path.explode (home ^ "/" ^ executable)
   169     (* write out problem file and call prover *)
   170     fun command_line probfile =
   171       (if Config.get ctxt measure_runtime then
   172          "TIMEFORMAT='%3U'; { time " ^
   173          space_implode " " [File.shell_path command, arguments timeout,
   174                             File.shell_path probfile] ^ " ; } 2>&1"
   175        else
   176          space_implode " " ["exec", File.shell_path command, arguments timeout,
   177                             File.shell_path probfile, "2>&1"]) ^
   178       (if overlord then
   179          " | sed 's/,/, /g' \
   180          \| sed 's/\\([^!=<]\\)\\([=|]\\)\\([^=>]\\)/\\1 \\2 \\3/g' \
   181          \| sed 's/  / /g' | sed 's/| |/||/g' \
   182          \| sed 's/ = = =/===/g' \
   183          \| sed 's/= = /== /g'"
   184        else
   185          "")
   186     fun split_time s =
   187       let
   188         val split = String.tokens (fn c => str c = "\n");
   189         val (output, t) = s |> split |> split_last |> apfst cat_lines;
   190         fun as_num f = f >> (fst o read_int);
   191         val num = as_num (Scan.many1 Symbol.is_ascii_digit);
   192         val digit = Scan.one Symbol.is_ascii_digit;
   193         val num3 = as_num (digit ::: digit ::: (digit >> single));
   194         val time = num --| Scan.$$ "." -- num3 >> (fn (a, b) => a * 1000 + b);
   195         val as_time = the_default 0 o Scan.read Symbol.stopper time o explode;
   196       in (output, as_time t) end;
   197     fun split_time' s =
   198       if Config.get ctxt measure_runtime then split_time s else (s, 0)
   199     fun run_on probfile =
   200       if File.exists command then
   201         write_tptp_file (debug andalso overlord) full_types explicit_apply
   202                         probfile clauses
   203         |> pair (apfst split_time' (bash_output (command_line probfile)))
   204       else if home = "" then
   205         error ("The environment variable " ^ quote home_var ^ " is not set.")
   206       else
   207         error ("Bad executable: " ^ Path.implode command ^ ".");
   208 
   209     (* If the problem file has not been exported, remove it; otherwise, export
   210        the proof file too. *)
   211     fun cleanup probfile =
   212       if the_dest_dir = "" then try File.rm probfile else NONE
   213     fun export probfile (((output, _), _), _) =
   214       if the_dest_dir = "" then
   215         ()
   216       else
   217         File.write (Path.explode (Path.implode probfile ^ "_proof"))
   218                    ((if overlord then
   219                        "% " ^ command_line probfile ^ "\n% " ^ timestamp () ^
   220                        "\n"
   221                      else
   222                        "") ^ output)
   223 
   224     val (((output, atp_run_time_in_msecs), res_code),
   225          (pool, conjecture_offset)) =
   226       with_path cleanup export run_on (prob_pathname subgoal);
   227     val conjecture_shape = shape_of_clauses (conjecture_offset + 1) goal_clss
   228     (* Check for success and print out some information on failure. *)
   229     val (proof, outcome) =
   230       extract_proof_and_outcome res_code proof_delims known_failures output
   231     val (message, relevant_thm_names) =
   232       case outcome of
   233         NONE =>
   234         proof_text isar_proof
   235             (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
   236             (full_types, minimize_command, proof, internal_thm_names, th,
   237              subgoal)
   238       | SOME failure => (string_for_failure failure ^ "\n", [])
   239   in
   240     {outcome = outcome, message = message, pool = pool,
   241      relevant_thm_names = relevant_thm_names,
   242      atp_run_time_in_msecs = atp_run_time_in_msecs, output = output,
   243      proof = proof, internal_thm_names = internal_thm_names,
   244      conjecture_shape = conjecture_shape,
   245      filtered_clauses = the_filtered_clauses}
   246   end
   247 
   248 fun tptp_prover name p = (name, generic_tptp_prover (name, p));
   249 
   250 
   251 (** common provers **)
   252 
   253 fun to_generous_secs time = (Time.toMilliseconds time + 999) div 1000
   254 
   255 (* Vampire *)
   256 
   257 (* Vampire requires an explicit time limit. *)
   258 
   259 val vampire_config : prover_config =
   260   {home_var = "VAMPIRE_HOME",
   261    executable = "vampire",
   262    arguments = fn timeout =>
   263      "--output_syntax tptp --mode casc -t " ^
   264      string_of_int (to_generous_secs timeout),
   265    proof_delims =
   266      [("=========== Refutation ==========",
   267        "======= End of refutation ======="),
   268       ("% SZS output start Refutation", "% SZS output end Refutation")],
   269    known_failures =
   270      [(Unprovable, "UNPROVABLE"),
   271       (IncompleteUnprovable, "CANNOT PROVE"),
   272       (Unprovable, "Satisfiability detected"),
   273       (OutOfResources, "Refutation not found")],
   274    max_axiom_clauses = 60,
   275    prefers_theory_relevant = false}
   276 val vampire = tptp_prover "vampire" vampire_config
   277 
   278 
   279 (* E prover *)
   280 
   281 val tstp_proof_delims =
   282   ("# SZS output start CNFRefutation.", "# SZS output end CNFRefutation")
   283 
   284 val e_config : prover_config =
   285   {home_var = "E_HOME",
   286    executable = "eproof",
   287    arguments = fn timeout =>
   288      "--tstp-in --tstp-out -l5 -xAutoDev -tAutoDev --silent --cpu-limit=" ^
   289      string_of_int (to_generous_secs timeout),
   290    proof_delims = [tstp_proof_delims],
   291    known_failures =
   292      [(Unprovable, "SZS status: Satisfiable"),
   293       (Unprovable, "SZS status Satisfiable"),
   294       (TimedOut, "Failure: Resource limit exceeded (time)"),
   295       (TimedOut, "time limit exceeded"),
   296       (OutOfResources,
   297        "# Cannot determine problem status within resource limit"),
   298       (OutOfResources, "SZS status: ResourceOut"),
   299       (OutOfResources, "SZS status ResourceOut")],
   300    max_axiom_clauses = 100,
   301    prefers_theory_relevant = false}
   302 val e = tptp_prover "e" e_config
   303 
   304 
   305 (* SPASS *)
   306 
   307 (* The "-VarWeight=3" option helps the higher-order problems, probably by
   308    counteracting the presence of "hAPP". *)
   309 val spass_config : prover_config =
   310   {home_var = "SPASS_HOME",
   311    executable = "SPASS",
   312    arguments = fn timeout =>
   313      "-TPTP -Auto -SOS=1 -PGiven=0 -PProblem=0 -Splits=0 -FullRed=0 -DocProof \
   314      \-VarWeight=3 -TimeLimit=" ^ string_of_int (to_generous_secs timeout),
   315    proof_delims = [("Here is a proof", "Formulae used in the proof")],
   316    known_failures =
   317      [(IncompleteUnprovable, "SPASS beiseite: Completion found"),
   318       (TimedOut, "SPASS beiseite: Ran out of time"),
   319       (OutOfResources, "SPASS beiseite: Maximal number of loops exceeded"),
   320       (MalformedInput, "Undefined symbol"),
   321       (MalformedInput, "Free Variable"),
   322       (OldSpass, "unrecognized option `-TPTP'"),
   323       (OldSpass, "Unrecognized option TPTP")],
   324    max_axiom_clauses = 40,
   325    prefers_theory_relevant = true}
   326 val spass = tptp_prover "spass" spass_config
   327 
   328 (* remote prover invocation via SystemOnTPTP *)
   329 
   330 val systems = Synchronized.var "atp_systems" ([]: string list);
   331 
   332 fun get_systems () =
   333   case bash_output "\"$ISABELLE_ATP_MANAGER/SystemOnTPTP\" -w" of
   334     (answer, 0) => split_lines answer
   335   | (answer, _) =>
   336     error ("Failed to get available systems at SystemOnTPTP:\n" ^ answer)
   337 
   338 fun refresh_systems_on_tptp () =
   339   Synchronized.change systems (fn _ => get_systems ());
   340 
   341 fun get_system prefix = Synchronized.change_result systems (fn systems =>
   342   (if null systems then get_systems () else systems)
   343   |> `(find_first (String.isPrefix prefix)));
   344 
   345 fun the_system prefix =
   346   (case get_system prefix of
   347     NONE => error ("System " ^ quote prefix ^
   348                    " not available at SystemOnTPTP.")
   349   | SOME sys => sys);
   350 
   351 val remote_known_failures =
   352   [(TimedOut, "says Timeout"),
   353    (MalformedOutput, "Remote script could not extract proof")]
   354 
   355 fun remote_prover_config atp_prefix args
   356         ({proof_delims, known_failures, max_axiom_clauses,
   357           prefers_theory_relevant, ...} : prover_config) : prover_config =
   358   {home_var = "ISABELLE_ATP_MANAGER",
   359    executable = "SystemOnTPTP",
   360    arguments = fn timeout =>
   361      args ^ " -t " ^ string_of_int (to_generous_secs timeout) ^ " -s " ^
   362      the_system atp_prefix,
   363    proof_delims = insert (op =) tstp_proof_delims proof_delims,
   364    known_failures = remote_known_failures @ known_failures,
   365    max_axiom_clauses = max_axiom_clauses,
   366    prefers_theory_relevant = prefers_theory_relevant}
   367 
   368 val remote_vampire =
   369   tptp_prover (remotify (fst vampire))
   370               (remote_prover_config "Vampire---9" "" vampire_config)
   371 
   372 val remote_e =
   373   tptp_prover (remotify (fst e))
   374               (remote_prover_config "EP---" "" e_config)
   375 
   376 val remote_spass =
   377   tptp_prover (remotify (fst spass))
   378               (remote_prover_config "SPASS---" "-x" spass_config)
   379 
   380 fun maybe_remote (name, _) ({home_var, ...} : prover_config) =
   381   name |> getenv home_var = "" ? remotify
   382 
   383 fun default_atps_param_value () =
   384   space_implode " " [maybe_remote e e_config, maybe_remote spass spass_config,
   385                      remotify (fst vampire)]
   386 
   387 val provers = [spass, vampire, e, remote_vampire, remote_spass, remote_e]
   388 val prover_setup = fold add_prover provers
   389 
   390 val setup =
   391   dest_dir_setup
   392   #> problem_prefix_setup
   393   #> measure_runtime_setup
   394   #> prover_setup
   395 
   396 end;