src/HOL/Tools/res_atp.ML
author mengj
Thu May 25 08:08:04 2006 +0200 (2006-05-25 ago)
changeset 19718 e709f643c578
parent 19675 a4894fb2a5f2
child 19722 e7a5b54248bc
permissions -rw-r--r--
Added support for DFG format, used by SPASS.
     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 fun dfg_writer logic goals filename (axioms,classrels,arities) =
   295     if is_fol_logic logic 
   296     then ResClause.dfg_write_file goals filename (axioms, classrels, arities)
   297     else ResHolClause.dfg_write_file goals filename (axioms, classrels, arities);
   298 
   299 
   300 fun write_subgoal_file mode ctxt conjectures user_thms n =
   301     let val conj_cls = make_clauses conjectures 
   302 	val hyp_cls = cnf_hyps_thms ctxt
   303 	val goal_cls = conj_cls@hyp_cls
   304 	val user_rules = map ResAxioms.pairname user_thms
   305 	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)  
   306 	val thy = ProofContext.theory_of ctxt
   307 	val prob_logic = case mode of Auto => problem_logic_goals [map prop_of goal_cls]
   308 				    | Fol => FOL
   309 				    | Hol => HOL
   310 	val keep_types = if is_fol_logic prob_logic then !fol_keep_types else is_typed_hol ()
   311 	val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   312 	val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   313         val writer = if !prover = "spass" then dfg_writer else tptp_writer 
   314 	val file = atp_input_file()
   315     in
   316 	(writer prob_logic goal_cls file (axclauses_as_thms,classrel_clauses,arity_clauses);
   317 	 warning ("Writing to " ^ file);
   318 	 file)
   319     end;
   320 
   321 
   322 (**** remove tmp files ****)
   323 fun cond_rm_tmp file = 
   324     if !keep_atp_input then warning "ATP input kept..." 
   325     else if !destdir <> "" then warning ("ATP input kept in directory " ^ (!destdir))
   326     else (warning "deleting ATP inputs..."; OS.FileSys.remove file);
   327 
   328 
   329 (****** setup ATPs as Isabelle methods ******)
   330 fun atp_meth' tac ths ctxt = 
   331     Method.SIMPLE_METHOD' HEADGOAL
   332     (tac ctxt ths);
   333 
   334 fun atp_meth tac ths ctxt = 
   335     let val thy = ProofContext.theory_of ctxt
   336 	val _ = ResClause.init thy
   337 	val _ = ResHolClause.init thy
   338     in
   339 	atp_meth' tac ths ctxt
   340     end;
   341 
   342 fun atp_method tac = Method.thms_ctxt_args (atp_meth tac);
   343 
   344 (***************************************************************)
   345 (* automatic ATP invocation                                    *)
   346 (***************************************************************)
   347 
   348 (* call prover with settings and problem file for the current subgoal *)
   349 fun watcher_call_provers sign sg_terms (childin, childout, pid) =
   350   let
   351     fun make_atp_list [] n = []
   352       | make_atp_list (sg_term::xs) n =
   353           let
   354             val probfile = prob_pathname n
   355             val time = Int.toString (!time_limit)
   356           in
   357             Output.debug ("problem file in watcher_call_provers is " ^ probfile);
   358             (*options are separated by Watcher.setting_sep, currently #"%"*)
   359             if !prover = "spass"
   360             then
   361               let val spass = helper_path "SPASS_HOME" "SPASS"
   362                   val sopts =
   363    "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
   364               in 
   365                   ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
   366               end
   367             else if !prover = "vampire"
   368 	    then 
   369               let val vampire = helper_path "VAMPIRE_HOME" "vampire"
   370                   val casc = if !time_limit > 70 then "--mode casc%" else ""
   371                   val vopts = casc ^ "-m 100000%-t " ^ time
   372               in
   373                   ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
   374               end
   375       	     else if !prover = "E"
   376       	     then
   377 	       let val Eprover = helper_path "E_HOME" "eproof"
   378 	       in
   379 		  ("E", Eprover, 
   380 		     "--tptp-in%-l5%-xAuto%-tAuto%--cpu-limit=" ^ time, probfile) ::
   381 		   make_atp_list xs (n+1)
   382 	       end
   383 	     else error ("Invalid prover name: " ^ !prover)
   384           end
   385 
   386     val atp_list = make_atp_list sg_terms 1
   387   in
   388     Watcher.callResProvers(childout,atp_list);
   389     Output.debug "Sent commands to watcher!"
   390   end
   391 
   392 (*We write out problem files for each subgoal. Argument pf generates filenames,
   393   and allows the suppression of the suffix "_1" in problem-generation mode.
   394   FIXME: does not cope with &&, and it isn't easy because one could have multiple
   395   subgoals, each involving &&.*)
   396 fun write_problem_files pf (ctxt,th)  =
   397   let val goals = Thm.prems_of th
   398       val _ = Output.debug ("number of subgoals = " ^ Int.toString (length goals))
   399       val axclauses = ResClasimp.get_clasimp_atp_lemmas ctxt goals [] (true,true,true) (!run_relevance_filter) (* no user supplied rules here, because no user invocation *)
   400       val _ = Output.debug ("claset, simprules and atprules total clauses = " ^ 
   401                      Int.toString (length axclauses))
   402       val thy = ProofContext.theory_of ctxt
   403       fun get_neg_subgoals n =
   404 	  if n=0 then []
   405 	  else
   406 	      let val st = Seq.hd (EVERY'
   407 				       [rtac ccontr, ObjectLogic.atomize_tac, skolemize_tac] n th)
   408 		  val negs = Option.valOf (metahyps_thms n st)
   409 		  val negs_clauses = make_clauses negs
   410 	      in
   411 		  negs_clauses::(get_neg_subgoals (n - 1))
   412 	      end
   413       val neg_subgoals = get_neg_subgoals (length goals) 
   414       val goals_logic = case !linkup_logic_mode of Auto => problem_logic_goals (map (map prop_of) neg_subgoals)
   415 						 | Fol => FOL
   416 						 | Hol => HOL
   417       val keep_types = if is_fol_logic goals_logic then !ResClause.keep_types else is_typed_hol ()
   418       val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   419       val _ = Output.debug ("classrel clauses = " ^ Int.toString (length classrel_clauses))
   420       val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   421       val _ = Output.debug ("arity clauses = " ^ Int.toString (length arity_clauses))
   422       val writer = if !prover = "spass" then dfg_writer else tptp_writer 
   423       fun write_all [] _ = []
   424 	| write_all (subgoal::subgoals) k =
   425 	  (writer goals_logic subgoal (pf k) (axclauses,classrel_clauses,arity_clauses); pf k):: (write_all subgoals (k - 1))
   426       val thm_names = Array.fromList (map (#1 o #2) axclauses)
   427   in
   428       (write_all neg_subgoals (length goals), thm_names)
   429   end;
   430 
   431 val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream * 
   432                                     Posix.Process.pid * string list) option);
   433 
   434 fun kill_last_watcher () =
   435     (case !last_watcher_pid of 
   436          NONE => ()
   437        | SOME (_, _, pid, files) => 
   438 	  (Output.debug ("Killing old watcher, pid = " ^ string_of_pid pid);
   439 	   Watcher.killWatcher pid;  
   440 	   ignore (map (try OS.FileSys.remove) files)))
   441      handle OS.SysErr _ => Output.debug "Attempt to kill watcher failed";
   442 
   443 (*writes out the current clasimpset to a tptp file;
   444   turns off xsymbol at start of function, restoring it at end    *)
   445 val isar_atp = setmp print_mode [] 
   446  (fn (ctxt, th) =>
   447   if Thm.no_prems th then ()
   448   else
   449     let
   450       val _ = kill_last_watcher()
   451       val (files,thm_names) = write_problem_files prob_pathname (ctxt,th)
   452       val (childin, childout, pid) = Watcher.createWatcher (th, thm_names)
   453     in
   454       last_watcher_pid := SOME (childin, childout, pid, files);
   455       Output.debug ("problem files: " ^ space_implode ", " files); 
   456       Output.debug ("pid: " ^ string_of_pid pid);
   457       watcher_call_provers (sign_of_thm th) (Thm.prems_of th) (childin, childout, pid)
   458     end);
   459 
   460 val isar_atp_writeonly = setmp print_mode [] 
   461       (fn (ctxt,th) =>
   462        if Thm.no_prems th then ()
   463        else 
   464          let val pf = if Thm.nprems_of th = 1 then probfile_nosuffix 
   465          	      else prob_pathname
   466          in ignore (write_problem_files pf (ctxt,th)) end);
   467 
   468 
   469 (** the Isar toplevel hook **)
   470 
   471 fun invoke_atp_ml (ctxt, goal) =
   472   let val thy = ProofContext.theory_of ctxt;
   473   in
   474     Output.debug ("subgoals in isar_atp:\n" ^ 
   475 		  Pretty.string_of (ProofContext.pretty_term ctxt
   476 		    (Logic.mk_conjunction_list (Thm.prems_of goal))));
   477     Output.debug ("current theory: " ^ Context.theory_name thy);
   478     hook_count := !hook_count +1;
   479     Output.debug ("in hook for time: " ^ Int.toString (!hook_count));
   480     ResClause.init thy;
   481     ResHolClause.init thy;
   482     if !destdir = "" andalso !time_limit > 0 then isar_atp (ctxt, goal)
   483     else isar_atp_writeonly (ctxt, goal)
   484   end;
   485 
   486 val invoke_atp = Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep
   487  (fn state =>
   488   let val (ctxt, (_, goal)) = Proof.get_goal (Toplevel.proof_of state)
   489   in  invoke_atp_ml (ctxt, goal)  end);
   490 
   491 val call_atpP =
   492   OuterSyntax.command 
   493     "ProofGeneral.call_atp" 
   494     "call automatic theorem provers" 
   495     OuterKeyword.diag
   496     (Scan.succeed invoke_atp);
   497 
   498 val _ = OuterSyntax.add_parsers [call_atpP];
   499 
   500 end;