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

;;;; Classical Planning Problems in a PDDL-like Representation

;;; A state is a list of ground atoms, such as ((At C1 SFO) (Cargo C1)), under
;;; the closed-world assumption: an atom that is not in the list is false.
;;; States are kept in a canonical (sorted, duplicate-free) form, so that two
;;; equal states are EQUAL.  An atom is always a list, even when it has no
;;; arguments: (Have Cake), (A).  A literal is an atom or (not atom).
;;;
;;; An action schema has a name such as (Load $c $p $a), whose arguments are
;;; the parameters ($-variables, as in logic/algorithms/unify.lisp), a
;;; precondition and an effect.  Both are lists of literals; a negative
;;; literal in the effect is a delete, a positive one an add.  A precondition
;;; may also contain inequality tests (/= x y) [Fig. 11.4].  A ground action
;;; is an action schema with no variables.

(defstructure planning-problem
  "A planning problem: the initial state (a list of ground atoms), the goal
  (a list of literals) and the action schemas [Sec. 11.1]."
  (initial nil)
  (goal nil)
  (schemas nil))

(defstructure action-schema
  "An action schema (or a ground action): name, precondition and effect."
  name
  (precond nil)
  (effect nil))

(defmethod print-structure ((a action-schema) stream)
  (format stream "#<ACTION ~A>" (action-schema-name a)))

(defmethod print-structure ((p planning-problem) stream)
  (format stream "#<PLANNING-PROBLEM goal: ~A>" (planning-problem-goal p)))

;;;; Literals and States

