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

;;;; Testing Logical Inference

(deftest logic
  "Some simple examples in Propositional Logic"
  "First, just test the infix reader."
  ((logic "P=>Q <=> ~Q=>~P") '(<=> (=> P Q) (=> (not Q) (not P))))
  "Print a truth table, as on [p 169]."
  ((truth-table "(P | H) ^ ~H => P"))
  
  "Some simple examples"
  ((validity "P=>Q <=> ~Q=>~P") 'valid)
  ((validity "SillyQuestion") 'satisfiable)
  ((validity "~SillyQuestion") 'satisfiable)
  ((validity "ToBe or not ToBe") 'valid)
  ((validity "ToBe and not ToBe") 'unsatisfiable)
  ((validity "((S => W1|W2|W3|W4) ^ S ^ (~W1^~W2^~W3)) => W4") 'valid)
  ((validity "Ok ^ (Ok <=> ~W^~P) => ~W") 'valid)
  ((setf kb (make-prop-kb)))
  ((tell kb "S => W1|W2|W3|W4"))
  ((tell kb "S"))
  ((tell kb "~W1"))
  ((tell kb "~W2"))
  ((ask kb "W4") 'nil)
  ((tell kb "~W3"))
  ((ask kb "W4") 't)
  ((tell kb "Ok <=> ~W ^ ~P"))
  ((tell kb "Ok"))
  ((ask kb "W") 'nil)
  ((ask kb "~W") 't)
  ((tell kb "ToBe and ~ToBe"))
  ((ask kb "SillyQuestion") 't)
  
  "A look at Normal forms (conjunctive, implicative, and Horn)."
  ((->cnf '(<=> P Q))
   '(AND (OR P (NOT Q)) (OR (NOT P) Q)))
  ((->inf '(<=> P Q))
   '(AND (=> Q P) (=> P Q)))
  ((->horn '(<=> P Q))
   '(AND (=> Q P) (=> P Q)))
  ((->cnf '(=> (not P) R))
   '(OR R P))
  ((->inf '(=> (not P) R))
   '(=> TRUE (OR R P)))
  
  "Use the KB to solve the `Wumpus at [1,3]' problem [p 174-176]."
  "This builds a KB with 12 propositional symbols -- about the max."
  "you can do without starting to slow down."
  ((setq kb1 (make-prop-kb)))
  "The initial state of knowledge"
  ((tell kb1 "~S11 ^ ~S21 ^S12 ^ ~B11 ^ B21 ^ ~B12"))
  "Rules R1 through R4"
  ((tell kb1 "~S11 => ~W11 ^ ~W12 ^ ~W21"))
  ((tell kb1 "~S21 => ~W11 ^ ~W21 ^ ~W22 ^ ~W31"))
  ((tell kb1 "~S12 => ~W11 ^ ~W12 ^ ~W22 ^ ~W13"))
  ((tell kb1 "S12 => W13 | W12 | W22 | W11"))
  "Now the query -- this may take a while."
  ((ask kb1 "W13") *)
  
  "Now a quick demo of the Horn Logic backward chainer."
  ((setf kb2 (make-horn-kb)))
  "Now we define the Member predicate."
  ((tell kb2 "Member(x,Cons(x,y))"))
  ((tell kb2 "Member(x,rest) => Member(x,Cons(y,rest))"))
  ((ask-each kb2 "Member(x,Cons(1,Cons(2,Cons(3,Nil))))" #'print))
  ((ask-patterns kb2 "Member(x,Cons(1,Cons(2,Cons(3,Nil))))" "x") '(1 2 3))
  ((ask-pattern kb2 "Member(x,Cons(1,Cons(2,Cons(3,Nil)))) & x=2" "x") '2)
  ((ask-patterns kb2 "s = Cons(1,Cons(2,Nil))
                        & Member(x,s) & Member(y,s)" '($x $y))
   '((1 1) (1 2) (2 1) (2 2)))
 
  "A family relationships knowledge base and problem."
  ((tell kb2 '(Mother Gerda Peter)))
  ((tell kb2 '(Father Torsten Peter)))
  ((tell kb2 '(Father Peter Isabella)))
  ((tell kb2 '(Father Peter Juliet)))
  ((tell kb2 '(=> (mother $x $y) (parent $x $y))))
  ((tell kb2 '(=> (father $x $y) (parent $x $y))))
  ((tell kb2 '(=> (and (parent $g $p) (parent $p $c)) (grand-parent $g $c))))
  ((ask-patterns kb2 '(grand-parent $x $y)) 
   '((Grand-parent Gerda Isabella) (Grand-parent Gerda Juliet) 
     (Grand-parent Torsten Isabella) (Grand-parent Torsten Juliet)))
  
  "Now the 'Criminal' problem from [p 271-272]."
  ((setf kb3 (make-horn-kb)))
  ((tell kb3 "American(x) ^ Weapon(y) ^ Nation(z) ^ Hostile(z) ^ Sells(x,z,y)
		 => Criminal(x)"))
  ((tell kb3 "Owns(Nono,M1)"))
  ((tell kb3 "Missle(M1)"))
  ((tell kb3 "Owns(Nono,x) ^ Missle(x) => Sells(West,Nono,x)"))
  ((tell kb3 "Missle(x) => Weapon(x)"))
  ((tell kb3 "Enemy(x,America) => Hostile(x)"))
  ((tell kb3 "American(West)"))
  ((tell kb3 "Nation(Nono)"))
  ((tell kb3 "Enemy(Nono,America)"))
  ((tell kb3 "Nation(America)"))
  ((ask kb3 "Criminal(West)") 't)
  ((ask-pattern kb3 "Criminal(x)" "x") 'West)

  "Propositional resolution [Fig. 7.13] on the wumpus KB of section 7.4.3."
  ((setf wumpus-kb0 (make-prop-kb)))
  ((tell wumpus-kb0 "~P11"))
  ((tell wumpus-kb0 "B11 <=> (P12 | P21)"))
  ((tell wumpus-kb0 "B21 <=> (P11 | P22 | P31)"))
  ((tell wumpus-kb0 "~B11"))
  ((tell wumpus-kb0 "B21"))
  ((pl-resolution wumpus-kb0 "~P11") 't)
  ((pl-resolution wumpus-kb0 "~P12") 't)
  ((pl-resolution wumpus-kb0 "~B11") 't)
  ((pl-resolution wumpus-kb0 "P22") 'nil)
  ((pl-resolution wumpus-kb0 "P22 | P31") 't)

  "Forward chaining [Fig. 7.15] on the definite clauses of Fig. 7.16."
  ((setf horn-kb0 (make-prop-definite-kb)))
  ((dolist (s '("P => Q" "L ^ M => P" "B ^ L => M" "A ^ P => L" "A ^ B => L"
		"A" "B"))
     (tell horn-kb0 s)))
  ((pl-fc-entails horn-kb0 "Q") 't)
  ((pl-fc-entails horn-kb0 "SomethingSilly") 'nil)
  ((ask horn-kb0 "L") 't)
  ((pl-resolution horn-kb0 "P") 't)
  ((setf horn-kb1 (make-prop-definite-kb)))
  ((dolist (s '("B ^ F => E" "A ^ E ^ F => G" "B ^ C => F" "A ^ B => D"
		"E ^ F => H" "H ^ I => J" "A" "B" "C"))
     (tell horn-kb1 s)))
  ((pl-fc-entails horn-kb1 "G") 't)
  ((pl-fc-entails horn-kb1 "H") 't)
  ((pl-fc-entails horn-kb1 "I") 'nil)
  ((pl-fc-entails horn-kb1 "J") 'nil)

  "DPLL [Fig. 7.17] returns a model, an alist of (symbol . value) pairs."
  ((setf sat-sentence "A ^ ~B ^ C ^ (A | ~D) ^ (~E | ~D) ^ (C | ~D) ^ (~A | ~F)
     ^ (E | ~F) ^ (~D | ~F) ^ (B | ~C | D) ^ (A | ~E | F) ^ (~A | E | D)"))
  ((dpll-satisfiable sat-sentence) (pl-satisfies-p * sat-sentence))
  ((dpll-satisfiable "A ^ B ^ ~C ^ D") (pl-satisfies-p * "A ^ B ^ ~C ^ D"))
  ((dpll-satisfiable "A <=> B") '((A . t) (B . t)))
  ((dpll-satisfiable "A ^ ~B") '((A . t) (B . nil)))
  ((dpll-satisfiable "P ^ ~P") 'nil)
  "The pigeonhole problem with 3 pigeons and 2 holes is unsatisfiable."
  ((setf pigeons "(P11 | P12) ^ (P21 | P22) ^ (P31 | P32)
     ^ (~P11 | ~P21) ^ (~P11 | ~P31) ^ (~P21 | ~P31)
     ^ (~P12 | ~P22) ^ (~P12 | ~P32) ^ (~P22 | ~P32)"))
  ((dpll-satisfiable pigeons) 'nil)
  "Every branching heuristic finds a model, and reports an unsatisfiable
  sentence."
  ((setf sat-sentence2 "(A | B | C) ^ (~A | ~B) ^ (~B | ~C) ^ (A | C)"))
  ((every #'(lambda (h)
	      (let ((m (dpll-satisfiable sat-sentence2 :branching-heuristic h)))
		(and m (pl-satisfies-p m sat-sentence2)
		     (null (dpll-satisfiable pigeons :branching-heuristic h)))))
	  (list #'no-branching-heuristic #'moms #'momsf #'posit #'zm
		#'dlis #'dlcs #'jw #'jw2))
   't)

  "CDCL, with two watched literals, clause learning and restarts."
  ((cdcl-satisfiable sat-sentence) (pl-satisfies-p * sat-sentence))
  ((cdcl-satisfiable "A <=> B") '((A . t) (B . t)))
  ((cdcl-satisfiable "A ^ ~B") '((A . t) (B . nil)))
  ((cdcl-satisfiable "P ^ ~P") 'nil)
  ((cdcl-satisfiable "(A | A) ^ ~A") 'nil)
  ((cdcl-satisfiable "A | ~A") '((A . t)))
  ((cdcl-satisfiable pigeons) 'nil)
  ((setf sat-sentence3 "(A | B | C) ^ (~A | ~B) ^ (~B | ~C) ^ (A | C)
     ^ (D | ~A) ^ (~D | B)"))
  ((every #'(lambda (r)
	      (let ((m (cdcl-satisfiable sat-sentence3 :restart-strategy r)))
		(and m (pl-satisfies-p m sat-sentence3)
		     (null (cdcl-satisfiable pigeons :restart-strategy r)))))
	  (list #'no-restart #'luby #'glucose))
   't)
  ((every #'(lambda (h)
	      (let ((m (cdcl-satisfiable sat-sentence3 :branching-heuristic h)))
		(and m (pl-satisfies-p m sat-sentence3)
		     (null (cdcl-satisfiable pigeons :branching-heuristic h)))))
	  (list #'moms #'jw2 #'dlis))
   't)
  ((mapcar #'luby-sequence '(1 2 3 4 5 6 7 8)) '(1 1 2 1 1 2 4 1))

  "WalkSAT [Fig. 7.18]."
  ((walksat (list sat-sentence2)) (pl-satisfies-p * sat-sentence2))
  ((walksat '("A ^ B" "A ^ C")) (pl-satisfies-p * "A ^ B ^ C"))
  ((walksat '("A ^ ~A") :max-flips 100) 'nil)

  "SATPlan [Fig. 7.22] on transition models: (state . ((action . next)...))."
  ((setf transition0 '((A (Left . A) (Right . B))
		       (B (Left . A) (Right . C))
		       (C (Left . B) (Right . C)))))
  ((satplan 'A transition0 'C 1) 'nil)
  ((satplan 'A transition0 'B 2) '(Right))
  ((satplan 'C transition0 'A 2) '(Left Left))
  ((satplan 'C transition0 'A 2 :sat-solver #'cdcl-satisfiable) '(Left Left))
  ((setf transition1 '(((0 0) (Right . (0 1)) (Down . (1 0)))
		       ((0 1) (Left . (1 0)) (Down . (1 1)))
		       ((1 0) (Right . (1 0)) (Up . (1 0)) (Left . (1 0))
			      (Down . (1 0)))
		       ((1 1) (Left . (1 0)) (Up . (0 1))))))
  ((satplan '(0 0) transition1 '(1 1) 4) '(Right Down))
  ((satplan '(0 0) transition1 #'(lambda (s) (equal s '(1 1))) 4)
   '(Right Down))

  "The wumpus KB of the hybrid agent: at time 0, with no percept, [2,1] is
  safe and [2,2] is not known to be."
  ((setf wumpus-kb1 (make-wumpus-kb :n 4)))
  ((progn (wumpus-kb-tell-atemporal wumpus-kb1)
	  (wumpus-kb-tell-percept wumpus-kb1 '(nil nil nil nil nil) 0)
	  (wumpus-kb-tell-physics wumpus-kb1 0)
	  t))
  ((wumpus-kb-ask wumpus-kb1 'OK21_0) 't)
  ((wumpus-kb-ask wumpus-kb1 'OK22_0) 'nil)
  ((wumpus-plan-route '(1 1 east) '((1 2)) '((1 1) (1 2)))
   '((turn left) forward))
  ((wumpus-plan-route '(1 1 east) nil '((1 1))) 'nil)
  ((wumpus-plan-shot '(1 1 east) '((2 2)) '((1 1) (2 1) (1 2) (2 2)) 2)
   (eq (last1 *) 'shoot))
  "The hybrid agent [Fig. 7.20] in the world of Fig. 7.2: it finds the gold
  in [2,3] without dying, and climbs out."
  ((setf wumpus-env (make-wumpus-world
		     :stream nil :max-steps 60
		     :aspec '(hybrid-wumpus-agent)
		     :bspec '((at edge wall) (at (1 3) wumpus) (at (3 1) pit)
			      (at (3 3) pit) (at (4 4) pit) (at (2 3) gold)))))
  ((run-environment wumpus-env))
  ((agent-score (first (environment-agents wumpus-env))) (> * 900))

  "First-order forward chaining [Fig. 9.3] on the crime KB."
  ((setf crime-kb (make-fol-definite-kb)))
  ((dolist (s '("American(x) ^ Weapon(y) ^ Sells(x,y,z) ^ Hostile(z)
		   => Criminal(x)"
		"Owns(Nono,M1)" "Missile(M1)"
		"Missile(x) ^ Owns(Nono,x) => Sells(West,x,Nono)"
		"Missile(x) => Weapon(x)" "Enemy(x,America) => Hostile(x)"
		"American(West)" "Enemy(Nono,America)"))
     (tell crime-kb s)))
  ((ask-patterns crime-kb "Criminal(x)" "x") '(West))
  ((ask-patterns crime-kb "Enemy(x,America)" "x") '(Nono))
  ((fol-fc-ask crime-kb "Criminal(West)") +no-bindings+)
  ((fol-fc-ask crime-kb "Criminal(Nono)") +fail+)
  "A full first-order KB answers by resolution refutation."
  ((setf full-kb (make-fol-kb)))
  ((dolist (s '("P(A)" "P(x) => Q(x)" "Q(x) => R(x) | S(x)" "~S(A)"))
     (tell full-kb (logic s))))
  ((ask full-kb "R(A)") 't)
  ((ask full-kb "R(B)") 'nil)
  ((setf rabbit-kb (make-fol-definite-kb)))
  ((dolist (s '("Farmer(Mac)" "Rabbit(Pete)" "Mother(MrsMac,Mac)"
		"Mother(MrsRabbit,Pete)" "Rabbit(r) ^ Farmer(f) => Hates(f,r)"
		"Mother(m,c) => Loves(m,c)"
		"Mother(m,r) ^ Rabbit(r) => Rabbit(m)"
		"Farmer(f) => Human(f)" "Mother(m,h) ^ Human(h) => Human(m)"))
     (tell rabbit-kb s)))
  ((ask-patterns rabbit-kb "Farmer(x)" "x") '(Mac))
  ((ask-patterns rabbit-kb "Human(x)" "x")
   (null (set-exclusive-or * '(Mac MrsMac))))
  ((ask-patterns rabbit-kb "Rabbit(x)" "x")
   (null (set-exclusive-or * '(Pete MrsRabbit))))

  "APPEND [Fig. 9.8], compiled into Lisp with logic variables and a trail."
  ((prolog-append-solutions (make-prolog-var) (make-prolog-var) '(1 2 3))
   '((nil (1 2 3) (1 2 3)) ((1) (2 3) (1 2 3)) ((1 2) (3) (1 2 3))
     ((1 2 3) nil (1 2 3))))
  ((prolog-append-solutions '(1 2) '(3) (make-prolog-var))
   '(((1 2) (3) (1 2 3))))
  ((prolog-append-solutions '(1) '(2) '(1 3)) 'nil)
  "The same Append predicate in a Horn KB, with the backward chainer."
  ((setf append-kb (make-horn-kb)))
  ((tell append-kb "Append(Nil,y,y)"))
  ((tell append-kb "Append(x,y,z) => Append(Cons(a,x),y,Cons(a,z))"))
  ((ask-patterns append-kb "Append(x,y,Cons(1,Cons(2,Nil)))" '($x $y))
   '((|Nil| (Cons 1 (Cons 2 |Nil|))) ((Cons 1 |Nil|) (Cons 2 |Nil|))
     ((Cons 1 (Cons 2 |Nil|)) |Nil|)))

  "Martelli-Montanari unification."
  ((unify-mm '$x '$x) +no-bindings+)
  ((unify-mm '$x 3) '(($x . 3)))
  ((unify-mm '(and $x 4 $y) '(and 6 $y 4)) '(($x . 6) ($y . 4)))
  ((unify-mm '(A $x) '(A B)) '(($x . B)))
  ((let* ((x '(P (F $x $z) (G $u $z)))
	  (y '(P (F $y $a) $y))
	  (b (unify-mm x y)))
     (and b (equal (subst-bindings b x) (subst-bindings b y))))
   't)
  ((subst-bindings (unify-mm '(P A $x (F (G $y))) '(P $z (F $z) (F $u)))
		   '($z $x $u))
   '(A (F A) (G $y)))
  ((unify-mm '(P A) '(P B)) +fail+)
  ((unify-mm '$x '(F $x)) +fail+)

  "First-order resolution [Section 9.5]: curiosity killed the cat (Fig. 9.12)."
  ((setf cat-clauses '("Animal(F(x)) | Loves(G(x),x)"
		       "~Loves(x,F(x)) | Loves(G(x),x)"
		       "~Loves(y,x) | ~Animal(z) | ~Kills(x,z)"
		       "~Animal(x) | Loves(Jack,x)"
		       "Kills(Jack,Tuna) | Kills(Curiosity,Tuna)"
		       "Cat(Tuna)" "~Cat(x) | Animal(x)")))
  ((fol-resolution cat-clauses "Kills(Curiosity,Tuna)") 't)
  ((fol-resolution cat-clauses "Kills(Jack,Tuna)" :max-clauses 800) 'nil)
  ((setf crime-clauses
	 '("~American(x) | ~Weapon(y) | ~Sells(x,y,z) | ~Hostile(z) | Criminal(x)"
	   "~Missile(x) | ~Owns(Nono,x) | Sells(West,x,Nono)"
	   "~Enemy(x,America) | Hostile(x)" "~Missile(x) | Weapon(x)"
	   "Owns(Nono,M1)" "Missile(M1)" "American(West)"
	   "Enemy(Nono,America)")))
  ((fol-resolution crime-clauses "Criminal(West)") 't)
  ((fol-resolution crime-clauses "Criminal(x)") 't)
  ((fol-resolution crime-clauses "Criminal(Nono)") 'nil)
  "Demodulation and paramodulation [Section 9.5.5]."
  ((demodulate "Equal(Father(Father(x)),PaternalGrandfather(x))"
	       "Birthdate(Father(Father(Bella)),1926)")
   '(Birthdate (PaternalGrandfather Bella) 1926))
  ((some #'(lambda (c)
	     (null (set-exclusive-or (disjuncts c) '((P B A) (Q A) (R B))
				     :test #'equal)))
	 (paramodulate "Equal(F(A,y),y) | R(y)" "P(F(x,B),x) | Q(x)"))
   't)
  ((fol-resolution '("Equal(F(A),B)" "P(F(A))") "P(B)") 'nil)
  ((fol-resolution '("Equal(F(A),B)" "P(F(A))") "P(B)" :equality t) 't)

  "A knowledge-based agent [Fig. 7.1] on a Horn KB: it tells the KB its"
  "percept, asks for an action, and tells the KB the action it did."
  ((setf agent-kb (make-horn-kb)))
  ((progn (tell agent-kb '(=> (Percept Dirty $t) (Action Suck $t)))
	  (tell agent-kb '(=> (Percept Clean $t) (Action Right $t)))
	  t))
  ((mapcar (make-kb-agent-program agent-kb) '(Dirty Clean Dirty))
   '(Suck Right Suck))
  ((ask agent-kb '(Did Right 1)) 't)
  ((ask agent-kb '(Did Suck 1)) 'nil)
  "The action-value agent asks for a great action first."
  ((setf agent-kb (make-horn-kb)))
  ((progn (tell agent-kb '(=> (Percept Glitter $t) (Great Grab $t)))
	  (tell agent-kb '(Good Forward 0))
	  t))
  ((funcall (make-action-value-agent-program :kb agent-kb) 'Glitter) 'Grab)

  "Infix sentences are converted to prefix form:"
  ((->prefix "P ^ Q => R") '(=> (and P Q) R))
  ((->prefix "~P | Q") '(or (not P) Q))
  "Map coloring as a SAT problem: Australia with 3 colors, but not with 2."
  ((setf map-sat (make-map-coloring-sat '(R G B) *australia-neighbors*)))
  "7 at-least-one, 21 at-most-one, and 3 clauses for each of the 9 borders."
  ((length (args map-sat)) 55)
  ((setf map-model (dpll-satisfiable map-sat)) (pl-satisfies-p * map-sat))
  ((csp-solution? (make-australia-csp)
		  (map-coloring-sat-solution map-model '(R G B)
					     *australia-neighbors*))
   't)
  ((dpll-satisfiable (make-map-coloring-sat '(R G) *australia-neighbors*))
   'nil)

  "Unification [Fig. 9.1] on the examples of section 9.2.2:"
  ((subst-bindings (unify '(Knows John $x) '(Knows John Jane)) '$x) 'Jane)
  ((subst-bindings (unify '(Knows John $x) '(Knows $y Bill)) '($x $y))
   '(Bill John))
  ((subst-bindings (unify '(Knows John $x) '(Knows $y (Mother $y))) '$x)
   '(Mother John))
  ((unify '(Knows John $x) '(Knows $x Elizabeth)) +fail+)
  "Backward chaining [Fig. 9.6] on the crime KB, by BACK-CHAIN-EACH:"
  ((let ((answers nil))
     (back-chain-each kb3 (list (logic "Criminal(x)")) +no-bindings+
		      #'(lambda (b) (push (subst-bindings b '$x) answers)))
     (remove-duplicates answers))
   '(West))
  "PROLOG-APPEND calls its continuation once for each solution:"
  ((let ((n 0))
     (prolog-append (make-prolog-var) (make-prolog-var) '(1 2)
		    #'(lambda () (incf n)))
     n)
   3)
  "Conversion of first-order sentences to CNF, as lists of clauses:"
  ((->minimal-cnf '(<=> P Q)) '((P (NOT Q)) ((NOT P) Q)))
  ((->minimal-cnf '(and (or (P $x) (Q $x)) (R $x))) '(((P $x) (Q $x)) ((R $x))))
  "Subsumption: P(x) subsumes P(A) | Q(B), but P(A) does not subsume"
  "P(B) | Q(A), and P(x) | Q(x) does not subsume P(A) | Q(B)."
  ((fol-subsumes? '((P $x)) '((P A) (Q B))) 't)
  ((fol-subsumes? '((P $x) (Q $y)) '((P A) (Q B))) 't)
  ((fol-subsumes? '((P A)) '((P B) (Q A))) 'nil)
  ((fol-subsumes? '((P $x) (Q $x)) '((P A) (Q B))) 'nil)
  ((fol-subsumes? '((not (P $x))) '((not (P F)) (R))) 't)

  "The shopping world, a grid environment with a supermarket."
  ((shopping-world-p (make-shopping-world)) 't)
  )
