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

;;;; Hierarchical Planning: Hierarchical Search and Angelic Search

;;; A plan is a list of action names.  A hierarchy is a list of REFINEMENTs:
;;; a high-level action (HLA) is an action name that matches the HLA of some
;;; refinement, and every other action is primitive and is executed with the
;;; action schemas of the planning problem [Sec. 11.4.1].  A refinement may
;;; have a precondition, and its steps may use the variables of its HLA,
;;; e.g. (make-refinement :hla '(Go $x $y) :steps '((Taxi $x $y))).

(defstructure refinement
  "One way of implementing a high-level action by a sequence of steps
  [Fig. 11.7]."
  hla
  (precond nil)
  (steps nil))

(defun hla-p (name hierarchy)
  "Is the action NAME a high-level action in HIERARCHY?"
  (some #'(lambda (r) (not (eq (unify (refinement-hla r) name) +fail+)))
	hierarchy))

(defun hla-refinements (hla state hierarchy)
  "The step sequences of the refinements of HLA whose preconditions are
  satisfied in STATE, in the order of HIERARCHY."
  (let ((result nil))
    (dolist (r hierarchy (nreverse result))
      (let ((b (unify (refinement-hla r) hla)))
	(unless (eq b +fail+)
	  (when (planning-satisfies-p
		 state (subst-bindings b (refinement-precond r)))
	    (push (subst-bindings b (refinement-steps r)) result)))))))

