Skip to content

Keep agent ids and field names in JSONDataRecorder numpy snapshots - #4061

Merged
quaquel merged 2 commits into
mesa:mainfrom
lahari936:fix-json-recorder-numpy-agent-ids
Nov 20, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
lahari936:fix-json-recorder-numpy-agent-ids

Conversation

@lahari936

@lahari936 lahari936 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

When JSONDataRecorder records a NumpyAgentDataSet, it stores the bare array and nothing else. Neither the saved file nor get_table_dataframe() says which agent a row belongs to or which field a value is.

Bug / Issue

There is no issue for this yet. Reproduction on main (c9600b8):

from mesa import Agent, Model
from mesa.experimental.data_collection import DataRecorder, DatasetConfig, JSONDataRecorder


class Person(Agent):
    def __init__(self, model, wealth):
        super().__init__(model)
        self.wealth = wealth


for recorder_class in (DataRecorder, JSONDataRecorder):
    model = Model()
    model.data_registry.track_agents_numpy(Person, "people", fields=["wealth"], n=3)
    Person.create_agents(model, 3, [10.0, 20.0, 30.0])
    recorder = recorder_class(model, {"people": DatasetConfig()})
    model.step()
    print(recorder_class.__name__)
    print(recorder.get_table_dataframe("people"), "\n")

On main:

DataRecorder
   agent_id  wealth  time
0         1    10.0   0.0
1         2    20.0   0.0
2         3    30.0   0.0

JSONDataRecorder
   time                     value
0   0.0  [[10.0], [20.0], [30.0]]

With this PR the JSON recorder returns the same table as DataRecorder. ParquetDataRecorder and SQLDataRecorder already return agent_id, the fields and time.

The agent ids are not in the saved .json file either. NumpyAgentDataSet removes an agent by moving the last row into its place, so the position of a row does not identify an agent once anyone has been removed.

Implementation

In JSONDataRecorder._store_dataset_snapshot, an array from a dataset that has agent_ids is stored as one dict per agent, {"agent_id": ..., <field>: ...}. That is the shape the recorder already uses for an AgentDataSet, so get_table_dataframe() needs no change. An array from a dataset without agent ids is stored as nested lists, as before.

Testing

  • test_json_recorder_numpy_dataset_keeps_agent_ids_and_field_names checks the dataframe columns and values and the content of the saved file. It fails on main and passes here.
  • test_json_recorder_stores_a_plain_array_as_a_list pins the unchanged behaviour for a custom dataset.
  • test_json_recorder_numpy_dataset_ids_stay_aligned_after_removal (suggested in review) removes an agent so the last row swaps into its place, and checks that each id keeps its own values in the recorded data and in the saved file. It fails on main and passes here.
  • pytest tests/experimental/test_datarecorder.py: 88 passed.

Additional Notes

🤖 Generated with Claude Code

…ataset

A NumpyAgentDataSet hands the recorder a bare array of values. The JSON
recorder stored it with tolist() and nothing else, so neither the saved
file nor get_table_dataframe() said which agent a row belonged to or
which field a value was. The dataset removes agents by swapping in the
last row, so row order does not identify an agent either. The dataframe
came back as one row per snapshot with the whole nested list in a
"value" column, where the other three recorders return agent_id, the
fields and time.

Store such a snapshot as one dict per agent, with agent_id and the
field names, which is the shape the recorder already uses for an
AgentDataSet. An array from a dataset without agent ids is stored as
before.

Co-Authored-By: Claude <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 01:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Nov 10, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -1.5% [-2.2%, -0.9%] 🔵 -0.6% [-0.9%, -0.4%]
BoltzmannWealth large 🔵 +1.0% [-0.1%, +2.1%] 🔵 +0.7% [-0.8%, +1.8%]
Schelling small 🔵 -1.0% [-1.5%, -0.4%] 🔵 -0.2% [-1.0%, +0.6%]
Schelling large 🔵 -0.6% [-1.3%, +0.2%] 🔵 -1.9% [-3.0%, -0.7%]
WolfSheep small 🔵 -1.6% [-2.0%, -1.2%] 🔵 +0.4% [-3.8%, +4.7%]
WolfSheep large 🔵 -1.7% [-2.4%, -1.0%] 🔵 -2.2% [-4.1%, -0.3%]
SugarscapeG1mt small 🔵 -1.6% [-2.2%, -1.0%] 🔵 -1.1% [-2.8%, +0.6%]
SugarscapeG1mt large 🔵 +1.3% [-0.5%, +3.2%] 🔵 +1.5% [-0.6%, +3.6%]
BoidFlockers small 🔵 -1.8% [-2.5%, -1.1%] 🔵 -2.4% [-2.9%, -2.0%]
BoidFlockers large 🔵 +0.7% [-0.1%, +1.6%] 🔵 -0.0% [-0.3%, +0.2%]
MultiLevelAllianceModel small 🔵 +3.6% [+2.3%, +4.9%] 🔵 +0.2% [-0.1%, +0.6%]
MultiLevelAllianceModel large 🔵 +1.5% [-0.2%, +3.2%] 🔵 +1.0% [+0.1%, +1.9%]

