-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
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.