mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Improvements to DataSet and DataRecorder

Open quaquel opened this issue 9 months ago • 25 comments

In #3156, we added a new DataSet for tracking the state of part of the model at any given instance. This DataSet forms the basis of the new approach to data collection. In #3145, we added DataRecorder for takings snapshots of DataSets. However there is ample room for improvements

  • [x] add DataSet.set_dirty_flag(); A major potential benefit of datasets is that we can reuse them elsewhere in the model. However, to fully benefit from this, we need a way of indicating whether the data is clean or dirty. For example, in Boltzmann, we collect wealth data from agents and use this in gini. Ideally, we gather the agent wealth data only once per step. If we have a way of setting, manually, a flag indicating whether the data is clean or needs to be collected again, that would save runtime
  • [ ] Handle run_ended; At the moment, DataRecorder subscribes to model.time ObservableSignals.CHANGED. So whenever time is changed, we collect data. This effectively means that data is collected before the event of the new time is executed. In turn this means that when a run is completed, we do not collect the data after that last event.
  • [ ] Add an ObservableAgentDataSet;
  • [ ] Align AgentDataSet and NumpyDataSet to both use an Agent class instead of the agents for the first and the class for the second.
  • [ ] Agree on and implement an API along the lines of the [conversation here](add DataSet.set_dirty_flag() handle run_ended add a dataset for observables). DataSet.record has already been added. We also agree on the idea of a Snapshot data class. The other ideas are still under consideration.

quaquel avatar Feb 18 '26 10:02 quaquel

  • Handle run_ended; At the moment, DataRecorder subscribes to model.time ObservableSignals.CHANGED. So whenever time is changed, we collect data. This effectively means that data is collected before the event of the new time is executed. In turn this means that when a run is completed, we do not collect the data after that last event.

Hi @quaquel ,

I'd like to take this on.

I see that there are two ways to solve this.

  1. Add a STEP_COMPLETED signal Have DataRecorder subscribe to a lifecycle event emitted after model.step() finishes. This would align snapshots with completed steps and naturally capture the final state. Architecturally this feels better.
  2. Add a RUN_ENDED signal Keeping the current behavior but emit a RUN_ENDED event and collect one final snapshot when the simulation finishes.

let me know which direction you’d prefer and I can start working on it.

som-or avatar Feb 18 '26 12:02 som-or

Right now DataRecorder subscribes to model.time changes. Because _advance_time sets self.time before executing the event, snapshots can be taken before state mutations happen. This means we are effectively recording the previous state and also missing the final state when a run completes.

I think data collection should be tied to execution lifecycle boundaries rather than time mutation. A better approach would be to trigger recording after _do_step or after event execution, so snapshots reflect the actual post-update state.

My idea is to:

  • Move recording to a lifecycle boundary instead of time changes
  • Ensure the final state is captured when a run ends
  • Explore adding a dirty flag to avoid redundant collection

I'll start on a draft PR that moves this to a post-step trigger. This also addresses the run_ended issue and provides a clean hook for the dirty-flag implementation.

souro26 avatar Feb 18 '26 13:02 souro26

I think data collection should be tied to execution lifecycle boundaries rather than time mutation. A better approach would be to trigger recording after _do_step or after event execution, so snapshots reflect the actual post-update state.

No, the choice for tying it to the change of time is very deliberate and we are not going to change that. See the original PR and the data collection discussion for background.

quaquel avatar Feb 18 '26 14:02 quaquel

2. Add a RUN_ENDED signal Keeping the current behavior but emit a RUN_ENDED event and collect one final snapshot when the simulation finishes.

Understood, @quaquel, I'll keep the DataRecorder tied to model.time.

So to resolve the issue of missing the terminal state we can then proceed with the RUN_ENDED signal method. This allows us to capture the final snapshot once the simulation loop concludes without altering the current time-based trigger logic.

I’m happy to submit a PR for the RUN_ENDED implementation. Kindly assign it to me.

