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

;;;; Constraint Satisfaction Problems: Backtracking, Min-Conflicts, Tree CSPs

;;; This is the representation of binary CSPs used in chapter 6 of the 4th
;;; edition (it sits next to the 1995 CSP-PROBLEM of csp.lisp, which is kept
;;; for the old search functions).  A CSP has a list of variables, a domain
;;; and a list of neighbors for each variable, and a constraint function
;;; (fn var1 val1 var2 val2) that is true when the neighbors VAR1 and VAR2
;;; may take the values VAL1 and VAL2.  Variables and values are compared
;;; with EQUAL.  An assignment is a hash table during the search and is
;;; returned as an alist ((var . value) ...) in the order of the variables.
;;; For constraint propagation the CSP keeps the current domains, and the
;;; values pruned by an inference are logged in a "removals" vector so that
;;; they can be put back when the search backtracks.

(defstructure (csp (:constructor create-csp))
  "A binary constraint satisfaction problem."
  (variables nil)                       ; list of the variables
  (domains (make-hash-table :test #'equal))   ; var -> list of values
  (neighbors (make-hash-table :test #'equal)) ; var -> list of variables
  (constraint-fn #'true)                ; (fn var1 val1 var2 val2) -> true
  (curr-domains nil)                    ; var -> values still possible, or nil
  (nassigns 0)                          ; number of assignments made
  (nchecks 0)                           ; number of constraint checks made
  )

(defun make-csp (&key variables domains (domain nil domain?) neighbors
		      (constraint-fn #'true))
  "Build a CSP.  DOMAINS is an alist ((var . values) ...), or DOMAIN gives
  the same list of values to every variable; NEIGHBORS is an alist
  ((var . neighbor-variables) ...).  VARIABLES defaults to the variables
  of DOMAINS, or else of NEIGHBORS."
  (let ((vars (or variables (mapcar #'car domains) (mapcar #'car neighbors)))
	(dtable (make-hash-table :test #'equal))
	(ntable (make-hash-table :test #'equal)))
    (dolist (var vars)
      (setf (gethash var dtable)
	    (copy-list (if domain? domain
			 (cdr (assoc var domains :test #'equal)))))
      (setf (gethash var ntable)
	    (copy-list (cdr (assoc var neighbors :test #'equal)))))
    (create-csp :variables vars :domains dtable :neighbors ntable
		:constraint-fn constraint-fn)))

(defun copy-csp-fresh (csp)
  "A copy of CSP without current domains, and with the counters reset."
  (let ((new (copy-csp csp)))
    (setf (csp-curr-domains new) nil
	  (csp-nassigns new) 0
	  (csp-nchecks new) 0)
    new))

(defmethod print-structure ((csp csp) stream)
  (format stream "#<CSP ~D variables>" (length (csp-variables csp))))

;;;; Basic Operations on a CSP

(defun csp-domain (csp var)
  "The original domain of VAR."
  (gethash var (csp-domains csp)))

(defun csp-var-neighbors (csp var)
  "The variables that share a constraint with VAR."
  (gethash var (csp-neighbors csp)))

(defun csp-check (csp var1 val1 var2 val2)
  "Do neighbors VAR1=VAL1 and VAR2=VAL2 satisfy the constraint?  Every call
  is counted in the NCHECKS slot."
  (incf (csp-nchecks csp))
  (funcall (csp-constraint-fn csp) var1 val1 var2 val2))

(defun make-csp-assignment ()
  "An empty assignment."
  (make-hash-table :test #'equal))

(defun csp-assigned? (var assignment)
  (nth-value 1 (gethash var assignment)))

(defun csp-assign (csp var val assignment)
  "Add VAR=VAL to the assignment."
  (setf (gethash var assignment) val)
  (incf (csp-nassigns csp)))

(defun csp-unassign (csp var assignment)
  "Remove VAR from the assignment."
  (declare (ignore csp))
  (remhash var assignment))

(defun csp-assignment->alist (csp assignment)
  "The assignment as an alist, in the order of the variables of CSP."
  (loop for var in (csp-variables csp)
	when (csp-assigned? var assignment)
	collect (cons var (gethash var assignment))))

(defun csp-nconflicts (csp var val assignment)
  "The number of assigned neighbors of VAR that conflict with VAR=VAL."
  (count-if #'(lambda (var2)
		(and (csp-assigned? var2 assignment)
		     (not (csp-check csp var val var2
				     (gethash var2 assignment)))))
	    (csp-var-neighbors csp var)))

(defun csp-count-lost-values (csp var val assignment)
  "How many values VAR=VAL rules out in the domains of the unassigned
  neighbors of VAR (the count used by the LCV heuristic)."
  (let ((n 0))
    (dolist (neighbor (csp-var-neighbors csp var) n)
      (unless (csp-assigned? neighbor assignment)
	(dolist (val2 (csp-domain csp neighbor))
	  (unless (csp-check csp var val neighbor val2)
	    (incf n)))))))

(defun csp-goal? (csp assignment)
  "Is the assignment complete and consistent?"
  (every #'(lambda (var)
	     (and (csp-assigned? var assignment)
		  (= 0 (csp-nconflicts csp var (gethash var assignment)
				       assignment))))
	 (csp-variables csp)))

(defun csp-solution? (csp solution)
  "Is SOLUTION, an alist ((var . value) ...), a complete and consistent
  assignment of CSP?"
  (let ((assignment (make-csp-assignment)))
    (loop for (var . value) in solution do
	  (setf (gethash var assignment) value))
    (and solution (csp-goal? csp assignment))))

;;;; Current Domains and Removals (for Constraint Propagation)

(defun make-csp-removals ()
  "An empty log of the (var . value) pairs pruned by an inference."
  (make-array 0 :adjustable t :fill-pointer 0))

(defun csp-support-pruning (csp)
  "Make sure the current domains exist (a copy of the original ones)."
  (unless (csp-curr-domains csp)
    (let ((table (make-hash-table :test #'equal)))
      (dolist (var (csp-variables csp))
	(setf (gethash var table) (copy-list (csp-domain csp var))))
      (setf (csp-curr-domains csp) table)))
  csp)

(defun csp-curr-domain (csp var)
  "The values still possible for VAR."
  (gethash var (csp-curr-domains csp)))

(defun csp-suppose (csp var value)
  "Start accumulating inferences from assuming VAR=VALUE; return the log."
  (csp-support-pruning csp)
  (let ((removals (make-csp-removals)))
    (dolist (a (csp-curr-domain csp var))
      (unless (equal a value)
	(vector-push-extend (cons var a) removals)))
    (setf (gethash var (csp-curr-domains csp)) (list value))
    removals))

(defun csp-prune (csp var value removals)
  "Rule out VAR=VALUE, logging it in REMOVALS (unless that is nil)."
  (setf (gethash var (csp-curr-domains csp))
	(remove value (csp-curr-domain csp var) :test #'equal :count 1))
  (when removals
    (vector-push-extend (cons var value) removals)))

(defun csp-choices (csp var)
  "The values of VAR that are not ruled out."
  (if (csp-curr-domains csp)
      (csp-curr-domain csp var)
    (csp-domain csp var)))

(defun csp-infer-assignment (csp)
  "The partial assignment implied by the current domains, as an alist."
  (csp-support-pruning csp)
  (loop for var in (csp-variables csp)
	when (= 1 (length (csp-curr-domain csp var)))
	collect (cons var (first (csp-curr-domain csp var)))))

(defun csp-restore (csp removals)
  "Undo a supposition and the inferences logged in REMOVALS."
  (loop for pair across removals do
	(push (cdr pair) (gethash (car pair) (csp-curr-domains csp)))))

(defun csp-conflicted-vars (csp current)
  "The variables of the complete assignment CURRENT that are in conflict."
  (remove-if-not #'(lambda (var)
		     (> (csp-nconflicts csp var (gethash var current) current)
			0))
		 (csp-variables csp)))

;;;; Backtracking Search [Fig. 6.5]

;;; Variable ordering

(defun first-unassigned-variable (assignment csp)
  "The default variable order."
  (find-if-not #'(lambda (var) (csp-assigned? var assignment))
	       (csp-variables csp)))

(defun mrv (assignment csp)
  "Minimum-remaining-values heuristic (ties broken at random)."
  (the-smallest-random-tie
   #'(lambda (var) (num-legal-values csp var assignment))
   (remove-if #'(lambda (var) (csp-assigned? var assignment))
	      (csp-variables csp))))

(defun num-legal-values (csp var assignment)
  "The number of values still legal for VAR."
  (if (csp-curr-domains csp)
      (length (csp-curr-domain csp var))
    (count-if #'(lambda (val) (= 0 (csp-nconflicts csp var val assignment)))
	      (csp-domain csp var))))

;;; Value ordering

(defun unordered-domain-values (var assignment csp)
  "The default value order."
  (declare (ignore assignment))
  (csp-choices csp var))

(defun lcv (var assignment csp)
  "Least-constraining-value heuristic."
  (sort (copy-list (csp-choices csp var)) #'<
	:key #'(lambda (val) (csp-count-lost-values csp var val assignment))))

;;; Inference

(defun no-inference (csp var value assignment removals)
  "Do no inference, and always succeed."
  (declare (ignore csp var value assignment removals))
  t)

(defun forward-checking (csp var value assignment removals)
  "Prune the neighbor values that are inconsistent with VAR=VALUE.
  Fail if a domain becomes empty."
  (csp-support-pruning csp)
  (dolist (var2 (csp-var-neighbors csp var) t)
    (unless (csp-assigned? var2 assignment)
      (dolist (val2 (copy-list (csp-curr-domain csp var2)))
	(unless (csp-check csp var value var2 val2)
	  (csp-prune csp var2 val2 removals)))
      (when (null (csp-curr-domain csp var2))
	(return nil)))))

(defun mac (csp var value assignment removals
		&optional (constraint-propagation #'ac-3b))
  "Maintaining Arc Consistency: propagate VAR=VALUE with AC-3 (by default
  its AC-3b variant), starting from the arcs (X, VAR) of the neighbors X.
  Fail if a domain is wiped out."
  (declare (ignore value assignment))
  (values (funcall constraint-propagation csp
		   :queue (mapcar #'(lambda (X) (cons X var))
				  (csp-var-neighbors csp var))
		   :removals removals)))

;;; The search proper

(defun backtracking-search (csp &key
				(select-unassigned-variable
				 #'first-unassigned-variable)
				(order-domain-values #'unordered-domain-values)
				(inference #'no-inference))
  "Backtracking search for a solution of CSP; return the assignment as an
  alist, or nil if there is none. [Fig. 6.5]"
  (let ((assignment (make-csp-assignment)))
    (labels
	((backtrack ()
	   (when (= (hash-table-count assignment) (length (csp-variables csp)))
	     (return-from backtrack t))
	   (let ((var (funcall select-unassigned-variable assignment csp)))
	     (dolist (value (copy-list
			     (funcall order-domain-values var assignment csp)))
	       (when (= 0 (csp-nconflicts csp var value assignment))
		 (csp-assign csp var value assignment)
		 (let ((removals (csp-suppose csp var value)))
		   (when (and (funcall inference csp var value assignment
				       removals)
			      (backtrack))
		     (return-from backtrack t))
		   (csp-restore csp removals))))
	     (csp-unassign csp var assignment)
	     nil)))
      (when (backtrack)
	(csp-assignment->alist csp assignment)))))

;;;; Min-Conflicts [Fig. 6.9]

;;; The 1995 code solves the n-queens CSP-PROBLEM by hill climbing with
;;; MIN-CONFLICTS-VALUE (see csp.lisp and iterative.lisp); this is the
;;; algorithm of the figure on the representation above.

(defun min-conflicts (csp &key (max-steps 100000))
  "Solve CSP by local search on the number of conflicts; return the
  solution as an alist, or nil after MAX-STEPS steps. [Fig. 6.9]"
  (let ((current (make-csp-assignment)))
    (dolist (var (csp-variables csp))
      (csp-assign csp var (csp-min-conflicts-value csp var current) current))
    (dotimes (i max-steps nil)
      (declare (ignorable i))
      (let ((conflicted (csp-conflicted-vars csp current)))
	(when (null conflicted)
	  (return (csp-assignment->alist csp current)))
	(let ((var (random-element conflicted)))
	  (csp-assign csp var (csp-min-conflicts-value csp var current)
		      current))))))

(defun csp-min-conflicts-value (csp var current)
  "The value of VAR with the fewest conflicts (ties broken at random)."
  (the-smallest-random-tie
   #'(lambda (val) (csp-nconflicts csp var val current))
   (csp-domain csp var)))

;;;; Tree-Structured CSPs [Fig. 6.11]

(defun tree-csp-solver (csp)
  "Solve a tree-structured CSP in time linear in the number of variables:
  sort the variables topologically from a root, make each arc from parent
  to child arc-consistent from the leaves up, then assign the variables from
  the root down.  Return the assignment as an alist, or nil. [Fig. 6.11]"
  (let ((assignment (make-csp-assignment))
	(root (first (csp-variables csp))))
    (multiple-value-bind (order parents) (csp-topological-sort csp root)
      (csp-support-pruning csp)
      (dolist (Xj (reverse (rest order)))
	(unless (make-arc-consistent (gethash Xj parents) Xj csp)
	  (return-from tree-csp-solver nil)))
      (when (null (csp-curr-domain csp root))
	(return-from tree-csp-solver nil))
      (setf (gethash root assignment) (first (csp-curr-domain csp root)))
      (dolist (Xi (rest order))
	(multiple-value-bind (value found?)
	    (csp-consistent-child-value (gethash Xi parents) Xi csp assignment)
	  (unless found? (return-from tree-csp-solver nil))
	  (setf (gethash Xi assignment) value)))
      (csp-assignment->alist csp assignment))))

(defun csp-topological-sort (csp root)
  "Order the variables connected to ROOT so that each comes after its
  parent; return the order and a hash table of the parents."
  (let ((visited (make-hash-table :test #'equal))
	(parents (make-hash-table :test #'equal))
	(stack nil))
    (labels ((visit (node parent)
	       (setf (gethash node visited) t)
	       (dolist (n (csp-var-neighbors csp node))
		 (unless (gethash n visited)
		   (visit n node)))
	       (setf (gethash node parents) parent)
	       (push node stack)))
      (visit root nil))
    (values stack parents)))

(defun make-arc-consistent (Xj Xk csp)
  "Make the arc from the parent XJ to the child XK consistent, by pruning
  the values of XJ that have no support in XK.  Return the domain of XJ."
  (dolist (val1 (copy-list (csp-curr-domain csp Xj)))
    (unless (some #'(lambda (val2) (csp-check csp Xj val1 Xk val2))
		  (csp-curr-domain csp Xk))
      (csp-prune csp Xj val1 nil)))
  (csp-curr-domain csp Xj))

(defun csp-consistent-child-value (Xj Xk csp assignment)
  "The first value of the child XK consistent with the value of its parent
  XJ; the second value says whether there is one."
  (let ((parent-value (gethash Xj assignment)))
    (dolist (val (csp-curr-domain csp Xk) (values nil nil))
      (when (csp-check csp Xj parent-value Xk val)
	(return (values val t))))))
