Container model of human mobility
The container model of human mobility of Alessandretti, Aslak, and Lehmann.
- Class:
ContainerMobilitySystem - Import:
from skcomplex.systems.social.organizations import ContainerMobilitySystem - Field:
social/organizations - Topics:
agents,human mobility,hierarchy,containers,scales - References:
- Alessandretti, Aslak, and Lehmann 2020
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.social.organizations import ContainerMobilitySystem
trajectory = ContainerMobilitySystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_individuals |
10 |
levels |
3 |
side |
4 |
travel |
(0.6, 0.3, 0.1) |
exponent |
1.5 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | none |
| Laws | update |
| Randomness | stochastic |
| Domains | integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class ContainerMobilitySystem(BaseSystem):
"""The container model of human mobility of Alessandretti, Aslak, and Lehmann.
Its trajectories cross scales. Space is a hierarchy of `L` levels of containers, a nested grid where every container
holds `side` by `side` containers of the level below, down to the locations, and every container has an
attractiveness among its siblings, drawn from a power law. An individual travels at the level-distance `d`, the
highest level at which its origin and destination differ, with the probability `p_d`, chooses the destination
container of level `d` among the other children of its container of level `d + 1` by attractiveness, and descends by
attractiveness to a location (arXiv 2109.07381 Methods, Generating traces). The nested grid, the power law of the
attractivenesses, and the probabilities of travel that do not depend on the distance from home follow Supplementary
Note 3. Displacements are a mixture of the scales of the containers, from one cell to `side^(L - 1)` cells.
The system has the group `individuals`.
Args:
n_individuals:
The number of individuals.
levels:
The number `L` of levels.
side:
The number of children of a container along every axis.
travel:
The probabilities `p_d` of displacements at the level-distances 1 to `L`.
exponent:
The exponent of the power law of the attractivenesses.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Examples:
>>> from skcomplex.systems.social.organizations import ContainerMobilitySystem
>>> ContainerMobilitySystem(3).prepare().system_.elements[0].size
3
"""
field = 'social/organizations'
topics = ('agents', 'human mobility', 'hierarchy', 'containers', 'scales')
references = ('Alessandretti, Aslak, and Lehmann 2020',)
until = 500
def __init__(
self,
n_individuals: int = 10,
*,
levels: int = 3,
side: int = 4,
travel: Sequence[float] = (0.6, 0.3, 0.1),
exponent: float = 1.5,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_individuals = n_individuals
self.levels = levels
self.side = side
self.travel = travel
self.exponent = exponent
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components built from the model parameters."""
super()._prepare(context)
individuals = ExplorerElement('individuals', size=self.n_individuals)
displacement = ContainerMobilityInteraction(
'displacement',
target='individuals',
levels=self.levels,
side=self.side,
travel=self.travel,
exponent=self.exponent,
)
self.system_ = System(self.label, elements=[individuals], interactions=[displacement])
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
ExplorerElement, fromElement
Interactions:
ContainerMobilityInteraction, fromInteraction
class ExplorerElement(Element):
"""Individual of the mobility systems.
It holds its position, its number of distinct locations, and its last level.
Args:
label:
The label of the individual or the group.
x:
The first coordinate of the current location.
y:
The second coordinate of the current location.
distinct:
The number of distinct locations visited.
level:
The level-distance of the last displacement in a hierarchy of containers, 0 without one.
size:
The number of members, or `None` for one.
Examples:
>>> from skcomplex.systems.social.organizations import ExplorerElement
>>> ExplorerElement('individual').distinct
1.0
"""
def __init__(
self,
label: str,
*,
x: object = 0.0,
y: object = 0.0,
distinct: Annotated[object, NN] = 1.0,
level: Annotated[object, NN] = 0.0,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.x = x
self.y = y
self.distinct = distinct
self.level = level
class ContainerMobilityInteraction(Interaction):
"""Container model of Alessandretti and coauthors.
It displaces individuals between locations nested in containers. Space is a nested grid of `levels` levels, every
container of a level split into `side` by `side` containers of the level below, and the containers of the lowest
level are the locations. The children of every container have attractivenesses drawn from a power law of the
exponent `exponent` and normalized, and home is the location of the largest attractiveness at every level. Every
step every individual draws the level-distance `d` of its displacement from `travel`, chooses a container of level
`d` other than its own among the children of its container of level `d + 1`, by attractiveness, and then descends to
a location by the attractivenesses of the children at every level below. Every individual has its own hierarchy,
drawn at its first step, and starts at home.
Args:
label:
The label of the interaction.
target:
The path of the group of individuals.
levels:
The number `L` of levels.
side:
The number of children of a container along every axis.
travel:
The probabilities of displacements at the level-distances 1 to `L`, the same from any distance from home.
exponent:
The exponent of the power law of the attractivenesses.
Raises:
ValidationError:
The probabilities of travel do not match the levels, raised by `prepare`.
Examples:
>>> from skcomplex.systems.social.organizations import ContainerMobilityInteraction
>>> ContainerMobilityInteraction('displacement', target='individuals').levels
3
"""
draws = True
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
levels: Annotated[int, NN] = 3,
side: Annotated[int, NN] = 4,
travel: Sequence[float] = (0.6, 0.3, 0.1),
exponent: Annotated[float, RealSet.open(0, oo)] = 1.5,
) -> None:
super().__init__(label)
self.target = target
self.levels = levels
self.side = side
self.travel = travel
self.exponent = exponent
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The probabilities of travel do not match the levels.
"""
super()._check_arguments()
if len(self.travel) != self.levels or not np.isclose(sum(self.travel), 1.0):
error_msg = f'Give {self.levels} probabilities of travel that sum to 1, not {tuple(self.travel)}.'
raise ValidationError(error_msg)
def _prepare(self, s: SimpleNamespace) -> None:
"""Set the displacement rule.
Args:
s:
The namespace of the symbols the laws can use.
"""
super()._prepare(s)
self.laws_: list[BaseLaw] = [UpdateLaw(s, self.move)]
def _get_attractiveness(self, rng: np.random.Generator) -> list[Array]:
"""Return the attractiveness of every container of every level.
Child 0 of every container is the largest.
"""
children = int(self.side) ** 2
result = []
for level in range(int(self.levels)):
parents = children ** (int(self.levels) - level - 1)
values = np.sort((1 - rng.random((parents, children))) ** (-1 / self.exponent), axis=1)[:, ::-1]
result.append((values / values.sum(axis=1, keepdims=True)).ravel())
return result
def _get_position(self, location: int) -> tuple[float, float]:
"""Return the centre of a location on the nested grid.
The location is a unit cell of the lowest level.
"""
side, children = int(self.side), int(self.side) ** 2
x = y = 0.0
for level in range(int(self.levels)):
child = (location // children**level) % children
x += (child % side) * side**level
y += (child // side) * side**level
return x + 0.5, y + 0.5
def _descend(self, container: int, level: int, attractiveness: list[Array], rng: np.random.Generator) -> int:
"""Return a location inside a container of a level.
A child is chosen by attractiveness at every level below.
"""
children = int(self.side) ** 2
for below in range(level - 1, 0, -1):
weights = attractiveness[below - 1][container * children : (container + 1) * children]
container = container * children + int(rng.choice(children, p=weights))
return container
def move(self, system: SystemView) -> None:
"""Displace every individual once.
The displacement is at a drawn level-distance, to a location chosen by attractiveness.
Args:
system:
The system.
"""
rng = system.rng
memory = system.storage
children, levels = int(self.side) ** 2, int(self.levels)
travel = np.asarray(self.travel, dtype=float)
for individual in cast(list[ExplorerView], system.get_agents(self.target)):
if f'location {individual.id}' not in memory:
memory[f'attractiveness {individual.id}'] = self._get_attractiveness(rng)
memory[f'location {individual.id}'], memory[f'visited {individual.id}'] = 0, {0}
individual.x, individual.y = self._get_position(0)
attractiveness = memory[f'attractiveness {individual.id}']
location = memory[f'location {individual.id}']
visited = memory[f'visited {individual.id}']
if not isinstance(attractiveness, list) or not isinstance(location, int) or not isinstance(visited, set):
continue
level = int(rng.choice(levels, p=travel)) + 1
# The location is its digits of base `children`, the lowest level first, and the container of a level its
# leading digits, so a container of level `level` is the location divided by `children^(level - 1)`.
own = location // children ** (level - 1)
siblings = (own // children) * children + np.arange(children)
weights = attractiveness[level - 1][siblings].copy()
weights[own % children] = 0.0
chosen = int(siblings[rng.choice(children, p=weights / weights.sum())])
location = self._descend(chosen, level, attractiveness, rng)
visited.add(location)
memory[f'location {individual.id}'] = location
individual.x, individual.y = self._get_position(location)
individual.level = float(level)
individual.distinct = float(len(visited))
Equations
The equations are those that symbolic returns for the system with its default parameters.