src/HOL/Tools/sat_solver.ML
author webertj
Thu May 21 15:23:32 2009 +0100 (2009-05-21)
changeset 31219 034f23104635
parent 30275 381ce8d88cb8
child 32740 9dd0a2f83429
permissions -rw-r--r--
write_dimacs_{sat,cnf}_file now write the DIMACS file on the fly, without building it in memory first
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@22567
    29
  val solvers       : (string * solver) list 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@22567
   236
      List.mapPartial 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@22567
   275
    (parse_lines o (List.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@22567
   285
    (writefn fm; system 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
wenzelm@22567
   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)
wenzelm@22567
   353
    o List.concat
wenzelm@22567
   354
    o (map (String.fields (fn c => c mem [#" ", #"\t", #"\n"])))
wenzelm@22567
   355
    o filter_preamble
wenzelm@22567
   356
    o (List.filter (fn l => l <> ""))
wenzelm@22567
   357
    o split_lines
wenzelm@22567
   358
    o File.read)
wenzelm@22567
   359
      path
wenzelm@22567
   360
  end;
webertj@15040
   361
webertj@15040
   362
(* ------------------------------------------------------------------------- *)
webertj@14453
   363
(* solvers: a (reference to a) table of all registered SAT solvers           *)
webertj@14453
   364
(* ------------------------------------------------------------------------- *)
webertj@14453
   365
wenzelm@22567
   366
  val solvers = ref ([] : (string * solver) list);
webertj@14453
   367
webertj@14453
   368
(* ------------------------------------------------------------------------- *)
webertj@14453
   369
(* add_solver: updates 'solvers' by adding a new solver                      *)
webertj@14453
   370
(* ------------------------------------------------------------------------- *)
webertj@14453
   371
wenzelm@22567
   372
  (* string * solver -> unit *)
webertj@14453
   373
haftmann@22220
   374
    fun add_solver (name, new_solver) =
haftmann@22220
   375
      let
haftmann@22220
   376
        val the_solvers = !solvers;
haftmann@22220
   377
        val _ = if AList.defined (op =) the_solvers name
haftmann@22220
   378
          then warning ("SAT solver " ^ quote name ^ " was defined before")
haftmann@22220
   379
          else ();
haftmann@22220
   380
      in solvers := AList.update (op =) (name, new_solver) the_solvers end;
webertj@14453
   381
webertj@14453
   382
(* ------------------------------------------------------------------------- *)
webertj@14453
   383
(* invoke_solver: returns the solver associated with the given 'name'        *)
webertj@15605
   384
(* Note: If no solver is associated with 'name', exception 'Option' will be  *)
webertj@14453
   385
(*       raised.                                                             *)
webertj@14453
   386
(* ------------------------------------------------------------------------- *)
webertj@14453
   387
wenzelm@22567
   388
  (* string -> solver *)
webertj@14453
   389
wenzelm@22567
   390
  fun invoke_solver name =
wenzelm@22567
   391
    (the o AList.lookup (op =) (!solvers)) name;
webertj@14453
   392
webertj@14453
   393
end;  (* SatSolver *)
webertj@14453
   394
webertj@14453
   395
webertj@14453
   396
(* ------------------------------------------------------------------------- *)
webertj@14453
   397
(* Predefined SAT solvers                                                    *)
webertj@14453
   398
(* ------------------------------------------------------------------------- *)
webertj@14453
   399
webertj@14453
   400
(* ------------------------------------------------------------------------- *)
webertj@14753
   401
(* Internal SAT solver, available as 'SatSolver.invoke_solver "enumerate"'   *)
webertj@14753
   402
(* -- simply enumerates assignments until a satisfying assignment is found   *)
webertj@14453
   403
(* ------------------------------------------------------------------------- *)
webertj@14453
   404
webertj@14453
   405
let
wenzelm@22567
   406
  fun enum_solver fm =
wenzelm@22567
   407
  let
wenzelm@22567
   408
    (* int list *)
wenzelm@22567
   409
    val indices = PropLogic.indices fm
wenzelm@22567
   410
    (* int list -> int list -> int list option *)
wenzelm@22567
   411
    (* binary increment: list 'xs' of current bits, list 'ys' of all bits (lower bits first) *)
wenzelm@22567
   412
    fun next_list _ ([]:int list) =
wenzelm@22567
   413
      NONE
wenzelm@22567
   414
      | next_list [] (y::ys) =
wenzelm@22567
   415
      SOME [y]
wenzelm@22567
   416
      | next_list (x::xs) (y::ys) =
wenzelm@22567
   417
      if x=y then
wenzelm@22567
   418
        (* reset the bit, continue *)
wenzelm@22567
   419
        next_list xs ys
wenzelm@22567
   420
      else
wenzelm@22567
   421
        (* set the lowest bit that wasn't set before, keep the higher bits *)
wenzelm@22567
   422
        SOME (y::x::xs)
wenzelm@22567
   423
    (* int list -> int -> bool *)
wenzelm@22567
   424
    fun assignment_from_list xs i =
wenzelm@22567
   425
      i mem xs
wenzelm@22567
   426
    (* int list -> SatSolver.result *)
wenzelm@22567
   427
    fun solver_loop xs =
wenzelm@22567
   428
      if PropLogic.eval (assignment_from_list xs) fm then
wenzelm@22567
   429
        SatSolver.SATISFIABLE (SOME o (assignment_from_list xs))
wenzelm@22567
   430
      else
wenzelm@22567
   431
        (case next_list xs indices of
wenzelm@22567
   432
          SOME xs' => solver_loop xs'
wenzelm@22567
   433
        | NONE     => SatSolver.UNSATISFIABLE NONE)
wenzelm@22567
   434
  in
wenzelm@22567
   435
    (* start with the "first" assignment (all variables are interpreted as 'false') *)
wenzelm@22567
   436
    solver_loop []
wenzelm@22567
   437
  end
webertj@14453
   438
in
wenzelm@22567
   439
  SatSolver.add_solver ("enumerate", enum_solver)
webertj@14453
   440
end;
webertj@14453
   441
webertj@14453
   442
(* ------------------------------------------------------------------------- *)
webertj@14753
   443
(* Internal SAT solver, available as 'SatSolver.invoke_solver "dpll"' -- a   *)
webertj@14753
   444
(* simple implementation of the DPLL algorithm (cf. L. Zhang, S. Malik: "The *)
webertj@14753
   445
(* Quest for Efficient Boolean Satisfiability Solvers", July 2002, Fig. 1).  *)
webertj@14453
   446
(* ------------------------------------------------------------------------- *)
webertj@14453
   447
webertj@14453
   448
let
wenzelm@22567
   449
  local
wenzelm@22567
   450
    open PropLogic
wenzelm@22567
   451
  in
wenzelm@22567
   452
    fun dpll_solver fm =
wenzelm@22567
   453
    let
wenzelm@22567
   454
      (* We could use 'PropLogic.defcnf fm' instead of 'PropLogic.nnf fm' *)
wenzelm@22567
   455
      (* but that sometimes leads to worse performance due to the         *)
wenzelm@22567
   456
      (* introduction of additional variables.                            *)
wenzelm@22567
   457
      val fm' = PropLogic.nnf fm
wenzelm@22567
   458
      (* int list *)
wenzelm@22567
   459
      val indices = PropLogic.indices fm'
wenzelm@22567
   460
      (* int list -> int -> prop_formula *)
wenzelm@22567
   461
      fun partial_var_eval []      i = BoolVar i
wenzelm@22567
   462
        | 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
   463
      (* int list -> prop_formula -> prop_formula *)
wenzelm@22567
   464
      fun partial_eval xs True             = True
wenzelm@22567
   465
        | partial_eval xs False            = False
wenzelm@22567
   466
        | partial_eval xs (BoolVar i)      = partial_var_eval xs i
wenzelm@22567
   467
        | partial_eval xs (Not fm)         = SNot (partial_eval xs fm)
wenzelm@22567
   468
        | partial_eval xs (Or (fm1, fm2))  = SOr (partial_eval xs fm1, partial_eval xs fm2)
wenzelm@22567
   469
        | partial_eval xs (And (fm1, fm2)) = SAnd (partial_eval xs fm1, partial_eval xs fm2)
wenzelm@22567
   470
      (* prop_formula -> int list *)
wenzelm@22567
   471
      fun forced_vars True              = []
wenzelm@22567
   472
        | forced_vars False             = []
wenzelm@22567
   473
        | forced_vars (BoolVar i)       = [i]
wenzelm@22567
   474
        | forced_vars (Not (BoolVar i)) = [~i]
wenzelm@22567
   475
        | forced_vars (Or (fm1, fm2))   = (forced_vars fm1) inter_int (forced_vars fm2)
wenzelm@22567
   476
        | forced_vars (And (fm1, fm2))  = (forced_vars fm1) union_int (forced_vars fm2)
wenzelm@22567
   477
        (* Above, i *and* ~i may be forced.  In this case the first occurrence takes   *)
wenzelm@22567
   478
        (* precedence, and the next partial evaluation of the formula returns 'False'. *)
wenzelm@22567
   479
        | forced_vars _                 = error "formula is not in negation normal form"
wenzelm@22567
   480
      (* int list -> prop_formula -> (int list * prop_formula) *)
wenzelm@22567
   481
      fun eval_and_force xs fm =
wenzelm@22567
   482
      let
wenzelm@22567
   483
        val fm' = partial_eval xs fm
wenzelm@22567
   484
        val xs' = forced_vars fm'
wenzelm@22567
   485
      in
wenzelm@22567
   486
        if null xs' then
wenzelm@22567
   487
          (xs, fm')
wenzelm@22567
   488
        else
wenzelm@22567
   489
          eval_and_force (xs@xs') fm'  (* xs and xs' should be distinct, so '@' here should have *)
wenzelm@22567
   490
                                       (* the same effect as 'union_int'                         *)
wenzelm@22567
   491
      end
wenzelm@22567
   492
      (* int list -> int option *)
wenzelm@22567
   493
      fun fresh_var xs =
wenzelm@22567
   494
        Library.find_first (fn i => not (i mem_int xs) andalso not ((~i) mem_int xs)) indices
wenzelm@22567
   495
      (* int list -> prop_formula -> int list option *)
wenzelm@22567
   496
      (* partial assignment 'xs' *)
wenzelm@22567
   497
      fun dpll xs fm =
wenzelm@22567
   498
      let
wenzelm@22567
   499
        val (xs', fm') = eval_and_force xs fm
wenzelm@22567
   500
      in
wenzelm@22567
   501
        case fm' of
wenzelm@22567
   502
          True  => SOME xs'
wenzelm@22567
   503
        | False => NONE
wenzelm@22567
   504
        | _     =>
wenzelm@22567
   505
          let
wenzelm@22567
   506
            val x = valOf (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
wenzelm@22567
   507
          in
wenzelm@22567
   508
            case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
wenzelm@22567
   509
              SOME xs'' => SOME xs''
wenzelm@22567
   510
            | NONE      => dpll ((~x)::xs') fm'  (* now try interpreting 'x' as 'False' *)
wenzelm@22567
   511
          end
wenzelm@22567
   512
      end
wenzelm@22567
   513
      (* int list -> assignment *)
wenzelm@22567
   514
      fun assignment_from_list [] i =
wenzelm@22567
   515
        NONE  (* the DPLL procedure didn't provide a value for this variable *)
wenzelm@22567
   516
        | assignment_from_list (x::xs) i =
wenzelm@22567
   517
        if x=i then (SOME true)
wenzelm@22567
   518
        else if x=(~i) then (SOME false)
wenzelm@22567
   519
        else assignment_from_list xs i
wenzelm@22567
   520
    in
wenzelm@22567
   521
      (* initially, no variable is interpreted yet *)
wenzelm@22567
   522
      case dpll [] fm' of
wenzelm@22567
   523
        SOME assignment => SatSolver.SATISFIABLE (assignment_from_list assignment)
wenzelm@22567
   524
      | NONE            => SatSolver.UNSATISFIABLE NONE
wenzelm@22567
   525
    end
wenzelm@22567
   526
  end  (* local *)
webertj@14453
   527
in
wenzelm@22567
   528
  SatSolver.add_solver ("dpll", dpll_solver)
webertj@14453
   529
end;
webertj@14453
   530
webertj@14453
   531
(* ------------------------------------------------------------------------- *)
webertj@14753
   532
(* Internal SAT solver, available as 'SatSolver.invoke_solver "auto"': uses  *)
webertj@17577
   533
(* the last installed solver (other than "auto" itself) that does not raise  *)
webertj@15299
   534
(* 'NOT_CONFIGURED'.  (However, the solver may return 'UNKNOWN'.)            *)
webertj@14453
   535
(* ------------------------------------------------------------------------- *)
webertj@14453
   536
webertj@14453
   537
let
wenzelm@22567
   538
  fun auto_solver fm =
wenzelm@22567
   539
  let
wenzelm@22567
   540
    fun loop [] =
wenzelm@22567
   541
      SatSolver.UNKNOWN
wenzelm@22567
   542
      | loop ((name, solver)::solvers) =
wenzelm@22567
   543
      if name="auto" then
wenzelm@22567
   544
        (* do not call solver "auto" from within "auto" *)
wenzelm@22567
   545
        loop solvers
wenzelm@22567
   546
      else (
wenzelm@22567
   547
        (if name="dpll" orelse name="enumerate" then
wenzelm@22567
   548
          warning ("Using SAT solver " ^ quote name ^ "; for better performance, consider using an external solver.")
wenzelm@22567
   549
        else
wenzelm@22567
   550
          tracing ("Using SAT solver " ^ quote name ^ "."));
wenzelm@22567
   551
        (* apply 'solver' to 'fm' *)
wenzelm@22567
   552
        solver fm
wenzelm@22567
   553
          handle SatSolver.NOT_CONFIGURED => loop solvers
wenzelm@22567
   554
      )
wenzelm@22567
   555
  in
wenzelm@22567
   556
    loop (!SatSolver.solvers)
wenzelm@22567
   557
  end
webertj@14453
   558
in
wenzelm@22567
   559
  SatSolver.add_solver ("auto", auto_solver)
webertj@14453
   560
end;
webertj@14453
   561
webertj@14453
   562
(* ------------------------------------------------------------------------- *)
webertj@20033
   563
(* MiniSat 1.14                                                              *)
webertj@20033
   564
(* (http://www.cs.chalmers.se/Cs/Research/FormalMethods/MiniSat/)            *)
webertj@20033
   565
(* ------------------------------------------------------------------------- *)
webertj@20033
   566
webertj@20135
   567
(* ------------------------------------------------------------------------- *)
webertj@20135
   568
(* "minisat_with_proofs" requires a modified version of MiniSat 1.14 by John *)
webertj@20135
   569
(* Matthews, which can output ASCII proof traces.  Replaying binary proof    *)
webertj@20135
   570
(* traces generated by MiniSat-p_v1.14 has _not_ been implemented.           *)
webertj@20135
   571
(* ------------------------------------------------------------------------- *)
webertj@20135
   572
webertj@20135
   573
(* add "minisat_with_proofs" _before_ "minisat" to the available solvers, so *)
webertj@20135
   574
(* that the latter is preferred by the "auto" solver                         *)
webertj@20135
   575
webertj@20152
   576
(* There is a complication that is dealt with in the code below: MiniSat     *)
webertj@20152
   577
(* introduces IDs for original clauses in the proof trace.  It does not (in  *)
webertj@20152
   578
(* general) follow the convention that the original clauses are numbered     *)
webertj@20152
   579
(* from 0 to n-1 (where n is the number of clauses in the formula).          *)
webertj@20135
   580
webertj@20135
   581
let
wenzelm@22567
   582
  exception INVALID_PROOF of string
wenzelm@22567
   583
  fun minisat_with_proofs fm =
wenzelm@22567
   584
  let
wenzelm@22567
   585
    val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   586
    val serial_str = serial_string ()
blanchet@29872
   587
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   588
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
blanchet@29872
   589
    val proofpath  = File.tmp_path (Path.explode ("result" ^ serial_str ^ ".prf"))
wenzelm@22567
   590
    val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.implode inpath) ^ " -r " ^ (Path.implode outpath) ^ " -t " ^ (Path.implode proofpath) ^ "> /dev/null"
wenzelm@22567
   591
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath fm
wenzelm@22567
   592
    fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
wenzelm@22567
   593
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   594
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   595
    val cnf        = PropLogic.defcnf fm
wenzelm@22567
   596
    val result     = SatSolver.make_external_solver cmd writefn readfn cnf
wenzelm@22567
   597
    val _          = try File.rm inpath
wenzelm@22567
   598
    val _          = try File.rm outpath
wenzelm@22567
   599
  in  case result of
wenzelm@22567
   600
    SatSolver.UNSATISFIABLE NONE =>
wenzelm@22567
   601
    (let
wenzelm@22567
   602
      (* string list *)
wenzelm@22567
   603
      val proof_lines = (split_lines o File.read) proofpath
wenzelm@22567
   604
        handle IO.Io _ => raise INVALID_PROOF "Could not read file \"result.prf\""
wenzelm@22567
   605
      (* representation of clauses as ordered lists of literals (with duplicates removed) *)
wenzelm@22567
   606
      (* prop_formula -> int list *)
wenzelm@22567
   607
      fun clause_to_lit_list (PropLogic.Or (fm1, fm2)) =
wenzelm@22567
   608
        OrdList.union int_ord (clause_to_lit_list fm1) (clause_to_lit_list fm2)
wenzelm@22567
   609
        | clause_to_lit_list (PropLogic.BoolVar i) =
wenzelm@22567
   610
        [i]
wenzelm@22567
   611
        | clause_to_lit_list (PropLogic.Not (PropLogic.BoolVar i)) =
wenzelm@22567
   612
        [~i]
wenzelm@22567
   613
        | clause_to_lit_list _ =
wenzelm@22567
   614
        raise INVALID_PROOF "Error: invalid clause in CNF formula."
wenzelm@22567
   615
      (* prop_formula -> int *)
wenzelm@22567
   616
      fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) =
wenzelm@22567
   617
        cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
wenzelm@22567
   618
        | cnf_number_of_clauses _ =
wenzelm@22567
   619
        1
wenzelm@22567
   620
      val number_of_clauses = cnf_number_of_clauses cnf
wenzelm@22567
   621
      (* int list array *)
wenzelm@22567
   622
      val clauses = Array.array (number_of_clauses, [])
wenzelm@22567
   623
      (* initialize the 'clauses' array *)
wenzelm@22567
   624
      (* prop_formula * int -> int *)
wenzelm@22567
   625
      fun init_array (PropLogic.And (fm1, fm2), n) =
wenzelm@22567
   626
        init_array (fm2, init_array (fm1, n))
wenzelm@22567
   627
        | init_array (fm, n) =
wenzelm@22567
   628
        (Array.update (clauses, n, clause_to_lit_list fm); n+1)
wenzelm@22567
   629
      val _ = init_array (cnf, 0)
wenzelm@22567
   630
      (* optimization for the common case where MiniSat "R"s clauses in their *)
wenzelm@22567
   631
      (* original order:                                                      *)
wenzelm@22567
   632
      val last_ref_clause = ref (number_of_clauses - 1)
wenzelm@22567
   633
      (* search the 'clauses' array for the given list of literals 'lits', *)
wenzelm@22567
   634
      (* starting at index '!last_ref_clause + 1'                          *)
wenzelm@22567
   635
      (* int list -> int option *)
wenzelm@22567
   636
      fun original_clause_id lits =
wenzelm@22567
   637
      let
wenzelm@22567
   638
        fun original_clause_id_from index =
wenzelm@22567
   639
          if index = number_of_clauses then
wenzelm@22567
   640
            (* search from beginning again *)
wenzelm@22567
   641
            original_clause_id_from 0
wenzelm@22567
   642
          (* both 'lits' and the list of literals used in 'clauses' are sorted, so *)
wenzelm@22567
   643
          (* testing for equality should suffice -- barring duplicate literals     *)
wenzelm@22567
   644
          else if Array.sub (clauses, index) = lits then (
wenzelm@22567
   645
            (* success *)
wenzelm@22567
   646
            last_ref_clause := index;
wenzelm@22567
   647
            SOME index
wenzelm@22567
   648
          ) else if index = !last_ref_clause then
wenzelm@22567
   649
            (* failure *)
wenzelm@22567
   650
            NONE
wenzelm@22567
   651
          else
wenzelm@22567
   652
            (* continue search *)
wenzelm@22567
   653
            original_clause_id_from (index + 1)
wenzelm@22567
   654
      in
wenzelm@22567
   655
        original_clause_id_from (!last_ref_clause + 1)
wenzelm@22567
   656
      end
wenzelm@22567
   657
      (* string -> int *)
wenzelm@22567
   658
      fun int_from_string s = (
wenzelm@22567
   659
        case Int.fromString s of
wenzelm@22567
   660
          SOME i => i
wenzelm@22567
   661
        | NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
wenzelm@22567
   662
      )
wenzelm@22567
   663
      (* parse the proof file *)
wenzelm@22567
   664
      val clause_table  = ref (Inttab.empty : int list Inttab.table)
wenzelm@22567
   665
      val empty_id      = ref ~1
wenzelm@22567
   666
      (* contains a mapping from clause IDs as used by MiniSat to clause IDs in *)
wenzelm@22567
   667
      (* our proof format, where original clauses are numbered starting from 0  *)
wenzelm@22567
   668
      val clause_id_map = ref (Inttab.empty : int Inttab.table)
wenzelm@22567
   669
      fun sat_to_proof id = (
wenzelm@22567
   670
        case Inttab.lookup (!clause_id_map) id of
wenzelm@22567
   671
          SOME id' => id'
wenzelm@22567
   672
        | NONE     => raise INVALID_PROOF ("Clause ID " ^ Int.toString id ^ " used, but not defined.")
wenzelm@22567
   673
      )
wenzelm@22567
   674
      val next_id = ref (number_of_clauses - 1)
wenzelm@22567
   675
      (* string list -> unit *)
wenzelm@22567
   676
      fun process_tokens [] =
wenzelm@22567
   677
        ()
wenzelm@22567
   678
        | process_tokens (tok::toks) =
wenzelm@22567
   679
        if tok="R" then (
wenzelm@22567
   680
          case toks of
wenzelm@22567
   681
            id::sep::lits =>
wenzelm@22567
   682
            let
wenzelm@22567
   683
              val _        = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"R\" disallowed after \"X\"."
wenzelm@22567
   684
              val cid      = int_from_string id
wenzelm@22567
   685
              val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   686
              val ls       = sort int_ord (map int_from_string lits)
wenzelm@22567
   687
              val proof_id = case original_clause_id ls of
wenzelm@22567
   688
                               SOME orig_id => orig_id
wenzelm@22567
   689
                             | NONE         => raise INVALID_PROOF ("Original clause (new ID is " ^ id ^ ") not found.")
wenzelm@22567
   690
            in
wenzelm@22567
   691
              (* extend the mapping of clause IDs with this newly defined ID *)
wenzelm@22567
   692
              clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
wenzelm@22567
   693
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"R\").")
wenzelm@22567
   694
              (* the proof itself doesn't change *)
wenzelm@22567
   695
            end
wenzelm@22567
   696
          | _ =>
wenzelm@22567
   697
            raise INVALID_PROOF "File format error: \"R\" followed by an insufficient number of tokens."
wenzelm@22567
   698
        ) else if tok="C" then (
wenzelm@22567
   699
          case toks of
wenzelm@22567
   700
            id::sep::ids =>
wenzelm@22567
   701
            let
wenzelm@22567
   702
              val _        = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"C\" disallowed after \"X\"."
wenzelm@22567
   703
              val cid      = int_from_string id
wenzelm@22567
   704
              val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   705
              (* ignore the pivot literals in MiniSat's trace *)
wenzelm@22567
   706
              fun unevens []             = raise INVALID_PROOF "File format error: \"C\" followed by an even number of IDs."
wenzelm@22567
   707
                | unevens (x :: [])      = x :: []
wenzelm@22567
   708
                | unevens (x :: _ :: xs) = x :: unevens xs
wenzelm@22567
   709
              val rs       = (map sat_to_proof o unevens o map int_from_string) ids
wenzelm@22567
   710
              (* extend the mapping of clause IDs with this newly defined ID *)
wenzelm@22567
   711
              val proof_id = inc next_id
wenzelm@22567
   712
              val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
wenzelm@22567
   713
                               handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"C\").")
wenzelm@22567
   714
            in
wenzelm@22567
   715
              (* update clause table *)
wenzelm@22567
   716
              clause_table := Inttab.update_new (proof_id, rs) (!clause_table)
wenzelm@22567
   717
                handle Inttab.DUP _ => raise INVALID_PROOF ("Error: internal ID for clause " ^ id ^ " already used.")
wenzelm@22567
   718
            end
wenzelm@22567
   719
          | _ =>
wenzelm@22567
   720
            raise INVALID_PROOF "File format error: \"C\" followed by an insufficient number of tokens."
wenzelm@22567
   721
        ) else if tok="D" then (
wenzelm@22567
   722
          case toks of
wenzelm@22567
   723
            [id] =>
wenzelm@22567
   724
            let
wenzelm@22567
   725
              val _ = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"D\" disallowed after \"X\"."
wenzelm@22567
   726
              val _ = sat_to_proof (int_from_string id)
wenzelm@22567
   727
            in
wenzelm@22567
   728
              (* simply ignore "D" *)
wenzelm@22567
   729
              ()
wenzelm@22567
   730
            end
wenzelm@22567
   731
          | _ =>
wenzelm@22567
   732
            raise INVALID_PROOF "File format error: \"D\" followed by an illegal number of tokens."
wenzelm@22567
   733
        ) else if tok="X" then (
wenzelm@22567
   734
          case toks of
wenzelm@22567
   735
            [id1, id2] =>
wenzelm@22567
   736
            let
wenzelm@22567
   737
              val _            = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one end-of-proof statement."
wenzelm@22567
   738
              val _            = sat_to_proof (int_from_string id1)
wenzelm@22567
   739
              val new_empty_id = sat_to_proof (int_from_string id2)
wenzelm@22567
   740
            in
wenzelm@22567
   741
              (* update conflict id *)
wenzelm@22567
   742
              empty_id := new_empty_id
wenzelm@22567
   743
            end
wenzelm@22567
   744
          | _ =>
wenzelm@22567
   745
            raise INVALID_PROOF "File format error: \"X\" followed by an illegal number of tokens."
wenzelm@22567
   746
        ) else
wenzelm@22567
   747
          raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
wenzelm@22567
   748
      (* string list -> unit *)
wenzelm@22567
   749
      fun process_lines [] =
wenzelm@22567
   750
        ()
wenzelm@22567
   751
        | process_lines (l::ls) = (
wenzelm@22567
   752
          process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l);
wenzelm@22567
   753
          process_lines ls
wenzelm@22567
   754
        )
wenzelm@22567
   755
      (* proof *)
wenzelm@22567
   756
      val _ = process_lines proof_lines
wenzelm@22567
   757
      val _ = if !empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
wenzelm@22567
   758
    in
wenzelm@22567
   759
      SatSolver.UNSATISFIABLE (SOME (!clause_table, !empty_id))
wenzelm@22567
   760
    end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
wenzelm@22567
   761
  | result =>
wenzelm@22567
   762
    result
wenzelm@22567
   763
  end
webertj@20135
   764
in
wenzelm@22567
   765
  SatSolver.add_solver ("minisat_with_proofs", minisat_with_proofs)
webertj@20135
   766
end;
webertj@20135
   767
webertj@20033
   768
let
wenzelm@22567
   769
  fun minisat fm =
wenzelm@22567
   770
  let
wenzelm@22567
   771
    val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   772
    val serial_str = serial_string ()
blanchet@29872
   773
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   774
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@22567
   775
    val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.implode inpath) ^ " -r " ^ (Path.implode outpath) ^ " > /dev/null"
wenzelm@22567
   776
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   777
    fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
wenzelm@22567
   778
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   779
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   780
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   781
    val _          = try File.rm inpath
wenzelm@22567
   782
    val _          = try File.rm outpath
wenzelm@22567
   783
  in
wenzelm@22567
   784
    result
wenzelm@22567
   785
  end
webertj@20033
   786
in
wenzelm@22567
   787
  SatSolver.add_solver ("minisat", minisat)
webertj@20033
   788
end;
webertj@20033
   789
webertj@20033
   790
(* ------------------------------------------------------------------------- *)
webertj@15332
   791
(* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
webertj@14453
   792
(* ------------------------------------------------------------------------- *)
webertj@14453
   793
webertj@17493
   794
(* ------------------------------------------------------------------------- *)
webertj@17493
   795
(* 'zchaff_with_proofs' applies the "zchaff" prover to a formula, and if     *)
webertj@17493
   796
(* zChaff finds that the formula is unsatisfiable, a proof of this is read   *)
webertj@17493
   797
(* from a file "resolve_trace" that was generated by zChaff.  See the code   *)
webertj@17493
   798
(* below for the expected format of the "resolve_trace" file.  Aside from    *)
webertj@17493
   799
(* some basic syntactic checks, no verification of the proof is performed.   *)
webertj@17493
   800
(* ------------------------------------------------------------------------- *)
webertj@17493
   801
webertj@17493
   802
(* add "zchaff_with_proofs" _before_ "zchaff" to the available solvers, so   *)
webertj@17493
   803
(* that the latter is preferred by the "auto" solver                         *)
webertj@17493
   804
webertj@17493
   805
let
wenzelm@22567
   806
  exception INVALID_PROOF of string
wenzelm@22567
   807
  fun zchaff_with_proofs fm =
wenzelm@22567
   808
  case SatSolver.invoke_solver "zchaff" fm of
wenzelm@22567
   809
    SatSolver.UNSATISFIABLE NONE =>
wenzelm@22567
   810
    (let
wenzelm@22567
   811
      (* string list *)
wenzelm@22567
   812
      val proof_lines = ((split_lines o File.read) (Path.explode "resolve_trace"))
wenzelm@22567
   813
        handle IO.Io _ => raise INVALID_PROOF "Could not read file \"resolve_trace\""
wenzelm@22567
   814
      (* PropLogic.prop_formula -> int *)
wenzelm@22567
   815
      fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) = cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
wenzelm@22567
   816
        | cnf_number_of_clauses _                          = 1
wenzelm@22567
   817
      (* string -> int *)
wenzelm@22567
   818
      fun int_from_string s = (
wenzelm@22567
   819
        case Int.fromString s of
wenzelm@22567
   820
          SOME i => i
wenzelm@22567
   821
        | NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
wenzelm@22567
   822
      )
wenzelm@22567
   823
      (* parse the "resolve_trace" file *)
wenzelm@22567
   824
      val clause_offset = ref ~1
wenzelm@22567
   825
      val clause_table  = ref (Inttab.empty : int list Inttab.table)
wenzelm@22567
   826
      val empty_id      = ref ~1
wenzelm@22567
   827
      (* string list -> unit *)
wenzelm@22567
   828
      fun process_tokens [] =
wenzelm@22567
   829
        ()
wenzelm@22567
   830
        | process_tokens (tok::toks) =
wenzelm@22567
   831
        if tok="CL:" then (
wenzelm@22567
   832
          case toks of
wenzelm@22567
   833
            id::sep::ids =>
wenzelm@22567
   834
            let
wenzelm@22567
   835
              val _   = if !clause_offset = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"VAR:\".")
wenzelm@22567
   836
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"CONF:\".")
wenzelm@22567
   837
              val cid = int_from_string id
wenzelm@22567
   838
              val _   = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   839
              val rs  = map int_from_string ids
wenzelm@22567
   840
            in
wenzelm@22567
   841
              (* update clause table *)
wenzelm@22567
   842
              clause_table := Inttab.update_new (cid, rs) (!clause_table)
wenzelm@22567
   843
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once.")
wenzelm@22567
   844
            end
wenzelm@22567
   845
          | _ =>
wenzelm@22567
   846
            raise INVALID_PROOF "File format error: \"CL:\" followed by an insufficient number of tokens."
wenzelm@22567
   847
        ) else if tok="VAR:" then (
wenzelm@22567
   848
          case toks of
wenzelm@22567
   849
            id::levsep::levid::valsep::valid::antesep::anteid::litsep::lits =>
wenzelm@22567
   850
            let
wenzelm@22567
   851
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"VAR:\" disallowed after \"CONF:\".")
wenzelm@22567
   852
              (* set 'clause_offset' to the largest used clause ID *)
wenzelm@22567
   853
              val _   = if !clause_offset = ~1 then clause_offset :=
wenzelm@22567
   854
                (case Inttab.max_key (!clause_table) of
wenzelm@22567
   855
                  SOME id => id
wenzelm@22567
   856
                | NONE    => cnf_number_of_clauses (PropLogic.defcnf fm) - 1  (* the first clause ID is 0, not 1 *))
wenzelm@22567
   857
                else
wenzelm@22567
   858
                  ()
wenzelm@22567
   859
              val vid = int_from_string id
wenzelm@22567
   860
              val _   = if levsep = "L:" then () else raise INVALID_PROOF ("File format error: \"L:\" expected (" ^ quote levsep ^ " encountered).")
wenzelm@22567
   861
              val _   = int_from_string levid
wenzelm@22567
   862
              val _   = if valsep = "V:" then () else raise INVALID_PROOF ("File format error: \"V:\" expected (" ^ quote valsep ^ " encountered).")
wenzelm@22567
   863
              val _   = int_from_string valid
wenzelm@22567
   864
              val _   = if antesep = "A:" then () else raise INVALID_PROOF ("File format error: \"A:\" expected (" ^ quote antesep ^ " encountered).")
wenzelm@22567
   865
              val aid = int_from_string anteid
wenzelm@22567
   866
              val _   = if litsep = "Lits:" then () else raise INVALID_PROOF ("File format error: \"Lits:\" expected (" ^ quote litsep ^ " encountered).")
wenzelm@22567
   867
              val ls  = map int_from_string lits
wenzelm@22567
   868
              (* convert the data provided by zChaff to our resolution-style proof format *)
wenzelm@22567
   869
              (* each "VAR:" line defines a unit clause, the resolvents are implicitly    *)
wenzelm@22567
   870
              (* given by the literals in the antecedent clause                           *)
wenzelm@22567
   871
              (* we use the sum of '!clause_offset' and the variable ID as clause ID for the unit clause *)
wenzelm@22567
   872
              val cid = !clause_offset + vid
wenzelm@22567
   873
              (* the low bit of each literal gives its sign (positive/negative), therefore  *)
wenzelm@22567
   874
              (* we have to divide each literal by 2 to obtain the proper variable ID; then *)
wenzelm@22567
   875
              (* we add '!clause_offset' to obtain the ID of the corresponding unit clause  *)
wenzelm@22567
   876
              val vids = filter (not_equal vid) (map (fn l => l div 2) ls)
wenzelm@22567
   877
              val rs   = aid :: map (fn v => !clause_offset + v) vids
wenzelm@22567
   878
            in
wenzelm@22567
   879
              (* update clause table *)
wenzelm@22567
   880
              clause_table := Inttab.update_new (cid, rs) (!clause_table)
wenzelm@22567
   881
                handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int cid ^ " (derived from antecedent for variable " ^ id ^ ") already defined.")
wenzelm@22567
   882
            end
wenzelm@22567
   883
          | _ =>
wenzelm@22567
   884
            raise INVALID_PROOF "File format error: \"VAR:\" followed by an insufficient number of tokens."
wenzelm@22567
   885
        ) else if tok="CONF:" then (
wenzelm@22567
   886
          case toks of
wenzelm@22567
   887
            id::sep::ids =>
wenzelm@22567
   888
            let
wenzelm@22567
   889
              val _   = if !empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one conflicting clause specified."
wenzelm@22567
   890
              val cid = int_from_string id
wenzelm@22567
   891
              val _   = if sep = "==" then () else raise INVALID_PROOF ("File format error: \"==\" expected (" ^ quote sep ^ " encountered).")
wenzelm@22567
   892
              val ls  = map int_from_string ids
wenzelm@22567
   893
              (* the conflict clause must be resolved with the unit clauses *)
wenzelm@22567
   894
              (* for its literals to obtain the empty clause                *)
wenzelm@22567
   895
              val vids         = map (fn l => l div 2) ls
wenzelm@22567
   896
              val rs           = cid :: map (fn v => !clause_offset + v) vids
wenzelm@22567
   897
              val new_empty_id = getOpt (Inttab.max_key (!clause_table), !clause_offset) + 1
wenzelm@22567
   898
            in
wenzelm@22567
   899
              (* update clause table and conflict id *)
wenzelm@22567
   900
              clause_table := Inttab.update_new (new_empty_id, rs) (!clause_table)
wenzelm@22567
   901
                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
   902
              empty_id     := new_empty_id
wenzelm@22567
   903
            end
wenzelm@22567
   904
          | _ =>
wenzelm@22567
   905
            raise INVALID_PROOF "File format error: \"CONF:\" followed by an insufficient number of tokens."
wenzelm@22567
   906
        ) else
wenzelm@22567
   907
          raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
wenzelm@22567
   908
      (* string list -> unit *)
wenzelm@22567
   909
      fun process_lines [] =
wenzelm@22567
   910
        ()
wenzelm@22567
   911
        | process_lines (l::ls) = (
wenzelm@22567
   912
          process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l);
wenzelm@22567
   913
          process_lines ls
wenzelm@22567
   914
        )
wenzelm@22567
   915
      (* proof *)
wenzelm@22567
   916
      val _ = process_lines proof_lines
wenzelm@22567
   917
      val _ = if !empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
wenzelm@22567
   918
    in
wenzelm@22567
   919
      SatSolver.UNSATISFIABLE (SOME (!clause_table, !empty_id))
wenzelm@22567
   920
    end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
wenzelm@22567
   921
  | result =>
wenzelm@22567
   922
    result
webertj@17493
   923
in
wenzelm@22567
   924
  SatSolver.add_solver ("zchaff_with_proofs", zchaff_with_proofs)
webertj@17493
   925
end;
webertj@17493
   926
webertj@14487
   927
let
wenzelm@22567
   928
  fun zchaff fm =
wenzelm@22567
   929
  let
wenzelm@22567
   930
    val _          = if (getenv "ZCHAFF_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   931
    val serial_str = serial_string ()
blanchet@29872
   932
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   933
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@22567
   934
    val cmd        = (getenv "ZCHAFF_HOME") ^ "/zchaff " ^ (Path.implode inpath) ^ " > " ^ (Path.implode outpath)
wenzelm@22567
   935
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   936
    fun readfn ()  = SatSolver.read_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
wenzelm@22567
   937
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   938
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   939
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   940
    val _          = try File.rm inpath
wenzelm@22567
   941
    val _          = try File.rm outpath
wenzelm@22567
   942
  in
wenzelm@22567
   943
    result
wenzelm@22567
   944
  end
webertj@14487
   945
in
wenzelm@22567
   946
  SatSolver.add_solver ("zchaff", zchaff)
webertj@14965
   947
end;
webertj@14965
   948
webertj@14965
   949
(* ------------------------------------------------------------------------- *)
webertj@14965
   950
(* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
webertj@14965
   951
(* ------------------------------------------------------------------------- *)
webertj@14965
   952
webertj@14965
   953
let
wenzelm@22567
   954
  fun berkmin fm =
wenzelm@22567
   955
  let
blanchet@30275
   956
    val _          = if (getenv "BERKMIN_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   957
    val serial_str = serial_string ()
blanchet@29872
   958
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   959
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
blanchet@30275
   960
    val exec       = getenv "BERKMIN_EXE"
blanchet@30275
   961
    val cmd        = (getenv "BERKMIN_HOME") ^ "/" ^ (if exec = "" then "BerkMin561" else exec) ^ " " ^ (Path.implode inpath) ^ " > " ^ (Path.implode outpath)
wenzelm@22567
   962
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   963
    fun readfn ()  = SatSolver.read_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
wenzelm@22567
   964
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   965
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   966
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   967
    val _          = try File.rm inpath
wenzelm@22567
   968
    val _          = try File.rm outpath
wenzelm@22567
   969
  in
wenzelm@22567
   970
    result
wenzelm@22567
   971
  end
webertj@14965
   972
in
wenzelm@22567
   973
  SatSolver.add_solver ("berkmin", berkmin)
webertj@14965
   974
end;
webertj@14965
   975
webertj@14965
   976
(* ------------------------------------------------------------------------- *)
webertj@14965
   977
(* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
webertj@14965
   978
(* ------------------------------------------------------------------------- *)
webertj@14965
   979
webertj@14965
   980
let
wenzelm@22567
   981
  fun jerusat fm =
wenzelm@22567
   982
  let
wenzelm@22567
   983
    val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
blanchet@29872
   984
    val serial_str = serial_string ()
blanchet@29872
   985
    val inpath     = File.tmp_path (Path.explode ("isabelle" ^ serial_str ^ ".cnf"))
blanchet@29872
   986
    val outpath    = File.tmp_path (Path.explode ("result" ^ serial_str))
wenzelm@22567
   987
    val cmd        = (getenv "JERUSAT_HOME") ^ "/Jerusat1.3 " ^ (Path.implode inpath) ^ " > " ^ (Path.implode outpath)
wenzelm@22567
   988
    fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
wenzelm@22567
   989
    fun readfn ()  = SatSolver.read_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
wenzelm@22567
   990
    val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.implode inpath)) else ()
wenzelm@22567
   991
    val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.implode outpath)) else ()
wenzelm@22567
   992
    val result     = SatSolver.make_external_solver cmd writefn readfn fm
wenzelm@22567
   993
    val _          = try File.rm inpath
wenzelm@22567
   994
    val _          = try File.rm outpath
wenzelm@22567
   995
  in
wenzelm@22567
   996
    result
wenzelm@22567
   997
  end
webertj@14965
   998
in
wenzelm@22567
   999
  SatSolver.add_solver ("jerusat", jerusat)
webertj@14487
  1000
end;
webertj@14453
  1001
webertj@14453
  1002
(* ------------------------------------------------------------------------- *)
webertj@14453
  1003
(* Add code for other SAT solvers below.                                     *)
webertj@14453
  1004
(* ------------------------------------------------------------------------- *)
webertj@14453
  1005
webertj@14453
  1006
(*
webertj@14487
  1007
let
wenzelm@22567
  1008
  fun mysolver fm = ...
webertj@14487
  1009
in
wenzelm@22567
  1010
  SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
webertj@14487
  1011
end;
webertj@14453
  1012
webertj@14453
  1013
-- the solver is now available as SatSolver.invoke_solver "myname"
webertj@14453
  1014
*)