som-or avatar Feb 18 '26 15:02 som-or

No, the choice for tying it to the change of time is very deliberate and we are not going to change that. See the original PR and the data collection discussion for background.

Thanks for clarifying that time-based triggering is deliberate, i will keep that invariant. Since run_ended is being handled, I’d like to focus on DataSet.set_dirty_flag(). From the issue description, it seems the main goal is to allow manual control over whether a dataset is considered clean or dirty, so that extraction can be reused within the same simulation instant when appropriate.

Before drafting an implementation, I’d like to clarify:

  • Should dirtiness be purely manually controlled via set_dirty_flag(), or should the framework also invalidate automatically at certain boundaries, such as time progression?
  • Is the intent that this mechanism remains purely an optimization layer, without altering existing snapshot semantics?
  • For composed datasets, like gini depending on wealth, should freshness rely entirely on pull-based access rather than signal chaining?

I want to make sure the semantics are aligned before implementing.

souro26 avatar Feb 18 '26 15:02 souro26

I’m happy to submit a PR for the RUN_ENDED implementation. Kindly assign it to me.

We don't agree yet on how it should be handled, so a PR at this point is premature. Please open a discussion first with your intended approach.

quaquel avatar Feb 18 '26 16:02 quaquel

Before drafting an implementation, I’d like to clarify:

  1. There is no general way to invalidate data. So at best, we can add a method to at least AgentDataSet for setting a is_dirty=True, and on DataSet.data we set is_dirty = True.
  2. only optimization
  3. Ideas are welcome, but let's start with pull based only and only AgentDataSet.

quaquel avatar Feb 18 '26 16:02 quaquel

I went on and implemented the approach I mentioned here

To specifically test the edge case raised by @quaquel, pausing the model, manually scheduling a new event at the paused time, and then resuming, I put together this MRE:

    model = BoltzmannWealth()
    
    model.run_for(5)
    df1 = model.recorder.get_table_dataframe("model_data")
    print(f"Current Dataframe:\n{df1.to_string()}")
    print(f"\nCurrent Gini at time 5.0: {df1.loc[df1['time'] == 5.0, 'gini'].values[0]:.6f}\n")

    def trade():
        for agent in model.agents:
            agent.wealth += 10

    model.schedule_event(trade, at=5.0)
    model.run_until(10)
    
    df2 = model.recorder.get_table_dataframe("model_data")
    print(f"\nFinal Dataframe:\n {df2.to_string()}")
    print(f"\nUpdated Gini at time 5.0 after second run: {df2.loc[df2['time'] == 5.0, 'gini'].values[0]:.6f}\n")

Output:

Current Dataframe:
     gini  time
0  0.0000   0.0
1  0.4766   1.0
2  0.5366   2.0
3  0.5746   3.0
4  0.5478   4.0
5  0.5860   5.0

Current Gini at time 5.0: 0.586000


Final Dataframe:
         gini  time
0   0.000000   0.0
1   0.476600   1.0
2   0.536600   2.0
3   0.574600   3.0
4   0.547800   4.0
5   0.053273   5.0
6   0.074691   6.0
7   0.089000   7.0
8   0.095382   8.0
9   0.105345   9.0
10  0.115018  10.0

Updated Gini at time 5.0 after second run: 0.053273

I would be very much interested to hear what everyone(especially @quaquel) thinks of this approach.

codebreaker32 avatar Feb 22 '26 08:02 codebreaker32

I'll try to post a more elaborate response to the conversation in #3347 as well. But, in short, I am fine with a lightweight deduplication solution on the recorder side. However, I still want to think through in more detail both a RunConfiguration object and the stopping condition problem. Conceptually, with a lightweight solution on the recorder side, these conversations can be handled separately.

quaquel avatar Feb 22 '26 08:02 quaquel

