Skip to content

Actors Container

Bases: _AgentsContainer

AgentsContainer for the MainModel.

Source code in abses/container.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self._unique_ids: Dict[str, int] = {}

register

register(actor_cls)

Registers a new breed of actors.

Parameters:

Name Type Description Default
actor_cls Type[Actor]

The class of the actor to register. It can be a single class, or an iterable of classes. Once a breed is registered, it will be added to all the containers of the model globally. It means, it's not necessary to register the same breed again.

required

Raises:

Type Description
ValueError

If the breed is already registered.

Source code in abses/container.py
def register(self, actor_cls: Type[Actor]) -> None:
    """Registers a new breed of actors.

    Parameters:
        actor_cls:
            The class of the actor to register.
            It can be a single class, or an iterable of classes.
            Once a breed is registered,
            it will be added to all the containers of the model globally.
            It means, it's not necessary to register the same breed again.

    Raises:
        ValueError:
            If the breed is already registered.
    """
    breed = actor_cls.breed
    if breed in self._model.breeds:
        raise ValueError(f"{breed} is already registered.")
    setattr(self._model, "breeds", actor_cls)
    self._unique_ids[breed] = 0

new

new(breed_cls=Actor, num=None, singleton=False, unique_ids=None, **kwargs)

Create one or more actors of the given breed class.

Parameters:

Name Type Description Default
breed_cls Type[Actor]

The breed class of the actor(s) to create.

Actor
num Optional[int]

The number of actors to create. Defaults to 1.

None
singleton bool

Whether to create a singleton actor. Defaults to False.

False
**kwargs Any

Additional keyword arguments to pass to the actor constructor.

{}

Returns:

Type Description
Union[Actor, ActorsList[Actor]]

The created actor(s).

Example
from abses import Actor, MainModel
model = MainModel()
actor = model.agents.new(singleton=True)
>>> type(actor)
>>> Actor

actors = model.agents.new(singleton=False)
>>> type(actors)
>>> ActorsList
Source code in abses/container.py
def new(
    self,
    breed_cls: Type[Actor] = Actor,
    num: Optional[int] = None,
    singleton: bool = False,
    unique_ids: Optional[UniqueIDs] = None,
    **kwargs: Any,
) -> Union[Actor, ActorsList[Actor]]:
    """Create one or more actors of the given breed class.

    Parameters:
        breed_cls:
            The breed class of the actor(s) to create.
        num:
            The number of actors to create. Defaults to 1.
        singleton (bool, optional):
            Whether to create a singleton actor. Defaults to False.
        **kwargs:
            Additional keyword arguments to pass to the actor constructor.

    Returns:
        The created actor(s).

    Example:
        ```python
        from abses import Actor, MainModel
        model = MainModel()
        actor = model.agents.new(singleton=True)
        >>> type(actor)
        >>> Actor

        actors = model.agents.new(singleton=False)
        >>> type(actors)
        >>> ActorsList
        ```
    """
    # check if the breed class is registered, if not, register it.
    self.check_registration(breed_cls, register=True)
    num, unique_ids = self._check_ids_and_num(num, unique_ids)

    # create actors.
    objs = []
    for unique_id in unique_ids:
        agent = self._new_one(
            unique_id=unique_id, agent_cls=breed_cls, **kwargs
        )
        objs.append(agent)
    # return the created actor(s).
    actors_list: ActorsList[Actor] = ActorsList(
        model=self.model, objs=objs
    )
    logger.debug(f"{self} created {num} {breed_cls.__name__}.")
    return cast(Actor, actors_list.item()) if singleton else actors_list

new_from_graph

new_from_graph(graph, link_name, actor_cls=Actor, **kwargs)

Create a set of new agents from networkx graph.

Source code in abses/container.py
def new_from_graph(
    self,
    graph: "nx.Graph",
    link_name: str,
    actor_cls: Type[Actor] = Actor,
    **kwargs,
):
    """Create a set of new agents from networkx graph."""
    self.check_registration(actor_cls, register=True)
    actors = []
    mapping = {}
    for node, attr in graph.nodes(data=True):
        unique_id = get_node_unique_id(node=node)
        actor = self._new_one(unique_id, agent_cls=actor_cls, **attr)
        actors.append(actor)
        mapping[unique_id] = actor
    self.model.human.add_links_from_graph(
        graph, link_name=link_name, mapping_dict=mapping, **kwargs
    )
    return ActorsList(model=self.model, objs=actors)

new_from_gdf

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

Create actors from a geopandas.GeoDataFrame object.

Parameters:

