src/HOL/Tools/sat_solver.ML
author wenzelm
Fri Sep 24 15:53:13 2010 +0200 (2010-09-24)
changeset 39687 4e9b6ada3a21
parent 37254 3625d37a0079
child 40314 b5ec88d9ac03
permissions -rw-r--r--
modernized structure Ord_List;
webertj@14453
     1
(*  Title:      HOL/Tools/sat_solver.ML
webertj@14453
     2
    Author:     Tjark Weber
webertj@31219
     3
    Copyright   2004-2009
webertj@14453
     4
webertj@14453
     5
Interface to external SAT solvers, and (simple) built-in SAT solvers.
webertj@14453
     6
*)
webertj@14453
     7
webertj@14453
     8
signature SAT_SOLVER =
webertj@14453
     9
sig
wenzelm@22567
    10
  exception NOT_CONFIGURED
webertj@14453
    11
wenzelm@22567
    12
  type assignment = int -> bool option
wenzelm@22567
    13
  type proof      = int list Inttab.table * int
wenzelm@22567
    14
  datatype result = SATISFIABLE of assignment
wenzelm@22567
    15
                  | UNSATISFIABLE of proof option
wenzelm@22567
    16
                  | UNKNOWN
wenzelm@22567
    17
  type solver     = PropLogic.prop_formula -> result
webertj@14965
    18
wenzelm@22567
    19
  (* auxiliary functions to create external SAT solvers *)
wenzelm@22567
    20
  val write_dimacs_cnf_file : Path.T -> PropLogic.prop_formula -> unit
wenzelm@22567
    21
  val write_dimacs_sat_file : Path.T -> PropLogic.prop_formula -> unit
wenzelm@22567
    22
  val read_std_result_file  : Path.T -> string * string * string -> result
webertj@31219
    23
  val make_external_solver  : string -> (PropLogic.prop_formula -> unit) ->
webertj@31219
    24
                                (unit -> result) -> solver
webertj@14453
    25
wenzelm@22567
    26
  val read_dimacs_cnf_file : Path.T -> PropLogic.prop_formula
webertj@15040
    27
wenzelm@22567
    28
  (* generic solver interface *)
wenzelm@32740
    29
  val solvers       : (string * solver) list Unsynchronized.ref
wenzelm@22567
    30
  val add_solver    : string * solver -> unit
wenzelm@22567
    31
  val invoke_solver : string -> solver  (* exception Option *)
webertj@14453
    32
end;
webertj@14453
    33
webertj@14453
    34
structure SatSolver : SAT_SOLVER =
webertj@14453
    35
struct
webertj@14453
    36
wenzelm@22567
    37
  open PropLogic;
webertj@14453
    38
webertj@14453
    39
(* ------------------------------------------------------------------------- *)
webertj@14965
    40
(* should be raised by an external SAT solver to indicate that the solver is *)
webertj@14965
    41
(* not configured properly                                                   *)
webertj@14965
    42
(* ------------------------------------------------------------------------- *)
webertj@14965
    43
wenzelm@22567
    44
  exception NOT_CONFIGURED;
webertj@14965
    45
webertj@14965
    46
(* ------------------------------------------------------------------------- *)
skalberg@15531
    47
(* type of partial (satisfying) assignments: 'a i = NONE' means that 'a' is  *)
webertj@19190
    48
(*      a satisfying assignment regardless of the value of variable 'i'      *)
webertj@14453
    49
(* ------------------------------------------------------------------------- *)
webertj@14453
    50
wenzelm@22567
    51
  type assignment = int -> bool option;
webertj@14965
    52
webertj@14965
    53
(* ------------------------------------------------------------------------- *)
webertj@17493
    54
(* a proof of unsatisfiability, to be interpreted as follows: each integer   *)
webertj@17493
    55
(*      is a clause ID, each list 'xs' stored under the key 'x' in the table *)
webertj@17493
    56
(*      contains the IDs of clauses that must be resolved (in the given      *)
webertj@17493
    57
(*      order) to obtain the new clause 'x'.  Each list 'xs' must be         *)
webertj@17493
    58
(*      non-empty, and the literal to be resolved upon must always be unique *)
webertj@17494
    59
(*      (e.g. "A | ~B" must not be resolved with "~A | B").  Circular        *)
webertj@17493
    60
(*      dependencies of clauses are not allowed.  (At least) one of the      *)
webertj@17493
    61
(*      clauses in the table must be the empty clause (i.e. contain no       *)
webertj@17493
    62
(*      literals); its ID is given by the second component of the proof.     *)
webertj@17493
    63
(*      The clauses of the original problem passed to the SAT solver have    *)
webertj@17493
    64
(*      consecutive IDs starting with 0.  Clause IDs must be non-negative,   *)
webertj@17493
    65
(*      but do not need to be consecutive.                                   *)
webertj@17493
    66
(* ------------------------------------------------------------------------- *)
webertj@17493
    67
wenzelm@22567
    68
  type proof = int list Inttab.table * int;
webertj@17493
    69
webertj@17493
    70
(* ------------------------------------------------------------------------- *)
webertj@14965
    71
(* return type of SAT solvers: if the result is 'SATISFIABLE', a satisfying  *)
webertj@17493
    72
(*      assignment must be returned as well; if the result is                *)
webertj@17493
    73
(*      'UNSATISFIABLE', a proof of unsatisfiability may be returned         *)
webertj@14965
    74
(* ------------------------------------------------------------------------- *)
webertj@14965
    75
wenzelm@22567
    76
  datatype result = SATISFIABLE of assignment
wenzelm@22567
    77
                  | UNSATISFIABLE of proof option
wenzelm@22567
    78
                  | UNKNOWN;
webertj@14965
    79
webertj@14965
    80
(* ------------------------------------------------------------------------- *)
webertj@14965
    81
(* type of SAT solvers: given a propositional formula, a satisfying          *)
webertj@14965
    82
(*      assignment may be returned                                           *)
webertj@14965
    83
(* ------------------------------------------------------------------------- *)
webertj@14965
    84
wenzelm@22567
    85
  type solver = prop_formula -> result;
webertj@14453
    86
webertj@14453
    87
(* ------------------------------------------------------------------------- *)
webertj@14453
    88
(* write_dimacs_cnf_file: serializes a formula 'fm' of propositional logic   *)
webertj@14453
    89
