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