@quaquel, I took some time to walk through the execution flow and the BaseDataRecorder, and I think we can address the terminal snapshot issue without touching the intentional time-based design. From what I understand, the current time → CHANGED subscription is correct — it records the fully completed state of the previous time step (using old). The only gap seems to be that when a run ends without another time change, the final state isn’t captured.

A minimal approach could be:

  • Keep the existing time-based trigger exactly as it is.
  • Emit a small RUN_ENDED signal at the end of run_for() / run_until().
  • Let the recorder listen to that signal and store one final snapshot at model.time, without altering _next_collection or any interval scheduling logic.

To handle edge cases like pause → inject event → resume, the recorder could simply overwrite the last snapshot if it has the same timestamp. That keeps deduplication fully on the recorder side and avoids introducing lifecycle coupling into the execution logic. This way:

  • The time-based semantics remain intact.
  • The final state is always captured.
  • We don’t change step ordering or execution boundaries.
  • The solution stays lightweight and localized.

ShreyasN707 avatar Feb 25 '26 06:02 ShreyasN707

@quaquel I wanted to check the direction you had in mind regarding ObservableAgentDataSet.

Looking at the current datasets, they are all pull-based in the sense they gather values when .data is accessed. But with the signals system and Observable descriptors, agents can also emit ObservableSignals.CHANGED. So I was wondering if the idea behind ObservableAgentDataSet is to subscribe to those change signals and maintain a cached dataset that updates when observables change, instead of recomputing the snapshot every time .data is accessed like AgentDataSet does. Or were you thinking of something simpler that still follows the current pull-based pattern?

souro26 avatar Mar 09 '26 08:03 souro26

@quaquel I wanted to check the direction you had in mind regarding ObservableAgentDataSet.

Yes, the idea is that the dataset subscribes to signals from Agents for a the specified observables and keeps an active view of those. Any call to .data should then return this view.

quaquel avatar Mar 09 '26 08:03 quaquel

I was looking at the align AgentDataSet and NumpyDataSet point and tried to understand what alignment would actually mean in practice. Right now the constructors differ : AgentDataSet(name, agents, ...) and NumpyAgentDataSet(name, agent_type, ...).

I found that they actually operate in quite different ways. AgentDataSet works by iterating over an existing AgentSet and pulling attributes from agent instances. NumpyAgentDataSet on the other hand installs properties on the agent class and stores values directly in a NumPy array. Because of that it needs the class up front to instrument it. So the difference in constructor arguments seems to reflect two different data collection paradigms rather than just an API inconsistency.

From a user perspective, the entry point is usually the DataRegistry anyway, which already provides a reasonably unified interface. Because of that, aligning the dataset constructors themselves might not provide much benefit and could blur the underlying difference between snapshot-style datasets and instrumented NumPy storage. Maybe the real alignment point is keeping the registry API consistent, while allowing the underlying dataset implementations to differ where their mechanisms require it?

souro26 avatar Mar 09 '26 19:03 souro26

I found that they actually operate in quite different ways. AgentDataSet works by iterating over an existing AgentSet and pulling attributes from agent instances. NumpyAgentDataSet on the other hand installs properties on the agent class and stores values directly in a NumPy array. Because of that it needs the class up front to instrument it. So the difference in constructor arguments seems to reflect two different data collection paradigms rather than just an API inconsistency.

I have been going back and forth on this. I am still inclined to align both on passing the agent class. So, AgentData would also collect for all agents of a given class. There have been past conversations about adding selections to this to create a dynamically changing agent data set to collect from. But this was never fully developed. The reason to let AgentData also work on the class is that it keeps the API consistent, avoiding confusion. The benefit of the current design, however, is that you can, in principle, collect on custom agent data sets. I am just not sure how common a use case this is.

quaquel avatar Mar 09 '26 19:03 quaquel

Since alignment on passing the agent class is the direction, then i have a few possible directions that might keep the API consistent while preserving some of that flexibility in the original design

1. Class-based dataset with optional AgentSet override

AgentDataSet("wealth", TraderAgent, fields="wealth", agents=model.agents.select(...))

