;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/agents/hybrid-wumpus-agent.lisp

;;;; A Hybrid Agent for the Wumpus World

;;; The agent of [Fig. 7.20] keeps a propositional KB with the wumpus world
;;; axioms of section 7.7 and asks it, by satisfiability, which squares are
;;; safe, where it is, and where the wumpus may be; it plans its routes with
;;; A* search.  It runs in the wumpus world of agents/environments/wumpus.lisp,
;;; whose N x N cave is surrounded by walls (so the default 6 x 6 grid holds
;;; the 4 x 4 cave of the book), with percepts (stench breeze glitter bump
;;; sound) and the actions FORWARD, (TURN LEFT), (TURN RIGHT), GRAB, SHOOT
;;; and CLIMB.  Square [x,y] is at grid location (x y), and the agent starts in
;;; [1,1] facing east, i.e., towards increasing x.

;;; The propositions are symbols named as in the book: P31 (pit in [3,1]),
;;; W13, B21 (breeze in [2,1]), S12, and, at time t, L11_t (the agent is in
;;; [1,1]), OK21_t, FacingEast_t, HaveArrow_t, WumpusAlive_t, Stench_t,
;;; Breeze_t, Glitter_t, Bump_t, Scream_t, Forward_t, TurnLeft_t,
;;; TurnRight_t, Shoot_t.

