Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
width = 3 # width of grid
height = 5 # height of grid
self.grid = Grid(width, height, self.torus)
self.agents = []
counter = 0
for x in range(width):
for y in range(height):
if TEST_GRID[x][y] == 0:
continue
counter += 1
# Create and place the mock agent
a = MockAgent(counter, None)
self.agents.append(a)
self.grid.place_agent(a, (x, y))
def __init__(self, width, height, key1=103, key2=104):
self.width = width
self.height = height
self.key1 = key1,
self.key2 = key2
self.schedule = SimultaneousActivation(self)
self.grid = Grid(width, height, torus=True)
for (c, x, y) in self.grid.coord_iter():
a = MockAgent(x + y * 100, self, x * y * 3)
self.grid.place_agent(a, (x, y))
self.schedule.add(a)
super().__init__()
self.height = height
self.width = width
self.citizen_density = citizen_density
self.cop_density = cop_density
self.citizen_vision = citizen_vision
self.cop_vision = cop_vision
self.legitimacy = legitimacy
self.max_jail_term = max_jail_term
self.active_threshold = active_threshold
self.arrest_prob_constant = arrest_prob_constant
self.movement = movement
self.max_iters = max_iters
self.iteration = 0
self.schedule = RandomActivation(self)
self.grid = Grid(height, width, torus=True)
model_reporters = {
"Quiescent": lambda m: self.count_type_citizens(m, "Quiescent"),
"Active": lambda m: self.count_type_citizens(m, "Active"),
"Jailed": lambda m: self.count_jailed(m)}
agent_reporters = {
"x": lambda a: a.pos[0],
"y": lambda a: a.pos[1],
'breed': lambda a: a.breed,
"jail_sentence": lambda a: getattr(a, 'jail_sentence', None),
"condition": lambda a: getattr(a, "condition", None),
"arrest_probability": lambda a: getattr(a, "arrest_probability",
None)
}
self.datacollector = DataCollector(model_reporters=model_reporters,
agent_reporters=agent_reporters)
unique_id = 0
def __init__(self, width=20, height=20):
'''
Create a 2D lattice with strict borders where agents live
The agents next state is first determined before updating the grid
'''
self._grid = Grid(width, height, torus=False)
self._schedule = SimultaneousActivation(self)
# self._grid.coord_iter()
# --> should really not return content + col + row
# -->but only col & row
# for (contents, col, row) in self._grid.coord_iter():
# replaced content with _ to appease linter
for (_, row, col) in self._grid.coord_iter():
cell = ColorCell((row, col), self,
ColorCell.OPINIONS[random.randrange(0, 16)])
self._grid.place_agent(cell, (row, col))
self._schedule.add(cell)
self.running = True
def __init__(self, height=50, width=50):
'''
Create a new playing area of (height, width) cells.
'''
# Set up the grid and schedule.
# Use SimultaneousActivation which simulates all the cells
# computing their next state simultaneously. This needs to
# be done because each cell's next state depends on the current
# state of all its neighbors -- before they've changed.
self.schedule = SimultaneousActivation(self)
# Use a simple grid, where edges wrap around.
self.grid = Grid(height, width, torus=True)
# Place a cell at each location, with some initialized to
# ALIVE and some to DEAD.
for (contents, x, y) in self.grid.coord_iter():
cell = Cell((x, y), self)
if random() < .1:
cell.state = cell.ALIVE
self.grid.place_agent(cell, (x, y))
self.schedule.add(cell)
self.running = True
if len(self.empties) == 0:
raise Exception("ERROR: Grid full")
coords = agent.random.choice(sorted(self.empties))
else:
coords = (x, y)
agent.pos = coords
self._place_agent(coords, agent)
def _place_agent(self, pos, agent):
if self.is_cell_empty(pos):
super()._place_agent(pos, agent)
else:
raise Exception("Cell not empty")
class MultiGrid(Grid):
""" Grid where each cell can contain more than one object.
Grid cells are indexed by [x][y], where [0][0] is assumed to be at
bottom-left and [width-1][height-1] is the top-right. If a grid is
toroidal, the top and bottom, and left and right, edges wrap to each other.
Each grid cell holds a set object.
Properties:
width, height: The grid's width and height.
torus: Boolean which determines whether to treat the grid as a torus.
grid: Internal list-of-lists which holds the grid cells themselves.
Methods:
def __init__(self, height=100, width=100, density=0.65):
"""
Create a new forest fire model.
Args:
height, width: The size of the grid to model
density: What fraction of grid cells have a tree in them.
"""
# Initialize model parameters
self.height = height
self.width = width
self.density = density
# Set up model objects
self.schedule = RandomActivation(self)
self.grid = Grid(height, width, torus=False)
self.datacollector = DataCollector(
{"Fine": lambda m: self.count_type(m, "Fine"),
"On Fire": lambda m: self.count_type(m, "On Fire"),
"Burned Out": lambda m: self.count_type(m, "Burned Out")})
# Place a tree in each cell with Prob = density
for (contents, x, y) in self.grid.coord_iter():
if random.random() < self.density:
# Create a tree
new_tree = TreeCell((x, y), self)
# Set all trees in the first column on fire.
if x == 0:
new_tree.condition = "On Fire"
self.grid._place_agent((x, y), new_tree)
self.schedule.add(new_tree)
"Consider replacing it with having a model or agent object "
"explicitly pick one of the grid's list of empty cells."),
DeprecationWarning)
if self.exists_empty_cells():
pos = random.choice(sorted(self.empties))
return pos
else:
return None
def exists_empty_cells(self):
""" Return True if any cells empty else False. """
return len(self.empties) > 0
class SingleGrid(Grid):
""" Grid where each cell contains exactly at most one object. """
empties = set()
def __init__(self, width, height, torus):
""" Create a new single-item grid.
Args:
width, height: The width and width of the grid
torus: Boolean whether the grid wraps or not.
"""
super().__init__(width, height, torus)
def position_agent(self, agent, x="random", y="random"):
""" Position an agent on the grid.
This is used when first placing agents! Use 'move_to_empty()'
@accept_tuple_argument
def iter_cell_list_contents(self, cell_list):
"""
Args:
cell_list: Array-like of (x, y) tuples, or single tuple.
Returns:
A iterator of the contents of the cells identified in cell_list
"""
return itertools.chain.from_iterable(
self[x][y] for x, y in cell_list if not self.is_cell_empty((x, y)))
class HexGrid(Grid):
""" Hexagonal Grid: Extends Grid to handle hexagonal neighbors.
Functions according to odd-q rules.
See http://www.redblobgames.com/grids/hexagons/#coordinates for more.
Properties:
width, height: The grid's width and height.
torus: Boolean which determines whether to treat the grid as a torus.
Methods:
get_neighbors: Returns the objects surrounding a given cell.
get_neighborhood: Returns the cells surrounding a given cell.
neighbor_iter: Iterates over position neightbors.
iter_neighborhood: Returns an iterator over cell coordinates that are
in the neighborhood of a certain point.