;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: learning/algorithms/foil.lisp

;;;; FOIL: Learning First-Order Horn Clauses (Inductive Logic Programming)

;;; The background knowledge is a list of ground facts such as
;;; (mother anne peter).  Variables are symbols that start with ?, the
;;; target is a literal such as (parent ?x ?y), and the examples are
;;; binding lists for its variables, such as ((?x . anne) (?y . peter)).
;;; A clause is (head . body), a list of literals meaning body => head.

(defun foil-variable? (x)
  (and (symbolp x) (> (length (symbol-name x)) 1) (char= (char (symbol-name x) 0) #\?)))

(defun foil-substitute (literal bindings)
  (mapcar #'(lambda (x) (let ((b (assoc x bindings))) (if b (cdr b) x))) literal))

(defun literal-variables (literal)
  (remove-duplicates (remove-if-not #'foil-variable? (rest literal))))

(defun extend-example (bindings literal background)
  "The extensions of BINDINGS that make LITERAL one of the BACKGROUND facts,
  binding the new variables of the literal in every possible way."
  (let ((pattern (foil-substitute literal bindings))
        (extensions nil))
    (dolist (fact background extensions)
      (when (and (eq (first fact) (first pattern))
                 (= (length fact) (length pattern)))
        (let ((b bindings) (ok t))
          (loop for p in (rest pattern)
                for c in (rest fact)
                while ok
                do (cond ((foil-variable? p)
                          (let ((old (assoc p b)))
                            (cond ((null old) (push (cons p c) b))
                                  ((not (eq (cdr old) c)) (setf ok nil)))))
                         ((not (eq p c)) (setf ok nil))))
          (when ok (pushnew b extensions :test #'equal)))))))

(defun extend-examples (examples literal background)
  (mapcan #'(lambda (e) (extend-example e literal background)) examples))

(defun background-predicates (background)
  "The (predicate . arity) pairs of the BACKGROUND facts."
  (remove-duplicates (mapcar #'(lambda (fact) (cons (first fact) (length (rest fact))))
                             background)
                     :test #'equal))

(defun new-literals (clause background)
  "The literals that may be added to the body of CLAUSE: a background
  predicate applied to variables of the clause and new variables, with at
  least one variable of the clause."
  (let* ((old (remove-duplicates (loop for l in clause append (literal-variables l))))
         (literals nil))
    (dolist (pa (background-predicates background) (reverse literals))
      (let ((new (loop for i from 1 below (cdr pa)
                       collect (intern (format nil "?V~D" (+ i (length old)))))))
        (dolist (args (cartesian-product (make-list (cdr pa) :initial-element
                                                    (append old new))))
          (when (and (intersection args old)
                     (not (member (cons (car pa) args) (rest clause) :test #'equal)))
            (push (cons (car pa) args) literals)))))))

(defun foil-gain (literal positive negative background)
  "The information gain of adding LITERAL, for the extended examples."
  (let* ((p0 (length positive))
         (n0 (length negative))
         (positive1 (extend-examples positive literal background))
         (p1 (length positive1))
         (n1 (length (extend-examples negative literal background)))
         (covered (count-if #'(lambda (e) (extend-example e literal background)) positive)))
    (if (zerop p1)
        nil
      (* covered (- (log (/ p1 (+ p1 n1)) 2) (log (/ p0 (+ p0 n0)) 2))))))

(defun new-clause (positive negative target background &key (max-length 4))
  "Grow a clause for TARGET, adding the literal of highest gain until it
  covers no negative example (or reaches MAX-LENGTH literals)."
  (let ((clause (list target)))
    (loop while (and negative (< (length (rest clause)) max-length))
          do (let ((best nil) (best-gain nil))
               (dolist (l (new-literals clause background))
                 (let ((gain (foil-gain l positive negative background)))
                   (when (and gain (or (null best-gain) (> gain best-gain)))
                     (setf best l best-gain gain))))
               (unless best (return))
               (setf clause (append clause (list best))
                     positive (extend-examples positive best background)
                     negative (extend-examples negative best background))))
    clause))

(defun clause-covers? (clause bindings background)
  "Can BINDINGS be extended to satisfy every literal of the body of CLAUSE?"
  (let ((extensions (list bindings)))
    (dolist (literal (rest clause) (and extensions t))
      (setf extensions (extend-examples extensions literal background)))))

(defun foil (positive negative target background)
  "Learn a set of Horn clauses for TARGET that cover the POSITIVE examples
  and none of the NEGATIVE ones."
  (let ((clauses nil))
    (loop while positive
          do (let* ((clause (new-clause positive negative target background))
                    (covered (remove-if-not
                              #'(lambda (e) (clause-covers? clause e background))
                              positive)))
               (unless covered (return))
               (setf positive (set-difference positive covered :test #'equal))
               (push clause clauses)))
    (reverse clauses)))

(defun clause-facts (clause background)
  "The ground instances of the head of CLAUSE that the BACKGROUND proves."
  (remove-duplicates
   (mapcar #'(lambda (bindings) (foil-substitute (first clause) bindings))
           (let ((extensions (list nil)))
             (dolist (literal (rest clause) extensions)
               (setf extensions (extend-examples extensions literal background)))))
   :test #'equal))
