Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BatchRunner crashes with sparse data collection (IndexError) #2987

@Nithin9585

Description

@Nithin9585

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugRelease notes label

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions