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

;;;; Bayesian Networks: Exact and Approximate Inference (Chapter 13)

;;; A Bayesian network is a list of nodes in topological order (parents
;;; before children).  A variable is Boolean, with values T and NIL, unless
;;; its node lists other VALUES.  The conditional probability table (CPT)
;;; of a node is an alist that maps the list of the values of its parents
;;; to P(variable = T | parents) for a Boolean variable, or to the
;;; distribution of the variable, an alist ((value . p) ...), otherwise.
;;; Enumeration works on every network; variable elimination and the
;;; sampling algorithms on Boolean networks only.
;;; An event (an assignment of values to some variables) is an alist of
;;; (variable . value) pairs.  A distribution is returned as the alist
;;; ((T . p) (NIL . 1-p)).

(defstruct (bn-node (:type list))
  variable parents cpt (values '(t nil)))

(defstruct bayes-net
  (nodes nil))            ; in topological order

(defun bayes-net (specs)
  "Build a Bayes net from a list of (variable parents cpt [values])
  specifications, given in topological order.  The CPT of a node without
  parents may be just the number P(variable = T), or its distribution."
  (make-bayes-net
   :nodes (mapcar #'(lambda (spec)
                      (destructuring-bind (variable parents cpt
                                           &optional (values '(t nil)))
                          spec
                        (make-bn-node :variable variable :parents parents
                                      :values values
                                      :cpt (if (and (null parents)
                                                    (or (numberp cpt)
                                                        (not (consp (caar cpt)))))
                                               (list (cons nil cpt))
                                             cpt))))
                  specs)))

(defun bn-variables (bn)
  "The variables of the network, in topological order."
  (mapcar #'bn-node-variable (bayes-net-nodes bn)))

(defun bn-variable-node (variable bn)
  (find variable (bayes-net-nodes bn) :key #'bn-node-variable))

(defun bn-children (variable bn)
  "The nodes that have VARIABLE among their parents."
  (remove-if-not #'(lambda (node) (member variable (bn-node-parents node)))
                 (bayes-net-nodes bn)))

(defun event-value (variable event)
  "The value of VARIABLE in EVENT (an alist)."
  (cdr (assoc variable event)))

(defun event-assigns? (variable event)
  "Does EVENT give a value to VARIABLE?"
  (assoc variable event))

(defun extend-event (event variable value)
  "A copy of EVENT with VARIABLE set to VALUE."
  (cons (cons variable value) (remove variable event :key #'car)))

(defun bn-probability (node value event)
  "P(variable = VALUE | parents), with the parents' values taken from EVENT."
  (let ((p (cdr (assoc (mapcar #'(lambda (parent) (event-value parent event))
                               (bn-node-parents node))
                       (bn-node-cpt node) :test #'equal))))
    (cond ((consp p) (probability-of value p))
          (value p)
          (t (- 1 p)))))

(defun bn-relevant-nodes (variables bn)
  "The nodes of VARIABLES and of their ancestors, in topological order;
  the other variables are irrelevant to a query on VARIABLES."
  (let ((relevant (copy-list variables)))
    (dolist (node (reverse (bayes-net-nodes bn)))
      (when (member (bn-node-variable node) relevant)
        (setf relevant (union (bn-node-parents node) relevant))))
    (remove-if-not #'(lambda (node) (member (bn-node-variable node) relevant))
                   (bayes-net-nodes bn))))

(defun boolean-distribution (p-true p-false)
  "Normalize the two numbers into the distribution ((T . p) (NIL . 1-p))."
  (normalize-distribution (list (cons t p-true) (cons nil p-false))))

;;;; Exact Inference by Enumeration [Figure 13.11]

(defun enumeration-ask (query e bn)
  "The distribution of the QUERY variable given the evidence event E.
  Only the ancestors of the query and evidence variables are enumerated."
  (let ((nodes (bn-relevant-nodes (cons query (mapcar #'car e)) bn)))
    (normalize-distribution
     (mapcar #'(lambda (value)
                 (cons value (enumerate-all nodes (extend-event e query value))))
             (bn-node-values (bn-variable-node query bn))))))

(defun enumerate-all (nodes e)
  "Sum the product of the CPT entries of NODES over their unassigned
  variables, with the other variables fixed by the event E."
  (if (null nodes)
      1
    (let* ((node (first nodes))
           (Y (bn-node-variable node)))
      (if (event-assigns? Y e)
          (* (bn-probability node (event-value Y e) e)
             (enumerate-all (rest nodes) e))
        (reduce #'+ (mapcar #'(lambda (value)
                                (* (bn-probability node value e)
                                   (enumerate-all (rest nodes)
                                                  (extend-event e Y value))))
                            (bn-node-values node)))))))

;;;; Exact Inference by Variable Elimination [Figure 13.13]

;;; A factor has a list of variables and a table, an alist that maps each
;;; list of values of those variables to a number.

(defstruct factor variables table)

(defun all-assignments (variables)
  "All the lists of Boolean values for VARIABLES."
  (if (null variables)
      (list nil)
    (let ((rest (all-assignments (rest variables))))
      (append (mapcar #'(lambda (values) (cons t values)) rest)
              (mapcar #'(lambda (values) (cons nil values)) rest)))))

(defun factor-value (factor event)
  "The entry of FACTOR for the values that EVENT gives to its variables."
  (cdr (assoc (mapcar #'(lambda (v) (event-value v event))
                      (factor-variables factor))
              (factor-table factor) :test #'equal)))

(defun make-factor-from-table (variables fn)
  "The factor on VARIABLES whose entry for an event is (FN event)."
  (make-factor
   :variables variables
   :table (mapcar #'(lambda (values)
                      (cons values (funcall fn (mapcar #'cons variables values))))
                  (all-assignments variables))))

(defun make-bn-factor (node e)
  "The factor for the CPT of NODE, restricted by the evidence E: its
  variables are those of the node and its parents that E leaves free."
  (let ((variables (remove-if #'(lambda (v) (event-assigns? v e))
                              (cons (bn-node-variable node)
                                    (bn-node-parents node)))))
    (make-factor-from-table
     variables
     #'(lambda (event)
         (let ((full (append event e)))
           (bn-probability node (event-value (bn-node-variable node) full)
                           full))))))

(defun pointwise-product (factors)
  "The product of a list of factors."
  (reduce #'(lambda (f g)
              (make-factor-from-table
               (union (factor-variables f) (factor-variables g))
               #'(lambda (event)
                   (* (factor-value f event) (factor-value g event)))))
          factors))

(defun sum-out-factor (variable factor)
  "Sum VARIABLE out of FACTOR."
  (make-factor-from-table
   (remove variable (factor-variables factor))
   #'(lambda (event)
       (+ (factor-value factor (extend-event event variable t))
          (factor-value factor (extend-event event variable nil))))))

(defun sum-out (variable factors)
  "Multiply the factors that mention VARIABLE and sum it out of the product."
  (let ((with (remove-if-not #'(lambda (f) (member variable (factor-variables f)))
                             factors))
        (without (remove-if #'(lambda (f) (member variable (factor-variables f)))
                            factors)))
    (if with
        (cons (sum-out-factor variable (pointwise-product with)) without)
      without)))

(defun elimination-ask (query e bn)
  "The distribution of the QUERY variable given the evidence E, by variable elimination.
  The variables are taken in reverse topological order."
  (let ((factors nil))
    (dolist (node (reverse (bayes-net-nodes bn)))
      (let ((V (bn-node-variable node)))
        (push (make-bn-factor node e) factors)
        (unless (or (eq V query) (event-assigns? V e))
          (setf factors (sum-out V factors)))))
    (let ((product (pointwise-product factors)))
      (boolean-distribution
       (factor-value product (list (cons query t)))
       (factor-value product (list (cons query nil)))))))

;;;; Approximate Inference by Sampling

(defun prior-sample (bn)
  "Sample an event from the prior distribution of BN [Figure 13.16]."
  (let ((event nil))
    (dolist (node (bayes-net-nodes bn) (reverse event))
      (push (cons (bn-node-variable node)
                  (sample-boolean (bn-probability node t event)))
            event))))

(defun consistent-event? (sample e)
  "Does SAMPLE agree with every value of the evidence E?"
  (every #'(lambda (pair) (eq (event-value (car pair) sample) (cdr pair))) e))

(defun rejection-sampling (query e bn N)
  "Estimate P(QUERY | E) from N samples of the prior, rejecting those that
  disagree with E [Figure 13.17]."
  (let ((count-t 0) (count-nil 0))
    (dotimes (j N)
      (let ((sample (prior-sample bn)))
        (when (consistent-event? sample e)
          (if (event-value query sample) (incf count-t) (incf count-nil)))))
    (boolean-distribution count-t count-nil)))

(defun weighted-sample (bn e)
  "Sample the nonevidence variables of BN, with the evidence E fixed;
  return the event and its weight, the likelihood of E."
  (let ((w 1) (event nil))
    (dolist (node (bayes-net-nodes bn))
      (let ((Xi (bn-node-variable node)))
        (if (event-assigns? Xi e)
            (progn
              (setf w (* w (bn-probability node (event-value Xi e) event)))
              (push (cons Xi (event-value Xi e)) event))
          (push (cons Xi (sample-boolean (bn-probability node t event)))
                event))))
    (values (reverse event) w)))

(defun likelihood-weighting (query e bn N)
  "Estimate P(QUERY | E) from N samples weighted by the likelihood of the
  evidence [Figure 13.18]."
  (let ((weight-t 0) (weight-nil 0))
    (dotimes (j N)
      (multiple-value-bind (sample w) (weighted-sample bn e)
        (if (event-value query sample) (incf weight-t w) (incf weight-nil w))))
    (boolean-distribution weight-t weight-nil)))

(defun markov-blanket-probability (node event bn)
  "P(variable = T | Markov blanket), from the values in EVENT."
  (let ((variable (bn-node-variable node))
        (children (bn-children (bn-node-variable node) bn)))
    (flet ((score (value)
             (let ((full (extend-event event variable value)))
               (* (bn-probability node value full)
                  (reduce #'* (mapcar #'(lambda (child)
                                          (bn-probability
                                           child
                                           (event-value (bn-node-variable child) full)
                                           full))
                                      children))))))
      (let ((p-t (score t)) (p-nil (score nil)))
        (/ p-t (+ p-t p-nil))))))

(defun gibbs-ask (query e bn N)
  "Estimate P(QUERY | E) by Gibbs sampling [Figure 13.20].  Each step
  samples one nonevidence variable from its distribution given its Markov
  blanket, cycling through the variables, and counts the value of QUERY."
  (let* ((nonevidence (remove-if #'(lambda (node)
                                     (event-assigns? (bn-node-variable node) e))
                                 (bayes-net-nodes bn)))
         (state (append e (mapcar #'(lambda (node)
                                      (cons (bn-node-variable node)
                                            (sample-boolean 0.5)))
                                  nonevidence)))
         (count-t 0) (count-nil 0))
    (dotimes (k N)
      (let ((node (nth (mod k (length nonevidence)) nonevidence)))
        (setf state (extend-event state (bn-node-variable node)
                                  (sample-boolean
                                   (markov-blanket-probability node state bn))))
        (if (event-value query state) (incf count-t) (incf count-nil))))
    (boolean-distribution count-t count-nil)))
