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