(*      to a file in DIMACS CNF format (see "Satisfiability Suggested        *)
webertj@14453
    90
(*      Format", May 8 1993, Section 2.1)                                    *)
webertj@14453
    91
(* Note: 'fm' must not contain a variable index less than 1.                 *)
webertj@14965
    92
(* Note: 'fm' must be given in CNF.                                          *)
webertj@14453
    93
(* ------------------------------------------------------------------------- *)
webertj@14453
    94
wenzelm@22567
    95
  (* Path.T -> prop_formula -> unit *)
webertj@14453
    96
wenzelm@22567
    97
  fun write_dimacs_cnf_file path fm =
wenzelm@22567
    98
  let
wenzelm@22567
    99
    (* prop_formula -> prop_formula *)
wenzelm@22567
   100
    fun cnf_True_False_elim True =
wenzelm@22567
   101
      Or (BoolVar 1, Not (BoolVar 1))
wenzelm@22567
   102
      | cnf_True_False_elim False =
wenzelm@22567
   103
      And (BoolVar 1, Not (BoolVar 1))
wenzelm@22567
   104
      | cnf_True_False_elim fm =
webertj@31219
   105
      fm  (* since 'fm' is in CNF, either 'fm'='True'/'False',
webertj@31219
   106
             or 'fm' does not contain 'True'/'False' at all *)
wenzelm@22567
   107
    (* prop_formula -> int *)
webertj@31219
   108
    fun cnf_number_of_clauses (And (fm1, fm2)) =
wenzelm@22567
   109
      (cnf_number_of_clauses fm1) + (cnf_number_of_clauses fm2)
wenzelm@22567
   110
      | cnf_number_of_clauses _ =
wenzelm@22567
   111
      1
webertj@31219
   112
    (* TextIO.outstream -> unit *)
webertj@31219
   113
    fun write_cnf_file out =
wenzelm@22567
   114
    let
webertj@31219
   115
      (* prop_formula -> unit *)
webertj@31219
   116
      fun write_formula True =
webertj@31219
   117
          error "formula is not in CNF"
webertj@31219
   118
        | write_formula False =
webertj@31219
   119
          error "formula is not in CNF"
webertj@31219
   120
        | write_formula (BoolVar i) =
webertj@31219
   121
          (i>=1 orelse error "formula contains a variable index less than 1";
webertj@31219
   122
           TextIO.output (out, string_of_int i))
webertj@31219
   123
        | write_formula (Not (BoolVar i)) =
webertj@31219
   124
          (TextIO.output (out, "-");
webertj@31219
   125
           write_formula (BoolVar i))
webertj@31219
   126
        | write_formula (Not _) =
webertj@31219
   127
          error "formula is not in CNF"
webertj@31219
   128
        | write_formula (Or (fm1, fm2)) =
webertj@31219
   129
          (write_formula fm1;
webertj@31219
   130
           TextIO.output (out, " ");
webertj@31219
   131
           write_formula fm2)
webertj@31219
   132
        | write_formula (And (fm1, fm2)) =
webertj@31219
   133
          (write_formula fm1;
webertj@31219
   134
           TextIO.output (out, " 0\n");
webertj@31219
   135
           write_formula fm2)
webertj@31219
   136
      val fm'               = cnf_True_False_elim fm
webertj@31219
   137
      val number_of_vars    = maxidx fm'
webertj@31219
   138
      val number_of_clauses = cnf_number_of_clauses fm'
wenzelm@22567
   139
    in
webertj@31219
   140
      TextIO.output (out, "c This file was generated by SatSolver.write_dimacs_cnf_file\n");
webertj@31219
   141
      TextIO.output (out, "p cnf " ^ string_of_int number_of_vars ^ " " ^
webertj@31219
   142
                            string_of_int number_of_clauses ^ "\n");
webertj@31219
   143
      write_formula fm';
webertj@31219
   144
      TextIO.output (out, " 0\n")
wenzelm@22567
   145
    end
wenzelm@22567
   146
  in
webertj@31219
   147
    File.open_output write_cnf_file path
wenzelm@22567
   148
  end;
webertj@14453
   149
webertj@14453
   150
(* ------------------------------------------------------------------------- *)
webertj@14453
   151
(* write_dimacs_sat_file: serializes a formula 'fm' of propositional logic   *)
webertj@14453
   152
(*      to a file in DIMACS SAT format (see "Satisfiability Suggested        *)
webertj@14453
   153
(*      Format", May 8 1993, Section 2.2)                                    *)
webertj@14453
   154
(* Note: 'fm' must not contain a variable index less than 1.                 *)
webertj@14453
   155
(* ------------------------------------------------------------------------- *)
webertj@14453
   156
wenzelm@22567
   157
  (* Path.T -> prop_formula -> unit *)
webertj@14453
   158
wenzelm@22567
   159
  fun write_dimacs_sat_file path fm =
wenzelm@22567
   160
  let
webertj@31219
   161
    (* TextIO.outstream -> unit *)
webertj@31219
   162
    fun write_sat_file out =
wenzelm@22567
   163
    let
webertj@31219
   164
      (* prop_formula -> unit *)
webertj@31219
   165
      fun write_formula True =
webertj@31219
   166
          TextIO.output (out, "*()")
webertj@31219
   167
        | write_formula False =
webertj@31219
   168
          TextIO.output (out, "+()")
webertj@31219
   169
        | write_formula (BoolVar i) =
webertj@31219
   170
          (i>=1 orelse error "formula contains a variable index less than 1";
webertj@31219
   171
           TextIO.output (out, string_of_int i))
webertj@31219
   172
        | write_formula (Not (BoolVar i)) =
webertj@31219
   173
          (TextIO.output (out, "-");
webertj@31219
   174
           write_formula (BoolVar i))
webertj@31219
   175
        | write_formula (Not fm) =
webertj@31219
   176
          (TextIO.output (out, "-(");
webertj@31219
   177
           write_formula fm;
webertj@31219
   178
           TextIO.output (out, ")"))
webertj@31219
   179
        | write_formula (Or (fm1, fm2)) =
webertj@31219
   180
          (TextIO.output (out, "+(");
webertj@31219
   181
           write_formula_or fm1;
webertj@31219
   182
           TextIO.output (out, " ");
webertj@31219
   183
           write_formula_or fm2;
webertj@31219
   184
           TextIO.output (out, ")"))
webertj@31219
   185
        | write_formula (And (fm1, fm2)) =
webertj@31219
   186
          (TextIO.output (out, "*(");
webertj@31219
   187
           write_formula_and fm1;
webertj@31219
   188
           TextIO.output (out, " ");
webertj@31219
   189
           write_formula_and fm2;
webertj@31219
   190
           TextIO.output (out, ")"))
wenzelm@22567
   191
      (* optimization to make use of n-ary disjunction/conjunction *)
webertj@31219
   192
      and write_formula_or (Or (fm1, fm2)) =
webertj@31219
   193
          (write_formula_or fm1;
webertj@31219
   194
           TextIO.output (out, " ");
webertj@31219
   195
           write_formula_or fm2)
webertj@31219
   196
        | write_formula_or fm =
webertj@31219
   197
          write_formula fm
webertj@31219
   198
      and write_formula_and (And (fm1, fm2)) =
webertj@31219
   199
          (write_formula_and fm1;
webertj@31219
   200
           TextIO.output (out, " ");
webertj@31219
   201
           write_formula_and fm2)
webertj@31219
   202
        | write_formula_and fm =
webertj@31219
   203
          write_formula fm
webertj@31219
   204
      val number_of_vars = Int.max (maxidx fm, 1)
wenzelm@22567
   205
    in
webertj@31219
   206
      TextIO.output (out, "c This file was generated by SatSolver.write_dimacs_sat_file\n");
webertj@31219
   207
      TextIO.output (out, "p sat " ^ string_of_int number_of_vars ^ "\n");
webertj@31219
   208
      TextIO.output (out, "(");
webertj@31219
   209
      write_formula fm;
webertj@31219
   210
      TextIO.output (out, ")\n")
wenzelm@22567
   211
    end
wenzelm@22567
   212
  in
webertj@31219
   213
    File.open_output write_sat_file path
wenzelm@22567
   214
  end;
webertj@14453
   215
webertj@14453
   216
(* ------------------------------------------------------------------------- *)
webertj@17620
   217
(* read_std_result_file: scans a SAT solver's output file for a satisfying   *)
webertj@14965
   218
(*      variable assignment.  Returns the assignment, or 'UNSATISFIABLE' if  *)
webertj@14965
   219
(*      the file contains 'unsatisfiable', or 'UNKNOWN' if the file contains *)
webertj@14965
   220
(*      neither 'satisfiable' nor 'unsatisfiable'.  Empty lines are ignored. *)
webertj@14965
   221
(*      The assignment must be given in one or more lines immediately after  *)
webertj@14965
   222
(*      the line that contains 'satisfiable'.  These lines must begin with   *)
webertj@14965
   223
(*      'assignment_prefix'.  Variables must be separated by " ".  Non-      *)
webertj@14965
   224
(*      integer strings are ignored.  If variable i is contained in the      *)
webertj@14965
   225
(*      assignment, then i is interpreted as 'true'.  If ~i is contained in  *)
webertj@14965
   226
(*      the assignment, then i is interpreted as 'false'.  Otherwise the     *)
webertj@14965
   227
(*      value of i is taken to be unspecified.                               *)
webertj@14453
   228
(* ------------------------------------------------------------------------- *)
webertj@14453
   229
wenzelm@22567
   230
  (* Path.T -> string * string * string -> result *)
webertj@14453
   231
wenzelm@22567
   232
  fun read_std_result_file path (satisfiable, assignment_prefix, unsatisfiable) =
wenzelm@22567
   233
  let
wenzelm@22567
   234
    (* string -> int list *)
wenzelm@22567
   235
    fun int_list_from_string s =
wenzelm@32952
   236
      map_filter Int.fromString (space_explode " " s)
wenzelm@22567
   237
    (* int list -> assignment *)
wenzelm@22567
   238
    fun assignment_from_list [] i =
wenzelm@22567
   239
      NONE  (* the SAT solver didn't provide a value for this variable *)
wenzelm@22567
   240
      | assignment_from_list (x::xs) i =
wenzelm@22567
   241
      if x=i then (SOME true)
wenzelm@22567
   242
      else if x=(~i) then (SOME false)
wenzelm@22567
   243
      else assignment_from_list xs i
wenzelm@22567
   244
    (* int list -> string list -> assignment *)
wenzelm@22567
   245
    fun parse_assignment xs [] =
wenzelm@22567
   246
      assignment_from_list xs
wenzelm@22567
   247
      | parse_assignment xs (line::lines) =
wenzelm@22567
   248
      if String.isPrefix assignment_prefix line then
wenzelm@22567
   249
        parse_assignment (xs @ int_list_from_string line) lines
wenzelm@22567
   250
      else
wenzelm@22567
   251
        assignment_from_list xs
wenzelm@22567
   252
    (* string -> string -> bool *)
wenzelm@22567
   253
    fun is_substring needle haystack =
wenzelm@22567
   254
    let
wenzelm@22567
   255
      val length1 = String.size needle
wenzelm@22567
   256
      val length2 = String.size haystack
wenzelm@22567
   257
    in
wenzelm@22567
   258
      if length2 < length1 then
wenzelm@22567
   259
        false
wenzelm@22567
   260
      else if needle = String.substring (haystack, 0, length1) then
wenzelm@22567
   261
        true
wenzelm@22567
   262
      else is_substring needle (String.substring (haystack, 1, length2-1))
wenzelm@22567
   263
    end
wenzelm@22567
   264
    (* string list -> result *)
wenzelm@22567
   265
    fun parse_lines [] =
wenzelm@22567
   266
      UNKNOWN
wenzelm@22567
   267
      | parse_lines (line::lines) =
wenzelm@22567
   268
      if is_substring unsatisfiable line then
wenzelm@22567
   269
        UNSATISFIABLE NONE
wenzelm@22567
   270
      else if is_substring satisfiable line then
wenzelm@22567
   271
        SATISFIABLE (parse_assignment [] lines)
wenzelm@22567
   272
      else
wenzelm@22567
   273
        parse_lines lines
wenzelm@22567
   274
  in
wenzelm@33317
   275
    (parse_lines o filter (fn l => l <> "") o split_lines o File.read) path
wenzelm@22567
   276
  end;
webertj@14453
   277
webertj@14453
   278
(* ------------------------------------------------------------------------- *)
webertj@14453
   279
(* make_external_solver: call 'writefn', execute 'cmd', call 'readfn'        *)
webertj@14453
   280
(* ------------------------------------------------------------------------- *)
webertj@14453
   281
wenzelm@22567
   282
  (* string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver *)
webertj@14453
   283
wenzelm@22567
   284
  fun make_external_solver cmd writefn readfn fm =
wenzelm@35010
   285
    (writefn fm; bash cmd; readfn ());
webertj@14453
   286
webertj@14453
   287
(* ------------------------------------------------------------------------- *)
webertj@15040
   288
(* read_dimacs_cnf_file: returns a propositional formula that corresponds to *)
webertj@15040
   289
(*      a SAT problem given in DIMACS CNF format                             *)
webertj@15040
   290
(* ------------------------------------------------------------------------- *)
webertj@15040
   291
wenzelm@22567
   292
  (* Path.T -> PropLogic.prop_formula *)
webertj@15040
   293
wenzelm@22567
   294
  fun read_dimacs_cnf_file path =
wenzelm@22567
   295
  let
wenzelm@22567
   296
    (* string list -> string list *)
wenzelm@22567
   297
    fun filter_preamble [] =
wenzelm@22567
   298
      error "problem line not found in DIMACS CNF file"
wenzelm@22567
   299
      | filter_preamble (line::lines) =
wenzelm@22567
   300
      if String.isPrefix "c " line orelse line = "c" then
wenzelm@22567
   301
        (* ignore comments *)
wenzelm@22567
   302
        filter_preamble lines
wenzelm@22567
   303
      else if String.isPrefix "p " line then
wenzelm@22567
   304
        (* ignore the problem line (which must be the last line of the preamble) *)
wenzelm@22567
   305
        (* Ignoring the problem line implies that if the file contains more clauses *)
wenzelm@22567
   306
        (* or variables than specified in its preamble, we will accept it anyway.   *)
wenzelm@22567
   307
        lines
wenzelm@22567
   308
      else
wenzelm@22567
   309
        error "preamble in DIMACS CNF file contains a line that does not begin with \"c \" or \"p \""
wenzelm@22567
   310
    (* string -> int *)
wenzelm@22567
   311
    fun int_from_string s =
wenzelm@22567
   312
      case Int.fromString s of
wenzelm@22567
   313
        SOME i => i
webertj@33937
   314
      | NONE   => error ("token " ^ quote s ^ " in DIMACS CNF file is not a number")
wenzelm@22567
   315
    (* int list -> int list list *)
wenzelm@22567
   316
    fun clauses xs =
wenzelm@22567
   317
      let
wenzelm@22567
   318
        val (xs1, xs2) = take_prefix (fn i => i <> 0) xs
wenzelm@22567
   319
      in
wenzelm@22567
   320
        case xs2 of
wenzelm@22567
   321
          []      => [xs1]
wenzelm@22567
   322
        | (0::[]) => [xs1]
wenzelm@22567
   323
        | (0::tl) => xs1 :: clauses tl
wenzelm@22567
   324
        | _       => sys_error "this cannot happen"
wenzelm@22567
   325
      end
wenzelm@22567
   326
    (* int -> PropLogic.prop_formula *)
wenzelm@22567
   327
    fun literal_from_int i =
wenzelm@22567
   328
      (i<>0 orelse error "variable index in DIMACS CNF file is 0";
wenzelm@22567
   329
      if i>0 then
wenzelm@22567
   330
        PropLogic.BoolVar i
wenzelm@22567
   331
      else
wenzelm@22567
   332
        PropLogic.Not (PropLogic.BoolVar (~i)))
wenzelm@22567
   333
    (* PropLogic.prop_formula list -> PropLogic.prop_formula *)
wenzelm@22567
   334
    fun disjunction [] =
wenzelm@22567
   335
      error "empty clause in DIMACS CNF file"
wenzelm@22567
   336
      | disjunction (x::xs) =
wenzelm@22567
   337
      (case xs of
wenzelm@22567
   338
        [] => x
wenzelm@22567
   339
      | _  => PropLogic.Or (x, disjunction xs))
wenzelm@22567
   340
    (* PropLogic.prop_formula list -> PropLogic.prop_formula *)
wenzelm@22567
   341
    fun conjunction [] =
wenzelm@22567
   342
      error "no clause in DIMACS CNF file"
wenzelm@22567
   343
      | conjunction (x::xs) =
wenzelm@22567
   344
      (case xs of
wenzelm@22567
   345
        [] => x
wenzelm@22567
   346
      | _  => PropLogic.And (x, conjunction xs))
wenzelm@22567
   347
  in
wenzelm@22567
   348
    (conjunction
wenzelm@22567
   349
    o (map disjunction)
wenzelm@22567
   350
    o (map (map literal_from_int))
wenzelm@22567
   351
    o clauses
wenzelm@22567
   352
    o (map int_from_string)
haftmann@36692
   353
    o (maps (String.tokens (member (op =) [#" ", #"\t", #"\n"])))
wenzelm@22567
   354
    o filter_preamble
wenzelm@33317
   355
    o filter (fn l => l <> "")
wenzelm@22567
   356
    o split_lines
wenzelm@22567
   357
    o File.read)
wenzelm@22567
   358
      path
wenzelm@22567
   359
  end;
webertj@15040
   360
webertj@15040
   361
(* ------------------------------------------------------------------------- *)
webertj@14453
   362
(* solvers: a (reference to a) table of all registered SAT solvers           *)
webertj@14453
   363
(* ------------------------------------------------------------------------- *)
webertj@14453
   364
wenzelm@32740
   365
  val solvers = Unsynchronized.ref ([] : (string * solver) list);
webertj@14453
   366
webertj@14453
   367
(* ------------------------------------------------------------------------- *)
webertj@14453
   368
(* add_solver: updates 'solvers' by adding a new solver                      *)
webertj@14453
   369
(* ------------------------------------------------------------------------- *)
webertj@14453
   370
wenzelm@22567
   371
  (* string * solver -> unit *)
webertj@14453
   372
wenzelm@33228
   373
    fun add_solver (name, new_solver) = CRITICAL (fn () =>
haftmann@22220
   374
      let
haftmann@22220
   375
        val the_solvers = !solvers;
haftmann@22220
   376
        val _ = if AList.defined (op =) the_solvers name
haftmann@22220
   377
          then warning ("SAT solver " ^ quote name ^ " was defined before")
haftmann@22220
   378
          else ();
wenzelm@33228
   379
      in solvers := AList.update (op =) (name, new_solver) the_solvers end);
webertj@14453
   380
webertj@14453
   381
(* ------------------------------------------------------------------------- *)
webertj@14453
   382
(* invoke_solver: returns the solver associated with the given 'name'        *)
webertj@15605
   383
(* Note: If no solver is associated with 'name', exception 'Option' will be  *)
webertj@14453
   384
(*       raised.                                                             *)
webertj@14453
   385
(* ------------------------------------------------------------------------- *)
webertj@14453
   386
wenzelm@22567
   387
  (* string -> solver *)
webertj@14453
   388
wenzelm@22567
   389
  fun invoke_solver name =
wenzelm@22567
   390
    (the o AList.lookup (op =) (!solvers)) name;
webertj@14453
   391
webertj@14453
   392
end;  (* SatSolver *)
webertj@14453
   393
webertj@14453
   394
webertj@14453
   395
(* ------------------------------------------------------------------------- *)
webertj@14453
   396
(* Predefined SAT solvers                                                    *)
webertj@14453
   397
(* ------------------------------------------------------------------------- *)
webertj@14453
   398
webertj@14453
   399
(* ------------------------------------------------------------------------- *)
webertj@14753
   400
(* Internal SAT solver, available as 'SatSolver.invoke_solver "enumerate"'   *)
webertj@14753
   401
(* -- simply enumerates assignments until a satisfying assignment is found   *)
webertj@14453
   402
(* ------------------------------------------------------------------------- *)
webertj@14453
   403
webertj@14453
   404
let
wenzelm@22567
   405
  fun enum_solver fm =
wenzelm@22567
   406
  let
wenzelm@22567
   407
    (* int list *)
wenzelm@22567
   408
    val indices = PropLogic.indices fm
wenzelm@22567
   409
    (* int list -> int list -> int list option *)
wenzelm@22567
   410
    (* binary increment: list 'xs' of current bits, list 'ys' of all bits (lower bits first) *)
wenzelm@22567
   411
    fun next_list _ ([]:int list) =
wenzelm@22567
   412
      NONE
wenzelm@22567
   413
      | next_list [] (y::ys) =
wenzelm@22567
   414
      SOME [y]
wenzelm@22567
   415
      | next_list (x::xs) (y::ys) =
wenzelm@22567
   416
      if x=y then
wenzelm@22567
   417
        (* reset the bit, continue *)
wenzelm@22567
   418
        next_list xs ys
wenzelm@22567
   419
      else
wenzelm@22567
   420
        (* set the lowest bit that wasn't set before, keep the higher bits *)
wenzelm@22567
   421
        SOME (y::x::xs)
wenzelm@22567
   422
    (* int list -> int -> bool *)
wenzelm@22567
   423
    fun assignment_from_list xs i =
haftmann@36692
   424
      member (op =) xs i
wenzelm@22567
   425
    (* int list -> SatSolver.result *)
wenzelm@22567
   426
    fun solver_loop xs =
wenzelm@22567
   427
      if PropLogic.eval (assignment_from_list xs) fm then
wenzelm@22567
   428
        SatSolver.SATISFIABLE (SOME o (assignment_from_list xs))
wenzelm@22567
   429
      else
wenzelm@22567
   430
        (case next_list xs indices of
wenzelm@22567
   431
          SOME xs' => solver_loop xs'
wenzelm@22567
   432
        | NONE     => SatSolver.UNSATISFIABLE NONE)
wenzelm@22567
   433
  in
wenzelm@22567
   434
    (* start with the "first" assignment (all variables are interpreted as 'false') *)
wenzelm@22567
   435
    solver_loop []
wenzelm@22567
   436
  end
webertj@14453
   437
in
wenzelm@22567
   438
  SatSolver.add_solver ("enumerate", enum_solver)
webertj@14453
   439
end;
webertj@14453
   440
webertj@14453
   441
(* ------------------------------------------------------------------------- *)
webertj@14753
   442
(* Internal SAT solver, available as 'SatSolver.invoke_solver "dpll"' -- a   *)
webertj@14753
   443
(* simple implementation of the DPLL algorithm (cf. L. Zhang, S. Malik: "The *)
webertj@14753
   444
(* Quest for Efficient Boolean Satisfiability Solvers", July 2002, Fig. 1).  *)
webertj@14453
   445
(* ------------------------------------------------------------------------- *)
webertj@14453
   446
webertj@14453
   447
let
wenzelm@22567
   448
  local
wenzelm@22567
   449
    open PropLogic
wenzelm@22567
   450
  in
wenzelm@22567
   451
    fun dpll_solver fm =
wenzelm@22567
   452
    let
wenzelm@22567
   453
      (* We could use 'PropLogic.defcnf fm' instead of 'PropLogic.nnf fm' *)
wenzelm@22567
   454
      (* but that sometimes leads to worse performance due to the         *)
wenzelm@22567
   455
      (* introduction of additional variables.                            *)
wenzelm@22567
   456
      val fm' = PropLogic.nnf fm
wenzelm@22567
   457
      (* int list *)
wenzelm@22567
   458
      val indices = PropLogic.indices fm'
wenzelm@22567
   459
      (* int list -> int -> prop_formula *)
wenzelm@22567
   460
      fun partial_var_eval []      i = BoolVar i
wenzelm@22567
   461
        | partial_var_eval (x::xs) i = if x=i then True else if x=(~i) then False else partial_var_eval xs i
wenzelm@22567
   462
      (* int list -> prop_formula -> prop_formula *)
wenzelm@22567
   463
      fun partial_eval xs True             = True
wenzelm@22567
   464
        | partial_eval xs False            = False
wenzelm@22567
   465
        | partial_eval xs (BoolVar i)      = partial_var_eval xs i
wenzelm@22567
   466
        | partial_eval xs (Not fm)         = SNot (partial_eval xs fm)
wenzelm@22567
   467
        | partial_eval xs (Or (fm1, fm2))  = SOr (partial_eval xs fm1, partial_eval xs fm2)
wenzelm@22567
   468
        | partial_eval xs (And (fm1, fm2)) = SAnd (partial_eval xs fm1, partial_eval xs fm2)
wenzelm@22567
   469
      (* prop_formula -> int list *)
wenzelm@22567
   470
      fun forced_vars True              = []
wenzelm@22567
   471
        | forced_vars False             = []
wenzelm@22567
   472
        | forced_vars (BoolVar i)       = [i]
wenzelm@22567
   473
        | forced_vars (Not (BoolVar i)) = [~i]
haftmann@33049
   474
        | forced_vars (Or (fm1, fm2))   = inter (op =) (forced_vars fm1) (forced_vars fm2)
haftmann@33042
   475
        | forced_vars (And (fm1, fm2))  = union (op =) (forced_vars fm1) (forced_vars fm2)
wenzelm@22567
   476
        (* Above, i *and* ~i may be forced.  In this case the first occurrence takes   *)
wenzelm@22567
   477
        (* precedence, and the next partial evaluation of the formula returns 'False'. *)
wenzelm@22567
   478
        | forced_vars _                 = error "formula is not in negation normal form"
wenzelm@22567
   479
      (* int list -> prop_formula -> (int list * prop_formula) *)
wenzelm@22567
   480
      fun eval_and_force xs fm =
wenzelm@22567
   481
      let
wenzelm@22567
   482
        val fm' = partial_eval xs fm
wenzelm@22567
   483
        val xs' = forced_vars fm'
wenzelm@22567
   484
      in
wenzelm@22567
   485
        if null xs' then
wenzelm@22567
   486
          (xs, fm')
wenzelm@22567
   487
        else
wenzelm@22567
   488
          eval_and_force (xs@xs') fm'  (* xs and xs' should be distinct, so '@' here should have *)
wenzelm@22567
   489
                                       (* the same effect as 'union_int'                         *)
wenzelm@22567
   490
      end
wenzelm@22567
   491
      (* int list -> int option *)
wenzelm@22567
   492
      fun fresh_var xs =
haftmann@36692
   493
        find_first (fn i => not (member (op =) xs i) andalso not (member (op =) xs (~i))) indices
wenzelm@22567
   494
      (* int list -> prop_formula -> int list option *)
wenzelm@22567
   495
      (* partial assignment 'xs' *)
wenzelm@22567
   496
      fun dpll xs fm =
wenzelm@22567
   497
      let
wenzelm@22567
   498
        val (xs', fm') = eval_and_force xs fm
wenzelm@22567
   499
      in
wenzelm@22567
   500
        case fm' of
wenzelm@22567
   501
          True  => SOME xs'
wenzelm@22567
   502
        | False => NONE
wenzelm@22567
   503
        | _     =>
wenzelm@22567
   504
          let
wenzelm@33035
   505
            val x = the (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
wenzelm@22567
   506
          in
wenzelm@22567
   507
            case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
wenzelm@22567
   508
              SOME xs'' => SOME xs''
wenzelm@22567
   509
            | NONE      => dpll ((~x)::xs') fm'  (* now try interpreting 'x' as 'False' *)
wenzelm@22567
   510
          end
wenzelm@22567
   511
      end
wenzelm@22567
   512
      (* int list -> assignment *)
wenzelm@22567
   513
      fun assignment_from_list [] i =
wenzelm@22567
   514
        NONE  (* the DPLL procedure didn't provide a value for this variable *)
wenzelm@22567
   515
        | assignment_from_list (x::xs) i =
wenzelm@22567
   516
        if x=i then (SOME true)
wenzelm@22567
   517
        else if x=(~i) then (SOME false)
wenzelm@22567
   518
        else assignment_from_list xs i
wenzelm@22567
   519
    in
wenzelm@22567
   520
      (* initially, no variable is interpreted yet *)
wenzelm@22567
   521
      case dpll [] fm' of
wenzelm@22567
   522
        SOME assignment => SatSolver.SATISFIABLE (assignment_from_list assignment)
wenzelm@22567
   523
      | NONE            => SatSolver.UNSATISFIABLE NONE
wenzelm@22567
   524
    end
wenzelm@22567
   525
  end  (* local *)
webertj@14453
   526
in
wenzelm@22567
   527
  SatSolver.add_solver ("dpll", dpll_solver)
webertj@14453
   528
end;
webertj@14453
   529
webertj@14453
   530
(* ------------------------------------------------------------------------- *)
webertj@14753
   531
(* Internal SAT solver, available as 'SatSolver.invoke_solver "auto"': uses  *)
webertj@17577
   532
(* the last installed solver (other than "auto" itself) that does not raise  *)
webertj@15299
   533
(* 'NOT_CONFIGURED'.  (However, the solver may return 'UNKNOWN'.)            *)
webertj@14453
   534
(* ------------------------------------------------------------------------- *)
webertj@14453
   535
webertj@14453
   536
let
wenzelm@22567
   537
  fun auto_solver fm =
wenzelm@22567
   538
  let
wenzelm@22567
   539
    fun loop [] =
wenzelm@22567
   540
      SatSolver.UNKNOWN
wenzelm@22567
   541
      | loop ((name, solver)::solvers) =
wenzelm@22567
   542
      if name="auto" then
wenzelm@22567
   543
        (* do not call solver "auto" from within "auto" *)
wenzelm@22567
   544
        loop solvers
wenzelm@22567
   545
      else (
wenzelm@22567
   546
        (* apply 'solver' to 'fm' *)
wenzelm@22567
   547
        solver fm
wenzelm@22567
   548
          handle SatSolver.NOT_CONFIGURED => loop solvers
wenzelm@22567
   549
      )
wenzelm@22567
   550
  in
wenzelm@22567
   551
    loop (!SatSolver.solvers)
wenzelm@22567
   552
  end
webertj@14453
   553
in
wenzelm@22567
   554
  SatSolver.add_solver ("auto", auto_solver)
webertj@14453
   555
end;
webertj@14453
   556
webertj@14453
   557
(* ------------------------------------------------------------------------- *)
webertj@20033
   558
(* MiniSat 1.14                                                              *)
webertj@20033
   559
(* (http://www.cs.chalmers.se/Cs/Research/FormalMethods/MiniSat/)            *)
webertj@20033
   560
(* ------------------------------------------------------------------------- *)
webertj@20033
   561
webertj@20135
   562
(* ------------------------------------------------------------------------- *)
webertj@20135
   563
(* "minisat_with_proofs" requires a modified version of MiniSat 1.14 by John *)
webertj@20135
   564
(* Matthews, which can output ASCII proof traces.  Replaying binary proof    *)
webertj@20135
   565
(* traces generated by MiniSat-p_v1.14 has _not_ been implemented.           *)
webertj@20135
   566
(* ------------------------------------------------------------------------- *)
webertj@20135
   567
webertj@20135
   568
(* add "minisat_with_proofs" _before_ "minisat" to the available solvers, so *)
webertj@20135
   569
(* that the latter is preferred by the "auto" solver                         *)
webertj@20135
   570
webertj@20152
   571
(* There is a complication that is dealt with in the code below: MiniSat     *)
webertj@20152
   572
(* introduces IDs for original clauses in the proof trace.  It does not (in  *)
webertj@20152
   573
(* general) follow the convention that the original clauses are numbered     *)
webertj@20152
   574
(* from 0 to n-1 (where n is the number of clauses in the formula).          *)
webertj@20135
   575
webertj@20135
   576
let
wenzelm@22567
   577
  exception INVALID_PROOF of string
wenzelm@22567
   578
  fun minisat_with_proofs fm =
wenzelm@22567
   579
  let
wenzelm@22567
   580
    val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   581
    val serial_str = serial_string ()
blanchet@29872
   582
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   583
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
blanchet@29872
   584
    val proofpath  = File.tmp_path (Path.explode ("result" ^ serial_str ^ ".prf"))
wenzelm@35011
   585
    val cmd        = getenv "MINISAT_HOME" ^ "/minisat " ^ File.shell_path inpath ^ " -r " ^ File.shell_path outpath ^ " -t " ^ File.shell_path proofpath ^ "> /dev/null"
wenzelm@22567
   586
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath fm
wenzelm@22567
   587
    fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
wenzelm@22567
   588
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   589
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   590
    val cnf        = PropLogic.defcnf fm
wenzelm@22567
   591
    val result     = SatSolver.make_external_solver cmd writefn readfn cnf
wenzelm@22567
   592
    val _          = try File.rm inpath
wenzelm@22567
   593
    val _          = try File.rm outpath
wenzelm@22567
   594
  in  case result of
wenzelm@22567
   595
    SatSolver.UNSATISFIABLE NONE =>
wenzelm@22567
   596
    (let
wenzelm@22567
   597
      (* string list *)
wenzelm@22567
   598
      val proof_lines = (split_lines o File.read) proofpath
wenzelm@22567
   599
        handle IO.Io _ => raise INVALID_PROOF "Could not read file \"result.prf\""
wenzelm@22567
   600
      (* representation of clauses as ordered lists of literals (with duplicates removed) *)
wenzelm@22567
   601
      (* prop_formula -> int list *)
wenzelm@22567
   602
      fun clause_to_lit_list (PropLogic.Or (fm1, fm2)) =
wenzelm@39687
   603
        Ord_List.union int_ord (clause_to_lit_list fm1) (clause_to_lit_list fm2)
wenzelm@22567
   604
        | clause_to_lit_list (PropLogic.BoolVar i) =
wenzelm@22567
   605
        [i]
wenzelm@22567
   606
        | clause_to_lit_list (PropLogic.Not (PropLogic.BoolVar i)) =
wenzelm@22567
   607
        [~i]
wenzelm@22567
   608
        | clause_to_lit_list _ =
wenzelm@22567
   609
        raise INVALID_PROOF "Error: invalid clause in CNF formula."
wenzelm@22567
   610
      (* prop_formula -> int *)
wenzelm@22567
   611
      fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) =
wenzelm@22567
   612
        cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
wenzelm@22567
   613
        | cnf_number_of_clauses _ =
wenzelm@22567
   614
        1
wenzelm@22567
   615
      val number_of_clauses = cnf_number_of_clauses cnf
wenzelm@22567
   616
      (* int list array *)
wenzelm@22567
   617
      val clauses = Array.array (number_of_clauses, [])
wenzelm@22567
   618
      (* initialize the 'clauses' array *)
wenzelm@22567
   619
      (* prop_formula * int -> int *)
wenzelm@22567
   620
      fun init_array (PropLogic.And (fm1, fm2), n) =
wenzelm@22567
   621
        init_array (fm2, init_array (fm1, n))
wenzelm@22567
   622
        | init_array (fm, n) =
wenzelm@22567
   623
        (Array.update (clauses, n, clause_to_lit_list fm); n+1)
wenzelm@22567
   624
      val _ = init_array (cnf, 0)
wenzelm@22567
   625
      (* optimization for the common case where MiniSat "R"s clauses in their *)
wenzelm@22567
   626
      (* original order:                                                      *)
wenzelm@32740
   627
      val last_ref_clause = Unsynchronized.ref (number_of_clauses - 1)
wenzelm@22567
   628
      (* search the 'clauses' array for the given list of literals 'lits', *)
wenzelm@22567
   629
      (* starting at index '!last_ref_clause + 1'                          *)
wenzelm@22567
   630
      (* int list -> int option *)
wenzelm@22567
   631
      fun original_clause_id lits =
wenzelm@22567
   632
      let
wenzelm@22567
   633
        fun original_clause_id_from index =
wenzelm@22567
   634
          if index = number_of_clauses then
wenzelm@22567
   635
            (* search from beginning again *)
wenzelm@22567
   636
            original_clause_id_from 0
wenzelm@22567
   637
          (* both 'lits' and the list of literals used in 'clauses' are sorted, so *)
wenzelm@22567
   638
          (* testing for equality should suffice -- barring duplicate literals     *)
wenzelm@22567
   639
          else if Array.sub (clauses, index) = lits then (
wenzelm@22567
   640
            (* success *)
wenzelm@22567
   641
            last_ref_clause := index;
wenzelm@22567
   642
            SOME index
wenzelm@22567
   643
          ) else if index = !last_ref_clause then
wenzelm@22567
   644
            (* failure *)
wenzelm@22567
   645
            NONE
wenzelm@22567
   646
          else
wenzelm@22567
   647
            (* continue search *)
wenzelm@22567
   648
            original_clause_id_from (index + 1)
wenzelm@22567
   649
      in
wenzelm@22567
   650
        original_clause_id_from (!last_ref_clause + 1)
wenzelm@22567
   651
      end
wenzelm@22567
   652
      (* string -> int *)
wenzelm@22567
   653
      fun int_from_string s = (
wenzelm@22567
   654
        case Int.fromString s of
wenzelm@22567
   655
          SOME i => i
wenzelm@22567
   656
        | NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
wenzelm@22567
   657
      )
wenzelm@22567
   658
      (* parse the proof file *)
wenzelm@32740
   659
      val clause_table  = Unsynchronized.ref (Inttab.empty : int list Inttab.table)
wenzelm@32740
   660
      val empty_id      = Unsynchronized.ref ~1
wenzelm@22567
   661
      (* contains a mapping from clause IDs as used by MiniSat to clause IDs in *)
wenzelm@22567
   662
      (* our proof format, where original clauses are numbered starting from 0  *)
wenzelm@32740
   663
      val clause_id_map = Unsynchronized.ref (Inttab.empty : int Inttab.table)
wenzelm@22567
   664
      fun sat_to_proof id = (
wenzelm@22567
   665
        case Inttab.lookup (!clause_id_map) id of
wenzelm@22567
   666
          SOME id' => id'
wenzelm@22567
   667
        | NONE     => raise INVALID_PROOF ("Clause ID " ^ Int.toString id ^ " used, but not defined.")
wenzelm@22567
   668
      )
wenzelm@32740
   669
      val next_id = Unsynchronized.ref (number_of_clauses - 1)
wenzelm@22567
   670
      (* string list -> unit *)
wenzelm@22567
   671
      fun process_tokens [] =
wenzelm@22567
   672
        ()
wenzelm@22567
   673
        | process_tokens (tok::toks) =
wenzelm@22567
   674
        if tok="R" then (
wenzelm@22567
   675
          case toks of
wenzelm@22567
   676
            id::sep::lits =>
wenzelm@22567
   677
            let
wenzelm@22567
   678
              val _        = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"R\" disallowed after \"X\"."
wenzelm@22567
   679
              val cid      = int_from_string id
wenzelm@22567
   680
              val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   681
              val ls       = sort int_ord (map int_from_string lits)
wenzelm@22567
   682
              val proof_id = case original_clause_id ls of
wenzelm@22567
   683
                               SOME orig_id => orig_id
wenzelm@22567
   684
                             | NONE         => raise INVALID_PROOF ("Original clause (new ID is " ^ id ^ ") not found.")
wenzelm@22567
   685
            in
wenzelm@22567
   686
              (* extend the mapping of clause IDs with this newly defined ID *)
wenzelm@22567
   687
              clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
wenzelm@22567
   688
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"R\").")
wenzelm@22567
   689
              (* the proof itself doesn't change *)
wenzelm@22567
   690
            end
wenzelm@22567
   691
          | _ =>
wenzelm@22567
   692
            raise INVALID_PROOF "File format error: \"R\" followed by an insufficient number of tokens."
wenzelm@22567
   693
        ) else if tok="C" then (
wenzelm@22567
   694
          case toks of
wenzelm@22567
   695
            id::sep::ids =>
wenzelm@22567
   696
            let
wenzelm@22567
   697
              val _        = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"C\" disallowed after \"X\"."
wenzelm@22567
   698
              val cid      = int_from_string id
wenzelm@22567
   699
              val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   700
              (* ignore the pivot literals in MiniSat's trace *)
wenzelm@22567
   701
              fun unevens []             = raise INVALID_PROOF "File format error: \"C\" followed by an even number of IDs."
wenzelm@22567
   702
                | unevens (x :: [])      = x :: []
wenzelm@22567
   703
                | unevens (x :: _ :: xs) = x :: unevens xs
wenzelm@22567
   704
              val rs       = (map sat_to_proof o unevens o map int_from_string) ids
wenzelm@22567
   705
              (* extend the mapping of clause IDs with this newly defined ID *)
wenzelm@32740
   706
              val proof_id = Unsynchronized.inc next_id
wenzelm@22567
   707
              val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
wenzelm@22567
   708
                               handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"C\").")
wenzelm@22567
   709
            in
wenzelm@22567
   710
              (* update clause table *)
wenzelm@22567
   711
              clause_table := Inttab.update_new (proof_id, rs) (!clause_table)
wenzelm@22567
   712
                handle Inttab.DUP _ => raise INVALID_PROOF ("Error: internal ID for clause " ^ id ^ " already used.")
wenzelm@22567
   713
            end
wenzelm@22567
   714
          | _ =>
wenzelm@22567
   715
            raise INVALID_PROOF "File format error: \"C\" followed by an insufficient number of tokens."
wenzelm@22567
   716
        ) else if tok="D" then (
wenzelm@22567
   717
          case toks of
wenzelm@22567
   718
            [id] =>
wenzelm@22567
   719
            let
wenzelm@22567
   720
              val _ = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"D\" disallowed after \"X\"."
wenzelm@22567
   721
              val _ = sat_to_proof (int_from_string id)
wenzelm@22567
   722
            in
wenzelm@22567
   723
              (* simply ignore "D" *)
wenzelm@22567
   724
              ()
wenzelm@22567
   725
            end
wenzelm@22567
   726
          | _ =>
wenzelm@22567
   727
            raise INVALID_PROOF "File format error: \"D\" followed by an illegal number of tokens."
wenzelm@22567
   728
        ) else if tok="X" then (
wenzelm@22567
   729
          case toks of
wenzelm@22567
   730
            [id1, id2] =>
wenzelm@22567
   731
            let
wenzelm@22567
   732
              val _            = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one end-of-proof statement."
wenzelm@22567
   733
              val _            = sat_to_proof (int_from_string id1)
wenzelm@22567
   734
              val new_empty_id = sat_to_proof (int_from_string id2)
wenzelm@22567
   735
            in
wenzelm@22567
   736
              (* update conflict id *)
wenzelm@22567
   737
              empty_id := new_empty_id
wenzelm@22567
   738
            end
wenzelm@22567
   739
          | _ =>
wenzelm@22567
   740
            raise INVALID_PROOF "File format error: \"X\" followed by an illegal number of tokens."
wenzelm@22567
   741
        ) else
wenzelm@22567
   742
          raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
wenzelm@22567
   743
      (* string list -> unit *)
wenzelm@22567
   744
      fun process_lines [] =
wenzelm@22567
   745
        ()
wenzelm@22567
   746
        | process_lines (l::ls) = (
wenzelm@22567
   747
          process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l);
wenzelm@22567
   748
          process_lines ls
wenzelm@22567
   749
        )
wenzelm@22567
   750
      (* proof *)
wenzelm@22567
   751
      val _ = process_lines proof_lines
wenzelm@22567
   752
      val _ = if !empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
wenzelm@22567
   753
    in
wenzelm@22567
   754
      SatSolver.UNSATISFIABLE (SOME (!clause_table, !empty_id))
wenzelm@22567
   755
    end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
wenzelm@22567
   756
  | result =>
wenzelm@22567
   757
    result
wenzelm@22567
   758
  end
webertj@20135
   759
in
wenzelm@22567
   760
  SatSolver.add_solver ("minisat_with_proofs", minisat_with_proofs)
webertj@20135
   761
end;
webertj@20135
   762
webertj@20033
   763
let
wenzelm@22567
   764
  fun minisat fm =
wenzelm@22567
   765
  let
wenzelm@35011
   766
    val _          = if getenv "MINISAT_HOME" = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   767
    val serial_str = serial_string ()
blanchet@29872
   768
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   769
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@35011
   770
    val cmd        = getenv "MINISAT_HOME" ^ "/minisat " ^ File.shell_path inpath ^ " -r " ^ File.shell_path outpath ^ " > /dev/null"
wenzelm@22567
   771
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   772
    fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
wenzelm@22567
   773
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   774
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   775
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   776
    val _          = try File.rm inpath
wenzelm@22567
   777
    val _          = try File.rm outpath
wenzelm@22567
   778
  in
wenzelm@22567
   779
    result
wenzelm@22567
   780
  end
webertj@20033
   781
in
wenzelm@22567
   782
  SatSolver.add_solver ("minisat", minisat)
webertj@20033
   783
end;
webertj@20033
   784
webertj@20033
   785
(* ------------------------------------------------------------------------- *)
webertj@15332
   786
(* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
webertj@14453
   787
(* ------------------------------------------------------------------------- *)
webertj@14453
   788
webertj@17493
   789
(* ------------------------------------------------------------------------- *)
webertj@17493
   790
(* 'zchaff_with_proofs' applies the "zchaff" prover to a formula, and if     *)
webertj@17493
   791
(* zChaff finds that the formula is unsatisfiable, a proof of this is read   *)
webertj@17493
   792
(* from a file "resolve_trace" that was generated by zChaff.  See the code   *)
webertj@17493
   793
(* below for the expected format of the "resolve_trace" file.  Aside from    *)
webertj@17493
   794
(* some basic syntactic checks, no verification of the proof is performed.   *)
webertj@17493
   795
(* ------------------------------------------------------------------------- *)
webertj@17493
   796
webertj@17493
   797
(* add "zchaff_with_proofs" _before_ "zchaff" to the available solvers, so   *)
webertj@17493
   798
(* that the latter is preferred by the "auto" solver                         *)
webertj@17493
   799
webertj@17493
   800
let
wenzelm@22567
   801
  exception INVALID_PROOF of string
wenzelm@22567
   802
  fun zchaff_with_proofs fm =
wenzelm@22567
   803
  case SatSolver.invoke_solver "zchaff" fm of
wenzelm@22567
   804
    SatSolver.UNSATISFIABLE NONE =>
wenzelm@22567
   805
    (let
wenzelm@22567
   806
      (* string list *)
wenzelm@22567
   807
      val proof_lines = ((split_lines o File.read) (Path.explode "resolve_trace"))
wenzelm@22567
   808
        handle IO.Io _ => raise INVALID_PROOF "Could not read file \"resolve_trace\""
wenzelm@22567
   809
      (* PropLogic.prop_formula -> int *)
wenzelm@22567
   810
      fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) = cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
wenzelm@22567
   811
        | cnf_number_of_clauses _                          = 1
wenzelm@22567
   812
      (* string -> int *)
wenzelm@22567
   813
      fun int_from_string s = (
wenzelm@22567
   814
        case Int.fromString s of
wenzelm@22567
   815
          SOME i => i
wenzelm@22567
   816
        | NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
wenzelm@22567
   817
      )
wenzelm@22567
   818
      (* parse the "resolve_trace" file *)
wenzelm@32740
   819
      val clause_offset = Unsynchronized.ref ~1
wenzelm@32740
   820
      val clause_table  = Unsynchronized.ref (Inttab.empty : int list Inttab.table)
wenzelm@32740
   821
      val empty_id      = Unsynchronized.ref ~1
wenzelm@22567
   822
      (* string list -> unit *)
wenzelm@22567
   823
      fun process_tokens [] =
wenzelm@22567
   824
        ()
wenzelm@22567
   825
        | process_tokens (tok::toks) =
wenzelm@22567
   826
        if tok="CL:" then (
wenzelm@22567
   827
          case toks of
wenzelm@22567
   828
            id::sep::ids =>
wenzelm@22567
   829
            let
wenzelm@22567
   830
              val _   = if !clause_offset = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"VAR:\".")
wenzelm@22567
   831
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"CONF:\".")
wenzelm@22567
   832
              val cid = int_from_string id
wenzelm@22567
   833
              val _   = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   834
              val rs  = map int_from_string ids
wenzelm@22567
   835
            in
wenzelm@22567
   836
              (* update clause table *)
wenzelm@22567
   837
              clause_table := Inttab.update_new (cid, rs) (!clause_table)
wenzelm@22567
   838
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once.")
wenzelm@22567
   839
            end
wenzelm@22567
   840
          | _ =>
wenzelm@22567
   841
            raise INVALID_PROOF "File format error: \"CL:\" followed by an insufficient number of tokens."
wenzelm@22567
   842
        ) else if tok="VAR:" then (
wenzelm@22567
   843
          case toks of
wenzelm@22567
   844
            id::levsep::levid::valsep::valid::antesep::anteid::litsep::lits =>
wenzelm@22567
   845
            let
wenzelm@22567
   846
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"VAR:\" disallowed after \"CONF:\".")
wenzelm@22567
   847
              (* set 'clause_offset' to the largest used clause ID *)
wenzelm@22567
   848
              val _   = if !clause_offset = ~1 then clause_offset :=
wenzelm@22567
   849
                (case Inttab.max_key (!clause_table) of
wenzelm@22567
   850
                  SOME id => id
wenzelm@22567
   851
                | NONE    => cnf_number_of_clauses (PropLogic.defcnf fm) - 1  (* the first clause ID is 0, not 1 *))
wenzelm@22567
   852
                else
wenzelm@22567
   853
                  ()
wenzelm@22567
   854
              val vid = int_from_string id
wenzelm@22567
   855
              val _   = if levsep = "L:" then () else raise INVALID_PROOF ("File format error: \"L:\" expected (" ^ quote levsep ^ " encountered).")
wenzelm@22567
   856
              val _   = int_from_string levid
wenzelm@22567
   857
              val _   = if valsep = "V:" then () else raise INVALID_PROOF ("File format error: \"V:\" expected (" ^ quote valsep ^ " encountered).")
wenzelm@22567
   858
              val _   = int_from_string valid
wenzelm@22567
   859
              val _   = if antesep = "A:" then () else raise INVALID_PROOF ("File format error: \"A:\" expected (" ^ quote antesep ^ " encountered).")
wenzelm@22567
   860
              val aid = int_from_string anteid
wenzelm@22567
   861
              val _   = if litsep = "Lits:" then () else raise INVALID_PROOF ("File format error: \"Lits:\" expected (" ^ quote litsep ^ " encountered).")
wenzelm@22567
   862
              val ls  = map int_from_string lits
wenzelm@22567
   863
              (* convert the data provided by zChaff to our resolution-style proof format *)
wenzelm@22567
   864
              (* each "VAR:" line defines a unit clause, the resolvents are implicitly    *)
wenzelm@22567
   865
              (* given by the literals in the antecedent clause                           *)
wenzelm@22567
   866
              (* we use the sum of '!clause_offset' and the variable ID as clause ID for the unit clause *)
wenzelm@22567
   867
              val cid = !clause_offset + vid
wenzelm@22567
   868
              (* the low bit of each literal gives its sign (positive/negative), therefore  *)
wenzelm@22567
   869
              (* we have to divide each literal by 2 to obtain the proper variable ID; then *)
wenzelm@22567
   870
              (* we add '!clause_offset' to obtain the ID of the corresponding unit clause  *)
wenzelm@22567
   871
              val vids = filter (not_equal vid) (map (fn l => l div 2) ls)
wenzelm@22567
   872
              val rs   = aid :: map (fn v => !clause_offset + v) vids
wenzelm@22567
   873
            in
wenzelm@22567
   874
              (* update clause table *)
wenzelm@22567
   875
              clause_table := Inttab.update_new (cid, rs) (!clause_table)
wenzelm@22567
   876
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int cid ^ " (derived from antecedent for variable " ^ id ^ ") already defined.")
wenzelm@22567
   877
            end
wenzelm@22567
   878
          | _ =>
wenzelm@22567
   879
            raise INVALID_PROOF "File format error: \"VAR:\" followed by an insufficient number of tokens."
wenzelm@22567
   880
        ) else if tok="CONF:" then (
wenzelm@22567
   881
          case toks of
wenzelm@22567
   882
            id::sep::ids =>
wenzelm@22567
   883
            let
wenzelm@22567
   884
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one conflicting clause specified."
wenzelm@22567
   885
              val cid = int_from_string id
wenzelm@22567
   886
              val _   = if sep = "==" then () else raise INVALID_PROOF ("File format error: \"==\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   887
              val ls  = map int_from_string ids
wenzelm@22567
   888
              (* the conflict clause must be resolved with the unit clauses *)
wenzelm@22567
   889
              (* for its literals to obtain the empty clause                *)
wenzelm@22567
   890
              val vids         = map (fn l => l div 2) ls
wenzelm@22567
   891
              val rs           = cid :: map (fn v => !clause_offset + v) vids
wenzelm@33035
   892
              val new_empty_id = the_default (!clause_offset) (Inttab.max_key (!clause_table)) + 1
wenzelm@22567
   893
            in
wenzelm@22567
   894
              (* update clause table and conflict id *)
wenzelm@22567
   895
              clause_table := Inttab.update_new (new_empty_id, rs) (!clause_table)
wenzelm@22567
   896
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int new_empty_id ^ " (empty clause derived from clause " ^ id ^ ") already defined.");
wenzelm@22567
   897
              empty_id     := new_empty_id
wenzelm@22567
   898
            end
wenzelm@22567
   899
          | _ =>
wenzelm@22567
   900
            raise INVALID_PROOF "File format error: \"CONF:\" followed by an insufficient number of tokens."
wenzelm@22567
   901
        ) else
wenzelm@22567
   902
          raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
wenzelm@22567
   903
      (* string list -> unit *)
wenzelm@22567
   904
      fun process_lines [] =
wenzelm@22567
   905
        ()
wenzelm@22567
   906
        | process_lines (l::ls) = (
wenzelm@22567
   907
          process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l);
wenzelm@22567
   908
          process_lines ls
wenzelm@22567
   909
        )
wenzelm@22567
   910
      (* proof *)
wenzelm@22567
   911
      val _ = process_lines proof_lines
wenzelm@22567
   912
      val _ = if !empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
wenzelm@22567
   913
    in
wenzelm@22567
   914
      SatSolver.UNSATISFIABLE (SOME (!clause_table, !empty_id))
wenzelm@22567
   915
    end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
wenzelm@22567
   916
  | result =>
wenzelm@22567
   917
    result
webertj@17493
   918
in
wenzelm@22567
   919
  SatSolver.add_solver ("zchaff_with_proofs", zchaff_with_proofs)
webertj@17493
   920
end;
webertj@17493
   921
webertj@14487
   922
let
wenzelm@22567
   923
  fun zchaff fm =
wenzelm@22567
   924
  let
wenzelm@35011
   925
    val _          = if getenv "ZCHAFF_HOME" = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   926
    val serial_str = serial_string ()
blanchet@29872
   927
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   928
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@35011
   929
    val cmd        = getenv "ZCHAFF_HOME" ^ "/zchaff " ^ File.shell_path inpath ^ " > " ^ File.shell_path outpath
wenzelm@22567
   930
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   931
    fun readfn ()  = SatSolver.read_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
wenzelm@22567
   932
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   933
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   934
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   935
    val _          = try File.rm inpath
wenzelm@22567
   936
    val _          = try File.rm outpath
wenzelm@22567
   937
  in
wenzelm@22567
   938
    result
wenzelm@22567
   939
  end
webertj@14487
   940
in
wenzelm@22567
   941
  SatSolver.add_solver ("zchaff", zchaff)
webertj@14965
   942
end;
webertj@14965
   943
webertj@14965
   944
(* ------------------------------------------------------------------------- *)
webertj@14965
   945
(* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
webertj@14965
   946
(* ------------------------------------------------------------------------- *)
webertj@14965
   947
webertj@14965
   948
let
wenzelm@22567
   949
  fun berkmin fm =
wenzelm@22567
   950
  let
blanchet@30275
   951
    val _          = if (getenv "BERKMIN_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   952
    val serial_str = serial_string ()
blanchet@29872
   953
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   954
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
blanchet@30275
   955
    val exec       = getenv "BERKMIN_EXE"
wenzelm@35011
   956
    val cmd        = getenv "BERKMIN_HOME" ^ "/" ^ (if exec = "" then "BerkMin561" else exec) ^ " " ^ File.shell_path inpath ^ " > " ^ File.shell_path outpath
wenzelm@22567
   957
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   958
    fun readfn ()  = SatSolver.read_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
wenzelm@22567
   959
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   960
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   961
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   962
    val _          = try File.rm inpath
wenzelm@22567
   963
    val _          = try File.rm outpath
wenzelm@22567
   964
  in
wenzelm@22567
   965
    result
wenzelm@22567
   966
  end
webertj@14965
   967
in
wenzelm@22567
   968
  SatSolver.add_solver ("berkmin", berkmin)
webertj@14965
   969
end;
webertj@14965
   970
webertj@14965
   971
(* ------------------------------------------------------------------------- *)
webertj@14965
   972
(* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
webertj@14965
   973
(* ------------------------------------------------------------------------- *)
webertj@14965
   974
webertj@14965
   975
let
wenzelm@22567
   976
  fun jerusat fm =
wenzelm@22567
   977
  let
wenzelm@22567
   978
    val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   979
    val serial_str = serial_string ()
blanchet@29872
   980
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   981
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@35011
   982
    val cmd        = getenv "JERUSAT_HOME" ^ "/Jerusat1.3 " ^ File.shell_path inpath ^ " > " ^ File.shell_path outpath
wenzelm@22567
   983
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   984
    fun readfn ()  = SatSolver.read_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
wenzelm@22567
   985
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   986
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   987
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   988
    val _          = try File.rm inpath
wenzelm@22567
   989
    val _          = try File.rm outpath
wenzelm@22567
   990
  in
wenzelm@22567
   991
    result
wenzelm@22567
   992
  end
webertj@14965
   993
in
wenzelm@22567
   994
  SatSolver.add_solver ("jerusat", jerusat)
webertj@14487
   995
end;
webertj@14453
   996
webertj@14453
   997
(* ------------------------------------------------------------------------- *)
webertj@14453
   998
(* Add code for other SAT solvers below.                                     *)
webertj@14453
   999
(* ------------------------------------------------------------------------- *)
webertj@14453
  1000
webertj@14453
  1001
(*
webertj@14487
  1002
let
wenzelm@22567
  1003
  fun mysolver fm = ...
webertj@14487
  1004
in
wenzelm@22567
  1005
  SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
webertj@14487
  1006
end;
webertj@14453
  1007
webertj@14453
  1008
-- the solver is now available as SatSolver.invoke_solver "myname"
webertj@14453
  1009
*)