(defstructure (hybrid-wumpus-agent
   (:include wumpus-agent (program (make-hybrid-wumpus-agent-program))))
  "An agent that reasons with a propositional KB and plans its routes with
  A* search. [Fig. 7.20]")

;;;; The Wumpus KB

(defstructure wumpus-kb
  "A propositional KB for the N x N wumpus world, kept as a list of clauses.
  ASK is by refutation: KB entails a literal iff KB plus its negation is
  unsatisfiable for SAT-SOLVER, a function of a list of clauses such as
  CDCL-CLAUSES-SATISFIABLE or DPLL-CLAUSES-SATISFIABLE."
  (n 4)
  (clauses nil)
  (sat-solver #'cdcl-clauses-satisfiable))

(defparameter *wumpus-headings* '(east north west south)
  "The headings in counterclockwise order, i.e., the order of left turns.")

(defun wumpus-heading-delta (heading)
  (ecase heading (east '(1 0)) (north '(0 1)) (west '(-1 0)) (south '(0 -1))))

(defun wumpus-turn (heading direction)
  "The heading after turning LEFT or RIGHT."
  (let ((i (position heading *wumpus-headings*)))
    (nth (mod (+ i (if (eq direction 'left) 1 -1)) 4) *wumpus-headings*)))

(defun wumpus-symbol (name &optional x y (time nil))
  "The proposition NAME, NAMExy, NAME_t or NAMExy_t."
  (intern (format nil "~A~@[~D~]~@[~D~]~@[_~D~]" name x y time) :cl-user))

(defun wumpus-facing-symbol (heading time)
  (wumpus-symbol (ecase heading
		   (east "FACINGEAST") (north "FACINGNORTH")
		   (west "FACINGWEST") (south "FACINGSOUTH"))
		 nil nil time))

(defun wumpus-kb-squares (kb)
  (let ((squares nil) (n (wumpus-kb-n kb)))
    (loop for x from 1 to n do
	  (loop for y from 1 to n do (push (list x y) squares)))
    (nreverse squares)))

(defun wumpus-kb-neighbors (kb x y)
  (let ((n (wumpus-kb-n kb)))
    (remove-if-not #'(lambda (sq) (and (<= 1 (first sq) n) (<= 1 (second sq) n)))
		   (list (list (1- x) y) (list (1+ x) y)
			 (list x (1- y)) (list x (1+ y))))))

(defun wumpus-kb-tell-clause (kb &rest literals)
  (push literals (wumpus-kb-clauses kb)))

(defun wumpus-kb-tell-equiv (kb head disjuncts)
  "Tell HEAD <=> (C1 v ... v Cn), where each Ci is a list of literals (a
  conjunction).  A conjunction of two or more literals gets a new symbol Ai
  with Ai => Ci, so that the clauses stay linear in size; this keeps the
  entailed sentences over the original symbols the same."
  (let ((aux-literals nil))
    (dolist (conjunction disjuncts)
      ;; Ci => HEAD
      (push (cons head (mapcar #'pl-negate-literal conjunction))
	    (wumpus-kb-clauses kb))
      (if (length=1 conjunction)
	  (push (first conjunction) aux-literals)
	(let ((aux (make-symbol "A")))
	  (push aux aux-literals)
	  (dolist (literal conjunction)
	    (wumpus-kb-tell-clause kb (list 'not aux) literal)))))
    ;; HEAD => A1 v ... v An
    (push (cons (list 'not head) aux-literals) (wumpus-kb-clauses kb))))

(defun wumpus-kb-ask (kb literal)
  "Does the KB entail the literal?"
  (not (funcall (wumpus-kb-sat-solver kb)
		(cons (list (pl-negate-literal literal)) (wumpus-kb-clauses kb)))))

(defun wumpus-kb-tell-atemporal (kb)
  "Tell the axioms that do not depend on time, and the state at time 0."
  (let ((squares (wumpus-kb-squares kb)))
    (wumpus-kb-tell-clause kb '(not P11))
    (wumpus-kb-tell-clause kb '(not W11))
    (dolist (sq squares)
      (destructuring-bind (x y) sq
	(let ((neighbors (wumpus-kb-neighbors kb x y)))
	  (wumpus-kb-tell-equiv kb (wumpus-symbol "B" x y)
				(mapcar #'(lambda (nb)
					    (list (wumpus-symbol "P" (first nb)
								 (second nb))))
					neighbors))
	  (wumpus-kb-tell-equiv kb (wumpus-symbol "S" x y)
				(mapcar #'(lambda (nb)
					    (list (wumpus-symbol "W" (first nb)
								 (second nb))))
					neighbors)))))
    ;; There is exactly one wumpus
    (push (mapcar #'(lambda (sq) (wumpus-symbol "W" (first sq) (second sq)))
		  squares)
	  (wumpus-kb-clauses kb))
    (loop for (sq1 . others) on squares do
	  (dolist (sq2 others)
	    (wumpus-kb-tell-clause
	     kb (list 'not (wumpus-symbol "W" (first sq1) (second sq1)))
	     (list 'not (wumpus-symbol "W" (first sq2) (second sq2))))))
    ;; The state at time 0
    (dolist (sq squares)
      (let ((l (wumpus-symbol "L" (first sq) (second sq) 0)))
	(wumpus-kb-tell-clause kb (if (equal sq '(1 1)) l (list 'not l)))))
    (dolist (heading *wumpus-headings*)
      (let ((f (wumpus-facing-symbol heading 0)))
	(wumpus-kb-tell-clause kb (if (eq heading 'east) f (list 'not f)))))
    (wumpus-kb-tell-clause kb (wumpus-symbol "HAVEARROW" nil nil 0))
    (wumpus-kb-tell-clause kb (wumpus-symbol "WUMPUSALIVE" nil nil 0))))

(defun wumpus-kb-tell-percept (kb percept time)
  "Tell the percept (stench breeze glitter bump sound) at TIME."
  (loop for value in percept
	for name in '("STENCH" "BREEZE" "GLITTER" "BUMP" "SCREAM")
	do (let ((p (wumpus-symbol name nil nil time)))
	     (wumpus-kb-tell-clause kb (if value p (list 'not p))))))

(defun wumpus-kb-tell-action (kb action time)
  "Tell which of the actions FORWARD, SHOOT, (TURN LEFT) and (TURN RIGHT)
  was done at TIME."
  (loop for a in '(forward shoot (turn left) (turn right))
	for name in '("FORWARD" "SHOOT" "TURNLEFT" "TURNRIGHT")
	do (let ((p (wumpus-symbol name nil nil time)))
	     (wumpus-kb-tell-clause kb (if (equal a action) p (list 'not p))))))

(defun wumpus-kb-tell-physics (kb time)
  "Tell the axioms that relate the percepts at TIME to the squares and, for
  TIME > 0, the successor-state axioms from TIME - 1 to TIME."
  (let ((n (wumpus-kb-n kb))
	(alive (wumpus-symbol "WUMPUSALIVE" nil nil time)))
    (flet ((neg (p) (list 'not p)))
      (dolist (sq (wumpus-kb-squares kb))
	(destructuring-bind (x y) sq
	  (let ((l (wumpus-symbol "L" x y time))
		(p (wumpus-symbol "P" x y))
		(w (wumpus-symbol "W" x y)))
	    ;; L_xy^t => (Breeze^t <=> B_xy) and (Stench^t <=> S_xy)
	    (dolist (pair '(("BREEZE" . "B") ("STENCH" . "S")))
	      (let ((percept (wumpus-symbol (car pair) nil nil time))
		    (fact (wumpus-symbol (cdr pair) x y)))
		(wumpus-kb-tell-clause kb (neg l) (neg percept) fact)
		(wumpus-kb-tell-clause kb (neg l) percept (neg fact))))
	    ;; OK_xy^t <=> ~P_xy ^ ~(W_xy ^ WumpusAlive^t)
	    (wumpus-kb-tell-equiv kb (wumpus-symbol "OK" x y time)
				  (list (list (neg p) (neg w))
					(list (neg p) (neg alive))))
	    ;; The successor-state axiom for the location
	    (when (> time 0)
	      (let* ((u (1- time))
		     (forward (wumpus-symbol "FORWARD" nil nil u))
		     (l-before (wumpus-symbol "L" x y u))
		     (disjuncts
		      (list (list l-before (neg forward))
			    (list l-before (wumpus-symbol "BUMP" nil nil time)))))
		(dolist (heading *wumpus-headings*)
		  (destructuring-bind (dx dy) (wumpus-heading-delta heading)
		    (let ((sx (- x dx)) (sy (- y dy)))
		      (when (and (<= 1 sx n) (<= 1 sy n))
			(push (list (wumpus-symbol "L" sx sy u)
				    (wumpus-facing-symbol heading u)
				    forward)
			      disjuncts)))))
		(wumpus-kb-tell-equiv kb l disjuncts))))))
      (when (> time 0)
	(let ((u (1- time))
	      (left (wumpus-symbol "TURNLEFT" nil nil (1- time)))
	      (right (wumpus-symbol "TURNRIGHT" nil nil (1- time))))
	  ;; The orientation
	  (dolist (heading *wumpus-headings*)
	    (wumpus-kb-tell-equiv
	     kb (wumpus-facing-symbol heading time)
	     (list (list (wumpus-facing-symbol (wumpus-turn heading 'right) u)
			 left)
		   (list (wumpus-facing-symbol (wumpus-turn heading 'left) u)
			 right)
		   (list (wumpus-facing-symbol heading u) (neg left) (neg right)))))
	  ;; The arrow and the wumpus
	  (wumpus-kb-tell-equiv kb (wumpus-symbol "HAVEARROW" nil nil time)
				(list (list (wumpus-symbol "HAVEARROW" nil nil u)
					    (neg (wumpus-symbol "SHOOT" nil nil u)))))
	  (wumpus-kb-tell-equiv kb alive
				(list (list (wumpus-symbol "WUMPUSALIVE" nil nil u)
					    (neg (wumpus-symbol "SCREAM" nil nil
								time))))))))))

;;;; The Agent Program [Fig. 7.20]

(defun make-hybrid-wumpus-agent-program (&key (n 4)
					      (sat-solver
					       #'cdcl-clauses-satisfiable))
  "Return the program of a hybrid agent for an N x N wumpus world."
  (let ((kb (make-wumpus-kb :n n :sat-solver sat-solver))
	(time 0)
	(plan nil)
	(pose (list 1 1 'east))		; (x y heading)
	(visited nil)
	(safe nil))
    (wumpus-kb-tell-atemporal kb)
    #'(lambda (percept)
	(wumpus-kb-tell-percept kb percept time)
	(wumpus-kb-tell-physics kb time)
	(setf pose (wumpus-kb-locate kb pose time))
	(pushnew (subseq pose 0 2) visited :test #'equal)
	(let ((squares (wumpus-kb-squares kb)))
	  (dolist (sq squares)
	    (unless (member sq safe :test #'equal)
	      (when (wumpus-kb-ask kb (wumpus-symbol "OK" (first sq) (second sq)
						     time))
		(push sq safe))))
	  (when (wumpus-kb-ask kb (wumpus-symbol "GLITTER" nil nil time))
	    (setf plan (append '(grab)
			       (wumpus-plan-route pose '((1 1)) safe)
			       '(climb))))
	  (let ((unvisited (set-difference squares visited :test #'equal)))
	    (when (null plan)
	      (setf plan (wumpus-plan-route
			  pose (intersection unvisited safe :test #'equal) safe)))
	    (when (and (null plan)
		       (wumpus-kb-ask kb (wumpus-symbol "HAVEARROW" nil nil time)))
	      (let ((possible-wumpus
		     (remove-if #'(lambda (sq)
				    (wumpus-kb-ask kb (list 'not (wumpus-symbol
								  "W" (first sq)
								  (second sq)))))
				squares)))
		(setf plan (wumpus-plan-shot pose possible-wumpus safe n))))
	    (when (null plan)
	      (let ((not-unsafe
		     (remove-if #'(lambda (sq)
				    (wumpus-kb-ask kb (list 'not (wumpus-symbol
								  "OK" (first sq)
								  (second sq)
								  time))))
				unvisited)))
		(setf plan (wumpus-plan-route pose not-unsafe safe))))
	    (when (null plan)
	      (setf plan (append (wumpus-plan-route pose '((1 1)) safe)
				 '(climb))))))
	(let ((action (pop plan)))
	  (wumpus-kb-tell-action kb action time)
	  (incf time)
	  action))))

(defun wumpus-kb-locate (kb pose time)
  "The pose (x y heading) at TIME, asked to the KB; the squares near the
  previous pose are asked first.  If the KB does not entail one, keep POSE."
  (destructuring-bind (x y heading) pose
    (let* ((squares (wumpus-kb-squares kb))
	   (ahead (mapcar #'+ (list x y) (wumpus-heading-delta heading)))
	   (candidates (remove-duplicates
			(append (list (list x y) ahead) squares)
			:test #'equal :from-end t))
	   (square (or (find-if #'(lambda (sq)
				    (and (member sq squares :test #'equal)
					 (wumpus-kb-ask
					  kb (wumpus-symbol "L" (first sq)
							    (second sq) time))))
				candidates)
		       (list x y)))
	   (new-heading
	    (or (find-if #'(lambda (h)
			     (wumpus-kb-ask kb (wumpus-facing-symbol h time)))
			 (cons heading (remove heading *wumpus-headings*)))
		heading)))
      (list (first square) (second square) new-heading))))

;;;; Planning Routes and Shots with A* Search

(defstructure (wumpus-route-problem (:include problem))
  "Find a sequence of actions from a pose (x y heading) to one of the GOALS,
  squares (x y) or poses (x y heading), moving only through the ALLOWED
  squares (or the goal squares)."
  (goals nil)
  (allowed nil))

(defmethod successors ((problem wumpus-route-problem) state)
  (destructuring-bind (x y heading) state
    (let* ((ahead (mapcar #'+ (list x y) (wumpus-heading-delta heading)))
	   (result (list (cons '(turn left)
			       (list x y (wumpus-turn heading 'left)))
			 (cons '(turn right)
			       (list x y (wumpus-turn heading 'right))))))
      (when (or (member ahead (wumpus-route-problem-allowed problem)
			:test #'equal)
		(member ahead (wumpus-route-problem-goals problem)
			:test #'equal))
	(push (cons 'forward (append ahead (list heading))) result))
      result)))

(defmethod goal-test ((problem wumpus-route-problem) state)
  (let ((goals (wumpus-route-problem-goals problem)))
    (or (member state goals :test #'equal)
	(member (subseq state 0 2) goals :test #'equal))))

(defmethod h-cost ((problem wumpus-route-problem) state)
  "The Manhattan distance to the nearest goal square."
  (reduce #'min (wumpus-route-problem-goals problem)
	  :key #'(lambda (goal) (+ (abs (- (first goal) (first state)))
				   (abs (- (second goal) (second state)))))
	  :initial-value 1000))

(defun wumpus-plan-route (pose goals allowed)
  "The actions of a shortest route from POSE to one of the GOALS through the
  ALLOWED squares, or NIL if there is none (or POSE is a goal)."
  (when goals
    (let ((node (A*-search (make-wumpus-route-problem
			    :initial-state pose :goals goals
			    :allowed allowed))))
      (and node (solution-actions node)))))

(defun wumpus-plan-shot (pose possible-wumpus allowed n)
  "The actions that move to a pose in line with one of the squares in
  POSSIBLE-WUMPUS, facing it, and shoot; or NIL if there is no such pose."
  (let ((poses nil))
    (dolist (sq possible-wumpus)
      (destructuring-bind (wx wy) sq
	(loop for i from 1 to n do
	      (cond ((< i wx) (push (list i wy 'east) poses))
		    ((> i wx) (push (list i wy 'west) poses)))
	      (cond ((< i wy) (push (list wx i 'north) poses))
		    ((> i wy) (push (list wx i 'south) poses))))))
    (setf poses (remove-if #'(lambda (p)
			       (or (member (subseq p 0 2) possible-wumpus
					   :test #'equal)
				   (not (member (subseq p 0 2) allowed
						:test #'equal))))
			   poses))
    (when poses
      (let ((node (A*-search (make-wumpus-route-problem
			      :initial-state pose :goals poses
			      :allowed allowed))))
	(when node
	  (append (solution-actions node) '(shoot)))))))
