Skip to content

Actors List

Bases: List[Link], Generic[Link]

A list of actors in an agent-based model.

Source code in abses/sequences.py
def __init__(
    self, model: MainModel[Any, Any], objs: Iterable[Link] = ()
) -> None:
    super().__init__(objs)
    self._model = model

random cached property

random

Random module

plot cached property

plot

Plotting module

to_dict

to_dict()

Convert all actors in this list to a dictionary like {breed: ActorList}.

Returns:

Type Description
Dict[str, ActorsList[Link]]

key is the breed of actors, and values are corresponding actors.

Source code in abses/sequences.py
def to_dict(self) -> Dict[str, ActorsList[Link]]:
    """Convert all actors in this list to a dictionary like {breed: ActorList}.

    Returns:
        key is the breed of actors, and values are corresponding actors.
    """
    dic: Dict[str, ActorsList[Link]] = {}
    for actor in iter(self):
        breed = actor.breed
        if breed not in dic:
            dic[breed] = ActorsList(self._model, [actor])
        else:
            dic[breed].append(actor)
    return dic

select

select(selection=None, geo_type=None)

Returns a new :class:ActorList based on selection.

Parameters:

Name Type Description Default
selection Optional[Selection]

List with same length as the agent list. Positions that return True will be selected.

None
geo_type Optional[GeoType]

Type of Actors' Geometry.

None

Returns:

Type Description
ActorsList[Link]

A subset containing.

Source code in abses/sequences.py
def select(
    self,
    selection: Optional[Selection] = None,
    geo_type: Optional[GeoType] = None,
) -> ActorsList[Link]:
    """
    Returns a new :class:`ActorList` based on `selection`.

    Parameters:
        selection:
            List with same length as the agent list.
            Positions that return True will be selected.
        geo_type:
            Type of Actors' Geometry.

    Returns:
        A subset containing.
    """
    actors = self._subset(geo_type=geo_type)
    if selection is None:
        return actors
    if isinstance(selection, (str, dict)):
        bool_ = [selecting(actor, selection) for actor in actors]
    elif isinstance(selection, (list, tuple, np.ndarray)):
        bool_ = make_list(selection)
    else:
        raise TypeError(f"Invalid selection type {type(selection)}")
    selected = [a for a, s in zip(actors, bool_) if s]
    return ActorsList(self._model, selected)

ids

ids(ids)

Subsets ActorsList by a ids.

Parameters:

Name Type Description Default
ids Iterable[UniqueID] | UniqueID

an iterable id list. List[id], ID is an attr of agent obj.

required

Returns:

Name Type Description
ActorList ActorsList[Link]

A subset of origin agents list.

Source code in abses/sequences.py
def ids(self, ids: Iterable[UniqueID] | UniqueID) -> ActorsList[Link]:
    """Subsets ActorsList by a `ids`.

    Parameters:
        ids:
            an iterable id list. List[id], ID is an attr of agent obj.

    Returns:
        ActorList: A subset of origin agents list.
    """
    ids = make_list(ids)
    return self.select([agent.unique_id in ids for agent in self])

better

better(metric, than=None)

Selects the elements of the sequence that are better than a given value or actor based on a specified metric.

Parameters:

Name Type Description Default
metric str

The name of the attribute to use as the metric for comparison.

required
than Optional[Union[Number, Actor]]

The value or actor to compare against. If None, selects the elements with the highest value for the specified metric. If a number, selects the elements with a value greater than the specified number. If an Actor, selects the elements with a value greater than the specified Actor's value for the specified metric.

None

Returns:

Type Description
ActorsList[Link]

A new sequence containing the selected elements.

Raises:

Type Description
ABSESpyError

If the than parameter is not a Number or an Actor.

Notes

This method compares the values of the specified metric for all elements in the sequence and selects the elements that are better than the specified value or actor. The comparison is based on the greater than operator (>) for numbers and the difference between the values for actors.

