Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fixed multiple errors to make py.test rum successfully #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def make_action_sentence(self, action, t):
#______________________________________________________________________________

class Expr:
"""A symbolic mathematical expression. We use this class for logical
"""a symbolic mathematical expression. We use this class for logical
expressions, and for terms within logical expressions. In general, an
Expr has an op (operator) and a list of args. The op can be:
Null-ary (no args) op:
Expand Down Expand Up @@ -165,7 +165,7 @@ def __init__(self, op, *args):
"Op is a string or number; args are Exprs (or are coerced to Exprs)."
assert isinstance(op, str) or (isnumber(op) and not args)
self.op = num_or_str(op)
self.args = map(expr, args) ## Coerce args to Exprs
self.args = list(map(expr, args)) ## Coerce args to Exprs

def __call__(self, *args):
"""Self must be a symbol with no args, such as Expr('F'). Create a new
Expand All @@ -178,11 +178,11 @@ def __repr__(self):
if not self.args: # Constant or proposition with arity 0
return str(self.op)
elif is_symbol(self.op): # Functional or propositional operator
return '%s(%s)' % (self.op, ', '.join(map(repr, self.args)))
return '%s(%s)' % (self.op, ', '.join(list(map(repr, self.args))))
elif len(self.args) == 1: # Prefix operator
return self.op + repr(self.args[0])
else: # Infix operator
return '(%s)' % (' '+self.op+' ').join(map(repr, self.args))
return '(%s)' % (' '+self.op+' ').join(list(map(repr, self.args)))

def __eq__(self, other):
"""x and y are equal iff their ops and args are equal."""
Expand Down Expand Up @@ -310,8 +310,8 @@ def parse_definite_clause(s):
return conjuncts(antecedent), consequent

## Useful constant Exprs used in examples and code:
TRUE, FALSE, ZERO, ONE, TWO = map(Expr, ['TRUE', 'FALSE', 0, 1, 2])
A, B, C, D, E, F, G, P, Q, x, y, z = map(Expr, 'ABCDEFGPQxyz')
TRUE, FALSE, ZERO, ONE, TWO = list(map(Expr, ['TRUE', 'FALSE', 0, 1, 2]))
A, B, C, D, E, F, G, P, Q, x, y, z = list(map(Expr, 'ABCDEFGPQxyz'))

#______________________________________________________________________________

Expand Down Expand Up @@ -434,7 +434,7 @@ def eliminate_implications(s):
((A & ~B) | (~A & B))
"""
if not s.args or is_symbol(s.op): return s ## (Atoms are unchanged.)
args = map(eliminate_implications, s.args)
args = list(map(eliminate_implications, s.args))
a, b = args[0], args[-1]
if s.op == '>>':
return (b | ~a)
Expand Down Expand Up @@ -462,13 +462,13 @@ def move_not_inwards(s):
NOT = lambda b: 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('|', map(NOT, a.args))
if a.op =='|': return associate('&', map(NOT, a.args))
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, *map(move_not_inwards, s.args))
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
Expand All @@ -492,7 +492,7 @@ def distribute_and_over_or(s):
return associate('&', [distribute_and_over_or(c|rest)
for c in conj.args])
elif s.op == '&':
return associate('&', map(distribute_and_over_or, s.args))
return associate('&', list(map(distribute_and_over_or, s.args)))
else:
return s

Expand Down Expand Up @@ -938,7 +938,7 @@ def test_ask(query, kb=None):
key=repr)

test_kb = FolKB(
map(expr, ['Farmer(Mac)',
list(map(expr, ['Farmer(Mac)',
'Rabbit(Pete)',
'Mother(MrsMac, Mac)',
'Mother(MrsRabbit, Pete)',
Expand All @@ -950,11 +950,11 @@ def test_ask(query, kb=None):
# would result in infinite recursion:
#'(Human(h) & Mother(m, h)) ==> Human(m)'
'(Mother(m, h) & Human(h)) ==> Human(m)'
])
]))
)

crime_kb = FolKB(
map(expr,
list(map(expr,
['(American(x) & Weapon(y) & Sells(x, y, z) & Hostile(z)) ==> Criminal(x)',
'Owns(Nono, M1)',
'Missile(M1)',
Expand All @@ -963,7 +963,7 @@ def test_ask(query, kb=None):
'Enemy(x, America) ==> Hostile(x)',
'American(West)',
'Enemy(Nono, America)'
])
]))
)

