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:

Methods:

__init__

Initialize a new AgentSet.

rename

Rename this agent set.

add

Add agents to the AgentSet.

contains

Check if agents with the specified IDs are in the AgentSet.

do

Invoke a method on the AgentSet.

get

Retrieve agent attributes as a Series or DataFrame.

remove

Remove agents from this AbstractAgentSet.

set

Update agent attributes, optionally on a masked subset.

select

Update the active-agent mask using selection criteria.

shuffle

Randomly permute agent order.

sort

Sort agents by one or more columns.

__add__

Add agents to a new AbstractAgentSet through the + operator.

__contains__

Membership test for an agent id in this set.

__copy__

Create a shallow copy of the AbstractAgentSetRegistry.

__deepcopy__

Create a deep copy of the AbstractAgentSetRegistry.

__iadd__

Add agents to the AbstractAgentSet through the += operator.

__isub__

Remove agents via -= operator.

__repr__

Return repr(self).

__setitem__

Set values using [] syntax, delegating to set().

__str__

Return str(self).

__sub__

Return a new set with agents removed via - operator.

copy

Create a copy of the Class.

discard

Remove an agent from the AbstractAgentSet.

step

Run a single step of the AbstractAgentSet.

Attributes:

model

Return the parent model for this agent set.

random

Return the random number generator shared with the model.

space

Return the space attached to the parent model, if any.

df

Return the full backing DataFrame for this agent set.

active_agents

Return the subset of agents currently marked as active.

inactive_agents

Return the subset of agents currently marked as inactive.

index

Return the unique identifier index for agents in this set.

pos

Return positional data for agents from the attached space.

name

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:
  • new_name (str) – Desired new name.

  • inplace (bool, optional) – Whether to perform the rename in place. If False, a renamed copy is returned, by default True.

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.

Parameters:
  • agents (pl.DataFrame | Sequence[Any] | dict[str, Any]) – The agents to add.

  • inplace (bool, optional) – Whether to add the agents in place, by default True.

Returns:

The updated AgentSet.

Return type:

Self

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:
  • attr_names (str | Collection[str] | None, optional) – Column name or collection of names to fetch. When None, return all agent attributes (excluding any internal identifiers).

  • mask (AgentMask | None, optional) – Subset selector limiting which agents are included. None means operate on the full set.

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 from values.

  • 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 n agents 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:
  • by (str | Sequence[str]) – Column name(s) to sort on.

  • ascending (bool | Sequence[bool], optional) – Sort order per column, by default True.

  • inplace (bool, optional) – Whether to mutate in place or return a sorted copy, by default True.

  • **kwargs (Any) – Backend-specific keyword arguments forwarded to the concrete sorter.

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

__contains__(agents: int) bool#

Membership test for an agent id in this set.

__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.

__repr__() str#

Return repr(self).

__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().

__str__() str#

Return str(self).

__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:

mesa_frames.concrete.model.Model

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 None when 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.

property name: str#

Return the name of the AgentSet.

class mesa_frames.AgentSetRegistry(model: mesa_frames.concrete.model.Model)[source]#

A collection of AgentSets. All agents of the model are stored here.

Methods:

__init__

Initialize a new AgentSetRegistry.

add

Add AgentSets to the AbstractAgentSetRegistry.

rename

Rename AgentSets with conflict handling.

replace

Batch assign/replace AgentSets by index or name.

contains

Check if selected AgentSets are present in the registry.

do

Invoke a method on the AbstractAgentSetRegistry.

get

Safe lookup for AgentSet(s) by index, name, or type.

remove

Remove AgentSets from the AbstractAgentSetRegistry.

shuffle

Shuffle the order of AgentSets in the registry.

sort

Sort the AgentSets in the registry based on the given criteria.

__add__

Add AgentSets to a new AbstractAgentSetRegistry through the + operator.

__contains__

Check if an AgentSet is in the AbstractAgentSetRegistry.

__copy__

Create a shallow copy of the AbstractAgentSetRegistry.

__deepcopy__

Create a deep copy of the AbstractAgentSetRegistry.

__iadd__

Add AgentSets to the registry through the += operator.

__isub__

Remove AgentSets from the registry through the -= operator.

__setitem__

Assign/replace a single AgentSet at an index or name.

__sub__

Remove AgentSets from a new registry through the - operator.

copy

Create a copy of the Class.

discard

Remove AgentSets selected by sets.

items

Iterate (key, AgentSet) pairs for contained sets.

keys

Iterate keys for contained AgentSets (by name|index|type).

values

Iterate contained AgentSets (values view).

__getattr__

Fallback for retrieving attributes of the AgentSetRegistry.

__iter__

Iterate over AgentSets in the registry.

__len__

Get the number of AgentSets in the registry.

__repr__

Get a string representation of the AgentSets in the registry.

__reversed__

Iterate over AgentSets in reverse order.

__str__

Get a string representation of the AgentSets in the registry.

__getitem__

Retrieve AgentSet(s) by index, name, or type.

Attributes:

model

The model that the AbstractAgentSetRegistry belongs to.

random

The random number generator of the model.

space

The space of the model.

ids

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_results is 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_results is True, returns a dictionary keyed per key_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:
  • by (str | Sequence[str]) – The attribute(s) to sort by.

  • ascending (bool | Sequence[bool]) – Whether to sort in ascending order.

  • inplace (bool) – Whether to sort the agents in place.

  • **kwargs – Keyword arguments to pass to the sort

Returns:

A new or updated AbstractAgentSetRegistry.

Return type:

Self

__add__(other: AbstractAgentSet | Collection[AbstractAgentSet]) Self#

Add AgentSets to a new AbstractAgentSetRegistry through the + operator.

__contains__(sets: AbstractAgentSet) bool#

Check if an AgentSet is in the AbstractAgentSetRegistry.

__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 replace for 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 model: Model#

The model that the AbstractAgentSetRegistry belongs to.

Return type:

mesa_frames.concrete.model.Model

property random: Generator#

The random number generator of the model.

Return type:

Generator

property space: Space | None#

The space of the model.

Return type:

mesa_frames.abstract.space.Space | None

values() Iterable[AbstractAgentSet]#

Iterate contained AgentSets (values view).

__getattr__(name: str) Any | dict[str, Any][source]#

Fallback for retrieving attributes of the AgentSetRegistry.

__iter__() Iterator[AgentSet][source]#

Iterate over AgentSets in the registry.

__len__() int[source]#

Get the number of AgentSets in the registry.

__repr__() str[source]#

Get a string representation of the AgentSets in the registry.

__reversed__() Iterator[AgentSet][source]#

Iterate over AgentSets in reverse order.

__str__() str[source]#

Get a string representation of the AgentSets in the registry.

property ids: Series#

Public view of all agent unique_id values across contained sets.

__getitem__(key: int) AgentSet[source]#
__getitem__(key: str) AgentSet
__getitem__(key: type[AgentSet]) list[AgentSet]

Retrieve AgentSet(s) by index, name, or type.