Skip to content

Commit

Permalink
Style: address pep8 warnings in main code.
Browse files Browse the repository at this point in the history
  • Loading branch information
reachtarunhere committed Jun 20, 2016
1 parent 2c458ae commit 0dbb1f6
Show file tree
Hide file tree
Showing 12 changed files with 150 additions and 121 deletions.
77 changes: 40 additions & 37 deletions agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ def __add__(self, heading):
}.get(heading, None)

def move_forward(self, from_location):
x,y = from_location
x, y = from_location
if self.direction == self.R:
return (x+1, y)
elif self.direction == self.L:
Expand All @@ -389,11 +389,12 @@ def __init__(self, width=10, height=10):
self.width = width
self.height = height
self.observers = []
#Sets iteration start and end (no walls).
self.x_start,self.y_start = (0,0)
self.x_end,self.y_end = (self.width, self.height)
# Sets iteration start and end (no walls).
self.x_start, self.y_start = (0, 0)
self.x_end, self.y_end = (self.width, self.height)

perceptible_distance = 1

def things_near(self, location, radius=None):
"Return all things within radius of location."
if radius is None:
Expand Down Expand Up @@ -447,7 +448,7 @@ def move_to(self, thing, destination):
# for obs in self.observers:
# obs.thing_added(thing)

def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items = False):
def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False):
'''Adds things to the world.
If (exclude_duplicate_class_items) then the item won't be added if the location
has at least one item of the same class'''
Expand All @@ -462,7 +463,7 @@ def is_inbounds(self, location):
x,y = location
return not (x < self.x_start or x >= self.x_end or y < self.y_start or y >= self.y_end)

def random_location_inbounds(self, exclude = None):
def random_location_inbounds(self, exclude=None):
'''Returns a random location that is inbounds (within walls if we have walls)'''
location = (random.randint(self.x_start, self.x_end), random.randint(self.y_start, self.y_end))
if exclude is not None:
Expand All @@ -486,14 +487,14 @@ def add_walls(self):
'''Put walls around the entire perimeter of the grid.'''
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height-1))
self.add_thing(Wall(), (x, self.height - 1))
for y in range(self.height):
self.add_thing(Wall(), (0, y))
self.add_thing(Wall(), (self.width-1, y))
self.add_thing(Wall(), (self.width - 1, y))

#Updates iteration start and end (with walls).
self.x_start,self.y_start = (1,1)
self.x_end,self.y_end = (self.width-1, self.height-1)
# Updates iteration start and end (with walls).
self.x_start, self.y_start = (1, 1)
self.x_end, self.y_end = (self.width - 1, self.height - 1)

