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

;;;; Generative Programs for Open-Universe Probability Models (Chapter 15)

;;; Each function samples one possible world of a model of Chapter 15.
;;; Where the book leaves a part of a model unspecified (the grammar of
;;; citations, the physics of seismic waves, the font of a letter), the
;;; simplest version that keeps the structure of the figure is used.

(defparameter *lowercase-letters* "abcdefghijklmnopqrstuvwxyz")

(defun random-letter ()
  (char *lowercase-letters* (random 26)))

(defun random-word (min-length max-length)
  "A string of lowercase letters, of length between the two bounds."
  (let ((word (make-string (random-integer min-length max-length))))
    (dotimes (i (length word) word)
      (setf (char word i) (random-letter)))))

(defun om (a b)
  "The order-of-magnitude distribution OM(a, b) of Section 15.2: values of
  about 10^a, give or take b orders of magnitude."
  (round (expt 10 (sample-gaussian a b))))

;;;; Citation Information Extraction [Figure 15.5]

(defstruct researcher name professor?)
(defstruct paper author title)
(defstruct citation cited-paper text)

(defun generate-citation-world (&optional (n-citations 10))
  "Sample the researchers (#Researcher ~ OM(3, 1)), each a professor with
  probability 0.2, with #Paper ~ OM(1.5, 0.5) papers for a professor and
  OM(1, 0.5) otherwise, and N-CITATIONS citations of papers chosen
  uniformly.  The text of a citation (the HMM grammar of the figure) is the
  name of the author and the title, with a typo now and then.  Returns
  the researchers, the papers and the citations, as three values."
  (let ((researchers
          (loop repeat (max 1 (om 3 1))
                collect (make-researcher
                         :name (string-capitalize (random-word 4 9))
                         :professor? (sample-boolean 0.2))))
        (papers nil)
        (citations nil))
    (dolist (r researchers)
      (loop repeat (max 0 (if (researcher-professor? r) (om 1.5 0.5) (om 1 0.5)))
            do (push (make-paper :author r :title (random-title)) papers)))
    (when papers
      (let ((paper-vector (coerce papers 'vector)))
        (dotimes (i n-citations)
          (let ((p (aref paper-vector (random (length paper-vector)))))
            (push (make-citation
                   :cited-paper p
                   :text (noisy-text
                          (format nil "~A. ~A." (researcher-name (paper-author p))
                                  (paper-title p))))
                  citations)))))
    (values researchers papers citations)))

(defun random-title ()
  "PaperTitlePrior(): 2 to 6 words of 3 to 8 letters."
  (string-capitalize
   (format nil "~{~A~^ ~}" (loop repeat (random-integer 2 6)
                                 collect (random-word 3 8)))
   :end 1))

(defun noisy-text (text &optional (p-typo 0.02))
  "Replace each letter of TEXT by a random one with probability P-TYPO."
  (map 'string #'(lambda (c)
                   (if (and (alpha-char-p c) (sample-boolean p-typo))
                       (random-letter)
                     c))
       text))

;;;; Seismic Monitoring: a Simplified NET-VISA [Figure 15.6]

(defparameter *earth-radius* 6371.0d0 "In kilometers.")
(defparameter *p-wave-speed* 8.0d0
  "In km/s: a constant speed stands in for the travel-time model GeoTT.")

(defun degrees->radians (x) (* x (/ pi 180)))

(defun great-circle-distance (location1 location2)
  "The distance in km between two (latitude longitude) points, in degrees."
  (destructuring-bind (lat1 lon1) (mapcar #'degrees->radians location1)
    (destructuring-bind (lat2 lon2) (mapcar #'degrees->radians location2)
      (* *earth-radius*
         (acos (max -1 (min 1 (+ (* (sin lat1) (sin lat2))
                                 (* (cos lat1) (cos lat2) (cos (- lon1 lon2)))))))))))

(defun uniform-earth ()
  "A point uniformly distributed on the surface of the earth."
  (list (/ (* 180 (asin (random-real -1 1))) pi) (random-real -180 180)))

(defstruct seismic-event time earthquake? location depth magnitude)
(defstruct detection station event onset-time amplitude)

(defun generate-seismic-world (stations &key (duration 3600) (event-rate 1/1800)
                                             (noise-rate 1/600)
                                             (spatial-prior #'uniform-earth))
  "Sample the seismic events of DURATION seconds (#SeismicEvents ~
  Poisson(T * event-rate)), each an earthquake with probability 0.999,
  located by SPATIAL-PRIOR if so and anywhere otherwise, with an
  Exponential(log 10) magnitude; and the detections of each station in
  the list of (latitude longitude) STATIONS: an event is detected with a
  logistic probability in its magnitude, depth and distance, and each
  station also records Poisson(T * noise-rate) noise detections.  The
  simplifications are a single phase, a constant wave speed, and no
  azimuth or slowness.  Returns the events and the detections."
  (let ((events nil) (detections nil))
    (loop repeat (sample-poisson (* duration event-rate))
          do (let ((earthquake? (sample-boolean 0.999)))
               (push (make-seismic-event
                      :time (random-real 0 duration)
                      :earthquake? earthquake?
                      :location (if earthquake? (funcall spatial-prior) (uniform-earth))
                      :depth (if earthquake? (random-real 0 700) 0)
                      :magnitude (sample-exponential (log 10)))
                     events)))
    (loop for site in stations for s from 0
          do (dolist (e events)
               (let* ((distance (great-circle-distance (seismic-event-location e) site))
                      (p-detect (/ 1 (+ 1 (exp (- (+ (* 2 (seismic-event-magnitude e))
                                                     (* -0.001 (seismic-event-depth e))
                                                     (* -0.0005 distance))))))))
                 (when (sample-boolean p-detect)
                   (push (make-detection
                          :station s :event e
                          :onset-time (+ (seismic-event-time e)
                                         (/ distance *p-wave-speed*)
                                         (sample-laplace 0 1))
                          :amplitude (exp (+ (seismic-event-magnitude e)
                                             (/ distance -5000)
                                             (sample-gaussian 0 0.5))))
                         detections))))
             (loop repeat (sample-poisson (* duration noise-rate))
                   do (push (make-detection
                             :station s :event nil
                             :onset-time (random-real 0 duration)
                             :amplitude (exp (sample-gaussian -1 0.5)))
                            detections)))
    (values (reverse events) (reverse detections))))

;;;; Radar Tracking of Multiple Targets [Figure 15.9]

(defstruct aircraft entry-time (track nil))  ; track: alist of (time . state)
(defstruct blip time source z)

(defun sample-linear-gaussian (matrix x variances)
  "A sample of N(MATRIX x, diag(VARIANCES))."
  (mapcar #'(lambda (mean variance) (sample-gaussian mean (sqrt variance)))
          (matrix-vector-multiply matrix x) variances))

(defun generate-radar-world (duration &key (aircraft-rate 0.3) (exit-probability 0.1)
                                           (false-alarm-rate 1.0)
                                           (region '((0 100) (0 100)))
                                           (detection-probability
                                            #'(lambda (x) (declare (ignore x)) 0.9)))
  "Sample DURATION time steps of the radar model: at each step Poisson(
  AIRCRAFT-RATE) aircraft enter at a uniform position with zero velocity,
  every aircraft in flight exits with probability EXIT-PROBABILITY, moves
  by the linear-Gaussian model X_t ~ N(F X_t-1, Sigma_x) (the state is
  x, y, vx, vy) and produces a blip with probability given by its state,
  observed as Z ~ N(H X_t, Sigma_z); Poisson(FALSE-ALARM-RATE) false
  alarms per step appear uniformly in the region.  The covariances are
  diagonal.  Returns the aircraft and the blips."
  (let ((f '((1 0 1 0) (0 1 0 1) (0 0 1 0) (0 0 0 1)))
        (sigma-x '(0.1 0.1 0.5 0.5))
        (h '((1 0 0 0) (0 1 0 0)))
        (sigma-z '(1 1))
        (aircraft nil) (in-flight nil) (blips nil))
    (destructuring-bind ((x0 x1) (y0 y1)) region
      (dotimes (time duration)
        (dolist (a in-flight)
          (if (sample-boolean exit-probability)
              (setf in-flight (remove a in-flight))
            (push (cons time (sample-linear-gaussian
                              f (cdr (assoc (- time 1) (aircraft-track a))) sigma-x))
                  (aircraft-track a))))
        (loop repeat (sample-poisson aircraft-rate)
              do (let ((a (make-aircraft
                           :entry-time time
                           :track (list (cons time (list (random-real x0 x1)
                                                         (random-real y0 y1) 0 0))))))
                   (push a aircraft)
                   (push a in-flight)))
        (dolist (a in-flight)
          (let ((x (cdr (assoc time (aircraft-track a)))))
            (when (sample-boolean (funcall detection-probability x))
              (push (make-blip :time time :source a
                               :z (sample-linear-gaussian h x sigma-z))
                    blips))))
        (loop repeat (sample-poisson false-alarm-rate)
              do (push (make-blip :time time :source nil
                                  :z (list (random-real x0 x1) (random-real y0 y1)))
                       blips))))
    (values (reverse aircraft) (reverse blips))))

;;;; Optical Character Recognition [Figures 15.11 and 15.15]

(defparameter *font*
  (mapcar #'cons (coerce *lowercase-letters* 'list)
          '("010101111101101" "110101110101110" "011100100100011" "110101101101110"
            "111100110100111" "111100110100100" "011100101101011" "101101111101101"
            "111010010010111" "001001001101010" "101101110101101" "100100100100111"
            "101111111101101" "110101101101101" "010101101101010" "110101110100100"
            "010101101011001" "110101110101101" "011100010001110" "111010010010010"
            "101101101101111" "101101101101010" "101101111111101" "101101010101101"
            "101101010010010" "111001010100111"))
  "A 3 x 5 pixel font: for each letter, 15 bits, row by row.")

(defun generate-letters (mean)
  "GENERATE-LETTERS: Poisson(MEAN) letters, each chosen uniformly."
  (loop repeat (sample-poisson mean) collect (random-letter)))

(defun render (letters width height &key (text-top 10) (text-left 10))
  "A clean image (an array of WIDTH rows and HEIGHT columns, the book's
  names) with 1 where a letter of the font is drawn and 0 elsewhere;
  letters that do not fit are cut."
  (let ((image (make-array (list width height) :initial-element 0)))
    (loop for letter in letters for k from 0
          do (let ((glyph (cdr (assoc letter *font*)))
                   (left (+ text-left (* 4 k))))
               (dotimes (r 5)
                 (dotimes (c 3)
                   (when (and (< (+ text-top r) width) (< (+ left c) height)
                              (char= (char glyph (+ (* 3 r) c)) #\1))
                     (setf (aref image (+ text-top r) (+ left c)) 1))))))
    image))

(defun render-noisy-image (letters width height)
  "RENDER-NOISY-IMAGE: the clean rendering plus Gaussian noise at every
  pixel, with a variance drawn uniformly from 0.1 to 1."
  (let* ((image (render letters width height))
         (sd (sqrt (random-real 0.1 1))))
    (dotimes (row width image)
      (dotimes (col height)
        (setf (aref image row col) (sample-gaussian (aref image row col) sd))))))

(defun generate-image ()
  "GENERATE-IMAGE: about 10 letters rendered as a noisy 32 x 128 image.
  The letters are the second value, so that inference can be checked."
  (let ((letters (generate-letters 10)))
    (values (render-noisy-image letters 32 128) letters)))

(defun letter-bigram-model (words)
  "MARKOV-INITIAL and MARKOV-TRANSITION estimated from a list of words:
  the alist distribution of the first letters, and an alist that maps each
  letter to the distribution of the letter that follows it."
  (let ((initial nil) (transition nil))
    (dolist (word words)
      (let ((word (string-downcase word)))
        (when (plusp (length word))
          (incf (cdr (or (assoc (char word 0) initial)
                         (first (push (cons (char word 0) 0) initial)))))
          (loop for a across word
                for b across (subseq word 1)
                do (let ((row (or (assoc a transition)
                                  (first (push (list a) transition)))))
                     (incf (cdr (or (assoc b (cdr row))
                                    (first (push (cons b 0) (cdr row)))))))))))
    (values (normalize-distribution initial)
            (mapcar #'(lambda (row) (cons (car row) (normalize-distribution (cdr row))))
                    transition))))

(defun generate-markov-letters (mean initial transition)
  "GENERATE-MARKOV-LETTERS: Poisson(MEAN) letters, the first drawn from
  INITIAL and each other one from the TRANSITION distribution of the
  letter before it (from INITIAL after a letter with no successor)."
  (let ((letters nil) (letter-probs initial))
    (loop repeat (sample-poisson mean)
          do (push (sample-categorical letter-probs) letters)
             (setf letter-probs (or (cdr (assoc (first letters) transition))
                                    initial)))
    (reverse letters)))
