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

;;;; Probabilistic Reasoning over Time (Chapter 14)

;;; A hidden Markov model has states 0 .. S-1.  The transition model is an
;;; S x S matrix T, with T[i][j] = P(X_t = j | X_t-1 = i); the sensor model
;;; is an alist that maps each evidence value e to the vector of the
;;; P(e | X_t = i); the prior is the vector P(X_0).  Messages (forward,
;;; backward, smoothed) are vectors of length S.

(defstruct hmm
  transition
  sensor
  prior)

(defun hmm-sensor-vector (hmm e)
  "The vector of the P(e | X = i)."
  (cdr (assoc e (hmm-sensor hmm) :test #'equal)))

(defun hmm-predict (hmm f)
  "The one-step prediction of the state distribution F: sum_i f_i T[i][j]."
  (matrix-vector-multiply (transpose (hmm-transition hmm)) f))

(defun hmm-forward (hmm f e)
  "The forward message after evidence E, given the previous message F."
  (normalize-vector (mapcar #'* (hmm-sensor-vector hmm e) (hmm-predict hmm f))))

(defun hmm-backward (hmm b e)
  "The backward message for one more step of evidence E."
  (matrix-vector-multiply (hmm-transition hmm)
                          (mapcar #'* (hmm-sensor-vector hmm e) b)))

(defun hmm-filter (hmm ev)
  "The filtered distribution P(X_t | e_1:t) for the evidence list EV."
  (let ((f (hmm-prior hmm)))
    (dolist (e ev f)
      (setf f (hmm-forward hmm f e)))))

;;;; Smoothing [Figure 14.4]

(defun forward-backward (hmm ev)
  "The list of the smoothed distributions P(X_k | e_1:t), for k = 1 .. t,
  given the evidence list EV = (e_1 ... e_t)."
  (let ((fv (list (hmm-prior hmm)))   ; forward messages, latest first
        (b (make-list (length (hmm-prior hmm)) :initial-element 1))
        (sv nil))
    (dolist (e ev)
      (push (hmm-forward hmm (first fv) e) fv))
    ;; now fv = (f_t ... f_1 f_0); go back from t to 1
    (dolist (e (reverse ev) sv)
      (push (normalize-vector (mapcar #'* (pop fv) b)) sv)
      (setf b (hmm-backward hmm b e)))))

(defun make-fixed-lag-smoother (hmm d)
  "Return a function that takes the evidence e_t of each new time step and
  returns the smoothed distribution P(X_t-d | e_1:t), or NIL while t <= d
  [Figure 14.6].  The d-step backward transformation B is updated
  incrementally with the inverses of the transition and sensor matrices."
  (let* ((n (length (hmm-prior hmm)))
         (tt (hmm-transition hmm))
         (tt-inverse (matrix-inverse tt))
         (time 1)
         (f (hmm-prior hmm))
         (b (identity-matrix n))
         (evidence nil))                 ; e_t-d .. e_t, oldest first
    #'(lambda (e)
        (setf evidence (append evidence (list e)))
        (let ((o-t (diagonal-matrix (hmm-sensor-vector hmm e))))
          (if (> time d)
              (let* ((e-old (pop evidence))
                     (o-old-inverse
                      (diagonal-matrix
                       (mapcar #'(lambda (p) (/ 1 p))
                               (hmm-sensor-vector hmm e-old)))))
                (setf f (hmm-forward hmm f e-old))
                (setf b (matrix-multiply
                         (matrix-multiply o-old-inverse tt-inverse)
                         (matrix-multiply b (matrix-multiply tt o-t)))))
            (setf b (matrix-multiply b (matrix-multiply tt o-t)))))
        (incf time)
        (when (> time (+ d 1))
          (normalize-vector
           (mapcar #'* f (matrix-vector-multiply
                          b (make-list n :initial-element 1))))))))

;;;; The Most Likely Sequence

(defun hmm-viterbi (hmm ev)
  "The most likely sequence of states for the evidence list EV, by the
  Viterbi algorithm (Section 14.2.3).  The second value is the list of
  the probabilities of the most likely path that ends at each step (the
  first one normalized, as in the forward message)."
  (let* ((n (length (hmm-prior hmm)))
         (tt (hmm-transition hmm))
         (m (hmm-forward hmm (hmm-prior hmm) (first ev)))
         (ms (list m))
         (backpointers nil))
    (dolist (e (rest ev))
      (let ((best-previous
              (loop for j below n
                    collect (the-biggest #'(lambda (i) (* (nth i m) (nth j (nth i tt))))
                                         (iota n)))))
        (push best-previous backpointers)
        (setf m (loop for j below n
                      for i in best-previous
                      collect (* (nth j (hmm-sensor-vector hmm e))
                                 (nth i m) (nth j (nth i tt)))))
        (push m ms)))
    ;; follow the back pointers from the most likely final state
    (let ((path (list (the-biggest #'(lambda (i) (nth i m)) (iota n)))))
      (dolist (pointers backpointers)
        (push (nth (first path) pointers) path))
      (values path (reverse (mapcar #'(lambda (v) (reduce #'max v)) ms))))))

;;;; Particle Filtering [Figure 14.17]

(defun hmm-sample-transition (hmm i)
  "Sample the next state from state I."
  (sample-categorical (mapcar #'cons (iota (length (hmm-prior hmm)))
                              (nth i (hmm-transition hmm)))))

(defun particle-filtering (e N hmm &optional samples)
  "Advance the N samples (states) of the model by one step with evidence E,
  weight them by the likelihood of E and resample them.  With no SAMPLES,
  they are first drawn from the prior."
  (let* ((states (iota (length (hmm-prior hmm))))
         (samples (or samples
                      (loop repeat N
                            collect (sample-categorical
                                     (mapcar #'cons states (hmm-prior hmm))))))
         (moved (mapcar #'(lambda (s) (hmm-sample-transition hmm s)) samples))
         (weights (mapcar #'(lambda (s) (nth s (hmm-sensor-vector hmm e))) moved)))
    (weighted-sample-with-replacement N moved weights)))

;;;; The Kalman Filter (Section 14.4)

;;; A linear-Gaussian model: X_t+1 = F X_t + noise of covariance SIGMA-X,
;;; and Z_t = H X_t + noise of covariance SIGMA-Z.

(defstruct kalman-model
  transition                  ; F
  sensor                      ; H
  transition-noise            ; Sigma_x
  sensor-noise)               ; Sigma_z

(defun kalman-update (model mean cov z)
  "One prediction and update step: the new mean and covariance, given the
  observation Z (a vector, or a number for a one-dimensional sensor)."
  (let* ((f (kalman-model-transition model))
         (h (kalman-model-sensor model))
         (z (if (numberp z) (list z) z))
         (mean-p (matrix-vector-multiply f mean))
         (cov-p (matrix-add (matrix-multiply f (matrix-multiply cov (transpose f)))
                            (kalman-model-transition-noise model)))
         (gain (matrix-multiply
                (matrix-multiply cov-p (transpose h))
                (matrix-inverse
                 (matrix-add (matrix-multiply h (matrix-multiply cov-p (transpose h)))
                             (kalman-model-sensor-noise model)))))
         (innovation (mapcar #'- z (matrix-vector-multiply h mean-p))))
    (values (mapcar #'+ mean-p (matrix-vector-multiply gain innovation))
            (matrix-multiply (matrix-subtract (identity-matrix (length mean))
                                              (matrix-multiply gain h))
                             cov-p))))

(defun kalman-filter (model mean cov observations)
  "Filter the list of OBSERVATIONS from the prior N(MEAN, COV); return the
  list of the (mean . covariance) estimates after each observation."
  (loop for z in observations
        collect (multiple-value-bind (m c) (kalman-update model mean cov z)
                  (setf mean m cov c)
                  (cons m c))))
