Repository navigation
Keep agent ids and field names in JSONDataRecorder numpy snapshots - #4061
Conversation
…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]>
|
Performance benchmarks:
|
atul-upadhyay-7
left a comment
There was a problem hiding this comment.
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.
|
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
left a comment
There was a problem hiding this comment.
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:
- A snapshot with zero agents is stored as
[], andget_table_dataframeturns 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. - A tracked field named
agent_idsilently 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?
|
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? |
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
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:
i'll also fill in the description. |
|
@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. |
|
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. |
|
@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. |
| 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 _: |
There was a problem hiding this comment.
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?
|
good question, i had to go back and look. right now all four recorders get the array from moving it up the stack would mean the dataset hands out records instead of the array. i'd rather not change what i could do instead is add a small method on the dataset that returns the |
|
Thanks @lahari936 for explaining the recorder paths and offering a helper. @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 Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
…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)
…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)
Pre-PR Checklist
Summary
When
JSONDataRecorderrecords aNumpyAgentDataSet, it stores the bare array and nothing else. Neither the saved file norget_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):On
main:With this PR the JSON recorder returns the same table as
DataRecorder.ParquetDataRecorderandSQLDataRecorderalready returnagent_id, the fields andtime.The agent ids are not in the saved
.jsonfile either.NumpyAgentDataSetremoves 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 hasagent_idsis stored as one dict per agent,{"agent_id": ..., <field>: ...}. That is the shape the recorder already uses for anAgentDataSet, soget_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_nameschecks the dataframe columns and values and the content of the saved file. It fails onmainand passes here.test_json_recorder_stores_a_plain_array_as_a_listpins 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 onmainand passes here.pytest tests/experimental/test_datarecorder.py: 88 passed.Additional Notes
value == [], as it does for anAgentDataSettoday. Record TableDataSet rows once in data recorders #3969 addresses that.🤖 Generated with Claude Code