;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/sma-star.lisp

;;;; Simplified Memory-Bounded A* (SMA*), as described in the 4th edition

;;; SMA* proceeds like A* until the search tree holds MEMORY nodes; then it
;;; drops the worst leaf (highest f, the oldest among ties) and backs its
;;; f-cost up to the parent, which regenerates the forgotten subtree only
;;; when every other path looks worse.  It expands the newest best leaf.
;;; Unlike TREE-SMA in sma.lisp, it remembers the f-cost of each forgotten
;;; successor, and it returns nil when no solution fits in the memory.

(defstructure (sma-node (:include node))
  (children nil)  ; successors currently in memory
  (pending nil)   ; (action . state) pairs not yet generated
  (forgotten nil) ; alist from a dropped (action . state) pair to its f-cost
  (time 0))       ; creation order, to break ties

(defun sma*-search (problem &optional (memory 20))
  "Search with SMA* within MEMORY nodes; return a solution node or nil.
  [Section 3.5.5]"
  (let* ((clock 0)
	 (root (sma*-make-node problem (create-start-node problem)
			       0 nil memory (incf clock)))
	 (tree (list root)))
    (loop
     (let ((leaves (remove-if-not
		    #'(lambda (x) (or (not (sma*-complete? x))
				      (goal-test problem (node-state x))))
		    tree))
	   n)
       (when (null leaves) (return nil))
       ;; The leaf with the lowest priority, the newest among ties
       (setf n (first leaves))
       (dolist (x (rest leaves))
	 (let ((px (sma*-priority problem x))
	       (pn (sma*-priority problem n)))
	   (when (or (< px pn)
		     (and (= px pn) (> (sma-node-time x) (sma-node-time n))))
	     (setf n x))))
       (when (>= (sma*-priority problem n) infinity) (return nil))
       (when (goal-test problem (node-state n)) (return n))
       (block generate
	 (when (>= (length tree) memory)
	   (let ((droppable (remove-if #'(lambda (x)
					   (or (sma-node-children x)
					       (eq x root) (eq x n)))
				       tree)))
	     (when (null droppable)
	       ;; The tree is a single path that fills the memory
	       (setf (node-f-cost n) infinity
		     (sma-node-pending n) nil
		     (sma-node-forgotten n) nil)
	       (sma*-backup (node-parent n))
	       (return-from generate))
	     ;; The worst leaf, the oldest among ties
	     (let ((worst (first droppable)))
	       (dolist (x (rest droppable))
		 (when (or (> (node-f-cost x) (node-f-cost worst))
			   (and (= (node-f-cost x) (node-f-cost worst))
				(< (sma-node-time x) (sma-node-time worst))))
		   (setf worst x)))
	       (setf tree (remove worst tree :test #'eq))
	       (let ((parent (node-parent worst)))
		 (setf (sma-node-children parent)
		       (remove worst (sma-node-children parent) :test #'eq))
		 (push (cons (cons (node-action worst) (node-state worst))
			     (node-f-cost worst))
		       (sma-node-forgotten parent))
		 (sma*-backup parent)))))
	 (let (pair remembered)
	   (if (sma-node-pending n)
	       (setf pair (pop (sma-node-pending n)))
	     (let ((best (first (sma-node-forgotten n))))
	       (dolist (entry (rest (sma-node-forgotten n)))
		 (when (< (cdr entry) (cdr best)) (setf best entry)))
	       (setf pair (car best)
		     remembered (cdr best)
		     (sma-node-forgotten n)
		     (remove best (sma-node-forgotten n) :test #'eq))))
	   (let ((s (sma*-make-node problem (sma*-child n pair problem)
				    (node-f-cost n) remembered memory
				    (incf clock))))
	     (push s (sma-node-children n))
	     (push s tree)
	     (sma*-backup n))))))))

(defun sma*-child (node pair problem)
  "The node reached from NODE by the (action . state) PAIR."
  (incf (problem-num-expanded problem))
  (let ((action (car pair))
	(state (cdr pair)))
    (make-node :state state :parent node :action action
	       :depth (1+ (node-depth node))
	       :g-cost (+ (node-g-cost node)
			  (edge-cost problem node action state)))))

(defun sma*-make-node (problem node parent-f remembered memory time)
  "Turn NODE into an SMA* node and give it its f-cost."
  (let* ((state (node-state node))
	 (n (make-sma-node :state state :parent (node-parent node)
			   :action (node-action node) :depth (node-depth node)
			   :g-cost (node-g-cost node)
			   :h-cost (h-cost problem state)
			   :pending (successors problem state)
			   :time time))
	 (g+h (+ (node-g-cost n) (node-h-cost n))))
    (setf (node-f-cost n)
	  (cond ((goal-test problem state) (max parent-f g+h))
		((or (>= (node-depth n) (- memory 1)) (null (sma-node-pending n)))
		 infinity)  ; it cannot lead to a solution that fits in memory
		(t (max parent-f g+h (or remembered 0)))))
    n))

(defun sma*-complete? (node)
  "Are all the successors of NODE in memory?"
  (and (null (sma-node-pending node)) (null (sma-node-forgotten node))))

(defun sma*-priority (problem node)
  "The f-cost of the next successor that NODE would generate."
  (if (or (sma-node-pending node) (goal-test problem (node-state node)))
      (node-f-cost node)
    (reduce #'min (sma-node-forgotten node) :key #'cdr)))

(defun sma*-backup (node)
  "Once all its successors have been generated, a node is worth the best
  of them; propagate the change up to the root."
  (loop while (and node (null (sma-node-pending node))) do
	(let ((f (reduce #'min
			 (append (mapcar #'node-f-cost (sma-node-children node))
				 (mapcar #'cdr (sma-node-forgotten node)))
			 :initial-value infinity)))
	  (when (= f (node-f-cost node)) (return))
	  (setf (node-f-cost node) f
		node (node-parent node)))))
