;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: uncertainty/algorithms/pomdp.lisp

;;;; Partially Observable MDPs: Value Iteration over Conditional Plans

;;; A POMDP has a list of states, actions and percepts, and models given as
;;; functions: (TRANSITION s a s2) is P(s2 | s, a), (SENSOR e s) is
;;; P(e | s), and (REWARD s) is R(s).  A belief state is a list of
;;; probabilities, one for each state, in the order of STATES.
;;; A conditional plan is NIL (the empty plan) or a list
;;; (action (percept . plan) ...); a utility function is a list of plans
;;; with their utility vectors alpha, as (alpha . plan) pairs.

(defstruct pomdp
  states actions percepts
  transition sensor reward
  (gamma 0.9))

(defun pomdp-update-belief (pomdp b action percept)
  "The belief state after ACTION and PERCEPT (Equation 17.11):
  b'(s2) = alpha P(e | s2) sum_s P(s2 | s, a) b(s)."
  (let ((states (pomdp-states pomdp)))
    (normalize-vector
     (mapcar #'(lambda (s2)
                 (* (funcall (pomdp-sensor pomdp) percept s2)
                    (sum (mapcar #'(lambda (s p)
                                     (* p (funcall (pomdp-transition pomdp) s action s2)))
                                 states b))))
             states))))

(defun plan-utility (alpha b)
  "The expected utility alpha . b of a plan in belief state B."
  (dot-product alpha b))

(defun utility-of-belief (U b)
  "The utility of belief state B: the best expected utility of the plans in U."
  (reduce #'max (mapcar #'(lambda (plan) (plan-utility (car plan) b)) U)))

(defun cartesian-product (lists)
  "All the lists made of one element of each of LISTS."
  (if (null lists)
      (list nil)
    (let ((rest (cartesian-product (rest lists))))
      (mapcan #'(lambda (x) (mapcar #'(lambda (r) (cons x r)) rest))
              (first lists)))))

(defun pomdp-plans-backup (pomdp U)
  "The set of all plans that start with an action and continue, for each
  possible percept, with a plan of U; the utility vector of a plan p with
  action a and subplans p_e is
  alpha_p(s) = R(s) + gamma sum_s2 P(s2 | s, a) sum_e P(e | s2) alpha_p_e(s2)."
  (let ((states (pomdp-states pomdp))
        (percepts (pomdp-percepts pomdp))
        (gamma (pomdp-gamma pomdp))
        (plans nil))
    (dolist (a (pomdp-actions pomdp) (nreverse plans))
      (dolist (choice (cartesian-product (mapcar #'(lambda (e) (declare (ignore e)) U)
                                                 percepts)))
        (push (cons (mapcar
                     #'(lambda (s)
                         (+ (funcall (pomdp-reward pomdp) s)
                            (* gamma
                               (sum (loop for s2 in states for i from 0
                                          collect
                                          (* (funcall (pomdp-transition pomdp) s a s2)
                                             (sum (loop for e in percepts
                                                        for plan in choice
                                                        collect
                                                        (* (funcall (pomdp-sensor pomdp) e s2)
                                                           (nth i (car plan)))))))))))
                     states)
                    (cons a (mapcar #'(lambda (e plan) (cons e (cdr plan)))
                                    percepts choice)))
              plans)))))

(defun belief-grid (n k)
  "All the belief states over N states whose probabilities are multiples of 1/K."
  (if (= n 1)
      (list (list 1))
    (loop for i from 0 to k
          nconc (mapcar #'(lambda (rest)
                            (cons (/ i k) (mapcar #'(lambda (p) (* p (/ (- k i) k))) rest)))
                        (if (= i k)
                            (list (make-list (- n 1) :initial-element 0))
                          (belief-grid (- n 1) (- k i)))))))

(defun remove-dominated-plans (U points)
  "Keep only the plans of U that are the best at some of the belief states
  in POINTS.  (The book uses linear programs to find the plans that are the
  best somewhere in the whole belief space; a fine grid of points is used
  here instead.)"
  (remove-duplicates
   (mapcar #'(lambda (b) (the-biggest #'(lambda (plan) (plan-utility (car plan) b)) U))
           points)
   :test #'eq))

(defun max-difference (U1 U2 points)
  "The largest difference between the utilities of U1 and U2 over POINTS."
  (reduce #'max (mapcar #'(lambda (b) (abs (- (utility-of-belief U1 b)
                                              (utility-of-belief U2 b))))
                        points)))

(defun pomdp-value-iteration (pomdp epsilon &key (grid-size 20) (max-iterations 1000))
  "Value iteration for POMDPs [Figure 17.16]: a utility function, as a set
  of conditional plans with their utility vectors, within EPSILON of the
  optimal one on the belief states of a grid with GRID-SIZE divisions."
  (let* ((points (belief-grid (length (pomdp-states pomdp)) grid-size))
         (gamma (pomdp-gamma pomdp))
         (U nil)
         (U2 (list (cons (mapcar (pomdp-reward pomdp) (pomdp-states pomdp)) nil))))
    (loop repeat max-iterations
          do (setf U U2
                   U2 (remove-dominated-plans (pomdp-plans-backup pomdp U) points))
          until (<= (max-difference U U2 points) (/ (* epsilon (- 1 gamma)) gamma)))
    U))

(defun pomdp-bellman-backup (pomdp U b)
  "The utility of belief state B after one step of lookahead from the
  utility function U, computed by updating the belief state."
  (let ((states (pomdp-states pomdp)))
    (+ (sum (mapcar #'(lambda (s p) (* p (funcall (pomdp-reward pomdp) s))) states b))
       (* (pomdp-gamma pomdp)
          (reduce #'max
                  (mapcar
                   #'(lambda (a)
                       (sum (mapcar
                             #'(lambda (e)
                                 (let ((p-e (sum (mapcar
                                                  #'(lambda (s p)
                                                      (* p (sum (mapcar
                                                                 #'(lambda (s2)
                                                                     (* (funcall (pomdp-transition pomdp) s a s2)
                                                                        (funcall (pomdp-sensor pomdp) e s2)))
                                                                 states))))
                                                  states b))))
                                   (if (zerop p-e)
                                       0
                                     (* p-e (utility-of-belief
                                             U (pomdp-update-belief pomdp b a e))))))
                             (pomdp-percepts pomdp))))
                   (pomdp-actions pomdp)))))))

