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

;;;; Expectiminimax for Games with Chance Nodes

;;; A stochastic game tree is given explicitly as an alist from each
;;; non-terminal node to its description:
;;;   (node MAX (action . child) ...)   MAX chooses an action
;;;   (node MIN (action . child) ...)   MIN chooses an action
;;;   (node CHANCE (probability . child) ...)   chance picks a child
;;; A node that is not in the alist is terminal; it is either a number, its
;;; utility for MAX, or a name found in the UTILITIES alist.

(defstructure chance-game-tree
  "An explicit game tree with MAX, MIN and CHANCE nodes."
  (root nil)
  (nodes nil)      ; alist from node to (type . branches)
  (utilities nil)) ; alist from terminal node name to utility

(defun expectiminimax-value (tree node)
  "The expectiminimax value of NODE: the utility of a terminal node, the
  maximum or minimum over the children of a MAX or MIN node, and the
  probability-weighted average over the children of a CHANCE node.
  [Section 5.5]"
  (let ((entry (cdr (assoc node (chance-game-tree-nodes tree) :test #'equal))))
    (if (null entry)
	(if (numberp node)
	    node
	  (cdr (assoc node (chance-game-tree-utilities tree) :test #'equal)))
      (let ((branches (rest entry)))
	(ecase (first entry)
	  (max (reduce #'max branches
		       :key #'(lambda (b) (expectiminimax-value tree (cdr b)))))
	  (min (reduce #'min branches
		       :key #'(lambda (b) (expectiminimax-value tree (cdr b)))))
	  (chance (reduce #'+ branches
			  :key #'(lambda (b)
				   (* (car b)
				      (expectiminimax-value tree (cdr b)))))))))))

(defun expectiminimax-decision (tree &optional
				     (node (chance-game-tree-root tree)))
  "Return the action of the MAX node NODE with the highest expectiminimax
  value."
  (let ((branches (rest (cdr (assoc node (chance-game-tree-nodes tree)
				    :test #'equal)))))
    (car (the-biggest #'(lambda (b) (expectiminimax-value tree (cdr b)))
		      branches))))

(defun make-small-chance-game-tree
    (&optional (leaves '(2 3 1 4 20 30 1 400)))
  "A small tree in the style of [Fig. 5.13]: MAX chooses a1 or a2, each
  followed by a chance node with probabilities 0.9 and 0.1 of reaching a
  MIN node over two leaves, given in order by LEAVES."
  (destructuring-bind (l1 l2 l3 l4 l5 l6 l7 l8) leaves
    (make-chance-game-tree
     :root 'a
     :nodes `((a max (a1 . c1) (a2 . c2))
	      (c1 chance (0.9 . b1) (0.1 . b2))
	      (c2 chance (0.9 . b3) (0.1 . b4))
	      (b1 min (b11 . ,l1) (b12 . ,l2))
	      (b2 min (b21 . ,l3) (b22 . ,l4))
	      (b3 min (b31 . ,l5) (b32 . ,l6))
	      (b4 min (b41 . ,l7) (b42 . ,l8))))))
