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

;;;; GRAPHPLAN: Planning Graphs and Solution Extraction

;;; A planning graph alternates levels of literals S0, S1, ... and levels of
;;; actions A0, A1, ...  Literal levels hold positive and negative literals
;;; (S0 has the initial atoms and the negation of every other fluent).  The
;;; actions of Ai are the ground actions whose preconditions are in Si and
;;; pairwise not mutex, plus a persistence action (no-op) for each literal of
;;; Si.  Mutual exclusion links follow the usual definitions:
;;; two actions are mutex if they have inconsistent effects, if one
;;; interferes with a precondition of the other, or if they have competing
;;; needs; two literals are mutex if one is the negation of the other, or if
;;; every pair of actions achieving them is mutex (inconsistent support).
;;; Planning graphs and GRAPHPLAN are described in the 3rd edition (Sec. 10.3,
;;; Fig. 10.9) and mentioned in Sec. 11.2.3 of the 4th.

(defstructure graphplan-level
  "One literal level Si, with its mutexes, and the action level Ai that
  follows it (empty until the graph is expanded)."
  (literals nil)                       ; list of literals
  (literal-mutexes (make-hash-table :test #'equal)) ; (l1 . l2) -> t
  (actions nil)                        ; list of action-schema (no-ops too)
  (action-mutexes (make-hash-table :test #'equal))  ; (name1 . name2) -> t
  (achievers (make-hash-table :test #'equal)))      ; literal -> actions of Ai-1

(defstructure graphplan-graph
  "A planning graph: the levels, the ground actions and the goal."
  (levels nil)                         ; vector of graphplan-level
  (actions nil)
  (goal nil))

(defun graphplan-noop-p (action)
  (eq (first (action-schema-name action)) 'noop))

(defun graphplan-noop (literal)
  "The persistence action for LITERAL."
  (make-action-schema :name (list 'noop literal)
		      :precond (list literal) :effect (list literal)))

(defun graphplan-mark (table x y)
  (setf (gethash (cons x y) table) t
	(gethash (cons y x) table) t))

(defun graphplan-mutex-p (table x y)
  (gethash (cons x y) table))

(defun graphplan-initial-graph (problem)
  "The planning graph with the single literal level S0."
  (let* ((actions (planning-ground-actions problem))
	 (initial (planning-canonical (planning-problem-initial problem)))
	 (atoms (planning-canonical
		 (append initial
			 (mapcar #'planning-atom (planning-problem-goal problem))
			 (mapcan #'(lambda (a)
				     (mapcar #'planning-atom
					     (append (action-schema-precond a)
						     (action-schema-effect a))))
				 actions))))
	 (literals (mapcar #'(lambda (atom)
			       (if (member atom initial :test #'equal)
				   atom
				 (list 'not atom)))
			   atoms)))
    (make-graphplan-graph
     :levels (make-array 1 :adjustable t :fill-pointer 1
			 :initial-element (make-graphplan-level :literals literals))
     :actions actions
     :goal (planning-problem-goal problem))))

(defun graphplan-last-level (graph)
  (let ((levels (graphplan-graph-levels graph)))
    (aref levels (1- (length levels)))))

(defun graphplan-actions-mutex-p (a b literal-mutexes)
  "Are the actions A and B mutex, given the mutexes of the literal level
  they start from?"
  (let ((pre-a (action-schema-precond a)) (eff-a (action-schema-effect a))
	(pre-b (action-schema-precond b)) (eff-b (action-schema-effect b)))
    (flet ((negates (literals others)
	     (some #'(lambda (l) (member (planning-negate l) others :test #'equal))
		   literals)))
      (or (negates eff-a eff-b)		; inconsistent effects
	  (negates eff-a pre-b)		; interference
	  (negates eff-b pre-a)
	  (some #'(lambda (p)		; competing needs
		    (some #'(lambda (q) (graphplan-mutex-p literal-mutexes p q))
			  pre-b))
		pre-a)))))

(defun graphplan-expand (graph)
  "Add the action level after the last literal level, and the next
  literal level with its mutexes."
  (let* ((level (graphplan-last-level graph))
	 (literals (graphplan-level-literals level))
	 (mutexes (graphplan-level-literal-mutexes level))
	 (actions (mapcar #'graphplan-noop literals)))
    ;; The actions whose preconditions hold and are pairwise not mutex
    (dolist (action (graphplan-graph-actions graph))
      (let ((pre (action-schema-precond action)))
	(when (and (every #'(lambda (p) (member p literals :test #'equal)) pre)
		   (loop for (p . rest) on pre
			 never (some #'(lambda (q) (graphplan-mutex-p mutexes p q))
				     rest)))
	  (push action actions))))
    (setf actions (nreverse actions))
    (setf (graphplan-level-actions level) actions)
    ;; Action mutexes
    (let ((action-mutexes (graphplan-level-action-mutexes level)))
      (loop for (a . rest) on actions do
	(dolist (b rest)
	  (when (graphplan-actions-mutex-p a b mutexes)
	    (graphplan-mark action-mutexes
			    (action-schema-name a) (action-schema-name b)))))
      ;; The next literal level, its achievers and its mutexes
      (let ((next (make-graphplan-level))
	    (new-literals nil))
	(dolist (action actions)
	  (dolist (literal (action-schema-effect action))
	    (unless (gethash literal (graphplan-level-achievers next))
	      (push literal new-literals))
	    (push action (gethash literal (graphplan-level-achievers next)))))
	(setf new-literals (planning-canonical new-literals))
	(setf (graphplan-level-literals next) new-literals)
	(loop for (l1 . rest) on new-literals do
	  (dolist (l2 rest)
	    (when (or (equal l2 (planning-negate l1))
		      (every #'(lambda (a1)
				 (every #'(lambda (a2)
					    (and (not (eq a1 a2))
						 (graphplan-mutex-p
						  action-mutexes
						  (action-schema-name a1)
						  (action-schema-name a2))))
					(gethash l2 (graphplan-level-achievers next))))
			     (gethash l1 (graphplan-level-achievers next))))
	      (graphplan-mark (graphplan-level-literal-mutexes next) l1 l2))))
	(vector-push-extend next (graphplan-graph-levels graph))
	graph))))

(defun graphplan-leveled-off-p (graph)
  "Have the last two literal levels the same literals and mutexes?"
  (let ((levels (graphplan-graph-levels graph)))
    (and (>= (length levels) 2)
	 (let ((a (aref levels (- (length levels) 2)))
	       (b (aref levels (- (length levels) 1))))
	   (and (= (length (graphplan-level-literals a))
		   (length (graphplan-level-literals b)))
		(= (hash-table-count (graphplan-level-literal-mutexes a))
		   (hash-table-count (graphplan-level-literal-mutexes b))))))))

(defun graphplan-goals-possible-p (graph goals)
  "Are all GOALS in the last literal level, and pairwise not mutex?"
  (let* ((level (graphplan-last-level graph))
	 (literals (graphplan-level-literals level))
	 (mutexes (graphplan-level-literal-mutexes level)))
    (and (every #'(lambda (g) (member g literals :test #'equal)) goals)
	 (loop for (g . rest) on goals
	       never (some #'(lambda (h) (graphplan-mutex-p mutexes g h)) rest)))))

(defun graphplan-extract-solution (graph goals index nogoods)
  "Search backward from literal level INDEX for a set of non-mutex actions
  achieving GOALS, then recursively for their preconditions.  Return the
  plan as a list of steps (each a list of action names), or :FAIL.
  Failed (level . goals) pairs are recorded in the NOGOODS table."
  (let ((goals (planning-canonical goals)))
    (cond ((= index 0) nil)		; the goals are in S0 by construction
	  ((gethash (cons index goals) nogoods) :fail)
	  (t (let* ((levels (graphplan-graph-levels graph))
		    (here (aref levels index))
		    (previous (aref levels (1- index)))
		    (mutexes (graphplan-level-action-mutexes previous)))
	       (labels
		   ((choose (open chosen)
		      (cond
		       ((null open)
			(let ((sub (graphplan-extract-solution
				    graph
				    (remove-duplicates
				     (mapcan #'(lambda (a)
						 (copy-list (action-schema-precond a)))
					     chosen)
				     :test #'equal)
				    (1- index) nogoods)))
			  (unless (eq sub :fail)
			    (return-from graphplan-extract-solution
			      (append sub
				      (list (mapcar #'action-schema-name
						    (remove-if #'graphplan-noop-p
							       (reverse chosen)))))))))
		       ((some #'(lambda (a)
				  (member (first open) (action-schema-effect a)
					  :test #'equal))
			      chosen)
			(choose (rest open) chosen))
		       (t
			;; Try the no-op first, then the other achievers.
			(dolist (a (sort (copy-list (gethash (first open)
							     (graphplan-level-achievers here)))
					 #'(lambda (x y)
					     (and (graphplan-noop-p x)
						  (not (graphplan-noop-p y))))))
			  (when (notany #'(lambda (c)
					    (graphplan-mutex-p mutexes
							       (action-schema-name a)
							       (action-schema-name c)))
					chosen)
			    (choose (rest open) (cons a chosen))))))))
		 (choose goals nil)
		 (setf (gethash (cons index goals) nogoods) t)
		 :fail))))))

(defun graphplan (problem &key (max-levels 100))
  "Solve a planning problem with GRAPHPLAN.  Return the plan as a list of
  steps, each a list of the names of actions that can be executed in any
  order, or :FAIL."
  (let ((graph (graphplan-initial-graph problem))
	(goals (planning-problem-goal problem))
	(nogoods (make-hash-table :test #'equal))
	(previous-nogoods -1))
    (loop
      (let ((index (1- (length (graphplan-graph-levels graph)))))
	(when (graphplan-goals-possible-p graph goals)
	  (let ((plan (graphplan-extract-solution graph goals index nogoods)))
	    (unless (eq plan :fail)
	      (return (remove nil plan)))))
	;; Once the graph has leveled off, fail when an expansion adds no
	;; new nogood.
	(when (graphplan-leveled-off-p graph)
	  (when (= previous-nogoods (hash-table-count nogoods))
	    (return :fail))
	  (setf previous-nogoods (hash-table-count nogoods)))
	(when (>= index max-levels) (return :fail))
	(graphplan-expand graph)))))

(defun linearize-plan (steps)
  "Turn a GRAPHPLAN solution into a sequence of actions: the actions of a
  step are not mutex, so any order of them is valid."
  (if (listp steps) (apply #'append steps) steps))
