-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkbsk.py
569 lines (508 loc) · 15.3 KB
/
kbsk.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
# CS 503 Fall 2013
# Skeleton code for an interpreter for a
# "deductive database" or "production rule"
# programming language.
#
# There are four things that you have to write
# to complete this file:
# *** RENEW ***
# a set of functions to replace all the
# variables in an expression with fresh copies
# needed to enforce the meanings of
# logic variables as universally quantified
# and make inference generic
# *** INFER ***
# the basic function to implement a step of
# modus ponens and yield the conclusion if
# any
# *** RUN ***
# a process to figure out all the conclusions
# that follow from a program; implemented
# with a queue.
# *** QUERY ***
# a user-level process to figure out what
# instances of a passed formula are true
# in the result of running a program.
# Search in the file to find these sections
import unify
import rules
import st
import collections
import test
test.verbose = True
########################################
# *** RENEW ***
# function gensym
# make a new name that has never
# appeared before that begins withx1
# the passed prefix
_gensym_count = 0
def gensym(prefix) :
global _gensym_count
_gensym_count = _gensym_count + 1
return prefix + str(_gensym_count)
# function copy
# take a collection of variables as input
# return a dictionary that associates
# each of these old variables with a
# fresh variable that has never been
# considered before in running the
# program.
def copy(variables):
d = dict()
for v in variables:
d[v] = gensym(v)
return d
# function index
# take a collection of variables as input
# return a dictionary that associates
# each of these old variables with
# consecutive integers.
def index(variables) :
count = 0
d = dict()
for v in variables :
d[v] = "X" + str(count)
count += 1
return d
# function substitute
# given a term and a binding dictionary d
# construct a corresponding term
# where each occurrence of a variable
# has been replaced by whatever value
# it has in d.
## note: you should also substitute inside the
## value given by d!
## hint: works by structural recursion
## on terms.
# caveat: be sure to return complex results
# as tuples. you can always convert a list fred
# to a tuple by saying tuple(fred).
def ssub(t,d):
if t in d:
t=d[t]
return t
if type(t)==tuple:
t=list(t)
for i in range(len(t)):
if t[i] in d:
t[i]=d[t[i]]
t=tuple(t)
elif type(t)==list:
for i in range(len(t)):
if t[i] in d:
t[i]=d[t[i]]
return t
def substitute(t, d):
t=ssub(t,d)
if type(t)!= list and type(t)!= tuple:
return t
for i in range(len(t)):
if type(t)==tuple:
t=list(t)
t[i]=substitute(t[i],d)
t=tuple(t)
else:
t[i]=substitute(t[i],d)
return t
# tests for subsitute`
# always use the same substitution
# { "X": ("f", "a"), "Y" : ("g", "X")
def ts(term, answer) :
test.test("substitute",
lambda t : substitute(t, { "X": ("f", "a"), "Y" : ("g", "X") }),
term,
answer,
str)
test_substitute = True
if test_substitute :
# Base cases
ts("f", "f")
ts(1, 1)
ts("X", ("f", "a"))
# Recursive cases
ts(("g", "X"), ("g", ("f", "a")))
ts(("g", ("f", "X")), ("g", ("f", ("f", "a"))))
# Substitution requires recursive passes
# (substitute recursively into own output)
ts(("g", "Y"), ("g", ("g", ("f", "a"))))
# function addvariables
# given a term t and a list vrs,
# update l by appending to vrs
# each of the variables that occurs in t
# that is not yet a member of vrs
# hint: uses structural recursion
# heads up: the otherwise more natural 'vars'
# is reserved keyword in python
#
# additional note: it would be more efficient
# to use a set structure in addvariables,
# other things being equal.
# But set structures in python are ordered
# by the hash value of their elements.
# It is important for the way addvariables
# is used throughout the program that
# the variables be listed in the order
# that they occur in the term.
def addvariables(t, vrs) :
if type(t) != tuple and type(t) != list:
if t in vrs:
return vrs
elif not type(t)==str:
return vrs
elif t[0] in map(chr, range(65, 91)) or t[0]=="_":
vrs.append(t)
return vrs
else:
return vrs
for x in t:
vrs= addvariables(x,vrs)
return vrs
# tests for add variables
def tav(term, answer) :
x = []
addvariables(term, x)
test.test("addvariables", lambda v : x, (), answer, str)
test_addvariables = False
if test_addvariables :
# Base cases
tav("a", [])
tav(1, [])
tav("X", ["X"])
# Recursive cases
tav(("f", "X", "Y"), ["X", "Y"])
tav(("f", "X", ("g", "Y")), ["X", "Y"])
tav(("f", "X", "X"), ["X"])
# function renew(fr)
# make a copy of fact or rule FR in which
# all the variables in FR are
# replaced by new values.
# pseudocode:
# - find the variables that
# occur in FR
# - create a substitution that
# maps the variables to unique
# new variables
# - infer the substitution to FR
# - return the result
def renew(fr) :
vrs = []
fr.app(lambda t:addvariables(t, vrs))
subs = copy(vrs)
return fr.xform(lambda t:substitute(t, subs))
########################################
# *** INFER ***
# function infer
# implement modus ponens with unification
# given:
# FACT fact
# RULE rule
# make a new copy of the fact and the rule
# to handle the universally quantified
# variables in the two expressions.
# try to unify the fact body (copy_of_fact.term)
# and antecedent of the rule (copy_of_rule.cond)
# if this succeeds, you'll get a substitution out.
# use this substitution to return an
# instance of the result expression
# (copy_of_rule.result)
# incorporating the constraints
# discovered from unification.
# otherwise, return None
def infer(fact,rule):
d=dict()
def sub(n):
return substitute(n,d)
if unify.unify(fact.term,rule.cond,d):
return rule.result.xform(sub)
################## other method###############################
# import string
# def clean(a):
# if type(a)!=str:
# a=str(a)
# a=a.replace('FACT','')
# a=a.replace('RULE','')
# a=a.replace(' ','')
# return a
# def tt(a):#tuple to tuple canges a(k) to a,k
# if '(' in a:
# if len(a)==4:
# a=a.replace(')','')
# return (a[0],a[-1])
# else:
# temp=a[2:-1]
# return (a[0],temp[:temp.find(',')],temp[temp.find(',')+1:])
# return a
# def infer(fact, rule):
# a=clean(fact)# changes 'FACT a' to 'a'
# b=clean(rule)# changes 'RULE a => FACT b' to 'a=>b'
# if a+"=>" in b:
# b=b.replace(a+"=>",'')
# if '=>' in b:# returns rule
# return rules.RULE(tt(b[:b.find("=>")]),rules.FACT(tt(b[b.find('=>')+2:])))
# return rules.FACT(tt(b)) #returns Fact
# if a==a.lower(): #fact has no Variables
# if b==b.lower():
# return None
# else:# changing a variable to a constant to see if it matches the fact
# for x in string.uppercase:
# for y in string.lowercase:
# if a in b.replace(x,y):
# return infer(a,b.replace(x,y))
# else: #fact has a variable
# for x in string.uppercase:
# for y in string.lowercase:
# if a.replace(x,y) in b: # changing each variable to constants
# return infer(a.replace(x,y),b)
##################################other method #####################
# test inference
# these tests depend on a correct implementation
# of addvariables and substitute,
# so get those working first,
# before enabling these tests.
# deal with the fact that terms will have
# different variables because of the
# renaming of variables involved in
# inference.
def normalize(t):
if t == None :
return t
vs = []
t.app(lambda p:addvariables(p,vs))
subs = index(vs)
return t.xform(lambda p:substitute(p, subs))
def ti(factstr, rulestr, resultstr) :
try :
fact = st.parse_program(factstr)[0]
rule = st.parse_program(rulestr)[0]
if resultstr != None :
result = st.parse_program(resultstr)[0]
canonical = normalize(result)
else :
canonical = None
test.test("infer",
lambda (f,r) : normalize(infer(f, r)),
(fact, rule),
canonical,
str)
except Exception as e :
print "Infer test badly specified:", str(e)
test_infer = True
if test_infer :
# Propositional inference
# ti("a.", "a => b.", "b.")
# ti("c.", "a => b.", None)
# ti("a.", "a => b => c.", "b => c.")
# Instantiating variables
ti("a(k).", "a(X) => b(X).", "b(k).")
ti("a(k).", "a(l) => b(l).", None)
ti("a(k).", "a(X) => b(X) => c(X).", "b(k) => c(k).")
ti("a(X).", "a(k) => b(k).", "b(k).")
ti("a(X).", "a(k) => b(k) => c(k).", "b(k) => c(k).")
# Free variables
ti("a(k).", "a(X) => b(X,Y).", "b(k,Y).")
ti("a(k).", "a(X) => b(X,Y) => c(X,Y).", "b(k,Y) => c(k,Y).")
########################################
# *** RUN ***
#
# For running a program,
# it's convenient to keep two lists
# storing the formulas you've processed so far:
# - one list of the atomic facts (facts)
# - and one list of the implications (rules)
# You also need a queue of
# information that you still have to process
# create a queue with
# collections.deque(initial_items)
# add something to the queue with
# queue.appendleft(x)
# remove something from the queue with
# queue.pop()
# Propagate
# called when a new fact is discovered
# to find all the consequences of the fact
# arguments:
# new fact
# list of rules
# queue
# for each rule, use infer to check whether
# the fact leads to a new inference, and
# if so, enqueue it.
facts=[]
def propagate(fact, rules, queue) :
for x in rules:
a=infer(fact,x)
if a==None:
pass
elif a in queue or a in rules:
pass
else: queue.appendleft(a)
# Fire
# called when a new rule is discovered
# to find all the results of using the
# rule on existing data
# arguments:
# new rule
# list of facts
# queue
# for each fact, use infer to check whether
# the rule leads to a new inference, and
# if so, enqueue it.
def fire(rule, facts, queue) :
for x in facts:
a=infer(x,rule)
if a==None:
pass
elif a in facts or a in queue:
pass
else:
queue.appendleft(a)
# testing code for propagate and fire
def tx(itemstr, programstr, resultstr, name, op) :
try :
item = st.parse_program(itemstr)[0]
program = st.parse_program(programstr)
if resultstr != None :
result = st.parse_program(resultstr)
canonical = map(normalize, result)
else :
canonical = []
queue = collections.deque()
def process (pr) :
(i, l) = pr
op(i, l, queue)
return map(normalize, list(reversed(queue)))
test.test(name, process, (item, program), canonical, lambda x:map(str,x))
except Exception as e :
print name, "test badly specified:", str(e)
test_propagate = True
if test_propagate :
# Propositional cases
tx("a.", "a => b.", "b.",
"propagate", propagate)
tx("b.", "a => b.", None,
"propagate", propagate)
tx("a.", "a => b. a => c.", "b. c.",
"propagate", propagate)
# First-order cases
tx("a(k).", "a(X) => b(X).", "b(k).",
"propagate", propagate)
tx("b(k).", "a(X) => b(X).", None,
"propagate", propagate)
tx("a(k).", "a(X) => b(X). a(X) => c(X).", "b(k). c(k).",
"propagate", propagate)
# Fancy
tx("a(k).",
"a(X) => b(X,Y) => d(Y).",
"b(k,Y) => d(Y).",
"propagate", propagate)
tx("a(k).",
"a(X) => b(X,Y) => d(Y). a(X) => c(X,Y) => e(Y).",
"b(k,Y) => d(Y). c(k,Y) => e(Y).",
"propagate", propagate)
test_fire = True
if test_fire :
# Propositional cases
tx("a => b.", "a.", "b.",
"fire", fire)
tx("a => b.", "b.", None,
"fire", fire)
# First-order cases
tx("a(X) => b(X).", "a(k).", "b(k).",
"fire", fire)
tx("a(X) => b(X).", "b(k).", None,
"fire", fire)
tx("a(X) => b(X).", "a(k). a(l).", "b(k). b(l).",
"fire", fire)
# Fancy
tx("a(X) => b(X,Y) => c(Y).",
"a(k).",
"b(k,Y) => c(Y).",
"fire", fire)
tx("a(X) => b(X,Y) => c(Y).",
"a(k). a(l).",
"b(k,Y) => c(Y). b(l,Y) => c(Y).",
"fire", fire)
# Process
# called when new information is discovered
# arguments:
# item just inferred
# list of facts
# list of rules
# queue
# check whether you have a fact or a rule,
# using isinstance
# if it's a fact,
# check if it occurs in facts
# if not, propagate it and add it to facts
# if it's a rule
# check if it occurs in rules
# if not, fire it and add it to rules
#
# it's easy to see that testing for
# a formula that you already have by equality
# is a shortcut around what logic would
# dictate in general, but it's enough for
# this assignment. if you want to be
# fancier, you can normalize facts and rules
# before putting them into the lists,
# and before comparing them.
def process(item, factlist, rulelist, queue) :
if isinstance(item,rules.FACT):
if not item in factlist:
factlist.append(item)
propagate(item,rulelist,queue)
elif isinstance(item,rules.RULE):
if not item in rulelist:
rulelist.append(item)
fire(item,factlist,queue)
# Run
# puts everything together
# input
# a list of formulas
# output
# all the consequences of the rules
#
# put all the items on the queue
# then process items while items remain on the queue
# return a pair
# (facts, rules)
# showing what you have inferred
def run(items) :
queue = collections.deque(items)
factlist = []
rulelist = []
while len(queue) != 0 :
process(queue.pop(), factlist, rulelist, queue)
return (factlist, rulelist)
########################################
# *** QUERY ***
# query
# arguments:
# a fact with variables
# a list of facts
# return
# the substitution instances that can be obtained
# by successfully unifying pattern with
# a fact in the passed list.
def query(pat, factlist) :
results = []
for f in factlist :
b = dict()
if unify.unify(pat.term, f.term, b) :
results.append(pat.xform(lambda t:substitute(t, b)))
return results
# qt
# short for query text
# user-level query function
# given a string representing a program
# and the facts resulting from running a program
# print out all the instances of the string
# in the facts.
def qt(string, factlist) :
pat = ast.parse_program(string)
assert isinstance(pat, rules.FACT), \
"Error: Can only query facts"
rules.prettyprintkb(query(pat, factlist))
# Print out overall status
test.test_report()