The class becomes the primary API, but users can still pass a custom AgentSet. This would keep the API aligned while remaining backwards compatible with the current flexibility.

2. Class-based dataset with a selection and filter mechanism

AgentDataSet("wealth", TraderAgent, fields="wealth", selection=...)

Here the dataset would resolve agents of the given class internally and apply an optional predicate or filter. That would keep the public API class-based while still supporting dynamic subsets.

I think the first option would be the better approach right now since its the lowest disruption path, but we can also move towards a dynamically changing agent dataset, although it would likely require additional lifecycle handling for agent creation and removal.

souro26 avatar Mar 09 '26 20:03 souro26

I have been looking at the return of AgentDataSet. This is now a list of dicts. But if I want to say get the wealth of all agents, this means I have to again iterate over all the agents. So, I am wondering whether we should not change the return to be a dict of lists. In that case, I can just get the wealth value from the dict and have a list of values for all agents.

The bigger question here is what is more common: accessing individual agents, or accessing an attribute for all agents.

@codebreaker32, any thoughts?

quaquel avatar Mar 10 '26 13:03 quaquel

I think this question mostly comes down to the expected access pattern. The current list[dict] layout seems more natural when iterating over agents, But for analysis workloads, the common pattern is often attribute-centric rather than agent-centric. If the return structure were dict[list], extracting a single attribute across all agents would become a constant-time lookup rather than requiring another iteration over the dataset.

My suggestion would be to keep the internal representation as a dict of lists but provide a row-oriented view when iterating, similar to how some tabular libraries expose both row and column access. It might also depend on the intended downstream use, for example, if datasets are primarily consumed for analysis or statistics, column-oriented output might be better for that workflow.

souro26 avatar Mar 10 '26 14:03 souro26

I strongly lean toward changing the return type to a dict of lists.

what is more common: accessing individual agents, or accessing an attribute for all agents.

In my experience, accessing an attribute across the entire population is vastly more common. Users typically extract data to calculate aggregations (e.g., Gini coefficient, mean energy, infection rates) or to plot distributions. There is also a hidden performance benefit for the DataRecorder backends we are building. Pandas is fundamentally column-oriented. Constructing a pd.DataFrame({"wealth": [10, 20], "id": [1, 2]}) is highly optimized in C and faster as well i.e dict of lists converts to a DataFrame in a single pd.DataFrame(data) call with no iteration Conceptually, this aligns AgentDataSet with NumpyAgentDataSet. With NumPy, users can grab a whole column instantly via array slicing (data[:, col_idx]). Moving AgentDataSet to a dictionary of lists brings that same $O(1)$ column-access mentality to agents. For this to work, We would just need a minor refactoring on the recorder side and then we are good to go

One more reason because I like it is the upcoming developments around scenario. For that, we are going to need recorder anyway and it is going to be calling this conversion for every scenario in a sweep. Faster per-run conversion compounds quickly at batch scale.

codebreaker32 avatar Mar 10 '26 15:03 codebreaker32

However I have one major concern, each agent is a discrete object holding its own bundle of attributes. Currently, AgentDataSet takes a snapshot by simply zipping the agent's attributes into a dictionary: [dict(zip(self._attributes, self._collector(agent))) for agent in self.agents]. This is a very fast, direct 1:1 mapping from memory.

If you force the dataset to return a dict of lists, Python has to actively unpack and transpose this row-oriented memory into separate columns on the fly during every single simulation step

I would confirm the performance implications after carrying out some profiling on both approaches

codebreaker32 avatar Mar 10 '26 15:03 codebreaker32

I think there should not be a big difference in collection cost between the two layouts. In both cases we still iterate over the agents and collect their attributes each step, so the overall complexity is already O(N). The difference is mainly how the data is arranged after collection. So it would be better to profile both approaches to see whether the layout choice actually has a measurable impact in practice.

souro26 avatar Mar 11 '26 07:03 souro26