def fol_bc_ask(KB, query):
Expand Down Expand Up @@ -1033,7 +1033,7 @@ def diff(y, x):

def simp(x):
if not x.args: return x
args = map(simp, x.args)
args = list(map(simp, x.args))
u, op, v = args[0], x.op, args[-1]
if op == '+':
if v == ZERO: return u
Expand Down
8 changes: 4 additions & 4 deletions probability.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def __init__(self, X, parents, cpt):
if isinstance(cpt, (float, int)): # no parents, 0-tuple
cpt = {(): cpt}
elif isinstance(cpt, dict):
if cpt and isinstance(cpt.keys()[0], bool): # one parent, 1-tuple
if cpt and isinstance(list(cpt.keys())[0], bool): # one parent, 1-tuple
cpt = dict(((v,), p) for v, p in cpt.items())

assert isinstance(cpt, dict)
Expand Down Expand Up @@ -406,7 +406,7 @@ def rejection_sampling(X, e, bn, N):
'False: 0.7, True: 0.3'
"""
counts = dict((x, 0) for x in bn.variable_values(X)) # bold N in Fig. 14.14
for j in xrange(N):
for j in range(N):
sample = prior_sample(bn) # boldface x in Fig. 14.14
if consistent_with(sample, e):
counts[sample[X]] += 1
Expand All @@ -428,7 +428,7 @@ def likelihood_weighting(X, e, bn, N):
'False: 0.702, True: 0.298'
"""
W = dict((x, 0) for x in bn.variable_values(X))
for j in xrange(N):
for j in range(N):
sample, weight = weighted_sample(bn, e) # boldface x, w in Fig. 14.15
W[sample[X]] += weight
return ProbDist(X, W)
Expand Down Expand Up @@ -462,7 +462,7 @@ def gibbs_ask(X, e, bn, N):
state = dict(e) # boldface x in Fig. 14.16
for Zi in Z:
state[Zi] = random.choice(bn.variable_values(Zi))
for j in xrange(N):
for j in range(N):
for Zi in Z:
state[Zi] = markov_blanket_sample(Zi, state, bn)
counts[state[X]] += 1
Expand Down
13 changes: 8 additions & 5 deletions probability_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@
from probability import *

def tests():
cpt = burglary.variable_node('Alarm').cpt
cpt = burglary.variable_node('Alarm')
parents = ['Burglary', 'Earthquake']
event = {'Burglary': True, 'Earthquake': True}
assert cpt.p(True, parents, event) == 0.95
assert cpt.p(True, event) == 0.95
event = {'Burglary': False, 'Earthquake': True}
assert cpt.p(False, parents, event) == 0.71
assert cpt.p(False, event) == 0.71
#BoolCPT not yet implemented
"""
assert BoolCPT({T: 0.2, F: 0.625}).p(False, ['Burglary'], event) == 0.375
assert BoolCPT(0.75).p(False, [], {}) == 0.25
cpt = BoolCPT({True: 0.2, False: 0.7})
assert cpt.rand(['A'], {'A': True}) in [True, False]
cpt = BoolCPT({(True, True): 0.1, (True, False): 0.3,
(False, True): 0.5, (False, False): 0.7})
assert cpt.rand(['A', 'B'], {'A': True, 'B': False}) in [True, False]
"""
#enumeration_ask('Earthquake', {}, burglary)

s = {'A': True, 'B': False, 'C': True, 'D': False}
Expand All @@ -23,8 +26,8 @@ def tests():
assert not consistent_with(s, {'A': False})
assert not consistent_with(s, {'D': True})

seed(21); p = rejection_sampling('Earthquake', {}, burglary, 1000)
random.seed(21); p = rejection_sampling('Earthquake', {}, burglary, 1000)
assert p[True], p[False] == (0.001, 0.999)

seed(71); p = likelihood_weighting('Earthquake', {}, burglary, 1000)
random.seed(71); p = likelihood_weighting('Earthquake', {}, burglary, 1000)
assert p[True], p[False] == (0.002, 0.998)