Name Type Description Default
gdf GeoDataFrame

The geopandas.GeoDataFrame object to convert.

required
unique_id Optional[str]

A column name, to be converted to unique index of created geo-agents (Social-ecological system Actors).

None
agent_cls type[Actor]

Agent class to create.

Actor

Raises:

Type Description
ValueError

If the column specified by unique_id is not unique.

Returns:

Type Description
ActorsList[Actor]

An ActorsList with all new created actors stored.

Source code in abses/container.py
def new_from_gdf(
    self,
    gdf: gpd.GeoDataFrame,
    unique_id: Optional[str] = None,
    agent_cls: type[Actor] = Actor,
    attrs: IncludeFlag = False,
    **kwargs,
) -> ActorsList[Actor]:
    """Create actors from a `geopandas.GeoDataFrame` object.

    Parameters:
        gdf:
            The `geopandas.GeoDataFrame` object to convert.
        unique_id:
            A column name, to be converted to unique index
            of created geo-agents (Social-ecological system Actors).
        agent_cls:
            Agent class to create.

    Raises:
        ValueError:
            If the column specified by `unique_id` is not unique.

    Returns:
        An `ActorsList` with all new created actors stored.
    """
    # 检查创建主体的数据标识是否唯一,若唯一则设置为索引
    if unique_id:
        gdf = gdf.set_index(unique_id, verify_integrity=True)
    # 如果还没有注册这种主体,那么注册一下
    self.check_registration(agent_cls, register=True)
    # 检查坐标参考系是否一致
    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 index, row in gdf.iterrows():
        geometry = row[geo_col]
        new_agent = self._new_one(
            geometry=geometry,
            unique_id=index,
            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)
    # 添加主体到模型容器里
    self.add(agents)
    return ActorsList(model=self.model, objs=agents)

Bases: _AgentsContainer

Container for agents located at cells.

Source code in abses/container.py
def __init__(
    self,
    model: MainModel[Any, Any],
    cell: PatchCell,
    max_len: int | None = None,
):
    super().__init__(model, max_len)
    self._cell = cell

remove

remove(agent)

Remove the given agent from the cell. Generally, it stores all the agents on this cell. Therefore, it is not recommended to use this method directly. Consider to use actor.move.off() to let the actor leave this cell instead.

Parameters:

Name Type Description Default
agent Actor

The agent (actor) to remove.

required

Raises:

Type Description
ABSESpyError

If the agent is not on this cell.

Source code in abses/container.py
def remove(self, agent: Actor) -> None:
    """Remove the given agent from the cell.
    Generally, it stores all the agents on this cell.
    Therefore, it is not recommended to use this method directly.
    Consider to use `actor.move.off()` to let the actor leave this cell instead.

    Parameters:
        agent:
            The agent (actor) to remove.

    Raises:
        ABSESpyError:
            If the agent is not on this cell.
    """
    if agent.at is not self._cell:
        raise ABSESpyError(f"{agent} is not on this cell.")
    self[agent.breed].remove(agent)
    del agent.at

new

new(breed_cls=Actor, num=1, singleton=False, unique_ids=None, **kwargs)

Creates a new actor or a list of actors of the given breed class. The created actors are added to both the cell and the model's global container.

Parameters:

Name Type Description Default
breed_cls Type[Actor]

The breed class of the actor(s) to create.

Actor
num int

The number of actors to create. Defaults to 1.

1
singleton bool

Whether to create a singleton actor. Defaults to False.

False
**kwargs Any

Additional keyword arguments to pass to the actor constructor.

{}

Returns:

Type Description
Actor | ActorsList

The created actor(s).

Source code in abses/container.py
def new(
    self,
    breed_cls: Type[Actor] = Actor,
    num: int = 1,
    singleton: bool = False,
    unique_ids: Optional[UniqueIDs] = None,
    **kwargs: Any,
) -> Actor | ActorsList:
    """Creates a new actor or a list of actors of the given breed class.
    The created actors are added to both the cell and the model's global container.

    Parameters:
        breed_cls:
            The breed class of the actor(s) to create.
        num:
            The number of actors to create. Defaults to 1.
        singleton:
            Whether to create a singleton actor. Defaults to False.
        **kwargs:
            Additional keyword arguments to pass to the actor constructor.

    Returns:
        The created actor(s).
    """
    # Using model's container to create a list of actors
    new_actors = self.model.agents.new(
        breed_cls, num, singleton, unique_ids, **kwargs
    )
    # move the actors to the cell
    for a in make_list(new_actors):
        a.move.to(self._cell)
    return new_actors