| Hosted by CoCalc | Download
Kernel: Python 3 (Ubuntu Linux)

Mesa on CoCalc (Python 3, Ubuntu Linux)

Mesa is a modular framework for building, analyzing and visualizing agent-based models.

https://mesa.readthedocs.io/en/master/tutorials/intro_tutorial.html

import mesa import random mesa
<module 'mesa' from '/usr/local/lib/python3.6/dist-packages/mesa/__init__.py'>
mesa.__version__
'0.8.4'
from mesa import Agent, Model class MoneyAgent(Agent): """An agent with fixed initial wealth.""" def __init__(self, unique_id, model): super().__init__(unique_id, model) self.wealth = 1 class MoneyModel(Model): """A model with some number of agents.""" def __init__(self, N): self.num_agents = N # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self)
from mesa import Agent, Model from mesa.time import RandomActivation class MoneyAgent(Agent): """ An agent with fixed initial wealth.""" def __init__(self, unique_id, model): super().__init__(unique_id, model) self.wealth = 1 def step(self): # The agent's step will go here. pass class MoneyModel(Model): """A model with some number of agents.""" def __init__(self, N): self.num_agents = N self.schedule = RandomActivation(self) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) def step(self): '''Advance the model by one step.''' self.schedule.step()
class MoneyAgent(Agent): """ An agent with fixed initial wealth.""" def __init__(self, unique_id, model): super().__init__(unique_id, model) self.wealth = 1 def step(self): if self.wealth == 0: return other_agent = random.choice(self.model.schedule.agents) other_agent.wealth += 1 self.wealth -= 1
model = MoneyModel(10) for i in range(10): model.step()
import matplotlib.pyplot as plt agent_wealth = [a.wealth for a in model.schedule.agents] plt.hist(agent_wealth)
(array([ 5., 4., 0., 0., 0., 0., 0., 0., 0., 1.]), array([ 0. , 0.6, 1.2, 1.8, 2.4, 3. , 3.6, 4.2, 4.8, 5.4, 6. ]), <a list of 10 Patch objects>)
Image in a Jupyter notebook
all_wealth = [] for j in range(100): # Run the model model = MoneyModel(10) for i in range(10): model.step() # Store the results for agent in model.schedule.agents: all_wealth.append(agent.wealth) plt.hist(all_wealth, bins=range(max(all_wealth)+1))
(array([ 428., 308., 160., 58., 37., 5., 4.]), array([0, 1, 2, 3, 4, 5, 6, 7]), <a list of 7 Patch objects>)
Image in a Jupyter notebook
from mesa.space import MultiGrid
from mesa.space import MultiGrid from mesa import Agent, Model from mesa.time import RandomActivation class MoneyModel(Model): """A model with some number of agents.""" def __init__(self, N, width, height): self.num_agents = N self.grid = MultiGrid(width, height, True) self.schedule = RandomActivation(self) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = random.randrange(self.grid.width) y = random.randrange(self.grid.height) self.grid.place_agent(a, (x, y)) def step(self): self.schedule.step() class MoneyAgent(Agent): """ An agent with fixed initial wealth.""" def __init__(self, unique_id, model): super().__init__(unique_id, model) self.wealth = 1 def move(self): possible_steps = self.model.grid.get_neighborhood( self.pos, moore=True, include_center=False) new_position = random.choice(possible_steps) self.model.grid.move_agent(self, new_position) def give_money(self): cellmates = self.model.grid.get_cell_list_contents([self.pos]) if len(cellmates) > 1: other = random.choice(cellmates) other.wealth += 1 self.wealth -= 1 def step(self): self.move() if self.wealth > 0: self.give_money()
model = MoneyModel(50, 10, 10) for i in range(20): model.step()
import numpy as np agent_counts = np.zeros((model.grid.width, model.grid.height)) for cell in model.grid.coord_iter(): cell_content, x, y = cell agent_count = len(cell_content) agent_counts[x][y] = agent_count plt.imshow(agent_counts, interpolation='nearest') plt.colorbar() # If running from a text editor or IDE, remember you'll need the following: plt.show()
Image in a Jupyter notebook
from mesa.datacollection import DataCollector def compute_gini(model): agent_wealths = [agent.wealth for agent in model.schedule.agents] x = sorted(agent_wealths) N = model.num_agents B = sum( xi * (N-i) for i,xi in enumerate(x) ) / (N*sum(x)) return (1 + (1/N) - 2*B) class MoneyModel(Model): """A model with some number of agents.""" def __init__(self, N, width, height): self.num_agents = N self.grid = MultiGrid(width, height, True) self.schedule = RandomActivation(self) # Create agents for i in range(self.num_agents): a = MoneyAgent(i, self) self.schedule.add(a) # Add the agent to a random grid cell x = random.randrange(self.grid.width) y = random.randrange(self.grid.height) self.grid.place_agent(a, (x, y)) self.datacollector = DataCollector( model_reporters={"Gini": compute_gini}, # A function to call agent_reporters={"Wealth": "wealth"}) # An agent attribute def step(self): self.datacollector.collect(self) self.schedule.step()
model = MoneyModel(50, 10, 10) for i in range(100): model.step()
gini = model.datacollector.get_model_vars_dataframe() gini.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f7605acbc88>
Image in a Jupyter notebook
agent_wealth = model.datacollector.get_agent_vars_dataframe() agent_wealth.head()
Wealth
Step AgentID
0 0 1
1 1
2 1
3 1
4 1
end_wealth = agent_wealth.xs(99, level="Step")["Wealth"] end_wealth.hist(bins=range(agent_wealth.Wealth.max()+1))
<matplotlib.axes._subplots.AxesSubplot at 0x7f7605abee80>
Image in a Jupyter notebook