;;;; Online Decisions with a Dynamic Decision Network [Section 17.4.3]

;;; A POMDP is a dynamic decision network: the agent projects it DEPTH
;;; steps into the future, and solves the projection by expectimax search
;;; over belief states, in which the decision nodes choose an action and
;;; the chance nodes branch over the percepts, with the belief state
;;; updated by filtering along each branch.

(defun pomdp-percept-probability (pomdp b action e)
  "P(e | b, action), the probability of the next percept E."
  (let ((states (pomdp-states pomdp)))
    (sum (mapcar #'(lambda (s2)
                     (* (funcall (pomdp-sensor pomdp) e s2)
                        (sum (mapcar #'(lambda (s p)
                                         (* p (funcall (pomdp-transition pomdp)
                                                       s action s2)))
                                     states b))))
                 states))))

(defun ddn-q-value (pomdp b action depth)
  "The expected discounted reward of doing ACTION in belief state B and then
  acting optimally for DEPTH - 1 more steps."
  (+ (sum (mapcar #'(lambda (s p) (* p (funcall (pomdp-reward pomdp) s)))
                  (pomdp-states pomdp) b))
     (* (pomdp-gamma pomdp)
        (sum (mapcar #'(lambda (e)
                         (let ((p-e (pomdp-percept-probability pomdp b action e)))
                           (if (zerop p-e)
                               0
                             (* p-e (ddn-utility
                                     pomdp (pomdp-update-belief pomdp b action e)
                                     (- depth 1))))))
                     (pomdp-percepts pomdp))))))

(defun ddn-utility (pomdp b depth)
  "The expectimax value of belief state B with DEPTH steps to go."
  (if (<= depth 0)
      0
    (reduce #'max (mapcar #'(lambda (a) (ddn-q-value pomdp b a depth))
                          (pomdp-actions pomdp)))))

(defun ddn-lookahead (pomdp b depth)
  "The best action in belief state B by a DEPTH-step lookahead in the
  dynamic decision network of the POMDP, and its value."
  (let ((best (the-biggest #'(lambda (a) (ddn-q-value pomdp b a depth))
                           (pomdp-actions pomdp))))
    (values best (ddn-q-value pomdp b best depth))))
