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