Skip to content

Bases: _AgentsContainer

Specialized container for agents in the main model with GeoDataFrame support.

This container extends the base agent container with additional functionality for creating agents from geospatial data sources. It provides methods to instantiate agents from GeoDataFrames while handling coordinate reference system (CRS) transformations and attribute mapping.

The container ensures that all geospatial data is properly aligned with the model's coordinate system before creating agents, maintaining spatial consistency across the entire model.

Source code in abses/agents/container.py
def __init__(self, model: MainModelProtocol, max_len: None | Number = None):
    if not isinstance(model, Model):
        raise TypeError(f"{model} is not a Mesa Model.")
    self._model: MainModelProtocol = model
    self._agents = model._all_agents
    self._max_length = max_len

new_from_gdf

new_from_gdf(gdf, agent_cls=Actor, attrs=False, **kwargs)

Create actors from a geopandas.GeoDataFrame object.

This method creates actors from a GeoDataFrame, automatically assigning unique IDs to each actor. The geometries from the GeoDataFrame are used to initialize the actors' spatial properties, and selected attributes can be transferred to the created actors.

Parameters:

Name Type Description Default
gdf GeoDataFrame

The geopandas.GeoDataFrame object to convert.

required
agent_cls type[ActorProtocol]

Agent class to create. Defaults to Actor.

Actor
attrs IncludeFlag

Specifies which attributes from the GeoDataFrame to include in the created actors. Can be a boolean, list of column names, or exclusion pattern. Defaults to False (no attributes transferred).

False
**kwargs

Additional keyword arguments to pass to the actor constructor.

{}

Returns:

Type Description
ActorsList[ActorProtocol]

An ActorsList with all new created actors stored.

Note

Each created actor will have a unique ID automatically assigned by the Mesa framework. The geometry from the GeoDataFrame will be converted to match the model's coordinate reference system (CRS).

Source code in abses/agents/container.py
def new_from_gdf(
    self,
    gdf: gpd.GeoDataFrame,
    agent_cls: type[ActorProtocol] = Actor,
    attrs: IncludeFlag = False,
    **kwargs,
) -> ActorsList[ActorProtocol]:
    # TODO: 这个方法需要适配到最新的 Mesa 版本
    """Create actors from a `geopandas.GeoDataFrame` object.

    This method creates actors from a GeoDataFrame, automatically assigning
    unique IDs to each actor. The geometries from the GeoDataFrame are used
    to initialize the actors' spatial properties, and selected attributes
    can be transferred to the created actors.

    Parameters:
        gdf:
            The `geopandas.GeoDataFrame` object to convert.
        agent_cls:
            Agent class to create. Defaults to `Actor`.
        attrs:
            Specifies which attributes from the GeoDataFrame to include in
            the created actors. Can be a boolean, list of column names, or
            exclusion pattern. Defaults to False (no attributes transferred).
        **kwargs:
            Additional keyword arguments to pass to the actor constructor.

    Returns:
        An `ActorsList` with all new created actors stored.

    Note:
        Each created actor will have a unique ID automatically assigned by
        the Mesa framework. The geometry from the GeoDataFrame will be
        converted to match the model's coordinate reference system (CRS).
    """
    # 检查坐标参考系是否一致
    self._check_crs(gdf)
    # 看一下哪些属性是需要加入到主体的
    geo_col = gdf.geometry.name
    set_attributes = clean_attrs(gdf.columns, attrs, exclude=geo_col)
    if not isinstance(set_attributes, dict):
        set_attributes = {col: col for col in set_attributes}
    # 创建主体
    agents = []
    for _, row in gdf.iterrows():
        geometry = row[geo_col]
        new_agent = self._new_one(geometry=geometry, agent_cls=agent_cls, **kwargs)
        new_agent.crs = self.crs

        for col, name in set_attributes.items():
            setattr(new_agent, name, row[col])
        agents.append(new_agent)
    # 添加主体到模型容器里
    return ActorsList(model=self.model, objs=agents)

Bases: _AgentsContainer

Container for agents located at specific spatial cells.

This specialized container manages agents that are positioned at a particular cell in the model's spatial grid. It extends the base container functionality with spatial awareness, ensuring that agents are properly linked to their location when added or removed.

The container maintains the spatial relationship between agents and cells, automatically updating agent positions when they are added to or removed from the cell. It supports capacity limits to control the maximum number of agents that can occupy a single cell.

Attributes:

Name Type Description
model MainModelProtocol

The ABSESpy model this container belongs to.

_cell

The specific cell this container represents.

_agents

The agent set containing all agents at this cell.

Parameters:

Name Type Description Default
model MainModelProtocol

The ABSESpy model this container belongs to.

required
cell PatchCell

The specific cell this container manages agents for.

required
max_len int | float

Maximum number of agents allowed in this cell. Defaults to infinity (no limit).

float('inf')
Source code in abses/agents/container.py
def __init__(
    self,
    model: MainModelProtocol,
    cell: PatchCell,
    max_len: int | float = float("inf"),
) -> None:
    """Initialize a cell agents container.

    Parameters:
        model: The ABSESpy model this container belongs to.
        cell: The specific cell this container manages agents for.
        max_len: Maximum number of agents allowed in this cell.
            Defaults to infinity (no limit).
    """
    super().__init__(model, max_len)
    self._agents = AgentSet([], random=model.random)
    self._cell = cell

remove

remove(agent=None)

Remove the given agent from the cell.

This method removes agents from the cell's container, breaking the spatial relationship between the agent and the cell. It can remove a specific agent or clear all agents from the cell if no agent is specified.

It is generally recommended to use actor.move.off() instead, which provides a higher-level interface for agent movement and properly manages all related state updates.

Parameters:

Name Type Description Default
agent Optional[ActorProtocol]

The agent (actor) to remove. If None, all agents are removed from the cell.

None

Raises:

Type Description
ABSESpyError

If the specified agent is not currently located on this cell.

Source code in abses/agents/container.py
def remove(self, agent: Optional[ActorProtocol] = None) -> None:
    """Remove the given agent from the cell.

    This method removes agents from the cell's container, breaking the spatial
    relationship between the agent and the cell. It can remove a specific agent
    or clear all agents from the cell if no agent is specified.

    It is generally recommended to use `actor.move.off()` instead, which provides
    a higher-level interface for agent movement and properly manages all related
    state updates.

    Parameters:
        agent:
            The agent (actor) to remove. If None, all agents are removed from
            the cell.

    Raises:
        ABSESpyError:
            If the specified agent is not currently located on this cell.
    """
    if agent is None:
        self._agents.clear()
        return
    assert isinstance(agent, ActorProtocol), f"{agent} is not an ActorProtocol."
    if agent.at is not self._cell:
        raise ABSESpyError(f"{agent} is not on this cell.")
    self._agents.remove(agent)
    del agent.at