本文整理汇总了Python中mesa.space.SingleGrid类的典型用法代码示例。如果您正苦于以下问题:Python SingleGrid类的具体用法?Python SingleGrid怎么用?Python SingleGrid使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SingleGrid类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: WorldModel
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()
开发者ID:hypeserver,项目名称:ajan,代码行数:30,代码来源:model.py
示例2: ShapesModel
class ShapesModel(Model):
def __init__(self, N, width=20, height=10):
self.running = True
self.N = N # num of agents
self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1)) # tuples are fast
self.grid = SingleGrid(width, height, torus=False)
self.schedule = RandomActivation(self)
self.make_walker_agents()
def make_walker_agents(self):
unique_id = 0
while True:
if unique_id == self.N:
break
x = random.randrange(self.grid.width)
y = random.randrange(self.grid.height)
pos = (x, y)
heading = random.choice(self.headings)
# heading = (1, 0)
if self.grid.is_cell_empty(pos):
print("Creating agent {2} at ({0}, {1})"
.format(x, y, unique_id))
a = Walker(unique_id, self, pos, heading)
self.schedule.add(a)
self.grid.place_agent(a, pos)
unique_id += 1
def step(self):
self.schedule.step()
开发者ID:GeoESW,项目名称:mesa,代码行数:29,代码来源:model.py
示例3: Schelling
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
开发者ID:bangtree,项目名称:mesa,代码行数:55,代码来源:model.py
示例4: SchellingModel
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
开发者ID:projectmesa,项目名称:Presentations,代码行数:54,代码来源:Schelling.py
示例5: PD_Model
class PD_Model(Model):
'''
Model class for iterated, spatial prisoner's dilemma model.
'''
schedule_types = {"Sequential": BaseScheduler,
"Random": RandomActivation,
"Simultaneous": SimultaneousActivation}
# This dictionary holds the payoff for this agent,
# keyed on: (my_move, other_move)
payoff = {("C", "C"): 1,
("C", "D"): 0,
("D", "C"): 1.6,
("D", "D"): 0}
def __init__(self, height, width, schedule_type, payoffs=None):
'''
Create a new Spatial Prisoners' Dilemma Model.
Args:
height, width: Grid size. There will be one agent per grid cell.
schedule_type: Can be "Sequential", "Random", or "Simultaneous".
Determines the agent activation regime.
payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
'''
self.running = True
self.grid = SingleGrid(height, width, torus=True)
self.schedule_type = schedule_type
self.schedule = self.schedule_types[self.schedule_type](self)
# Create agents
for x in range(width):
for y in range(height):
agent = PD_Agent((x, y), self)
self.grid.place_agent(agent, (x, y))
self.schedule.add(agent)
self.datacollector = DataCollector({
"Cooperating_Agents":
lambda m: len([a for a in m.schedule.agents if a.move == "C"])
})
def step(self):
self.datacollector.collect(self)
self.schedule.step()
def run(self, n):
'''
Run the model for a certain number of steps.
'''
for _ in range(n):
self.step()
开发者ID:csmaxwell,项目名称:mesa,代码行数:54,代码来源:pd_grid.py
示例6: SchellingModel
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
开发者ID:nshlapo,项目名称:ComplexSocialModeling,代码行数:50,代码来源:model.py
示例7: __init__
def __init__(self, N, width=20, height=10):
self.running = True
self.N = N # num of agents
self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1)) # tuples are fast
self.grid = SingleGrid(width, height, torus=False)
self.schedule = RandomActivation(self)
self.make_walker_agents()
开发者ID:GeoESW,项目名称:mesa,代码行数:7,代码来源:model.py
示例8: __init__
def __init__(self, height, width, schedule_type, payoffs=None):
"""
Create a new Spatial Prisoners' Dilemma Model.
Args:
height, width: Grid size. There will be one agent per grid cell.
schedule_type: Can be "Sequential", "Random", or "Simultaneous".
Determines the agent activation regime.
payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
"""
self.running = True
self.grid = SingleGrid(height, width, torus=True)
self.schedule_type = schedule_type
self.schedule = self.schedule_types[self.schedule_type](self)
# Create agents
for x in range(width):
for y in range(height):
agent = PD_Agent((x, y))
self.grid.place_agent(agent, (x, y))
self.schedule.add(agent)
self.datacollector = DataCollector(
{"Cooperating_Agents": lambda m: len([a for a in m.schedule.agents if a.move == "C"])}
)
开发者ID:projectmesa,项目名称:Presentations,代码行数:25,代码来源:pd_grid.py
示例9: setUp
def setUp(self):
self.space = SingleGrid(50, 50, False)
self.agents = []
for i, pos in enumerate(TEST_AGENTS_GRID):
a = MockAgent(i, None)
self.agents.append(a)
self.space.place_agent(a, pos)
开发者ID:bangtree,项目名称:mesa,代码行数:7,代码来源:test_space.py
示例10: __init__
def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
super().__init__(seed=seed)
self.number_of_bug = num_bug
if not(strategy in ["stick", "switch"]):
raise TypeError("'strategy' must be one of {stick, switch}")
self.strategy = strategy
self.grid = SingleGrid(width, height, torus)
self.schedule = RandomActivation(self)
data = {"Bean": lambda m: m.number_of_bean,
"Corn": lambda m: m.number_of_corn,
"Soy": lambda m: m.number_of_soy,
"Bug": lambda m: m.number_of_bug,
}
self.datacollector = DataCollector(data)
# create foods
self._populate(Bean)
self._populate(Corn)
self._populate(Soy)
# create bugs
for i in range(self.number_of_bug):
pos = self.grid.find_empty()
bug = Bug(i, self)
bug.strategy = self.strategy
self.grid.place_agent(bug, pos)
self.schedule.add(bug)
开发者ID:dadaromeo,项目名称:bayes-dap,代码行数:28,代码来源:model.py
示例11: Foraging
class Foraging(Model):
number_of_bean = 0
number_of_corn = 0
number_of_soy = 0
def __init__(self, width=50, height=50, torus=True, num_bug=50, seed=42, strategy=None):
super().__init__(seed=seed)
self.number_of_bug = num_bug
if not(strategy in ["stick", "switch"]):
raise TypeError("'strategy' must be one of {stick, switch}")
self.strategy = strategy
self.grid = SingleGrid(width, height, torus)
self.schedule = RandomActivation(self)
data = {"Bean": lambda m: m.number_of_bean,
"Corn": lambda m: m.number_of_corn,
"Soy": lambda m: m.number_of_soy,
"Bug": lambda m: m.number_of_bug,
}
self.datacollector = DataCollector(data)
# create foods
self._populate(Bean)
self._populate(Corn)
self._populate(Soy)
# create bugs
for i in range(self.number_of_bug):
pos = self.grid.find_empty()
bug = Bug(i, self)
bug.strategy = self.strategy
self.grid.place_agent(bug, pos)
self.schedule.add(bug)
def step(self):
self.schedule.step()
self.datacollector.collect(self)
if not(self.grid.exists_empty_cells()):
self.running = False
def _populate(self, food_type):
prefix = "number_of_{}"
counter = 0
while counter < food_type.density * (self.grid.width * self.grid.height):
pos = self.grid.find_empty()
food = food_type(counter, self)
self.grid.place_agent(food, pos)
self.schedule.add(food)
food_name = food_type.__name__.lower()
attr_name = prefix.format(food_name)
val = getattr(self, attr_name)
val += 1
setattr(self, attr_name, val)
counter += 1
开发者ID:dadaromeo,项目名称:bayes-dap,代码行数:57,代码来源:model.py
示例12: __init__
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)
开发者ID:Avnerus,项目名称:separationbarrier,代码行数:50,代码来源:SeparationBarrier.py
示例13: setUp
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))
开发者ID:CHEN-JIANGHANG,项目名称:mesa,代码行数:16,代码来源:test_grid.py
示例14: __init__
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
开发者ID:nshlapo,项目名称:ComplexSocialModeling,代码行数:16,代码来源:Model.py
示例15: setUp
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))
开发者ID:GeoESW,项目名称:mesa,代码行数:18,代码来源:test_grid.py
示例16: __init__
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
开发者ID:projectmesa,项目名称:Presentations,代码行数:38,代码来源:Schelling.py
示例17: __init__
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.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)
for cell in self.grid.coord_iter():
x = cell[1]
y = cell[2]
if random.random() < self.density:
if 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)
开发者ID:GeoESW,项目名称:mesa,代码行数:37,代码来源:model.py
示例18: TestSingleGrid
class TestSingleGrid(unittest.TestCase):
def setUp(self):
self.space = SingleGrid(50, 50, False)
self.agents = []
for i, pos in enumerate(TEST_AGENTS_GRID):
a = MockAgent(i, None)
self.agents.append(a)
self.space.place_agent(a, pos)
def test_agent_positions(self):
'''
Ensure that the agents are all placed properly.
'''
for i, pos in enumerate(TEST_AGENTS_GRID):
a = self.agents[i]
assert a.pos == pos
def test_remove_agent(self):
for i, pos in enumerate(TEST_AGENTS_GRID):
a = self.agents[i]
assert a.pos == pos
assert self.space.grid[pos[0]][pos[1]] == a
self.space.remove_agent(a)
assert a.pos is None
assert self.space.grid[pos[0]][pos[1]] is None
def move_agent(self):
agent_number = 0
initial_pos = TEST_AGENTS_GRID[agent_number]
final_pos = (7, 7)
_agent = self.agents[agent_number]
assert _agent.pos == initial_pos
assert self.space.grid[initial_pos[0]][initial_pos[1]] == _agent
assert self.space.grid[final_pos[0]][final_pos[1]] is None
self.space.move_agent(_agent, final_pos)
assert _agent.pos == final_pos
assert self.space.grid[initial_pos[0]][initial_pos[1]] is None
assert self.space.grid[final_pos[0]][final_pos[1]] == _agent
开发者ID:bangtree,项目名称:mesa,代码行数:40,代码来源:test_space.py
示例19: SchellingModel
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()
开发者ID:nshlapo,项目名称:ComplexSocialModeling,代码行数:65,代码来源:Model.py
示例20: TestSingleGrid
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])
开发者ID:CHEN-JIANGHANG,项目名称:mesa,代码行数:54,代码来源:test_grid.py
注:本文中的mesa.space.SingleGrid类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论