Payne system
The Payne system, where the speed of traffic relaxes to the Greenshields speed.
- Class:
PayneSystem - Import:
from skcomplex.systems.engineering.traffic import PayneSystem - Field:
engineering/traffic - Topics:
traffic,field,conservation law,finite volume,pde - References:
- Payne 1971
- Chowdhury, Santen, and Schadschneider 2000
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.engineering.traffic import PayneSystem
trajectory = PayneSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n |
200 |
density |
0.3 |
bump |
0.2 |
vmax |
1.0 |
rho_max |
1.0 |
tau |
0.5 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | lattice |
| Laws | rate |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class PayneSystem(BaseSystem):
"""The Payne system, where the speed of traffic relaxes to the Greenshields speed.
The speed also anticipates density. The density and the flow `q = rho v` on a ring road of length 1 follow
`rho_t + q_x = 0` and `q_t + (q^2 / rho + P(rho))_x = (rho V(rho) - q) / τ`, with
`V(rho) = vmax (1 - rho / rho_max)` and the anticipation pressure `P(rho) = vmax rho / (2 τ rho_max)`. This is the
speed equation `v_t + v v_x = (V - v) / τ + V'(rho) rho_x / (2 τ rho)` in conservation form. The flow starts in
equilibrium with a bump of density. The system has the density `road.rho` and the flow `road.q`.
Args:
n:
The number of cells.
density:
The mean density.
bump:
The relative height of the density bump.
vmax:
The speed on an empty road.
rho_max:
The jam density.
tau:
The relaxation time of the speed.
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.engineering.traffic import PayneSystem
>>> PayneSystem(10).prepare().system_.elements[0].tau
0.5
"""
field = 'engineering/traffic'
topics = ('traffic', 'field', 'conservation law', 'finite volume', 'pde')
references = ('Payne 1971', 'Chowdhury, Santen, and Schadschneider 2000')
until = 1.0
dt = 0.05
@staticmethod
def _get_density_bump(n: int, density: float, bump: float) -> np.ndarray:
"""Return a uniform density on a ring with a smooth bump around the middle.
The bump has the relative height `bump`.
"""
centers = (np.arange(n) + 0.5) / n
return density * (1 + bump * np.exp(-(((centers - 0.5) / 0.05) ** 2)))
def __init__(
self,
n: int = 200,
*,
density: float = 0.3,
bump: float = 0.2,
vmax: float = 1.0,
rho_max: float = 1.0,
tau: float = 0.5,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n = n
self.density = density
self.bump = bump
self.vmax = vmax
self.rho_max = rho_max
self.tau = tau
@staticmethod
def _get_payne_flux(s: SimpleNamespace) -> Expression:
"""Return the flux `q^2 / rho + P(rho)` of the flow with the anticipation pressure."""
road = s.target
return road.q**2 / road.rho + road.vmax * road.rho / (2 * road.tau * road.rho_max)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components of the system built from its model parameters."""
super()._prepare(context)
density = self.density
rho = PayneSystem._get_density_bump(self.n, density, self.bump)
road = PayneElement(
'road',
rho=rho,
q=rho * self.vmax * (1 - rho / self.rho_max),
vmax=self.vmax,
rho_max=self.rho_max,
tau=self.tau,
space=LatticeSpace(self.n, spacing=1 / self.n, discretization='finite-volume'),
)
density = Interaction(
'density',
roles={'target': 'road'},
laws=lambda s: [RateLaw(s.target.rho, -divergence([s.target.q]))],
)
flow = Interaction(
'flow',
roles={'target': 'road'},
laws=lambda s: [RateLaw(s.target.q, -divergence([self._get_payne_flux(s)]))],
)
relaxation = SpeedAdaptationInteraction(
'relaxation',
target='road',
state='q',
goal=lambda s: s.target.rho * s.target.vmax * (1 - s.target.rho / s.target.rho_max),
time=lambda s: s.target.tau,
)
self.system_ = System(
self.label,
elements=[road],
interactions=[density, flow, relaxation],
solver=SSPRKSolver(),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
PayneElement, fromElement
Interactions:
InteractionSpeedAdaptationInteraction, fromInteraction
class PayneElement(Element):
"""Cell of a road with the density `rho` and the flow `q` of the Payne system.
The density and the flow are conserved by conservation laws, and the flow relaxes to the Greenshields flow
by a relaxation interaction.
"""
def __init__(
self,
label: str,
*,
rho: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
q: object = 0.21,
vmax: Annotated[object, RealSet.open(0, oo)] = 1.0,
rho_max: Annotated[object, RealSet.open(0, oo)] = 1.0,
tau: Annotated[object, RealSet.open(0, oo)] = 0.5,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.rho = rho
self.q = q
self.vmax = vmax
self.rho_max = rho_max
self.tau = tau
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
class SpeedAdaptationInteraction(Interaction):
"""Adaptation of a speed or a flow towards a desired one over an adaptation time.
Traffic engineering names it the speed adaptation of a driver, as in the optimal velocity and Payne-Whitham models.
The rate is `(goal(s) - x) / time(s)` of a value `x` of the target, with optional noise. With a constant goal and
time and an additive noise of amplitude `sigma`, the value follows the Ornstein-Uhlenbeck process
`dx = (goal - x) / time dt + sigma dW`, whose stationary variance is `sigma**2 time / 2`. The value is a state of
the target, such as the flow `Q` of a road, or the speed `"x'"` of a car, the derivative of its position. A goal, a
time, or a noise is a number or a function of the namespace of the interaction, whose target is `s.target`.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element or group whose value relaxes.
state:
The name of the value of the target that relaxes, with a prime for the derivative of a value.
goal:
A function of the namespace that returns the goal, or a number.
time:
A function of the namespace that returns the relaxation time, or a positive number.
noise:
A function of the namespace that returns the amplitude of the noise, a number, or `None` for no noise.
Raises:
ValidationError:
A goal, a time, or a noise is neither callable nor a number, raised by `prepare`.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.engineering.common.traffic import SpeedAdaptationInteraction
>>> relaxation = SpeedAdaptationInteraction('relaxation', target='stock', goal=10.0, time=0.5)
>>> system = System(elements=[Element('stock', values={'x': 0.0})], interactions=[relaxation]).prepare()
>>> round(float(system.simulate(until=5.0, dt=0.01).get_values('stock.x')[-1]), 3)
10.0
"""
law_classes = (RateLaw, NoiseLaw)
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'x',
goal: Setting = 0.0,
time: Setting = 1.0,
noise: Setting | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.goal = goal
self.time = time
self.noise = noise
def _get_tags(self) -> Tags:
"""Return the tags of the rate, with a noise when the interaction has one.
It has one when the noise is given or a subclass writes `_get_noise`.
"""
noisy = self.noise is not None or type(self)._get_noise is not SpeedAdaptationInteraction._get_noise
return self._get_variant_tags((RateLaw, NoiseLaw) if noisy else (RateLaw,))
def _check_arguments(self) -> None:
"""Raise an error for a goal, a time, or a noise that is no function or number.
Raises:
ValidationError:
A goal, a time, or a noise is neither callable nor a number.
"""
super()._check_arguments()
for name in ('goal', 'time', 'noise'):
value = getattr(self, name)
if not (callable(value) or isinstance(value, int | float) or (name == 'noise' and value is None)):
error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function of the namespace or a number.'
raise ValidationError(error_msg)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the relaxation of the value of the target and its noise.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
s, t = context, context.t
position = getattr(s.target, self.state.rstrip("'"))
order = len(self.state) - len(self.state.rstrip("'"))
value = position.diff(t, order) if order else position
laws: list[BaseLaw] = [RateLaw(value.diff(t), (self._get_goal(s) - value) / self._get_time(s))]
noise = self._get_noise(s)
if noise is not None:
laws.append(NoiseLaw(position.diff(t, order + 1), noise))
self.laws_ = laws
@staticmethod
def _evaluate(value: Setting, namespace: SimpleNamespace) -> object:
"""Return a number, or the value of a function of the namespace."""
return value(namespace) if callable(value) else value
def _get_goal(self, namespace: SimpleNamespace) -> object:
"""Return the goal, the hook a subclass overrides to derive it from its parameters."""
return self._evaluate(self.goal, namespace)
def _get_time(self, namespace: SimpleNamespace) -> object:
"""Return the relaxation time, the hook a subclass overrides to derive it from its parameters."""
return self._evaluate(self.time, namespace)
def _get_noise(self, namespace: SimpleNamespace) -> object:
"""Return the amplitude of the noise, or `None`, the hook a subclass overrides."""
return None if self.noise is None else self._evaluate(self.noise, namespace)