Wheel and rail contact
A rail segment on a sleeper, loaded by the wheels of passing bogies.
- Class:
WheelRailContactSystem - Import:
from skcomplex.systems.engineering.power_systems import WheelRailContactSystem - Field:
engineering/power_systems - Topics:
energy,vibration,railways,pulses,ode - References:
- Trzaska 2023
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.power_systems import WheelRailContactSystem
trajectory = WheelRailContactSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
F |
1000.0 |
T |
10.0 |
width |
1.0 |
spacing |
3.0 |
k2 |
0.0 |
Mr |
60.0 |
Ms |
156.0 |
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 | none |
| Laws | rate |
| Randomness | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class WheelRailContactSystem(BaseSystem):
"""A rail segment on a sleeper, loaded by the wheels of passing bogies.
The rail and the sleeper are lumped masses joined by the pad, a spring and a damper, and the sleeper rests on the
ballast, `Mr z'' + br (z' - zs') + kr (z - zs) = F(t)` and `Ms zs'' + br (zs' - z') + bs zs' + kr (zs - z) + ks zs +
k2 (alpha zs^2 + β zs^3) = 0`. The load is two rectangular pulses of force `F` per period `T`, one per wheel of a
bogie, `spacing` apart. The nonlinear ballast term, with `alpha = 1.75` and `β = -1`, is off for `k2 = 0`. The
system has the deflections `rail.z` of the rail and `rail.zs` of the sleeper, and their
velocities `rail.z'` and `rail.zs'`.
Args:
F:
The force of a wheel.
T:
The period of the passing bogies.
width:
The duration of the load of one wheel.
spacing:
The time between the two wheels of a bogie.
k2:
The stiffness of the nonlinear ballast term.
Mr:
The mass of the rail segment.
Ms:
The mass of the sleeper.
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.power_systems import WheelRailContactSystem
>>> WheelRailContactSystem(k2=500.0).prepare().system_.interactions[1].k2
500.0
"""
field = 'engineering/power_systems'
topics = ('energy', 'vibration', 'railways', 'pulses', 'ode')
references = ('Trzaska 2023',)
until = 60.0
dt = 0.05
def __init__(
self,
*,
F: float = 1000.0,
T: float = 10.0,
width: float = 1.0,
spacing: float = 3.0,
k2: float = 0.0,
Mr: float = 60.0,
Ms: float = 156.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.F = F
self.T = T
self.width = width
self.spacing = spacing
self.k2 = k2
self.Mr = Mr
self.Ms = Ms
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the rail and its sleeper, the wheels, the pad, and the ballast."""
super()._prepare(context)
rail = Element('rail', values={'z': 0.0, 'zs': 0.0, 'Mr': self.Mr, 'Ms': self.Ms})
wheels = WheelLoadInteraction(
'wheels',
target='rail',
F=self.F,
T=self.T,
width=self.width,
spacing=self.spacing,
)
ballast = BallastInteraction('ballast', target='rail', k2=self.k2)
pad = SpringDamperInteraction('pad', target='rail', states=('z', 'zs'), masses=('Mr', 'Ms'), k=6000.0, b=300.0)
self.system_ = System(self.label, elements=[rail], interactions=[wheels, ballast, pad])
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
WheelLoadInteraction, fromInteractionBallastInteraction, fromInteractionSpringDamperInteraction, fromInteraction
class Element(BaseElement):
"""An element that holds named values of one thing or of a group of members.
It holds its values by name, such as the height and mass of a ball in
`Element('ball', values={'x': 10.0, 'm': 1.0})`, and the laws of the interactions decide which values change. With
`size` it holds a group of members with values of their own, such as 1000 molecules of a gas, and with `space` one
member per site, such as the cells of a grid. A subclass may take its values as arguments of `__init__` instead,
such as a population class with a growth rate. Members whose values change by agent rules, Python functions run for
each member at each step, act as agents, and their values may be any Python object. It holds a prey population, a
firm of an economy, and the charge of a capacitor.
Read more in the user guide, under Elements.
Args:
label:
The name of the element, unique among the components of its system, such as `'rabbits'`.
values:
Values by name, such as `{'x': 10.0, 'm': 1.0}`. A derivative or a past value that a law reads starts from
the value named with primes or a past index, such as `{'x': 10.0, "x'": 3.0}` for a ball thrown upwards or
`{'y': 1.0, 'y[-1]': 0.5}` for an economy. A group of members takes one value per member as an array.
size:
The number of members, each with its own values, such as `1000` molecules of a gas, or `None` for one.
space:
The space of the element, with one member per site, such as a lattice of cells, or `None` for none.
on:
The part of a network space that holds one member each: `'edges'` for every link, `'hyperedges'` for every
hyperedge, the name of a layer for every link of that layer, such as `'immune'`, or `None` for every site.
Attributes:
default_visual_:
How the element is drawn by default, the `visual` of its class.
See Also:
BaseElement: The base of every element.
Interaction: States the laws that change the values of elements.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
>>> ball.get_params()['x']
10.0
"""
law_classes: ClassVar[tuple[type, ...]] = ()
def __init__(
self,
label: str,
*,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
on: str | None = None,
) -> None:
super().__init__(label)
self.values = values
self.size = size
self.space = space
self.on: object = on
def get_params(self, deep: bool = True) -> dict[str, Any]:
"""Return the parameters of the element, with each entry of `values` when deep.
An entry of `values` whose name is a Python identifier is listed under its own name, so a system lists it as
`<element>__<name>` and `set_params(ball__x=2.0)`, grid searches, and sweeps reach it. A primed or past value,
such as `"x'"` or `'x[-1]'`, is no identifier and stays inside `values`. An entry that has the name of an
argument is not listed twice.
Args:
deep:
Whether to add the parameters of nested estimators and the entries of `values`.
Returns:
params:
The parameters by name.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
>>> params['x'], "x'" in params
(10.0, False)
"""
params = super().get_params(deep=deep)
if deep and isinstance(self.values, Mapping):
entries = self._get_value_entries()
params.update({name: value for name, value in entries.items() if name not in params})
return params
def set_params(self, **params: object) -> Self:
"""Set parameters of the element and entries of `values` by name.
An entry of `values` takes its new value in a new mapping, so the mapping the user gave never changes, as
`clone` of scikit-learn leaves the arguments of an estimator unchanged. A new `values` is set first, so the
output of `get_params` is accepted as it is.
Args:
**params:
The new values, by the name of a parameter or of an entry of `values`, such as `x=2.0`.
Returns:
self:
The element.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> values = {'x': 10.0}
>>> Element('ball', values=values).set_params(x=2.0).values, values
({'x': 2.0}, {'x': 10.0})
"""
arguments = super().get_params(deep=True)
if 'values' in params:
super().set_params(values=params['values'])
entries = self._get_value_entries()
changed = {name: value for name, value in params.items() if name in entries and name not in arguments}
rest = {name: value for name, value in params.items() if name not in changed and name != 'values'}
super().set_params(**rest)
if changed:
self.values = {**(self.values or {}), **changed}
return self
def _get_value_entries(self) -> dict[str, object]:
"""Return the entries of `values` whose names are Python identifiers."""
values = self.values if isinstance(self.values, Mapping) else {}
return {name: value for name, value in values.items() if name.isidentifier()}
def _prepare(self, context: BaseSpace | None = None) -> None:
"""Set `default_visual_`, checking the reserved names.
Args:
context:
The space the element inherits from its system, which an element with `on` and no space of its own
sits on.
Raises:
ValidationError:
`size` is not a number of members, `space` is not a space, or `values` is not a mapping, as when a
subclass stores a quantity of its own under a reserved name.
"""
super()._prepare(context)
size = self.size
checks = {
'size': size is None or (isinstance(size, numbers.Integral) and not isinstance(size, bool) and size >= 1),
'space': self.space is None or isinstance(self.space, BaseSpace),
'values': self.values is None or isinstance(self.values, Mapping),
}
for name, valid in checks.items():
if not valid:
error_msg = (
f'Element {self.label!r} has {name} = {getattr(self, name)!r}, but {name} is the '
f'{RESERVED_MEANINGS[name]}. The names {", ".join(RESERVED)} are reserved, so rename the value, '
f'such as half_side for the half side of a table.'
)
raise ValidationError(error_msg)
self._check_on(self.space if self.space is not None else context)
def _get_tags(self) -> Tags:
"""Return the tags of the element, with the tags of its space when it has one.
A field on a phase space thus asks for a solver that supports phase spaces, as a group on it does.
"""
tags = super()._get_tags()
if not isinstance(self.space, BaseSpace):
return tags
return replace(tags, space=self.space.get_tags().space)
def _check_on(self, space: BaseSpace | None) -> None:
"""Raise an error for an `on` that names no part of a network space.
A value named `on` that the element declares as its own state or parameter names no place. The space is the
element's own, or else that of its system.
"""
if isinstance(type(self)._get_specs().get('on'), _StateSpec | _ParameterSpec):
return
on = getattr(self, 'on', None)
if on is None or (isinstance(space, NetworkSpace) and (on in LINKS or on in space.prepare().graphs_)):
return
error_msg = (
f'Element {self.label!r} has on = {on!r}, but on is the part of a network space that holds one member '
"each, 'edges', 'hyperedges', or the name of a layer for its edges, such as "
"Element('links', values={'sign': 1}, space=network, on='edges'). The names "
f'{", ".join(RESERVED)} are reserved, so rename a value of the element named on, such as closed for a '
'switch.'
)
raise ValidationError(error_msg)
@staticmethod
def _get_domain_of(annotation: object, value: object) -> object:
"""Return the domain of a value from its annotation or its Python type.
A value without an annotation, such as one given through `values`, takes the domain of its type, so `3` is an
integer and `0.5 + 1j` is complex. The annotation `object` says nothing of the kind, so a value annotated so,
such as a point that may be one number or an array of complex numbers, also takes the domain of its type, and
so does a value of one of several types, such as `float | Sequence[float]`. A subshift, such as
`Annotated[int, SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))]`, is the domain of the cells of a
lattice whose configurations hold no forbidden word.
"""
if get_origin(annotation) is Annotated:
for item in get_args(annotation)[1:]:
if isinstance(item, set | frozenset):
return FiniteEnumeratedSet(sorted(item, key=str))
allowed = hasattr(item, '__contains__') and not isinstance(item, str | MatrixGroupSpec)
if allowed or isinstance(item, SubshiftSpec | PowerSeriesSpec):
return item
annotation = get_args(annotation)[0]
annotated = isinstance(annotation, type) and annotation not in {inspect.Parameter.empty, object}
kind = annotation if annotated else type(value)
if kind is bool:
return BOOLEAN
if kind is int:
return ZZ
if kind is complex or (isinstance(kind, type) and issubclass(kind, np.complexfloating)):
return CC
return RR
def _get_domain_tags(self) -> frozenset[str]:
"""Return the domain tags of the states of the element.
An element that declares no states has the domains of all its numeric values, since the laws of the system
decide which of them are states, such as `boolean` for `opinion: Annotated[int, {0, 1}] = 0`.
"""
if self._get_component_specs():
return super()._get_domain_tags()
params = self.get_params(deep=False)
values = {name: params.get(name) for name in self._get_hints()}
values |= {name: value for name, value in (self.values or {}).items() if name.isidentifier()}
hints = self._get_hints()
domains = {
_StateSpec(domain=self._get_domain_of(hints.get(name, inspect.Parameter.empty), value))._get_domain_tag()
for name, value in values.items()
if isinstance(value, numbers.Number | list | np.ndarray)
}
return frozenset(domain for domain in domains if domain is not None)
def _get_hints(self) -> dict[str, object]:
"""Return the type hint of every value argument by name, in their order.
The hints are the annotations of the arguments of the class, such as `Annotated[float, Quantity('energy')]`,
from which the kind, the allowed values, the quantity, and the period of each value are read. A generic
subclass that takes its values through `values` gives their hints here instead, and the arguments it leaves
out, such as the allowed values themselves, are no values.
"""
parameters = inspect.signature(type(self)).parameters
return {name: parameter.annotation for name, parameter in parameters.items() if name not in RESERVED}
@classmethod
def _get_view(cls) -> type | None:
"""Return the class of the views of the element's agents.
The result is `None` for the engine's plain view. An agent element names a subclass of the engine's `AgentView`
that annotates its states and parameters, such as `class WordView(AgentView): count: float`, so its rules read
them with checked types.
"""
return None
class WheelLoadInteraction(Interaction):
"""Load of the two wheels of passing bogies on a rail.
Every bogie presses the rail with two rectangular pulses of force `F` and duration `width`, `spacing` apart, once
per period `T`, and the load accelerates the rail divided by its mass.
Args:
label:
The label of the interaction.
target:
The path of the element that holds the rail.
state:
The name of the deflection of the rail.
mass:
The name of the mass of the rail.
F:
The force of a wheel.
T:
The period of the passing bogies.
width:
The duration of the load of one wheel.
spacing:
The time between the two wheels of a bogie.
Examples:
>>> from skcomplex.systems.engineering.power_systems import WheelLoadInteraction
>>> WheelLoadInteraction('wheels', target='rail', F=500.0).F
500.0
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'z',
mass: str = 'Mr',
F: Annotated[float, RealSet.closed_open(0, oo)] = 1000.0,
T: Annotated[float, RealSet.open(0, oo)] = 10.0,
width: Annotated[float, RealSet.open(0, oo)] = 1.0,
spacing: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.mass = mass
self.F = F
self.T = T
self.width = width
self.spacing = spacing
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the acceleration of the rail by the wheels.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
s, z = context, getattr(context.target, self.state)
load = pulse_train(s.t, s.T, s.width, s.F) + pulse_train(s.t, s.T, s.width, s.F, start=s.spacing)
self.laws_: list[BaseLaw] = [RateLaw(z.diff(s.t, 2), load / getattr(s.target, self.mass))]
class BallastInteraction(Interaction):
"""Ballast under a sleeper, a damped spring with an optional nonlinear term.
The ballast pushes the sleeper with `-bs zs' - ks zs - k2 (alpha zs^2 + beta zs^3)`, which accelerates it divided
by its mass. The nonlinear term is off for `k2 = 0`.
Args:
label:
The label of the interaction.
target:
The path of the element that holds the sleeper.
state:
The name of the deflection of the sleeper.
mass:
The name of the mass of the sleeper.
ks:
The stiffness of the ballast.
bs:
The damping of the ballast.
k2:
The stiffness of the nonlinear term.
alpha:
The quadratic coefficient of the nonlinear term.
beta:
The cubic coefficient of the nonlinear term.
Examples:
>>> from skcomplex.systems.engineering.power_systems import BallastInteraction
>>> BallastInteraction('ballast', target='rail', k2=500.0).k2
500.0
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'zs',
mass: str = 'Ms',
ks: Annotated[float, RealSet.closed_open(0, oo)] = 1500.0,
bs: Annotated[float, RealSet.closed_open(0, oo)] = 520.0,
k2: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
alpha: float = 1.75,
beta: float = -1.0,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.mass = mass
self.ks = ks
self.bs = bs
self.k2 = k2
self.alpha = alpha
self.beta = beta
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the acceleration of the sleeper by the ballast.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
s, zs = context, getattr(context.target, self.state)
force = -s.bs * zs.diff(s.t) - s.ks * zs - s.k2 * (s.alpha * zs**2 + s.beta * zs**3)
self.laws_: list[BaseLaw] = [RateLaw(zs.diff(s.t, 2), force / getattr(s.target, self.mass))]
class SpringDamperInteraction(Interaction):
"""Linear spring and damper between two coordinates `x1` and `x2` of one element.
The spring pulls the coordinates together with the force `-k (x1 - x2)` and the damper with `-b (x1' - x2')`. Both
forces accelerate the first coordinate divided by its mass and the second, with the opposite sign, divided by its
own, as the suspension between the body and the wheel of a car or the pad between a rail and its sleeper.
Args:
label:
The label of the interaction.
target:
The path of the element with the two coordinates and their masses.
states:
The names of the two coordinates.
masses:
The names of the masses of the two coordinates.
k:
The stiffness of the spring.
b:
The damping of the damper.
Raises:
ValidationError:
The states or the masses are not two names.
Examples:
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.engineering.common.mechanics import SpringDamperInteraction
>>> car = Element('car', values={'x1': 0.1, 'x2': 0.0, 'm1': 250.0, 'm2': 30.0})
>>> suspension = SpringDamperInteraction('suspension', target='car', k=16000.0, b=1000.0)
>>> System(elements=[car], interactions=[suspension]).prepare().states_
('car.x1', "car.x1'", 'car.x2', "car.x2'")
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
states: Sequence[str] = ('x1', 'x2'),
masses: Sequence[str] = ('m1', 'm2'),
k: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
b: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
) -> None:
super().__init__(label)
self.target = target
self.states = states
self.masses = masses
self.k = k
self.b = b
def _check_names(self) -> None:
"""Raise an error for states or masses that are not two names.
Raises:
ValidationError:
The states or the masses are not two names.
"""
for name, value in (('states', self.states), ('masses', self.masses)):
names = [value] if isinstance(value, str) else list(value)
if len(names) != N_STATES or not all(isinstance(item, str) and item.isidentifier() for item in names):
error_msg = f'{self.label!r} has the {name} {value!r}. Give two names, such as ("y1", "y2").'
raise ValidationError(error_msg)
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The states or the masses are not two names.
"""
super()._check_arguments()
self._check_names()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the accelerations of both coordinates by the spring and by the damper.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
member, t = context.target, context.t
first, second = (getattr(member, name) for name in self.states)
spring = -context.k * (first - second)
damper = -context.b * (first.diff(t) - second.diff(t))
laws: list[BaseLaw] = []
for state, mass, sign in ((first, self.masses[0], 1), (second, self.masses[1], -1)):
laws += [
RateLaw(state.diff(t, 2), sign * spring / getattr(member, mass)),
RateLaw(state.diff(t, 2), sign * damper / getattr(member, mass)),
]
self.laws_ = laws
Equations
The equations are those that symbolic returns for the system with its default parameters.
rail.z: diff(z_rail(t), t, t) == -k_pad*(z_rail(t) - zs_rail(t))/Mr_rail - b_pad*(diff(z_rail(t), t) - diff(zs_rail(t), t))/Mr_rail + (where(both(t >= 0.0, mod(t, T_wheels) < width_wheels), F_wheels, 0) + where(both(t >= spacing_wheels, mod(-spacing_wheels + t, T_wheels) < width_wheels), F_wheels, 0))/Mr_rail
rail.zs: diff(zs_rail(t), t, t) == k_pad*(z_rail(t) - zs_rail(t))/Ms_rail + b_pad*(diff(z_rail(t), t) - diff(zs_rail(t), t))/Ms_rail - ((beta_ballast*zs_rail(t)^3 + alpha_ballast*zs_rail(t)^2)*k2_ballast + ks_ballast*zs_rail(t) + bs_ballast*diff(zs_rail(t), t))/Ms_rail