def add_observer(self, observer):
"""Adds an observer to the list of observers.
Expand Down Expand Up @@ -662,6 +663,7 @@ class Wumpus(Agent):
class Stench(Thing):
pass


class Explorer(Agent):
holding = []
has_arrow = True
Expand All @@ -674,8 +676,9 @@ def can_grab(self, thing):


class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 #Probability to spawn a pit in a location. (From Chapter 7.2)
#Room should be 4x4 grid of rooms. The extra 2 for walls
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls

def __init__(self, agent_program, width=6, height=6):
super(WumpusEnvironment, self).__init__(width, height)
self.init_world(agent_program)
Expand All @@ -690,47 +693,46 @@ def init_world(self, program):
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x,y), True)
self.add_thing(Breeze(), (x - 1,y), True)
self.add_thing(Breeze(), (x,y - 1), True)
self.add_thing(Breeze(), (x + 1,y), True)
self.add_thing(Breeze(), (x,y + 1), True)
self.add_thing(Pit(), (x, y), True)
self.add_thing(Breeze(), (x - 1, y), True)
self.add_thing(Breeze(), (x, y - 1), True)
self.add_thing(Breeze(), (x + 1, y), True)
self.add_thing(Breeze(), (x, y + 1), True)

"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude = (1,1))
w_x, w_y = self.random_location_inbounds(exclude=(1, 1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)

"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude = (1,1)), True)
self.add_thing(Gold(), self.random_location_inbounds(exclude=(1, 1)), True)
#self.add_thing(Gold(), (2,1), True) Making debugging a whole lot easier

"AGENT"
self.add_thing(Explorer(program), (1,1), True)
self.add_thing(Explorer(program), (1, 1), True)

def get_world(self, show_walls = True):
def get_world(self, show_walls=True):
'''returns the items in the world'''
result = []
x_start,y_start = (0,0) if show_walls else (1,1)
x_end,y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
x_start, y_start = (0, 0) if show_walls else (1, 1)
x_end, y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x,y)))
row.append(self.list_things_at((x, y)))
result.append(row)
return result

def percepts_from(self, agent, location, tclass = Thing):
def percepts_from(self, agent, location, tclass=Thing):
'''Returns percepts from a given location, and replaces some items with percepts from chapter 7.'''
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()
}
Pit: Breeze()}
'''Agents don't need to get their percepts'''
thing_percepts[agent.__class__] = None

Expand All @@ -740,19 +742,19 @@ def percepts_from(self, agent, location, tclass = Thing):


result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]

def percept(self, agent):
'''Returns things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]'''
x,y = agent.location
x, y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1,y)))
result.append(self.percepts_from(agent, (x + 1,y)))
result.append(self.percepts_from(agent, (x,y - 1)))
result.append(self.percepts_from(agent, (x,y + 1)))
result.append(self.percepts_from(agent, (x,y)))
result.append(self.percepts_from(agent, (x - 1, y)))
result.append(self.percepts_from(agent, (x + 1, y)))
result.append(self.percepts_from(agent, (x, y - 1)))
result.append(self.percepts_from(agent, (x, y + 1)))
result.append(self.percepts_from(agent, (x, y)))

'''The wumpus gives out a a loud scream once it's killed.'''
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
Expand Down Expand Up @@ -781,14 +783,14 @@ def execute_action(self, agent, action):
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location)
if agent.can_grab(thing)]
if agent.can_grab(thing)]
if len(things):
print("Grabbing", things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1,1): #Agent can only climb out of (1,1)
if agent.location == (1, 1): # Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
Expand Down Expand Up @@ -831,6 +833,7 @@ def is_done(self):
#Almost done. Arrow needs to be implemented
# ______________________________________________________________________________


def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Expand Down
8 changes: 4 additions & 4 deletions canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def mouse_move(self, x, y):
def execute(self, exec_str):
"Stores the command to be exectued to a list which is used later during update()"
if not isinstance(exec_str, str):
print("Invalid execution argument:",exec_str)
print("Invalid execution argument:", exec_str)
self.alert("Recieved invalid execution command format")
prefix = "{0}_canvas_object.".format(self.id)
self.exec_list.append(prefix + exec_str + ';')
Expand Down Expand Up @@ -98,14 +98,14 @@ def font(self, font):
"Changes the font of text"
self.execute('font("{0}")'.format(font))

def text(self, txt, x, y, fill = True):
def text(self, txt, x, y, fill=True):
"Display a text at (x, y)"
if fill:
self.execute('fill_text("{0}", {1}, {2})'.format(txt, x, y))
else:
self.execute('stroke_text("{0}", {1}, {2})'.format(txt, x, y))

def text_n(self, txt, xn, yn, fill = True):
def text_n(self, txt, xn, yn, fill=True):
"Similar to text(), but with normalized coordinates"
x = round(xn * self.width)
y = round(yn * self.height)
Expand All @@ -117,6 +117,6 @@ def alert(self, message):

def update(self):
"Execute the JS code to execute the commands queued by execute()"
exec_code = "<script>\n"+'\n'.join(self.exec_list)+"\n</script>"
exec_code = "<script>\n" + '\n'.join(self.exec_list) + "\n</script>"
self.exec_list = []
display(HTML(exec_code))
4 changes: 2 additions & 2 deletions csp.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ def display(self, assignment):
for var in range(n):
if assignment.get(var, '') == val:
ch = 'Q'
elif (var+val) % 2 == 0:
elif (var + val) % 2 == 0:
ch = '.'
else:
ch = '-'
Expand All @@ -492,7 +492,7 @@ def display(self, assignment):
ch = '*'
else:
ch = ' '
print(str(self.nconflicts(var, val, assignment))+ch, end=' ')
print(str(self.nconflicts(var, val, assignment)) + ch, end=' ')
print()

# ______________________________________________________________________________
Expand Down
16 changes: 8 additions & 8 deletions games.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def max_value(state, alpha, beta, depth):
v = -infinity
for a in game.actions(state):
v = max(v, min_value(game.result(state, a),
alpha, beta, depth+1))
alpha, beta, depth + 1))
if v >= beta:
return v
alpha = max(alpha, v)
Expand All @@ -108,7 +108,7 @@ def min_value(state, alpha, beta, depth):
v = infinity
for a in game.actions(state):
v = min(v, max_value(game.result(state, a),
alpha, beta, depth+1))
alpha, beta, depth + 1))
if v <= alpha:
return v
beta = min(beta, v)
Expand Down Expand Up @@ -245,8 +245,8 @@ def __init__(self, h=3, v=3, k=3):
self.h = h
self.v = v
self.k = k
moves = [(x, y) for x in range(1, h+1)
for y in range(1, v+1)]
moves = [(x, y) for x in range(1, h + 1)
for y in range(1, v + 1)]
self.initial = GameState(to_move='X', utility=0, board={}, moves=moves)

def actions(self, state):
Expand Down Expand Up @@ -274,8 +274,8 @@ def terminal_test(self, state):

def display(self, state):
board = state.board
for x in range(1, self.h+1):
for y in range(1, self.v+1):
for x in range(1, self.h + 1):
for y in range(1, self.v + 1):
print(board.get((x, y), '.'), end=' ')
print()

Expand Down Expand Up @@ -315,7 +315,7 @@ def __init__(self, h=7, v=6, k=4):

def actions(self, state):
return [(x, y) for (x, y) in state.moves
if y == 1 or (x, y-1) in state.board]
if y == 1 or (x, y - 1) in state.board]


class Canvas_TicTacToe(Canvas):
Expand Down Expand Up @@ -374,7 +374,7 @@ def draw_board(self):
if utility == 0:
self.text_n('Game Draw!', 0.1, 0.1)
else:
self.text_n('Player {} wins!'.format(1 if utility>0 else 2), 0.1, 0.1)
self.text_n('Player {} wins!'.format(1 if utility > 0 else 2), 0.1, 0.1)
else: # Print which player's turn it is
self.text_n("Player {}'s move({})".format(self.turn+1, self.players[self.turn]), 0.1, 0.1)

Expand Down
12 changes: 6 additions & 6 deletions learning.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ def BackPropagationLearner(dataset, net, learning_rate, epoches):
o_units = len(o_nodes)
err = [t_val[i] - o_nodes[i].value
for i in range(o_units)]
delta[-1] = [(o_nodes[i].value)*(1 - o_nodes[i].value) *
delta[-1] = [(o_nodes[i].value) * (1 - o_nodes[i].value) *
(err[i]) for i in range(o_units)]

# Backward pass
Expand Down Expand Up @@ -620,7 +620,7 @@ def predict(example):
def Linearlearner(dataset, learning_rate=0.01, epochs=100):
"""Define with learner = Linearlearner(data); infer with learner(x)."""
idx_i = dataset.inputs
idx_t = dataset.target # As of now, dataset.target gives only one index.
idx_t = dataset.target # As of now, dataset.target gives only one index.
examples = dataset.examples

# X transpose
Expand Down Expand Up @@ -794,23 +794,23 @@ def cross_validation(learner, size, dataset, k=10, trials=1):
k=10, trials=1)
trial_errT += errT
trial_errV += errV
return trial_errT/trials, trial_errV/trials
return trial_errT / trials, trial_errV / trials
else:
fold_errT = 0
fold_errV = 0
n = len(dataset.examples)
examples = dataset.examples
for fold in range(k):
random.shuffle(dataset.examples)
train_data, val_data = train_and_test(dataset, fold * (n/k),
(fold + 1) * (n/k))
train_data, val_data = train_and_test(dataset, fold * (n / k),
(fold + 1) * (n / k))
dataset.examples = train_data
h = learner(dataset, size)
fold_errT += test(h, dataset, train_data)
fold_errV += test(h, dataset, val_data)
# Reverting back to original once test is completed
dataset.examples = examples
return fold_errT/k, fold_errV/k
return fold_errT / k, fold_errV / k


def cross_validation_wrapper(learner, dataset, k=10, trials=1):
Expand Down
Loading

0 comments on commit 0dbb1f6

Please sign in to comment.