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

;;;; Decision Networks

;;; A decision network [Section 16.5] is a Bayes net (see bayes-nets.lisp)
;;; with a DECISION node, whose value is one of ACTIONS, and a utility node,
;;; whose parents are the decision and the UTILITY-VARIABLES.  The chance
;;; nodes may have the decision among their parents.  UTILITY is a function
;;; of the action and of an event that gives values to the utility
;;; variables.

(defstruct decision-network
  bn
  decision
  actions
  utility-variables
  utility)

(defun decision-network-expected-utility (dn action e)
  "The expected utility of ACTION given the evidence E: the sum over the
  values of the utility variables of their probability, given E and the
  action, times their utility."
  (let* ((bn (decision-network-bn dn))
	 (variables (decision-network-utility-variables dn))
	 (e (extend-event e (decision-network-decision dn) action))
	 (nodes (bn-relevant-nodes (append variables (mapcar #'car e)) bn))
	 (total 0)
	 (sum 0))
    (dolist (values (cartesian-product
		     (mapcar #'(lambda (v) (bn-node-values (bn-variable-node v bn)))
			     variables)))
      (let* ((event (mapcar #'cons variables values))
	     (p (enumerate-all nodes (append event e))))
	(incf total p)
	(incf sum (* p (funcall (decision-network-utility dn) action event)))))
    (/ sum total)))

(defun decision-network-best-action (dn e)
  "The action with the maximum expected utility given the evidence E, and
  that utility. [Section 16.5.2]"
  (let ((best (the-biggest #'(lambda (a) (decision-network-expected-utility
					  dn a e))
			   (decision-network-actions dn))))
    (values best (decision-network-expected-utility dn best e))))

(defparameter *umbrella-decision-network*
  (make-decision-network
   :bn (bayes-net '((rain () 0.3)
		    (forecast (rain) (((t) . 0.8) ((nil) . 0.1)))))
   :decision 'umbrella
   :actions '(take leave)
   :utility-variables '(rain)
   :utility #'(lambda (action event)
		(if (eq action 'take)
		    (if (event-value 'rain event) 70 20)
		  (if (event-value 'rain event) 0 100))))
  "Whether to take the umbrella, given a forecast of rain that is right 80%
  of the times it rains, and wrong 10% of the times it does not.")
