Minimum-time control of a free particle, a harmonic oscillator, and a saddle
A linear plant steered to the origin of its phase space in minimum time.
- Class:
MinimumTimeControlSystem - Import:
from skcomplex.systems.engineering.control import MinimumTimeControlSystem - Field:
engineering/control - Topics:
control,bang-bang,optimal control,pontryagin,events,ode - References:
- Pontryagin et al. 1962
- Dilão 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.control import MinimumTimeControlSystem
trajectory = MinimumTimeControlSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
x |
3.0 |
v |
2.0 |
plant |
'free_particle' |
interval |
0.1 |
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, update |
| Randomness | deterministic |
| Domains | integer, real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class MinimumTimeControlSystem(BaseSystem):
"""A linear plant steered to the origin of its phase space in minimum time.
A sampled bang-bang control steers it. The plant follows `x'' = a x + u` with `|u| <= 1`: a free particle,
`x'' = u`, a harmonic oscillator, `x'' + x = u`, or an unstable saddle, `x'' - x = u`. Pontryagin's maximum
principle makes the minimum-time control bang-bang, `u = ±1`, with the switch on the curve of the two trajectories
under `u = 1` and `u = -1` that reach the origin: the control is -1 above the curve and 1 below it. As in Dilão's
examples, the controller samples the position and the velocity every `interval` and holds the control until the next
sample, so the plant reaches a neighbourhood of the origin, whose size shrinks with the interval, and stays there. A
free particle from `(x, v)` above the curve reaches the origin at the time `v + 2 sqrt(x + v^2 / 2)`, about 6.47 for
the defaults. Only the states between the lines `y = -(x + 1)` and `y = -(x - 1)` of the saddle are controllable,
and from the others the plant escapes to infinity.
The system has the position `plant.x`, the velocity `plant.x'`, and the control `plant.u`, which the samples
`sample` set.
Args:
x:
The initial position.
v:
The initial velocity.
plant:
The plant, `'free_particle'`, `'harmonic_oscillator'`, or `'saddle'`.
interval:
The time between two samples of the controller.
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.
Raises:
ParameterError:
The plant is unknown, or the interval is not positive.
Examples:
>>> from skcomplex.systems.engineering.control import MinimumTimeControlSystem
>>> MinimumTimeControlSystem(plant='saddle', x=0.5, v=0.0).prepare().system_.elements[0].u
-1.0
"""
field = 'engineering/control'
topics = ('control', 'bang-bang', 'optimal control', 'pontryagin', 'events', 'ode')
references = ('Pontryagin et al. 1962', 'Dilão 2023')
until = 10.0
dt = 0.01
def __init__(
self,
x: float = 3.0,
v: float = 2.0,
*,
plant: str = 'free_particle',
interval: float = 0.1,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.x = x
self.v = v
self.plant = plant
self.interval = interval
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)
if self.plant not in PLANTS:
error_msg = f'Unknown plant {self.plant!r}. Use one of {", ".join(PLANTS)}.'
raise ParameterError(error_msg)
if not self.interval > 0:
error_msg = f'The interval of the samples is {self.interval!r}. Give a positive number.'
raise ParameterError(error_msg)
start = float(BangBangPlantInteraction._get_control(self.plant, self.x, self.v))
sample = {'u': lambda s: BangBangPlantInteraction._get_control(self.plant, s.target.x, s.target.x.diff(s.t))}
self.system_ = System(
self.label,
elements=[BangBangPlantElement('plant', x=self.x, u=start, values={"x'": self.v})],
interactions=[
BangBangPlantInteraction('motion', target='plant', a=PLANTS[self.plant]),
PulseInteraction('sample', target='plant', reset=sample, period=self.interval, start=self.interval),
],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
BangBangPlantElement, fromElement
Interactions:
BangBangPlantInteraction, fromInteractionPulseInteraction, fromInteraction
class BangBangPlantElement(Element):
"""Second-order linear plant at the position `x` with the held control `u`.
Its velocity is the derivative `x'`, and `BangBangPlantInteraction` moves it.
Args:
label:
The label of the plant.
x:
The initial position.
u:
The initial control, -1 or 1.
values:
Further values by name, such as the initial velocity `"x'"`.
Examples:
>>> from skcomplex.systems.engineering.control import BangBangPlantElement
>>> BangBangPlantElement('plant', u=-1.0).u
-1.0
"""
def __init__(
self,
label: str,
*,
x: float = 0.0,
u: Annotated[float, FiniteEnumeratedSet([-1, 1])] = 1.0,
values: Mapping[str, object] | None = None,
) -> None:
super().__init__(label, values=values)
self.x = x
self.u = u
class BangBangPlantInteraction(Interaction):
"""Motion of a second-order linear plant under a bang-bang control.
The control is held between samples, and it steers the plant to the origin. The plant follows `x'' = a x + u` with
the control `u` of size 1, `a = 0` for a free particle, `a = -1` for a harmonic oscillator, and `a = 1` for a
saddle. The control stays constant between samples, and at every sample takes `-1` above the switching curve
`x' = g(x)` of the plant and `1` below it. The curve is made of the two trajectories of the plant under `u = 1` and
`u = -1` that reach the origin: `g(x) = -sign(x) sqrt(2 |x|)` for the free particle, the half circles
`g(x) = sqrt(1 - (x + 1)^2)` on `[-2, 0]` and `-sqrt(1 - (x - 1)^2)` on `[0, 2]`, and 0 outside, for the harmonic
oscillator, and `g(x) = sqrt(x^2 - 2 x)` for `x <= 0` and `-sqrt(x^2 + 2 x)` for `x >= 0` for the saddle.
Args:
label:
The label of the interaction.
target:
The path of the plant.
a:
The coefficient of the position in the acceleration, 0, -1, or 1.
Examples:
>>> from skcomplex.systems.engineering.control import BangBangPlantInteraction
>>> BangBangPlantInteraction('motion', target='plant', a=-1.0).a
-1.0
"""
law_classes = (RateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
a: Annotated[float, FiniteEnumeratedSet([-1, 0, 1])] = 0.0,
) -> None:
super().__init__(label)
self.target = target
self.a = a
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the motion of the plant under the held control.
Args:
context:
The namespace of the plant, the time `t`, and the parameters.
"""
super()._prepare(context)
plant, t = context.target, context.t
self.laws_: list[BaseLaw] = [RateLaw(plant.x.diff(t, 2), context.a * plant.x + plant.u)]
@staticmethod
def _get_switching_curve(plant: str, x: Expression) -> Expression:
"""Return the velocity `g(x)` of the switching curve of a plant at a position.
Args:
plant:
The plant, `'free_particle'`, `'harmonic_oscillator'`, or `'saddle'`.
x:
The position, a number or a symbol.
Returns:
velocity:
The velocity of the switching curve.
Raises:
ParameterError:
The plant is unknown.
"""
if plant == 'free_particle':
curve: Expression = -sign(x) * sqrt(2 * abs_symbolic(x))
elif plant == 'harmonic_oscillator':
left = sqrt(abs_symbolic(1 - (x + 1) ** 2))
right = -sqrt(abs_symbolic(1 - (x - 1) ** 2))
curve = where(abs_symbolic(x) > CIRCLES_END, 0, where(x < 0, left, right))
elif plant == 'saddle':
curve = where(x <= 0, sqrt(abs_symbolic(x**2 - 2 * x)), -sqrt(abs_symbolic(x**2 + 2 * x)))
else:
error_msg = f'Unknown plant {plant!r}. Use one of {", ".join(PLANTS)}.'
raise ParameterError(error_msg)
return curve
@staticmethod
def _get_control(plant: str, x: Expression, y: Expression) -> Expression:
"""Return the bang-bang control of a plant.
It is -1 above its switching curve and 1 below it.
Args:
plant:
The plant, `'free_particle'`, `'harmonic_oscillator'`, or `'saddle'`.
x:
The position.
y:
The velocity.
Returns:
control:
The control.
"""
control: Expression = where(y > BangBangPlantInteraction._get_switching_curve(plant, x), -1, 1)
return control
class PulseInteraction(Interaction):
"""Pulses that set states of the target to new values at given or periodic times.
Engineering names them pulses or impulses, as the kicks of a sampled controller or of a pulsed circuit. The pulses
fall at every time of `times` and, with a `period`, at `start + j * period` for `j` from 0, `count` times or without
end. A pulse at the initial time of a run does not fire. The new values are functions of the namespace, which holds
`namespace.target`, the states and parameters of the target, and the time `namespace.t`. A name with primes sets a
derivative, so `{"x'": lambda s: s.target.x.diff(s.t) + 1.0}` kicks the rate of `x`. A pulse sets the states of
every member of a group at once, and the trajectory records every pulse among its events, under the label of the
interaction.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the element or group whose states the pulses set.
reset:
A mapping from the name of a state of the target, or of its derivative such as `"x'"`, to the function
`f(namespace)` of its new value.
times:
The times of the pulses.
period:
The period of the periodic pulses, or `None` for none.
start:
The time of the first periodic pulse.
count:
The number of periodic pulses, or `None` for pulses without end.
Raises:
ValidationError:
The pulses set no state, a new value is not a function, the pulses have no time, the period is not
positive, or the count is not a positive integer.
Examples:
>>> from skcomplex.systems.engineering.common.signals import PulseInteraction
>>> reset = {'c': lambda s: s.target.c + 1.0}
>>> dose = PulseInteraction('dose', target='body', reset=reset, period=8.0, count=3)
>>> dose.start
0.0
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (EventLaw,)
def __init__(
self,
label: str,
*,
target: Role,
reset: Mapping[str, Callable[[SimpleNamespace], object]],
times: Sequence[float] = (),
period: float | None = None,
start: float = 0.0,
count: int | None = None,
) -> None:
super().__init__(label)
self.target = target
self.reset = reset
self.times = times
self.period = period
self.start = start
self.count = count
def _check_pulses(self) -> None:
"""Raise an error for pulses without states or times, or a bad period or count.
Raises:
ValidationError:
The pulses set no state, a new value is not a function, the pulses have no time, the period is not
positive, or the count is not a positive integer.
"""
if not self.reset or not all(callable(function) for function in self.reset.values()):
error_msg = f'The pulses {self.label!r} set {self.reset!r}. Map state names to functions of the namespace.'
raise ValidationError(error_msg)
if not self.times and self.period is None:
error_msg = f'The pulses {self.label!r} have no time. Give `times`, or a `period`.'
raise ValidationError(error_msg)
if self.period is not None and not self.period > 0:
error_msg = f'The period of the pulses {self.label!r} is {self.period!r}. Give a positive number.'
raise ValidationError(error_msg)
if self.count is not None and (
isinstance(self.count, bool) or not isinstance(self.count, int) or self.count < 1
):
error_msg = f'The count of the pulses {self.label!r} is {self.count!r}. Give a positive integer, or None.'
raise ValidationError(error_msg)
@staticmethod
def _get_reset_state(context: SimpleNamespace, name: str) -> object:
"""Return the state a name of `reset` sets, or its derivative for a name with primes, such as `"x'"`."""
base = name.rstrip("'")
state = getattr(context.target, base)
order = len(name) - len(base)
return state.diff(context.t, order) if order else state
def _check_arguments(self) -> None:
"""Raise an error for an argument the interaction cannot take.
Raises:
ValidationError:
The pulses set no state, a new value is not a function, the pulses have no time, the period is not
positive, or the count is not a positive integer.
"""
super()._check_arguments()
self._check_pulses()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set one event law per given time and one for the periodic pulses.
Args:
context:
The namespace of the target and the time.
"""
super()._prepare(context)
reset = {self._get_reset_state(context, name): SR(f(context)) for name, f in self.reset.items()}
laws: list[BaseLaw] = [EventLaw(context.t - time, reset, 1, label=self.label) for time in self.times]
if self.period is not None:
guard = periodic_guard(context.t, self.period, self.start, self.count)
laws.append(EventLaw(guard, reset, 0, False, label=self.label))
self.laws_ = laws
Equations
The equations are those that symbolic returns for the system with its default parameters.
plant.x: diff(x_plant(t), t, t) == a_motion*x_plant(t) + u_plant(t)
plant.u: diff(u_plant(t), t) == 0