@atul-upadhyay-7 atul-upadhyay-7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the agent ids stay aligned with their values after a swap-with-last removal, in both the dataframe and saved json. earlier rows stay unchanged, and plain arrays keep their previous format. no issue found in those cases. lgtm.

@lahari936

lahari936 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

sorry, the body was just the commit message. i'll rewrite it with the bug-fix template, the reproducer and the test result, and fix the title.

@arzaanxeng arzaanxeng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic looks right to me. I checked this locally: after a swap-with-last removal, ids stay with their values in both the dataframe and the saved JSON.

One request: the tests don't cover removal, which is the main motivation for this change. Here is a regression test. It passes on this branch and fails on the pre-PR code, since the old format has no agent_id keys:

def test_json_recorder_numpy_dataset_ids_stay_aligned_after_removal(tmp_path):
    """Removing an agent swaps the last row in; each id must keep its own values."""
    model = MockModel(n=4)  # agent ids 1-4 hold value 0-3 (other_value is 2 * value)
    recorder = JSONDataRecorder(
        model, {"numpy_data": DatasetConfig()}, output_dir=tmp_path
    )
    recorder.collect()

    # Removing agent 1 moves agent 4's row into row 0 (swap-with-last).
    next(agent for agent in model.agents if agent.unique_id == 1).remove()
    recorder.collect()

    before, after = recorder.data["numpy_data"]
    assert {row["agent_id"]: row["value"] for row in before["data"]} == {
        1: 0.0,
        2: 1.0,
        3: 2.0,
        4: 3.0,
    }
    # Row order changed, so this only passes if ids travel with their values.
    assert after["data"][0]["agent_id"] == 4
    assert {row["agent_id"]: row["value"] for row in after["data"]} == {
        2: 1.0,
        3: 2.0,
        4: 3.0,
    }
    assert all(row["other_value"] == 2 * row["value"] for row in after["data"])

    recorder.save_to_json()
    with open(tmp_path / "numpy_data.json") as f:
        saved = json.load(f)
    assert [snapshot["data"] for snapshot in saved] == [
        before["data"],
        after["data"],
    ]

It can go right after test_json_recorder_numpy_dataset_keeps_agent_ids_and_field_names.

Two non-blocking points:

  1. A snapshot with zero agents is stored as [], and get_table_dataframe turns it into a {"time": ..., "value": []} row. The Parquet and SQL recorders skip empty arrays (data.size > 0), so this is inconsistent. It behaved the same before this PR.
  2. A tracked field named agent_id silently overwrites the real id in {"agent_id": ..., **fields}, so the actual ids are lost.

Also, the PR description is empty. Could you fill in the template and link an issue?

@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

the id and field-name fix still looks good, but the description hasn't selected the bug-fix template yet. could you fill its sections with a small reproducer and the test command/results, remove the leftover template chooser, and fix the cut-off title and opening line?

@lahari936

Copy link
Copy Markdown
Contributor Author

thanks for the test, added as-is (b71912a). it fails without the change (TypeError on the old list-of-lists format) and passes with it, 88 passed in test_datarecorder.py.

on your two other points:

  1. empty snapshots: same as before this PR. Record TableDataSet rows once in data recorders #3969 deals with it, so i left it out here.
  2. a field literally named agent_id: it isn't json-specific, DataRecorder also gives two agent_id columns for that model, so it needs a guard in the dataset/registry rather than in this recorder. happy to open a small issue for it if you think it's worth it.

i'll also fill in the description.

@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

@lahari936 the checks are green now. could you fix the cut-off title and opening line, and fill in the bug-fix template with the reproducer and test results? the template chooser is still in the description.

@lahari936 lahari936 changed the title Keep agent ids and field names when JSONDataRecorder stores a numpy d… Keep agent ids and field names in JSONDataRecorder numpy snapshots Nov 12, 2026
@lahari936

Copy link
Copy Markdown
Contributor Author

