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

;;;; Bidirectional Best-First Search

;;; BIBF-SEARCH keeps two frontiers, one searching forward from the initial
;;; state of PROBLEM-F and one searching backward from the initial state of
;;; PROBLEM-B (the goal of the forward problem, with the actions reversed).
;;; Whenever a state is reached in both directions, the two paths are joined
;;; into a candidate solution, and the best one is kept until no cheaper
;;; solution can be found.

(defun bibf-search (problem-f f-f problem-b f-b
		    &key (reverse-action #'bibf-default-reverse-action))
  "Bidirectional best-first search, expanding at each step the frontier
  whose best node has the lower value of its evaluation function (F-F
  forward, F-B backward).  Return a solution node of the forward problem,
  or nil. [Fig. 3.14]  The steps of the backward half are turned around
  with REVERSE-ACTION, a function of a backward node that returns the
  action leading from its state to its parent's state; by default it is
  the parent's state, as in route finding."
  (let ((node-f (create-start-node problem-f))
	(node-b (create-start-node problem-b))
	(frontier-f (make-empty-queue))
	(frontier-b (make-empty-queue))
	(reached-f (make-hash-table :test #'equal))
	(reached-b (make-hash-table :test #'equal))
	(solution nil))
    (when (equal (node-state node-f) (node-state node-b))
      (return-from bibf-search node-f))
    (enqueue-by-priority frontier-f (list node-f) f-f)
    (enqueue-by-priority frontier-b (list node-b) f-b)
    (setf (gethash (node-state node-f) reached-f) node-f
	  (gethash (node-state node-b) reached-b) node-b)
    (loop
     (when (bibf-terminated? solution frontier-f f-f frontier-b f-b)
       (return solution))
     (if (< (funcall f-f (queue-front frontier-f))
	    (funcall f-b (queue-front frontier-b)))
	 (setf solution (bibf-proceed :forward problem-f frontier-f f-f
				      reached-f reached-b solution
				      reverse-action))
       (setf solution (bibf-proceed :backward problem-b frontier-b f-b
				    reached-b reached-f solution
				    reverse-action))))))

(defun bibf-proceed (dir problem frontier f reached reached2 solution
		     reverse-action)
  "Expand the best node of FRONTIER in direction DIR; return the best
  solution found so far."
  (let ((node (remove-front frontier)))
    (dolist (child (expand node problem) solution)
      (let* ((s (node-state child))
	     (old (gethash s reached)))
	(when (or (null old) (< (node-g-cost child) (node-g-cost old)))
	  (setf (gethash s reached) child)
	  (enqueue-by-priority frontier (list child) f)
	  (let ((other (gethash s reached2)))
	    (when other
	      (let ((solution2 (if (eq dir :forward)
				   (bibf-join-nodes child other reverse-action)
				 (bibf-join-nodes other child reverse-action))))
		(when (or (null solution)
			  (< (node-g-cost solution2) (node-g-cost solution)))
		  (setf solution solution2))))))))))

(defun bibf-terminated? (solution frontier-f f-f frontier-b f-b)
  "Stop when a frontier is empty, or when no node left on either frontier
  can lead to a solution cheaper than SOLUTION (with admissible F-F and F-B,
  every solution not yet found costs at least the larger of the two best
  frontier values)."
  (or (empty-queue? frontier-f)
      (empty-queue? frontier-b)
      (and solution
	   (<= (node-g-cost solution)
	       (max (funcall f-f (queue-front frontier-f))
		    (funcall f-b (queue-front frontier-b)))))))

(defun bibf-join-nodes (forward backward reverse-action)
  "Extend the forward path ending in FORWARD with the backward path from
  BACKWARD (which has the same state) to the goal."
  (let ((node forward)
	(b backward))
    (loop while (node-parent b) do
	  (let ((parent (node-parent b)))
	    (setf node (make-node
			:state (node-state parent)
			:parent node
			:action (funcall reverse-action b)
			:depth (1+ (node-depth node))
			:g-cost (+ (node-g-cost node)
				   (- (node-g-cost b) (node-g-cost parent))))
		  b parent)))
    node))

(defun bibf-default-reverse-action (backward-node)
  "The action that goes from the node's state to its parent's state, when
  actions are named by the state they reach (as in route finding)."
  (node-state (node-parent backward-node)))

;;;; Bidirectional search on reversible problems

(defun reverse-problem (problem)
  "A copy of PROBLEM that searches from its goal back to its initial state.
  This is the backward problem only when the actions can be reversed with
  the same costs, as on the road maps of route finding."
  (let ((backward (copy-structure problem)))
    (setf (problem-initial-state backward) (problem-goal problem)
	  (problem-goal backward) (problem-initial-state problem)
	  (problem-num-expanded backward) 0)
    backward))

(defun bidirectional-search (problem)
  "Bidirectional uniform-cost search: BIBF-SEARCH with f = g in both
  directions, on PROBLEM and its reverse."
  (let* ((backward (reverse-problem problem))
	 (solution (bibf-search problem #'node-g-cost
				backward #'node-g-cost)))
    (incf (problem-num-expanded problem) (problem-num-expanded backward))
    solution))

(defun bidirectional-a*-search (problem)
  "Bidirectional A* search: BIBF-SEARCH with f = g + h in both directions;
  the backward heuristic estimates the distance to the initial state."
  (let* ((backward (reverse-problem problem))
	 (solution (bibf-search problem #'node-f-cost
				backward #'node-f-cost)))
    (incf (problem-num-expanded problem) (problem-num-expanded backward))
    solution))
