(deftest uncertainty
  "Test code for reasoning with uncertainty.  Currently, just MDPs."
  "Given the MDP (Markov Decision Process) for the 4x3 grid from Ch.s 17, 20,"
  "create an agent, and an environment corresponding to the MDP."
  ((setq agent (make-mdp-agent :mdp *4x3-mdp*
			       :algorithm 'value-iteration-policy)))
  ((setq env (make-mdp-environment :mdp *4x3-mdp* 
				   :agents (list agent))))
  "Now run the agent in the environment."
  "If all goes well, we get to the (4 3) terminal square."
  ((run-environment env))

  "Decision-theoretic agent (Figure 12.1) in the umbrella world: the belief"
  "in rain after seeing the umbrella makes it take one, and leave it after"
  "seeing none.  The utility is -1 when carrying it in the dry, or not in the rain."
  ((setq dt-program
         (make-dt-agent-program
          :prior '((rain . 0.5) (dry . 0.5))
          :actions '(take-umbrella leave-umbrella)
          :transition #'(lambda (s a s2) (declare (ignore a))
                          (if (eq s s2) 0.7 0.3))
          :sensor #'(lambda (umbrella s)
                      (let ((p (if (eq s 'rain) 0.9 0.2))) (if umbrella p (- 1 p))))
          :utility #'(lambda (a s)
                       (cond ((eq a 'take-umbrella) (if (eq s 'rain) 0 -1))
                             (t (if (eq s 'rain) -1 0)))))))
  ((mapcar dt-program '(t nil)) '(take-umbrella leave-umbrella))

  "Bayesian networks (Chapter 13): exact inference by enumeration and by"
  "variable elimination on the burglary network of Figure 13.2."
  ((enumeration-ask 'burglary '((johncalls . t) (marycalls . t)) *burglary-net*)
   (approximately-equal * '((t . 0.2842) (nil . 0.7158)) 1e-4))
  ((enumeration-ask 'burglary '((johncalls . t) (marycalls . nil)) *burglary-net*)
   (approximately-equal * '((t . 0.00513) (nil . 0.99487)) 1e-5))
  ((enumeration-ask 'burglary '((marycalls . t)) *burglary-net*)
   (approximately-equal * '((t . 0.0561) (nil . 0.9439)) 1e-4))
  ((elimination-ask 'burglary '((johncalls . t) (marycalls . t)) *burglary-net*)
   (approximately-equal * '((t . 0.2842) (nil . 0.7158)) 1e-4))
  ((elimination-ask 'burglary '((johncalls . t) (marycalls . nil)) *burglary-net*)
   (approximately-equal * '((t . 0.00513) (nil . 0.99487)) 1e-5))
  ((elimination-ask 'rain '((wetgrass . t)) *sprinkler-net*)
   (approximately-equal * '((t . 0.7079) (nil . 0.2921)) 1e-4))
  ((elimination-ask 'cloudy '((rain . t) (sprinkler . t)) *sprinkler-net*)
   (approximately-equal * '((t . 0.4444) (nil . 0.5556)) 1e-4))
  "Approximate inference by sampling, with tolerances of several standard"
  "deviations; the exact values are 0.5, 0.8, 0.7079 and 0.1667."
  ((prior-sample *sprinkler-net*)
   (equal (mapcar #'car *) '(cloudy sprinkler rain wetgrass)))
  ((/ (count-if #'(lambda (x) (event-value 'cloudy x))
                (loop repeat 2000 collect (prior-sample *sprinkler-net*)))
      2000.0)
   (approximately-equal * 0.5 0.06))
  ((rejection-sampling 'cloudy '((rain . t)) *sprinkler-net* 10000)
   (approximately-equal * '((t . 0.8) (nil . 0.2)) 0.03))
  ((likelihood-weighting 'rain '((wetgrass . t)) *sprinkler-net* 10000)
   (approximately-equal * '((t . 0.7079) (nil . 0.2921)) 0.03))
  ((likelihood-weighting 'cloudy '((sprinkler . t)) *sprinkler-net* 10000)
   (approximately-equal * '((t . 0.1667) (nil . 0.8333)) 0.03))
  ((gibbs-ask 'cloudy '((rain . t)) *sprinkler-net* 10000)
   (approximately-equal * '((t . 0.8) (nil . 0.2)) 0.05))

  "Temporal models (Chapter 14) on the umbrella world: filtering and"
  "smoothing (Figure 14.4) with the values of Section 14.2."
  ((hmm-filter *umbrella-hmm* '(t t))
   (approximately-equal * '(0.8834 0.1166) 1e-4))
  ((forward-backward *umbrella-hmm* '(t t))
   (approximately-equal * '((0.8834 0.1166) (0.8834 0.1166)) 1e-4))
  ((forward-backward *umbrella-hmm* '(t t nil t t))
   (approximately-equal * '((0.8673 0.1327) (0.8204 0.1796) (0.3075 0.6925)
                            (0.8204 0.1796) (0.8673 0.1327)) 1e-4))
  ((forward-backward *umbrella-hmm* '(t nil t nil t))
   (approximately-equal * '((0.7177 0.2823) (0.2324 0.7676) (0.6072 0.3928)
                            (0.2324 0.7676) (0.7177 0.2823)) 1e-4))
  "Fixed-lag smoothing (Figure 14.6) with lag 2 gives P(X_t-2 | e_1:t)."
  ((mapcar (make-fixed-lag-smoother *umbrella-hmm* 2) '(t nil t nil t))
   (approximately-equal * '(nil nil (0.7251 0.2749) (0.2259 0.7741)
                            (0.6072 0.3928)) 1e-4))
  ((mapcar (make-fixed-lag-smoother *umbrella-hmm* 0) '(t t))
   (approximately-equal * '((0.8182 0.1818) (0.8834 0.1166)) 1e-4))
  "The most likely sequence (Viterbi): rain is state 0."
  ((multiple-value-list (hmm-viterbi *umbrella-hmm* '(t t nil t t)))
   (approximately-equal * '((0 0 1 0 0) (0.8182 0.5155 0.1237 0.0334 0.0210)) 1e-4))
  ((hmm-viterbi *umbrella-hmm* '(t nil t nil t)) '(0 1 1 1 0))
  "Particle filtering (Figure 14.17): 1000 particles after one umbrella."
  ((particle-filtering t 1000 *umbrella-hmm*)
   (and (= (length *) 1000)
        (approximately-equal (/ (count 0 *) 1000.0) 0.8182 0.06)))
  "The Kalman filter on a one-dimensional random walk: the posterior after"
  "z = 2.5 is N(1.875, 0.75), and the variance with unit noises converges"
  "to (sqrt(5) - 1) / 2."
  ((kalman-filter (make-kalman-model :transition '((1)) :sensor '((1))
                                     :transition-noise '((2)) :sensor-noise '((1)))
                  '(0) '((1)) '(2.5))
   (approximately-equal * '(((1.875) . ((0.75)))) 1e-6))
  ((car (last (kalman-filter (make-kalman-model :transition '((1)) :sensor '((1))
                                                :transition-noise '((1))
                                                :sensor-noise '((1)))
                             '(0) '((1)) (make-list 60 :initial-element 0))))
   (approximately-equal (first (first (cdr *))) (/ (- (sqrt 5d0) 1) 2) 1e-6))
  "With a constant-velocity model, rising positions give a positive velocity."
  ((car (last (kalman-filter (make-kalman-model
                              :transition '((1 1) (0 1)) :sensor '((1 0))
                              :transition-noise '((0.01 0) (0 0.01))
                              :sensor-noise '((1)))
                             '(0 0) '((1 0) (0 1)) '(1 2 3 4 5))))
   (> (second (car *)) 0))

  "Generative programs of open-universe models (Chapter 15)."
  ((multiple-value-list (generate-citation-world 20))
   (destructuring-bind (researchers papers citations) *
     (and (= (length citations) 20)
          (every #'(lambda (c) (member (citation-cited-paper c) papers)) citations)
          (every #'(lambda (c) (member (paper-author (citation-cited-paper c))
                                       researchers))
                 citations))))
  ((multiple-value-list (generate-seismic-world '((0 0) (45 90)) :duration 36000))
   (destructuring-bind (events detections) *
     (and events detections
          (some #'(lambda (d) (null (detection-event d))) detections)
          (every #'(lambda (d)
                     (or (null (detection-event d))
                         (> (detection-onset-time d)
                            (- (seismic-event-time (detection-event d)) 20))))
                 detections))))
  ((multiple-value-list (generate-radar-world 30))
   (destructuring-bind (aircraft blips) *
     (and aircraft blips
          (every #'(lambda (b) (<= 0 (blip-time b) 29)) blips)
          (some #'(lambda (b) (null (blip-source b))) blips)
          (some #'blip-source blips)
          (every #'(lambda (a)
                     (let ((times (sort (mapcar #'car (aircraft-track a)) #'<)))
                       (and (= (first times) (aircraft-entry-time a))
                            (equal times (iota (length times) (first times))))))
                 aircraft))))
  ((render '(#\l) 32 128)
   (and (equal (array-dimensions *) '(32 128))
        (= (loop for i below (array-total-size *) sum (row-major-aref * i))
           (count #\1 (cdr (assoc #\l *font*))))))
  ((multiple-value-list (generate-image))
   (destructuring-bind (image letters) *
     (let ((clean (render letters 32 128)))
       (approximately-equal
        (/ (loop for i below (array-total-size image)
                 sum (- (row-major-aref image i) (row-major-aref clean i)))
           (array-total-size image))
        0 0.08))))
  ((multiple-value-list (letter-bigram-model '("ab" "ab")))
   '(((#\a . 1)) ((#\a (#\b . 1)))))
  ((multiple-value-bind (initial transition) (letter-bigram-model '("ab" "ab"))
     (generate-markov-letters 20 initial transition))
   (every #'char= * (loop for i below (length *) collect (if (evenp i) #\a #\b))))

  "Value of information and an information-gathering agent (Figure 16.9):"
  "one of 4 blocks has oil worth 1000, each block costs 250, and a survey"
  "tells whether block 3 has oil; its value of information is 1000/4."
  ((setq survey (make-evidence-variable
                 :name 'survey-3 :values '(yes no) :cost 100
                 :likelihood #'(lambda (v s) (if (eq (eql s 3) (eq v 'yes)) 1 0)))))
  ((setq oil-utility #'(lambda (a s) (if (eq a 'none) 0 (- (if (eql a s) 1000 0) 250)))))
  ((value-of-perfect-information survey '((1 . 1/4) (2 . 1/4) (3 . 1/4) (4 . 1/4))
                                 '(1 2 3 4 none) oil-utility)
   (= * 250))
  ((setq oil-agent (make-information-gathering-agent
                    :belief '((1 . 1/4) (2 . 1/4) (3 . 1/4) (4 . 1/4))
                    :actions '(1 2 3 4 none) :utility oil-utility
                    :evidence (list survey))))
  ((funcall oil-agent nil) '(request survey-3))
  ((funcall oil-agent '(survey-3 . yes)) 3)
  ((funcall (make-information-gathering-agent
             :belief '((1 . 1/4) (2 . 1/4) (3 . 1/4) (4 . 1/4))
             :actions '(1 2 3 4 none) :utility oil-utility
             :evidence (list (make-evidence-variable
                              :name 'survey-3 :values '(yes no) :cost 300
                              :likelihood (evidence-variable-likelihood survey))))
            nil)
   (not (consp *)))

  "POMDP value iteration (Figure 17.16) on the two-state world of Section"
  "17.4: Go switches state and Stay stays, with probability 0.9; the sensor"
  "is right with probability 0.6; R(0) = 0 and R(1) = 1."
  ((setq two-state-pomdp
         (make-pomdp :states '(0 1) :actions '(stay go) :percepts '(0 1)
                     :transition #'(lambda (s a s2)
                                     (if (eq (= s s2) (eq a 'stay)) 0.9 0.1))
                     :sensor #'(lambda (e s) (if (= e s) 0.6 0.4))
                     :reward #'(lambda (s) s)
                     :gamma 1)))
  "With gamma = 1, the one-step plans [Stay] and [Go] of the book."
  ((mapcar #'car (pomdp-plans-backup two-state-pomdp (list (cons '(0 1) nil))))
   (approximately-equal * '((0.1 1.9) (0.9 1.1)) 1e-6))
  ((setf (pomdp-gamma two-state-pomdp) 0.9))
  ((setq pomdp-u (pomdp-value-iteration two-state-pomdp 0.1)))
  ((every #'(lambda (b)
              (approximately-equal (utility-of-belief pomdp-u b)
                                   (pomdp-bellman-backup two-state-pomdp pomdp-u b)
                                   0.02))
          (belief-grid 2 20))
   *)
  ((> (utility-of-belief pomdp-u '(0 1)) (utility-of-belief pomdp-u '(1 0))) *)
  ((pomdp-update-belief two-state-pomdp '(0.5 0.5) 'stay 0)
   (approximately-equal * '(0.6 0.4) 1e-6))

  "Value iteration [Fig. 17.6] gives the utilities of Fig. 17.3 for the"
  "4x3 world, and the policy of Fig. 17.2."
  ((setq U4x3 (value-iteration *4x3-mdp*)))
  ((mapcar #'(lambda (s) (gethash s U4x3))
           '((1 1) (1 2) (1 3) (2 1) (2 3) (3 1) (3 2) (3 3) (4 1)))
   (approximately-equal * '(0.705 0.762 0.812 0.655 0.868 0.611 0.660 0.918
                            0.388)
                        0.001))
  ((setq P4x3 (optimal-policy U4x3 (mdp-model *4x3-mdp*) (mdp-rewards *4x3-mdp*))))
  ((mapcar #'(lambda (s) (caar (gethash s P4x3)))
           '((1 1) (1 2) (1 3) (2 1) (2 3) (3 1) (3 2) (3 3) (4 1)))
   '(up up right left right left up right left))
  "Policy evaluation [Section 17.2.2] of the optimal policy gives the same"
  "utilities, and policy iteration [Fig. 17.9] keeps that policy."
  ((value-determination P4x3 (copy-hash-table (mdp-rewards *4x3-mdp*) #'identity)
                        (mdp-model *4x3-mdp*) (mdp-rewards *4x3-mdp*))
   (approximately-equal (gethash '(1 1) *) 0.705 0.001))
  ((policy-iteration *4x3-mdp* U4x3)
   (equal (mapcar #'(lambda (s) (caar (gethash s *))) '((1 1) (3 1) (3 3)))
          '(up left right)))
  "A small MDP in which every policy ends: from A, Safe leads to B, whence"
  "Go wins with probability 0.8; Risky wins or loses with even odds."
  ((setq small-mdp (alists->mdp '((A (safe ((B 1.0)))
                                     (risky ((win 0.5) (lose 0.5))))
                                  (B (go ((win 0.8) (lose 0.2)))))
                                '((A -0.1) (B -0.1) (win 1) (lose -1))
                                :initial-state 'A :terminal-states '(win lose))))
  ((setq U (value-iteration small-mdp)))
  ((list (gethash 'A U) (gethash 'B U)) (approximately-equal * '(0.4 0.5) 1e-4))
  ((setq P (make-hash-table :test #'equal)))
  ((progn (setf (gethash 'A P) '((risky 1.0)) (gethash 'B P) '((go 1.0)))
          (setq U (value-determination P (copy-hash-table (mdp-rewards small-mdp)
                                                          #'identity)
                                       (mdp-model small-mdp)
                                       (mdp-rewards small-mdp)))
          (list (gethash 'A U) (gethash 'B U)))
   (approximately-equal * '(-0.1 0.5) 1e-4))
  "Policy iteration starts from Risky (the best move on the rewards alone)"
  "and switches to Safe."
  ((caar (gethash 'A (policy-iteration small-mdp))) 'safe)

  "Dynamic decision networks (Section 17.4.3): lookahead in the two-state"
  "POMDP goes to state 1, and then stays there."
  ((setq ddn-pomdp
         (make-pomdp :states '(0 1) :actions '(stay go) :percepts '(0 1)
                     :transition #'(lambda (s a s2)
                                     (if (eq (= s s2) (eq a 'stay)) 0.9 0.1))
                     :sensor #'(lambda (e s) (if (= e s) 0.6 0.4))
                     :reward #'(lambda (s) s)
                     :gamma 0.9)))
  ((multiple-value-list (ddn-lookahead ddn-pomdp '(1 0) 2))
   (and (eq (first *) 'go) (approximately-equal (second *) 0.81 1e-6)))
  ((ddn-lookahead ddn-pomdp '(0 1) 2) 'stay)
  ((ddn-lookahead ddn-pomdp '(0.9 0.1) 3) 'go)

  "Probability distributions [Section 12.3] and inference by enumeration of"
  "the full joint distribution of Fig. 12.3: P(Cavity | toothache) = 0.6."
  ((setq coin (make-prob-dist 'flip '((heads . 1) (tails . 1)))))
  ((typep coin 'prob-dist) t)
  ((prob-dist-probability coin 'heads) 1/2)
  ((prob-dist-probability (prob-dist-normalize (prob-dist-set coin 'edge 1))
                          'edge)
   1/2)
  ((prob-dist-values coin) '(heads tails edge))
  ((prob-dist-table (enumerate-joint-ask 'cavity '((toothache . t))
                                         *dentist-joint*))
   (approximately-equal * '((t . 0.6) (nil . 0.4)) 1e-6))
  ((prob-dist-table (enumerate-joint-ask 'cavity nil *dentist-joint*))
   (approximately-equal * '((t . 0.2) (nil . 0.8)) 1e-6))
  ((prob-dist-probability (enumerate-joint-ask 'toothache
                                               '((cavity . t) (catch . nil))
                                               *dentist-joint*)
                          t)
   (approximately-equal * 0.6 1e-6))

  "A Bayes net built by BAYES-NET, with a three-valued variable: the"
  "weather is sunny, rainy or cloudy, and the grass is wet."
  ((setq weather-net (bayes-net '((weather () ((sunny . 0.7) (rainy . 0.2)
                                               (cloudy . 0.1))
                                   (sunny rainy cloudy))
                                  (wet (weather) (((sunny) . 0.1)
                                                  ((rainy) . 0.9)
                                                  ((cloudy) . 0.3)))))))
  ((bn-variables weather-net) '(weather wet))
  ((enumeration-ask 'weather '((wet . t)) weather-net)
   (approximately-equal * '((sunny . 0.25) (rainy . 0.6429) (cloudy . 0.1071))
                        1e-4))
  ((enumeration-ask 'wet nil weather-net)
   (approximately-equal * '((t . 0.28) (nil . 0.72)) 1e-6))
  "The burglary network in BIF gives the same answer as Figure 13.2:"
  ((setq bif-net (read-bif "network burglary { }
variable Burglary { type discrete [ 2 ] { True, False }; }
variable Earthquake { type discrete [ 2 ] { True, False }; }
variable Alarm { type discrete [ 2 ] { True, False }; }
variable JohnCalls { type discrete [ 2 ] { True, False }; }
variable MaryCalls { type discrete [ 2 ] { True, False }; }
probability ( JohnCalls | Alarm ) { (True) 0.90, 0.10; (False) 0.05, 0.95; }
probability ( MaryCalls | Alarm ) { (True) 0.70, 0.30; (False) 0.01, 0.99; }
probability ( Alarm | Burglary, Earthquake ) {
  (True, True) 0.95, 0.05; (True, False) 0.94, 0.06;
  (False, True) 0.29, 0.71; (False, False) 0.001, 0.999; }
probability ( Burglary ) { table 0.001, 0.999; }
probability ( Earthquake ) { table 0.002, 0.998; }")))
  ((length (bn-variables bif-net)) 5)
  ((enumeration-ask 'burglary '((johncalls . true) (marycalls . true)) bif-net)
   (approximately-equal * '((true . 0.2842) (false . 0.7158)) 1e-4))
  "The car insurance network, read from aima-data: only adolescents can be"
  "good students."
  ((setq insurance (insurance-net)))
  ((length (bn-variables insurance)) 27)
  ((enumeration-ask 'socioecon nil insurance)
   (approximately-equal * '((prole . 0.42) (middle . 0.36) (uppermiddle . 0.21)
                            (wealthy . 0.01))
                        1e-6))
  ((enumeration-ask 'age '((goodstudent . true)) insurance)
   (approximately-equal * '((adolescent . 1) (adult . 0) (senior . 0)) 1e-6))

  "A hybrid network (Fig. 13.5): the density of the linear Gaussian Cost,"
  "the probit of Buys, and P(buys | subsidy) = Phi(1 / sqrt(3)) = 0.7181"
  "by likelihood weighting."
  ((hybrid-bn-probability (third *crop-net*) 5 '((subsidy . t) (harvest . 10)))
   (approximately-equal * 0.398942 1e-5))
  ((hybrid-bn-probability (fourth *crop-net*) t '((cost . 6)))
   (approximately-equal * 0.5 1e-6))
  ((normal-cdf 1.96) (approximately-equal * 0.975 1e-4))
  ((setq tiny-hybrid (hybrid-bayes-net '((x :gaussian () () ((() . (() 0 1))))
                                         (y :probit () (x) ((() . (0 1))))))))
  ((hybrid-likelihood-weighting 'y nil tiny-hybrid 10000)
   (approximately-equal * '((t . 0.5) (nil . 0.5)) 0.03))
  ((hybrid-likelihood-weighting 'buys '((subsidy . t)) *crop-net* 10000)
   (approximately-equal * '((t . 0.7181) (nil . 0.2819)) 0.03))
  ((hybrid-likelihood-weighting 'subsidy '((buys . t)) *crop-net* 10000)
   (approximately-equal * '((t . 0.7181) (nil . 0.2819)) 0.03))

  "The umbrella DBN unrolled for 2 slices: exact inference gives the"
  "filtered and smoothed values of Section 14.2."
  ((setq umbrella-net (dbn-unroll *umbrella-dbn* 2)))
  ((typep *umbrella-dbn* 'dynamic-bayes-net) t)
  ((bn-variables umbrella-net) '(rain_0 rain_1 umbrella_1 rain_2 umbrella_2))
  ((enumeration-ask 'rain_2 '((umbrella_1 . t) (umbrella_2 . t)) umbrella-net)
   (approximately-equal * '((t . 0.8834) (nil . 0.1166)) 1e-4))
  ((enumeration-ask 'rain_1 '((umbrella_1 . t) (umbrella_2 . t)) umbrella-net)
   (approximately-equal * '((t . 0.8834) (nil . 0.1166)) 1e-4))
  "The structure of the umbrella HMM:"
  ((typep *umbrella-hmm* 'hmm) t)
  ((length (hmm-transition *umbrella-hmm*)) 2)

  "A decision network (Section 16.5): with no forecast leave the umbrella"
  "(expected utility 70), with a forecast of rain take it (58.71)."
  ((typep *umbrella-decision-network* 'decision-network) t)
  ((multiple-value-list
    (decision-network-best-action *umbrella-decision-network* nil))
   (and (eq (first *) 'leave) (approximately-equal (second *) 70 0.01)))
  ((decision-network-expected-utility *umbrella-decision-network* 'take nil)
   (approximately-equal * 35 0.01))
  ((multiple-value-list
    (decision-network-best-action *umbrella-decision-network* '((forecast . t))))
   (and (eq (first *) 'take) (approximately-equal (second *) 58.71 0.01)))
  )