(defun hla-split (plan hierarchy)
  "Return the first HLA of PLAN (or nil), and the actions before and after it."
  (let ((i (position-if #'(lambda (a) (hla-p a hierarchy)) plan)))
    (if i
	(values (elt plan i) (subseq plan 0 i) (subseq plan (1+ i)))
      (values nil plan nil))))

;;;; Hierarchical Search

(defun hierarchical-search (problem hierarchy &key (initial-plan '((Act)))
				    (max-length nil))
  "A breadth-first implementation of hierarchical forward planning search
  [Fig. 11.8].  Return the primitive plan and T, or NIL and NIL on failure.
  MAX-LENGTH, if given, prunes the plans with more actions, which makes the
  search terminate on recursive hierarchies."
  (let ((frontier (list initial-plan))
	(initial (planning-canonical (planning-problem-initial problem))))
    (loop
      (when (null frontier) (return (values nil nil)))
      (let ((plan (pop frontier)))
	(multiple-value-bind (hla prefix suffix) (hla-split plan hierarchy)
	  (let ((outcome (planning-result problem initial prefix)))
	    (unless (eq outcome :fail)
	      (if (null hla)
		  (when (planning-goal-test problem outcome)
		    (return (values plan t)))
		(dolist (sequence (hla-refinements hla outcome hierarchy))
		  (let ((new (append prefix sequence suffix)))
		    (when (or (null max-length) (<= (length new) max-length))
		      (setf frontier (append frontier (list new))))))))))))))

;;;; Angelic Descriptions and Reachable Sets

;;; An angelic description of an HLA gives a precondition and an optimistic
;;; and a pessimistic effect [Sec. 11.4.3].  Besides the literals of an
;;; ordinary effect, an angelic effect may contain (possibly-add atom),
;;; (possibly-delete atom) and (possibly-add-or-delete atom).  An HLA without
;;; an angelic description is described exactly by its action schema in the
;;; planning problem, as a primitive action is.

(defstructure angelic-description
  "The optimistic and pessimistic descriptions of a high-level action."
  hla
  (precond nil)
  (optimistic nil)
  (pessimistic nil))

(defun angelic-effect-sets (effects)
  "All the ordinary effects (lists of literals) that the angelic EFFECTS
  allow, e.g. ((A) (possibly-delete (B))) allows ((A) (not (B))) and ((A))."
  (if (null effects)
      (list nil)
    (let ((rest (angelic-effect-sets (rest effects)))
	  (e (first effects)))
      (mapcan #'(lambda (choice)
		  (mapcar #'(lambda (r) (append choice r)) rest))
	      (case (first e)
		(possibly-add (list (list (second e)) nil))
		(possibly-delete (list (list (list 'not (second e))) nil))
		(possibly-add-or-delete (list (list (second e))
					      (list (list 'not (second e)))
					      nil))
		(t (list (list e))))))))

(defun angelic-step-states (problem descriptions name state optimistic?)
  "The states reachable from STATE by the action NAME, according to its
  optimistic or pessimistic angelic description if it has one, and to its
  action schema otherwise."
  (let ((description
	 (find-if #'(lambda (d)
		      (not (eq (unify (angelic-description-hla d) name) +fail+)))
		  descriptions)))
    (if description
	(let ((b (unify (angelic-description-hla description) name)))
	  (if (planning-satisfies-p
	       state (subst-bindings b (angelic-description-precond description)))
	      (planning-canonical-states
	       (mapcar #'(lambda (effect) (planning-apply-effects state effect))
		       (angelic-effect-sets
			(subst-bindings
			 b (if optimistic?
			       (angelic-description-optimistic description)
			     (angelic-description-pessimistic description))))))
	    nil))
      (let ((next (planning-result problem state (list name))))
	(if (eq next :fail) nil (list next))))))

(defun planning-canonical-states (states)
  "Remove the duplicate states."
  (remove-duplicates states :test #'equal :from-end t))

(defun angelic-reach (problem descriptions state plan optimistic?)
  "The optimistic (REACH+) or pessimistic (REACH-) reachable set of PLAN
  from STATE: the list of the states in which it may end."
  (let ((states (list state)))
    (dolist (name plan states)
      (setf states
	    (planning-canonical-states
	     (mapcan #'(lambda (s)
			 (copy-list (angelic-step-states problem descriptions
							 name s optimistic?)))
		     states))))))

;;;; Angelic Search

(defun angelic-search (problem hierarchy descriptions initial-plan)
  "A hierarchical planning algorithm that uses angelic semantics to commit
  to high-level plans that work and to discard those that do not
  [Fig. 11.11].  Return the primitive plan and T, or NIL and NIL."
  (angelic-search-from problem hierarchy descriptions
		       (planning-canonical (planning-problem-initial problem))
		       #'(lambda (s) (planning-goal-test problem s))
		       initial-plan))

(defun angelic-search-from (problem hierarchy descriptions initial goal-p
				    initial-plan)
  "ANGELIC-SEARCH from the state INITIAL to a state satisfying GOAL-P."
  (let ((frontier (list initial-plan)))
    (loop
      (when (null frontier) (return (values nil nil)))
      (let ((plan (pop frontier)))
	(when (some goal-p (angelic-reach problem descriptions initial plan t))
	  (multiple-value-bind (hla prefix suffix) (hla-split plan hierarchy)
	    ;; REACH+ is exact for primitive plans
	    (when (null hla) (return (values plan t)))
	    (let ((guaranteed (remove-if-not
			       goal-p
			       (angelic-reach problem descriptions initial plan nil))))
	      ;; MAKING-PROGRESS: the plan is not the initial plan
	      (when (and guaranteed (not (equal plan initial-plan)))
		(return (angelic-decompose problem hierarchy descriptions
					   initial plan (first guaranteed)))))
	    (let ((outcome (planning-result problem initial prefix)))
	      (unless (eq outcome :fail)
		(dolist (sequence (hla-refinements hla outcome hierarchy))
		  (setf frontier
			(append frontier
				(list (append prefix sequence suffix)))))))))))))

(defun angelic-decompose (problem hierarchy descriptions s0 plan sf)
  "DECOMPOSE [Fig. 11.11]: refine each action of PLAN, from the last one
  back, into a primitive plan between two states of the pessimistic
  reachable sets.  Return the primitive plan and T, or NIL and NIL."
  (let ((solution nil)
	(plan (copy-list plan)))
    (loop while plan do
      (let* ((action (car (last plan)))
	     (si nil))
	(setf plan (butlast plan))
	(setf si (find-if #'(lambda (s)
			      (member sf (angelic-reach problem descriptions s
							(list action) nil)
				      :test #'equal))
			  (angelic-reach problem descriptions s0 plan nil)))
	(unless si (return-from angelic-decompose (values nil nil)))
	(let ((target sf))
	  (multiple-value-bind (sub found?)
	      (angelic-search-from problem hierarchy descriptions si
				   #'(lambda (s) (equal s target))
				   (list action))
	    (unless found? (return-from angelic-decompose (values nil nil)))
	    (setf solution (append sub solution)
		  sf si)))))
    (values solution t)))
