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

;;;; Decoding Shift and Substitution Ciphers with a Bigram Model of Letters

;;; Texts are canonicalized to lowercase letters and single spaces.  A
;;; bigram letter model counts the pairs of consecutive characters of a
;;; training text, with add-one smoothing over the 27 x 27 pairs of letters
;;; and space.

(defparameter *letters* "abcdefghijklmnopqrstuvwxyz")

(defun canonical-text (text)
  "TEXT in lowercase, with every run of characters other than the letters
  a-z replaced by one space, and no space at either end."
  (let ((space nil))
    (string-trim
     " "
     (with-output-to-string (out)
       (loop for c across text
             do (let ((lower (char-downcase c)))
                  (cond ((find lower *letters*)
                         (when space (write-char #\Space out))
                         (setf space nil)
                         (write-char lower out))
                        (t (setf space t)))))))))

(defun letter-index (c)
  "0 to 25 for the letters a to z, and 26 for the space."
  (or (position c *letters*) 26))

(defstruct (bigram-letter-model (:constructor new-bigram-letter-model))
  (counts (make-array '(27 27) :initial-element 0))
  (letter-counts (make-array 27 :initial-element 0))
  (total 0))

(defun make-bigram-letter-model (text)
  "The counts of the letters and of the bigrams of the canonical TEXT."
  (let ((text (canonical-text text))
        (model (new-bigram-letter-model)))
    (dotimes (i (length text) model)
      (incf (aref (bigram-letter-model-letter-counts model) (letter-index (char text i))))
      (when (< (+ i 1) (length text))
        (incf (aref (bigram-letter-model-counts model)
                    (letter-index (char text i)) (letter-index (char text (+ i 1)))))
        (incf (bigram-letter-model-total model))))))

(defun bigram-log-probability (model text)
  "log P(TEXT) under the bigram MODEL: the sum over the bigrams of the
  canonical TEXT of log((count + 1) / (total + 27^2))."
  (let ((counts (bigram-letter-model-counts model))
        (denominator (+ (bigram-letter-model-total model) 729)))
    (loop for i from 0 below (- (length text) 1)
          sum (log (/ (+ 1d0 (aref counts (letter-index (char text i))
                                   (letter-index (char text (+ i 1)))))
                      denominator)))))

;;;; Shift (Caesar) Ciphers

(defun shift-encode (text n)
  "Encode TEXT by moving each letter N letters forward in the alphabet."
  (map 'string #'(lambda (c)
                   (let ((i (position (char-downcase c) *letters*)))
                     (if i
                         (let ((d (char *letters* (mod (+ i n) 26))))
                           (if (upper-case-p c) (char-upcase d) d))
                       c)))
       text))

(defun rot13 (text)
  (shift-encode text 13))

(defun shift-decode (ciphertext model)
  "There are only 26 shift ciphers: try them all, and return the decoding of
  CIPHERTEXT that is the most probable under the bigram MODEL."
  (let* ((text (canonical-text ciphertext))
         (best (the-biggest #'(lambda (n) (bigram-log-probability model (shift-encode text n)))
                            (iota 26))))
    (shift-encode ciphertext best)))

;;;; Substitution (Permutation) Ciphers

;;; A key is a string of 26 letters: the letter i of the alphabet is
;;; replaced by the letter i of the key.

(defun substitute-letters (text key)
  "TEXT with each letter replaced through KEY."
  (map 'string #'(lambda (c)
                   (let ((i (position c *letters*)))
                     (if i (char key i) c)))
       text))

(defun letters-by-frequency (counts)
  "The 26 letters, by decreasing COUNTS (a function of a letter), ties in
  alphabetical order."
  (stable-sort (copy-seq *letters*) #'> :key counts))

(defun permutation-decode (ciphertext model)
  "Decode a substitution cipher, among the 26! keys, by local search: start
  from the key that maps the cipher letters to the letters of the same
  frequency rank in the training text of the bigram MODEL, then swap the
  images of two letters whenever that makes the decoded text more probable,
  until no swap does.  Returns the decoded text and the decoding key."
  (let* ((text (canonical-text ciphertext))
         (key (make-string 26 :initial-element #\a))
         (letter-counts (bigram-letter-model-letter-counts model)))
    (loop for c across (letters-by-frequency #'(lambda (c) (count c text)))
          for p across (letters-by-frequency
                        #'(lambda (c) (aref letter-counts (letter-index c))))
          do (setf (char key (letter-index c)) p))
    (let ((best (bigram-log-probability model (substitute-letters text key)))
          (improved t))
      (loop while improved
            do (setf improved nil)
               (dotimes (i 26)
                 (loop for j from (+ i 1) below 26
                       do (rotatef (char key i) (char key j))
                          (let ((score (bigram-log-probability
                                        model (substitute-letters text key))))
                            (if (> score (+ best 1e-9))
                                (setf best score
                                      improved t)
                              (rotatef (char key i) (char key j)))))))
      (values (substitute-letters text key) key))))
