src/HOL/Tools/sat_solver.ML
author webertj
Thu Jul 21 18:52:17 2005 +0200 (2005-07-21)
changeset 16899 ee4d620bcc1c
parent 16270 4280d6bbc1bb
child 16911 20a139ca2f62
permissions -rw-r--r--
write_dimacs_sat_file now generates slightly smaller files
     1 (*  Title:      HOL/Tools/sat_solver.ML
     2     ID:         $Id$
     3     Author:     Tjark Weber
     4     Copyright   2004
     5 
     6 Interface to external SAT solvers, and (simple) built-in SAT solvers.
     7 *)
     8 
     9 signature SAT_SOLVER =
    10 sig
    11 	exception NOT_CONFIGURED
    12 
    13 	type assignment = int -> bool option
    14 	datatype result = SATISFIABLE of assignment
    15 	                | UNSATISFIABLE
    16 	                | UNKNOWN
    17 	type solver     = PropLogic.prop_formula -> result
    18 
    19 	(* auxiliary functions to create external SAT solvers *)
    20 	val write_dimacs_cnf_file : Path.T -> PropLogic.prop_formula -> unit
    21 	val write_dimacs_sat_file : Path.T -> PropLogic.prop_formula -> unit
    22 	val parse_std_result_file : Path.T -> string * string * string -> result
    23 	val make_external_solver  : string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver
    24 
    25 	val read_dimacs_cnf_file : Path.T -> PropLogic.prop_formula
    26 
    27 	(* generic solver interface *)
    28 	val solvers       : (string * solver) list ref
    29 	val add_solver    : string * solver -> unit
    30 	val invoke_solver : string -> solver  (* exception Option *)
    31 end;
    32 
    33 structure SatSolver : SAT_SOLVER =
    34 struct
    35 
    36 	open PropLogic;
    37 
    38 (* ------------------------------------------------------------------------- *)
    39 (* should be raised by an external SAT solver to indicate that the solver is *)
    40 (* not configured properly                                                   *)
    41 (* ------------------------------------------------------------------------- *)
    42 
    43 	exception NOT_CONFIGURED;
    44 
    45 (* ------------------------------------------------------------------------- *)
    46 (* type of partial (satisfying) assignments: 'a i = NONE' means that 'a' is  *)
    47 (*      a satisfying assigment regardless of the value of variable 'i'       *)
    48 (* ------------------------------------------------------------------------- *)
    49 
    50 	type assignment = int -> bool option;
    51 
    52 (* ------------------------------------------------------------------------- *)
    53 (* return type of SAT solvers: if the result is 'SATISFIABLE', a satisfying  *)
    54 (*      assignment must be returned as well                                  *)
    55 (* ------------------------------------------------------------------------- *)
    56 
    57 	datatype result = SATISFIABLE of assignment
    58 	                | UNSATISFIABLE
    59 	                | UNKNOWN;
    60 
    61 (* ------------------------------------------------------------------------- *)
    62 (* type of SAT solvers: given a propositional formula, a satisfying          *)
    63 (*      assignment may be returned                                           *)
    64 (* ------------------------------------------------------------------------- *)
    65 
    66 	type solver = prop_formula -> result;
    67 
    68 (* ------------------------------------------------------------------------- *)
    69 (* write_dimacs_cnf_file: serializes a formula 'fm' of propositional logic   *)
    70 (*      to a file in DIMACS CNF format (see "Satisfiability Suggested        *)
    71 (*      Format", May 8 1993, Section 2.1)                                    *)
    72 (* Note: 'fm' must not contain a variable index less than 1.                 *)
    73 (* Note: 'fm' must be given in CNF.                                          *)
    74 (* ------------------------------------------------------------------------- *)
    75 
    76 	(* Path.T -> prop_formula -> unit *)
    77 
    78 	fun write_dimacs_cnf_file path fm =
    79 	let
    80 		(* prop_formula -> prop_formula *)
    81 		fun cnf_True_False_elim True =
    82 			Or (BoolVar 1, Not (BoolVar 1))
    83 		  | cnf_True_False_elim False =
    84 			And (BoolVar 1, Not (BoolVar 1))
    85 		  | cnf_True_False_elim fm =
    86 			fm  (* since 'fm' is in CNF, either 'fm'='True'/'False', or 'fm' does not contain 'True'/'False' at all *)
    87 		(* prop_formula -> int *)
    88 		fun cnf_number_of_clauses (And (fm1,fm2)) =
    89 			(cnf_number_of_clauses fm1) + (cnf_number_of_clauses fm2)
    90 		  | cnf_number_of_clauses _ =
    91 			1
    92 		(* prop_formula -> string *)
    93 		fun cnf_string fm =
    94 		let
    95 			(* prop_formula -> string list -> string list *)
    96 			fun cnf_string_acc True acc =
    97 				error "formula is not in CNF"
    98 			  | cnf_string_acc False acc =
    99 				error "formula is not in CNF"
   100 			  | cnf_string_acc (BoolVar i) acc =
   101 				(assert (i>=1) "formula contains a variable index less than 1";
   102 				string_of_int i :: acc)
   103 			  | cnf_string_acc (Not (BoolVar i)) acc =
   104 				"-" :: cnf_string_acc (BoolVar i) acc
   105 			  | cnf_string_acc (Not _) acc =
   106 				error "formula is not in CNF"
   107 			  | cnf_string_acc (Or (fm1,fm2)) acc =
   108 				cnf_string_acc fm1 (" " :: cnf_string_acc fm2 acc)
   109 			  | cnf_string_acc (And (fm1,fm2)) acc =
   110 				cnf_string_acc fm1 (" 0\n" :: cnf_string_acc fm2 acc)
   111 		in
   112 			concat (cnf_string_acc fm [])
   113 		end
   114 	in
   115 		File.write path
   116 			(let
   117 				val fm'               = cnf_True_False_elim fm
   118 				val number_of_vars    = maxidx fm'
   119 				val number_of_clauses = cnf_number_of_clauses fm'
   120 			in
   121 				"c This file was generated by SatSolver.write_dimacs_cnf_file\n" ^
   122 				"c (c) Tjark Weber\n" ^
   123 				"p cnf " ^ string_of_int number_of_vars ^ " " ^ string_of_int number_of_clauses ^ "\n" ^
   124 				cnf_string fm' ^ " 0\n"
   125 			end)
   126 	end;
   127 
   128 (* ------------------------------------------------------------------------- *)
   129 (* write_dimacs_sat_file: serializes a formula 'fm' of propositional logic   *)
   130 (*      to a file in DIMACS SAT format (see "Satisfiability Suggested        *)
   131 (*      Format", May 8 1993, Section 2.2)                                    *)
   132 (* Note: 'fm' must not contain a variable index less than 1.                 *)
   133 (* ------------------------------------------------------------------------- *)
   134 
   135 	(* Path.T -> prop_formula -> unit *)
   136 
   137 	fun write_dimacs_sat_file path fm =
   138 	let
   139 		(* prop_formula -> string *)
   140 		fun sat_string fm =
   141 		let
   142 			(* prop_formula -> string list -> string list *)
   143 			fun sat_string_acc True acc =
   144 				"*()" :: acc
   145 			  | sat_string_acc False acc =
   146 				"+()" :: acc
   147 			  | sat_string_acc (BoolVar i) acc =
   148 				(assert (i>=1) "formula contains a variable index less than 1";
   149 				string_of_int i :: acc)
   150 			  | sat_string_acc (Not (BoolVar i)) acc =
   151 				"-" :: sat_string_acc (BoolVar i) acc
   152 			  | sat_string_acc (Not fm) acc =
   153 				"-(" :: sat_string_acc fm (")" :: acc)
   154 			  | sat_string_acc (Or (fm1,fm2)) acc =
   155 				"+(" :: sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 (")" :: acc))
   156 			  | sat_string_acc (And (fm1,fm2)) acc =
   157 				"*(" :: sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 (")" :: acc))
   158 			(* optimization to make use of n-ary disjunction/conjunction *)
   159 			(* prop_formula -> string list -> string list *)
   160 			and sat_string_acc_or (Or (fm1,fm2)) acc =
   161 				sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 acc)
   162 			  | sat_string_acc_or fm acc =
   163 				sat_string_acc fm acc
   164 			(* prop_formula -> string list -> string list *)
   165 			and sat_string_acc_and (And (fm1,fm2)) acc =
   166 				sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 acc)
   167 			  | sat_string_acc_and fm acc =
   168 				sat_string_acc fm acc
   169 		in
   170 			concat (sat_string_acc fm [])
   171 		end
   172 	in
   173 		File.write path
   174 			(let
   175 				val number_of_vars = Int.max (maxidx fm, 1)
   176 			in
   177 				"c This file was generated by SatSolver.write_dimacs_sat_file\n" ^
   178 				"c (c) Tjark Weber\n" ^
   179 				"p sat " ^ string_of_int number_of_vars ^ "\n" ^
   180 				(*"(" ^*) sat_string fm ^ "\n" (*")\n"*)
   181 			end)
   182 	end;
   183 
   184 (* ------------------------------------------------------------------------- *)
   185 (* parse_std_result_file: scans a SAT solver's output file for a satisfying  *)
   186 (*      variable assignment.  Returns the assignment, or 'UNSATISFIABLE' if  *)
   187 (*      the file contains 'unsatisfiable', or 'UNKNOWN' if the file contains *)
   188 (*      neither 'satisfiable' nor 'unsatisfiable'.  Empty lines are ignored. *)
   189 (*      The assignment must be given in one or more lines immediately after  *)
   190 (*      the line that contains 'satisfiable'.  These lines must begin with   *)
   191 (*      'assignment_prefix'.  Variables must be separated by " ".  Non-      *)
   192 (*      integer strings are ignored.  If variable i is contained in the      *)
   193 (*      assignment, then i is interpreted as 'true'.  If ~i is contained in  *)
   194 (*      the assignment, then i is interpreted as 'false'.  Otherwise the     *)
   195 (*      value of i is taken to be unspecified.                               *)
   196 (* ------------------------------------------------------------------------- *)
   197 
   198 	(* Path.T -> string * string * string -> result *)
   199 
   200 	fun parse_std_result_file path (satisfiable, assignment_prefix, unsatisfiable) =
   201 	let
   202 		(* string -> int list *)
   203 		fun int_list_from_string s =
   204 			List.mapPartial Int.fromString (space_explode " " s)
   205 		(* int list -> assignment *)
   206 		fun assignment_from_list [] i =
   207 			NONE  (* the SAT solver didn't provide a value for this variable *)
   208 		  | assignment_from_list (x::xs) i =
   209 			if x=i then (SOME true)
   210 			else if x=(~i) then (SOME false)
   211 			else assignment_from_list xs i
   212 		(* int list -> string list -> assignment *)
   213 		fun parse_assignment xs [] =
   214 			assignment_from_list xs
   215 		  | parse_assignment xs (line::lines) =
   216 			if String.isPrefix assignment_prefix line then
   217 				parse_assignment (xs @ int_list_from_string line) lines
   218 			else
   219 				assignment_from_list xs
   220 		(* string -> string -> bool *)
   221 		fun is_substring needle haystack =
   222 		let
   223 			val length1 = String.size needle
   224 			val length2 = String.size haystack
   225 		in
   226 			if length2 < length1 then
   227 				false
   228 			else if needle = String.substring (haystack, 0, length1) then
   229 				true
   230 			else is_substring needle (String.substring (haystack, 1, length2-1))
   231 		end
   232 		(* string list -> result *)
   233 		fun parse_lines [] =
   234 			UNKNOWN
   235 		  | parse_lines (line::lines) =
   236 			if is_substring satisfiable line then
   237 				SATISFIABLE (parse_assignment [] lines)
   238 			else if is_substring unsatisfiable line then
   239 				UNSATISFIABLE
   240 			else
   241 				parse_lines lines
   242 	in
   243 		(parse_lines o (List.filter (fn l => l <> "")) o split_lines o File.read) path
   244 	end;
   245 
   246 (* ------------------------------------------------------------------------- *)
   247 (* make_external_solver: call 'writefn', execute 'cmd', call 'readfn'        *)
   248 (* ------------------------------------------------------------------------- *)
   249 
   250 	(* string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver *)
   251 
   252 	fun make_external_solver cmd writefn readfn fm =
   253 		(writefn fm; system cmd; readfn ());
   254 
   255 (* ------------------------------------------------------------------------- *)
   256 (* read_dimacs_cnf_file: returns a propositional formula that corresponds to *)
   257 (*      a SAT problem given in DIMACS CNF format                             *)
   258 (* ------------------------------------------------------------------------- *)
   259 
   260 	(* Path.T -> PropLogic.prop_formula *)
   261 
   262 	fun read_dimacs_cnf_file path =
   263 	let
   264 		(* string list -> string list *)
   265 		fun filter_preamble [] =
   266 			error "problem line not found in DIMACS CNF file"
   267 		  | filter_preamble (line::lines) =
   268 			if String.isPrefix "c " line then
   269 				(* ignore comments *)
   270 				filter_preamble lines
   271 			else if String.isPrefix "p " line then
   272 				(* ignore the problem line (which must be the last line of the preamble) *)
   273 				(* Ignoring the problem line implies that if the file contains more clauses *)
   274 				(* or variables than specified in its preamble, we will accept it anyway.   *)
   275 				lines
   276 			else
   277 				error "preamble in DIMACS CNF file contains a line that does not begin with \"c \" or \"p \""
   278 		(* string -> int *)
   279 		fun int_from_string s =
   280 			case Int.fromString s of
   281 			  SOME i => i
   282 			| NONE   => error ("token " ^ quote s ^ "in DIMACS CNF file is not a number")
   283 		(* int list -> int list list *)
   284 		fun clauses xs =
   285 			let
   286 				val (xs1, xs2) = take_prefix (fn i => i <> 0) xs
   287 			in
   288 				case xs2 of
   289 				  []      => [xs1]
   290 				| (0::[]) => [xs1]
   291 				| (0::tl) => xs1 :: clauses tl
   292 				| _       => raise ERROR  (* this cannot happen *)
   293 			end
   294 		(* int -> PropLogic.prop_formula *)
   295 		fun literal_from_int i =
   296 			(assert (i<>0) "variable index in DIMACS CNF file is 0";
   297 			if i>0 then
   298 				PropLogic.BoolVar i
   299 			else
   300 				PropLogic.Not (PropLogic.BoolVar (~i)))
   301 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   302 		fun disjunction [] =
   303 			error "empty clause in DIMACS CNF file"
   304 		  | disjunction (x::xs) =
   305 			(case xs of
   306 			  [] => x
   307 			| _  => PropLogic.Or (x, disjunction xs))
   308 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   309 		fun conjunction [] =
   310 			error "no clause in DIMACS CNF file"
   311 		  | conjunction (x::xs) =
   312 			(case xs of
   313 			  [] => x
   314 			| _  => PropLogic.And (x, conjunction xs))
   315 	in
   316 		(conjunction
   317 		o (map disjunction)
   318 		o (map (map literal_from_int))
   319 		o clauses
   320 		o (map int_from_string)
   321 		o List.concat
   322 		o (map (String.fields (fn c => c mem [#" ", #"\t", #"\n"])))
   323 		o filter_preamble
   324 		o (List.filter (fn l => l <> ""))
   325 		o split_lines
   326 		o File.read)
   327 			path
   328 	end;
   329 
   330 (* ------------------------------------------------------------------------- *)
   331 (* solvers: a (reference to a) table of all registered SAT solvers           *)
   332 (* ------------------------------------------------------------------------- *)
   333 
   334 	val solvers = ref ([] : (string * solver) list);
   335 
   336 (* ------------------------------------------------------------------------- *)
   337 (* add_solver: updates 'solvers' by adding a new solver                      *)
   338 (* ------------------------------------------------------------------------- *)
   339 
   340 	(* string * solver -> unit *)
   341 
   342 	fun add_solver (name, new_solver) =
   343 		(solvers := overwrite_warn (!solvers, (name, new_solver)) ("SAT solver " ^ quote name ^ " was defined before"));
   344 
   345 (* ------------------------------------------------------------------------- *)
   346 (* invoke_solver: returns the solver associated with the given 'name'        *)
   347 (* Note: If no solver is associated with 'name', exception 'Option' will be  *)
   348 (*       raised.                                                             *)
   349 (* ------------------------------------------------------------------------- *)
   350 
   351 	(* string -> solver *)
   352 
   353 	fun invoke_solver name =
   354 		(valOf o assoc) (!solvers, name);
   355 
   356 end;  (* SatSolver *)
   357 
   358 
   359 (* ------------------------------------------------------------------------- *)
   360 (* Predefined SAT solvers                                                    *)
   361 (* ------------------------------------------------------------------------- *)
   362 
   363 (* ------------------------------------------------------------------------- *)
   364 (* Internal SAT solver, available as 'SatSolver.invoke_solver "enumerate"'   *)
   365 (* -- simply enumerates assignments until a satisfying assignment is found   *)
   366 (* ------------------------------------------------------------------------- *)
   367 
   368 let
   369 	fun enum_solver fm =
   370 	let
   371 		(* int list *)
   372 		val indices = PropLogic.indices fm
   373 		(* int list -> int list -> int list option *)
   374 		(* binary increment: list 'xs' of current bits, list 'ys' of all bits (lower bits first) *)
   375 		fun next_list _ ([]:int list) =
   376 			NONE
   377 		  | next_list [] (y::ys) =
   378 			SOME [y]
   379 		  | next_list (x::xs) (y::ys) =
   380 			if x=y then
   381 				(* reset the bit, continue *)
   382 				next_list xs ys
   383 			else
   384 				(* set the lowest bit that wasn't set before, keep the higher bits *)
   385 				SOME (y::x::xs)
   386 		(* int list -> int -> bool *)
   387 		fun assignment_from_list xs i =
   388 			i mem xs
   389 		(* int list -> SatSolver.result *)
   390 		fun solver_loop xs =
   391 			if PropLogic.eval (assignment_from_list xs) fm then
   392 				SatSolver.SATISFIABLE (SOME o (assignment_from_list xs))
   393 			else
   394 				(case next_list xs indices of
   395 				  SOME xs' => solver_loop xs'
   396 				| NONE     => SatSolver.UNSATISFIABLE)
   397 	in
   398 		(* start with the "first" assignment (all variables are interpreted as 'false') *)
   399 		solver_loop []
   400 	end
   401 in
   402 	SatSolver.add_solver ("enumerate", enum_solver)
   403 end;
   404 
   405 (* ------------------------------------------------------------------------- *)
   406 (* Internal SAT solver, available as 'SatSolver.invoke_solver "dpll"' -- a   *)
   407 (* simple implementation of the DPLL algorithm (cf. L. Zhang, S. Malik: "The *)
   408 (* Quest for Efficient Boolean Satisfiability Solvers", July 2002, Fig. 1).  *)
   409 (* ------------------------------------------------------------------------- *)
   410 
   411 let
   412 	local
   413 		open PropLogic
   414 	in
   415 		fun dpll_solver fm =
   416 		let
   417 			(* We could use 'PropLogic.defcnf fm' instead of 'PropLogic.nnf fm' *)
   418 			(* but that sometimes introduces more boolean variables than we can *)
   419 			(* handle efficiently.                                              *)
   420 			val fm' = PropLogic.nnf fm
   421 			(* int list *)
   422 			val indices = PropLogic.indices fm'
   423 			(* int list -> int -> prop_formula *)
   424 			fun partial_var_eval []      i = BoolVar i
   425 			  | partial_var_eval (x::xs) i = if x=i then True else if x=(~i) then False else partial_var_eval xs i
   426 			(* int list -> prop_formula -> prop_formula *)
   427 			fun partial_eval xs True             = True
   428 			  | partial_eval xs False            = False
   429 			  | partial_eval xs (BoolVar i)      = partial_var_eval xs i
   430 			  | partial_eval xs (Not fm)         = SNot (partial_eval xs fm)
   431 			  | partial_eval xs (Or (fm1, fm2))  = SOr (partial_eval xs fm1, partial_eval xs fm2)
   432 			  | partial_eval xs (And (fm1, fm2)) = SAnd (partial_eval xs fm1, partial_eval xs fm2)
   433 			(* prop_formula -> int list *)
   434 			fun forced_vars True              = []
   435 			  | forced_vars False             = []
   436 			  | forced_vars (BoolVar i)       = [i]
   437 			  | forced_vars (Not (BoolVar i)) = [~i]
   438 			  | forced_vars (Or (fm1, fm2))   = (forced_vars fm1) inter_int (forced_vars fm2)
   439 			  | forced_vars (And (fm1, fm2))  = (forced_vars fm1) union_int (forced_vars fm2)
   440 			  (* Above, i *and* ~i may be forced.  In this case the first occurrence takes   *)
   441 			  (* precedence, and the next partial evaluation of the formula returns 'False'. *)
   442 			  | forced_vars _                 = raise ERROR  (* formula is not in negation normal form *)
   443 			(* int list -> prop_formula -> (int list * prop_formula) *)
   444 			fun eval_and_force xs fm =
   445 			let
   446 				val fm' = partial_eval xs fm
   447 				val xs' = forced_vars fm'
   448 			in
   449 				if null xs' then
   450 					(xs, fm')
   451 				else
   452 					eval_and_force (xs@xs') fm'  (* xs and xs' should be distinct, so '@' here should have *)
   453 					                             (* the same effect as 'union_int'                         *)
   454 			end
   455 			(* int list -> int option *)
   456 			fun fresh_var xs =
   457 				Library.find_first (fn i => not (i mem_int xs) andalso not ((~i) mem_int xs)) indices
   458 			(* int list -> prop_formula -> int list option *)
   459 			(* partial assignment 'xs' *)
   460 			fun dpll xs fm =
   461 			let
   462 				val (xs', fm') = eval_and_force xs fm
   463 			in
   464 				case fm' of
   465 				  True  => SOME xs'
   466 				| False => NONE
   467 				| _     =>
   468 					let
   469 						val x = valOf (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
   470 					in
   471 						case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
   472 						  SOME xs'' => SOME xs''
   473 						| NONE      => dpll ((~x)::xs') fm'  (* now try interpreting 'x' as 'False' *)
   474 					end
   475 			end
   476 			(* int list -> assignment *)
   477 			fun assignment_from_list [] i =
   478 				NONE  (* the DPLL procedure didn't provide a value for this variable *)
   479 			  | assignment_from_list (x::xs) i =
   480 				if x=i then (SOME true)
   481 				else if x=(~i) then (SOME false)
   482 				else assignment_from_list xs i
   483 		in
   484 			(* initially, no variable is interpreted yet *)
   485 			case dpll [] fm' of
   486 			  SOME assignment => SatSolver.SATISFIABLE (assignment_from_list assignment)
   487 			| NONE            => SatSolver.UNSATISFIABLE
   488 		end
   489 	end  (* local *)
   490 in
   491 	SatSolver.add_solver ("dpll", dpll_solver)
   492 end;
   493 
   494 (* ------------------------------------------------------------------------- *)
   495 (* Internal SAT solver, available as 'SatSolver.invoke_solver "auto"': uses  *)
   496 (* the first installed solver (other than "auto" itself) that does not raise *)
   497 (* 'NOT_CONFIGURED'.  (However, the solver may return 'UNKNOWN'.)            *)
   498 (* ------------------------------------------------------------------------- *)
   499 
   500 let
   501 	fun auto_solver fm =
   502 	let
   503 		fun loop [] =
   504 			SatSolver.UNKNOWN
   505 		  | loop ((name, solver)::solvers) =
   506 			if name="auto" then
   507 				(* do not call solver "auto" from within "auto" *)
   508 				loop solvers
   509 			else (
   510 				(if name="dpll" orelse name="enumerate" then
   511 					warning ("Using SAT solver " ^ quote name ^ "; for better performance, consider using an external solver.")
   512 				else
   513 					());
   514 				(* apply 'solver' to 'fm' *)
   515 				solver fm
   516 					handle SatSolver.NOT_CONFIGURED => loop solvers
   517 			)
   518 	in
   519 		loop (rev (!SatSolver.solvers))
   520 	end
   521 in
   522 	SatSolver.add_solver ("auto", auto_solver)
   523 end;
   524 
   525 (* ------------------------------------------------------------------------- *)
   526 (* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
   527 (* ------------------------------------------------------------------------- *)
   528 
   529 let
   530 	fun zchaff fm =
   531 	let
   532 		val _          = if (getenv "ZCHAFF_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   533 		val _          = if (getenv "ZCHAFF_VERSION") <> "2004.5.13" andalso
   534 		                    (getenv "ZCHAFF_VERSION") <> "2004.11.15" then raise SatSolver.NOT_CONFIGURED else ()
   535 			(* both versions of zChaff appear to have the same interface, so we do *)
   536 			(* not actually need to distinguish between them in the following code *)
   537 		val satpath    = File.tmp_path (Path.unpack "isabelle.sat")
   538 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   539 		val outpath    = File.tmp_path (Path.unpack "result")
   540 		val cmd        = (getenv "ZCHAFF_HOME") ^ "/zchaff " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   541 		fun writefn fm = (SatSolver.write_dimacs_sat_file satpath fm; SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm))
   542 		fun readfn ()  = SatSolver.parse_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
   543 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   544 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   545 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   546 		val _          = try File.rm inpath
   547 		val _          = try File.rm outpath
   548 	in
   549 		result
   550 	end
   551 in
   552 	SatSolver.add_solver ("zchaff", zchaff)
   553 end;
   554 
   555 (* ------------------------------------------------------------------------- *)
   556 (* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
   557 (* ------------------------------------------------------------------------- *)
   558 
   559 let
   560 	fun berkmin fm =
   561 	let
   562 		val _          = if (getenv "BERKMIN_HOME") = "" orelse (getenv "BERKMIN_EXE") = "" then raise SatSolver.NOT_CONFIGURED else ()
   563 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   564 		val outpath    = File.tmp_path (Path.unpack "result")
   565 		val cmd        = (getenv "BERKMIN_HOME") ^ "/" ^ (getenv "BERKMIN_EXE") ^ " " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   566 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   567 		fun readfn ()  = SatSolver.parse_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
   568 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   569 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   570 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   571 		val _          = try File.rm inpath
   572 		val _          = try File.rm outpath
   573 	in
   574 		result
   575 	end
   576 in
   577 	SatSolver.add_solver ("berkmin", berkmin)
   578 end;
   579 
   580 (* ------------------------------------------------------------------------- *)
   581 (* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
   582 (* ------------------------------------------------------------------------- *)
   583 
   584 let
   585 	fun jerusat fm =
   586 	let
   587 		val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   588 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   589 		val outpath    = File.tmp_path (Path.unpack "result")
   590 		val cmd        = (getenv "JERUSAT_HOME") ^ "/Jerusat1.3 " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   591 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   592 		fun readfn ()  = SatSolver.parse_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
   593 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   594 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   595 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   596 		val _          = try File.rm inpath
   597 		val _          = try File.rm outpath
   598 	in
   599 		result
   600 	end
   601 in
   602 	SatSolver.add_solver ("jerusat", jerusat)
   603 end;
   604 
   605 (* ------------------------------------------------------------------------- *)
   606 (* Add code for other SAT solvers below.                                     *)
   607 (* ------------------------------------------------------------------------- *)
   608 
   609 (*
   610 let
   611 	fun mysolver fm = ...
   612 in
   613 	SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
   614 end;
   615 
   616 -- the solver is now available as SatSolver.invoke_solver "myname"
   617 *)