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

;;;; N-ary CSPs, Generalized Arc Consistency and Domain Splitting

;;; An n-ary CSP has a domain for each variable and a list of constraints,
;;; each with a scope (a list of variables) and a condition (a function of
;;; the values of the scope variables, in order).  Variables are compared
;;; with EQUAL, so they can be symbols, strings or lists; a domain may
;;; contain nil (e.g. the booleans t and nil).  The solvers make the CSP
;;; generalized-arc-consistent (GAC) and split the domains that still have
;;; more than one value: AC-SOLVER does it by recursion, AC-SEARCH-SOLVER by
;;; depth-first search on the problem whose states are the reduced domains.
;;; Neither is in the book (section 6.2 describes generalized arc
;;; consistency); they follow D. Poole and A. Mackworth, "Artificial
;;; Intelligence: Foundations of Computational Agents", chapter 4.

(defstructure nary-constraint
  "A constraint: the CONDITION holds on the values of the SCOPE variables."
  (scope nil)
  (condition #'true))

(defstructure (nary-csp (:constructor create-nary-csp))
  "An n-ary constraint satisfaction problem."
  (variables nil)     ; list of the variables, in the order of DOMAINS
  (domains nil)       ; alist ((var . values) ...)
  (constraints nil)   ; list of NARY-CONSTRAINTs
  (var-to-const (make-hash-table :test #'equal))) ; var -> its constraints

(defun make-nary-csp (&key domains constraints)
  "Build an n-ary CSP from an alist of DOMAINS ((var . values) ...) and a
  list of CONSTRAINTS (see MAKE-NARY-CONSTRAINT)."
  (let ((csp (create-nary-csp :variables (mapcar #'car domains)
			      :domains (mapcar #'(lambda (d)
						   (cons (car d)
							 (copy-list (cdr d))))
					       domains)
			      :constraints constraints)))
    (dolist (var (nary-csp-variables csp))
      (setf (gethash var (nary-csp-var-to-const csp)) nil))
    (dolist (const constraints)
      (dolist (var (nary-constraint-scope const))
	(pushnew const (gethash var (nary-csp-var-to-const csp)))))
    csp))

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

(defun nary-constraint-holds (const assignment)
  "The value of the constraint on ASSIGNMENT, an alist that binds all the
  variables of its scope."
  (apply (nary-constraint-condition const)
	 (mapcar #'(lambda (var) (cdr (assoc var assignment :test #'equal)))
		 (nary-constraint-scope const))))

(defun nary-csp-consistent? (csp assignment)
  "Do all the constraints whose variables are bound in ASSIGNMENT (an
  alist) hold?"
  (every #'(lambda (const)
	     (or (notevery #'(lambda (var) (assoc var assignment :test #'equal))
			   (nary-constraint-scope const))
		 (nary-constraint-holds const assignment)))
	 (nary-csp-constraints csp)))

;;;; Some Constraint Conditions

(defun all-diff-constraint (&rest values)
  "True if all the values are different."
  (= (length values)
     (length (remove-duplicates values :test #'equal))))

(defun is-word-constraint (words)
  "A condition true when the letters (characters) spell one of WORDS."
  (let ((table (make-hash-table :test #'equal)))
    (dolist (w words) (setf (gethash w table) t))
    #'(lambda (&rest letters)
	(gethash (coerce letters 'string) table))))

(defun meet-at-constraint (p1 p2)
  "A condition true when two words have the same letter at P1 and P2."
  #'(lambda (w1 w2)
      (and (< p1 (length w1)) (< p2 (length w2))
	   (eql (char w1 p1) (char w2 p2)))))

(defun adjacent-constraint (x y)
  "True if the numbers X and Y are adjacent."
  (= (abs (- x y)) 1))

(defun sum-constraint (n)
  "A condition true when the values add up to N."
  #'(lambda (&rest values) (= (reduce #'+ values) n)))

(defun is-constraint (val)
  "A condition true when its argument is VAL."
  #'(lambda (x) (equal x val)))

(defun ne-constraint (val)
  "A condition true when its argument is not VAL."
  #'(lambda (x) (not (equal x val))))

;;;; Arc Heuristics for GAC

;;; An arc is a pair (var . constraint); a heuristic picks the next one
;;; from a non-empty list of arcs.

(defun no-heuristic (arcs)
  "Take the arcs in list order."
  (first arcs))

(defun sat-up (arcs)
  "Take first an arc whose constraint has the smallest scope."
  (the-smallest #'(lambda (arc) (length (nary-constraint-scope (cdr arc))))
		arcs))

;;;; Generalized Arc Consistency

;;; Domains are kept in a hash table var -> list of values, which GAC copies
;;; before reducing it.

(defun nary-csp-domain-table (csp)
  "The domains of CSP as a hash table."
  (let ((table (make-hash-table :test #'equal)))
    (dolist (d (nary-csp-domains csp) table)
      (setf (gethash (car d) table) (copy-list (cdr d))))))

(defun gac (csp &key domains (to-do nil to-do?) (arc-heuristic #'sat-up))
  "Make CSP generalized-arc-consistent, starting from DOMAINS (a hash
  table, by default the domains of CSP) and the arcs TO-DO (by default all
  of them).  Return three values: nil if a domain is wiped out and t
  otherwise, the reduced domains, and the number of checks."
  (let ((domains (if domains
		     (copy-hash-table domains)
		   (nary-csp-domain-table csp)))
	(to-do (if to-do?
		   (copy-list to-do)
		 (loop for const in (nary-csp-constraints csp)
		       nconc (mapcar #'(lambda (var) (cons var const))
				     (nary-constraint-scope const)))))
	(checks 0))
    (setf to-do (remove-duplicates to-do :test #'equal))
    (loop while to-do do
	  (let* ((arc (funcall arc-heuristic to-do))
		 (var (car arc))
		 (const (cdr arc))
		 (other-vars (remove var (nary-constraint-scope const)
				     :test #'equal))
		 (new-domain nil))
	    (setf to-do (remove arc to-do :test #'equal :count 1))
	    (dolist (val (gethash var domains))
	      (multiple-value-bind (holds new-checks)
		  (nary-any-holds domains const (list (cons var val))
				  other-vars checks)
		(setf checks new-checks)
		(when holds (push val new-domain))))
	    (setf new-domain (nreverse new-domain))
	    (when (/= (length new-domain) (length (gethash var domains)))
	      (setf (gethash var domains) new-domain)
	      (when (null new-domain)
		(return-from gac (values nil domains checks)))
	      (dolist (new-arc (nary-new-to-do csp var const))
		(unless (member new-arc to-do :test #'equal)
		  (setf to-do (nconc to-do (list new-arc))))))))
    (values t domains checks)))

(defun nary-new-to-do (csp var const)
  "The arcs to recheck after the domain of VAR is reduced by CONST: those
  of the other variables of the other constraints on VAR.  With CONST nil,
  all the constraints on VAR are taken."
  (let ((result nil))
    (dolist (nconst (gethash var (nary-csp-var-to-const csp)))
      (unless (eq nconst const)
	(dolist (nvar (nary-constraint-scope nconst))
	  (unless (equal nvar var)
	    (pushnew (cons nvar nconst) result :test #'equal)))))
    (nreverse result)))

(defun nary-any-holds (domains const env other-vars &optional (checks 0))
  "Does CONST hold for some extension of the alist ENV with values of
  OTHER-VARS taken from DOMAINS?  Return also the number of checks."
  (if (null other-vars)
      (values (nary-constraint-holds const env) (+ checks 1))
    (let ((var (first other-vars)))
      (dolist (val (gethash var domains) (values nil checks))
	(multiple-value-bind (holds new-checks)
	    (nary-any-holds domains const (acons var val env)
			    (rest other-vars) checks)
	  (setf checks new-checks)
	  (when holds (return (values t checks))))))))

(defun partition-domain (domain)
  "Split a list of values in two halves."
  (let ((split (floor (length domain) 2)))
    (values (subseq domain 0 split) (subseq domain split))))

(defun nary-solution-from-domains (csp domains)
  "The assignment alist when every domain has a single value, else nil."
  (when (every #'(lambda (var) (= 1 (length (gethash var domains))))
	       (nary-csp-variables csp))
    (mapcar #'(lambda (var) (cons var (first (gethash var domains))))
	    (nary-csp-variables csp))))

(defun nary-domains-with (domains var values)
  "A copy of the domain table DOMAINS with VAR restricted to VALUES."
  (let ((new (copy-hash-table domains)))
    (setf (gethash var new) values)
    new))

;;;; Arc Consistency with Domain Splitting

(defun ac-domain-splitting (csp &key domains (to-do nil to-do?)
				(arc-heuristic #'sat-up))
  "Return a solution of CSP (an alist), or nil, by making the domains
  arc-consistent and splitting the first domain with more than one value."
  (multiple-value-bind (consistent new-domains)
      (if to-do?
	  (gac csp :domains domains :to-do to-do :arc-heuristic arc-heuristic)
	(gac csp :domains domains :arc-heuristic arc-heuristic))
    (cond ((not consistent) nil)
	  ((nary-solution-from-domains csp new-domains))
	  (t (let ((var (find-if #'(lambda (x)
				     (> (length (gethash x new-domains)) 1))
				 (nary-csp-variables csp))))
	       (multiple-value-bind (dom1 dom2)
		   (partition-domain (gethash var new-domains))
		 (let ((to-do (nary-new-to-do csp var nil)))
		   (or (ac-domain-splitting
			csp :domains (nary-domains-with new-domains var dom1)
			:to-do to-do :arc-heuristic arc-heuristic)
		       (ac-domain-splitting
			csp :domains (nary-domains-with new-domains var dom2)
			:to-do to-do :arc-heuristic arc-heuristic)))))))))

(defun ac-solver (csp &key (arc-heuristic #'sat-up))
  "Solve CSP by arc consistency and domain splitting; return the solution
  as an alist ((var . value) ...), or nil."
  (ac-domain-splitting csp :arc-heuristic arc-heuristic))

;;;; Arc Consistency with Search

;;; The problem whose states are arc-consistent domain tables: a successor
;;; splits a domain with more than one value and makes the half consistent.

(defstructure (ac-search-problem (:include problem))
  "Search for a solution of an n-ary CSP in the space of reduced domains."
  (csp nil)
  (arc-heuristic #'sat-up))

(defmethod goal-test ((problem ac-search-problem) domains)
  "A state is a goal when every domain has a single value."
  (every #'(lambda (var) (= 1 (length (gethash var domains))))
	 (nary-csp-variables (ac-search-problem-csp problem))))

(defmethod successors ((problem ac-search-problem) domains)
  "Split the first domain with more than one value, and keep the halves
  that GAC does not wipe out.  The action is the new state itself."
  (let* ((csp (ac-search-problem-csp problem))
	 (var (find-if #'(lambda (x) (> (length (gethash x domains)) 1))
		       (nary-csp-variables csp)))
	 (result nil))
    (when var
      (multiple-value-bind (dom1 dom2) (partition-domain (gethash var domains))
	(let ((to-do (nary-new-to-do csp var nil)))
	  (dolist (dom (list dom1 dom2))
	    (multiple-value-bind (consistent new-domains)
		(gac csp :domains (nary-domains-with domains var dom)
		     :to-do to-do
		     :arc-heuristic (ac-search-problem-arc-heuristic problem))
	      (when consistent
		(push (cons new-domains new-domains) result)))))))
    (nreverse result)))

(defun ac-search-solver (csp &key (arc-heuristic #'sat-up))
  "Solve CSP by arc consistency and depth-first search on the splits of
  the domains; return the solution as an alist ((var . value) ...), or nil."
  (multiple-value-bind (consistent domains)
      (gac csp :arc-heuristic arc-heuristic)
    (when consistent
      (let ((node (depth-first-search
		   (make-ac-search-problem :initial-state domains :csp csp
					   :arc-heuristic arc-heuristic))))
	(when node
	  (nary-solution-from-domains csp (node-state node)))))))
