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

;;;; Conflict-Driven Clause Learning (CDCL)

;;; A CDCL satisfiability solver (section 7.6.1 of the book mentions clause
;;; learning; the details follow aima-python's logic.py and the SAT
;;; literature): unit propagation with two watched literals, conflict
;;; analysis with the first unique implication point (1UIP), non-
;;; chronological backjumping, the VSIDS branching heuristic, and restart
;;; strategies.  CDCL-SATISFIABLE takes a sentence and returns a model (an
;;; alist of (atom . t-or-nil) pairs that gives a value to every atom), T for a
;;; satisfiable sentence with no atoms, or NIL if it is unsatisfiable.

;;; Inside the solver the atoms are numbered 1..n, and the literals are
;;; integers: 2v for atom v, and 2v+1 for its negation.  The first two
;;; literals of each clause of two or more literals are the watched ones; a
;;; clause is looked at only when one of them becomes false.

(defstruct cdcl-clause
  (lits #() :type simple-vector))

(defun cdcl-satisfiable (sentence &key (vsids-decay 0.95)
				       (restart-strategy #'no-restart)
				       (branching-heuristic nil))
  "Return a model of the sentence, or NIL if it is unsatisfiable.
  RESTART-STRATEGY is NO-RESTART, LUBY or GLUCOSE (or a function of the same
  arguments).  BRANCHING-HEURISTIC, if given, is one of the DPLL heuristics
  (e.g. MOMS or JW2), applied to the clauses not yet satisfied, in place of
  VSIDS."
  (cdcl-clauses-satisfiable (pl-sentence->clauses sentence)
			    :vsids-decay vsids-decay
			    :restart-strategy restart-strategy
			    :branching-heuristic branching-heuristic))

(defun cdcl-clauses-satisfiable (clauses &key (vsids-decay 0.95)
					      (restart-strategy #'no-restart)
					      (branching-heuristic nil))
  "CDCL-SATISFIABLE on a list of clauses."
  (let* ((atoms (pl-clauses-atoms clauses))
	 (n (length atoms))
	 (index (make-hash-table :test #'equal))
	 (atom-of (make-array (1+ n) :initial-element nil))
	 (value (make-array (1+ n) :initial-element 0)) ; 1, -1, or 0 if free
	 (level (make-array (1+ n) :initial-element 0))
	 (reason (make-array (1+ n) :initial-element nil))
	 (seen (make-array (1+ n) :initial-element nil))
	 (scores (make-array (+ 2 (* 2 n)) :initial-element 0d0))
	 (watches (make-array (+ 2 (* 2 n)) :initial-element nil))
	 (trail (make-array (max n 1) :fill-pointer 0))
	 (trail-lim nil)		; trail position where each level starts
	 (qhead 0)			; next trail literal to propagate
	 (current-level 0)
	 (all-clauses nil)		; the clause vectors, for the heuristic
	 (units nil)
	 (conflicts 0)
	 (restarts 1)
	 (sum-lbd 0)
	 (queue-lbd nil)
	 (active nil)			; the atoms with a VSIDS score
	 (cursor 1))			; no atom before it is free
    (when (zerop n)
      (return-from cdcl-clauses-satisfiable (if (member nil clauses) nil t)))
    (let ((v 0))
      (dolist (atom atoms)
	(setf (gethash atom index) (incf v)
	      (aref atom-of v) atom)))
    (labels
	((code (literal)
	   (let ((v (gethash (pl-literal-atom literal) index)))
	     (if (pl-negative-literal-p literal) (+ 1 v v) (+ v v))))
	 (decode (code)
	   (let ((atom (aref atom-of (ash code -1))))
	     (if (evenp code) atom (list 'not atom))))
	 (lit-value (code)
	   (let ((x (aref value (ash code -1))))
	     (if (evenp code) x (- x))))
	 (enqueue (code why)
	   (let ((v (ash code -1)))
	     (setf (aref value v) (if (evenp code) 1 -1)
		   (aref level v) current-level
		   (aref reason v) why)
	     (vector-push code trail)))
	 (watch (clause)
	   (let ((lits (cdcl-clause-lits clause)))
	     (push clause (aref watches (svref lits 0)))
	     (push clause (aref watches (svref lits 1)))))
	 (propagate ()
	   ;; Return a conflict clause, or NIL when no more unit clauses
	   (loop while (< qhead (fill-pointer trail)) do
	     (let* ((false-lit (logxor (aref trail qhead) 1))
		    (ws (aref watches false-lit)))
	       (incf qhead)
	       (setf (aref watches false-lit) nil)
	       (loop while ws do
		 (let* ((c (pop ws))
			(lits (cdcl-clause-lits c)))
		   ;; Make the false literal the second watched one
		   (when (= (svref lits 0) false-lit)
		     (rotatef (svref lits 0) (svref lits 1)))
		   (if (= (lit-value (svref lits 0)) 1)
		       (push c (aref watches false-lit)) ; clause already true
		     (let ((k (loop for k from 2 below (length lits)
				    unless (= (lit-value (svref lits k)) -1)
				    return k)))
		       (cond (k	; watch another literal that is not false
			      (rotatef (svref lits 1) (svref lits k))
			      (push c (aref watches (svref lits 1))))
			     (t
			      (push c (aref watches false-lit))
			      (if (= (lit-value (svref lits 0)) -1)
				  (progn ; conflict: keep the remaining watches
				    (dolist (c2 ws)
				      (push c2 (aref watches false-lit)))
				    (setf qhead (fill-pointer trail))
				    (return-from propagate c))
				(enqueue (svref lits 0) c))))))))))
	   nil)
	 (analyze (conflict)
	   ;; Return the learnt clause (its first literal is the asserting
	   ;; one, its second has the backjump level), the backjump level and
	   ;; the literal block distance (LBD) of the learnt clause.
	   (let ((learnt nil) (path-count 0) (p nil) (c conflict)
		 (i (1- (fill-pointer trail))))
	     (loop
	      (loop for q across (cdcl-clause-lits c) do
		(let ((v (ash q -1)))
		  (unless (or (and p (= v (ash p -1)))
			      (aref seen v)
			      (zerop (aref level v)))
		    (setf (aref seen v) t)
		    (if (= (aref level v) current-level)
			(incf path-count)
		      (push q learnt)))))
	      ;; The last assigned literal involved in the conflict
	      (loop (setf p (aref trail i))
		    (decf i)
		    (when (aref seen (ash p -1)) (return)))
	      (setf c (aref reason (ash p -1)))
	      (setf (aref seen (ash p -1)) nil)
	      (decf path-count)
	      (when (<= path-count 0) (return)))
	     (dolist (q learnt) (setf (aref seen (ash q -1)) nil))
	     (let* ((rest (sort learnt #'>
				:key #'(lambda (q) (aref level (ash q -1)))))
		    (lits (coerce (cons (logxor p 1) rest) 'simple-vector))
		    (bj (if rest (aref level (ash (first rest) -1)) 0))
		    (lbd (length (remove-duplicates
				  (map 'list #'(lambda (q) (aref level (ash q -1)))
				       lits)))))
	       (values lits bj lbd))))
	 (backjump (to-level)
	   (when (< to-level current-level)
	     (let ((start (nth (- current-level to-level 1) trail-lim)))
	       (loop for k from (1- (fill-pointer trail)) downto start do
		 (let ((v (ash (aref trail k) -1)))
		   (setf (aref value v) 0
			 (aref reason v) nil
			 cursor (min cursor v))))
	       (setf (fill-pointer trail) start
		     qhead start
		     trail-lim (nthcdr (- current-level to-level) trail-lim)
		     current-level to-level))))
	 (choose-literal ()
	   (or (and branching-heuristic (heuristic-literal))
	       ;; VSIDS: the free atom with the highest score of its literals;
	       ;; only the atoms in learnt clauses have a score, and among the
	       ;; others the first free one is taken
	       (let ((best nil) (best-score 0d0))
		 (dolist (v active)
		   (when (zerop (aref value v))
		     (let ((s (+ (aref scores (* 2 v))
				 (aref scores (1+ (* 2 v))))))
		       (when (or (> s best-score)
				 (and best (= s best-score) (< v best)))
			 (setf best v best-score s)))))
		 (unless best
		   (loop while (/= (aref value cursor) 0) do (incf cursor))
		   (setf best cursor))
		 (if (>= (aref scores (* 2 best)) (aref scores (1+ (* 2 best))))
		     (* 2 best)
		   (1+ (* 2 best))))))
	 (heuristic-literal ()
	   ;; Apply a DPLL heuristic to the clauses that are not yet true
	   (let ((open-clauses nil)
		 (symbols (loop for v from 1 to n
				when (zerop (aref value v))
				collect (aref atom-of v))))
	     (dolist (lits all-clauses)
	       (unless (some #'(lambda (q) (= (lit-value q) 1)) lits)
		 (push (loop for q across lits
			     when (zerop (lit-value q)) collect (decode q))
		       open-clauses)))
	     (multiple-value-bind (atom val)
		 (funcall branching-heuristic symbols (nreverse open-clauses))
	       (let ((v (and atom (gethash atom index))))
		 (when (and v (zerop (aref value v)))
		   (if val (* 2 v) (1+ (* 2 v)))))))))
      ;; Build the clause database
      (dolist (clause clauses)
	(let ((lits (remove-duplicates (mapcar #'code clause) :from-end t)))
	  (cond ((null lits)
		 (return-from cdcl-clauses-satisfiable nil))
		((some #'(lambda (q) (member (logxor q 1) lits)) lits)) ; tautology
		((null (rest lits)) (push (first lits) units))
		(t (let ((c (make-cdcl-clause
			     :lits (coerce lits 'simple-vector))))
		     (push (cdcl-clause-lits c) all-clauses)
		     (watch c))))))
      (dolist (q (nreverse units))
	(case (lit-value q)
	  (-1 (return-from cdcl-clauses-satisfiable nil))
	  (0 (enqueue q nil))))
      ;; The main loop
      (loop
       (let ((conflict (propagate)))
	 (cond
	  (conflict
	   (when (zerop current-level)
	     (return nil))
	   (incf conflicts)
	   (multiple-value-bind (lits bj lbd) (analyze conflict)
	     (push lbd queue-lbd)
	     (incf sum-lbd lbd)
	     (backjump bj)
	     (cond ((= (length lits) 1)
		    (enqueue (svref lits 0) nil))
		   (t (let ((c (make-cdcl-clause :lits lits)))
			(push lits all-clauses)
			(watch c)
			(enqueue (svref lits 0) c))))
	     (loop for q across lits do
	       (incf (aref scores q) 1d0)
	       (pushnew (ash q -1) active))
	     (dolist (v active)
	       (setf (aref scores (* 2 v)) (* (aref scores (* 2 v)) vsids-decay)
		     (aref scores (1+ (* 2 v)))
		     (* (aref scores (1+ (* 2 v))) vsids-decay)))
	     (when (funcall restart-strategy conflicts restarts queue-lbd sum-lbd)
	       (backjump 0)
	       (setf queue-lbd nil)
	       (incf restarts))))
	  ((= (fill-pointer trail) n)
	   (return (loop for v from 1 to n
			 collect (cons (aref atom-of v) (= (aref value v) 1)))))
	  (t (let ((q (choose-literal)))
	       (push (fill-pointer trail) trail-lim)
	       (incf current-level)
	       (enqueue q nil)))))))))

;;;; Restart Strategies

;;; Each takes the number of conflicts, the number of restarts (starting at
;;; 1), the LBDs of the clauses learnt since the last restart and the sum of
;;; all the LBDs, and says whether to restart now.

(defun no-restart (conflicts restarts queue-lbd sum-lbd)
  "Never restart."
  (declare (ignore conflicts restarts queue-lbd sum-lbd))
  nil)

(defun luby (conflicts restarts queue-lbd sum-lbd &optional (unit 512))
  "Restart after UNIT * L(i) conflicts, where L is the Luby sequence
  1 1 2 1 1 2 4 1 1 2 ... and i the number of restarts."
  (declare (ignore conflicts sum-lbd))
  (= (* unit (luby-sequence restarts)) (length queue-lbd)))

(defun luby-sequence (i)
  "The I-th term (from 1) of the Luby sequence."
  (do ((k 1 (1+ k)))
      (nil)
    (cond ((= i (1- (ash 1 k))) (return (ash 1 (1- k))))
	  ((<= (ash 1 (1- k)) i (- (ash 1 k) 2))
	   (return (luby-sequence (+ (- i (ash 1 (1- k))) 1)))))))

(defun glucose (conflicts restarts queue-lbd sum-lbd &optional (x 100) (k 0.7))
  "Glucose restarts: after at least X conflicts since the last restart,
  restart when K times the average LBD of the recent learnt clauses exceeds
  the average LBD of all of them."
  (declare (ignore restarts))
  (let ((len (length queue-lbd)))
    (and (>= len x)
	 (> (* (/ (reduce #'+ queue-lbd) len) k)
	    (/ sum-lbd conflicts)))))
