本文整理汇总了Python中mesa.space.SingleGrid.position_agent方法的典型用法代码示例。如果您正苦于以下问题:Python SingleGrid.position_agent方法的具体用法?Python SingleGrid.position_agent怎么用?Python SingleGrid.position_agent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mesa.space.SingleGrid
的用法示例。
在下文中一共展示了SingleGrid.position_agent方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WorldModel
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class WorldModel(Model):
def __init__(self, N, width, height):
self.grid = SingleGrid(height, width, True)
self.schedule = RandomActivation(self)
self.num_agents = N
self.running = True
for i in range(self.num_agents):
ethnicity = random.choice(Ethnicities)
a = PersonAgent(unique_id=i,
model=self,
ethnicity=int(ethnicity)
)
self.schedule.add(a)
# Add the agent to a random grid cell
self.grid.position_agent(a)
self.datacollector = DataCollector(
agent_reporters={
"Nationalism": lambda a: a.nationalism,
"X": lambda a: a.pos[0],
"Y": lambda a: a.pos[1]
}
)
def step(self):
self.datacollector.collect(self)
self.schedule.step()
示例2: Schelling
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class Schelling(Model):
'''
Model class for the Schelling segregation model.
'''
def __init__(self, height=20, width=20, density=0.8, minority_pc=0.2, homophily=3):
'''
'''
self.height = height
self.width = width
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=True)
self.happy = 0
self.datacollector = DataCollector(
{"happy": "happy"}, # Model-level count of happy agents
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
for cell in self.grid.coord_iter():
x = cell[1]
y = cell[2]
if self.random.random() < self.density:
if self.random.random() < self.minority_pc:
agent_type = 1
else:
agent_type = 0
agent = SchellingAgent((x, y), self, agent_type)
self.grid.position_agent(agent, (x, y))
self.schedule.add(agent)
self.running = True
self.datacollector.collect(self)
def step(self):
'''
Run one step of the model. If All agents are happy, halt the model.
'''
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
# collect data
self.datacollector.collect(self)
if self.happy == self.schedule.get_agent_count():
self.running = False
示例3: SchellingModel
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class SchellingModel(Model):
"""
Model class for the Schelling segregation model.
"""
def __init__(self, height, width, density, minority_pc, homophily):
"""
"""
self.height = height
self.width = width
self.density = density
self.minority_pc = minority_pc
self.homophily = homophily
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=True)
self.happy = 0
self.total_agents = 0
self.datacollector = DataCollector(
{"unhappy": lambda m: m.total_agents - m.happy},
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[X], "y": lambda a: a.pos[Y]},
)
self.running = True
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
for cell, x, y in self.grid.coord_iter():
if random.random() < self.density:
if random.random() < self.minority_pc:
agent_type = 1
else:
agent_type = 0
agent = SchellingAgent(self.total_agents, agent_type)
self.grid.position_agent(agent, x, y)
self.schedule.add(agent)
self.total_agents += 1
def step(self):
"""
Run one step of the model. If All agents are happy, halt the model.
"""
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
self.datacollector.collect(self)
if self.happy == self.total_agents:
self.running = False
示例4: SchellingModel
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class SchellingModel(Model):
'''
Model class for the Schelling segregation model.
'''
def __init__(self, height, width, density, type_pcs=[.2, .2, .2, .2, .2]):
'''
'''
self.height = height
self.width = width
self.density = density
self.type_pcs = type_pcs
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=False)
self.happy = 0
self.datacollector = DataCollector(
{"happy": lambda m: m.happy}, # Model-level count of happy agents
# For testing purposes, agent's individual x and y
{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
self.running = True
# Set up agents
# We use a grid iterator that returns
# the coordinates of a cell as well as
# its contents. (coord_iter)
total_agents = self.height * self.width * self.density
agents_by_type = [total_agents*val for val in self.type_pcs]
for loc, types in enumerate(agents_by_type):
for i in range(int(types)):
pos = self.grid.find_empty()
agent = SchellingAgent(pos, self, loc)
self.grid.position_agent(agent, pos)
self.schedule.add(agent)
def step(self):
'''
Run one step of the model. If All agents are happy, halt the model.
'''
self.happy = 0 # Reset counter of happy agents
self.schedule.step()
self.datacollector.collect(self)
if self.happy == self.schedule.get_agent_count():
self.running = False
示例5: TestSingleGrid
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class TestSingleGrid(unittest.TestCase):
'''
Test the SingleGrid object.
Since it inherits from Grid, all the functionality tested above should
work here too. Instead, this tests the enforcement.
'''
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
width = 3
height = 5
self.grid = SingleGrid(width, height, True)
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 test_enforcement(self):
'''
Test the SingleGrid empty count and enforcement.
'''
assert len(self.grid.empties) == 9
a = MockAgent(100, None)
with self.assertRaises(Exception):
self.grid._place_agent((0, 1), a)
# Place the agent in an empty cell
self.grid.position_agent(a)
# Test whether after placing, the empty cells are reduced by 1
assert a.pos not in self.grid.empties
assert len(self.grid.empties) == 8
for i in range(10):
self.grid.move_to_empty(a)
assert len(self.grid.empties) == 8
# Place agents until the grid is full
empty_cells = len(self.grid.empties)
for i in range(empty_cells):
a = MockAgent(101 + i, None)
self.grid.position_agent(a)
assert len(self.grid.empties) == 0
a = MockAgent(110, None)
with self.assertRaises(Exception):
self.grid.position_agent(a)
with self.assertRaises(Exception):
self.move_to_empty(self.agents[0])
示例6: TestSingleGrid
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class TestSingleGrid(unittest.TestCase):
'''
Test the SingleGrid object.
Since it inherits from Grid, all the functionality tested above should
work here too. Instead, this tests the enforcement.
'''
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
self.grid = SingleGrid(3, 5, True)
self.agents = []
counter = 0
for y in range(3):
for x in range(5):
if TEST_GRID[y][x] == 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 test_enforcement(self):
'''
Test the SingleGrid empty count and enforcement.
'''
assert len(self.grid.empties) == 10
a = MockAgent(100, None)
with self.assertRaises(Exception):
self.grid._place_agent((1, 0), a)
# Place the agent in an empty cell
self.grid.position_agent(a)
assert a.pos not in self.grid.empties
assert len(self.grid.empties) == 9
for i in range(10):
self.grid.move_to_empty(a)
assert len(self.grid.empties) == 9
# Place agents until the grid is full
for i in range(9):
a = MockAgent(101 + i, None)
self.grid.position_agent(a)
assert len(self.grid.empties) == 0
a = MockAgent(110, None)
with self.assertRaises(Exception):
self.grid.position_agent(a)
with self.assertRaises(Exception):
self.move_to_empty(self.agents[0])
示例7: SeparationBarrierModel
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class SeparationBarrierModel(Model):
def __init__(self, height, width, palestinian_density, settlement_density,
settlers_violence_rate, settlers_growth_rate, suicide_rate, greed_level,
settler_vision=1, palestinian_vision=1,
movement=True, max_iters=1000):
super(SeparationBarrierModel, self).__init__()
self.height = height
self.width = width
self.palestinian_density = palestinian_density
self.settler_vision = settler_vision
self.palestinian_vision = palestinian_vision
self.settlement_density = settlement_density
self.movement = movement
self.running = True
self.max_iters = max_iters
self.iteration = 0
self.schedule = RandomActivation(self)
self.settlers_violence_rate = settlers_violence_rate
self.settlers_growth_rate = settlers_growth_rate
self.suicide_rate = suicide_rate
self.greed_level = greed_level
self.total_violence = 0
self.grid = SingleGrid(height, width, torus=False)
model_reporters = {
}
agent_reporters = {
# "x": lambda a: a.pos[0],
# "y": lambda a: a.pos[1],
}
self.dc = DataCollector(model_reporters=model_reporters,
agent_reporters=agent_reporters)
self.unique_id = 0
# Israelis and palestinans split the region in half
for (contents, x, y) in self.grid.coord_iter():
if random.random() < self.palestinian_density:
palestinian = Palestinian(self.unique_id, (x, y), vision=self.palestinian_vision, breed="Palestinian",
model=self)
self.unique_id += 1
self.grid.position_agent(palestinian, x,y)
self.schedule.add(palestinian)
elif ((y > (self.grid.height) * (1-self.settlement_density)) and random.random() < self.settlement_density):
settler = Settler(self.unique_id, (x, y),
vision=self.settler_vision, model=self, breed="Settler")
self.unique_id += 1
self.grid.position_agent(settler, x,y)
self.schedule.add(settler)
def add_settler(self, pos):
settler = Settler(self.unique_id, pos,
vision=self.settler_vision, model=self, breed="Settler")
self.unique_id += 1
self.grid.position_agent(settler, pos[0], pos[1])
self.schedule.add(settler)
def set_barrier(self,victim_pos, violent_pos):
#print("Set barrier - Greed level", self.greed_level)
visible_spots = self.grid.get_neighborhood(victim_pos,
moore=True, radius=self.greed_level + 1)
furthest_empty = self.find_furthest_empty_or_palestinian(victim_pos, visible_spots)
x,y = furthest_empty
current = self.grid[y][x]
#print ("Set barrier!!", pos, current)
free = True
if (current is not None and current.breed == "Palestinian"):
#print ("Relocating Palestinian")
free = self.relocate_palestinian(current, current.pos)
if (free):
barrier = Barrier(-1, furthest_empty, model=self)
self.grid.position_agent(barrier, x,y)
# Relocate the violent palestinian
#violent_x, violent_y = violent_pos
#if violent_pos != furthest_empty:
# violent_palestinian = self.grid[violent_y][violent_x]
# self.relocate_palestinian(violent_palestinian, furthest_empty)
def relocate_palestinian(self, palestinian, destination):
#print ("Relocating Palestinian in ", palestinian.pos, "To somehwhere near ", destination)
visible_spots = self.grid.get_neighborhood(destination,
moore=True, radius=palestinian.vision)
nearest_empty = self.find_nearest_empty(destination, visible_spots)
#print("First Nearest empty to ", palestinian.pos, " Is ", nearest_empty)
if (nearest_empty):
self.grid.move_agent(palestinian, nearest_empty)
else:
#print ("Moveing to random empty")
if (self.grid.exists_empty_cells()):
self.grid.move_to_empty(palestinian)
else:
return False
return True
def find_nearest_empty(self, pos, neighborhood):
#.........这里部分代码省略.........
示例8: SchellingModel
# 需要导入模块: from mesa.space import SingleGrid [as 别名]
# 或者: from mesa.space.SingleGrid import position_agent [as 别名]
class SchellingModel(Model):
'''Model class for Schelling segregation model'''
def __init__(self, height=20, width=20, density=.8, group_ratio=.66, minority_ratio=.5, homophily=3):
self.height = height
self.width = width
self.density = density
self.group_ratio = group_ratio
self.minority_ratio = minority_ratio
self.homophily = homophily
self.happy = 0
self.segregated = 0
self.schedule = RandomActivation(self)
self.grid = SingleGrid(height, width, torus=False)
self.place_agents()
self.datacollector = DataCollector( {'happy': (lambda m: m.happy), 'segregated': (lambda m: m.segregated)})
self.running = True
def step(self):
'''Run one step of model'''
self.schedule.step()
self.calculate_stats()
self.datacollector.collect(self)
if self.happy == self.schedule.get_agent_count():
self.running = False
def place_agents(self):
for cell in self.grid.coord_iter():
x, y = cell[1:3]
if random.random() < self.density:
if random.random() < self.group_ratio:
if random.random() < self.minority_ratio:
group = 0
else:
group = 1
else:
group = 2
agent = SchellingAgent((x,y), group)
self.grid.position_agent(agent, (x,y))
self.schedule.add(agent)
for agent in self.schedule.agents:
count = 0
for neighbour in self.grid.iter_neighbors(agent.pos, moore=False):
if neighbour.group == agent.group:
count += 1
agent.similar = count
def calculate_stats(self):
happy_count = 0
avg_seg = 0
for agent in self.schedule.agents:
avg_seg += agent.similar
if agent.similar >= self.homophily:
happy_count += 1
self.happy = happy_count
self.segregated = avg_seg/self.schedule.get_agent_count()