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

;;;; Partial-Order Planning

;;; A partial-order plan [Section 11.2.3, and Sec. 10.4.4 of the 3rd
;;; edition] has a set of steps, each an instance of a ground action
;;; (see PLANNING-GROUND-ACTIONS), ordering constraints (i . j), saying that
;;; step i comes before step j, causal links (i p j), saying that step i
;;; achieves the precondition p of step j, and an agenda of the open
;;; preconditions (p . j).  Step 0 is Start, whose effects are the initial
;;; state (and, under the closed-world assumption, the negation of every
;;; other atom), and step 1 is Finish, whose preconditions are the goal.
;;; The planner closes the open preconditions one at a time, with an
;;; existing step or a new one, and protects each causal link from the
;;; steps that threaten it by ordering them before or after the link.  It
;;; backtracks over these choices, and searches for plans with at most 0,
;;; 1, 2, ... steps, so it finds a plan with the fewest steps.

(defstruct partial-order-plan
  (steps nil)        ; alist (id . ground action), Start and Finish excluded
  (orderings nil)    ; list of (i . j)
  (links nil)        ; list of (i p j)
  (agenda nil)       ; list of (p . j)
  (next-id 2))

(defun partial-order-before? (plan i j)
  "Does the plan order step I before step J (transitively)?"
  (let ((seen nil))
    (labels ((reach (k)
	       (some #'(lambda (o)
			 (and (eql (car o) k)
			      (not (member (cdr o) seen))
			      (progn (push (cdr o) seen)
				     (or (eql (cdr o) j) (reach (cdr o))))))
		     (partial-order-plan-orderings plan))))
      (reach i))))

(defun partial-order-can-order? (plan i j)
  "Can step I be ordered before step J without a cycle?"
  (and (not (eql i j)) (not (eql i 1)) (not (eql j 0))
       (not (partial-order-before? plan j i))))

(defun partial-order-add-ordering (plan i j)
  (let ((new (copy-partial-order-plan plan)))
    (push (cons i j) (partial-order-plan-orderings new))
    new))

(defun partial-order-achieves? (step-id action literal initial)
  "Does the step (Start if STEP-ID is 0) make LITERAL true?"
  (if (eql step-id 0)
      (if (planning-negative-p literal)
	  (not (member (planning-atom literal) initial :test #'equal))
	(member literal initial :test #'equal))
    (member literal (action-schema-effect action) :test #'equal)))

(defun partial-order-find-threat (plan)
  "A list (k i j) for a step k that deletes the condition of the causal
  link (i p j) and may come between i and j, or nil."
  (dolist (link (partial-order-plan-links plan) nil)
    (destructuring-bind (i p j) link
      (dolist (step (partial-order-plan-steps plan))
	(let ((k (car step)))
	  (when (and (not (eql k i)) (not (eql k j))
		     (member (planning-negate p) (action-schema-effect (cdr step))
			     :test #'equal)
		     (not (partial-order-before? plan k i))
		     (not (partial-order-before? plan j k)))
	    (return-from partial-order-find-threat (list k i j))))))))

(defun partial-order-search (plan actions initial max-steps)
  "Complete PLAN with at most MAX-STEPS steps; return the plan or nil."
  (let ((threat (partial-order-find-threat plan)))
    (if threat
	;; Protect the link: demotion (k before i) or promotion (j before k)
	(destructuring-bind (k i j) threat
	  (or (and (partial-order-can-order? plan k i)
		   (partial-order-search (partial-order-add-ordering plan k i)
					 actions initial max-steps))
	      (and (partial-order-can-order? plan j k)
		   (partial-order-search (partial-order-add-ordering plan j k)
					 actions initial max-steps))))
      (if (null (partial-order-plan-agenda plan))
	  plan
	(destructuring-bind (p . j) (first (partial-order-plan-agenda plan))
	  (flet ((close-with (i extend)
		   ;; Link step I to the open precondition p of step j
		   (let ((new (copy-partial-order-plan plan)))
		     (setf (partial-order-plan-agenda new)
			   (rest (partial-order-plan-agenda plan)))
		     (push (list i p j) (partial-order-plan-links new))
		     (push (cons i j) (partial-order-plan-orderings new))
		     (when extend (funcall extend new))
		     (partial-order-search new actions initial max-steps))))
	    (or
	     ;; an existing step, Start included
	     (some #'(lambda (step)
		       (and (partial-order-achieves? (car step) (cdr step) p
						     initial)
			    (partial-order-can-order? plan (car step) j)
			    (close-with (car step) nil)))
		   (cons (cons 0 nil) (partial-order-plan-steps plan)))
	     ;; a new step
	     (and (< (length (partial-order-plan-steps plan)) max-steps)
		  (some #'(lambda (action)
			    (and (partial-order-achieves? -1 action p initial)
				 (let ((id (partial-order-plan-next-id plan)))
				   (close-with
				    id
				    #'(lambda (new)
					(push (cons id action)
					      (partial-order-plan-steps new))
					(incf (partial-order-plan-next-id new))
					(push (cons 0 id)
					      (partial-order-plan-orderings new))
					(push (cons id 1)
					      (partial-order-plan-orderings new))
					(setf (partial-order-plan-agenda new)
					      (append
					       (partial-order-plan-agenda new)
					       (mapcar #'(lambda (q) (cons q id))
						       (action-schema-precond
							action)))))))))
			actions)))))))))

(defun partial-order-linearize (plan)
  "The names of the steps of PLAN in an order consistent with its
  orderings (a topological sort, smallest step number first)."
  (let ((left (mapcar #'car (partial-order-plan-steps plan)))
	(result nil))
    (loop while left do
	  (let ((next (reduce #'min
			      (remove-if #'(lambda (k)
					     (some #'(lambda (o)
						       (and (eql (cdr o) k)
							    (member (car o) left)))
						   (partial-order-plan-orderings
						    plan)))
					 left))))
	    (setf left (remove next left))
	    (push (action-schema-name
		   (cdr (assoc next (partial-order-plan-steps plan))))
		  result)))
    (nreverse result)))

(defun partial-order-planner (problem &key (max-steps 10))
  "Find a partial-order plan for the planning PROBLEM with the fewest steps
  (at most MAX-STEPS).  Return a linearization of the plan (a list of action
  names), and the partial-order plan itself; or :FAIL."
  (let ((actions (planning-ground-actions problem))
	(initial (planning-canonical (planning-problem-initial problem))))
    (loop for n from 0 to max-steps do
	  (let ((plan (partial-order-search
		       (make-partial-order-plan
			:orderings (list (cons 0 1))
			:agenda (mapcar #'(lambda (g) (cons g 1))
					(planning-problem-goal problem)))
		       actions initial n)))
	    (when plan
	      (return-from partial-order-planner
		(values (partial-order-linearize plan) plan)))))
    :fail))
