Agents#
- class mesa_frames.AgentSet(model: Model, name: str | None = None)[source]#
The AbstractAgentSet class is a container for agents of the same type.
- Parameters:
model (mesa_frames.concrete.model.Model) – The model that the agent set belongs to.
AgentSet. (Polars-based implementation of)
Methods:
Initialize a new AgentSet.
Rename this agent set.
Add agents to the AgentSet.
Check if agents with the specified IDs are in the AgentSet.
Invoke a method on the AgentSet.
Retrieve agent attributes as a Series or DataFrame.
Remove agents from this AbstractAgentSet.
Update agent attributes, optionally on a masked subset.
Update the active-agent mask using selection criteria.
Randomly permute agent order.
Sort agents by one or more columns.
Add agents to a new AbstractAgentSet through the + operator.
Membership test for an agent id in this set.
Create a shallow copy of the AbstractAgentSetRegistry.
Create a deep copy of the AbstractAgentSetRegistry.
Add agents to the AbstractAgentSet through the += operator.
Remove agents via -= operator.
Return repr(self).
Set values using [] syntax, delegating to set().
Return str(self).
Return a new set with agents removed via - operator.
Create a copy of the Class.
Remove an agent from the AbstractAgentSet.
Run a single step of the AbstractAgentSet.
Attributes:
Return the parent model for this agent set.
Return the random number generator shared with the model.
Return the space attached to the parent model, if any.
Return the full backing DataFrame for this agent set.
Return the subset of agents currently marked as active.
Return the subset of agents currently marked as inactive.
Return the unique identifier index for agents in this set.
Return positional data for agents from the attached space.
Return the name of the AgentSet.
- __init__(model: Model, name: str | None = None) None[source]#
Initialize a new AgentSet.
- Parameters:
model ("mesa_frames.concrete.model.Model") – The model that the agent set belongs to.
name (str | None, optional) – Name for this agent set. If None, class name is used. Will be converted to snake_case if in camelCase.
- rename(new_name: str, inplace: bool = True) Self[source]#
Rename this agent set. If attached to AgentSetRegistry, delegate for uniqueness enforcement.
- Parameters:
- Returns:
The updated AgentSet (or a renamed copy when
inplace=False).- Return type:
Self
- Raises:
ValueError – If name conflicts occur and delegate encounters errors.
- add(agents: DataFrame | Sequence[Any] | dict[str, Any], inplace: bool = True) Self[source]#
Add agents to the AgentSet.
- contains(agents: int) bool[source]#
- contains(agents: int | Collection[int] | Series | DataFrame) Series
Check if agents with the specified IDs are in the AgentSet.
- Parameters:
agents (IdsLike) – The ID(s) to check for.
- Returns:
True if the agent is in the AgentSet, False otherwise.
- Return type:
bool | BoolSeries
- do(method_name: str, *args, mask: Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame = None, return_results: Literal[False] = False, inplace: bool = True, **kwargs) Self[source]#
- do(method_name: str, *args, mask: Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame = None, return_results: Literal[True], inplace: bool = True, **kwargs) Any
Invoke a method on the AgentSet.
- Parameters:
method_name (str) – The name of the method to invoke.
*args (Any) – Positional arguments to pass to the method
mask (AgentMask | None, optional) – The subset of agents on which to apply the method
return_results (bool, optional) – Whether to return the result of the method, by default False
inplace (bool, optional) – Whether the operation should be done inplace, by default False
**kwargs (Any) – Keyword arguments to pass to the method
- Returns:
The updated AgentSet or the result of the method.
- Return type:
Self | Any
- get(attr_names: int | float | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | Series | None | Iterable[int | float | date | time | datetime | timedelta | str | bool | bytes | list[Any] | Expr | Series | None], mask: Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame = None) Series | DataFrame[source]#
Retrieve agent attributes as a Series or DataFrame.
- Parameters:
- Returns:
A Series when selecting a single attribute, otherwise a DataFrame containing the requested columns.
- Return type:
Series | DataFrame
- remove(agents: int | Collection[int] | Series | DataFrame | Sequence[int] | Literal['all', 'active'] | None | Expr, inplace: bool = True) Self[source]#
Remove agents from this AbstractAgentSet.
- Parameters:
agents (IdsLike | AgentMask) – The agents or mask to remove.
inplace (bool, optional) – Whether to remove in place, by default True.
- Returns:
The updated agent set.
- Return type:
Self
- set(attr_names: str | Collection[str] | dict[str, Any] | None = None, values: Any | None = None, mask: Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame = None, inplace: bool = True) Self[source]#
Update agent attributes, optionally on a masked subset.
- Parameters:
attr_names (str | Collection[str] | dict[str, Any] | None, optional) – Attribute(s) to assign. When
None, concrete implementations may derive targets fromvalues.values (Any | None, optional) – Replacement value(s) aligned with
attr_names.mask (AgentMask | None, optional) – Subset selector limiting which agents are updated.
inplace (bool, optional) – Whether to mutate in place or return an updated copy, by default True.
- Returns:
The updated AgentSet (or a modified copy when
inplace=False).- Return type:
Self
- select(mask: Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame = None, filter_func: Callable[[Self], Series] | None = None, n: int | None = None, negate: bool = False, inplace: bool = True) Self[source]#
Update the active-agent mask using selection criteria.
- Parameters:
mask (AgentMask | None, optional) – Pre-computed mask identifying agents to activate.
filter_func (Callable[[Self], BoolSeries] | None, optional) – Callable evaluated on the agent set to produce an additional mask.
n (int | None, optional) – Randomly sample
nagents from the selected mask when provided.negate (bool, optional) – Invert the effective mask, by default False.
inplace (bool, optional) – Whether to mutate in place or return an updated copy, by default True.
- Returns:
The updated AgentSet (or a modified copy when
inplace=False).- Return type:
Self
- shuffle(inplace: bool = True) Self[source]#
Randomly permute agent order.
- Parameters:
inplace (bool, optional) – Whether to mutate in place or return a shuffled copy, by default True.
- Returns:
The shuffled AgentSet (or a shuffled copy when
inplace=False).- Return type:
Self
- sort(by: str | Sequence[str], ascending: bool | Sequence[bool] = True, inplace: bool = True, **kwargs) Self[source]#
Sort agents by one or more columns.
- Parameters:
- Returns:
The sorted AgentSet (or a sorted copy when
inplace=False).- Return type:
Self
- __add__(other: DataFrame | Mapping[str, Sequence[object] | Mapping[str, Sequence[object]] | Series | Any] | Sequence[Any] | ndarray | Table | DataFrame) Self#
Add agents to a new AbstractAgentSet through the + operator.
Other can be: - A DataFrame: adds the agents from the DataFrame. - A DataFrameInput: passes the input to the DataFrame constructor.
- Parameters:
other (DataFrame | DataFrameInput) – The agents to add.
- Returns:
A new AbstractAgentSet with the added agents.
- Return type:
Self
- __copy__() Self#
Create a shallow copy of the AbstractAgentSetRegistry.
- Returns:
A shallow copy of the AbstractAgentSetRegistry.
- Return type:
Self
- __deepcopy__(memo: dict) Self#
Create a deep copy of the AbstractAgentSetRegistry.
- Parameters:
memo (dict) – A dictionary to store the copied objects.
- Returns:
A deep copy of the AbstractAgentSetRegistry.
- Return type:
Self
- __iadd__(other: DataFrame | Mapping[str, Sequence[object] | Mapping[str, Sequence[object]] | Series | Any] | Sequence[Any] | ndarray | Table | DataFrame) Self#
Add agents to the AbstractAgentSet through the += operator.
Other can be: - A DataFrame: adds the agents from the DataFrame. - A DataFrameInput: passes the input to the DataFrame constructor.
- Parameters:
other (DataFrame | DataFrameInput) – The agents to add.
- Returns:
The updated AbstractAgentSet.
- Return type:
Self
- __isub__(other: int | Collection[int] | Series | DataFrame | Sequence[int] | Literal['all', 'active'] | None | Expr) Self#
Remove agents via -= operator.
- __setitem__(key: str | Collection[str] | Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame | tuple[Sequence[int] | int | Literal['all', 'active'] | None | Expr | Series | DataFrame, str | Collection[str]], values: Any) None#
Set values using [] syntax, delegating to set().
- __sub__(other: int | Collection[int] | Series | DataFrame | Sequence[int] | Literal['all', 'active'] | None | Expr) Self#
Return a new set with agents removed via - operator.
- copy(deep: bool = False, memo: dict | None = None, skip: list[str] | None = None) Self#
Create a copy of the Class.
- Parameters:
deep (bool, optional) – Flag indicating whether to perform a deep copy of the AbstractAgentSetRegistry. If True, all attributes of the AbstractAgentSetRegistry will be recursively copied (except attributes in self._copy_reference_only). If False, only the top-level attributes will be copied. Defaults to False.
memo (dict | None, optional) – A dictionary used to track already copied objects during deep copy. Defaults to None.
skip (list[str] | None, optional) – A list of attribute names to skip during the copy process. Defaults to None.
- Returns:
A new instance of the AbstractAgentSetRegistry class that is a copy of the original instance.
- Return type:
Self
- discard(agents: int | Collection[int] | Series | DataFrame | Sequence[int] | Literal['all', 'active'] | None | Expr, inplace: bool = True) Self#
Remove an agent from the AbstractAgentSet. Does not raise an error if the agent is not found.
- Parameters:
agents (IdsLike | AgentMask) – The ids to remove
inplace (bool, optional) – Whether to remove the agent in place, by default True
- Returns:
The updated AbstractAgentSet.
- Return type:
Self
- property model: Model#
Return the parent model for this agent set.
- Returns:
The model instance that owns this agent set.
- Return type:
- property random: Generator#
Return the random number generator shared with the model.
- Returns:
Generator used for stochastic operations.
- Return type:
Generator
- property space: Space | None#
Return the space attached to the parent model, if any.
- Returns:
Spatial structure registered on the model, or
Nonewhen absent.- Return type:
mesa_frames.abstract.space.Space | None
- abstractmethod step() None#
Run a single step of the AbstractAgentSet. This method should be overridden by subclasses.
- property df: DataFrame#
Return the full backing DataFrame for this agent set.
- Returns:
Table containing every agent, including inactive records.
- Return type:
DataFrame
- property active_agents: DataFrame#
Return the subset of agents currently marked as active.
- Returns:
DataFrame view containing only active agents.
- Return type:
DataFrame
- property inactive_agents: DataFrame#
Return the subset of agents currently marked as inactive.
- Returns:
DataFrame view containing only inactive agents.
- Return type:
DataFrame
- property index: Series#
Return the unique identifier index for agents in this set.
- Returns:
Collection of unique agent identifiers.
- Return type:
Index
- property pos: DataFrame#
Return positional data for agents from the attached space.
- Returns:
Position records aligned with each agent’s
unique_id.- Return type:
DataFrame
- Raises:
AttributeError – If the model has no space attached.
- class mesa_frames.AgentSetRegistry(model: mesa_frames.concrete.model.Model)[source]#
A collection of AgentSets. All agents of the model are stored here.
Methods:
Initialize a new AgentSetRegistry.
Add AgentSets to the AbstractAgentSetRegistry.
Rename AgentSets with conflict handling.
Batch assign/replace AgentSets by index or name.
Check if selected AgentSets are present in the registry.
Invoke a method on the AbstractAgentSetRegistry.
Safe lookup for AgentSet(s) by index, name, or type.
Remove AgentSets from the AbstractAgentSetRegistry.
Shuffle the order of AgentSets in the registry.
Sort the AgentSets in the registry based on the given criteria.
Add AgentSets to a new AbstractAgentSetRegistry through the + operator.
Check if an AgentSet is in the AbstractAgentSetRegistry.
Create a shallow copy of the AbstractAgentSetRegistry.
Create a deep copy of the AbstractAgentSetRegistry.
Add AgentSets to the registry through the += operator.
Remove AgentSets from the registry through the -= operator.
Assign/replace a single AgentSet at an index or name.
Remove AgentSets from a new registry through the - operator.
Create a copy of the Class.
Remove AgentSets selected by
sets.Iterate (key, AgentSet) pairs for contained sets.
Iterate keys for contained AgentSets (by name|index|type).
Iterate contained AgentSets (values view).
Fallback for retrieving attributes of the AgentSetRegistry.
Iterate over AgentSets in the registry.
Get the number of AgentSets in the registry.
Get a string representation of the AgentSets in the registry.
Iterate over AgentSets in reverse order.
Get a string representation of the AgentSets in the registry.
Retrieve AgentSet(s) by index, name, or type.
Attributes:
The model that the AbstractAgentSetRegistry belongs to.
The random number generator of the model.
The space of the model.
Public view of all agent unique_id values across contained sets.
- __init__(model: mesa_frames.concrete.model.Model) None[source]#
Initialize a new AgentSetRegistry.
- Parameters:
model (mesa_frames.concrete.model.Model) – The model associated with the AgentSetRegistry.
- add(sets: AgentSet | Iterable[AgentSet], inplace: bool = True) Self[source]#
Add AgentSets to the AbstractAgentSetRegistry.
- Parameters:
sets (mesa_frames.abstract.agentset.AbstractAgentSet | Collection[mesa_frames.abstract.agentset.AbstractAgentSet]) – The AgentSet(s) to add.
inplace (bool) – Whether to add in place. Defaults to True.
- Returns:
The updated AbstractAgentSetRegistry.
- Return type:
Self
- rename(target: AgentSet | str | dict[AgentSet | str, str] | list[tuple[AgentSet | str, str]], new_name: str | None = None, *, on_conflict: Literal['canonicalize', 'raise'] = 'canonicalize', mode: Literal['atomic', 'best_effort'] = 'atomic', inplace: bool = True) Self[source]#
Rename AgentSets with conflict handling.
Supports single-target
(set | old_name, new_name)and batch rename via dict or list of pairs. Names remain unique across the registry.
- replace(mapping: dict[int | str, AgentSet] | list[tuple[int | str, AgentSet]], *, inplace: bool = True, atomic: bool = True) Self[source]#
Batch assign/replace AgentSets by index or name.
- Parameters:
mapping (dict[int | str, mesa_frames.abstract.agentset.AbstractAgentSet] | list[tuple[int | str, mesa_frames.abstract.agentset.AbstractAgentSet]]) – Keys are indices or names to assign; values are AgentSets bound to the same model.
inplace (bool, optional) – Whether to apply on this registry or return a copy, by default True.
atomic (bool, optional) – When True, validates all keys and name invariants before applying any change; either all assignments succeed or none are applied.
- Returns:
Updated registry.
- Return type:
Self
- contains(sets: AgentSet | type[AgentSet] | str) bool[source]#
- contains(sets: Iterable[AgentSet] | Iterable[type[AgentSet]] | Iterable[str]) Series
Check if selected AgentSets are present in the registry.
- Parameters:
sets (AgentSetSelector) – An AgentSet instance, class/type, name string, or a collection of those. For collections, returns a BoolSeries aligned with input order.
- Returns:
Boolean for single selector values; BoolSeries for collections.
- Return type:
bool | BoolSeries
- do(method_name: str, *args: Any, sets: AgentSetSelector | None = None, return_results: Literal[False] = False, inplace: bool = True, key_by: Literal['name', 'index', 'type'] = 'name', **kwargs: Any) Self[source]#
- do(method_name: str, *args: Any, sets: AgentSetSelector, return_results: Literal[True], inplace: bool = True, key_by: Literal['name', 'index', 'type'] = 'name', **kwargs: Any) dict[str, Any] | dict[int, Any] | dict[type[AgentSet], Any]
Invoke a method on the AbstractAgentSetRegistry.
- Parameters:
method_name (str) – The name of the method to invoke.
*args (Any) – Positional arguments to pass to the method
sets (AgentSetSelector, optional) – Which AgentSets to target (instance, type, name, or collection thereof). Defaults to all.
return_results (bool, optional) – Whether to return per-set results as a dictionary, by default False.
inplace (bool, optional) – Whether the operation should be done inplace, by default True
key_by (KeyBy, optional) – Key domain for the returned mapping when
return_resultsis True. - “name” (default) → keys are set names (str) - “index” → keys are positional indices (int) - “type” → keys are concrete set classes (type)**kwargs (Any) – Keyword arguments to pass to the method
- Returns:
The updated registry, or the method result(s). When
return_resultsis True, returns a dictionary keyed perkey_by.- Return type:
Self | Any | dict[str, Any] | dict[int, Any] | dict[type[mesa_frames.abstract.agentset.AbstractAgentSet], Any]
- get(key: int, default: None = None) AgentSet | None[source]#
- get(key: str, default: None = None) AgentSet | None
- get(key: type[AgentSet], default: None = None) list[AgentSet]
- get(key: int | str | type[AgentSet], default: AgentSet | list[AgentSet] | None) AgentSet | list[AgentSet] | None
Safe lookup for AgentSet(s) by index, name, or type.
- remove(sets: AgentSetSelector, inplace: bool = True) Self[source]#
Remove AgentSets from the AbstractAgentSetRegistry.
- Parameters:
sets (AgentSetSelector) – Which AgentSets to remove (instance, type, name, or collection thereof).
inplace (bool, optional) – Whether to remove the agent in place.
- Returns:
The updated AbstractAgentSetRegistry.
- Return type:
Self
- shuffle(inplace: bool = False) Self[source]#
Shuffle the order of AgentSets in the registry.
- Parameters:
inplace (bool) – Whether to shuffle in place.
- Returns:
A new or updated AbstractAgentSetRegistry.
- Return type:
Self
- sort(by: str | Sequence[str], ascending: bool | Sequence[bool] = True, inplace: bool = True, **kwargs: Any) Self[source]#
Sort the AgentSets in the registry based on the given criteria.
- Parameters:
- Returns:
A new or updated AbstractAgentSetRegistry.
- Return type:
Self
- __add__(other: AbstractAgentSet | Collection[AbstractAgentSet]) Self#
Add AgentSets to a new AbstractAgentSetRegistry through the + operator.
- __copy__() Self#
Create a shallow copy of the AbstractAgentSetRegistry.
- Returns:
A shallow copy of the AbstractAgentSetRegistry.
- Return type:
Self
- __deepcopy__(memo: dict) Self#
Create a deep copy of the AbstractAgentSetRegistry.
- Parameters:
memo (dict) – A dictionary to store the copied objects.
- Returns:
A deep copy of the AbstractAgentSetRegistry.
- Return type:
Self
- __iadd__(other: AbstractAgentSet | Collection[AbstractAgentSet]) Self#
Add AgentSets to the registry through the += operator.
- Parameters:
other (mesa_frames.abstract.agentset.AbstractAgentSet | Collection[mesa_frames.abstract.agentset.AbstractAgentSet]) – The AgentSets to add.
- Returns:
The updated AbstractAgentSetRegistry.
- Return type:
Self
- __isub__(other: AbstractAgentSet | Collection[AbstractAgentSet]) Self#
Remove AgentSets from the registry through the -= operator.
- Parameters:
other (mesa_frames.abstract.agentset.AbstractAgentSet | Collection[mesa_frames.abstract.agentset.AbstractAgentSet]) – The AgentSets to remove.
- Returns:
The updated AbstractAgentSetRegistry.
- Return type:
Self
- __setitem__(key: int | str, value: AbstractAgentSet) None#
Assign/replace a single AgentSet at an index or name.
Mirrors the invariants of
replacefor single-key assignment: - Names remain unique across the registry -value.model is self.model- For name keys, the key is authoritative for the assigned set’s name - For index keys, collisions on a different entry’s name must raise
- __sub__(other: AbstractAgentSet | Collection[AbstractAgentSet]) Self#
Remove AgentSets from a new registry through the - operator.
- Parameters:
other (mesa_frames.abstract.agentset.AbstractAgentSet | Collection[mesa_frames.abstract.agentset.AbstractAgentSet]) – The AgentSets to remove.
- Returns:
A new AbstractAgentSetRegistry with the removed AgentSets.
- Return type:
Self
- copy(deep: bool = False, memo: dict | None = None, skip: list[str] | None = None) Self#
Create a copy of the Class.
- Parameters:
deep (bool, optional) – Flag indicating whether to perform a deep copy of the AbstractAgentSetRegistry. If True, all attributes of the AbstractAgentSetRegistry will be recursively copied (except attributes in self._copy_reference_only). If False, only the top-level attributes will be copied. Defaults to False.
memo (dict | None, optional) – A dictionary used to track already copied objects during deep copy. Defaults to None.
skip (list[str] | None, optional) – A list of attribute names to skip during the copy process. Defaults to None.
- Returns:
A new instance of the AbstractAgentSetRegistry class that is a copy of the original instance.
- Return type:
Self
- discard(sets: AbstractAgentSetSelector, inplace: bool = True) Self#
Remove AgentSets selected by
sets. Ignores missing.- Parameters:
sets (AgentSetSelector) – Which AgentSets to remove (instance, type, name, or collection thereof).
inplace (bool) – Whether to remove in place. Defaults to True.
- Returns:
The updated AbstractAgentSetRegistry.
- Return type:
Self
- items(*, key_by: Literal['name', 'index', 'type'] = 'name') Iterable[tuple[str | int | type[AbstractAgentSet], AbstractAgentSet]]#
Iterate (key, AgentSet) pairs for contained sets.
- keys(*, key_by: Literal['name', 'index', 'type'] = 'name') Iterable[str | int | type[AbstractAgentSet]]#
Iterate keys for contained AgentSets (by name|index|type).
- property space: Space | None#
The space of the model.
- Return type:
mesa_frames.abstract.space.Space | None
- __getattr__(name: str) Any | dict[str, Any][source]#
Fallback for retrieving attributes of the AgentSetRegistry.
- property ids: Series#
Public view of all agent unique_id values across contained sets.