(defun planning-negative-p (literal)
  "Is LITERAL of the form (not atom)?"
  (eq (first literal) 'not))

(defun planning-test-p (literal)
  "Is LITERAL an inequality test (/= x y) rather than a fluent?"
  (eq (first literal) '/=))

(defun planning-atom (literal)
  "The atom of a literal."
  (if (planning-negative-p literal) (second literal) literal))

(defun planning-negate (literal)
  "The complementary literal."
  (if (planning-negative-p literal) (second literal) (list 'not literal)))

(defun planning-canonical (literals)
  "Sort a list of atoms or literals and drop the duplicates."
  (mapcar #'cdr
	  (sort (remove-duplicates
		 (mapcar #'(lambda (x) (cons (prin1-to-string x) x)) literals)
		 :test #'string= :key #'car)
		#'string< :key #'car)))

(defun planning-holds-p (literal state)
  "Does LITERAL hold in STATE (under the closed-world assumption)?"
  (cond ((planning-test-p literal)
	 (not (equal (second literal) (third literal))))
	((planning-negative-p literal)
	 (not (member (second literal) state :test #'equal)))
	(t (member literal state :test #'equal))))

(defun planning-satisfies-p (state literals)
  "Do all the LITERALS hold in STATE?"
  (every #'(lambda (literal) (planning-holds-p literal state)) literals))

(defun planning-apply-effects (state effects)
  "The state that results from STATE with the deletes and then the adds
  of EFFECTS."
  (let ((deletes (mapcar #'second (remove-if-not #'planning-negative-p effects)))
	(adds (remove-if #'planning-negative-p effects)))
    (planning-canonical
     (append adds (remove-if #'(lambda (atom)
				 (member atom deletes :test #'equal))
			     state)))))

(defun planning-applicable-p (action state)
  "Is the precondition of the ground ACTION satisfied in STATE?"
  (planning-satisfies-p state (action-schema-precond action)))

(defun planning-apply (action state)
  "RESULT(state, action) for a ground action [Sec. 11.1]."
  (planning-apply-effects state (action-schema-effect action)))

(defun planning-goal-test (problem state)
  "Is the goal of the planning problem satisfied in STATE?"
  (planning-satisfies-p state (planning-problem-goal problem)))

;;;; Executing Actions by Name

(defun planning-instantiate (schema bindings)
  "The action that results from substituting BINDINGS in SCHEMA."
  (make-action-schema
   :name (subst-bindings bindings (action-schema-name schema))
   :precond (subst-bindings bindings (action-schema-precond schema))
   :effect (subst-bindings bindings (action-schema-effect schema))))

(defun planning-find-action (name schemas)
  "The ground action called NAME, from the first schema whose name
  unifies with it, or nil."
  (dolist (schema schemas nil)
    (let ((b (unify (action-schema-name schema) name)))
      (unless (eq b +fail+)
	(return (planning-instantiate schema b))))))

(defun planning-result (problem state plan)
  "Execute the actions named in PLAN, starting from STATE.  Return the
  final state, or :FAIL if an action is unknown or not applicable."
  (dolist (name plan state)
    (let ((action (planning-find-action name (planning-problem-schemas problem))))
      (if (and action (planning-applicable-p action state))
	  (setf state (planning-apply action state))
	(return :fail)))))

(defun planning-execute (problem plan)
  "Execute PLAN from the initial state and return the final state (or :FAIL)."
  (planning-result problem (planning-canonical (planning-problem-initial problem))
		   plan))

(defun planning-plan-works-p (problem plan)
  "Does PLAN, executed from the initial state, achieve the goal?  PLAN may
  also be :FAIL, as returned by the planners that fail."
  (and (listp plan)
       (let ((state (planning-execute problem plan)))
	 (and (not (eq state :fail)) (planning-goal-test problem state)))))

;;;; Grounding the Action Schemas

;;; Ground actions are generated by relaxed reachability: starting from the
;;; initial atoms, each schema is instantiated by matching its positive
;;; preconditions against the atoms reached so far, and the adds of the new
;;; ground actions are reached in turn, until nothing changes.  Ignoring the
;;; deletes and the negative preconditions over-approximates the reachable
;;; actions, so no executable action is lost.  Parameters that occur in no
;;; positive precondition range over all the objects of the problem.

(defun planning-objects (problem)
  "All the constants that are arguments of an atom in the problem."
  (let ((objects nil))
    (labels ((walk (literal)
	       (unless (planning-test-p literal)
		 (dolist (arg (rest (planning-atom literal)))
		   (unless (variable? arg) (pushnew arg objects :test #'equal))))))
      (mapc #'walk (planning-problem-initial problem))
      (mapc #'walk (planning-problem-goal problem))
      (dolist (schema (planning-problem-schemas problem))
	(walk (action-schema-name schema))
	(mapc #'walk (action-schema-precond schema))
	(mapc #'walk (action-schema-effect schema))))
    (nreverse objects)))

(defun planning-match (literals index bindings)
  "All the extensions of BINDINGS that make each positive literal of
  LITERALS equal to an atom of INDEX (a table from predicate to atoms)."
  (if (null literals)
      (list bindings)
    (let ((literal (first literals)))
      (if (or (planning-negative-p literal) (planning-test-p literal))
	  (planning-match (rest literals) index bindings)
	(let ((result nil))
	  (dolist (atom (gethash (first literal) index) result)
	    (let ((b (unify literal atom bindings)))
	      (unless (eq b +fail+)
		(setf result (append result
				     (planning-match (rest literals) index b)))))))))))

(defun planning-complete-bindings (vars objects bindings)
  "Extend BINDINGS in every way that binds the unbound VARS to OBJECTS."
  (cond ((null vars) (list bindings))
	((get-binding (first vars) bindings)
	 (planning-complete-bindings (rest vars) objects bindings))
	(t (mapcan #'(lambda (object)
		       (planning-complete-bindings
			(rest vars) objects
			(extend-bindings (first vars) object bindings)))
		   objects))))

(defun planning-ground-actions (problem)
  "The ground actions of PROBLEM that are reachable when the deletes and
  the negative preconditions are ignored."
  (let ((reached (make-hash-table :test #'equal))
	(index (make-hash-table :test #'eq))
	(seen (make-hash-table :test #'equal))
	(objects (planning-objects problem))
	(actions nil)
	(changed t))
    (flet ((reach (atom)
	     (unless (gethash atom reached)
	       (setf (gethash atom reached) t
		     changed t)
	       (push atom (gethash (first atom) index)))))
      (mapc #'reach (planning-problem-initial problem))
      (loop while changed do
	(setf changed nil)
	(dolist (schema (planning-problem-schemas problem))
	  (dolist (b (planning-match (action-schema-precond schema) index
				     +no-bindings+))
	    (dolist (b2 (planning-complete-bindings
			 (variables-in (action-schema-name schema)) objects b))
	      (let ((action (planning-instantiate schema b2)))
		(unless (gethash (action-schema-name action) seen)
		  (when (every #'(lambda (literal)
				   (or (not (planning-test-p literal))
				       (planning-holds-p literal nil)))
			       (action-schema-precond action))
		    (setf (gethash (action-schema-name action) seen) t)
		    (push action actions)
		    (dolist (literal (action-schema-effect action))
		      (unless (planning-negative-p literal)
			(reach literal))))))))))
      ;; The tests are true for every ground action left: drop them.
      (mapcar #'(lambda (action)
		  (setf (action-schema-precond action)
			(remove-if #'planning-test-p (action-schema-precond action)))
		  action)
	      (nreverse actions)))))

(defun planning-fluents (actions)
  "The ground atoms that some ground action in ACTIONS adds or deletes;
  the other atoms never change."
  (let ((fluents nil))
    (dolist (action actions)
      (dolist (literal (action-schema-effect action))
	(push (planning-atom literal) fluents)))
    (planning-canonical fluents)))

;;;; Relaxed Reachability Levels (used by the heuristics)

(defun planning-atom-levels (state actions)
  "A table from each atom to the first level at which it is reached from
  STATE, ignoring deletes and negative preconditions (the level of the
  relaxed planning graph, Sec. 11.3)."
  (let ((levels (make-hash-table :test #'equal))
	(level 0)
	(pending actions))
    (dolist (atom state) (setf (gethash atom levels) 0))
    (loop
      (incf level)
      (let ((new nil) (still nil))
	(dolist (action pending)
	  (if (every #'(lambda (literal)
			 (or (planning-negative-p literal)
			     (gethash literal levels)))
		     (action-schema-precond action))
	      (dolist (literal (action-schema-effect action))
		(unless (or (planning-negative-p literal) (gethash literal levels))
		  (push literal new)))
	    (push action still)))
	(when (null new) (return levels))
	(dolist (atom new)
	  (unless (gethash atom levels) (setf (gethash atom levels) level)))
	(setf pending still)))))

(defparameter *planning-unreachable-cost* 1000000
  "Heuristic value for a state from which the goal is unreachable.")

(defun planning-max-level (literals levels)
  "The maximum level of the positive LITERALS (an admissible heuristic)."
  (let ((h 0))
    (dolist (literal literals h)
      (unless (planning-negative-p literal)
	(let ((level (gethash literal levels)))
	  (if level
	      (setf h (max h level))
	    (return *planning-unreachable-cost*)))))))