sorry for the delay on this. title is fixed now, and i filled in the description with the bug-fix template: a small reproducer with the before/after output, the implementation, and the test results (88 passed, including arzaan's removal test). the template chooser is gone too.

@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

@lahari936 checked b71912a. the title and bug-fix sections are clear now. i reran the reproducer and all 88 recorder tests, including the removal test. both regression tests fail on unchanged main, while the plain-array control passes. ids stay with their values in the recorded data and saved json. lgtm for this fix.

Comment on lines +328 to 338
snapshot = data.tolist()
dataset = self.registry.datasets[dataset_name]
# A numpy agent dataset holds bare values. Name them and say
# whose they are, or the rows cannot be told apart later.
if hasattr(dataset, "agent_ids"):
snapshot = [
{"agent_id": agent_id, **dict(zip(dataset._attributes, row))}
for agent_id, row in zip(dataset.agent_ids.tolist(), snapshot)
]
self.data[dataset_name].append({"time": time, "data": snapshot})
case _:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure about this approach although it is technically fine.

Should numpy agent datasets not be converted to a json format somewhere higher up in the stack? Basically, convert it into a dictionary with the data, and the agent id?

@lahari936

Copy link
Copy Markdown
Contributor Author

good question, i had to go back and look. right now all four recorders get the array from NumpyAgentDataSet.data and each one reads dataset.agent_ids and dataset._attributes itself to pair the ids and field names with it (DataRecorder stacks the ids as a column, Parquet and SQL build a dataframe with those columns). JSON was the only one that dropped them, so that's all this PR changes.

moving it up the stack would mean the dataset hands out records instead of the array. i'd rather not change .data, since the other three use the array directly, and as far as i can tell not building a dict per agent on every snapshot is the point of the numpy dataset.

what i could do instead is add a small method on the dataset that returns the {"agent_id": ..., field: ...} rows, and have the JSON recorder call that instead of zipping them itself. then the pairing lives in one place and the other recorders are untouched. happy to do that, or keep it as it is. which would you prefer?

@mesa-triage-bot

Copy link
Copy Markdown

Thanks @lahari936 for explaining the recorder paths and offering a helper. NumpyAgentDataSet.data currently returns an array view, and the other recorders pair it with IDs and field names themselves.

@quaquel, should #4061 keep conversion in the JSON recorder or use the dataset helper offered in the latest reply? I'd favor the helper: it puts ID/field pairing on the dataset while preserving .data for the other recorders.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

@quaquel
quaquel merged commit feb8845 into mesa:main Nov 20, 2026
16 checks passed
quaquel pushed a commit that referenced this pull request Nov 20, 2026
…#4157)

JSONDataRecorder.data now holds a bounded deque per dataset (#4072), while the test added in #4061 compares it to a list, so main fails test_json_recorder_stores_a_plain_array_as_a_list. Convert to a list before comparing.
EwoutH pushed a commit to EwoutH/mesa that referenced this pull request Nov 22, 2026
…esa#4061)

* Keep agent ids and field names when JSONDataRecorder stores a numpy dataset

A NumpyAgentDataSet hands the recorder a bare array of values. The JSON
recorder stored it with tolist() and nothing else, so neither the saved
file nor get_table_dataframe() said which agent a row belonged to or
which field a value was. The dataset removes agents by swapping in the
last row, so row order does not identify an agent either. The dataframe
came back as one row per snapshot with the whole nested list in a
"value" column, where the other three recorders return agent_id, the
fields and time.

Store such a snapshot as one dict per agent, with agent_id and the
field names, which is the shape the recorder already uses for an
AgentDataSet. An array from a dataset without agent ids is stored as
before.

Co-Authored-By: Claude <[email protected]>

* Test that agent ids stay with their values after a removal

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
(cherry picked from commit feb8845)
EwoutH pushed a commit to EwoutH/mesa that referenced this pull request Nov 22, 2026
…mesa#4157)

JSONDataRecorder.data now holds a bounded deque per dataset (mesa#4072), while the test added in mesa#4061 compares it to a list, so main fails test_json_recorder_stores_a_plain_array_as_a_list. Convert to a list before comparing.

(cherry picked from commit e89f241)
EwoutH added a commit to EwoutH/mesa that referenced this pull request Nov 22, 2026
Add mesa#3913, mesa#4061, mesa#4072, mesa#4105, mesa#4126, mesa#4136, mesa#4141, mesa#4157, mesa#4161 and the Starlette 1.x support backported from mesa#4007, and move the release date to 2026-11-22.

Assisted-by: Claude Opus 5.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants