src/HOL/Tools/sat_solver.ML
author wenzelm
Sat Jan 14 17:14:06 2006 +0100 (2006-01-14)
changeset 18678 dd0c569fa43d
parent 17621 afffade1697e
child 19190 7c311c513bae
permissions -rw-r--r--
sane ERROR handling;
     1 (*  Title:      HOL/Tools/sat_solver.ML
     2     ID:         $Id$
     3     Author:     Tjark Weber
     4     Copyright   2004-2005
     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 	type proof      = int list Inttab.table * int
    15 	datatype result = SATISFIABLE of assignment
    16 	                | UNSATISFIABLE of proof option
    17 	                | UNKNOWN
    18 	type solver     = PropLogic.prop_formula -> result
    19 
    20 	(* auxiliary functions to create external SAT solvers *)
    21 	val write_dimacs_cnf_file : Path.T -> PropLogic.prop_formula -> unit
    22 	val write_dimacs_sat_file : Path.T -> PropLogic.prop_formula -> unit
    23 	val read_std_result_file  : Path.T -> string * string * string -> result
    24 	val make_external_solver  : string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver
    25 
    26 	val read_dimacs_cnf_file : Path.T -> PropLogic.prop_formula
    27 
    28 	(* generic solver interface *)
    29 	val solvers       : (string * solver) list ref
    30 	val add_solver    : string * solver -> unit
    31 	val invoke_solver : string -> solver  (* exception Option *)
    32 end;
    33 
    34 structure SatSolver : SAT_SOLVER =
    35 struct
    36 
    37 	open PropLogic;
    38 
    39 (* ------------------------------------------------------------------------- *)
    40 (* should be raised by an external SAT solver to indicate that the solver is *)
    41 (* not configured properly                                                   *)
    42 (* ------------------------------------------------------------------------- *)
    43 
    44 	exception NOT_CONFIGURED;
    45 
    46 (* ------------------------------------------------------------------------- *)
    47 (* type of partial (satisfying) assignments: 'a i = NONE' means that 'a' is  *)
    48 (*      a satisfying assigment regardless of the value of variable 'i'       *)
    49 (* ------------------------------------------------------------------------- *)
    50 
    51 	type assignment = int -> bool option;
    52 
    53 (* ------------------------------------------------------------------------- *)
    54 (* a proof of unsatisfiability, to be interpreted as follows: each integer   *)
    55 (*      is a clause ID, each list 'xs' stored under the key 'x' in the table *)
    56 (*      contains the IDs of clauses that must be resolved (in the given      *)
    57 (*      order) to obtain the new clause 'x'.  Each list 'xs' must be         *)
    58 (*      non-empty, and the literal to be resolved upon must always be unique *)
    59 (*      (e.g. "A | ~B" must not be resolved with "~A | B").  Circular        *)
    60 (*      dependencies of clauses are not allowed.  (At least) one of the      *)
    61 (*      clauses in the table must be the empty clause (i.e. contain no       *)
    62 (*      literals); its ID is given by the second component of the proof.     *)
    63 (*      The clauses of the original problem passed to the SAT solver have    *)
    64 (*      consecutive IDs starting with 0.  Clause IDs must be non-negative,   *)
    65 (*      but do not need to be consecutive.                                   *)
    66 (* ------------------------------------------------------------------------- *)
    67 
    68 	type proof = int list Inttab.table * int;
    69 
    70 (* ------------------------------------------------------------------------- *)
    71 (* return type of SAT solvers: if the result is 'SATISFIABLE', a satisfying  *)
    72 (*      assignment must be returned as well; if the result is                *)
    73 (*      'UNSATISFIABLE', a proof of unsatisfiability may be returned         *)
    74 (* ------------------------------------------------------------------------- *)
    75 
    76 	datatype result = SATISFIABLE of assignment
    77 	                | UNSATISFIABLE of proof option
    78 	                | UNKNOWN;
    79 
    80 (* ------------------------------------------------------------------------- *)
    81 (* type of SAT solvers: given a propositional formula, a satisfying          *)
    82 (*      assignment may be returned                                           *)
    83 (* ------------------------------------------------------------------------- *)
    84 
    85 	type solver = prop_formula -> result;
    86 
    87 (* ------------------------------------------------------------------------- *)
    88 (* write_dimacs_cnf_file: serializes a formula 'fm' of propositional logic   *)
    89 (*      to a file in DIMACS CNF format (see "Satisfiability Suggested        *)
    90 (*      Format", May 8 1993, Section 2.1)                                    *)
    91 (* Note: 'fm' must not contain a variable index less than 1.                 *)
    92 (* Note: 'fm' must be given in CNF.                                          *)
    93 (* ------------------------------------------------------------------------- *)
    94 
    95 	(* Path.T -> prop_formula -> unit *)
    96 
    97 	fun write_dimacs_cnf_file path fm =
    98 	let
    99 		(* prop_formula -> prop_formula *)
   100 		fun cnf_True_False_elim True =
   101 			Or (BoolVar 1, Not (BoolVar 1))
   102 		  | cnf_True_False_elim False =
   103 			And (BoolVar 1, Not (BoolVar 1))
   104 		  | cnf_True_False_elim fm =
   105 			fm  (* since 'fm' is in CNF, either 'fm'='True'/'False', or 'fm' does not contain 'True'/'False' at all *)
   106 		(* prop_formula -> int *)
   107 		fun cnf_number_of_clauses (And (fm1,fm2)) =
   108 			(cnf_number_of_clauses fm1) + (cnf_number_of_clauses fm2)
   109 		  | cnf_number_of_clauses _ =
   110 			1
   111 		(* prop_formula -> string list *)
   112 		fun cnf_string fm =
   113 		let
   114 			(* prop_formula -> string list -> string list *)
   115 			fun cnf_string_acc True acc =
   116 				error "formula is not in CNF"
   117 			  | cnf_string_acc False acc =
   118 				error "formula is not in CNF"
   119 			  | cnf_string_acc (BoolVar i) acc =
   120 				(assert (i>=1) "formula contains a variable index less than 1";
   121 				string_of_int i :: acc)
   122 			  | cnf_string_acc (Not (BoolVar i)) acc =
   123 				"-" :: cnf_string_acc (BoolVar i) acc
   124 			  | cnf_string_acc (Not _) acc =
   125 				error "formula is not in CNF"
   126 			  | cnf_string_acc (Or (fm1,fm2)) acc =
   127 				cnf_string_acc fm1 (" " :: cnf_string_acc fm2 acc)
   128 			  | cnf_string_acc (And (fm1,fm2)) acc =
   129 				cnf_string_acc fm1 (" 0\n" :: cnf_string_acc fm2 acc)
   130 		in
   131 			cnf_string_acc fm []
   132 		end
   133 		val fm'               = cnf_True_False_elim fm
   134 		val number_of_vars    = maxidx fm'
   135 		val number_of_clauses = cnf_number_of_clauses fm'
   136 	in
   137 		File.write path
   138 			("c This file was generated by SatSolver.write_dimacs_cnf_file\n" ^
   139 			 "p cnf " ^ string_of_int number_of_vars ^ " " ^ string_of_int number_of_clauses ^ "\n");
   140 		File.append_list path
   141 			(cnf_string fm');
   142 		File.append path
   143 			" 0\n"
   144 	end;
   145 
   146 (* ------------------------------------------------------------------------- *)
   147 (* write_dimacs_sat_file: serializes a formula 'fm' of propositional logic   *)
   148 (*      to a file in DIMACS SAT format (see "Satisfiability Suggested        *)
   149 (*      Format", May 8 1993, Section 2.2)                                    *)
   150 (* Note: 'fm' must not contain a variable index less than 1.                 *)
   151 (* ------------------------------------------------------------------------- *)
   152 
   153 	(* Path.T -> prop_formula -> unit *)
   154 
   155 	fun write_dimacs_sat_file path fm =
   156 	let
   157 		(* prop_formula -> string list *)
   158 		fun sat_string fm =
   159 		let
   160 			(* prop_formula -> string list -> string list *)
   161 			fun sat_string_acc True acc =
   162 				"*()" :: acc
   163 			  | sat_string_acc False acc =
   164 				"+()" :: acc
   165 			  | sat_string_acc (BoolVar i) acc =
   166 				(assert (i>=1) "formula contains a variable index less than 1";
   167 				string_of_int i :: acc)
   168 			  | sat_string_acc (Not (BoolVar i)) acc =
   169 				"-" :: sat_string_acc (BoolVar i) acc
   170 			  | sat_string_acc (Not fm) acc =
   171 				"-(" :: sat_string_acc fm (")" :: acc)
   172 			  | sat_string_acc (Or (fm1,fm2)) acc =
   173 				"+(" :: sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 (")" :: acc))
   174 			  | sat_string_acc (And (fm1,fm2)) acc =
   175 				"*(" :: sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 (")" :: acc))
   176 			(* optimization to make use of n-ary disjunction/conjunction *)
   177 			(* prop_formula -> string list -> string list *)
   178 			and sat_string_acc_or (Or (fm1,fm2)) acc =
   179 				sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 acc)
   180 			  | sat_string_acc_or fm acc =
   181 				sat_string_acc fm acc
   182 			(* prop_formula -> string list -> string list *)
   183 			and sat_string_acc_and (And (fm1,fm2)) acc =
   184 				sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 acc)
   185 			  | sat_string_acc_and fm acc =
   186 				sat_string_acc fm acc
   187 		in
   188 			sat_string_acc fm []
   189 		end
   190 		val number_of_vars = Int.max (maxidx fm, 1)
   191 	in
   192 		File.write path
   193 			("c This file was generated by SatSolver.write_dimacs_sat_file\n" ^
   194 			 "p sat " ^ string_of_int number_of_vars ^ "\n" ^
   195 			 "(");
   196 		File.append_list path
   197 			(sat_string fm);
   198 		File.append path
   199 			")\n"
   200 	end;
   201 
   202 (* ------------------------------------------------------------------------- *)
   203 (* read_std_result_file: scans a SAT solver's output file for a satisfying   *)
   204 (*      variable assignment.  Returns the assignment, or 'UNSATISFIABLE' if  *)
   205 (*      the file contains 'unsatisfiable', or 'UNKNOWN' if the file contains *)
   206 (*      neither 'satisfiable' nor 'unsatisfiable'.  Empty lines are ignored. *)
   207 (*      The assignment must be given in one or more lines immediately after  *)
   208 (*      the line that contains 'satisfiable'.  These lines must begin with   *)
   209 (*      'assignment_prefix'.  Variables must be separated by " ".  Non-      *)
   210 (*      integer strings are ignored.  If variable i is contained in the      *)
   211 (*      assignment, then i is interpreted as 'true'.  If ~i is contained in  *)
   212 (*      the assignment, then i is interpreted as 'false'.  Otherwise the     *)
   213 (*      value of i is taken to be unspecified.                               *)
   214 (* ------------------------------------------------------------------------- *)
   215 
   216 	(* Path.T -> string * string * string -> result *)
   217 
   218 	fun read_std_result_file path (satisfiable, assignment_prefix, unsatisfiable) =
   219 	let
   220 		(* string -> int list *)
   221 		fun int_list_from_string s =
   222 			List.mapPartial Int.fromString (space_explode " " s)
   223 		(* int list -> assignment *)
   224 		fun assignment_from_list [] i =
   225 			NONE  (* the SAT solver didn't provide a value for this variable *)
   226 		  | assignment_from_list (x::xs) i =
   227 			if x=i then (SOME true)
   228 			else if x=(~i) then (SOME false)
   229 			else assignment_from_list xs i
   230 		(* int list -> string list -> assignment *)
   231 		fun parse_assignment xs [] =
   232 			assignment_from_list xs
   233 		  | parse_assignment xs (line::lines) =
   234 			if String.isPrefix assignment_prefix line then
   235 				parse_assignment (xs @ int_list_from_string line) lines
   236 			else
   237 				assignment_from_list xs
   238 		(* string -> string -> bool *)
   239 		fun is_substring needle haystack =
   240 		let
   241 			val length1 = String.size needle
   242 			val length2 = String.size haystack
   243 		in
   244 			if length2 < length1 then
   245 				false
   246 			else if needle = String.substring (haystack, 0, length1) then
   247 				true
   248 			else is_substring needle (String.substring (haystack, 1, length2-1))
   249 		end
   250 		(* string list -> result *)
   251 		fun parse_lines [] =
   252 			UNKNOWN
   253 		  | parse_lines (line::lines) =
   254 			if is_substring satisfiable line then
   255 				SATISFIABLE (parse_assignment [] lines)
   256 			else if is_substring unsatisfiable line then
   257 				UNSATISFIABLE NONE
   258 			else
   259 				parse_lines lines
   260 	in
   261 		(parse_lines o (List.filter (fn l => l <> "")) o split_lines o File.read) path
   262 	end;
   263 
   264 (* ------------------------------------------------------------------------- *)
   265 (* make_external_solver: call 'writefn', execute 'cmd', call 'readfn'        *)
   266 (* ------------------------------------------------------------------------- *)
   267 
   268 	(* string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver *)
   269 
   270 	fun make_external_solver cmd writefn readfn fm =
   271 		(writefn fm; system cmd; readfn ());
   272 
   273 (* ------------------------------------------------------------------------- *)
   274 (* read_dimacs_cnf_file: returns a propositional formula that corresponds to *)
   275 (*      a SAT problem given in DIMACS CNF format                             *)
   276 (* ------------------------------------------------------------------------- *)
   277 
   278 	(* Path.T -> PropLogic.prop_formula *)
   279 
   280 	fun read_dimacs_cnf_file path =
   281 	let
   282 		(* string list -> string list *)
   283 		fun filter_preamble [] =
   284 			error "problem line not found in DIMACS CNF file"
   285 		  | filter_preamble (line::lines) =
   286 			if String.isPrefix "c " line then
   287 				(* ignore comments *)
   288 				filter_preamble lines
   289 			else if String.isPrefix "p " line then
   290 				(* ignore the problem line (which must be the last line of the preamble) *)
   291 				(* Ignoring the problem line implies that if the file contains more clauses *)
   292 				(* or variables than specified in its preamble, we will accept it anyway.   *)
   293 				lines
   294 			else
   295 				error "preamble in DIMACS CNF file contains a line that does not begin with \"c \" or \"p \""
   296 		(* string -> int *)
   297 		fun int_from_string s =
   298 			case Int.fromString s of
   299 			  SOME i => i
   300 			| NONE   => error ("token " ^ quote s ^ "in DIMACS CNF file is not a number")
   301 		(* int list -> int list list *)
   302 		fun clauses xs =
   303 			let
   304 				val (xs1, xs2) = take_prefix (fn i => i <> 0) xs
   305 			in
   306 				case xs2 of
   307 				  []      => [xs1]
   308 				| (0::[]) => [xs1]
   309 				| (0::tl) => xs1 :: clauses tl
   310 				| _       => sys_error "this cannot happen"
   311 			end
   312 		(* int -> PropLogic.prop_formula *)
   313 		fun literal_from_int i =
   314 			(assert (i<>0) "variable index in DIMACS CNF file is 0";
   315 			if i>0 then
   316 				PropLogic.BoolVar i
   317 			else
   318 				PropLogic.Not (PropLogic.BoolVar (~i)))
   319 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   320 		fun disjunction [] =
   321 			error "empty clause in DIMACS CNF file"
   322 		  | disjunction (x::xs) =
   323 			(case xs of
   324 			  [] => x
   325 			| _  => PropLogic.Or (x, disjunction xs))
   326 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   327 		fun conjunction [] =
   328 			error "no clause in DIMACS CNF file"
   329 		  | conjunction (x::xs) =
   330 			(case xs of
   331 			  [] => x
   332 			| _  => PropLogic.And (x, conjunction xs))
   333 	in
   334 		(conjunction
   335 		o (map disjunction)
   336 		o (map (map literal_from_int))
   337 		o clauses
   338 		o (map int_from_string)
   339 		o List.concat
   340 		o (map (String.fields (fn c => c mem [#" ", #"\t", #"\n"])))
   341 		o filter_preamble
   342 		o (List.filter (fn l => l <> ""))
   343 		o split_lines
   344 		o File.read)
   345 			path
   346 	end;
   347 
   348 (* ------------------------------------------------------------------------- *)
   349 (* solvers: a (reference to a) table of all registered SAT solvers           *)
   350 (* ------------------------------------------------------------------------- *)
   351 
   352 	val solvers = ref ([] : (string * solver) list);
   353 
   354 (* ------------------------------------------------------------------------- *)
   355 (* add_solver: updates 'solvers' by adding a new solver                      *)
   356 (* ------------------------------------------------------------------------- *)
   357 
   358 	(* string * solver -> unit *)
   359 
   360 	fun add_solver (name, new_solver) =
   361 		(solvers := update_warn (op =) ("SAT solver " ^ quote name ^ " was defined before") (name, new_solver) (!solvers));
   362 
   363 (* ------------------------------------------------------------------------- *)
   364 (* invoke_solver: returns the solver associated with the given 'name'        *)
   365 (* Note: If no solver is associated with 'name', exception 'Option' will be  *)
   366 (*       raised.                                                             *)
   367 (* ------------------------------------------------------------------------- *)
   368 
   369 	(* string -> solver *)
   370 
   371 	fun invoke_solver name =
   372 		(the o AList.lookup (op =) (!solvers)) name;
   373 
   374 end;  (* SatSolver *)
   375 
   376 
   377 (* ------------------------------------------------------------------------- *)
   378 (* Predefined SAT solvers                                                    *)
   379 (* ------------------------------------------------------------------------- *)
   380 
   381 (* ------------------------------------------------------------------------- *)
   382 (* Internal SAT solver, available as 'SatSolver.invoke_solver "enumerate"'   *)
   383 (* -- simply enumerates assignments until a satisfying assignment is found   *)
   384 (* ------------------------------------------------------------------------- *)
   385 
   386 let
   387 	fun enum_solver fm =
   388 	let
   389 		(* int list *)
   390 		val indices = PropLogic.indices fm
   391 		(* int list -> int list -> int list option *)
   392 		(* binary increment: list 'xs' of current bits, list 'ys' of all bits (lower bits first) *)
   393 		fun next_list _ ([]:int list) =
   394 			NONE
   395 		  | next_list [] (y::ys) =
   396 			SOME [y]
   397 		  | next_list (x::xs) (y::ys) =
   398 			if x=y then
   399 				(* reset the bit, continue *)
   400 				next_list xs ys
   401 			else
   402 				(* set the lowest bit that wasn't set before, keep the higher bits *)
   403 				SOME (y::x::xs)
   404 		(* int list -> int -> bool *)
   405 		fun assignment_from_list xs i =
   406 			i mem xs
   407 		(* int list -> SatSolver.result *)
   408 		fun solver_loop xs =
   409 			if PropLogic.eval (assignment_from_list xs) fm then
   410 				SatSolver.SATISFIABLE (SOME o (assignment_from_list xs))
   411 			else
   412 				(case next_list xs indices of
   413 				  SOME xs' => solver_loop xs'
   414 				| NONE     => SatSolver.UNSATISFIABLE NONE)
   415 	in
   416 		(* start with the "first" assignment (all variables are interpreted as 'false') *)
   417 		solver_loop []
   418 	end
   419 in
   420 	SatSolver.add_solver ("enumerate", enum_solver)
   421 end;
   422 
   423 (* ------------------------------------------------------------------------- *)
   424 (* Internal SAT solver, available as 'SatSolver.invoke_solver "dpll"' -- a   *)
   425 (* simple implementation of the DPLL algorithm (cf. L. Zhang, S. Malik: "The *)
   426 (* Quest for Efficient Boolean Satisfiability Solvers", July 2002, Fig. 1).  *)
   427 (* ------------------------------------------------------------------------- *)
   428 
   429 let
   430 	local
   431 		open PropLogic
   432 	in
   433 		fun dpll_solver fm =
   434 		let
   435 			(* We could use 'PropLogic.defcnf fm' instead of 'PropLogic.nnf fm' *)
   436 			(* but that sometimes leads to worse performance due to the         *)
   437 			(* introduction of additional variables.                            *)
   438 			val fm' = PropLogic.nnf fm
   439 			(* int list *)
   440 			val indices = PropLogic.indices fm'
   441 			(* int list -> int -> prop_formula *)
   442 			fun partial_var_eval []      i = BoolVar i
   443 			  | partial_var_eval (x::xs) i = if x=i then True else if x=(~i) then False else partial_var_eval xs i
   444 			(* int list -> prop_formula -> prop_formula *)
   445 			fun partial_eval xs True             = True
   446 			  | partial_eval xs False            = False
   447 			  | partial_eval xs (BoolVar i)      = partial_var_eval xs i
   448 			  | partial_eval xs (Not fm)         = SNot (partial_eval xs fm)
   449 			  | partial_eval xs (Or (fm1, fm2))  = SOr (partial_eval xs fm1, partial_eval xs fm2)
   450 			  | partial_eval xs (And (fm1, fm2)) = SAnd (partial_eval xs fm1, partial_eval xs fm2)
   451 			(* prop_formula -> int list *)
   452 			fun forced_vars True              = []
   453 			  | forced_vars False             = []
   454 			  | forced_vars (BoolVar i)       = [i]
   455 			  | forced_vars (Not (BoolVar i)) = [~i]
   456 			  | forced_vars (Or (fm1, fm2))   = (forced_vars fm1) inter_int (forced_vars fm2)
   457 			  | forced_vars (And (fm1, fm2))  = (forced_vars fm1) union_int (forced_vars fm2)
   458 			  (* Above, i *and* ~i may be forced.  In this case the first occurrence takes   *)
   459 			  (* precedence, and the next partial evaluation of the formula returns 'False'. *)
   460 			  | forced_vars _                 = error "formula is not in negation normal form"
   461 			(* int list -> prop_formula -> (int list * prop_formula) *)
   462 			fun eval_and_force xs fm =
   463 			let
   464 				val fm' = partial_eval xs fm
   465 				val xs' = forced_vars fm'
   466 			in
   467 				if null xs' then
   468 					(xs, fm')
   469 				else
   470 					eval_and_force (xs@xs') fm'  (* xs and xs' should be distinct, so '@' here should have *)
   471 					                             (* the same effect as 'union_int'                         *)
   472 			end
   473 			(* int list -> int option *)
   474 			fun fresh_var xs =
   475 				Library.find_first (fn i => not (i mem_int xs) andalso not ((~i) mem_int xs)) indices
   476 			(* int list -> prop_formula -> int list option *)
   477 			(* partial assignment 'xs' *)
   478 			fun dpll xs fm =
   479 			let
   480 				val (xs', fm') = eval_and_force xs fm
   481 			in
   482 				case fm' of
   483 				  True  => SOME xs'
   484 				| False => NONE
   485 				| _     =>
   486 					let
   487 						val x = valOf (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
   488 					in
   489 						case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
   490 						  SOME xs'' => SOME xs''
   491 						| NONE      => dpll ((~x)::xs') fm'  (* now try interpreting 'x' as 'False' *)
   492 					end
   493 			end
   494 			(* int list -> assignment *)
   495 			fun assignment_from_list [] i =
   496 				NONE  (* the DPLL procedure didn't provide a value for this variable *)
   497 			  | assignment_from_list (x::xs) i =
   498 				if x=i then (SOME true)
   499 				else if x=(~i) then (SOME false)
   500 				else assignment_from_list xs i
   501 		in
   502 			(* initially, no variable is interpreted yet *)
   503 			case dpll [] fm' of
   504 			  SOME assignment => SatSolver.SATISFIABLE (assignment_from_list assignment)
   505 			| NONE            => SatSolver.UNSATISFIABLE NONE
   506 		end
   507 	end  (* local *)
   508 in
   509 	SatSolver.add_solver ("dpll", dpll_solver)
   510 end;
   511 
   512 (* ------------------------------------------------------------------------- *)
   513 (* Internal SAT solver, available as 'SatSolver.invoke_solver "auto"': uses  *)
   514 (* the last installed solver (other than "auto" itself) that does not raise  *)
   515 (* 'NOT_CONFIGURED'.  (However, the solver may return 'UNKNOWN'.)            *)
   516 (* ------------------------------------------------------------------------- *)
   517 
   518 let
   519 	fun auto_solver fm =
   520 	let
   521 		fun loop [] =
   522 			SatSolver.UNKNOWN
   523 		  | loop ((name, solver)::solvers) =
   524 			if name="auto" then
   525 				(* do not call solver "auto" from within "auto" *)
   526 				loop solvers
   527 			else (
   528 				(if name="dpll" orelse name="enumerate" then
   529 					warning ("Using SAT solver " ^ quote name ^ "; for better performance, consider using an external solver.")
   530 				else
   531 					Output.debug ("Using SAT solver " ^ quote name ^ "."));
   532 				(* apply 'solver' to 'fm' *)
   533 				solver fm
   534 					handle SatSolver.NOT_CONFIGURED => loop solvers
   535 			)
   536 	in
   537 		loop (!SatSolver.solvers)
   538 	end
   539 in
   540 	SatSolver.add_solver ("auto", auto_solver)
   541 end;
   542 
   543 (* ------------------------------------------------------------------------- *)
   544 (* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
   545 (* ------------------------------------------------------------------------- *)
   546 
   547 (* ------------------------------------------------------------------------- *)
   548 (* 'zchaff_with_proofs' applies the "zchaff" prover to a formula, and if     *)
   549 (* zChaff finds that the formula is unsatisfiable, a proof of this is read   *)
   550 (* from a file "resolve_trace" that was generated by zChaff.  See the code   *)
   551 (* below for the expected format of the "resolve_trace" file.  Aside from    *)
   552 (* some basic syntactic checks, no verification of the proof is performed.   *)
   553 (* ------------------------------------------------------------------------- *)
   554 
   555 (* add "zchaff_with_proofs" _before_ "zchaff" to the available solvers, so   *)
   556 (* that the latter is preferred by the "auto" solver                         *)
   557 
   558 let
   559 	exception INVALID_PROOF of string
   560 	fun zchaff_with_proofs fm =
   561 	case SatSolver.invoke_solver "zchaff" fm of
   562 	  SatSolver.UNSATISFIABLE NONE =>
   563 		(let
   564 			(* string list *)
   565 			val proof_lines = ((split_lines o File.read) (Path.unpack "resolve_trace"))
   566 				handle _ => raise INVALID_PROOF "Could not read file \"resolve_trace\""
   567 			(* PropLogic.prop_formula -> int *)
   568 			fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) = cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
   569 			  | cnf_number_of_clauses _                          = 1
   570 			(* string -> int *)
   571 			fun int_from_string s = (
   572 				case Int.fromString s of
   573 				  SOME i => i
   574 				| NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
   575 			)
   576 			(* parse the "resolve_trace" file *)
   577 			(* int ref *)
   578 			val clause_offset = ref ~1
   579 			(* string list -> proof -> proof *)
   580 			fun process_tokens [] proof =
   581 				proof
   582 			  | process_tokens (tok::toks) (clause_table, empty_id) =
   583 				if tok="CL:" then (
   584 					case toks of
   585 					  id::sep::ids =>
   586 						let
   587 							val _   = if !clause_offset = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"VAR:\".")
   588 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"CONF:\".")
   589 							val cid = int_from_string id
   590 							val _   = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   591 							val rs  = map int_from_string ids
   592 						in
   593 							(* update clause table *)
   594 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   595 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once.")
   596 						end
   597 					| _ =>
   598 						raise INVALID_PROOF "File format error: \"CL:\" followed by an insufficient number of tokens."
   599 				) else if tok="VAR:" then (
   600 					case toks of
   601 					  id::levsep::levid::valsep::valid::antesep::anteid::litsep::lits =>
   602 						let
   603 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"VAR:\" disallowed after \"CONF:\".")
   604 							(* set 'clause_offset' to the largest used clause ID *)
   605 							val _   = if !clause_offset = ~1 then clause_offset :=
   606 								(case Inttab.max_key clause_table of
   607 								  SOME id => id
   608 								| NONE    => cnf_number_of_clauses (PropLogic.defcnf fm) - 1  (* the first clause ID is 0, not 1 *))
   609 								else
   610 									()
   611 							val vid = int_from_string id
   612 							val _   = if levsep = "L:" then () else raise INVALID_PROOF ("File format error: \"L:\" expected (" ^ quote levsep ^ " encountered).")
   613 							val _   = int_from_string levid
   614 							val _   = if valsep = "V:" then () else raise INVALID_PROOF ("File format error: \"V:\" expected (" ^ quote valsep ^ " encountered).")
   615 							val _   = int_from_string valid
   616 							val _   = if antesep = "A:" then () else raise INVALID_PROOF ("File format error: \"A:\" expected (" ^ quote antesep ^ " encountered).")
   617 							val aid = int_from_string anteid
   618 							val _   = if litsep = "Lits:" then () else raise INVALID_PROOF ("File format error: \"Lits:\" expected (" ^ quote litsep ^ " encountered).")
   619 							val ls  = map int_from_string lits
   620 							(* convert the data provided by zChaff to our resolution-style proof format *)
   621 							(* each "VAR:" line defines a unit clause, the resolvents are implicitly    *)
   622 							(* given by the literals in the antecedent clause                           *)
   623 							(* we use the sum of '!clause_offset' and the variable ID as clause ID for the unit clause *)
   624 							val cid = !clause_offset + vid
   625 							(* the low bit of each literal gives its sign (positive/negative), therefore  *)
   626 							(* we have to divide each literal by 2 to obtain the proper variable ID; then *)
   627 							(* we add '!clause_offset' to obtain the ID of the corresponding unit clause  *)
   628 							val vids = filter (not_equal vid) (map (fn l => l div 2) ls)
   629 							val rs   = aid :: map (fn v => !clause_offset + v) vids
   630 						in
   631 							(* update clause table *)
   632 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   633 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int cid ^ " (derived from antecedent for variable " ^ id ^ ") already defined.")
   634 						end
   635 					| _ =>
   636 						raise INVALID_PROOF "File format error: \"VAR:\" followed by an insufficient number of tokens."
   637 				) else if tok="CONF:" then (
   638 					case toks of
   639 					  id::sep::ids =>
   640 						let
   641 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one conflicting clause specified."
   642 							val cid = int_from_string id
   643 							val _   = if sep = "==" then () else raise INVALID_PROOF ("File format error: \"==\" expected (" ^ quote sep ^ " encountered).")
   644 							val ls  = map int_from_string ids
   645 							(* the conflict clause must be resolved with the unit clauses *)
   646 							(* for its literals to obtain the empty clause                *)
   647 							val vids         = map (fn l => l div 2) ls
   648 							val rs           = cid :: map (fn v => !clause_offset + v) vids
   649 							val new_empty_id = getOpt (Inttab.max_key clause_table, !clause_offset) + 1
   650 						in
   651 							(* update clause table and conflict id *)
   652 							(Inttab.update_new (new_empty_id, rs) clause_table, new_empty_id)
   653 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int new_empty_id ^ " (empty clause derived from clause " ^ id ^ ") already defined.")
   654 						end
   655 					| _ =>
   656 						raise INVALID_PROOF "File format error: \"CONF:\" followed by an insufficient number of tokens."
   657 				) else
   658 					raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
   659 			(* string list -> proof -> proof *)
   660 			fun process_lines [] proof =
   661 				proof
   662 			  | process_lines (l::ls) proof =
   663 				process_lines ls (process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l) proof)
   664 			(* proof *)
   665 			val (clause_table, empty_id) = process_lines proof_lines (Inttab.empty, ~1)
   666 			val _                        = if empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
   667 		in
   668 			SatSolver.UNSATISFIABLE (SOME (clause_table, empty_id))
   669 		end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
   670 	| result =>
   671 		result
   672 in
   673 	SatSolver.add_solver ("zchaff_with_proofs", zchaff_with_proofs)
   674 end;
   675 
   676 let
   677 	fun zchaff fm =
   678 	let
   679 		val _          = if (getenv "ZCHAFF_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   680 		val _          = if (getenv "ZCHAFF_VERSION") <> "2004.5.13" andalso
   681 		                    (getenv "ZCHAFF_VERSION") <> "2004.11.15" then raise SatSolver.NOT_CONFIGURED else ()
   682 			(* both versions of zChaff appear to have the same interface, so we do *)
   683 			(* not actually need to distinguish between them in the following code *)
   684 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   685 		val outpath    = File.tmp_path (Path.unpack "result")
   686 		val cmd        = (getenv "ZCHAFF_HOME") ^ "/zchaff " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   687 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   688 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
   689 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   690 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   691 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   692 		val _          = try File.rm inpath
   693 		val _          = try File.rm outpath
   694 	in
   695 		result
   696 	end
   697 in
   698 	SatSolver.add_solver ("zchaff", zchaff)
   699 end;
   700 
   701 (* ------------------------------------------------------------------------- *)
   702 (* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
   703 (* ------------------------------------------------------------------------- *)
   704 
   705 let
   706 	fun berkmin fm =
   707 	let
   708 		val _          = if (getenv "BERKMIN_HOME") = "" orelse (getenv "BERKMIN_EXE") = "" then raise SatSolver.NOT_CONFIGURED else ()
   709 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   710 		val outpath    = File.tmp_path (Path.unpack "result")
   711 		val cmd        = (getenv "BERKMIN_HOME") ^ "/" ^ (getenv "BERKMIN_EXE") ^ " " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   712 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   713 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
   714 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   715 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   716 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   717 		val _          = try File.rm inpath
   718 		val _          = try File.rm outpath
   719 	in
   720 		result
   721 	end
   722 in
   723 	SatSolver.add_solver ("berkmin", berkmin)
   724 end;
   725 
   726 (* ------------------------------------------------------------------------- *)
   727 (* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
   728 (* ------------------------------------------------------------------------- *)
   729 
   730 let
   731 	fun jerusat fm =
   732 	let
   733 		val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   734 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   735 		val outpath    = File.tmp_path (Path.unpack "result")
   736 		val cmd        = (getenv "JERUSAT_HOME") ^ "/Jerusat1.3 " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   737 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   738 		fun readfn ()  = SatSolver.read_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
   739 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   740 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   741 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   742 		val _          = try File.rm inpath
   743 		val _          = try File.rm outpath
   744 	in
   745 		result
   746 	end
   747 in
   748 	SatSolver.add_solver ("jerusat", jerusat)
   749 end;
   750 
   751 (* ------------------------------------------------------------------------- *)
   752 (* Add code for other SAT solvers below.                                     *)
   753 (* ------------------------------------------------------------------------- *)
   754 
   755 (*
   756 let
   757 	fun mysolver fm = ...
   758 in
   759 	SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
   760 end;
   761 
   762 -- the solver is now available as SatSolver.invoke_solver "myname"
   763 *)