mesa icon indicating copy to clipboard operation
mesa copied to clipboard

BatchRunner crashes with sparse data collection (IndexError)

Open Nithin9585 opened this issue 11 months ago โ€ข 3 comments

Describe the bug

batch_run() crashes with IndexError: list index out of range when a model uses sparse data collection (collecting data only at specific steps, not every step). The bug is in batchrunner.py line 256, which incorrectly uses step numbers as list indices.

Expected behavior

batch_run() should work correctly when models collect data only at certain steps (e.g., every 5 steps, or only at the end). This is a common performance optimization to save memory.

To Reproduce

from mesa import Agent, Model
from mesa.datacollection import DataCollector
from mesa.batchrunner import batch_run

class SimpleAgent(Agent):
    def __init__(self, model):
        super().__init__(model)
        self.value = 0
    
    def step(self):
        self.value += 1

class TestModel(Model):
    def __init__(self, rng=None):
        super().__init__(rng=rng)
        self.agent = SimpleAgent(self)
        
        self.datacollector = DataCollector(
            model_reporters={"AgentValue": lambda m: m.agent.value}
        )
        self.running = True
    
    def step(self):
        # Only collect data every 5 steps (sparse collection)
        if self.steps % 5 == 0:
            self.datacollector.collect(self)
        
        self.agent.step()
        
        if self.steps >= 10:
            self.running = False

# This crashes
results = batch_run(
    TestModel,
    parameters={},
    iterations=1,
    max_steps=10,
    data_collection_period=1,
    number_processes=1,
)

Error Output:

IndexError: list index out of range

Traceback:
  File "mesa/batchrunner.py", line 256, in _collect_data
    model_data = {param: values[step] for param, values in dc.model_vars.items()}
                         ~~~~~~^^^^^^

Root Cause:

At line 256 in batchrunner.py:

model_data = {param: values[step] for param, values in dc.model_vars.items()}

The code uses step (a step number like 0, 5, 10) as a list index. But values is a list with only 3 items (indices 0, 1, 2). When it tries values[5] or values[10], it crashes.

Fix Needed:

Map step numbers to the correct list indices instead of using step numbers directly.

Nithin9585 avatar Dec 22 '25 11:12 Nithin9585

๐Ÿ“ CodeRabbit Plan Mode

Generate an implementation plan and prompts that you can use with your favorite coding agent.

  • [ ] Create Plan
Examples

๐Ÿ”— Similar Issues

Related Issues

  • https://github.com/mesa/mesa/issues/2982
  • https://github.com/mesa/mesa/issues/2962
  • https://github.com/mesa/mesa/issues/2958
  • https://github.com/mesa/mesa/issues/2980
๐Ÿ‘ค Suggested Assignees

๐Ÿงช Issue enrichment is currently in open beta.

You can configure auto-planning by selecting labels in the issue_enrichment configuration.

To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

issue_enrichment:
  auto_enrich:
    enabled: false

๐Ÿ’ฌ Have feedback or questions? Drop into our discord or schedule a call!

coderabbitai[bot] avatar Dec 22 '25 11:12 coderabbitai[bot]

@Nithin9585

I looked into this and I think the issue is a wrong use of the API rather than a bug.

  • The batch_run function has a data_collection_period parameter specifically to control when data is collected.
  • When users manually call datacollector_collect() at irregular intervals inside their model's steps() , it conflicts with how batch_run expects to access the data.
from mesa import Agent, Model
from mesa.datacollection import DataCollector

class SimpleAgent(Agent):
    def __init__(self, model):
        super().__init__(model)
        self.value = 0
    
    def step(self):
        self.value += 1

class TestModel(Model):
    def __init__(self, rng=None):
        super().__init__(rng=rng)
        self.agent = SimpleAgent(self)
        
        self.datacollector = DataCollector(
            model_reporters={"AgentValue": lambda m: m.agent.value}
        )
        self.running = True
    
    def step(self):
        if self.steps % 5 == 0:
            self.datacollector.collect(self)
        
        self.agent.step()
        
        if self.steps >= 10:
            self.running = False

model = TestModel()
while model.running:
    model.step()

model_data = model.datacollector.get_model_vars_dataframe()
print(model_data)

@EwoutH Just want to confirm whether this was the idea behind it or it's actually a bug.

codebyNJ avatar Dec 22 '25 19:12 codebyNJ

@codebyNJ @EwoutH Thanks! Just to clarify - should the documentation explicitly say "don't call collect() manually when using batch_run"? That would help users avoid this.

Nithin9585 avatar Dec 23 '25 00:12 Nithin9585