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