Source code in abses/sequences.py
def better(
    self, metric: str, than: Optional[Union[Number, Actor]] = None
) -> ActorsList[Link]:
    """
    Selects the elements of the sequence that are better than a given value or actor
    based on a specified metric.

    Parameters:
        metric:
            The name of the attribute to use as the metric for comparison.
        than:
            The value or actor to compare against. If None, selects the elements with the
            highest value for the specified metric. If a number, selects the elements with
            a value greater than the specified number. If an Actor, selects the elements
            with a value greater than the specified Actor's value for the specified metric.

    Returns:
        A new sequence containing the selected elements.

    Raises:
        ABSESpyError:
            If the `than` parameter is not a Number or an Actor.

    Notes:
        This method compares the values of the specified metric for all elements in the
        sequence and selects the elements that are better than the specified value or actor.
        The comparison is based on the greater than operator (>) for numbers and the
        difference between the values for actors.
    """
    metrics = self.array(attr=metric)
    if than is None:
        return self.select(metrics == max(metrics))
    if isinstance(than, Number):
        return self.select(metrics > than)
    if isinstance(than, mg.GeoAgent):
        diff = self.array(metric) - getattr(than, metric)
        return self.select(diff > 0)
    raise ABSESpyError(f"Invalid than type {type(than)}.")

update

update(attr, values)

Update the specified attribute of each agent in the sequence with the corresponding value in the given iterable.

Parameters:

Name Type Description Default
attr str

The name of the attribute to update.

required
values Iterable[Any]

An iterable of values to update the attribute with. Must be the same length as the sequence.

required

Raises:

Type Description
ValueError

If the length of the values iterable does not match the length of the sequence.

Source code in abses/sequences.py
def update(self, attr: str, values: Iterable[Any]) -> None:
    """Update the specified attribute of each agent in the sequence with the corresponding value in the given iterable.

    Parameters:
        attr:
            The name of the attribute to update.
        values:
            An iterable of values to update the attribute with. Must be the same length as the sequence.

    Raises:
        ValueError:
            If the length of the values iterable does not match the length of the sequence.
    """
    self._is_same_length(cast(Sized, values), rep_error=True)
    for agent, val in zip(self, values):
        setattr(agent, attr, val)

split

split(where)

Split agents into N+1 groups.

Parameters:

Name Type Description Default
where NDArray[Any]

indexes [size=N] denotes where to split.

required

Returns:

Type Description
List[ActorsList[Link]]

np.ndarray: N+1 groups: agents array

Source code in abses/sequences.py
def split(self, where: NDArray[Any]) -> List[ActorsList[Link]]:
    """Split agents into N+1 groups.

    Parameters:
        where:
            indexes [size=N] denotes where to split.

    Returns:
        np.ndarray: N+1 groups: agents array
    """
    split = np.hsplit(np.array(self), where)
    return [ActorsList(self._model, group) for group in split]

array

array(attr)

Convert the specified attribute of all actors to a numpy array.

Parameters:

Name Type Description Default
attr str

The name of the attribute to convert to a numpy array.

required

Returns:

Type Description
ndarray

A numpy array containing the specified attribute of all actors.

Source code in abses/sequences.py
def array(self, attr: str) -> np.ndarray:
    """Convert the specified attribute of all actors to a numpy array.

    Parameters:
        attr:
            The name of the attribute to convert to a numpy array.

    Returns:
        A numpy array containing the specified attribute of all actors.
    """
    return np.array([getattr(actor, attr) for actor in self])

trigger

trigger(func_name, *args, **kwargs)

Call a method with the given name on all actors in the sequence.

Parameters:

Name Type Description Default
func_name str

The name of the method to call on each actor.

required
*args Any

Positional arguments to pass to the method.

()
**kwargs Any

Keyword arguments to pass to the method.

{}

Returns:

Type Description
ndarray

An array of the results of calling the method on each actor.

Source code in abses/sequences.py
def trigger(self, func_name: str, *args: Any, **kwargs: Any) -> np.ndarray:
    """Call a method with the given name on all actors in the sequence.

    Parameters:
        func_name:
            The name of the method to call on each actor.
        *args:
            Positional arguments to pass to the method.
        **kwargs:
            Keyword arguments to pass to the method.

    Returns:
        An array of the results of calling the method on each actor.
    """
    results = [
        getattr(actor, func_name)(*args, **kwargs) for actor in iter(self)
    ]
    return np.array(results)

apply

apply(ufunc, *args, **kwargs)

Apply ufunc to all actors in the sequence.

Parameters:

Name Type Description Default
ufunc Callable

The function to apply to each actor.

required
*args Any

