Skip to content

Commit bd75e82

Browse files
committed
a few more examples are moved over
1 parent a0aad70 commit bd75e82

File tree

6 files changed

+46
-44
lines changed

6 files changed

+46
-44
lines changed

examples/hotelling_law/hotelling_law/model.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def get_store_price_lambda(unique_id):
140140
"""Return a lambda function that gets the
141141
price of a store by its unique ID."""
142142
return lambda m: next(
143-
(agent.price for agent in m.store_agents if agent.unique_id == unique_id), 0
143+
(agent.price for agent in m.agents_by_type[StoreAgent] if agent.unique_id == unique_id), 0
144144
)
145145

146146
@staticmethod
@@ -150,7 +150,7 @@ def get_market_share_lambda(unique_id):
150150
return lambda m: next(
151151
(
152152
agent.market_share
153-
for agent in m.store_agents
153+
for agent in m.agents_by_type[StoreAgent]
154154
if agent.unique_id == unique_id
155155
),
156156
0,
@@ -163,7 +163,7 @@ def get_revenue_lambda(unique_id):
163163
return lambda m: next(
164164
(
165165
agent.market_share * agent.price
166-
for agent in m.store_agents
166+
for agent in m.agents_by_type[StoreAgent]
167167
if agent.unique_id == unique_id
168168
),
169169
0,
@@ -211,10 +211,10 @@ def step(self):
211211

212212
def recalculate_market_share(self):
213213
# Reset market share for all stores directly
214-
for store in self.store_agents:
214+
for store in self.agents_by_type[StoreAgent]:
215215
store.market_share = 0
216216

217-
for consumer in self.consumer_agents:
217+
for consumer in self.agents_by_type[ConsumerAgent]:
218218
preferred_store = consumer.determine_preferred_store()
219219
if preferred_store:
220220
preferred_store.market_share += 1
@@ -238,16 +238,16 @@ def export_data(self):
238238
def compute_average_price(self):
239239
if len(self.store_agents) == 0:
240240
return 0
241-
return np.mean([agent.price for agent in self.store_agents])
241+
return np.mean([agent.price for agent in self.agents_by_type[StoreAgent]])
242242

243243
# Function to compute the average market share for all store agents,
244244
def compute_average_market_share(self):
245245
if not self.store_agents:
246246
return 0
247247

248-
total_consumers = sum(agent.market_share for agent in self.store_agents)
249-
average_market_share = total_consumers / len(self.store_agents)
248+
total_consumers = sum(agent.market_share for agent in self.agents_by_type[StoreAgent])
249+
average_market_share = total_consumers / len( self.agents_by_type[StoreAgent])
250250
return average_market_share
251251

252252
def compute_price_variance(self):
253-
return np.var([agent.price for agent in self.store_agents])
253+
return np.var([agent.price for agent in self.agents_by_type[StoreAgent]])

examples/pd_grid/pd_grid/agent.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import mesa
22

3+
from mesa.experimental.cell_space import CellAgent
34

4-
class PDAgent(mesa.Agent):
5+
class PDAgent(CellAgent):
56
"""Agent member of the iterated, spatial prisoner's dilemma model."""
67

78
def __init__(self, model, starting_move=None):
@@ -22,14 +23,15 @@ def __init__(self, model, starting_move=None):
2223
self.next_move = None
2324

2425
@property
25-
def isCooroperating(self):
26+
def is_cooroperating(self):
2627
return self.move == "C"
2728

2829
def step(self):
2930
"""Get the best neighbor's move, and change own move accordingly
3031
if better than own score."""
3132

32-
neighbors = self.model.grid.get_neighbors(self.pos, True, include_center=True)
33+
# neighbors = self.model.grid.get_neighbors(self.pos, True, include_center=True)
34+
neighbors = list(self.cell.neighborhood.agents) + [self,]
3335
best_neighbor = max(neighbors, key=lambda a: a.score)
3436
self.next_move = best_neighbor.move
3537

@@ -41,7 +43,7 @@ def advance(self):
4143
self.score += self.increment_score()
4244

4345
def increment_score(self):
44-
neighbors = self.model.grid.get_neighbors(self.pos, True)
46+
neighbors = self.cell.neighborhood.agents
4547
if self.model.activation_order == "Simultaneous":
4648
moves = [neighbor.next_move for neighbor in neighbors]
4749
else:

examples/pd_grid/pd_grid/model.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import mesa
2+
from mesa.experimental.cell_space import OrthogonalMooreGrid
23

34
from .agent import PDAgent
45

5-
66
class PdGrid(mesa.Model):
77
"""Model class for iterated, spatial prisoner's dilemma model."""
88

@@ -25,15 +25,19 @@ def __init__(
2525
Determines the agent activation regime.
2626
payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
2727
"""
28-
super().__init__()
28+
super().__init__(seed=seed)
2929
self.activation_order = activation_order
30-
self.grid = mesa.space.SingleGrid(width, height, torus=True)
30+
# self.grid = mesa.space.SingleGrid(width, height, torus=True)
31+
self.grid = OrthogonalMooreGrid((width, height), torus=True)
32+
33+
if payoffs is not None:
34+
self.payoff = payoffs
3135

3236
# Create agents
3337
for x in range(width):
3438
for y in range(height):
3539
agent = PDAgent(self)
36-
self.grid.place_agent(agent, (x, y))
40+
agent.cell = self.grid[(x, y)]
3741

3842
self.datacollector = mesa.DataCollector(
3943
{

examples/schelling/model.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import mesa
2+
from mesa.experimental.cell_space import CellAgent, OrthogonalMooreGrid
23

34

4-
class SchellingAgent(mesa.Agent):
5+
class SchellingAgent(CellAgent):
56
"""
67
Schelling segregation agent
78
"""
@@ -19,15 +20,13 @@ def __init__(self, model, agent_type):
1920

2021
def step(self):
2122
similar = 0
22-
for neighbor in self.model.grid.iter_neighbors(
23-
self.pos, moore=True, radius=self.model.radius
24-
):
23+
for neighbor in self.cell.get_neighborhood(radius=self.model.radius).agents:
2524
if neighbor.type == self.type:
2625
similar += 1
2726

2827
# If unhappy, move:
2928
if similar < self.model.homophily:
30-
self.model.grid.move_to_empty(self)
29+
self.cell = self.model.grid.select_random_empty_cell()
3130
else:
3231
self.model.happy += 1
3332

@@ -67,7 +66,7 @@ def __init__(
6766
self.homophily = homophily
6867
self.radius = radius
6968

70-
self.grid = mesa.space.SingleGrid(width, height, torus=True)
69+
self.grid = OrthogonalMooreGrid((width, height), torus=True)
7170

7271
self.happy = 0
7372
self.datacollector = mesa.DataCollector(
@@ -78,11 +77,11 @@ def __init__(
7877
# We use a grid iterator that returns
7978
# the coordinates of a cell as well as
8079
# its contents. (coord_iter)
81-
for _, pos in self.grid.coord_iter():
80+
for cell in self.grid.all_cells:
8281
if self.random.random() < self.density:
8382
agent_type = 1 if self.random.random() < self.minority_pc else 0
8483
agent = SchellingAgent(self, agent_type)
85-
self.grid.place_agent(agent, pos)
84+
agent.cell = cell
8685

8786
self.datacollector.collect(self)
8887

examples/schelling_experimental/model.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import mesa
22

3+
from mesa.experimental.cell_space import CellAgent, OrthogonalMooreGrid
34

4-
class SchellingAgent(mesa.Agent):
5+
class SchellingAgent(CellAgent):
56
"""
67
Schelling segregation agent
78
"""
@@ -18,13 +19,13 @@ def __init__(self, model, agent_type):
1819

1920
def step(self):
2021
similar = 0
21-
for neighbor in self.model.grid.iter_neighbors(self.pos, True):
22+
for neighbor in self.cell.neighborhood.agents:
2223
if neighbor.type == self.type:
2324
similar += 1
2425

2526
# If unhappy, move:
2627
if similar < self.model.homophily:
27-
self.model.grid.move_to_empty(self)
28+
self.cell = self.model.grid.select_random_empty_cell()
2829
else:
2930
self.model.happy += 1
3031

@@ -40,7 +41,7 @@ def __init__(self, width=20, height=20, density=0.8, minority_pc=0.2, homophily=
4041
self.height = height
4142
self.homophily = homophily
4243

43-
self.grid = mesa.space.SingleGrid(width, height, torus=True)
44+
self.grid = OrthogonalMooreGrid((width, height), torus=True)
4445

4546
self.happy = 0
4647
self.datacollector = mesa.DataCollector(
@@ -51,11 +52,11 @@ def __init__(self, width=20, height=20, density=0.8, minority_pc=0.2, homophily=
5152
# We use a grid iterator that returns
5253
# the coordinates of a cell as well as
5354
# its contents. (coord_iter)
54-
for _, pos in self.grid.coord_iter():
55+
for cell in self.grid.all_cells:
5556
if self.random.random() < density:
5657
agent_type = 1 if self.random.random() < minority_pc else 0
5758
agent = SchellingAgent(self, agent_type)
58-
self.grid.place_agent(agent, pos)
59+
agent.cell = cell
5960

6061
self.datacollector.collect(self)
6162

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import mesa
22

33

4+
from mesa.experimental.cell_space import OrthogonalMooreGrid
5+
46
class Walker(mesa.Agent):
57
def __init__(self, model, heading=(1, 0)):
68
super().__init__(model)
@@ -13,27 +15,21 @@ def __init__(self, N=2, width=20, height=10):
1315
super().__init__()
1416
self.N = N # num of agents
1517
self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1)) # tuples are fast
16-
self.grid = mesa.space.SingleGrid(width, height, torus=False)
18+
self.grid = OrthogonalMooreGrid((width, height), torus=True)
1719

1820
self.make_walker_agents()
1921
self.running = True
2022

2123
def make_walker_agents(self):
22-
unique_id = 0
23-
while True:
24-
if unique_id == self.N:
25-
break
26-
x = self.random.randrange(self.grid.width)
27-
y = self.random.randrange(self.grid.height)
28-
pos = (x, y)
24+
for _ in range(self.N):
25+
x = self.random.randrange(self.grid.dimensions[0])
26+
y = self.random.randrange(self.grid.dimensions[1])
27+
cell = self.grid[(x, y)]
2928
heading = self.random.choice(self.headings)
3029
# heading = (1, 0)
31-
if self.grid.is_cell_empty(pos):
32-
print(f"Creating agent {unique_id} at ({x}, {y})")
30+
if cell.is_empty:
3331
a = Walker(self, heading)
34-
35-
self.grid.place_agent(a, pos)
36-
unique_id += 1
32+
a.cell = cell
3733

3834
def step(self):
3935
self.agents.shuffle_do("step")

0 commit comments

Comments
 (0)