CoCalc Shared Filesmesa.ipynb
Author: Harald Schilly
Views : 33

# Mesa on CoCalc (Python 3, Ubuntu Linux)

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

In [1]:
import mesa import random mesa
<module 'mesa' from '/usr/local/lib/python3.6/dist-packages/mesa/__init__.py'>
In [2]:
mesa.__version__
'0.8.4'
In [3]:
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)
In [4]:
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()
In [5]:
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
In [6]:
model = MoneyModel(10) for i in range(10): model.step()
In [7]:
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>)
In [8]:
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>)
In [9]:
from mesa.space import MultiGrid
In [10]:
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()
In [11]:
model = MoneyModel(50, 10, 10) for i in range(20): model.step()
In [12]:
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()
In [13]:
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()
In [14]:
model = MoneyModel(50, 10, 10) for i in range(100): model.step()
In [15]:
gini = model.datacollector.get_model_vars_dataframe() gini.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7f7605acbc88>
In [16]: