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

;;;; Hybrid Bayesian Networks: Discrete and Continuous Variables

;;; A hybrid network [Section 13.2.3] has Boolean and continuous variables.
;;; Each node has discrete (Boolean) and continuous parents, and its
;;; PARAMETERS are an alist from the list of the values of the discrete
;;; parents to the parameters of the conditional distribution, whose form
;;; depends on the TYPE of the node:
;;;   :boolean   p            P(X = T) (no continuous parents)
;;;   :gaussian  (w b sigma)  X ~ N(w . c + b, sigma^2): the linear Gaussian
;;;                           model, c being the values of the continuous
;;;                           parents and w their weights
;;;   :probit    (mu sigma)   P(X = T | c) = Phi((mu - c) / sigma)
;;;   :logit     (mu sigma)   P(X = T | c) = 1 / (1 + exp(-2 (mu - c) / sigma))
;;; for the last two, c is the value of the one continuous parent.  The
;;; nodes are listed in topological order; events are alists as in
;;; bayes-nets.lisp.

(defstruct (hybrid-bn-node (:type list))
  variable type (discrete-parents nil) (continuous-parents nil) parameters)

(defun hybrid-bayes-net (specs)
  "A hybrid network from a list of (variable type discrete-parents
  continuous-parents parameters) specifications, in topological order."
  (mapcar #'(lambda (spec) (apply #'make-hybrid-bn-node
				   (mapcan #'list
					   '(:variable :type :discrete-parents
					     :continuous-parents :parameters)
					   spec)))
	  specs))

(defun normal-cdf (x &optional (mean 0) (sd 1))
  "The cumulative distribution function of N(MEAN, SD^2) at X, by the
  approximation of the error function 7.1.26 of Abramowitz and Stegun
  (absolute error below 1e-7)."
  (let* ((z (/ (- x mean) (* sd (sqrt 2d0))))
	 (s (abs z))
	 (u (/ 1 (+ 1 (* 0.3275911d0 s))))
	 (poly (* u (reduce #'(lambda (a acc) (+ a (* u acc)))
			    '(0.254829592d0 -0.284496736d0 1.421413741d0
			      -1.453152027d0 1.061405429d0)
			    :from-end t)))
	 (erf (- 1 (* poly (exp (- (* s s)))))))
    (/ (+ 1 (if (minusp z) (- erf) erf)) 2)))

(defun hybrid-bn-parameters (node event)
  (cdr (assoc (mapcar #'(lambda (parent) (event-value parent event))
		      (hybrid-bn-node-discrete-parents node))
	      (hybrid-bn-node-parameters node) :test #'equal)))

(defun hybrid-bn-probability (node value event)
  "The probability (for a Boolean node) or the density (for a Gaussian
  one) of VALUE, given the values of the parents in EVENT."
  (let ((params (hybrid-bn-parameters node event))
	(c (mapcar #'(lambda (parent) (event-value parent event))
		   (hybrid-bn-node-continuous-parents node))))
    (ecase (hybrid-bn-node-type node)
      (:boolean (if value params (- 1 params)))
      (:gaussian (destructuring-bind (w b sigma) params
		   (gaussian-density value (+ (reduce #'+ (mapcar #'* w c)) b)
				     sigma)))
      ((:probit :logit)
       (destructuring-bind (mu sigma) params
	 (let ((p (if (eq (hybrid-bn-node-type node) :probit)
		      (normal-cdf (/ (- mu (first c)) sigma))
		    (/ 1 (+ 1 (exp (/ (* -2 (- mu (first c))) sigma)))))))
	   (if value p (- 1 p))))))))

(defun hybrid-bn-sample (node event)
  "Sample a value of NODE given the values of its parents in EVENT."
  (if (eq (hybrid-bn-node-type node) :gaussian)
      (destructuring-bind (w b sigma) (hybrid-bn-parameters node event)
	(sample-gaussian (+ (reduce #'+ (mapcar #'* w
						(mapcar #'(lambda (parent)
							    (event-value parent event))
							(hybrid-bn-node-continuous-parents node))))
			    b)
			 sigma))
    (sample-boolean (hybrid-bn-probability node t event))))

(defun hybrid-likelihood-weighting (query e net N)
  "Estimate the distribution of the Boolean QUERY variable given the
  evidence E by likelihood weighting [Figure 13.18]: the evidence weights
  each sample by its probability, or by its density for a continuous
  variable."
  (let ((weight-t 0) (weight-nil 0))
    (dotimes (j N)
      (let ((w 1) (event nil))
	(dolist (node net)
	  (let ((X (hybrid-bn-node-variable node)))
	    (if (event-assigns? X e)
		(progn (setf w (* w (hybrid-bn-probability node (event-value X e)
							   event)))
		       (push (cons X (event-value X e)) event))
	      (push (cons X (hybrid-bn-sample node event)) event))))
	(if (event-value query event) (incf weight-t w) (incf weight-nil w))))
    (boolean-distribution weight-t weight-nil)))

(defparameter *crop-net*
  (hybrid-bayes-net
   '((subsidy :boolean () () ((() . 0.5)))
     (harvest :gaussian () () ((() . (() 10 2))))
     (cost :gaussian (subsidy) (harvest) (((t) . ((-0.5) 10 1))
					   ((nil) . ((-0.5) 12 1))))
     (buys :probit () (cost) ((() . (6 1))))))
  "The network of Fig. 13.5: Subsidy and Harvest determine the Cost, a
  linear Gaussian of Harvest for each value of Subsidy, and the customer
  Buys with a probit probability of the Cost; the numbers are made up.")
