;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/algorithms/walksat.lisp

;;;; WalkSAT: Local Search for Satisfiability

(defun walksat (sentences &key (p 0.5) (max-flips 10000))
  "Return a model that satisfies all the SENTENCES (a list of sentences,
  usually clauses), or NIL if none is found within MAX-FLIPS flips.  P is the
  probability of a random walk move. [Fig. 7.18]  The model is an alist of
  (atom . t-or-nil) pairs, as in DPLL-SATISFIABLE."
  (let* ((clauses (mappend #'pl-sentence->clauses sentences))
	 (symbols (pl-clauses-atoms clauses))
	 (model (make-hash-table :test #'equal)))
    (when (member nil clauses)		; an empty clause is never satisfied
      (return-from walksat nil))
    (when (null clauses)		; nothing to satisfy
      (return-from walksat t))
    (dolist (s symbols)
      (setf (gethash s model) (zerop (random 2))))
    (flet ((true-clause? (clause)
	     (some #'(lambda (literal)
		       (if (pl-negative-literal-p literal)
			   (not (gethash (arg1 literal) model))
			 (gethash literal model)))
		   clause))
	   (flip (s) (setf (gethash s model) (not (gethash s model)))))
      (dotimes (i max-flips nil)
	(let ((unsatisfied (remove-if #'true-clause? clauses)))
	  (when (null unsatisfied)
	    (return (mapcar #'(lambda (s) (cons s (gethash s model)))
			    symbols)))
	  (let* ((clause (random-element unsatisfied))
		 (atoms (remove-duplicates (mapcar #'pl-literal-atom clause)
					   :test #'equal)))
	    (if (< (random 1.0) p)
		(flip (random-element atoms))
	      ;; Flip the symbol that maximizes the number of satisfied clauses
	      (flip (the-biggest
		     #'(lambda (s)
			 (flip s)
			 (prog1 (count-if #'true-clause? clauses)
			   (flip s)))
		     atoms)))))))))
