Brothel movement system
The brothel movement system.
- Class:
TraffickingSystem - Import:
from skcomplex.systems.social.organizations import TraffickingSystem - Field:
social/organizations - Topics:
trafficking,agents,grid,crime - References:
- Chesney 2021
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 TraffickingSystem
trajectory = TraffickingSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
width |
30 |
height |
30 |
n_cities |
3 |
n_houses |
40 |
n_brothels |
3 |
n_victims |
12 |
n_free |
30 |
random_state |
0 |
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 | lattice |
| Laws | update |
| Randomness | unknown |
| Domains | boolean, integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class TraffickingSystem(BaseSystem):
"""The brothel movement system.
Victims moved between brothels leave traces in bills and train trips. The system has the groups `premises` and
`women`.
Args:
width:
The number of columns of the grid.
height:
The number of rows of the grid.
n_cities:
The number of cities, vertical bands of equal width.
n_houses:
The number of houses.
n_brothels:
The number of brothels.
n_victims:
The number of victims, spread over the brothels.
n_free:
The number of women who travel freely.
random_state:
The seed or generator of the places, the women, and the efficiencies.
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 TraffickingSystem
>>> system = TraffickingSystem(n_houses=5, n_brothels=2, n_victims=4, n_free=3).prepare().system_
>>> [group.size for group in system.elements]
[7, 7]
"""
field = 'social/organizations'
topics = ('trafficking', 'agents', 'grid', 'crime')
references = ('Chesney 2021',)
until = 90
def __init__(
self,
width: int = 30,
height: int = 30,
*,
n_cities: int = 3,
n_houses: int = 40,
n_brothels: int = 3,
n_victims: int = 12,
n_free: int = 30,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.width = width
self.height = height
self.n_cities = n_cities
self.n_houses = n_houses
self.n_brothels = n_brothels
self.n_victims = n_victims
self.n_free = n_free
self.random_state = random_state
@staticmethod
def _add_bills(system: SystemViewProtocol) -> None:
"""Count a day at every premises and add to its bills the growth `1 / (1 + exp(x0 - n))` for the `n` inside."""
places = [place for place in system.get_agents('premises') if isinstance(place, PremisesView)]
for place in places:
place.day = place.day + 1.0
occupancy = system.get_occupancy('women')
heat = [float(1 / (1 + np.exp(place.efficiency - occupancy.get(place.location_key, 0)))) for place in places]
for place, growth in zip(places, heat, strict=True):
place.bills = place.bills + growth
@staticmethod
def _close_quarter(system: SystemViewProtocol) -> None:
"""Record the bills of the quarter that ends at every premises and start the next quarter at zero."""
places = [place for place in system.get_agents('premises') if isinstance(place, PremisesView)]
for place in places:
place.last_bills = float(place.bills)
for place in places:
place.bills = 0.0
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components built from the model parameters."""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
n_places = self.n_houses + self.n_brothels
cells = rng.permutation(self.width * self.height)[:n_places]
places = [(int(cell % self.width), int(cell // self.width)) for cell in cells]
brothel = (np.arange(n_places) >= self.n_houses).astype(float)
space = LatticeSpace((self.width, self.height), boundary='fixed')
x, y = np.array(places).T
premises = PremisesElement(
'premises',
brothel=brothel,
efficiency=rng.uniform(0, 3, n_places),
values={'x': x, 'y': y},
size=n_places,
space=space,
)
homes = [places[self.n_houses + index % self.n_brothels] for index in range(self.n_victims)]
homes += [(int(rng.integers(self.width)), int(rng.integers(self.height))) for _ in range(self.n_free)]
victim = (np.arange(self.n_victims + self.n_free) < self.n_victims).astype(float)
x, y = np.array(homes).T
women = TravellerElement(
'women',
victim=victim,
values={'x': x, 'y': y},
size=self.n_victims + self.n_free,
space=space,
)
day = DailyMovementsInteraction(
'day',
women='women',
premises='premises',
n_cities=self.n_cities,
phase=DAILY,
victims_phase=MONTHLY,
)
bills = [
Interaction(
'bills',
roles={'premises': 'premises', 'women': 'women'},
laws=lambda s: [
UpdateLaw(s, self._add_bills, phase=BILLING),
UpdateLaw(s, self._close_quarter, phase=QUARTERLY),
],
),
]
phases = [
PhaseSpec(DAILY, activation='sequential'),
PhaseSpec(MONTHLY, activation='sequential', period=MONTH),
PhaseSpec(BILLING, activation='sequential'),
PhaseSpec(QUARTERLY, activation='sequential', period=QUARTER),
]
self.system_ = System(
self.label,
elements=[premises, women],
interactions=[day, *bills],
space=space,
solver=MesaSolver(phases=phases),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
DailyMovementsInteraction, fromInteractionInteraction
class PremisesElement(Element):
"""House or brothel of the brothel movement system.
Its energy bills grow with the people inside. Every day the bills grow by `1 / (1 + exp(x0 - n))` for the `n` people
in the premises' cell, and every quarter they are recorded and reset. In `TraffickingSystem`, maps of the bills read
the counts of the women by cell every day, and maps in a phase of a period of 90 days record and reset them.
Args:
label:
The label of the agent or group.
brothel:
Whether the premises are a brothel, 1, or a house, 0.
bills:
The bills of the current quarter.
last_bills:
The bills of the last full quarter.
efficiency:
The midpoint `x0` of the sigmoid of the bills.
day:
The number of days run.
values:
Further values by name, such as the cell `x` and `y` of every member.
size:
The number of members, or `None` for one.
space:
The grid whose axes `x` and `y` place the members, or `None` for none.
Examples:
>>> from skcomplex.systems.social.organizations import PremisesElement
>>> group = PremisesElement('premises', brothel=1.0, size=3)
>>> group.label, group.size
('premises', 3)
"""
visual = VisualSpec('agents', {'color_by': 'brothel', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
brothel: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
bills: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
last_bills: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
efficiency: object = 1.0,
day: Annotated[object, NN] = 0.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.brothel = brothel
self.bills = bills
self.last_bills = last_bills
self.efficiency = efficiency
self.day = day
class TravellerElement(Element):
"""Woman of the brothel movement system.
She is a trafficking victim, or a woman who travels freely.
Args:
label:
The label of the agent or group.
victim:
Whether the woman is a trafficking victim, 1, or not, 0.
trips:
The number of train trips between cities.
values:
Further values by name, such as the cell `x` and `y` of every member.
size:
The number of members, or `None` for one.
space:
The grid whose axes `x` and `y` place the members, or `None` for none.
Examples:
>>> from skcomplex.systems.social.organizations import TravellerElement
>>> group = TravellerElement('women', victim=1.0, size=4)
>>> group.label, group.size
('women', 4)
"""
visual = VisualSpec('agents', {'color_by': 'victim', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
victim: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
trips: Annotated[object, NN] = 0.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.victim = victim
self.trips = trips
class DailyMovementsInteraction(Interaction):
"""Movements of the women of the brothel movement system.
Every day one random free woman moves to a random cell of a random city, and in the steps of the phase
`victims_phase` the traffickers move a random number of the victims of every brothel to random brothels. A move
between cities counts as a train trip. The cities are vertical bands of equal width of the grid.
Args:
label:
The label of the interaction.
women:
The path of the group of travellers.
premises:
The path of the group of premises, whose brothels the victims move between.
n_cities:
The number of cities, vertical bands of equal width.
phase:
The phase of the step the free woman moves in, or `None` for the default phase.
victims_phase:
The phase of the step the victims move in, or `None` for the default phase.
Examples:
>>> from skcomplex.systems.social.organizations import DailyMovementsInteraction
>>> DailyMovementsInteraction('day', women='women', premises='premises').n_cities
3
"""
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
women: Role,
premises: Role,
n_cities: int = 3,
phase: str | None = None,
victims_phase: str | None = None,
) -> None:
super().__init__(label)
self.women = women
self.premises = premises
self.n_cities = n_cities
self.phase = phase
self.victims_phase = victims_phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rules of the free women and of the victims as rules of the system, in their phases.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [
UpdateLaw(context, self.move_free, phase=self.phase),
UpdateLaw(context, self.move_victims, phase=self.victims_phase),
]
def _get_city(self, location: object, width: int) -> int:
"""Return the city of a cell of a grid of a given width."""
return DailyMovementsInteraction._get_cell(location)[0] * self.n_cities // width
@staticmethod
def _get_shape(system: SystemView) -> tuple[int, int]:
"""Return the width and the height of the grid of the system."""
dimensions = system.dimensions
if dimensions is None:
error_msg = 'The trafficking system runs on a grid, and its agents live in no space.'
raise SpaceError(error_msg)
width, height = dimensions
return int(width), int(height)
def _travel(self, woman: TravellerView, cell: tuple[int, int], width: int) -> None:
"""Move a woman to a cell and count a trip when the city changes."""
if self._get_city(cell, width) != self._get_city(woman.location, width):
woman.trips += 1
woman.move_to(cell)
def move_free(self, system: SystemView) -> None:
"""Move a random free woman to a random cell of a random city.
Args:
system:
The system.
"""
free = [woman for woman in cast(list[TravellerView], system.get_agents('women')) if not woman.victim]
if not free:
return
width, height = self._get_shape(system)
city = int(system.rng.integers(self.n_cities))
start, stop = city * width // self.n_cities, (city + 1) * width // self.n_cities
cell = (int(system.rng.integers(start, stop)), int(system.rng.integers(height)))
self._travel(free[int(system.rng.integers(len(free)))], cell, width)
def move_victims(self, system: SystemView) -> None:
"""Move a random number of the victims of every brothel to random brothels.
Args:
system:
The system.
"""
women = cast(list[TravellerView], system.get_agents('women'))
brothels = [
DailyMovementsInteraction._get_cell(place.location)
for place in cast(list[PremisesView], system.get_agents('premises'))
if place.brothel
]
width = self._get_shape(system)[0]
for brothel in brothels:
victims = [
woman
for woman in women
if woman.victim and DailyMovementsInteraction._get_cell(woman.location) == brothel
]
moved = system.rng.permutation(len(victims))[: int(system.rng.integers(len(victims) + 1))]
for index in moved:
self._travel(victims[index], brothels[int(system.rng.integers(len(brothels)))], width)
@staticmethod
def _get_cell(location: object) -> tuple[int, int]:
"""Return a grid location as a tuple of integers."""
column, row = (int(item) for item in np.ravel(np.asarray(location)))
return column, row
class Interaction(BaseInteraction):
"""An interaction whose laws run once for the elements its roles bind.
It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
`Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
populations, a reaction between two chemicals, and an infection along the contacts of a network.
Read more in the user guide, under Interactions.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
The function of the namespace that returns the laws of a rule written without a class, such as
`lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
`None`.
among:
The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.
along:
`True` for the edges of the network the group lives on, the name of a layer of a network with several, such
as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
`RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.
within:
A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
force `-dV/dx` on its position `x`.
See Also:
BaseInteraction: The base of every interaction.
RandomPartition: Groups the members of a group at random at every step.
TrainingInteraction: Trains the parameters of a nested system.
Examples:
>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
"""
def __init__(
self,
label: str,
*,
roles: Mapping[str, object] | None = None,
laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
among: str | None = None,
along: bool | str | tuple[str, int] | RandomPartition | None = None,
within: RadiusNeighborhood | None = None,
) -> None:
super().__init__(label)
self.roles = roles
self.laws = laws
self.among = among
self.along = along
self.within = within
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None