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

;;;; Monte Carlo Tree Search

;;; This works on the games of search/environments/games.lisp.  The
;;; utility of a terminal state for a player is its score there (+1 for a
;;; win, -1 for a loss and 0 for a draw in tic-tac-toe), mapped to [0, 1].
;;; Each node of the search tree records the total utility U, for the
;;; player who made the move leading to it, of the playouts through it,
;;; and their number N.

(defstructure mcts-node
  state                 ; a game state
  (parent nil)
  (move nil)            ; the move that led here from the parent
  (children nil)        ; the child nodes generated so far
  (untried nil)         ; legal moves not yet expanded
  (u 0)                 ; total utility of the playouts through this node
  (n 0))                ; number of playouts through this node

(defun monte-carlo-tree-search (state game &optional (iterations 1000)
				      (c (sqrt 2)))
  "Choose a move by running ITERATIONS playouts, each one selecting a leaf
  by UCB1 with exploration constant C, expanding it, simulating a random
  game from it and backing the result up the tree; return the move of the
  most visited child of the root. [Fig. 5.11]"
  (let ((root (mcts-make-node state nil nil game)))
    (dotimes (i iterations)
      (let* ((leaf (mcts-select root c))
	     (child (mcts-expand leaf game))
	     (final (mcts-simulate (mcts-node-state child) game)))
	(mcts-back-propagate child final)))
    (mcts-node-move (the-biggest #'mcts-node-n (mcts-node-children root)))))

(defun mcts-make-node (state parent move game)
  (make-mcts-node :state state :parent parent :move move
		  :untried (if (game-over? game state)
			       nil
			     (legal-moves game state))))

(defun mcts-select (node c)
  "Follow the child with the highest UCB1 value down to a node that still
  has untried moves, or has no children."
  (loop while (and (null (mcts-node-untried node)) (mcts-node-children node))
	do (setf node (the-biggest #'(lambda (child) (mcts-ucb1 child c))
				   (mcts-node-children node))))
  node)

(defun mcts-ucb1 (node c)
  (+ (/ (mcts-node-u node) (mcts-node-n node))
     (* c (sqrt (/ (log (mcts-node-n (mcts-node-parent node)))
		   (mcts-node-n node))))))

(defun mcts-expand (node game)
  "Add a child for one untried move of NODE, if any; return it, or NODE."
  (if (null (mcts-node-untried node))
      node
    (let* ((move (pop (mcts-node-untried node)))
	   (child (mcts-make-node (make-move game (mcts-node-state node) move)
				  node move game)))
      (push child (mcts-node-children node))
      child)))

(defun mcts-simulate (state game)
  "Play random moves from STATE to the end; return the final state."
  (loop until (game-over? game state)
	do (setf state (make-move game state
				  (random-element (legal-moves game state)))))
  state)

(defun mcts-back-propagate (node final)
  "Add the utility of the FINAL state to the nodes from NODE up to the root."
  (loop while node do
	(incf (mcts-node-n node))
	(when (mcts-node-parent node)
	  ;; The player who moved into this node is now last in the order.
	  (let ((mover (previous-player (mcts-node-state node))))
	    (incf (mcts-node-u node) (mcts-utility final mover))))
	(setf node (mcts-node-parent node))))

(defun mcts-utility (state player)
  "The score of PLAYER in the terminal STATE, mapped from [-1, +1] to [0, 1]."
  (/ (+ 1 (getf (game-state-scores state) player 0)) 2))
