;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/algorithms/fol-resolution.lisp

;;;; First-Order Resolution, Demodulation and Paramodulation

;;; The resolution prover of section 9.5, written next to the unfinished one
;;; of fol.lisp (PROVE-BY-REFUTATION).  Clauses are lists of literals, as in
;;; pl-inference.lisp; their variables ($x, ...) are implicitly universally
;;; quantified, and Skolem functions stand for the existential ones.  The
;;; equality predicate is written Equal(x,y) or x = y.

;;;; Clauses

(defun fol-sentence->clauses (sentence)
  "Convert a sentence to a list of clauses."
  (mapcar #'(lambda (c) (fol-make-clause (disjuncts c)))
	  (conjuncts (->cnf (logic sentence)))))

(defun fol-make-clause (literals)
  "A clause of the literals, without repeated ones, in their order."
  (remove-duplicates literals :test #'equal :from-end t))

(defun fol-clause->sentence (clause)
  (disjunction clause))

(defun fol-canonical-key (clause)
  "A string that is the same for clauses that differ only in the order of
  their literals and the names of their variables."
  (let* ((sorted (sort (copy-list clause) #'string<
		       :key #'(lambda (literal)
				(prin1-to-string
				 (subst-if '? #'variable? literal)))))
	 (names nil))
    (labels ((rename (x)
	       (cond ((variable? x)
		      (or (cdr (assoc x names))
			  (let ((name (format nil "V~D" (length names))))
			    (push (cons x name) names)
			    name)))
		     ((consp x) (cons (rename (car x)) (rename (cdr x))))
		     (t x))))
      (prin1-to-string (rename sorted)))))

(defun fol-equality-p (atom)
  "Is the atom an equality, Equal(x,y) or x = y?"
  (and (consp atom) (member (op atom) '(= equal))
       (= (length (args atom)) 2)))

;;;; Resolution

(defun fol-resolvents (ci cj)
  "All the binary resolvents of clauses CI and CJ, after renaming the
  variables of CJ apart from those of CI."
  (let ((cj (rename-variables cj))
	(resolvents nil))
    (dolist (li ci)
      (dolist (lj cj)
	(when (not (eq (pl-negative-literal-p li) (pl-negative-literal-p lj)))
	  (let ((theta (unify (pl-literal-atom li) (pl-literal-atom lj))))
	    (when theta
	      (push (fol-make-clause
		     (subst-bindings theta
				     (append (remove li ci :count 1 :test #'eq)
					     (remove lj cj :count 1 :test #'eq))))
		    resolvents))))))
    resolvents))

(defun fol-factors (clause)
  "The factors of a clause: two literals of the same sign that unify
  become one."
  (let ((factors nil))
    (loop for (li . others) on clause do
	  (dolist (lj others)
	    (when (eq (pl-negative-literal-p li) (pl-negative-literal-p lj))
	      (let ((theta (unify li lj)))
		(when theta
		  (push (fol-make-clause (subst-bindings theta clause))
			factors))))))
    factors))

(defun fol-resolution (sentences query &key (equality nil) (max-clauses 5000))
  "Prove the conjunction of literals QUERY from SENTENCES (a list of
  sentences, usually clauses) by resolution refutation.  The negated query
  is the set of support: each step resolves its shortest clause with the
  others (unit preference), and each new clause is factored.  With EQUALITY,
  paramodulation is used too, and ~Equal(s,t) is dropped when s and t unify.
  Return T when the empty clause is derived, NIL when the clauses are
  saturated or MAX-CLAUSES have been generated. [Section 9.5]"
  (let* ((usable (remove-if #'pl-tautology-p
			    (mappend #'fol-sentence->clauses sentences)))
	 (seen (make-hash-table :test #'equal))
	 (negated (fol-make-clause (mapcar #'pl-negate-literal
					   (conjuncts (logic query)))))
	 (support (list negated)))
    (dolist (c usable) (setf (gethash (fol-canonical-key c) seen) t))
    (setf (gethash (fol-canonical-key negated) seen) t)
    (loop
     (when (null support) (return nil))
     (setf support (stable-sort support #'< :key #'length))
     (let ((given (pop support))
	   (new nil))
       (dolist (other (append usable (list given)))
	 (setf new (nconc (fol-resolvents given other) new))
	 (when equality
	   (setf new (nconc (fol-paramodulants given other)
			    (fol-paramodulants other given)
			    new))))
       (when equality
	 (dolist (literal given)
	   (when (and (pl-negative-literal-p literal)
		      (fol-equality-p (arg1 literal)))
	     (let ((theta (unify (arg1 (arg1 literal)) (arg2 (arg1 literal)))))
	       (when theta
		 (push (fol-make-clause
			(subst-bindings theta (remove literal given :test #'eq)))
		       new))))))
       (setf usable (append usable (list given)))
       (dolist (c new)
	 (when (null c) (return-from fol-resolution t))
	 (dolist (d (cons c (fol-factors c)))
	   (let ((key (fol-canonical-key d)))
	     (unless (or (gethash key seen) (pl-tautology-p d))
	       (setf (gethash key seen) t)
	       (setf support (append support (list d)))))))
       (when (> (hash-table-count seen) max-clauses)
	 (return nil))))))

;;;; Subsumption [Section 9.5.6]

(defun fol-subsumes? (c d)
  "Does clause C subsume clause D, i.e., is there a substitution theta such
  that every literal of C theta is in D?  Then D is redundant next to C.
  The variables of D are treated as constants."
  (labels ((match-all (literals bindings)
	     (if (null literals)
		 t
	       (some #'(lambda (literal)
			 (let ((b (fol-match (first literals) literal bindings)))
			   (and (not (eq b +fail+))
				(match-all (rest literals) b))))
		     d))))
    (match-all (rename-variables c) +no-bindings+)))

;;;; Demodulation and Paramodulation [Section 9.5.5]

(defun fol-subterms (x &optional path)
  "A list of (path . subterm) for each constant or compound term inside the
  arguments of X; a path is the list of argument positions leading there."
  (let ((result nil))
    (loop for arg in (args x)
	  for k from 0 do
	  (unless (variable? arg)
	    (let ((p (append path (list k))))
	      (push (cons p arg) result)
	      (when (consp arg)
		(setf result (append (reverse (fol-subterms arg p)) result))))))
    (nreverse result)))

(defun fol-replace-at (x path new)
  "X with the subterm at PATH replaced by NEW."
  (if (null path)
      new
    (cons (op x)
	  (loop for arg in (args x)
		for k from 0
		collect (if (= k (first path))
			    (fol-replace-at arg (rest path) new)
			  arg)))))

(defun fol-match (pattern term &optional (bindings +no-bindings+))
  "One-way unification: bindings for the variables of PATTERN only that make
  it equal to TERM, or +fail+."
  (cond ((eq bindings +fail+) +fail+)
	((variable? pattern)
	 (let ((binding (get-binding pattern bindings)))
	   (cond ((null binding) (extend-bindings pattern term bindings))
		 ((equal (binding-val binding) term) bindings)
		 (t +fail+))))
	((and (consp pattern) (consp term))
	 (fol-match (rest pattern) (rest term)
		    (fol-match (first pattern) (first term) bindings)))
	((equal pattern term) bindings)
	(t +fail+)))

(defun fol-literal-with-atom (literal atom)
  "LITERAL with its atom replaced by ATOM, keeping the sign."
  (if (pl-negative-literal-p literal) (list 'not atom) atom))

(defun demodulate (equation clause)
  "Demodulation: rewrite each subterm of CLAUSE that is an instance of the
  left side of the unit EQUATION, Equal(x,z), with the matching instance of
  its right side, until none is left.  Return the new clause as a sentence.
  [Section 9.5.5]"
  (let* ((equation (logic equation))
	 (x (arg1 equation))
	 (z (arg2 equation))
	 (clause (disjuncts (logic clause))))
    (loop repeat 1000 do
      (let ((changed nil))
	(setf clause
	      (mapcar #'(lambda (literal)
			  (let ((a (pl-literal-atom literal)))
			    (dolist (p+term (fol-subterms a))
			      (let ((theta (fol-match x (cdr p+term))))
				(when theta
				  (setf a (fol-replace-at a (car p+term)
							  (subst-bindings theta z))
					changed t)
				  (return))))
			    (fol-literal-with-atom literal a)))
		      clause))
	(unless changed (return))))
    (fol-clause->sentence (fol-make-clause clause))))

(defun paramodulate (c1 c2)
  "Paramodulation: for each literal Equal(x,z) of clause C1 and each
  subterm of clause C2 that unifies with x, the clause of the other literals
  of C1 and of C2 with that subterm replaced by z, under the unifier; and the
  same with x and z swapped.  Return the list of new clauses as sentences.
  [Section 9.5.5]"
  (mapcar #'fol-clause->sentence
	  (fol-paramodulants (disjuncts (logic c1)) (disjuncts (logic c2)))))

(defun fol-paramodulants (c1 c2)
  "PARAMODULATE on clauses (lists of literals)."
  (let ((c2 (rename-variables c2))
	(results nil))
    (dolist (eq-literal c1)
      (when (and (not (pl-negative-literal-p eq-literal))
		 (fol-equality-p eq-literal))
	(let ((others1 (remove eq-literal c1 :count 1 :test #'eq)))
	  (dolist (x+z (list (args eq-literal) (reverse (args eq-literal))))
	    (destructuring-bind (x z) x+z
	      (dolist (literal c2)
		(let ((a (pl-literal-atom literal)))
		  (dolist (p+term (fol-subterms a))
		    (let ((theta (unify x (cdr p+term))))
		      (when theta
			(let ((new (fol-literal-with-atom
				    literal (fol-replace-at a (car p+term) z))))
			  (push (fol-make-clause
				 (subst-bindings
				  theta
				  (append others1
					  (substitute new literal c2
						      :count 1 :test #'eq))))
				results))))))))))))
    (nreverse results)))
