src/HOL/Tools/res_atp.ML
author paulson
Wed May 17 12:28:47 2006 +0200 (2006-05-17 ago)
changeset 19675 a4894fb2a5f2
parent 19641 f1de44e61ec1
child 19718 e709f643c578
permissions -rw-r--r--
removing the string array from the result of get_clasimp_atp_lemmas
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory, NICTA
     2     ID: $Id$
     3     Copyright 2004 University of Cambridge
     4 
     5 ATPs with TPTP format input.
     6 *)
     7 
     8 signature RES_ATP =
     9 sig
    10   val prover: string ref
    11   val custom_spass: string list ref
    12   val destdir: string ref
    13   val helper_path: string -> string -> string
    14   val problem_name: string ref
    15   val time_limit: int ref
    16    
    17   datatype mode = Auto | Fol | Hol
    18   val linkup_logic_mode : mode ref
    19   val write_subgoal_file: mode -> Proof.context -> thm list -> thm list -> int -> string
    20   val vampire_time: int ref
    21   val eprover_time: int ref
    22   val run_vampire: int -> unit
    23   val run_eprover: int -> unit
    24   val vampireLimit: unit -> int
    25   val eproverLimit: unit -> int
    26   val atp_method: (ProofContext.context -> thm list -> int -> Tactical.tactic) ->
    27 		  Method.src -> ProofContext.context -> Method.method
    28   val cond_rm_tmp: string -> unit
    29   val keep_atp_input: bool ref
    30   val fol_keep_types: bool ref
    31   val hol_full_types: unit -> unit
    32   val hol_partial_types: unit -> unit
    33   val hol_const_types_only: unit -> unit
    34   val hol_no_types: unit -> unit
    35   val hol_typ_level: unit -> ResHolClause.type_level
    36   val run_relevance_filter: bool ref
    37   val invoke_atp_ml : ProofContext.context * thm -> unit
    38   val add_claset : unit -> unit
    39   val add_simpset : unit -> unit
    40   val add_clasimp : unit -> unit
    41   val add_atpset : unit -> unit
    42   val rm_claset : unit -> unit
    43   val rm_simpset : unit -> unit
    44   val rm_atpset : unit -> unit
    45   val rm_clasimp : unit -> unit
    46 end;
    47 
    48 structure ResAtp : RES_ATP =
    49 struct
    50 
    51 (********************************************************************)
    52 (* some settings for both background automatic ATP calling procedure*)
    53 (* and also explicit ATP invocation methods                         *)
    54 (********************************************************************)
    55 
    56 (*** background linkup ***)
    57 val call_atp = ref false; 
    58 val hook_count = ref 0;
    59 val time_limit = ref 30;
    60 val prover = ref "E";   (* use E as the default prover *)
    61 val custom_spass =   (*specialized options for SPASS*)
    62       ref ["-Auto=0","-FullRed=0","-IORe","-IOFc","-RTaut","-RFSub","-RBSub"];
    63 val destdir = ref "";   (*Empty means write files to /tmp*)
    64 val problem_name = ref "prob";
    65 
    66 (*Return the path to a "helper" like SPASS or tptp2X, first checking that
    67   it exists.  FIXME: modify to use Path primitives and move to some central place.*)  
    68 fun helper_path evar base =
    69   case getenv evar of
    70       "" => error  ("Isabelle environment variable " ^ evar ^ " not defined")
    71     | home => 
    72         let val path = home ^ "/" ^ base
    73         in  if File.exists (File.unpack_platform_path path) then path 
    74 	    else error ("Could not find the file " ^ path)
    75 	end;  
    76 
    77 fun probfile_nosuffix _ = 
    78   if !destdir = "" then File.platform_path (File.tmp_path (Path.basic (!problem_name)))
    79   else if File.exists (File.unpack_platform_path (!destdir))
    80   then !destdir ^ "/" ^ !problem_name
    81   else error ("No such directory: " ^ !destdir);
    82 
    83 fun prob_pathname n = probfile_nosuffix n ^ "_" ^ Int.toString n;
    84 
    85 
    86 (*** ATP methods ***)
    87 val vampire_time = ref 60;
    88 val eprover_time = ref 60;
    89 fun run_vampire time =  
    90     if (time >0) then vampire_time:= time
    91     else vampire_time:=60;
    92 
    93 fun run_eprover time = 
    94     if (time > 0) then eprover_time:= time
    95     else eprover_time:=60;
    96 
    97 fun vampireLimit () = !vampire_time;
    98 fun eproverLimit () = !eprover_time;
    99 
   100 val keep_atp_input = ref false;
   101 val fol_keep_types = ResClause.keep_types;
   102 val hol_full_types = ResHolClause.full_types;
   103 val hol_partial_types = ResHolClause.partial_types;
   104 val hol_const_types_only = ResHolClause.const_types_only;
   105 val hol_no_types = ResHolClause.no_types;
   106 fun hol_typ_level () = ResHolClause.find_typ_level ();
   107 fun is_typed_hol () = 
   108     let val tp_level = hol_typ_level()
   109     in
   110 	not (tp_level = ResHolClause.T_NONE)
   111     end;
   112 val include_combS = ResHolClause.include_combS;
   113 val include_min_comb = ResHolClause.include_min_comb;
   114 
   115 fun atp_input_file () =
   116     let val file = !problem_name 
   117     in
   118 	if !destdir = "" then File.platform_path (File.tmp_path (Path.basic file))
   119 	else if File.exists (File.unpack_platform_path (!destdir))
   120 	then !destdir ^ "/" ^ file
   121 	else error ("No such directory: " ^ !destdir)
   122     end;
   123 
   124 val include_simpset = ref false;
   125 val include_claset = ref false; 
   126 val include_atpset = ref true;
   127 val add_simpset = (fn () => include_simpset:=true);
   128 val add_claset = (fn () => include_claset:=true);
   129 val add_clasimp = (fn () => (include_simpset:=true;include_claset:=true));
   130 val add_atpset = (fn () => include_atpset:=true);
   131 val rm_simpset = (fn () => include_simpset:=false);
   132 val rm_claset = (fn () => include_claset:=false);
   133 val rm_clasimp = (fn () => (include_simpset:=false;include_claset:=false));
   134 val rm_atpset = (fn () => include_atpset:=false);
   135 
   136 
   137 (**** relevance filter ****)
   138 val run_relevance_filter = ref true;
   139 
   140 (******************************************************************)
   141 (* detect whether a given problem (clauses) is FOL/HOL/HOLC/HOLCS *)
   142 (******************************************************************)
   143 
   144 datatype logic = FOL | HOL | HOLC | HOLCS;
   145 
   146 fun string_of_logic FOL = "FOL"
   147   | string_of_logic HOL = "HOL"
   148   | string_of_logic HOLC = "HOLC"
   149   | string_of_logic HOLCS = "HOLCS";
   150 
   151 
   152 fun is_fol_logic FOL = true
   153   | is_fol_logic  _ = false
   154 
   155 
   156 (*HOLCS will not occur here*)
   157 fun upgrade_lg HOLC _ = HOLC
   158   | upgrade_lg HOL HOLC = HOLC
   159   | upgrade_lg HOL _ = HOL
   160   | upgrade_lg FOL lg = lg; 
   161 
   162 (* check types *)
   163 fun has_bool_hfn (Type("bool",_)) = true
   164   | has_bool_hfn (Type("fun",_)) = true
   165   | has_bool_hfn (Type(_, Ts)) = exists has_bool_hfn Ts
   166   | has_bool_hfn _ = false;
   167 
   168 fun is_hol_fn tp =
   169     let val (targs,tr) = strip_type tp
   170     in
   171 	exists (has_bool_hfn) (tr::targs)
   172     end;
   173 
   174 fun is_hol_pred tp =
   175     let val (targs,tr) = strip_type tp
   176     in
   177 	exists (has_bool_hfn) targs
   178     end;
   179 
   180 exception FN_LG of term;
   181 
   182 fun fn_lg (t as Const(f,tp)) (lg,seen) = 
   183     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   184   | fn_lg (t as Free(f,tp)) (lg,seen) = 
   185     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   186   | fn_lg (t as Var(f,tp)) (lg,seen) =
   187     if is_hol_fn tp then (upgrade_lg HOL lg,t ins seen) else (lg,t ins seen)
   188   | fn_lg (t as Abs(_,_,_)) (lg,seen) = (upgrade_lg HOLC lg,t ins seen)
   189   | fn_lg f _ = raise FN_LG(f); 
   190 
   191 
   192 fun term_lg [] (lg,seen) = (lg,seen)
   193   | term_lg (tm::tms) (FOL,seen) =
   194     let val (f,args) = strip_comb tm
   195 	val (lg',seen') = if f mem seen then (FOL,seen) 
   196 			  else fn_lg f (FOL,seen)
   197 	val _ =
   198           if is_fol_logic lg' then ()
   199           else warning ("Found a HOL term: " ^ Display.raw_string_of_term f)
   200 	 in
   201 	     term_lg (args@tms) (lg',seen')
   202     end
   203   | term_lg _ (lg,seen) = (lg,seen)
   204 
   205 exception PRED_LG of term;
   206 
   207 fun pred_lg (t as Const(P,tp)) (lg,seen)= 
   208     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen) 
   209   | pred_lg (t as Free(P,tp)) (lg,seen) =
   210     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen)
   211   | pred_lg (t as Var(_,_)) (lg,seen) = (upgrade_lg HOL lg, t ins seen)
   212   | pred_lg P _ = raise PRED_LG(P);
   213 
   214 
   215 fun lit_lg (Const("Not",_) $ P) (lg,seen) = lit_lg P (lg,seen)
   216   | lit_lg P (lg,seen) =
   217     let val (pred,args) = strip_comb P
   218 	val (lg',seen') = if pred mem seen then (lg,seen) 
   219 			  else pred_lg pred (lg,seen)
   220 	val _ =
   221           if is_fol_logic lg' then ()
   222           else warning ("Found a HOL predicate: " ^ Display.raw_string_of_term pred)
   223     in
   224 	term_lg args (lg',seen')
   225     end;
   226 
   227 fun lits_lg [] (lg,seen) = (lg,seen)
   228   | lits_lg (lit::lits) (FOL,seen) =
   229     let val (lg,seen') = lit_lg lit (FOL,seen)
   230 	val _ =
   231           if is_fol_logic lg then ()
   232           else warning ("Found a HOL literal: " ^ Display.raw_string_of_term lit)
   233     in
   234 	lits_lg lits (lg,seen')
   235     end
   236   | lits_lg lits (lg,seen) = (lg,seen);
   237 
   238 
   239 fun dest_disj_aux (Const ("op |", _) $ t $ t') disjs = 
   240     dest_disj_aux t (dest_disj_aux t' disjs)
   241   | dest_disj_aux t disjs = t::disjs;
   242 
   243 fun dest_disj t = dest_disj_aux t [];
   244 
   245 fun logic_of_clause tm (lg,seen) =
   246     let val tm' = HOLogic.dest_Trueprop tm
   247 	val disjs = dest_disj tm'
   248     in
   249 	lits_lg disjs (lg,seen)
   250     end;
   251 
   252 fun logic_of_clauses [] (lg,seen) = (lg,seen)
   253   | logic_of_clauses (cls::clss) (FOL,seen) =
   254     let val (lg,seen') = logic_of_clause cls (FOL,seen)
   255 	val _ =
   256           if is_fol_logic lg then ()
   257           else warning ("Found a HOL clause: " ^ Display.raw_string_of_term cls)
   258     in
   259 	logic_of_clauses clss (lg,seen')
   260     end
   261   | logic_of_clauses (cls::clss) (lg,seen) = (lg,seen);
   262 
   263 fun problem_logic_goals_aux [] (lg,seen) = lg
   264   | problem_logic_goals_aux (subgoal::subgoals) (lg,seen) = 
   265     problem_logic_goals_aux subgoals (logic_of_clauses subgoal (lg,seen));
   266     
   267 fun problem_logic_goals subgoals = problem_logic_goals_aux subgoals (FOL,[]);
   268 
   269 
   270 (***************************************************************)
   271 (* ATP invocation methods setup                                *)
   272 (***************************************************************)
   273 
   274 
   275 (**** prover-specific format: TPTP ****)
   276 
   277 
   278 fun cnf_hyps_thms ctxt = 
   279     let val ths = ProofContext.prems_of ctxt
   280     in fold (fold (insert Thm.eq_thm) o ResAxioms.skolem_thm) ths [] end;
   281 
   282 
   283 (**** write to files ****)
   284 
   285 datatype mode = Auto | Fol | Hol;
   286 
   287 val linkup_logic_mode = ref Auto;
   288 
   289 fun tptp_writer logic goals filename (axioms,classrels,arities) =
   290     if is_fol_logic logic 
   291     then ResClause.tptp_write_file goals filename (axioms, classrels, arities)
   292     else ResHolClause.tptp_write_file goals filename (axioms, classrels, arities);
   293 
   294 (*2006-04-07: not working: goals has type thm list (not term list as above) and
   295   axioms has type ResClause.clause list (not (thm * (string * int)) list as above)*)
   296 fun dfg_writer logic goals filename (axioms,classrels,arities) =
   297     if is_fol_logic logic 
   298     then ResClause.dfg_write_file goals filename (axioms, classrels, arities)
   299     else error "DFG output for higher-order translations is not implemented"
   300 
   301 
   302 fun write_subgoal_file mode ctxt conjectures user_thms n =
   303     let val conj_cls = make_clauses conjectures 
   304 	val hyp_cls = cnf_hyps_thms ctxt
   305 	val goal_cls = conj_cls@hyp_cls
   306 	val user_rules = map ResAxioms.pairname user_thms
   307 	val axclauses_as_thms = ResClasimp.get_clasimp_atp_lemmas ctxt (map prop_of goal_cls) user_rules (!include_claset,!include_simpset,!include_atpset) (!run_relevance_filter)  
   308 	val thy = ProofContext.theory_of ctxt
   309 	val prob_logic = case mode of Auto => problem_logic_goals [map prop_of goal_cls]
   310 				    | Fol => FOL
   311 				    | Hol => HOL
   312 	val keep_types = if is_fol_logic prob_logic then !fol_keep_types else is_typed_hol ()
   313 	val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   314 	val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   315         val writer = (*if !prover = "spass" then dfg_writer else*) tptp_writer 
   316 	val file = atp_input_file()
   317     in
   318 	(writer prob_logic goal_cls file (axclauses_as_thms,classrel_clauses,arity_clauses);
   319 	 warning ("Writing to " ^ file);
   320 	 file)
   321     end;
   322 
   323 
   324 (**** remove tmp files ****)
   325 fun cond_rm_tmp file = 
   326     if !keep_atp_input then warning "ATP input kept..." 
   327     else if !destdir <> "" then warning ("ATP input kept in directory " ^ (!destdir))
   328     else (warning "deleting ATP inputs..."; OS.FileSys.remove file);
   329 
   330 
   331 (****** setup ATPs as Isabelle methods ******)
   332 fun atp_meth' tac ths ctxt = 
   333     Method.SIMPLE_METHOD' HEADGOAL
   334     (tac ctxt ths);
   335 
   336 fun atp_meth tac ths ctxt = 
   337     let val thy = ProofContext.theory_of ctxt
   338 	val _ = ResClause.init thy
   339 	val _ = ResHolClause.init thy
   340     in
   341 	atp_meth' tac ths ctxt
   342     end;
   343 
   344 fun atp_method tac = Method.thms_ctxt_args (atp_meth tac);
   345 
   346 (***************************************************************)
   347 (* automatic ATP invocation                                    *)
   348 (***************************************************************)
   349 
   350 (* call prover with settings and problem file for the current subgoal *)
   351 fun watcher_call_provers sign sg_terms (childin, childout, pid) =
   352   let
   353     fun make_atp_list [] n = []
   354       | make_atp_list (sg_term::xs) n =
   355           let
   356             val probfile = prob_pathname n
   357             val time = Int.toString (!time_limit)
   358           in
   359             Output.debug ("problem file in watcher_call_provers is " ^ probfile);
   360             (*options are separated by Watcher.setting_sep, currently #"%"*)
   361             if !prover = "spass"
   362             then
   363               let val spass = helper_path "SPASS_HOME" "SPASS"
   364                   val sopts =
   365    "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
   366               in 
   367                   ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
   368               end
   369             else if !prover = "vampire"
   370 	    then 
   371               let val vampire = helper_path "VAMPIRE_HOME" "vampire"
   372                   val casc = if !time_limit > 70 then "--mode casc%" else ""
   373                   val vopts = casc ^ "-m 100000%-t " ^ time
   374               in
   375                   ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
   376               end
   377       	     else if !prover = "E"
   378       	     then
   379 	       let val Eprover = helper_path "E_HOME" "eproof"
   380 	       in
   381 		  ("E", Eprover, 
   382 		     "--tptp-in%-l5%-xAuto%-tAuto%--cpu-limit=" ^ time, probfile) ::
   383 		   make_atp_list xs (n+1)
   384 	       end
   385 	     else error ("Invalid prover name: " ^ !prover)
   386           end
   387 
   388     val atp_list = make_atp_list sg_terms 1
   389   in
   390     Watcher.callResProvers(childout,atp_list);
   391     Output.debug "Sent commands to watcher!"
   392   end
   393 
   394 (*We write out problem files for each subgoal. Argument pf generates filenames,
   395   and allows the suppression of the suffix "_1" in problem-generation mode.
   396   FIXME: does not cope with &&, and it isn't easy because one could have multiple
   397   subgoals, each involving &&.*)
   398 fun write_problem_files pf (ctxt,th)  =
   399   let val goals = Thm.prems_of th
   400       val _ = Output.debug ("number of subgoals = " ^ Int.toString (length goals))
   401       val axclauses = ResClasimp.get_clasimp_atp_lemmas ctxt goals [] (true,true,true) (!run_relevance_filter) (* no user supplied rules here, because no user invocation *)
   402       val _ = Output.debug ("claset, simprules and atprules total clauses = " ^ 
   403                      Int.toString (length axclauses))
   404       val thy = ProofContext.theory_of ctxt
   405       fun get_neg_subgoals n =
   406 	  if n=0 then []
   407 	  else
   408 	      let val st = Seq.hd (EVERY'
   409 				       [rtac ccontr, ObjectLogic.atomize_tac, skolemize_tac] n th)
   410 		  val negs = Option.valOf (metahyps_thms n st)
   411 		  val negs_clauses = make_clauses negs
   412 	      in
   413 		  negs_clauses::(get_neg_subgoals (n - 1))
   414 	      end
   415       val neg_subgoals = get_neg_subgoals (length goals) 
   416       val goals_logic = case !linkup_logic_mode of Auto => problem_logic_goals (map (map prop_of) neg_subgoals)
   417 						 | Fol => FOL
   418 						 | Hol => HOL
   419       val keep_types = if is_fol_logic goals_logic then !ResClause.keep_types else is_typed_hol ()
   420       val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   421       val _ = Output.debug ("classrel clauses = " ^ Int.toString (length classrel_clauses))
   422       val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   423       val _ = Output.debug ("arity clauses = " ^ Int.toString (length arity_clauses))
   424       val writer = (*if !prover = "spass" then dfg_writer else*) tptp_writer 
   425       fun write_all [] _ = []
   426 	| write_all (subgoal::subgoals) k =
   427 	  (writer goals_logic subgoal (pf k) (axclauses,classrel_clauses,arity_clauses); pf k):: (write_all subgoals (k - 1))
   428       val thm_names = Array.fromList (map (#1 o #2) axclauses)
   429   in
   430       (write_all neg_subgoals (length goals), thm_names)
   431   end;
   432 
   433 val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream * 
   434                                     Posix.Process.pid * string list) option);
   435 
   436 fun kill_last_watcher () =
   437     (case !last_watcher_pid of 
   438          NONE => ()
   439        | SOME (_, _, pid, files) => 
   440 	  (Output.debug ("Killing old watcher, pid = " ^ string_of_pid pid);
   441 	   Watcher.killWatcher pid;  
   442 	   ignore (map (try OS.FileSys.remove) files)))
   443      handle OS.SysErr _ => Output.debug "Attempt to kill watcher failed";
   444 
   445 (*writes out the current clasimpset to a tptp file;
   446   turns off xsymbol at start of function, restoring it at end    *)
   447 val isar_atp = setmp print_mode [] 
   448  (fn (ctxt, th) =>
   449   if Thm.no_prems th then ()
   450   else
   451     let
   452       val _ = kill_last_watcher()
   453       val (files,thm_names) = write_problem_files prob_pathname (ctxt,th)
   454       val (childin, childout, pid) = Watcher.createWatcher (th, thm_names)
   455     in
   456       last_watcher_pid := SOME (childin, childout, pid, files);
   457       Output.debug ("problem files: " ^ space_implode ", " files); 
   458       Output.debug ("pid: " ^ string_of_pid pid);
   459       watcher_call_provers (sign_of_thm th) (Thm.prems_of th) (childin, childout, pid)
   460     end);
   461 
   462 val isar_atp_writeonly = setmp print_mode [] 
   463       (fn (ctxt,th) =>
   464        if Thm.no_prems th then ()
   465        else 
   466          let val pf = if Thm.nprems_of th = 1 then probfile_nosuffix 
   467          	      else prob_pathname
   468          in ignore (write_problem_files pf (ctxt,th)) end);
   469 
   470 
   471 (** the Isar toplevel hook **)
   472 
   473 fun invoke_atp_ml (ctxt, goal) =
   474   let val thy = ProofContext.theory_of ctxt;
   475   in
   476     Output.debug ("subgoals in isar_atp:\n" ^ 
   477 		  Pretty.string_of (ProofContext.pretty_term ctxt
   478 		    (Logic.mk_conjunction_list (Thm.prems_of goal))));
   479     Output.debug ("current theory: " ^ Context.theory_name thy);
   480     hook_count := !hook_count +1;
   481     Output.debug ("in hook for time: " ^ Int.toString (!hook_count));
   482     ResClause.init thy;
   483     ResHolClause.init thy;
   484     if !destdir = "" andalso !time_limit > 0 then isar_atp (ctxt, goal)
   485     else isar_atp_writeonly (ctxt, goal)
   486   end;
   487 
   488 val invoke_atp = Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep
   489  (fn state =>
   490   let val (ctxt, (_, goal)) = Proof.get_goal (Toplevel.proof_of state)
   491   in  invoke_atp_ml (ctxt, goal)  end);
   492 
   493 val call_atpP =
   494   OuterSyntax.command 
   495     "ProofGeneral.call_atp" 
   496     "call automatic theorem provers" 
   497     OuterKeyword.diag
   498     (Scan.succeed invoke_atp);
   499 
   500 val _ = OuterSyntax.add_parsers [call_atpP];
   501 
   502 end;