;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: robotics/test-robotics.lisp

;;;; Test cases for robotics

(deftest robotics
  "Monte Carlo localization (Figure 26.6) on a grid map, with a deterministic"
  "motion model and a range sensor that is exact with probability 0.8."
  ((setq robot-map
         (make-array '(11 17) :initial-contents
                     '((0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0)
                       (0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0)
                       (1 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 0)
                       (0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0)
                       (0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0)
                       (0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0)
                       (0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0)
                       (0 0 1 1 1 1 1 0 0 0 1 1 1 0 1 1 0)
                       (0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0)
                       (0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0)
                       (0 0 1 1 1 1 1 0 0 0 1 1 1 0 0 1 0)))))
  ((setq robot-motion
         #'(lambda (state v w)
             (let ((orientation (mod (+ (third state) w) 4))
                   (step (rotate-clockwise v (mod (+ (third state) w) 4))))
               (list (+ (first state) (first step)) (+ (second state) (second step))
                     orientation)))))
  ((setq range-sensor #'(lambda (z z*) (cond ((= z z*) 0.8) ((<= (abs (- z z*)) 2) 0.05) (t 0)))))
  "The robot is at (9 8) facing north; it stays, then moves one cell east."
  ((loop for j below 4 collect (grid-ray-cast j '(9 8 0) robot-map)) '(5 6 2 9))
  ((loop for j below 4 collect (grid-ray-cast j '(9 9 0) robot-map)) '(5 5 2 10))
  ((setq particles (monte-carlo-localization '((0 0) 0) '(5 6 2 9) 5000
                                             robot-motion range-sensor robot-map)))
  ((setq particles (monte-carlo-localization '((0 1) 0) '(5 5 2 10) 5000
                                             robot-motion range-sensor robot-map particles)))
  ((/ (count-if #'(lambda (s) (and (= (first s) 9) (= (second s) 9))) particles) 5000.0)
   (> * 0.5))
  )
