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

;;;; Monte Carlo Localization [Figure 26.6]

;;; The map is a grid, a 2-D array with 1 for an obstacle and 0 for a free
;;; cell.  A kinematic state is (row column orientation), with orientation
;;; 0 (north), 1 (east), 2 (south) or 3 (west).  Sensor j, for j = 0 .. 3,
;;; measures the range in the direction j quarter turns clockwise from the
;;; orientation of the robot: the number of free cells from the robot to
;;; the nearest obstacle or edge of the map, its own cell included.

(defun grid-free-cells (map)
  (loop for row below (array-dimension map 0)
        nconc (loop for col below (array-dimension map 1)
                    when (zerop (aref map row col)) collect (list row col))))

(defun grid-sample-state (map &optional (free (grid-free-cells map)))
  "A kinematic state drawn uniformly from the free cells and orientations."
  (append (random-element free) (list (random 4))))

(defun rotate-clockwise (delta times)
  "Turn the displacement (drow dcol) TIMES quarter turns clockwise."
  (dotimes (i (mod times 4) delta)
    (setf delta (list (second delta) (- (first delta))))))

(defun grid-ray-cast (j state map)
  "The range that sensor J measures from the kinematic STATE."
  (let ((delta (rotate-clockwise (case j (0 '(-1 0)) (1 '(0 1)) (2 '(1 0)) (3 '(0 -1)))
                                 (third state)))
        (row (first state)) (col (second state))
        (range 0))
    (loop while (and (< -1 row (array-dimension map 0))
                     (< -1 col (array-dimension map 1))
                     (zerop (aref map row col)))
          do (incf row (first delta))
             (incf col (second delta))
             (incf range))
    range))

(defun monte-carlo-localization (a z n motion-sample sensor-model map &optional samples)
  "One update of the N samples of the robot's state: each sample is moved
  by the motion model with the velocities A = (v w), weighted by the
  likelihood of the range scan Z (a list of ranges) given the ranges
  computed by ray casting on the map, and resampled.  With no SAMPLES, they
  are first drawn uniformly.  (MOTION-SAMPLE state v w) samples the next
  state, and (SENSOR-MODEL z z*) is P(z | z*)."
  (let* ((free (grid-free-cells map))
         (samples (or samples (loop repeat n collect (grid-sample-state map free))))
         (moved (mapcar #'(lambda (s) (funcall motion-sample s (first a) (second a)))
                        samples))
         (weights (mapcar #'(lambda (s)
                              (let ((w 1))
                                (loop for zj in z for j from 0
                                      do (setf w (* w (funcall sensor-model zj
                                                               (grid-ray-cast j s map)))))
                                w))
                          moved)))
    (weighted-sample-with-replacement n moved weights)))
