from mesa.datacollection import DataCollector class MyModel(Model): def __init__(self): self.datacollector = DataCollector(model_reporters={"Count": lambda m: m.schedule.get_agent_count()}) def step(self): # model step code self.datacollector.collect(self) def run_model(self): self.datacollector.collect(self) # run model code model = MyModel() model.run_model() count_df = model.datacollector.get_model_vars_dataframe()
from mesa.datacollection import DataCollector class MyAgent(Agent): def __init__(self, unique_id, model): self.wealth = 0 self.model = model self.unique_id = unique_id def step(self): if self.wealth > 0: other_agent = self.random.choice(self.model.schedule.agents) other_agent.wealth += 1 self.wealth -= 1 class MyModel(Model): def __init__(self, N): self.schedule = RandomActivation(self) self.datacollector = DataCollector( model_reporters={"Gini": lambda m: compute_gini([a.wealth for a in m.schedule.agents])}, agent_reporters={"Wealth": lambda a: a.wealth}) for i in range(N): a = MyAgent(i, self) self.schedule.add(a) def step(self): self.datacollector.collect(self) self.schedule.step() def run_model(self, steps): for i in range(steps): self.step() model = MyModel(100) model.run_model(100) wealth_df = model.datacollector.get_agent_vars_dataframe() gini_df = model.datacollector.get_model_vars_dataframe()In this example, we create a model with agents that exchange wealth with other agents. We define agent_reporters that collect the agents' wealth and a model_reporter that computes the Gini coefficient of the model's wealth distribution. We then run the model for 100 steps and collect data at each step. Finally, we retrieve the agent and model data collected using the `get_agent_vars_dataframe` and `get_model_vars_dataframe` methods, respectively. Package library: mesa.