Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Use Mesa 2.2 API for Trading Sugarscape #99

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 6 additions & 28 deletions examples/sugarscape_g1mt/sugarscape_g1mt/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,17 @@ def __init__(
self.enable_trade = enable_trade
self.running = True

# initiate activation schedule
self.schedule = mesa.time.RandomActivationByType(self)
# initiate mesa grid class
self.grid = mesa.space.MultiGrid(self.width, self.height, torus=False)
# initiate datacollector
self.datacollector = mesa.DataCollector(
model_reporters={
"Trader": lambda m: m.schedule.get_type_count(Trader),
"Trader": lambda m: len(m.get_agents_of_type(Trader)),
"Trade Volume": lambda m: sum(
len(a.trade_partners)
for a in m.schedule.agents_by_type[Trader].values()
len(a.trade_partners) for a in m.get_agents_of_type(Trader)
),
"Price": lambda m: geometric_mean(
flatten(
[a.prices for a in m.schedule.agents_by_type[Trader].values()]
)
flatten([a.prices for a in m.get_agents_of_type(Trader)])
),
},
agent_reporters={"Trade Network": lambda a: get_trade(a)},
Expand All @@ -98,7 +93,6 @@ def __init__(
max_sugar = sugar_distribution[x, y]
max_spice = spice_distribution[x, y]
resource = Resource(agent_id, self, (x, y), max_sugar, max_spice)
self.schedule.add(resource)
self.grid.place_agent(resource, (x, y))
agent_id += 1

Expand Down Expand Up @@ -133,34 +127,21 @@ def __init__(
)
# place agent
self.grid.place_agent(trader, (x, y))
self.schedule.add(trader)
agent_id += 1

def randomize_traders(self):
"""
helper function for self.step()

puts traders in randomized list for step function
"""

traders_shuffle = list(self.schedule.agents_by_type[Trader].values())
self.random.shuffle(traders_shuffle)

return traders_shuffle

def step(self):
"""
Unique step function that does staged activation of sugar and spice
and then randomly activates traders
"""
# step Resource agents
for resource in self.schedule.agents_by_type[Resource].values():
for resource in self.get_agents_of_type(Resource):
resource.step()

# step trader agents
# to account for agent death and removal we need a seperate data strcuture to
# iterate
trader_shuffle = self.randomize_traders()
trader_shuffle = self.get_agents_of_type(Trader).shuffle(inplace=True)

for agent in trader_shuffle:
agent.prices = []
Expand All @@ -175,10 +156,7 @@ def step(self):
self.datacollector.collect(self)
return

trader_shuffle = self.randomize_traders()

for agent in trader_shuffle:
agent.trade_with_neighbors()
self.get_agents_of_type(Trader).shuffle(inplace=True).do("trade_with_neighbors")

self._steps += 1
# collect model level data
Expand Down
29 changes: 13 additions & 16 deletions examples/sugarscape_g1mt/sugarscape_g1mt/server.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mesa

from .model import SugarscapeG1mt
from .resource_agents import Spice, Sugar
from .resource_agents import Resource
from .trader_agents import Trader

sugar_dic = {4: "#005C00", 3: "#008300", 2: "#00AA00", 1: "#00F800"}
Expand All @@ -21,9 +21,18 @@ def Agent_portrayal(agent):
"Color": "#FF0A01",
}

elif isinstance(agent, Sugar):
color = sugar_dic[agent.amount] if agent.amount != 0 else "#D6F5D6"
layer = 1 if agent.amount > 2 else 0
elif isinstance(agent, Resource):
resource_type = "sugar" if agent.max_sugar > agent.max_spice else "spice"
if resource_type == "sugar":
color = (
sugar_dic[agent.sugar_amount] if agent.sugar_amount != 0 else "#D6F5D6"
)
layer = 1 if agent.sugar_amount > 2 else 0
else:
color = (
spice_dic[agent.spice_amount] if agent.spice_amount != 0 else "#D6F5D6"
)
layer = 1 if agent.spice_amount > 2 else 0
return {
"Color": color,
"Shape": "rect",
Expand All @@ -33,18 +42,6 @@ def Agent_portrayal(agent):
"h": 1,
}

elif isinstance(agent, Spice):
color = spice_dic[agent.amount] if agent.amount != 0 else "#D6F5D6"
layer = 1 if agent.amount > 2 else 0
return {
"Color": color,
"Shape": "rect",
"Filled": "true",
"Layer": 0,
"w": 1,
"h": 1,
}

return {}


Expand Down
2 changes: 1 addition & 1 deletion examples/sugarscape_g1mt/sugarscape_g1mt/trader_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def maybe_die(self):

if self.is_starved():
self.model.grid.remove_agent(self)
self.model.schedule.remove(self)
self.remove()

def trade_with_neighbors(self):
"""
Expand Down
4 changes: 2 additions & 2 deletions examples/sugarscape_g1mt/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_decreasing_price_variance():
model.datacollector._new_model_reporter(
"price_variance",
lambda m: np.var(
flatten([a.prices for a in m.schedule.agents_by_type[Trader].values()])
flatten([a.prices for a in m.get_agents_of_type(Trader)])
),
)
model.run_model(step_count=50)
Expand All @@ -40,7 +40,7 @@ def calculate_carrying_capacities(enable_trade):
for vision_max in visions:
model = SugarscapeG1mt(vision_max=vision_max, enable_trade=enable_trade)
model.run_model(step_count=50)
carrying_capacities.append(len(model.schedule.agents_by_type[Trader]))
carrying_capacities.append(len(model.get_agents_of_type(Trader)))
return carrying_capacities

# Carrying capacity should increase over mean vision (figure IV-6).
Expand Down
Loading