;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/algorithms/pl-inference.lisp

;;;; Propositional Inference: Resolution and Forward Chaining

;;; The propositional algorithms of chapter 7 (this file, dpll.lisp,
;;; walksat.lisp and cdcl.lisp) work on clauses, i.e., lists of literals.
;;; A literal is an atom or (not atom); an atom is a symbol such as P12, but
;;; any other object compared with EQUAL, e.g., (Farmer Mac), works as well.
;;; So the sentence "(A | ~B) ^ C" has the clauses ((A (not B)) (C)).

;;;; Clauses and Literals

(defun pl-literal-atom (literal)
  "The atom of a literal: P for both P and (not P)."
  (if (pl-negative-literal-p literal) (arg1 literal) literal))

(defun pl-negative-literal-p (literal)
  (and (consp literal) (eq (op literal) 'not)))

(defun pl-negate-literal (literal)
  "Return the complement of a literal: (not P) for P, and P for (not P)."
  (if (pl-negative-literal-p literal) (arg1 literal) (list 'not literal)))

(defun pl-sentence->clauses (sentence)
  "Convert a sentence (in prefix or infix form) to a list of clauses,
  dropping the constants TRUE and FALSE and repeated literals."
  (let ((clauses nil))
    (dolist (conjunct (conjuncts (->cnf (logic sentence))))
      (let ((literals (remove 'false (disjuncts conjunct))))
	(unless (member 'true literals)
	  (push (remove-duplicates literals :test #'equal :from-end t)
		clauses))))
    (nreverse clauses)))

(defun pl-clauses-atoms (clauses)
  "The atoms that appear in the clauses, in order of first appearance."
  (let ((table (make-hash-table :test #'equal))
	(atoms nil))
    (dolist (clause clauses)
      (dolist (literal clause)
	(let ((atom (pl-literal-atom literal)))
	  (unless (gethash atom table)
	    (setf (gethash atom table) t)
	    (push atom atoms)))))
    (nreverse atoms)))

(defun pl-tautology-p (clause)
  "Does the clause contain a literal and its complement?"
  (some #'(lambda (literal)
	    (and (pl-negative-literal-p literal)
		 (member (arg1 literal) clause :test #'equal)))
	clause))

(defun pl-literal-value (literal model)
  "The truth value of a literal in a model (an alist of (atom . t-or-nil)
  pairs): T, NIL, or :UNKNOWN when its atom has no value."
  (let ((pair (assoc (pl-literal-atom literal) model :test #'equal)))
    (cond ((null pair) :unknown)
	  ((pl-negative-literal-p literal) (not (cdr pair)))
	  (t (if (cdr pair) t nil)))))

(defun pl-satisfies-p (model sentence)
  "Is every clause of the sentence true in the model (an alist as returned
  by DPLL-SATISFIABLE)?  Atoms with no value count as neither true nor false."
  (let ((model (if (listp model) model nil)))
    (every #'(lambda (clause)
	       (some #'(lambda (literal)
			 (eq (pl-literal-value literal model) t))
		     clause))
	   (pl-sentence->clauses sentence))))

;;;; Resolution [Fig. 7.13]

(defun pl-resolution (kb alpha)
  "Does the KB entail ALPHA?  Resolution refutation on the clauses of
  KB ^ ~ALPHA. [Fig. 7.13]  KB is a PROP-KB, a PROP-DEFINITE-KB or a
  sentence."
  ;; Each round only resolves the pairs with at least one clause added by
  ;; the previous round, since the older pairs gave nothing new.
  (let* ((kb-sentence (cond ((prop-kb-p kb) (prop-kb-sentence kb))
			    ((prop-definite-kb-p kb)
			     (cons 'and (prop-definite-kb-clauses kb)))
			    (t (logic kb))))
	 (clauses (make-array 0 :adjustable t :fill-pointer 0))
	 (seen (make-hash-table :test #'equal))
	 (start 0))
    (flet ((add (clause)
	     (let ((clause (pl-canonical-clause clause)))
	       (unless (or (pl-tautology-p clause) (gethash clause seen))
		 (setf (gethash clause seen) t)
		 (vector-push-extend clause clauses)
		 t))))
      (dolist (clause (pl-sentence->clauses
		       `(and ,kb-sentence (not ,(logic alpha)))))
	(when (null clause) (return-from pl-resolution t))
	(add clause))
      (loop
       (let ((n (length clauses))
	     (new nil))
	 (dotimes (j n)
	   (dotimes (i j)
	     (when (>= j start)
	       (dolist (resolvent (pl-resolve (aref clauses i) (aref clauses j)))
		 (when (null resolvent) (return-from pl-resolution t))
		 (push resolvent new)))))
	 (setf start n)
	 ;; If no resolvent is new, the clauses are saturated
	 (let ((added nil))
	   (dolist (clause (nreverse new))
	     (when (add clause) (setf added t)))
	   (unless added (return nil))))))))

(defun pl-resolve (ci cj)
  "Return all the clauses obtained by resolving clauses CI and CJ."
  (let ((resolvents nil))
    (dolist (di ci)
      (dolist (dj cj)
	(when (equal di (pl-negate-literal dj))
	  (push (union (remove di ci :test #'equal)
		       (remove dj cj :test #'equal)
		       :test #'equal)
		resolvents))))
    resolvents))

(defun pl-canonical-clause (clause)
  "The clause without repeated literals, sorted, so that EQUAL compares sets."
  (sort (remove-duplicates (copy-list clause) :test #'equal)
	#'string< :key #'prin1-to-string))

;;;; Forward Chaining [Fig. 7.15]

(defstructure prop-definite-kb
  "A KB of propositional definite clauses: atoms, and implications
  (=> (and P1 ... Pn) Q) with atoms P1 ... Pn and Q."
  (clauses nil))

(defmethod tell ((kb prop-definite-kb) sentence)
  "Add a definite clause to the KB."
  (let ((clause (logic sentence)))
    (unless (pl-definite-clause-p clause)
      (error "~A is not a definite clause." sentence))
    (setf (prop-definite-kb-clauses kb)
	  (append (prop-definite-kb-clauses kb) (list clause)))
    t))

(defmethod retract ((kb prop-definite-kb) sentence)
  (deletef (logic sentence) (prop-definite-kb-clauses kb) :test #'equal)
  t)

(defmethod ask-each ((kb prop-definite-kb) query fn)
  "Call FN once (with no bindings) if forward chaining proves the query."
  (when (pl-fc-entails kb query)
    (funcall fn +no-bindings+)))

(defun pl-premises (rule)
  "The atoms on the left of the implication RULE.  The infix reader nests
  binary conjunctions, as (and (and A B) C), so they are flattened."
  (labels ((flatten (s)
	     (if (eq (op s) 'and) (mappend #'flatten (args s)) (list s))))
    (flatten (arg1 rule))))

(defun pl-definite-clause-p (sentence)
  "Is the sentence an atom, or an implication from a conjunction of atoms
  to an atom?"
  (flet ((atom? (s) (and s (atomic-clause? s) (not (member s '(true false))))))
    (or (atom? sentence)
	(and (eq (op sentence) '=>)
	     (every #'atom? (pl-premises sentence))
	     (atom? (arg2 sentence))))))

(defun pl-fc-entails (kb q)
  "Does the KB of definite clauses entail the atom Q?  Forward chaining.
  [Fig. 7.15]  KB is a PROP-DEFINITE-KB or a list of definite clauses."
  (let* ((clauses (mapcar #'logic (if (prop-definite-kb-p kb)
				      (prop-definite-kb-clauses kb)
				    kb)))
	 (q (logic q))
	 (rules (remove-if-not #'(lambda (c) (eq (op c) '=>)) clauses))
	 (count (make-hash-table :test #'eq))
	 (inferred (make-hash-table :test #'equal))
	 (agenda (remove-if #'(lambda (c) (eq (op c) '=>)) clauses)))
    (dolist (rule rules)
      (setf (gethash rule count) (length (pl-premises rule))))
    (loop (when (null agenda) (return nil))
	  (let ((p (pop agenda)))
	    (when (equal p q) (return t))
	    (unless (gethash p inferred)
	      (setf (gethash p inferred) t)
	      (dolist (rule rules)
		(when (member p (pl-premises rule) :test #'equal)
		  (when (zerop (decf (gethash rule count)))
		    (push (arg2 rule) agenda)))))))))
