AgentSet#
AgentSet related classes.
Core Objects: AgentSet, AbstractAgentSet, _HardKeyAgentSet, GroupBy.
- class AbstractAgentSet[source]#
An abstract base collection class that represents an ordered set of agents within an agent-based model (ABM).
This class defines the minimal interface that all AgentSet implementations must follow. Subclasses are free to override methods with optimized implementations based on their storage mechanism (weak references vs strong references).
- select(filter_func: Callable[[A], bool] | None = None, at_most: int | float = inf, inplace: bool = False, agent_type: type[A] | None = None) AbstractAgentSet[A][source]#
Select a subset of agents from the AbstractAgentSet based on a filter function and/or quantity limit.
- Parameters:
filter_func (Callable[[Agent], bool], optional) – A function that takes an Agent and returns True if the agent should be included in the result. Defaults to None, meaning no filtering is applied.
at_most (int | float, optional) – The maximum amount of agents to select. Defaults to infinity. - If an integer, at most the first number of matching agents are selected. - If a float between 0 and 1, at most that fraction of original the agents are selected.
inplace (bool, optional) – If True, modifies the current AbstractAgentSet; otherwise, returns a new AbstractAgentSet. Defaults to False.
agent_type (type[Agent], optional) – The class type of the agents to select. Defaults to None, meaning no type filtering is applied.
- Returns:
A new AbstractAgentSet containing the selected agents, unless inplace is True, in which case the current AbstractAgentSet is updated.
- Return type:
Notes
at_most just return the first n or fraction of agents. To take a random sample, shuffle() beforehand.
at_most is an upper limit. When specifying other criteria, the number of agents returned can be smaller.
- agg(attribute: str, func: Callable | Iterable[Callable]) Any | list[Any][source]#
Aggregate an attribute of all agents in the AgentSet using one or more functions.
- Parameters:
attribute (str) – The name of the attribute to aggregate.
func (Callable | Iterable[Callable]) –
If Callable: A single function to apply to the attribute values (e.g., min, max, sum, np.mean)
If Iterable: Multiple functions to apply to the attribute values
- Returns:
Result of applying the function(s) to the attribute values.
- Return type:
Any | [Any, …]
Examples
# Single function avg_energy = model.agents.agg(“energy”, np.mean)
# Multiple functions min_wealth, max_wealth, total_wealth = model.agents.agg(“wealth”, [min, max, sum])
- get(attr_names: str, handle_missing: Literal['error', 'default'] = 'error', default_value: Any = None) list[Any][source]#
- get(attr_names: list[str], handle_missing: Literal['error', 'default'] = 'error', default_value: Any = None) list[list[Any]]
Retrieve the specified attribute(s) from each agent in the AgentSet.
- Parameters:
attr_names (str | list[str]) – The name(s) of the attribute(s) to retrieve from each agent.
handle_missing (str, optional) – How to handle missing attributes. Can be: - ‘error’ (default): raises an AttributeError if attribute is missing. - ‘default’: returns the specified default_value.
default_value (Any, optional) – The default value to return if ‘handle_missing’ is set to ‘default’ and the agent does not have the attribute.
- Returns:
A list with the attribute value for each agent if attr_names is a str. list[list[Any]]: A list with a lists of attribute values for each agent if attr_names is a list of str.
- Return type:
list[Any]
- Raises:
AttributeError – If ‘handle_missing’ is ‘error’ and the agent does not have the specified attribute(s).
ValueError – If an unknown ‘handle_missing’ option is provided.
- set(attr_name: str, value: Any) AgentSet[A][source]#
Set a specified attribute to a given value for all agents in the AgentSet.
- to_list() list[A][source]#
Convert the AbstractAgentSet to a list.
Notes
This method provides an explicit way to convert the AgentSet to a list. It is the recommended approach when list operations (indexing, slicing) are needed, as direct sequence operations on AgentSet are deprecated and will be removed in Mesa 4.0.
- abstractmethod add(agent: A)[source]#
Add an agent to the AbstractAgentSet.
- Parameters:
agent (Agent) – The agent to add to the set.
Note
This method is an implementation of the abstract method from MutableSet.
- abstractmethod discard(agent: A)[source]#
Remove an agent from the AbstractAgentSet if it exists.
This method does not raise an error if the agent is not present.
- Parameters:
agent (Agent) – The agent to remove from the set.
Note
This method is an implementation of the abstract method from MutableSet.
- abstractmethod remove(agent: A)[source]#
Remove an agent from the AbstractAgentSet.
- Raises:
An Exception if the agent is not present. –
- Parameters:
agent (Agent) – The agent to remove from the set.
Note
This method is an implementation of the abstract method from MutableSet.
- groupby(by: Callable | str, result_type: Literal['agentset', 'list'] = 'agentset') GroupBy[source]#
Group agents by the specified attribute or return from the callable.
- Parameters:
by (Callable, str) –
used to determine what to group agents by
if
byis a callable, it will be called for each agent and the return is used for groupingif
byis a str, it should refer to an attribute on the agent and the value of this attribute will be used for grouping
result_type (str, optional) – The datatype for the resulting groups {“agentset”, “list”}
- Returns:
GroupBy
Notes
There might be performance benefits to using result_type=’list’ if you don’t need the advanced functionality of an AbstractAgentSet.
- abstractmethod shuffle(inplace: bool = False) AbstractAgentSet[A][source]#
Randomly shuffle the order of agents in the AbstractAgentSet.
- abstractmethod sort(key: Callable[[A], Any] | str, ascending: bool = False, inplace: bool = False) AbstractAgentSet[A][source]#
Sort the agents in the AbstractAgentSet based on a specified attribute or custom function.
- abstractmethod do(method: str | Callable, *args, **kwargs) AbstractAgentSet[A][source]#
Invoke a method or function on each agent in the AbstractAgentSet.
- abstractmethod shuffle_do(method: str | Callable, *args, **kwargs) AbstractAgentSet[A][source]#
Shuffle the agents in the AbstractAgentSet and then invoke a method or function on each agent.
- abstractmethod map(method: str | Callable, *args, **kwargs) list[Any][source]#
Invoke a method or function on each agent in the AbstractAgentSet and return the results.
- clear()#
This is slow (creates N new iterators!) but effective.
- isdisjoint(other)#
Return True if two sets have a null intersection.
- pop()#
Return the popped value. Raise KeyError if empty.
- class AgentSet(agents: Iterable[A], random: Random | None = None)[source]#
A collection class that represents an ordered set of agents using weak references.
This implementation uses weak references to agents, allowing for efficient management of agent lifecycles without preventing garbage collection.
- random#
The random number generator for this agent set.
- Type:
Random
Notes
The AgentSet maintains weak references to agents, which means that agents not referenced elsewhere in the program may be automatically removed from the AgentSet. This is the default implementation for most use cases where automatic cleanup is desired.
Performance-critical methods are optimized to work directly with weak references, avoiding the overhead of creating strong references during iteration.
Initialize the AgentSet with weak references to agents.
- Parameters:
agents (Iterable[Agent]) – An iterable of Agent objects to be included in the set.
random (Random | None) – The random number generator for this agent set.
- shuffle(inplace: bool = False) AgentSet[A][source]#
Randomly shuffle the order of agents in the AgentSet.
- Parameters:
inplace (bool, optional) – If True, shuffles the agents in the current AgentSet; otherwise, returns a new shuffled AgentSet. Defaults to False.
- Returns:
A shuffled AgentSet. Returns the current AgentSet if inplace is True.
- Return type:
Note
Using inplace = True is more performant
- sort(key: Callable[[A], Any] | str, ascending: bool = False, inplace: bool = False) AgentSet[A][source]#
Sort the agents in the AgentSet based on a specified attribute or custom function.
- Parameters:
key (Callable[[Agent], Any] | str) – A function or attribute name based on which the agents are sorted.
ascending (bool, optional) – If True, the agents are sorted in ascending order. Defaults to False.
inplace (bool, optional) – If True, sorts the agents in the current AgentSet; otherwise, returns a new sorted AgentSet. Defaults to False.
- Returns:
A sorted AgentSet. Returns the current AgentSet if inplace is True.
- Return type:
- do(method: str | Callable, *args, **kwargs) AgentSet[A][source]#
Invoke a method or function on each agent in the AgentSet.
- Parameters:
method (str, callable) –
the callable to do on each agent
in case of str, the name of the method to call on each agent.
in case of callable, the function to be called with each agent as first argument
*args – Variable length argument list passed to the callable being called.
**kwargs – Arbitrary keyword arguments passed to the callable being called.
- Returns:
The AgentSet instance itself.
- Return type:
- shuffle_do(method: str | Callable, *args, **kwargs) AgentSet[A][source]#
Shuffle the agents in the AgentSet and then invoke a method or function on each agent.
It’s a fast, optimized version of calling shuffle() followed by do().
- map(method: str | Callable, *args, **kwargs) list[Any][source]#
Invoke a method or function on each agent in the AgentSet and return the results.
- Parameters:
method (str, callable) –
the callable to apply on each agent
in case of str, the name of the method to call on each agent.
in case of callable, the function to be called with each agent as first argument
*args – Variable length argument list passed to the callable being called.
**kwargs – Arbitrary keyword arguments passed to the callable being called.
- Returns:
The results of the callable calls
- Return type:
list[Any]
- add(agent: A)[source]#
Add an agent to the AgentSet.
- Parameters:
agent (Agent) – The agent to add to the set.
Note
This method is an implementation of the abstract method from MutableSet.
- discard(agent: A)[source]#
Remove an agent from the AgentSet if it exists.
This method does not raise an error if the agent is not present.
- Parameters:
agent (Agent) – The agent to remove from the set.
Note
This method is an implementation of the abstract method from MutableSet.
- remove(agent: A)[source]#
Remove an agent from the AgentSet.
This method raises an error if the agent is not present.
- Parameters:
agent (Agent) – The agent to remove from the set.
Note
This method is an implementation of the abstract method from MutableSet.
- agg(attribute: str, func: Callable | Iterable[Callable]) Any | list[Any]#
Aggregate an attribute of all agents in the AgentSet using one or more functions.
- Parameters:
attribute (str) – The name of the attribute to aggregate.
func (Callable | Iterable[Callable]) –
If Callable: A single function to apply to the attribute values (e.g., min, max, sum, np.mean)
If Iterable: Multiple functions to apply to the attribute values
- Returns:
Result of applying the function(s) to the attribute values.
- Return type:
Any | [Any, …]
Examples
# Single function avg_energy = model.agents.agg(“energy”, np.mean)
# Multiple functions min_wealth, max_wealth, total_wealth = model.agents.agg(“wealth”, [min, max, sum])
- clear()#
This is slow (creates N new iterators!) but effective.
- count(value) integer -- return number of occurrences of value#
- get(attr_names, handle_missing='error', default_value=None)#
Retrieve the specified attribute(s) from each agent in the AgentSet.
- Parameters:
attr_names (str | list[str]) – The name(s) of the attribute(s) to retrieve from each agent.
handle_missing (str, optional) – How to handle missing attributes. Can be: - ‘error’ (default): raises an AttributeError if attribute is missing. - ‘default’: returns the specified default_value.
default_value (Any, optional) – The default value to return if ‘handle_missing’ is set to ‘default’ and the agent does not have the attribute.
- Returns:
A list with the attribute value for each agent if attr_names is a str. list[list[Any]]: A list with a lists of attribute values for each agent if attr_names is a list of str.
- Return type:
list[Any]
- Raises:
AttributeError – If ‘handle_missing’ is ‘error’ and the agent does not have the specified attribute(s).
ValueError – If an unknown ‘handle_missing’ option is provided.
- groupby(by: Callable | str, result_type: Literal['agentset', 'list'] = 'agentset') GroupBy#
Group agents by the specified attribute or return from the callable.
- Parameters:
by (Callable, str) –
used to determine what to group agents by
if
byis a callable, it will be called for each agent and the return is used for groupingif
byis a str, it should refer to an attribute on the agent and the value of this attribute will be used for grouping
result_type (str, optional) – The datatype for the resulting groups {“agentset”, “list”}
- Returns:
GroupBy
Notes
There might be performance benefits to using result_type=’list’ if you don’t need the advanced functionality of an AbstractAgentSet.
- index(value[, start[, stop]]) integer -- return first index of value.#
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- isdisjoint(other)#
Return True if two sets have a null intersection.
- pop()#
Return the popped value. Raise KeyError if empty.
- select(filter_func: Callable[[A], bool] | None = None, at_most: int | float = inf, inplace: bool = False, agent_type: type[A] | None = None) AbstractAgentSet[A]#
Select a subset of agents from the AbstractAgentSet based on a filter function and/or quantity limit.
- Parameters:
filter_func (Callable[[Agent], bool], optional) – A function that takes an Agent and returns True if the agent should be included in the result. Defaults to None, meaning no filtering is applied.
at_most (int | float, optional) – The maximum amount of agents to select. Defaults to infinity. - If an integer, at most the first number of matching agents are selected. - If a float between 0 and 1, at most that fraction of original the agents are selected.
inplace (bool, optional) – If True, modifies the current AbstractAgentSet; otherwise, returns a new AbstractAgentSet. Defaults to False.
agent_type (type[Agent], optional) – The class type of the agents to select. Defaults to None, meaning no type filtering is applied.
- Returns:
A new AbstractAgentSet containing the selected agents, unless inplace is True, in which case the current AbstractAgentSet is updated.
- Return type:
Notes
at_most just return the first n or fraction of agents. To take a random sample, shuffle() beforehand.
at_most is an upper limit. When specifying other criteria, the number of agents returned can be smaller.
- set(attr_name: str, value: Any) AgentSet[A]#
Set a specified attribute to a given value for all agents in the AgentSet.
- to_list() list[A]#
Convert the AbstractAgentSet to a list.
Notes
This method provides an explicit way to convert the AgentSet to a list. It is the recommended approach when list operations (indexing, slicing) are needed, as direct sequence operations on AgentSet are deprecated and will be removed in Mesa 4.0.
- class GroupBy(groups: dict[Any, list | AbstractAgentSet])[source]#
Helper class for AgentSet.groupby.
Initialize a GroupBy instance.
- Parameters:
groups (dict) – A dictionary with the group_name as key and group as values
- get_group(name: Hashable, default: Any = <object object>) list | AbstractAgentSet | Any[source]#
Return the group for the given name.
- Parameters:
name (Hashable) – The group name to retrieve.
default (Any, optional) – Value to return when the group is missing.
- Raises:
KeyError – If the group does not exist and no default is provided.
- map(method: Callable | str, *args, **kwargs) dict[Any, Any][source]#
Apply the specified callable to each group and return the results.
- Parameters:
method (Callable, str) –
The callable to apply to each group,
if
methodis a callable, it will be called it will be called with the group as first argumentif
methodis a str, it should refer to a method on the group
Additional arguments and keyword arguments will be passed on to the callable.
args – arguments to pass to the callable
kwargs – keyword arguments to pass to the callable
- Returns:
dict with group_name as key and the return of the method as value
Notes
this method is useful for methods or functions that do return something. It will break method chaining. For that, use
doinstead.
- do(method: Callable | str, *args, **kwargs) GroupBy[source]#
Apply the specified callable to each group.
- Parameters:
method (Callable, str) –
The callable to apply to each group,
if
methodis a callable, it will be called it will be called with the group as first argumentif
methodis a str, it should refer to a method on the group
Additional arguments and keyword arguments will be passed on to the callable.
args – arguments to pass to the callable
kwargs – keyword arguments to pass to the callable
- Returns:
the original GroupBy instance
Notes
this method is useful for methods or functions that don’t return anything and/or if you want to chain multiple do calls
- count() dict[Any, int][source]#
Return the count of agents in each group.
- Returns:
A dictionary mapping group names to the number of agents in each group.
- Return type: