;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: planning/algorithms/encodings.lisp

;;;; Planning as Satisfiability and as Constraint Satisfaction

;;; Two encodings of a planning problem of bounded length.  SAT-PLANNING
;;; builds the transition model of the reachable states and hands it to
;;; SATPLAN [Fig. 7.22] (logic/algorithms), which translates it into a
;;; propositional sentence for a SAT solver.  CSP-PLANNING encodes a plan of
;;; n steps as an n-ary CSP whose variables are the action at each step and
;;; the truth value of each fluent at each time, and solves it with
;;; AC-SEARCH-SOLVER (search/algorithms); both are outlined in Sec. 11.2.3.

;;;; Planning as Satisfiability

(defun planning-transition-model (problem)
  "Expand the states reachable from the initial state of PROBLEM.  Return
  the transition model, a list of (state . ((action . next-state) ...)),
  and the initial state."
  (let* ((actions (planning-ground-actions problem))
	 (initial (planning-canonical (planning-problem-initial problem)))
	 (seen (make-hash-table :test #'equal))
	 (frontier (list initial))
	 (model nil))
    (setf (gethash initial seen) t)
    (loop while frontier do
      (let* ((state (pop frontier))
	     (moves nil))
	(dolist (action actions)
	  (when (planning-applicable-p action state)
	    (let ((next (planning-apply action state)))
	      (push (cons (action-schema-name action) next) moves)
	      (unless (gethash next seen)
		(setf (gethash next seen) t)
		(setf frontier (append frontier (list next)))))))
	(push (cons state (nreverse moves)) model)))
    (values (nreverse model) initial)))

(defun sat-planning (problem t-max &key (sat-solver #'dpll-satisfiable))
  "Find a shortest plan of at most T-MAX actions by translating PROBLEM into
  propositional satisfiability problems solved by SAT-SOLVER: SATPLAN gets
  the transition model of the reachable states, and the goal as a predicate
  on them.  Return a list of action names, or :FAIL (nil when the initial
  state already satisfies the goal)."
  (multiple-value-bind (model initial) (planning-transition-model problem)
    (if (planning-goal-test problem initial)
	nil
      (or (satplan initial model
		   #'(lambda (state) (planning-goal-test problem state))
		   t-max :sat-solver sat-solver)
	  :fail))))

;;;; Planning as Constraint Satisfaction

(defun csp-planning (problem max-length &key (arc-heuristic #'sat-up))
  "Find a shortest plan of at most MAX-LENGTH actions by solving, for
  n = 1, 2, ..., an n-ary CSP whose variables are (ACTION k) for each step k
  and (fluent k) for each fluent and each time k.  The constraints fix the
  initial state and the goal and, for each fluent and step, relate the
  fluent before the action, the action and the fluent after it: the
  preconditions, the effects and the frame axiom.  Return a list of action
  names, or :FAIL."
  (let* ((actions (planning-ground-actions problem))
	 (fluents (planning-fluents actions))
	 (initial (planning-problem-initial problem))
	 (names (mapcar #'action-schema-name actions)))
    ;; A goal literal on an atom that never changes must hold initially.
    (unless (every #'(lambda (literal)
		       (or (member (planning-atom literal) fluents :test #'equal)
			   (planning-holds-p literal initial)))
		   (planning-problem-goal problem))
      (return-from csp-planning :fail))
    (flet ((requirement (action fluent)
	     ;; What the precondition of ACTION needs of FLUENT: T, NIL or :ANY
	     (cond ((member fluent (action-schema-precond action) :test #'equal) t)
		   ((member (list 'not fluent) (action-schema-precond action)
			    :test #'equal)
		    nil)
		   (t :any)))
	   (outcome (action fluent)
	     ;; What the effect of ACTION makes of FLUENT: T, NIL or :SAME
	     (cond ((member fluent (action-schema-effect action) :test #'equal) t)
		   ((member (list 'not fluent) (action-schema-effect action)
			    :test #'equal)
		    nil)
		   (t :same))))
      (loop for n from 1 to max-length do
	(let ((domains nil) (constraints nil))
	  (dotimes (k n)
	    (push (cons (list 'action k) names) domains))
	  (dolist (fluent fluents)
	    (dotimes (k (1+ n))
	      (push (cons (list fluent k) (list t nil)) domains)))
	  ;; Initial state and goal
	  (dolist (fluent fluents)
	    (let ((value (if (member fluent initial :test #'equal) t nil)))
	      (push (make-nary-constraint
		     :scope (list (list fluent 0))
		     :condition #'(lambda (x) (eq x value)))
		    constraints)))
	  (dolist (literal (planning-problem-goal problem))
	    (let ((fluent (planning-atom literal))
		  (value (not (planning-negative-p literal))))
	      (when (member fluent fluents :test #'equal)
		(push (make-nary-constraint
		       :scope (list (list fluent n))
		       :condition #'(lambda (x) (eq x value)))
		      constraints))))
	  ;; Preconditions, effects and frame axioms
	  (dolist (fluent fluents)
	    (let ((table (mapcar #'(lambda (action)
				     (list (action-schema-name action)
					   (requirement action fluent)
					   (outcome action fluent)))
				 actions)))
	      (dotimes (k n)
		(push (make-nary-constraint
		       :scope (list (list fluent k) (list 'action k)
				    (list fluent (1+ k)))
		       :condition
		       #'(lambda (before action after)
			   (let* ((entry (assoc action table :test #'equal))
				  (need (second entry))
				  (out (third entry)))
			     (and (or (eq need :any) (eq need before))
				  (if (eq out :same)
				      (eq after before)
				    (eq after out))))))
		      constraints))))
	  (let ((solution (ac-search-solver
			   (make-nary-csp :domains (nreverse domains)
					  :constraints (nreverse constraints))
			   :arc-heuristic arc-heuristic)))
	    (when solution
	      (return-from csp-planning
		(loop for k from 0 below n
		      collect (cdr (assoc (list 'action k) solution
					  :test #'equal))))))))
      :fail)))
