mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Improving GroupBy

Open quaquel opened this issue 8 months ago • 16 comments

AgentSet has a groupby operation that returns a GroupBy instance. However, to access the underlying groups, you need to do my_grouping.groups[some_identifier] or my_grouping.groups.get(some_identifier, None). I am wondering whether it makes sense to add __getitem__ and get(key, default=None) to GroupBy to shorten this to my_grouping[some_idenfier] and my_grouping.get(key, default=None). Thoughts are welcome, but please don't open a PR on this until there is agreement that it's a good idea. The PR itself is really trivial.

quaquel avatar Apr 02 '26 07:04 quaquel

I like this idea but I have a small concern. Currently, GroupBy is a lightweight wrapper and __getitem__ and get() might somewhere give a feel that it follows Mapping Protocol. Once muscle memory kicks in, users might inevitably try things like if "infected" in grouping: (which fails without __contains__) or grouping.keys() (throws an AttributeError). I see two paths:

  1. Go all-in on the Mapping Protocol
  2. Add an explicit .get_group(key)

Honestly, at least for now, I don't think the added complexity of fully implementing option 1 is worth the ergonomic benefits. I'd lean toward option 2 to keep things explicit, safe, and lightweight. What do you think? Any other options apart from these 2?

codebreaker32 avatar Apr 02 '26 15:04 codebreaker32

Fair enough. The mesa GroupBy class was inspired by pandas DataFrameGroupBy. The main method that the latter has, which we miss on the Mesa side is get_group, so adding that aligns with @codebreaker32's suggestion. The main question that then remains is how to handle passing a group key that does not exist.

quaquel avatar Apr 03 '26 06:04 quaquel

The main question that then remains is how to handle passing a group key that does not exist.

The first instinct is to mirror Pandas default behavior(i.e raising KeyError) but I think that may be dangerous for ABM. What if we add a default keyword which can raise KeyError for appropriate value(or None)?

codebreaker32 avatar Apr 03 '26 08:04 codebreaker32

I was also thinking in the direction of adding a default keyword option. But should None mean returning None or returning an empty agentset?

quaquel avatar Apr 03 '26 08:04 quaquel

I think None would be better so users can write standard logic to handle it

codebreaker32 avatar Apr 03 '26 09:04 codebreaker32

Does this implementation looks good to you?

_MISSING = object()

def get_group(self, name, default=_MISSING):
    if name in self.groups:
        return self.groups[name]
    if default is not _MISSING:
        return default
    raise KeyError(f"No group found with name: {name}")

codebreaker32 avatar Apr 04 '26 13:04 codebreaker32

I continued working on a small exam model, where I first ran into the limitations on GroupBy. I now do grouped_agents.groups.get(False, AgentSet([], random=self.random)).shuffle_do("step").

If we have get_group, the most sensible default in my view would be just an empty AgentSet. In which case the above becomes grouped_agents.get_group(False).shuffle_do("step"). Curious to get @codebreaker32 perspective.

quaquel avatar Apr 06 '26 18:04 quaquel

This syntax is undeniably clean. One thing that I keep coming back to is Errors should never pass silently . Suppose if I write grouped_agents.get_group("infcted").shuffle_do("step"), there's a small typo in "infected" but users won't know it if default will be an empty AgentSet. The loop will quietly execute on zero agents, no error will be thrown, and the user's simulation results will be silently corrupted without them ever knowing why. I am aware that this trap is still prevalent and also if some other default is set. This was one of my motive to raise KeyError and unsure about other scenarios. Thoughts @quaquel ?

codebreaker32 avatar Apr 07 '26 09:04 codebreaker32

That is a good point. But with the normal get on dict, you can also have a situation like this. Basically, with dicts, we have two routes. One which raises a keyerror and one where you can control the return value. Here we might want to collapse both into a single method, but than we need to use default or some other kwarg to control this behaviour.

quaquel avatar Apr 07 '26 09:04 quaquel

I have shared an implementation idea above. Does it makes sense to you? I think it kind of provides both behavior

codebreaker32 avatar Apr 07 '26 14:04 codebreaker32

It looks fine, I am just not entirely sure about the _MISSING sentinel. Is this because you want to give the user the option to have None as a default which then won't raise an exception?

quaquel avatar Apr 08 '26 06:04 quaquel

Is this because you want to give the user the option to have None as a default which then won't raise an exception?

Yes, exactly.

codebreaker32 avatar Apr 08 '26 07:04 codebreaker32

Is this ready for a PR using get_group(name, default=_MISSING) that raises KeyError when no default is provided and returns the supplied default, including None, otherwise?

pragnyanramtha avatar May 13 '26 19:05 pragnyanramtha

Not yet

codebreaker32 avatar May 14 '26 09:05 codebreaker32

I am slowly getting back on lline. So let's get this done. @codebreaker32, what about the below minor change to your code?

def get_group(self, name, default=_MISSING):
    try:
        return self.groups[name]
    except KeyError as e:
        if default is not _MISSING:
            return default
        raise KeyError(f"No group found with name: {name}") from e

quaquel avatar May 14 '26 09:05 quaquel

yes, that looks perfect to me. Let's get it done

codebreaker32 avatar May 14 '26 14:05 codebreaker32