forked from aimacode/aima-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.py
1608 lines (1308 loc) · 50.1 KB
/
logic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Representations and Inference for Logic (Chapters 7-9, 12)
Covers both Propositional and First-Order Logic. First we have four
important data types:
KB Abstract class holds a knowledge base of logical expressions
KB_Agent Abstract class subclasses agents.Agent
Expr A logical expression, imported from utils.py
substitution Implemented as a dictionary of var:value pairs, {x:1, y:x}
Be careful: some functions take an Expr as argument, and some take a KB.
Logical expressions can be created with Expr or expr, imported from utils, TODO
or with expr, which adds the capability to write a string that uses
the connectives ==>, <==, <=>, or <=/=>. But be careful: these have the
operator precedence of commas; you may need to add parens to make precedence work.
See logic.ipynb for examples.
Then we implement various functions for doing logical inference:
pl_true Evaluate a propositional logical sentence in a model
tt_entails Say if a statement is entailed by a KB
pl_resolution Do resolution on propositional sentences
dpll_satisfiable See if a propositional sentence is satisfiable
WalkSAT Try to find a solution for a set of clauses
And a few other functions:
to_cnf Convert to conjunctive normal form
unify Do unification of two FOL sentences
diff, simp Symbolic differentiation and simplification
"""
from utils import (
removeall, unique, first, argmax, probability,
isnumber, issequence, Expr, expr, subexpressions
)
from agents import Agent, Glitter, Bump, Stench, Breeze, Scream
from search import astar_search, PlanRoute
import itertools
import random
from collections import defaultdict
# ______________________________________________________________________________
class KB:
"""A knowledge base to which you can tell and ask sentences.
To create a KB, first subclass this class and implement
tell, ask_generator, and retract. Why ask_generator instead of ask?
The book is a bit vague on what ask means --
For a Propositional Logic KB, ask(P & Q) returns True or False, but for an
FOL KB, something like ask(Brother(x, y)) might return many substitutions
such as {x: Cain, y: Abel}, {x: Abel, y: Cain}, {x: George, y: Jeb}, etc.
So ask_generator generates these one at a time, and ask either returns the
first one or returns False."""
def __init__(self, sentence=None):
raise NotImplementedError
def tell(self, sentence):
"""Add the sentence to the KB."""
raise NotImplementedError
def ask(self, query):
"""Return a substitution that makes the query true, or, failing that, return False."""
return first(self.ask_generator(query), default=False)
def ask_generator(self, query):
"""Yield all the substitutions that make query true."""
raise NotImplementedError
def retract(self, sentence):
"""Remove sentence from the KB."""
raise NotImplementedError
class PropKB(KB):
"""A KB for propositional logic. Inefficient, with no indexing."""
def __init__(self, sentence=None):
self.clauses = []
if sentence:
self.tell(sentence)
def tell(self, sentence):
"""Add the sentence's clauses to the KB."""
self.clauses.extend(conjuncts(to_cnf(sentence)))
def ask_generator(self, query):
"""Yield the empty substitution {} if KB entails query; else no results."""
if tt_entails(Expr('&', *self.clauses), query):
yield {}
def ask_if_true(self, query):
"""Return True if the KB entails query, else return False."""
for _ in self.ask_generator(query):
return True
return False
def retract(self, sentence):
"""Remove the sentence's clauses from the KB."""
for c in conjuncts(to_cnf(sentence)):
if c in self.clauses:
self.clauses.remove(c)
# ______________________________________________________________________________
def KB_AgentProgram(KB):
"""A generic logical knowledge-based agent program. [Figure 7.1]"""
steps = itertools.count()
def program(percept):
t = next(steps)
KB.tell(make_percept_sentence(percept, t))
action = KB.ask(make_action_query(t))
KB.tell(make_action_sentence(action, t))
return action
def make_percept_sentence(percept, t):
return Expr("Percept")(percept, t)
def make_action_query(t):
return expr("ShouldDo(action, {})".format(t))
def make_action_sentence(action, t):
return Expr("Did")(action[expr('action')], t)
return program
def is_symbol(s):
"""A string s is a symbol if it starts with an alphabetic char.
>>> is_symbol('R2D2')
True
"""
return isinstance(s, str) and s[:1].isalpha()
def is_var_symbol(s):
"""A logic variable symbol is an initial-lowercase string.
>>> is_var_symbol('EXE')
False
"""
return is_symbol(s) and s[0].islower()
def is_prop_symbol(s):
"""A proposition logic symbol is an initial-uppercase string.
>>> is_prop_symbol('exe')
False
"""
return is_symbol(s) and s[0].isupper()
def variables(s):
"""Return a set of the variables in expression s.
>>> variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, 2)')) == {x, y, z}
True
"""
return {x for x in subexpressions(s) if is_variable(x)}
def is_definite_clause(s):
"""Returns True for exprs s of the form A & B & ... & C ==> D,
where all literals are positive. In clause form, this is
~A | ~B | ... | ~C | D, where exactly one clause is positive.
>>> is_definite_clause(expr('Farmer(Mac)'))
True
"""
if is_symbol(s.op):
return True
elif s.op == '==>':
antecedent, consequent = s.args
return (is_symbol(consequent.op) and
all(is_symbol(arg.op) for arg in conjuncts(antecedent)))
else:
return False
def parse_definite_clause(s):
"""Return the antecedents and the consequent of a definite clause."""
assert is_definite_clause(s)
if is_symbol(s.op):
return [], s
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent
# Useful constant Exprs used in examples and code:
A, B, C, D, E, F, G, P, Q, x, y, z = map(Expr, 'ABCDEFGPQxyz')
# ______________________________________________________________________________
def tt_entails(kb, alpha):
"""Does kb entail the sentence alpha? Use truth tables. For propositional
kb's and sentences. [Figure 7.10]. Note that the 'kb' should be an
Expr which is a conjunction of clauses.
>>> tt_entails(expr('P & Q'), expr('Q'))
True
"""
assert not variables(alpha)
symbols = list(prop_symbols(kb & alpha))
return tt_check_all(kb, alpha, symbols, {})
def tt_check_all(kb, alpha, symbols, model):
"""Auxiliary routine to implement tt_entails."""
if not symbols:
if pl_true(kb, model):
result = pl_true(alpha, model)
assert result in (True, False)
return result
else:
return True
else:
P, rest = symbols[0], symbols[1:]
return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and
tt_check_all(kb, alpha, rest, extend(model, P, False)))
def prop_symbols(x):
"""Return the set of all propositional symbols in x."""
if not isinstance(x, Expr):
return set()
elif is_prop_symbol(x.op):
return {x}
else:
return {symbol for arg in x.args for symbol in prop_symbols(arg)}
def constant_symbols(x):
"""Return the set of all constant symbols in x."""
if not isinstance(x, Expr):
return set()
elif is_prop_symbol(x.op) and not x.args:
return {x}
else:
return {symbol for arg in x.args for symbol in constant_symbols(arg)}
def predicate_symbols(x):
"""Return a set of (symbol_name, arity) in x.
All symbols (even functional) with arity > 0 are considered."""
if not isinstance(x, Expr) or not x.args:
return set()
pred_set = {(x.op, len(x.args))} if is_prop_symbol(x.op) else set()
pred_set.update({symbol for arg in x.args for symbol in predicate_symbols(arg)})
return pred_set
def tt_true(s):
"""Is a propositional sentence a tautology?
>>> tt_true('P | ~P')
True
"""
s = expr(s)
return tt_entails(True, s)
def pl_true(exp, model={}):
"""Return True if the propositional logic expression is true in the model,
and False if it is false. If the model does not specify the value for
every proposition, this may return None to indicate 'not obvious';
this may happen even when the expression is tautological.
>>> pl_true(P, {}) is None
True
"""
if exp in (True, False):
return exp
op, args = exp.op, exp.args
if is_prop_symbol(op):
return model.get(exp)
elif op == '~':
p = pl_true(args[0], model)
if p is None:
return None
else:
return not p
elif op == '|':
result = False
for arg in args:
p = pl_true(arg, model)
if p is True:
return True
if p is None:
result = None
return result
elif op == '&':
result = True
for arg in args:
p = pl_true(arg, model)
if p is False:
return False
if p is None:
result = None
return result
p, q = args
if op == '==>':
return pl_true(~p | q, model)
elif op == '<==':
return pl_true(p | ~q, model)
pt = pl_true(p, model)
if pt is None:
return None
qt = pl_true(q, model)
if qt is None:
return None
if op == '<=>':
return pt == qt
elif op == '^': # xor or 'not equivalent'
return pt != qt
else:
raise ValueError("illegal operator in logic expression" + str(exp))
# ______________________________________________________________________________
# Convert to Conjunctive Normal Form (CNF)
def to_cnf(s):
"""Convert a propositional logical sentence to conjunctive normal form.
That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253]
>>> to_cnf('~(B | C)')
(~B & ~C)
"""
s = expr(s)
if isinstance(s, str):
s = expr(s)
s = eliminate_implications(s) # Steps 1, 2 from p. 253
s = move_not_inwards(s) # Step 3
return distribute_and_over_or(s) # Step 4
def eliminate_implications(s):
"""Change implications into equivalent form with only &, |, and ~ as logical operators."""
s = expr(s)
if not s.args or is_symbol(s.op):
return s # Atoms are unchanged.
args = list(map(eliminate_implications, s.args))
a, b = args[0], args[-1]
if s.op == '==>':
return b | ~a
elif s.op == '<==':
return a | ~b
elif s.op == '<=>':
return (a | ~b) & (b | ~a)
elif s.op == '^':
assert len(args) == 2 # TODO: relax this restriction
return (a & ~b) | (~a & b)
else:
assert s.op in ('&', '|', '~')
return Expr(s.op, *args)
def move_not_inwards(s):
"""Rewrite sentence s by moving negation sign inward.
>>> move_not_inwards(~(A | B))
(~A & ~B)
"""
s = expr(s)
if s.op == '~':
def NOT(b):
return move_not_inwards(~b)
a = s.args[0]
if a.op == '~':
return move_not_inwards(a.args[0]) # ~~A ==> A
if a.op == '&':
return associate('|', list(map(NOT, a.args)))
if a.op == '|':
return associate('&', list(map(NOT, a.args)))
return s
elif is_symbol(s.op) or not s.args:
return s
else:
return Expr(s.op, *list(map(move_not_inwards, s.args)))
def distribute_and_over_or(s):
"""Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
>>> distribute_and_over_or((A & B) | C)
((A | C) & (B | C))
"""
s = expr(s)
if s.op == '|':
s = associate('|', s.args)
if s.op != '|':
return distribute_and_over_or(s)
if len(s.args) == 0:
return False
if len(s.args) == 1:
return distribute_and_over_or(s.args[0])
conj = first(arg for arg in s.args if arg.op == '&')
if not conj:
return s
others = [a for a in s.args if a is not conj]
rest = associate('|', others)
return associate('&', [distribute_and_over_or(c | rest)
for c in conj.args])
elif s.op == '&':
return associate('&', list(map(distribute_and_over_or, s.args)))
else:
return s
def associate(op, args):
"""Given an associative op, return an expression with the same
meaning as Expr(op, *args), but flattened -- that is, with nested
instances of the same op promoted to the top level.
>>> associate('&', [(A&B),(B|C),(B&C)])
(A & B & (B | C) & B & C)
>>> associate('|', [A|(B|(C|(A&B)))])
(A | B | C | (A & B))
"""
args = dissociate(op, args)
if len(args) == 0:
return _op_identity[op]
elif len(args) == 1:
return args[0]
else:
return Expr(op, *args)
_op_identity = {'&': True, '|': False, '+': 0, '*': 1}
def dissociate(op, args):
"""Given an associative op, return a flattened list result such
that Expr(op, *result) means the same as Expr(op, *args).
>>> dissociate('&', [A & B])
[A, B]
"""
result = []
def collect(subargs):
for arg in subargs:
if arg.op == op:
collect(arg.args)
else:
result.append(arg)
collect(args)
return result
def conjuncts(s):
"""Return a list of the conjuncts in the sentence s.
>>> conjuncts(A & B)
[A, B]
>>> conjuncts(A | B)
[(A | B)]
"""
return dissociate('&', [s])
def disjuncts(s):
"""Return a list of the disjuncts in the sentence s.
>>> disjuncts(A | B)
[A, B]
>>> disjuncts(A & B)
[(A & B)]
"""
return dissociate('|', [s])
# ______________________________________________________________________________
def pl_resolution(KB, alpha):
"""Propositional-logic resolution: say if alpha follows from KB. [Figure 7.12]
>>> pl_resolution(horn_clauses_KB, A)
True
"""
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
new = set()
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j])
for i in range(n) for j in range(i+1, n)]
for (ci, cj) in pairs:
resolvents = pl_resolve(ci, cj)
if False in resolvents:
return True
new = new.union(set(resolvents))
if new.issubset(set(clauses)):
return False
for c in new:
if c not in clauses:
clauses.append(c)
def pl_resolve(ci, cj):
"""Return all clauses that can be obtained by resolving clauses ci and cj."""
clauses = []
for di in disjuncts(ci):
for dj in disjuncts(cj):
if di == ~dj or ~di == dj:
dnew = unique(removeall(di, disjuncts(ci)) +
removeall(dj, disjuncts(cj)))
clauses.append(associate('|', dnew))
return clauses
# ______________________________________________________________________________
class PropDefiniteKB(PropKB):
"""A KB of propositional definite clauses."""
def tell(self, sentence):
"""Add a definite clause to this KB."""
assert is_definite_clause(sentence), "Must be definite clause"
self.clauses.append(sentence)
def ask_generator(self, query):
"""Yield the empty substitution if KB implies query; else nothing."""
if pl_fc_entails(self.clauses, query):
yield {}
def retract(self, sentence):
self.clauses.remove(sentence)
def clauses_with_premise(self, p):
"""Return a list of the clauses in KB that have p in their premise.
This could be cached away for O(1) speed, but we'll recompute it."""
return [c for c in self.clauses
if c.op == '==>' and p in conjuncts(c.args[0])]
def pl_fc_entails(KB, q):
"""Use forward chaining to see if a PropDefiniteKB entails symbol q.
[Figure 7.15]
>>> pl_fc_entails(horn_clauses_KB, expr('Q'))
True
"""
count = {c: len(conjuncts(c.args[0]))
for c in KB.clauses
if c.op == '==>'}
inferred = defaultdict(bool)
agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]
while agenda:
p = agenda.pop()
if p == q:
return True
if not inferred[p]:
inferred[p] = True
for c in KB.clauses_with_premise(p):
count[c] -= 1
if count[c] == 0:
agenda.append(c.args[1])
return False
""" [Figure 7.13]
Simple inference in a wumpus world example
"""
wumpus_world_inference = expr("(B11 <=> (P12 | P21)) & ~B11")
""" [Figure 7.16]
Propositional Logic Forward Chaining example
"""
horn_clauses_KB = PropDefiniteKB()
for s in "P==>Q; (L&M)==>P; (B&L)==>M; (A&P)==>L; (A&B)==>L; A;B".split(';'):
horn_clauses_KB.tell(expr(s))
"""
Definite clauses KB example
"""
definite_clauses_KB = PropDefiniteKB()
for clause in ['(B & F)==>E', '(A & E & F)==>G', '(B & C)==>F', '(A & B)==>D', '(E & F)==>H', '(H & I)==>J', 'A', 'B', 'C']:
definite_clauses_KB.tell(expr(clause))
# ______________________________________________________________________________
# DPLL-Satisfiable [Figure 7.17]
def dpll_satisfiable(s):
"""Check satisfiability of a propositional sentence.
This differs from the book code in two ways: (1) it returns a model
rather than True when it succeeds; this is more useful. (2) The
function find_pure_symbol is passed a list of unknown clauses, rather
than a list of all clauses and the model; this is more efficient.
>>> dpll_satisfiable(A |'<=>'| B) == {A: True, B: True}
True
"""
clauses = conjuncts(to_cnf(s))
symbols = list(prop_symbols(s))
return dpll(clauses, symbols, {})
def dpll(clauses, symbols, model):
"""See if the clauses are true in a partial model."""
unknown_clauses = [] # clauses with an unknown truth value
for c in clauses:
val = pl_true(c, model)
if val is False:
return False
if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
P, value = find_pure_symbol(symbols, unknown_clauses)
if P:
return dpll(clauses, removeall(P, symbols), extend(model, P, value))
P, value = find_unit_clause(clauses, model)
if P:
return dpll(clauses, removeall(P, symbols), extend(model, P, value))
if not symbols:
raise TypeError("Argument should be of the type Expr.")
P, symbols = symbols[0], symbols[1:]
return (dpll(clauses, symbols, extend(model, P, True)) or
dpll(clauses, symbols, extend(model, P, False)))
def find_pure_symbol(symbols, clauses):
"""Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
>>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A])
(A, True)
"""
for s in symbols:
found_pos, found_neg = False, False
for c in clauses:
if not found_pos and s in disjuncts(c):
found_pos = True
if not found_neg and ~s in disjuncts(c):
found_neg = True
if found_pos != found_neg:
return s, found_pos
return None, None
def find_unit_clause(clauses, model):
"""Find a forced assignment if possible from a clause with only 1
variable not bound in the model.
>>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})
(B, False)
"""
for clause in clauses:
P, value = unit_clause_assign(clause, model)
if P:
return P, value
return None, None
def unit_clause_assign(clause, model):
"""Return a single variable/value pair that makes clause true in
the model, if possible.
>>> unit_clause_assign(A|B|C, {A:True})
(None, None)
>>> unit_clause_assign(B|~C, {A:True})
(None, None)
>>> unit_clause_assign(~A|~B, {A:True})
(B, False)
"""
P, value = None, None
for literal in disjuncts(clause):
sym, positive = inspect_literal(literal)
if sym in model:
if model[sym] == positive:
return None, None # clause already True
elif P:
return None, None # more than 1 unbound variable
else:
P, value = sym, positive
return P, value
def inspect_literal(literal):
"""The symbol in this literal, and the value it should take to
make the literal true.
>>> inspect_literal(P)
(P, True)
>>> inspect_literal(~P)
(P, False)
"""
if literal.op == '~':
return literal.args[0], False
else:
return literal, True
# ______________________________________________________________________________
# Walk-SAT [Figure 7.18]
def WalkSAT(clauses, p=0.5, max_flips=10000):
"""Checks for satisfiability of all clauses by randomly flipping values of variables
>>> WalkSAT([A & ~A], 0.5, 100) is None
True
"""
# Set of all symbols in all clauses
symbols = {sym for clause in clauses for sym in prop_symbols(clause)}
# model is a random assignment of true/false to the symbols in clauses
model = {s: random.choice([True, False]) for s in symbols}
for i in range(max_flips):
satisfied, unsatisfied = [], []
for clause in clauses:
(satisfied if pl_true(clause, model) else unsatisfied).append(clause)
if not unsatisfied: # if model satisfies all the clauses
return model
clause = random.choice(unsatisfied)
if probability(p):
sym = random.choice(list(prop_symbols(clause)))
else:
# Flip the symbol in clause that maximizes number of sat. clauses
def sat_count(sym):
# Return the the number of clauses satisfied after flipping the symbol.
model[sym] = not model[sym]
count = len([clause for clause in clauses if pl_true(clause, model)])
model[sym] = not model[sym]
return count
sym = argmax(prop_symbols(clause), key=sat_count)
model[sym] = not model[sym]
# If no solution is found within the flip limit, we return failure
return None
# ______________________________________________________________________________
# Expr functions for WumpusKB and HybridWumpusAgent
def facing_east (time):
return Expr('FacingEast', time)
def facing_west (time):
return Expr('FacingWest', time)
def facing_north (time):
return Expr('FacingNorth', time)
def facing_south (time):
return Expr('FacingSouth', time)
def wumpus (x, y):
return Expr('W', x, y)
def pit(x, y):
return Expr('P', x, y)
def breeze(x, y):
return Expr('B', x, y)
def stench(x, y):
return Expr('S', x, y)
def wumpus_alive(time):
return Expr('WumpusAlive', time)
def have_arrow(time):
return Expr('HaveArrow', time)
def percept_stench(time):
return Expr('Stench', time)
def percept_breeze(time):
return Expr('Breeze', time)
def percept_glitter(time):
return Expr('Glitter', time)
def percept_bump(time):
return Expr('Bump', time)
def percept_scream(time):
return Expr('Scream', time)
def move_forward(time):
return Expr('Forward', time)
def shoot(time):
return Expr('Shoot', time)
def turn_left(time):
return Expr('TurnLeft', time)
def turn_right(time):
return Expr('TurnRight', time)
def ok_to_move(x, y, time):
return Expr('OK', x, y, time)
def location(x, y, time = None):
if time is None:
return Expr('L', x, y)
else:
return Expr('L', x, y, time)
# Symbols
def implies(lhs, rhs):
return Expr('==>', lhs, rhs)
def equiv(lhs, rhs):
return Expr('<=>', lhs, rhs)
# Helper Function
def new_disjunction(sentences):
t = sentences[0]
for i in range(1,len(sentences)):
t |= sentences[i]
return t
# ______________________________________________________________________________
class WumpusKB(PropKB):
"""
Create a Knowledge Base that contains the atemporal "Wumpus physics" and temporal rules with time zero.
"""
def __init__(self,dimrow):
super().__init__()
self.dimrow = dimrow
self.tell( ~wumpus(1, 1) )
self.tell( ~pit(1, 1) )
for y in range(1, dimrow+1):
for x in range(1, dimrow+1):
pits_in = list()
wumpus_in = list()
if x > 1: # West room exists
pits_in.append(pit(x - 1, y))
wumpus_in.append(wumpus(x - 1, y))
if y < dimrow: # North room exists
pits_in.append(pit(x, y + 1))
wumpus_in.append(wumpus(x, y + 1))
if x < dimrow: # East room exists
pits_in.append(pit(x + 1, y))
wumpus_in.append(wumpus(x + 1, y))
if y > 1: # South room exists
pits_in.append(pit(x, y - 1))
wumpus_in.append(wumpus(x, y - 1))
self.tell(equiv(breeze(x, y), new_disjunction(pits_in)))
self.tell(equiv(stench(x, y), new_disjunction(wumpus_in)))
## Rule that describes existence of at least one Wumpus
wumpus_at_least = list()
for x in range(1, dimrow+1):
for y in range(1, dimrow + 1):
wumpus_at_least.append(wumpus(x, y))
self.tell(new_disjunction(wumpus_at_least))
## Rule that describes existence of at most one Wumpus
for i in range(1, dimrow+1):
for j in range(1, dimrow+1):
for u in range(1, dimrow+1):
for v in range(1, dimrow+1):
if i!=u or j!=v:
self.tell(~wumpus(i, j) | ~wumpus(u, v))
## Temporal rules at time zero
self.tell(location(1, 1, 0))
for i in range(1, dimrow+1):
for j in range(1, dimrow + 1):
self.tell(implies(location(i, j, 0), equiv(percept_breeze(0), breeze(i, j))))
self.tell(implies(location(i, j, 0), equiv(percept_stench(0), stench(i, j))))
if i != 1 or j != 1:
self.tell(~location(i, j, 0))
self.tell(wumpus_alive(0))
self.tell(have_arrow(0))
self.tell(facing_east(0))
self.tell(~facing_north(0))
self.tell(~facing_south(0))
self.tell(~facing_west(0))
def make_action_sentence(self, action, time):
actions = [move_forward(time), shoot(time), turn_left(time), turn_right(time)]
for a in actions:
if action is a:
self.tell(action)
else:
self.tell(~a)
def make_percept_sentence(self, percept, time):
# Glitter, Bump, Stench, Breeze, Scream
flags = [0, 0, 0, 0, 0]
## Things perceived
if isinstance(percept, Glitter):
flags[0] = 1
self.tell(percept_glitter(time))
elif isinstance(percept, Bump):
flags[1] = 1
self.tell(percept_bump(time))
elif isinstance(percept, Stench):
flags[2] = 1
self.tell(percept_stench(time))
elif isinstance(percept, Breeze):
flags[3] = 1
self.tell(percept_breeze(time))
elif isinstance(percept, Scream):
flags[4] = 1
self.tell(percept_scream(time))
## Things not perceived
for i in range(len(flags)):
if flags[i] == 0:
if i == 0:
self.tell(~percept_glitter(time))
elif i == 1:
self.tell(~percept_bump(time))
elif i == 2:
self.tell(~percept_stench(time))
elif i == 3:
self.tell(~percept_breeze(time))
elif i == 4:
self.tell(~percept_scream(time))
def add_temporal_sentences(self, time):
if time == 0:
return
t = time - 1
## current location rules
for i in range(1, self.dimrow+1):
for j in range(1, self.dimrow+1):
self.tell(implies(location(i, j, time), equiv(percept_breeze(time), breeze(i, j))))
self.tell(implies(location(i, j, time), equiv(percept_stench(time), stench(i, j))))
s = list()
s.append(
equiv(
location(i, j, time), location(i, j, time) & ~move_forward(time) | percept_bump(time)))
if i != 1:
s.append(location(i - 1, j, t) & facing_east(t) & move_forward(t))
if i != self.dimrow:
s.append(location(i + 1, j, t) & facing_west(t) & move_forward(t))
if j != 1:
s.append(location(i, j - 1, t) & facing_north(t) & move_forward(t))
if j != self.dimrow:
s.append(location(i, j + 1, t) & facing_south(t) & move_forward(t))
## add sentence about location i,j
self.tell(new_disjunction(s))
## add sentence about safety of location i,j
self.tell(
equiv(ok_to_move(i, j, time), ~pit(i, j) & ~wumpus(i, j) & wumpus_alive(time))
)
## Rules about current orientation
a = facing_north(t) & turn_right(t)
b = facing_south(t) & turn_left(t)
c = facing_east(t) & ~turn_left(t) & ~turn_right(t)
s = equiv(facing_east(time), a | b | c)
self.tell(s)
a = facing_north(t) & turn_left(t)
b = facing_south(t) & turn_right(t)
c = facing_west(t) & ~turn_left(t) & ~turn_right(t)
s = equiv(facing_west(time), a | b | c)
self.tell(s)
a = facing_east(t) & turn_left(t)
b = facing_west(t) & turn_right(t)
c = facing_north(t) & ~turn_left(t) & ~turn_right(t)
s = equiv(facing_north(time), a | b | c)
self.tell(s)
a = facing_west(t) & turn_left(t)
b = facing_east(t) & turn_right(t)
c = facing_south(t) & ~turn_left(t) & ~turn_right(t)
s = equiv(facing_south(time), a | b | c)
self.tell(s)
## Rules about last action
self.tell(equiv(move_forward(t), ~turn_right(t) & ~turn_left(t)))
##Rule about the arrow
self.tell(equiv(have_arrow(time), have_arrow(t) & ~shoot(t)))
##Rule about Wumpus (dead or alive)
self.tell(equiv(wumpus_alive(time), wumpus_alive(t) & ~percept_scream(time)))