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

;;;; Probabilistic Parsing: the CYK Algorithm [Figure 23.5], and Parse Trees

;;; A probabilistic context-free grammar in Chomsky Normal Form has
;;; lexical rules (X word p), for X -> word [p], and grammar rules
;;; (X Y Z p), for X -> Y Z [p].  A parse tree is (X word) or (X left right).

(defstruct pcfg
  (lexicon nil)
  (rules nil)
  (start-symbol 'S))

(defun pcfg-lexical-rules (grammar word)
  "The (category . probability) pairs of the lexical rules for WORD."
  (mapcar #'(lambda (rule) (cons (first rule) (third rule)))
          (remove-if-not #'(lambda (rule) (eq (second rule) word))
                         (pcfg-lexicon grammar))))

(defun subspans (n)
  "The (i j k) triples, 0-based, for building a span i..k from the spans
  i..j and j+1..k, shortest spans first."
  (loop for length from 2 to n
        nconc (loop for i from 0 to (- n length)
                    nconc (let ((k (+ i length -1)))
                            (loop for j from i below k collect (list i j k))))))

(defun cyk-parse (words grammar)
  "Return a table T where T[(X i k)] is the most probable parse tree of
  category X that spans the words i..k (0-based), and, as a second value,
  the table P of the probabilities of those trees."
  (let ((tt (make-hash-table :test #'equal))
        (p (make-hash-table :test #'equal)))
    (flet ((prob (x i k) (gethash (list x i k) p 0)))
      ;; insert the lexical categories of each word
      (loop for word in words
            for i from 0
            do (dolist (xp (pcfg-lexical-rules grammar word))
                 (setf (gethash (list (car xp) i i) p) (cdr xp)
                       (gethash (list (car xp) i i) tt) (list (car xp) word))))
      ;; combine spans i..j and j+1..k into i..k, shortest spans first
      (dolist (ijk (subspans (length words)))
        (destructuring-bind (i j k) ijk
          (dolist (rule (pcfg-rules grammar))
            (destructuring-bind (x y z rule-p) rule
              (let ((pyz (* (prob y i j) (prob z (+ j 1) k) rule-p)))
                (when (> pyz (prob x i k))
                  (setf (gethash (list x i k) p) pyz
                        (gethash (list x i k) tt)
                        (list x (gethash (list y i j) tt)
                              (gethash (list z (+ j 1) k) tt))))))))))
    (values tt p)))

(defun cyk-best-parse (words grammar)
  "The most probable parse tree of the whole sentence, and its probability;
  NIL and 0 if the grammar does not generate WORDS."
  (multiple-value-bind (tt p) (cyk-parse words grammar)
    (let ((key (list (pcfg-start-symbol grammar) 0 (- (length words) 1))))
      (values (gethash key tt) (gethash key p 0)))))

;;;; Treebank Trees [Figure 23.8]

;;; A treebank tree is (label child ...), where a child is a tree or a word
;;; (a string).  A trace such as "*-1" stands for the constituent whose
;;; label ends in -1.

(defun trace? (word)
  (and (stringp word) (> (length word) 0) (char= (char word 0) #\*)))

(defun tree-words (tree)
  "The words of TREE, from left to right, without the traces."
  (cond ((stringp tree) (if (trace? tree) nil (list tree)))
        (t (mapcan #'tree-words (rest tree)))))

(defun label-index (label)
  "The index N of a label of the form X-N (e.g., NP-2), or NIL."
  (let* ((name (symbol-name label))
         (dash (position #\- name :from-end t)))
    (and dash (< (+ dash 1) (length name))
         (every #'digit-char-p (subseq name (+ dash 1)))
         (parse-integer name :start (+ dash 1)))))

(defun tree-traces (tree)
  "An alist that maps each index N to the words of the constituent
  labeled X-N, the antecedent of the traces *-N, sorted by index."
  (let ((traces nil))
    (labels ((walk (tree)
               (unless (stringp tree)
                 (let ((index (label-index (first tree))))
                   (when index (push (cons index (tree-words tree)) traces)))
                 (mapc #'walk (rest tree)))))
      (walk tree))
    (sort traces #'< :key #'car)))
