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

;;;; Information Retrieval and the HITS Algorithm (Section 23.2 of the 3rd edition)

;;;; A Simple Information Retrieval System

;;; The index maps each word to an alist of (document-number . count); the
;;; score of a document for a query is the sum over the query words of
;;; log(1 + count) / log(1 + length of the document).

(defstruct (ir-system (:constructor new-ir-system))
  (index (make-hash-table :test #'equal))
  (stopwords nil)
  (documents (make-array 0 :adjustable t :fill-pointer t)))  ; (title url n-words)

(defun make-ir-system (&optional (stopwords "the a of"))
  (new-ir-system :stopwords (text-words stopwords)))

(defun index-document (system text url)
  "Index the words of TEXT, whose first line is its title."
  (let ((words (text-words text))
        (docid (length (ir-system-documents system))))
    (vector-push-extend (list (string-trim " " (subseq text 0 (or (position #\Newline text)
                                                                  (length text))))
                              url (length words))
                        (ir-system-documents system))
    (dolist (word words docid)
      (unless (member word (ir-system-stopwords system) :test #'string=)
        (let ((entry (assoc docid (gethash word (ir-system-index system)))))
          (if entry
              (incf (cdr entry))
            (push (cons docid 1) (gethash word (ir-system-index system)))))))))

(defun ir-document-url (system docid)
  (second (aref (ir-system-documents system) docid)))

(defun ir-score (system word docid)
  (let ((count (or (cdr (assoc docid (gethash word (ir-system-index system)))) 0)))
    (/ (log (+ 1 count))
       (log (+ 1 (third (aref (ir-system-documents system) docid)))))))

(defun ir-query (system query &optional (n 10))
  "The N best (score . docid) pairs for the words of QUERY that are not
  stopwords, among the documents that contain the rarest of them."
  (let ((qwords (remove-if #'(lambda (w) (member w (ir-system-stopwords system)
                                                 :test #'string=))
                           (text-words query))))
    (when qwords
      (let* ((rarest (the-smallest #'(lambda (w) (length (gethash w (ir-system-index system))))
                                   qwords))
             (results (mapcar #'(lambda (entry)
                                  (let ((docid (car entry)))
                                    (cons (sum qwords #'(lambda (w) (ir-score system w docid)))
                                          docid)))
                              (gethash rarest (ir-system-index system))))
             (sorted (sort results #'> :key #'car)))
        (subseq sorted 0 (min n (length sorted)))))))

;;;; Hubs and Authorities [the HITS algorithm]

(defstruct (page (:constructor new-page))
  address content (outlinks nil) (inlinks nil) (hub 1) (authority 1))

(defun make-web (specs)
  "Pages from a list of (address content outlink-addresses); the inlinks
  are computed from the outlinks."
  (let ((pages (mapcar #'(lambda (spec)
                           (new-page :address (first spec) :content (second spec)
                                     :outlinks (third spec)))
                       specs)))
    (dolist (p pages pages)
      (setf (page-inlinks p)
            (mapcar #'page-address
                    (remove-if-not #'(lambda (q) (member (page-address p) (page-outlinks q)
                                                       :test #'equal))
                                   pages))))))

(defun relevant-pages (query pages)
  "The pages whose content contains every word of QUERY."
  (remove-if-not #'(lambda (p)
                     (every #'(lambda (w) (search w (page-content p) :test #'char-equal))
                            (text-words query)))
                 pages))

(defun expand-pages (selected pages)
  "Add to SELECTED every page that links to or is linked from one of them."
  (remove-if-not #'(lambda (p)
                     (or (member p selected)
                         (some #'(lambda (q)
                                   (or (member (page-address p) (page-outlinks q)
                                               :test #'equal)
                                       (member (page-address p) (page-inlinks q)
                                               :test #'equal)))
                               selected)))
                 pages))

(defun normalize-pages (pages)
  "Divide the hub and the authority scores by the square root of the sum
  of their squares."
  (let ((h (sqrt (sum pages #'(lambda (p) (square (page-hub p))))))
        (a (sqrt (sum pages #'(lambda (p) (square (page-authority p)))))))
    (dolist (p pages)
      (unless (zerop h) (setf (page-hub p) (/ (page-hub p) h)))
      (unless (zerop a) (setf (page-authority p) (/ (page-authority p) a))))))

(defun hits (query pages &key (iterations 100) (epsilon 1e-6))
  "Compute the hub and authority scores of the pages relevant to QUERY and
  of their neighbors, until they converge; return those pages."
  (let ((selected (expand-pages (relevant-pages query pages) pages)))
    (flet ((page-named (address) (find address selected :key #'page-address :test #'equal)))
      (dolist (p selected)
        (setf (page-hub p) 1 (page-authority p) 1))
      (loop repeat iterations
            do (let ((old (mapcar #'(lambda (p) (cons (page-hub p) (page-authority p)))
                                  selected)))
                 ;; all the authorities from the hubs, then all the hubs
                 ;; from the new authorities
                 (let ((authorities
                         (mapcar #'(lambda (p)
                                     (sum (remove nil (mapcar #'page-named (page-inlinks p)))
                                          #'page-hub))
                                 selected)))
                   (mapc #'(lambda (p a) (setf (page-authority p) a)) selected authorities))
                 (let ((hubs
                         (mapcar #'(lambda (p)
                                     (sum (remove nil (mapcar #'page-named (page-outlinks p)))
                                          #'page-authority))
                                 selected)))
                   (mapc #'(lambda (p h) (setf (page-hub p) h)) selected hubs))
                 (normalize-pages selected)
                 (when (every #'(lambda (p ha)
                                  (and (< (abs (- (page-hub p) (car ha))) epsilon)
                                       (< (abs (- (page-authority p) (cdr ha))) epsilon)))
                              selected old)
                   (return))))
      selected)))