Positional arguments to pass to the function.

()
**kwargs Any

Keyword arguments to pass to the function.

{}

Returns:

Type Description
ndarray

An array of the results of applying the function to each actor.

Source code in abses/sequences.py
def apply(self, ufunc: Callable, *args: Any, **kwargs: Any) -> np.ndarray:
    """Apply ufunc to all actors in the sequence.

    Parameters:
        ufunc:
            The function to apply to each actor.
        *args:
            Positional arguments to pass to the function.
        **kwargs:
            Keyword arguments to pass to the function.

    Returns:
        An array of the results of applying the function to each actor.
    """
    func = partial(ufunc, *args, **kwargs)
    return np.array(list(map(func, self)))

get

get(attr, target=None, how='only', default=None)

Retrieve the attribute of an either specified or randomly chosen agent.

Parameters:

Name Type Description Default
attr str

The name of the attribute to retrieve.

required
how HOW

The method to use to retrieve the attribute. Can be either "only" or "random".

'only'

Returns:

Type Description
Any

The attribute of the specified agent.

Source code in abses/sequences.py
def get(
    self,
    attr: str,
    target: Optional[TargetName] = None,
    how: HOW = "only",
    default: Optional[Any] = None,
) -> Any:
    """Retrieve the attribute of an either specified or randomly chosen agent.

    Parameters:
        attr:
            The name of the attribute to retrieve.
        how:
            The method to use to retrieve the attribute. Can be either "only" or "random".

    Returns:
        The attribute of the specified agent.
    """
    if agent := self.item(how=how, index=0):
        return agent.get(attr, target=target)
    if default is not None:
        return default
    raise ValueError("No agent found or default value.")

set

set(attr, value, target=None)

Set the attribute of all agents in the sequence to the specified value.

Parameters:

Name Type Description Default
attr str

The name of the attribute to set.

required
value Any

The value to set the attribute to.

required
Source code in abses/sequences.py
def set(
    self, attr: str, value: Any, target: Optional[TargetName] = None
) -> None:
    """Set the attribute of all agents in the sequence to the specified value.

    Parameters:
        attr:
            The name of the attribute to set.
        value:
            The value to set the attribute to.
    """
    for agent in iter(self):
        agent.set(attr, value, target=target)

item

item(how='item', index=0)

Retrieve one agent if possible.

Parameters:

Name Type Description Default
how HOW

The method to use to retrieve the agent. Can be either "only", "item", or "random". If "only", it will return the only agent in the container. In this case, the container must have only one agent. If more than one or no agent is found, it will raise an error. If "item", it will return the agent at the given index. If "random", it will return a randomly chosen agent.

'item'
index int

The index of the agent to retrieve.

0

Returns:

Type Description
Optional[Link]

The agent if found, otherwise None.

Source code in abses/sequences.py
def item(self, how: HOW = "item", index: int = 0) -> Optional[Link]:
    """Retrieve one agent if possible.

    Parameters:
        how:
            The method to use to retrieve the agent.
            Can be either "only", "item", or "random".
            If "only", it will return the only agent in the container.
            In this case, the container must have only one agent.
            If more than one or no agent is found, it will raise an error.
            If "item", it will return the agent at the given index.
            If "random", it will return a randomly chosen agent.
        index:
            The index of the agent to retrieve.

    Returns:
        The agent if found, otherwise None.
    """
    if how == "only":
        return get_only_agent(self)
    if how == "random":
        actor = self.random.choice(when_empty="return None")
        return cast(Optional["Actor"], actor)
    if how == "item":
        return self[index] if len(self) > index else None
    raise ValueError(f"Invalid how method '{how}'.")

summary

summary(geometry=False, **kwargs)

Returns a summarized dataframe of the actors.

Source code in abses/sequences.py
def summary(
    self, geometry: bool = False, **kwargs
) -> pd.DataFrame | gpd.GeoDataFrame:
    """Returns a summarized dataframe of the actors."""
    if len(self) == 0:
        raise ValueError("No actors to retrieve summary information.")
    df = pd.concat([actor.summary(**kwargs) for actor in self], axis=1).T
    if geometry:
        crs = self._check_crs_consistent()
        df["geometry"] = self.array("geometry")
        return gpd.GeoDataFrame(df, geometry="geometry", crs=crs)
    return df