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

;;;; Local Beam Search

;;; Like the iterative improvement algorithms in iterative.lisp, this
;;; minimizes the heuristic cost h, and returns two values: a solution node
;;; or nil, and the best node found.

(defun local-beam-search (problem &key (k 4) (new-state-fn nil)
				  (iterations 1000))
  "Keep K states; at each step generate all the successors of all of them
  and keep the K best, stopping when none improves on the current best.
  The K initial states come from NEW-STATE-FN, a function of no arguments,
  or are all the initial state of PROBLEM. [Section 4.1.3]"
  (let ((current
	 (loop repeat k
	       collect (if new-state-fn
			   (let ((state (funcall new-state-fn)))
			     (make-node :state state
					:h-cost (h-cost problem state)))
			 (create-start-node problem)))))
    (loop repeat iterations do
	  (let ((neighbors (mapcan #'(lambda (node) (expand node problem))
				   current)))
	    (when (null neighbors) (return))
	    (let ((best (subseq (sort neighbors #'< :key #'node-h-cost)
				0 (min k (length neighbors)))))
	      (when (>= (node-h-cost (first best))
			(reduce #'min current :key #'node-h-cost))
		(return))
	      (setf current best))))
    (let ((best (the-smallest #'node-h-cost current)))
      (values (if (goal-test problem (node-state best)) best nil)
	      best))))
