;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: language/algorithms/ngrams.lisp

;;;; N-gram Language Models and Word Segmentation (Section 23.1)

(defun text-words (text)
  "The list of the words of TEXT, lowercase: the maximal runs of letters
  and digits."
  (let ((words nil) (start nil))
    (loop for i from 0 to (length text)
          do (let ((c (and (< i (length text)) (char text i))))
               (cond ((and c (alphanumericp c))
                      (unless start (setf start i)))
                     (start
                      (push (string-downcase (subseq text start i)) words)
                      (setf start nil)))))
    (nreverse words)))

;;; An n-gram model counts the sequences of N consecutive words; the keys
;;; of its tables are lists of words.

(defstruct (ngram-model (:constructor new-ngram-model))
  n
  (counts (make-hash-table :test #'equal))       ; n-gram -> count
  (total 0)
  (successors (make-hash-table :test #'equal)))  ; (n-1)-gram -> alist of (word . count)

(defun make-ngram-model (n words)
  "The n-gram model of the list of WORDS."
  (ngram-model-add (new-ngram-model :n n) words))

(defun ngram-model-add (model tokens)
  "Count the n-grams of the list TOKENS (words, or characters) in MODEL."
  (let ((n (ngram-model-n model)))
    (loop for tail on tokens
          for remaining downfrom (length tokens)
          while (>= remaining n)
          do (let ((ngram (subseq tail 0 n)))
               (incf (gethash ngram (ngram-model-counts model) 0))
               (incf (ngram-model-total model))
               (let* ((prefix (butlast ngram))
                      (entry (assoc (car (last ngram))
                                    (gethash prefix (ngram-model-successors model))
                                    :test #'equal)))
                 (if entry
                     (incf (cdr entry))
                   (push (cons (car (last ngram)) 1)
                         (gethash prefix (ngram-model-successors model)))))))
    model))

(defun make-ngram-char-model (n words)
  "The n-gram model of the characters of each of the WORDS (strings), each
  preceded by a space to mark the beginning of a word (Section 23.1.3); the
  n-grams are lists of characters."
  (let ((model (new-ngram-model :n n)))
    (dolist (word words model)
      (ngram-model-add model (cons #\Space (coerce word 'list))))))

(defun ngram-probability (model ngram)
  "The relative frequency of NGRAM (a list of N words) in the model."
  (if (zerop (ngram-model-total model))
      0
    (/ (gethash ngram (ngram-model-counts model) 0) (ngram-model-total model))))

(defun ngram-conditional-probability (model prefix word)
  "P(word | prefix), for a list of the N-1 previous words PREFIX."
  (let* ((successors (gethash prefix (ngram-model-successors model)))
         (total (sum successors #'cdr)))
    (if (zerop total)
        0
      (/ (or (cdr (assoc word successors :test #'equal)) 0) total))))

(defun ngram-top (model k)
  "The K most frequent n-grams, as (count . ngram) pairs."
  (let ((pairs nil))
    (maphash #'(lambda (ngram count) (push (cons count ngram) pairs))
             (ngram-model-counts model))
    (let ((sorted (sort pairs #'> :key #'car)))
      (subseq sorted 0 (min k (length sorted))))))

(defun random-weighted-choice (alist)
  "A key of the alist of (key . count), chosen with probability
  proportional to its count."
  (let ((r (random (sum alist #'cdr))))
    (dolist (pair alist (car (last alist)))
      (when (< r (cdr pair)) (return (car pair)))
      (decf r (cdr pair)))))

(defun ngram-samples (model n-words)
  "A random text of N-WORDS words: a random n-gram, then each next word
  drawn given the N-1 words before it (a new random n-gram when the model
  has never seen them)."
  (let ((ngrams nil))
    (maphash #'(lambda (ngram count) (push (cons ngram count) ngrams))
             (ngram-model-counts model))
    (let ((output (reverse (random-weighted-choice ngrams))))  ; latest word first
      (loop while (< (length output) n-words)
            do (let ((successors (gethash (reverse (subseq output 0 (- (ngram-model-n model) 1)))
                                          (ngram-model-successors model))))
                 (if successors
                     (push (random-weighted-choice successors) output)
                   (setf output (append (reverse (random-weighted-choice ngrams)) output)))))
      (subseq (reverse output) 0 n-words))))

;;;; Segmentation of a Text without Spaces into Words

(defun viterbi-segment (text model)
  "The most probable segmentation of the string TEXT into words, under the
  unigram MODEL, by dynamic programming (the Viterbi algorithm); the
  second value is its probability."
  (let* ((n (length text))
         (best (make-array (+ n 1) :initial-element 0))
         (words (make-array (+ n 1) :initial-element "")))
    (setf (aref best 0) 1)
    (loop for i from 1 to n
          do (loop for j from 0 below i
                   do (let* ((w (subseq text j i))
                             (score (* (ngram-probability model (list w))
                                       (aref best j))))
                        (when (>= score (aref best i))
                          (setf (aref best i) score
                                (aref words i) w)))))
    ;; recover the sequence of the best words, from the end
    (let ((sequence nil) (i n))
      (loop while (> i 0)
            do (push (aref words i) sequence)
               (decf i (length (aref words i))))
      (values sequence (aref best n)))))
