Agent#
Agent related classes.
Core Objects: Agent and AgentSet.
- class Agent(model: Model, *args, **kwargs)[source]#
Base class for a model agent in Mesa.
- pos#
A reference to the position where this agent is located.
- Type:
Position
Notes
unique_id is unique relative to a model instance and starts from 1
Create a new agent.
- Parameters:
model (Model) – The model instance in which the agent exists.
args – passed on to super
kwargs – passed on to super
Notes
to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super
- remove() None [source]#
Remove and delete the agent from the model.
Notes
If you need to do additional cleanup when removing an agent by for example removing it from a space, consider extending this method in your own agent class.
- classmethod create_agents(model: Model, n: int, *args, **kwargs) AgentSet[Agent] [source]#
Create N agents.
- Parameters:
model – the model to which the agents belong
args – arguments to pass onto agent instances each arg is either a single object or a sequence of length n
n – the number of agents to create
kwargs – keyword arguments to pass onto agent instances each keyword arg is either a single object or a sequence of length n
- Returns:
AgentSet containing the agents created.
- property rng: Generator#
Return a seeded np.random rng.
- class AgentSet(agents: Iterable[Agent], random: Random | None = None)[source]#
A collection class that represents an ordered set of agents within an agent-based model (ABM).
This class extends both MutableSet and Sequence, providing set-like functionality with order preservation and sequence operations.
Notes
The AgentSet maintains weak references to agents, allowing for efficient management of agent lifecycles without preventing garbage collection. It is associated with a specific model instance, enabling interactions with the model’s environment and other agents.The implementation uses a WeakKeyDictionary to store agents, which means that agents not referenced elsewhere in the program may be automatically removed from the AgentSet.
Notes
A UserWarning is issued if random=None. You can resolve this warning by explicitly passing a random number generator. In most cases, this will be the seeded random number generator in the model. So, you would do random=self.random in a Model or Agent instance.
Initializes the AgentSet with a collection of agents and a reference to the model.
- Parameters:
agents (Iterable[Agent]) – An iterable of Agent objects to be included in the set.
random (Random) – the random number generator
- select(filter_func: Callable[[Agent], bool] | None = None, at_most: int | float = inf, inplace: bool = False, agent_type: type[Agent] | None = None) AgentSet [source]#
Select a subset of agents from the AgentSet 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 AgentSet; otherwise, returns a new AgentSet. 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 AgentSet containing the selected agents, unless inplace is True, in which case the current AgentSet 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.
- shuffle(inplace: bool = False) AgentSet [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[[Agent], Any] | str, ascending: bool = False, inplace: bool = False) AgentSet [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 [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 results of the callable calls if return_results is True, otherwise the AgentSet itself.
- Return type:
- shuffle_do(method: str | Callable, *args, **kwargs) AgentSet [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]
- agg(attribute: str, func: Callable) Any [source]#
Aggregate an attribute of all agents in the AgentSet using a specified function.
- Parameters:
attribute (str) – The name of the attribute to aggregate.
func (Callable) – The function to apply to the attribute values (e.g., min, max, sum, np.mean).
- Returns:
The result of applying the function to the attribute values. Often a single value.
- Return type:
Any
- 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 [source]#
Set a specified attribute to a given value for all agents in the AgentSet.
- add(agent: Agent)[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: Agent)[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: Agent)[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.
- groupby(by: Callable | str, result_type: str = '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
by
is a callable, it will be called for each agent and the return is used for groupingif
by
is 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 AgentSet.
- clear()#
This is slow (creates N new iterators!) but effective.
- count(value) integer -- return number of occurrences of value #
- 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.
- class GroupBy(groups: dict[Any, list | AgentSet])[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
- 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
method
is a callable, it will be called it will be called with the group as first argumentif
method
is 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
do
instead.
- 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
method
is a callable, it will be called it will be called with the group as first argumentif
method
is 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: