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

;;;; Dynamic Bayesian Networks and Their Unrolling

;;; A dynamic Bayesian network [Section 14.5] is given by the PRIOR, the
;;; specifications of the variables of slice 0, and the TRANSITION, those of
;;; the variables of a slice t > 0.  Both are lists of (variable parents
;;; cpt) specifications in the format of BAYES-NET (see bayes-nets.lisp),
;;; in topological order; in the transition, a parent written (prev X) is
;;; the variable X of slice t-1, and a plain X is that of slice t.  The
;;; variable X of slice t is named X_t, e.g. RAIN_2.

(defstruct dynamic-bayes-net
  (prior nil)
  (transition nil))

(defun dbn-slice-variable (variable time)
  "The name of VARIABLE in slice TIME."
  (intern (format nil "~A_~D" variable time)))

(defun dbn-unroll (dbn k)
  "Unroll DBN for slices 0 to K into an ordinary Bayes net, on which any
  exact or approximate inference algorithm can be run. [Section 14.5.2]"
  (bayes-net
   (append
    (mapcar #'(lambda (spec)
		(destructuring-bind (variable parents cpt &rest values) spec
		  (list* (dbn-slice-variable variable 0)
			 (mapcar #'(lambda (p) (dbn-slice-variable p 0)) parents)
			 cpt values)))
	    (dynamic-bayes-net-prior dbn))
    (loop for time from 1 to k
	  append (mapcar
		  #'(lambda (spec)
		      (destructuring-bind (variable parents cpt &rest values) spec
			(list* (dbn-slice-variable variable time)
			       (mapcar #'(lambda (p)
					   (if (consp p)
					       (dbn-slice-variable (second p)
								   (- time 1))
					     (dbn-slice-variable p time)))
				       parents)
			       cpt values)))
		  (dynamic-bayes-net-transition dbn))))))

(defparameter *umbrella-dbn*
  (make-dynamic-bayes-net
   :prior '((rain () 0.5))
   :transition '((rain ((prev rain)) (((t) . 0.7) ((nil) . 0.3)))
		 (umbrella (rain) (((t) . 0.9) ((nil) . 0.2)))))
  "The umbrella world of Figure 14.2 as a DBN.")
