Repository navigation
Fix DataCollector agenttype reporters to be consistently exact-type - #3797
Conversation
|
Performance benchmarks:
|
shipitdev
left a comment
There was a problem hiding this comment.
I looked over the old implementation where an exact-type lookup (model.agents_by_type[agent_type]) silently dropped subclass agents whenever a direct instance of the parent class existed. Your new implementation makes total sense to me, Moving from scanning all agents
I do have one quick thought on the architecture though:
Right now, DataCollector directly reaches into model.agents_by_type.items(). It might be cleaner if Model (or AgentSet) provided a public helper method for this lookup. That way, DataCollector doesn't need to depend on Model's internal dictionary layout, and simulation developers could easily reuse subclass-inclusive queries in their own model logic as well.
for example something like # Inside Model (or AgentSet)
def get_agents_by_type(self, agent_type: type[A], include_subclasses: bool = True) -> list[A]:
if not include_subclasses:
return list(self._agents_by_type.get(agent_type, []))
return [
agent
for a_type, bucket in self._agents_by_type.items()
if issubclass(a_type, agent_type)
for agent in bucket
] |
|
I am not sure this is a bug or desired behavior that just needs to be documented better. From an analyst point of view, I would argue that it makes much more sense to collect on specific classes and not include subclasses as well. |
|
Thanks both. @quaquel fair point, and exact-type collection is a reasonable analyst view. One thing worth flagging for the decision: the codebase currently leans the other way. Either semantics is defensible, but the current behavior is inconsistent regardless: the same reporter silently flips between including and excluding subclasses depending on whether a direct instance of the type happens to exist. So something should change either way, whether that is consistently subclass-inclusive (this PR) or consistently exact-type. Happy to go whichever way you prefer:
@shipitdev good point on not reaching into Just let me know the intended semantics and I'll align the PR. |
|
I agree with both of you here. The strongest point is the inconsistency, which is the real issue regardless of which direction the fix goes. The |
|
Sounds like we're converging. Concrete plan: Add a public helper on Model so DataCollector doesn't depend on the internal Then have the agenttype reporters call it. On the default: I'll go exact-type, That fixes the inconsistency (the real bug), and the flag covers both preferences |
|
sounds good, i'd say it'd be better if you covered the scope in two PRs - one for adding the helper also Since DataCollector is slated for deprecation, the helper in the model is the piece with real long term value. The Datacollector update is more of a short-term fix. probably best to wait for quaquel before pushing ahead. i'm also happy to co-author or help with a PR if you'd like |
|
Works for me on splitting into two PRs: one adding Model.get_agents_by_type, and I'll hold off on pushing either until you've weighed in, @quaquel: whether you're |
|
I am not sure. We have the agency_by_type attribute already, so adding a get method as well smells funny and seems not particularly pythonic. I am inclined towards documenting more clearly that subclasses are not included and shift the problem to the user if they want to handle this. Also, any idea how this will work with the new dataset data collection stuff? |
oh didn't realize that, that's right. two getter for the same fetch isn't very pythonic. i should look into the new data collection stuff. lemme get back to in sometime |
|
Good points, I'll drop the helper idea. With agents_by_type already there, a On the new dataset collection: it sidesteps this by design. AgentDataSet is built Given that, I'm fine going exact-type for the legacy collector and documenting Minimal fix matching your preference: make the reporter consistently exact-type |
|
I agree with your proposed minimum fix. So document properly and ensure behavior is also always exact-type. |
ff82049 to
a4c8390
Compare
|
Updated to exact-type per your call, @quaquel. Changes:
One extra thing I hit while doing this: with exact-type, a reporter on a type with no exact instances legitimately collects nothing, and Rebased on main. Full suite passes locally (761), ruff clean. |
shipitdev
left a comment
There was a problem hiding this comment.
Looks great, thanks for breaking down the AgentDataSet mechanics and keeping the legacy collector strictly exact-type.
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0. Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (#3797). Co-authored-by: Gracy769 <[email protected]>
…3797) Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit 0683549)
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0. Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (#3797). Co-authored-by: Gracy769 <[email protected]> (cherry picked from commit c45fbb7)
Describe the bug
agenttype_reporterscollect subclass agents inconsistently. Whether a superclass reporter includes its subclass agents depends on whether the superclass also has direct instances:isinstance).agents_by_type[agent_type]).Same reporter, contradictory results, failing silently (wrong/missing rows).
Expected behavior
A reporter keyed on a type should collect all agents that are instances of it, including subclasses, regardless of whether the type has direct instances. This is the behavior the existing
test_agenttype_superclass_reporteralready documents (aMockAgent/Agentreporter collects all 10 subclass agents) — that test only passes today because its model has no direct superclass instances.To Reproduce
Without the direct
Animal(model)line it returns 2 (the Wolves). Adding it flips the result to 1, dropping the subclasses.Root cause
_record_agenttypeused an exact-type lookup (model.agents_by_type[agent_type]) when the type had instances, but anisinstancescan otherwise. The two branches disagree on subclasses.Fix
Always collect subclass-inclusively by iterating the per-type buckets and keeping those whose type is a subclass of the requested type:
This is consistent in all cases, matches the documented
test_agenttype_superclass_reporterintent, and iterates registered types rather than every agent. The non-Agent-typeValueErroris preserved.Test
Added
test_agenttype_reporter_includes_subclasses_with_direct_instances(failsassert 2 == 5on the old code, passes on the fix). All 41test_datacollector.pytests pass under-Werror; ruff clean.Note
I'm aware
DataCollectoris slated for deprecation (#3547). Flagging this anyway because it's a silent data-correctness bug that contradicts existing tested behavior, not a cosmetic one — but happy to close if you'd rather leave the deprecated collector untouched.