;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/csp-arc.lisp

;;;; Arc Consistency: AC-3, AC-3b and AC-4

;;; These functions work on the CSP structure of csp-4e.lisp.  Each takes an
;;; optional QUEUE of arcs (Xi . Xj) (by default every arc of the CSP), a
;;; REMOVALS log (see MAKE-CSP-REMOVALS) and an ARC-HEURISTIC that picks the
;;; next arc from the queue.  Each returns two values: nil if a domain is
;;; wiped out (the CSP is inconsistent) and t otherwise, and the number of
;;; constraint checks made.  AC-3b and AC-4 are not in the book: AC-3b
;;; shares the work of an arc and its reverse with double-support checks,
;;; and AC-4 keeps a counter of the supports of each value.

;;;; Arc Queues

(defstructure (csp-arc-queue (:constructor create-csp-arc-queue))
  "A set of arcs (Xi . Xj), with a hash table for membership."
  (arcs nil)
  (table (make-hash-table :test #'equal)))

(defun make-csp-arc-queue (arcs)
  (let ((q (create-csp-arc-queue)))
    (dolist (arc arcs q)
      (csp-arc-queue-add q arc))))

(defun csp-all-arcs (csp)
  "Every arc (Xi . Xk) of the CSP, for each neighbor Xk of each Xi."
  (loop for Xi in (csp-variables csp)
	nconc (mapcar #'(lambda (Xk) (cons Xi Xk)) (csp-var-neighbors csp Xi))))

(defun csp-arc-queue-empty? (q)
  (null (csp-arc-queue-arcs q)))

(defun csp-arc-queue-member? (q arc)
  (gethash arc (csp-arc-queue-table q)))

(defun csp-arc-queue-add (q arc)
  (unless (csp-arc-queue-member? q arc)
    (setf (gethash arc (csp-arc-queue-table q)) t)
    (push arc (csp-arc-queue-arcs q))))

(defun csp-arc-queue-remove (q arc)
  (when (csp-arc-queue-member? q arc)
    (remhash arc (csp-arc-queue-table q))
    (setf (csp-arc-queue-arcs q)
	  (remove arc (csp-arc-queue-arcs q) :test #'equal :count 1))))

(defun csp-arc-queue-pop (q csp arc-heuristic)
  "Remove from the queue the arc chosen by ARC-HEURISTIC, and return it."
  (let ((arc (funcall arc-heuristic csp (csp-arc-queue-arcs q))))
    (csp-arc-queue-remove q arc)
    arc))

;;; Arc heuristics: each picks the next arc from a non-empty list of arcs.

(defun no-arc-heuristic (csp arcs)
  "Take the arcs in queue order."
  (declare (ignore csp))
  (first arcs))

(defun dom-j-up (csp arcs)
  "Take first the arc (Xi . Xj) whose Xj has the smallest current domain."
  (the-smallest #'(lambda (arc) (length (csp-curr-domain csp (cdr arc))))
		arcs))

;;;; AC-3 [Fig. 6.3]

(defun ac-3 (csp &key queue removals (arc-heuristic #'dom-j-up))
  "Make CSP arc-consistent.  Return nil if a domain is wiped out, t
  otherwise, and the number of checks. [Fig. 6.3]"
  (csp-support-pruning csp)
  (let ((q (make-csp-arc-queue (or queue (csp-all-arcs csp))))
	(checks 0))
    (loop until (csp-arc-queue-empty? q) do
	  (let* ((arc (csp-arc-queue-pop q csp arc-heuristic))
		 (Xi (car arc))
		 (Xj (cdr arc)))
	    (multiple-value-bind (revised new-checks)
		(csp-revise csp Xi Xj removals checks)
	      (setf checks new-checks)
	      (when revised
		(when (null (csp-curr-domain csp Xi))
		  (return-from ac-3 (values nil checks)))
		(dolist (Xk (csp-var-neighbors csp Xi))
		  (unless (equal Xk Xj)
		    (csp-arc-queue-add q (cons Xk Xi))))))))
    (values t checks)))

(defun csp-revise (csp Xi Xj removals &optional (checks 0))
  "Prune the values of Xi that have no support in Xj.  Return true if some
  value was pruned, and the number of checks. [Fig. 6.3]"
  (let ((revised nil))
    (dolist (x (copy-list (csp-curr-domain csp Xi)))
      (let ((conflict t))
	(dolist (y (csp-curr-domain csp Xj))
	  (incf checks)
	  (when (csp-check csp Xi x Xj y)
	    (setf conflict nil)
	    (return)))
	(when conflict
	  (csp-prune csp Xi x removals)
	  (setf revised t))))
    (values revised checks)))

;;;; AC-3b

(defun ac-3b (csp &key queue removals (arc-heuristic #'dom-j-up))
  "AC-3 with double-support checks: revising the arc (Xi . Xj) also finds
  supports for the values of Xj, so the reverse arc is revised at once.
  Return nil if a domain is wiped out, t otherwise, and the number of
  checks."
  (csp-support-pruning csp)
  (let ((q (make-csp-arc-queue (or queue (csp-all-arcs csp))))
	(checks 0))
    (loop until (csp-arc-queue-empty? q) do
	  (let* ((arc (csp-arc-queue-pop q csp arc-heuristic))
		 (Xi (car arc))
		 (Xj (cdr arc)))
	    ;; Si-p: values of Xi supported by Xj; Sj-p: values of Xj known to
	    ;; be supported by Xi; Sj-u: values of Xj not yet known to be.
	    (multiple-value-bind (Si-p Sj-p Sj-u new-checks)
		(csp-double-support-partition csp Xi Xj checks)
	      (setf checks new-checks)
	      (when (null Si-p)
		(return-from ac-3b (values nil checks)))
	      (let ((revised nil))
		(dolist (x (copy-list (csp-curr-domain csp Xi)))
		  (unless (member x Si-p :test #'equal)
		    (csp-prune csp Xi x removals)
		    (setf revised t)))
		(when revised
		  (dolist (Xk (csp-var-neighbors csp Xi))
		    (unless (equal Xk Xj)
		      (csp-arc-queue-add q (cons Xk Xi))))))
	      (when (csp-arc-queue-member? q (cons Xj Xi))
		(csp-arc-queue-remove q (cons Xj Xi))
		;; The values of Xj supported by Xi are Sj-p plus those of
		;; Sj-u that have a support in Si-p.
		(dolist (vj Sj-u)
		  (dolist (vi Si-p)
		    (incf checks)
		    (when (csp-check csp Xj vj Xi vi)
		      (push vj Sj-p)
		      (return))))
		(let ((revised nil))
		  (dolist (y (copy-list (csp-curr-domain csp Xj)))
		    (unless (member y Sj-p :test #'equal)
		      (csp-prune csp Xj y removals)
		      (setf revised t)))
		  (when revised
		    (dolist (Xk (csp-var-neighbors csp Xj))
		      (unless (equal Xk Xi)
			(csp-arc-queue-add q (cons Xk Xj))))))))))
    (values t checks)))

(defun csp-double-support-partition (csp Xi Xj &optional (checks 0))
  "Split the domains of Xi and Xj for AC-3b.  Return the values of Xi
  supported by Xj, the values of Xj found to be supported by Xi, the other
  values of Xj, and the number of checks.  A support for a value of Xi is
  first looked for among the values of Xj not yet known to be supported
  (double-support checks), and only then among the others."
  (let ((Si-p nil)
	(Sj-p nil)
	(Dj (csp-curr-domain csp Xj)))
    (dolist (vi (csp-curr-domain csp Xi))
      (let ((conflict t))
	(dolist (vj Dj)
	  (unless (member vj Sj-p :test #'equal)
	    (incf checks)
	    (when (csp-check csp Xi vi Xj vj)
	      (setf conflict nil)
	      (push vi Si-p)
	      (push vj Sj-p)
	      (return))))
	(when conflict
	  (dolist (vj Sj-p)
	    (incf checks)
	    (when (csp-check csp Xi vi Xj vj)
	      (setf conflict nil)
	      (push vi Si-p)
	      (return))))))
    (values (nreverse Si-p) Sj-p
	    (remove-if #'(lambda (vj) (member vj Sj-p :test #'equal)) Dj)
	    checks)))

;;;; AC-4

(defun ac-4 (csp &key queue removals (arc-heuristic #'dom-j-up))
  "Arc consistency with support counters: pruning a value only rechecks the
  values it supported.  Return nil if a domain is wiped out, t otherwise,
  and the number of checks."
  (csp-support-pruning csp)
  (let ((q (make-csp-arc-queue (or queue (csp-all-arcs csp))))
	(counter (make-hash-table :test #'equal))   ; (Xi x Xj) -> supports
	(supported (make-hash-table :test #'equal)) ; (Xj . y) -> ((Xi . x) ...)
	(unsupported nil)
	(checks 0))
    ;; Build the support sets and counters
    (loop until (csp-arc-queue-empty? q) do
	  (let* ((arc (csp-arc-queue-pop q csp arc-heuristic))
		 (Xi (car arc))
		 (Xj (cdr arc))
		 (revised nil))
	    (dolist (x (copy-list (csp-curr-domain csp Xi)))
	      (dolist (y (csp-curr-domain csp Xj))
		(incf checks)
		(when (csp-check csp Xi x Xj y)
		  (incf (gethash (list Xi x Xj) counter 0))
		  (pushnew (cons Xi x) (gethash (cons Xj y) supported)
			   :test #'equal)))
	      (when (= 0 (gethash (list Xi x Xj) counter 0))
		(csp-prune csp Xi x removals)
		(setf revised t)
		(push (cons Xi x) unsupported)))
	    (when (and revised (null (csp-curr-domain csp Xi)))
	      (return-from ac-4 (values nil checks)))))
    ;; Propagate the removed values
    (loop while unsupported do
	  (let* ((pair (pop unsupported))
		 (Xj (car pair)))
	    (dolist (pair2 (gethash pair supported))
	      (let ((Xi (car pair2))
		    (x (cdr pair2)))
		(when (member x (csp-curr-domain csp Xi) :test #'equal)
		  (when (= 0 (decf (gethash (list Xi x Xj) counter 0)))
		    (csp-prune csp Xi x removals)
		    (push (cons Xi x) unsupported)
		    (when (null (csp-curr-domain csp Xi))
		      (return-from ac-4 (values nil checks)))))))))
    (values t checks)))
