logic.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. """Representations and Inference for Logic (Chapters 7-9, 12)
  2. Covers both Propositional and First-Order Logic. First we have four
  3. important data types:
  4. KB Abstract class holds a knowledge base of logical expressions
  5. Expr A logical expression, imported from utils.py
  6. substitution Implemented as a dictionary of var:value pairs, {x:1, y:x}
  7. Be careful: some functions take an Expr as argument, and some take a KB.
  8. Logical expressions can be created with Expr or expr, imported from utils, TODO
  9. or with expr, which adds the capability to write a string that uses
  10. the connectives ==>, <==, <=>, or <=/=>. But be careful: these have the
  11. opertor precedence of commas; you may need to add parens to make precendence work.
  12. See logic.ipynb for examples.
  13. Then we implement various functions for doing logical inference:
  14. pl_true Evaluate a propositional logical sentence in a model
  15. tt_entails Say if a statement is entailed by a KB
  16. pl_resolution Do resolution on propositional sentences
  17. dpll_satisfiable See if a propositional sentence is satisfiable
  18. WalkSAT Try to find a solution for a set of clauses
  19. And a few other functions:
  20. to_cnf Convert to conjunctive normal form
  21. unify Do unification of two FOL sentences
  22. diff, simp Symbolic differentiation and simplification
  23. """
  24. from .utils import (
  25. removeall, unique, first, isnumber, issequence, Expr, expr, subexpressions
  26. )
  27. import itertools
  28. from collections import defaultdict
  29. # ______________________________________________________________________________
  30. class KB:
  31. """A knowledge base to which you can tell and ask sentences.
  32. To create a KB, first subclass this class and implement
  33. tell, ask_generator, and retract. Why ask_generator instead of ask?
  34. The book is a bit vague on what ask means --
  35. For a Propositional Logic KB, ask(P & Q) returns True or False, but for an
  36. FOL KB, something like ask(Brother(x, y)) might return many substitutions
  37. such as {x: Cain, y: Abel}, {x: Abel, y: Cain}, {x: George, y: Jeb}, etc.
  38. So ask_generator generates these one at a time, and ask either returns the
  39. first one or returns False."""
  40. def __init__(self, sentence=None):
  41. raise NotImplementedError
  42. def tell(self, sentence):
  43. "Add the sentence to the KB."
  44. raise NotImplementedError
  45. def ask(self, query):
  46. """Return a substitution that makes the query true, or, failing that, return False."""
  47. return first(self.ask_generator(query), default=False)
  48. def ask_generator(self, query):
  49. "Yield all the substitutions that make query true."
  50. raise NotImplementedError
  51. def retract(self, sentence):
  52. "Remove sentence from the KB."
  53. raise NotImplementedError
  54. class PropKB(KB):
  55. """A KB for propositional logic. Inefficient, with no indexing. """
  56. def __init__(self, sentence=None):
  57. self.clauses = []
  58. if sentence:
  59. self.tell(sentence)
  60. def tell(self, sentence):
  61. "Add the sentence's clauses to the KB."
  62. self.clauses.extend(conjuncts(to_cnf(sentence)))
  63. def ask_generator(self, query):
  64. "Yield the empty substitution {} if KB entails query; else no results."
  65. if tt_entails(Expr('&', *self.clauses), query):
  66. yield {}
  67. def ask_if_true(self, query):
  68. "Return True if the KB entails query, else return False."
  69. for _ in self.ask_generator(query):
  70. return True
  71. return False
  72. def retract(self, sentence):
  73. "Remove the sentence's clauses from the KB."
  74. for c in conjuncts(to_cnf(sentence)):
  75. if c in self.clauses:
  76. self.clauses.remove(c)
  77. # ______________________________________________________________________________
  78. def is_symbol(s):
  79. "A string s is a symbol if it starts with an alphabetic char."
  80. return isinstance(s, str) and s[:1].isalpha()
  81. def is_var_symbol(s):
  82. "A logic variable symbol is an initial-lowercase string."
  83. return is_symbol(s) and s[0].islower()
  84. def is_prop_symbol(s):
  85. """A proposition logic symbol is an initial-uppercase string."""
  86. return is_symbol(s) and s[0].isupper()
  87. def variables(s):
  88. """Return a set of the variables in expression s.
  89. >>> variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, 2)')) == {x, y, z}
  90. True
  91. """
  92. return {x for x in subexpressions(s) if is_variable(x)}
  93. def is_definite_clause(s):
  94. """returns True for exprs s of the form A & B & ... & C ==> D,
  95. where all literals are positive. In clause form, this is
  96. ~A | ~B | ... | ~C | D, where exactly one clause is positive.
  97. >>> is_definite_clause(expr('Farmer(Mac)'))
  98. True
  99. """
  100. if is_symbol(s.op):
  101. return True
  102. elif s.op == '==>':
  103. antecedent, consequent = s.args
  104. return (is_symbol(consequent.op) and
  105. all(is_symbol(arg.op) for arg in conjuncts(antecedent)))
  106. else:
  107. return False
  108. def parse_definite_clause(s):
  109. "Return the antecedents and the consequent of a definite clause."
  110. assert is_definite_clause(s)
  111. if is_symbol(s.op):
  112. return [], s
  113. else:
  114. antecedent, consequent = s.args
  115. return conjuncts(antecedent), consequent
  116. # Useful constant Exprs used in examples and code:
  117. A, B, C, D, E, F, G, P, Q, x, y, z = map(Expr, 'ABCDEFGPQxyz')
  118. # ______________________________________________________________________________
  119. def tt_entails(kb, alpha):
  120. """Does kb entail the sentence alpha? Use truth tables. For propositional
  121. kb's and sentences. [Figure 7.10]. Note that the 'kb' should be an
  122. Expr which is a conjunction of clauses.
  123. >>> tt_entails(expr('P & Q'), expr('Q'))
  124. True
  125. """
  126. assert not variables(alpha)
  127. return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
  128. def tt_check_all(kb, alpha, symbols, model):
  129. "Auxiliary routine to implement tt_entails."
  130. if not symbols:
  131. if pl_true(kb, model):
  132. result = pl_true(alpha, model)
  133. assert result in (True, False)
  134. return result
  135. else:
  136. return True
  137. else:
  138. P, rest = symbols[0], symbols[1:]
  139. return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and
  140. tt_check_all(kb, alpha, rest, extend(model, P, False)))
  141. def prop_symbols(x):
  142. "Return a list of all propositional symbols in x."
  143. if not isinstance(x, Expr):
  144. return []
  145. elif is_prop_symbol(x.op):
  146. return [x]
  147. else:
  148. return list(set(symbol for arg in x.args for symbol in prop_symbols(arg)))
  149. def tt_true(s):
  150. """Is a propositional sentence a tautology?
  151. >>> tt_true('P | ~P')
  152. True
  153. """
  154. s = expr(s)
  155. return tt_entails(True, s)
  156. def pl_true(exp, model={}):
  157. """Return True if the propositional logic expression is true in the model,
  158. and False if it is false. If the model does not specify the value for
  159. every proposition, this may return None to indicate 'not obvious';
  160. this may happen even when the expression is tautological."""
  161. if exp in (True, False):
  162. return exp
  163. op, args = exp.op, exp.args
  164. if is_prop_symbol(op):
  165. return model.get(exp)
  166. elif op == '~':
  167. p = pl_true(args[0], model)
  168. if p is None:
  169. return None
  170. else:
  171. return not p
  172. elif op == '|':
  173. result = False
  174. for arg in args:
  175. p = pl_true(arg, model)
  176. if p is True:
  177. return True
  178. if p is None:
  179. result = None
  180. return result
  181. elif op == '&':
  182. result = True
  183. for arg in args:
  184. p = pl_true(arg, model)
  185. if p is False:
  186. return False
  187. if p is None:
  188. result = None
  189. return result
  190. p, q = args
  191. if op == '==>':
  192. return pl_true(~p | q, model)
  193. elif op == '<==':
  194. return pl_true(p | ~q, model)
  195. pt = pl_true(p, model)
  196. if pt is None:
  197. return None
  198. qt = pl_true(q, model)
  199. if qt is None:
  200. return None
  201. if op == '<=>':
  202. return pt == qt
  203. elif op == '^': # xor or 'not equivalent'
  204. return pt != qt
  205. else:
  206. raise ValueError("illegal operator in logic expression" + str(exp))
  207. # ______________________________________________________________________________
  208. # Convert to Conjunctive Normal Form (CNF)
  209. def to_cnf(s):
  210. """Convert a propositional logical sentence to conjunctive normal form.
  211. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253]
  212. >>> to_cnf('~(B | C)')
  213. (~B & ~C)
  214. """
  215. s = expr(s)
  216. if isinstance(s, str):
  217. s = expr(s)
  218. s = eliminate_implications(s) # Steps 1, 2 from p. 253
  219. s = move_not_inwards(s) # Step 3
  220. return distribute_and_over_or(s) # Step 4
  221. def eliminate_implications(s):
  222. "Change implications into equivalent form with only &, |, and ~ as logical operators."
  223. if s is False:
  224. s = expr("F")
  225. if s is True:
  226. s = expr("T")
  227. s = expr(s)
  228. if not s.args or is_symbol(s.op):
  229. return s # Atoms are unchanged.
  230. args = list(map(eliminate_implications, s.args))
  231. a, b = args[0], args[-1]
  232. if s.op == '==>':
  233. return b | ~a
  234. elif s.op == '<==':
  235. return a | ~b
  236. elif s.op == '<=>':
  237. return (a | ~b) & (b | ~a)
  238. elif s.op == '^':
  239. assert len(args) == 2 # TODO: relax this restriction
  240. return (a & ~b) | (~a & b)
  241. else:
  242. assert s.op in ('&', '|', '~')
  243. return Expr(s.op, *args)
  244. def move_not_inwards(s):
  245. """Rewrite sentence s by moving negation sign inward.
  246. >>> move_not_inwards(~(A | B))
  247. (~A & ~B)"""
  248. s = expr(s)
  249. if s.op == '~':
  250. def NOT(b):
  251. return move_not_inwards(~b)
  252. a = s.args[0]
  253. if a.op == '~':
  254. return move_not_inwards(a.args[0]) # ~~A ==> A
  255. if a.op == '&':
  256. return associate('|', list(map(NOT, a.args)))
  257. if a.op == '|':
  258. return associate('&', list(map(NOT, a.args)))
  259. return s
  260. elif is_symbol(s.op) or not s.args:
  261. return s
  262. else:
  263. return Expr(s.op, *list(map(move_not_inwards, s.args)))
  264. def distribute_and_over_or(s):
  265. """Given a sentence s consisting of conjunctions and disjunctions
  266. of literals, return an equivalent sentence in CNF.
  267. >>> distribute_and_over_or((A & B) | C)
  268. ((A | C) & (B | C))
  269. """
  270. s = expr(s)
  271. if s.op == '|':
  272. s = associate('|', s.args)
  273. if s.op != '|':
  274. return distribute_and_over_or(s)
  275. if len(s.args) == 0:
  276. return False
  277. if len(s.args) == 1:
  278. return distribute_and_over_or(s.args[0])
  279. conj = first(arg for arg in s.args if arg.op == '&')
  280. if not conj:
  281. return s
  282. others = [a for a in s.args if a is not conj]
  283. rest = associate('|', others)
  284. return associate('&', [distribute_and_over_or(c | rest)
  285. for c in conj.args])
  286. elif s.op == '&':
  287. return associate('&', list(map(distribute_and_over_or, s.args)))
  288. else:
  289. return s
  290. def associate(op, args):
  291. """Given an associative op, return an expression with the same
  292. meaning as Expr(op, *args), but flattened -- that is, with nested
  293. instances of the same op promoted to the top level.
  294. >>> associate('&', [(A&B),(B|C),(B&C)])
  295. (A & B & (B | C) & B & C)
  296. >>> associate('|', [A|(B|(C|(A&B)))])
  297. (A | B | C | (A & B))
  298. """
  299. args = dissociate(op, args)
  300. if len(args) == 0:
  301. return _op_identity[op]
  302. elif len(args) == 1:
  303. return args[0]
  304. else:
  305. return Expr(op, *args)
  306. _op_identity = {'&': True, '|': False, '+': 0, '*': 1}
  307. def dissociate(op, args):
  308. """Given an associative op, return a flattened list result such
  309. that Expr(op, *result) means the same as Expr(op, *args)."""
  310. result = []
  311. def collect(subargs):
  312. for arg in subargs:
  313. if arg.op == op:
  314. collect(arg.args)
  315. else:
  316. result.append(arg)
  317. collect(args)
  318. return result
  319. def conjuncts(s):
  320. """Return a list of the conjuncts in the sentence s.
  321. >>> conjuncts(A & B)
  322. [A, B]
  323. >>> conjuncts(A | B)
  324. [(A | B)]
  325. """
  326. return dissociate('&', [s])
  327. def disjuncts(s):
  328. """Return a list of the disjuncts in the sentence s.
  329. >>> disjuncts(A | B)
  330. [A, B]
  331. >>> disjuncts(A & B)
  332. [(A & B)]
  333. """
  334. return dissociate('|', [s])
  335. # ______________________________________________________________________________
  336. def pl_resolution(KB, alpha):
  337. "Propositional-logic resolution: say if alpha follows from KB. [Figure 7.12]"
  338. clauses = KB.clauses + conjuncts(to_cnf(~alpha))
  339. new = set()
  340. while True:
  341. n = len(clauses)
  342. pairs = [(clauses[i], clauses[j])
  343. for i in range(n) for j in range(i+1, n)]
  344. for (ci, cj) in pairs:
  345. resolvents = pl_resolve(ci, cj)
  346. if False in resolvents:
  347. return True
  348. new = new.union(set(resolvents))
  349. if new.issubset(set(clauses)):
  350. return False
  351. for c in new:
  352. if c not in clauses:
  353. clauses.append(c)
  354. def pl_resolve(ci, cj):
  355. """Return all clauses that can be obtained by resolving clauses ci and cj."""
  356. clauses = []
  357. for di in disjuncts(ci):
  358. for dj in disjuncts(cj):
  359. if di == ~dj or ~di == dj:
  360. dnew = unique(removeall(di, disjuncts(ci)) +
  361. removeall(dj, disjuncts(cj)))
  362. clauses.append(associate('|', dnew))
  363. return clauses
  364. # ______________________________________________________________________________
  365. class PropDefiniteKB(PropKB):
  366. "A KB of propositional definite clauses."
  367. def tell(self, sentence):
  368. "Add a definite clause to this KB."
  369. assert is_definite_clause(sentence), "Must be definite clause"
  370. self.clauses.append(sentence)
  371. def ask_generator(self, query):
  372. "Yield the empty substitution if KB implies query; else nothing."
  373. if pl_fc_entails(self.clauses, query):
  374. yield {}
  375. def retract(self, sentence):
  376. self.clauses.remove(sentence)
  377. def clauses_with_premise(self, p):
  378. """Return a list of the clauses in KB that have p in their premise.
  379. This could be cached away for O(1) speed, but we'll recompute it."""
  380. return [c for c in self.clauses
  381. if c.op == '==>' and p in conjuncts(c.args[0])]
  382. def pl_fc_entails(KB, q):
  383. """Use forward chaining to see if a PropDefiniteKB entails symbol q.
  384. [Figure 7.15]
  385. >>> pl_fc_entails(horn_clauses_KB, expr('Q'))
  386. True
  387. """
  388. count = {c: len(conjuncts(c.args[0]))
  389. for c in KB.clauses
  390. if c.op == '==>'}
  391. inferred = defaultdict(bool)
  392. agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]
  393. while agenda:
  394. p = agenda.pop()
  395. if p == q:
  396. return True
  397. if not inferred[p]:
  398. inferred[p] = True
  399. for c in KB.clauses_with_premise(p):
  400. count[c] -= 1
  401. if count[c] == 0:
  402. agenda.append(c.args[1])
  403. return False
  404. """ [Figure 7.13]
  405. Simple inference in a wumpus world example
  406. """
  407. wumpus_world_inference = expr("(B11 <=> (P12 | P21)) & ~B11")
  408. """ [Figure 7.16]
  409. Propositional Logic Forward Chaining example
  410. """
  411. horn_clauses_KB = PropDefiniteKB()
  412. for s in "P==>Q; (L&M)==>P; (B&L)==>M; (A&P)==>L; (A&B)==>L; A;B".split(';'):
  413. horn_clauses_KB.tell(expr(s))
  414. # ______________________________________________________________________________
  415. # DPLL-Satisfiable [Figure 7.17]
  416. def dpll_satisfiable(s):
  417. """Check satisfiability of a propositional sentence.
  418. This differs from the book code in two ways: (1) it returns a model
  419. rather than True when it succeeds; this is more useful. (2) The
  420. function find_pure_symbol is passed a list of unknown clauses, rather
  421. than a list of all clauses and the model; this is more efficient."""
  422. clauses = conjuncts(to_cnf(s))
  423. symbols = prop_symbols(s)
  424. return dpll(clauses, symbols, {})
  425. def dpll(clauses, symbols, model):
  426. "See if the clauses are true in a partial model."
  427. unknown_clauses = [] # clauses with an unknown truth value
  428. for c in clauses:
  429. val = pl_true(c, model)
  430. if val is False:
  431. return False
  432. if val is not True:
  433. unknown_clauses.append(c)
  434. if not unknown_clauses:
  435. return model
  436. P, value = find_pure_symbol(symbols, unknown_clauses)
  437. if P:
  438. return dpll(clauses, removeall(P, symbols), extend(model, P, value))
  439. P, value = find_unit_clause(clauses, model)
  440. if P:
  441. return dpll(clauses, removeall(P, symbols), extend(model, P, value))
  442. if not symbols:
  443. raise TypeError("Argument should be of the type Expr.")
  444. P, symbols = symbols[0], symbols[1:]
  445. return (dpll(clauses, symbols, extend(model, P, True)) or
  446. dpll(clauses, symbols, extend(model, P, False)))
  447. def find_pure_symbol(symbols, clauses):
  448. """Find a symbol and its value if it appears only as a positive literal
  449. (or only as a negative) in clauses.
  450. >>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A])
  451. (A, True)
  452. """
  453. for s in symbols:
  454. found_pos, found_neg = False, False
  455. for c in clauses:
  456. if not found_pos and s in disjuncts(c):
  457. found_pos = True
  458. if not found_neg and ~s in disjuncts(c):
  459. found_neg = True
  460. if found_pos != found_neg:
  461. return s, found_pos
  462. return None, None
  463. def find_unit_clause(clauses, model):
  464. """Find a forced assignment if possible from a clause with only 1
  465. variable not bound in the model.
  466. >>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})
  467. (B, False)
  468. """
  469. for clause in clauses:
  470. P, value = unit_clause_assign(clause, model)
  471. if P:
  472. return P, value
  473. return None, None
  474. def unit_clause_assign(clause, model):
  475. """Return a single variable/value pair that makes clause true in
  476. the model, if possible.
  477. >>> unit_clause_assign(A|B|C, {A:True})
  478. (None, None)
  479. >>> unit_clause_assign(B|~C, {A:True})
  480. (None, None)
  481. >>> unit_clause_assign(~A|~B, {A:True})
  482. (B, False)
  483. """
  484. P, value = None, None
  485. for literal in disjuncts(clause):
  486. sym, positive = inspect_literal(literal)
  487. if sym in model:
  488. if model[sym] == positive:
  489. return None, None # clause already True
  490. elif P:
  491. return None, None # more than 1 unbound variable
  492. else:
  493. P, value = sym, positive
  494. return P, value
  495. def inspect_literal(literal):
  496. """The symbol in this literal, and the value it should take to
  497. make the literal true.
  498. >>> inspect_literal(P)
  499. (P, True)
  500. >>> inspect_literal(~P)
  501. (P, False)
  502. """
  503. if literal.op == '~':
  504. return literal.args[0], False
  505. else:
  506. return literal, True
  507. def unify(x, y, s):
  508. """Unify expressions x,y with substitution s; return a substitution that
  509. would make x,y equal, or None if x,y can not unify. x and y can be
  510. variables (e.g. Expr('x')), constants, lists, or Exprs. [Figure 9.1]"""
  511. if s is None:
  512. return None
  513. elif x == y:
  514. return s
  515. elif is_variable(x):
  516. return unify_var(x, y, s)
  517. elif is_variable(y):
  518. return unify_var(y, x, s)
  519. elif isinstance(x, Expr) and isinstance(y, Expr):
  520. return unify(x.args, y.args, unify(x.op, y.op, s))
  521. elif isinstance(x, str) or isinstance(y, str):
  522. return None
  523. elif issequence(x) and issequence(y) and len(x) == len(y):
  524. if not x:
  525. return s
  526. return unify(x[1:], y[1:], unify(x[0], y[0], s))
  527. else:
  528. return None
  529. def is_variable(x):
  530. "A variable is an Expr with no args and a lowercase symbol as the op."
  531. return isinstance(x, Expr) and not x.args and x.op[0].islower()
  532. def unify_var(var, x, s):
  533. if var in s:
  534. return unify(s[var], x, s)
  535. elif occur_check(var, x, s):
  536. return None
  537. else:
  538. return extend(s, var, x)
  539. def occur_check(var, x, s):
  540. """Return true if variable var occurs anywhere in x
  541. (or in subst(s, x), if s has a binding for x)."""
  542. if var == x:
  543. return True
  544. elif is_variable(x) and x in s:
  545. return occur_check(var, s[x], s)
  546. elif isinstance(x, Expr):
  547. return (occur_check(var, x.op, s) or
  548. occur_check(var, x.args, s))
  549. elif isinstance(x, (list, tuple)):
  550. return first(e for e in x if occur_check(var, e, s))
  551. else:
  552. return False
  553. def extend(s, var, val):
  554. "Copy the substitution s and extend it by setting var to val; return copy."
  555. s2 = s.copy()
  556. s2[var] = val
  557. return s2
  558. def subst(s, x):
  559. """Substitute the substitution s into the expression x.
  560. >>> subst({x: 42, y:0}, F(x) + y)
  561. (F(42) + 0)
  562. """
  563. if isinstance(x, list):
  564. return [subst(s, xi) for xi in x]
  565. elif isinstance(x, tuple):
  566. return tuple([subst(s, xi) for xi in x])
  567. elif not isinstance(x, Expr):
  568. return x
  569. elif is_var_symbol(x.op):
  570. return s.get(x, x)
  571. else:
  572. return Expr(x.op, *[subst(s, arg) for arg in x.args])
  573. def fol_fc_ask(KB, alpha):
  574. raise NotImplementedError
  575. def standardize_variables(sentence, dic=None):
  576. """Replace all the variables in sentence with new variables."""
  577. if dic is None:
  578. dic = {}
  579. if not isinstance(sentence, Expr):
  580. return sentence
  581. elif is_var_symbol(sentence.op):
  582. if sentence in dic:
  583. return dic[sentence]
  584. else:
  585. v = Expr('v_{}'.format(next(standardize_variables.counter)))
  586. dic[sentence] = v
  587. return v
  588. else:
  589. return Expr(sentence.op,
  590. *[standardize_variables(a, dic) for a in sentence.args])
  591. standardize_variables.counter = itertools.count()
  592. # ______________________________________________________________________________
  593. class FolKB(KB):
  594. """A knowledge base consisting of first-order definite clauses.
  595. >>> kb0 = FolKB([expr('Farmer(Mac)'), expr('Rabbit(Pete)'),
  596. ... expr('(Rabbit(r) & Farmer(f)) ==> Hates(f, r)')])
  597. >>> kb0.tell(expr('Rabbit(Flopsie)'))
  598. >>> kb0.retract(expr('Rabbit(Pete)'))
  599. >>> kb0.ask(expr('Hates(Mac, x)'))[x]
  600. Flopsie
  601. >>> kb0.ask(expr('Wife(Pete, x)'))
  602. False
  603. """
  604. def __init__(self, initial_clauses=[]):
  605. self.clauses = [] # inefficient: no indexing
  606. for clause in initial_clauses:
  607. self.tell(clause)
  608. def tell(self, sentence):
  609. if is_definite_clause(sentence):
  610. self.clauses.append(sentence)
  611. else:
  612. raise Exception("Not a definite clause: {}".format(sentence))
  613. def ask_generator(self, query):
  614. return fol_bc_ask(self, query)
  615. def retract(self, sentence):
  616. self.clauses.remove(sentence)
  617. def fetch_rules_for_goal(self, goal):
  618. return self.clauses
  619. def fol_bc_ask(KB, query):
  620. """A simple backward-chaining algorithm for first-order logic. [Figure 9.6]
  621. KB should be an instance of FolKB, and query an atomic sentence. """
  622. return fol_bc_or(KB, query, {})
  623. def fol_bc_or(KB, goal, theta):
  624. for rule in KB.fetch_rules_for_goal(goal):
  625. lhs, rhs = parse_definite_clause(standardize_variables(rule))
  626. for theta1 in fol_bc_and(KB, lhs, unify(rhs, goal, theta)):
  627. yield theta1
  628. def fol_bc_and(KB, goals, theta):
  629. if theta is None:
  630. pass
  631. elif not goals:
  632. yield theta
  633. else:
  634. first, rest = goals[0], goals[1:]
  635. for theta1 in fol_bc_or(KB, subst(theta, first), theta):
  636. for theta2 in fol_bc_and(KB, rest, theta1):
  637. yield theta2
  638. # ______________________________________________________________________________
  639. # Example application (not in the book).
  640. # You can use the Expr class to do symbolic differentiation. This used to be
  641. # a part of AI; now it is considered a separate field, Symbolic Algebra.
  642. def diff(y, x):
  643. """Return the symbolic derivative, dy/dx, as an Expr.
  644. However, you probably want to simplify the results with simp.
  645. >>> diff(x * x, x)
  646. ((x * 1) + (x * 1))
  647. """
  648. if y == x:
  649. return 1
  650. elif not y.args:
  651. return 0
  652. else:
  653. u, op, v = y.args[0], y.op, y.args[-1]
  654. if op == '+':
  655. return diff(u, x) + diff(v, x)
  656. elif op == '-' and len(y.args) == 1:
  657. return -diff(u, x)
  658. elif op == '-':
  659. return diff(u, x) - diff(v, x)
  660. elif op == '*':
  661. return u * diff(v, x) + v * diff(u, x)
  662. elif op == '/':
  663. return (v * diff(u, x) - u * diff(v, x)) / (v * v)
  664. elif op == '**' and isnumber(x.op):
  665. return (v * u ** (v - 1) * diff(u, x))
  666. elif op == '**':
  667. return (v * u ** (v - 1) * diff(u, x) +
  668. u ** v * Expr('log')(u) * diff(v, x))
  669. elif op == 'log':
  670. return diff(u, x) / u
  671. else:
  672. raise ValueError("Unknown op: {} in diff({}, {})".format(op, y, x))
  673. def simp(x):
  674. "Simplify the expression x."
  675. if isnumber(x) or not x.args:
  676. return x
  677. args = list(map(simp, x.args))
  678. u, op, v = args[0], x.op, args[-1]
  679. if op == '+':
  680. if v == 0:
  681. return u
  682. if u == 0:
  683. return v
  684. if u == v:
  685. return 2 * u
  686. if u == -v or v == -u:
  687. return 0
  688. elif op == '-' and len(args) == 1:
  689. if u.op == '-' and len(u.args) == 1:
  690. return u.args[0] # --y ==> y
  691. elif op == '-':
  692. if v == 0:
  693. return u
  694. if u == 0:
  695. return -v
  696. if u == v:
  697. return 0
  698. if u == -v or v == -u:
  699. return 0
  700. elif op == '*':
  701. if u == 0 or v == 0:
  702. return 0
  703. if u == 1:
  704. return v
  705. if v == 1:
  706. return u
  707. if u == v:
  708. return u ** 2
  709. elif op == '/':
  710. if u == 0:
  711. return 0
  712. if v == 0:
  713. return Expr('Undefined')
  714. if u == v:
  715. return 1
  716. if u == -v or v == -u:
  717. return 0
  718. elif op == '**':
  719. if u == 0:
  720. return 0
  721. if v == 0:
  722. return 1
  723. if u == 1:
  724. return 1
  725. if v == 1:
  726. return u
  727. elif op == 'log':
  728. if u == 1:
  729. return 0
  730. else:
  731. raise ValueError("Unknown op: " + op)
  732. # If we fall through to here, we can not simplify further
  733. return Expr(op, *args)
  734. def d(y, x):
  735. "Differentiate and then simplify."
  736. return simp(diff(y, x))