Skip to content

Magnetic levitation under alternating impulses

A conductive ball levitated in a vacuum by a field.

  • Class: MagneticLevitationSystem
  • Import: from skcomplex.systems.engineering.mechatronics import MagneticLevitationSystem
  • Field: engineering/mechatronics
  • Topics: mechatronics, levitation, impulses, events, ode
  • References:
    • Pilipchuk 2010
    • 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.mechatronics import MagneticLevitationSystem

trajectory = MagneticLevitationSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
v None
b 1.0
m 0.2
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 real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class MagneticLevitationSystem(BaseSystem):
    """A conductive ball levitated in a vacuum by a field.

    The field pushes and pulls it with alternating impulses. The velocity follows
    `v' + b v = m Σ_k [δ(t + 1 - 4 k) - δ(t - 1 - 4 k)]`: it relaxes freely, rises by `m` at the times `4 k - 1`, and
    falls by `m` at the times `4 k + 1`. Its periodic solution, with the triangular wave
    `τ(t) = (2 / π) arcsin(sin(π t / 2))` and the rectangular wave `e(t) = sign(cos(π t / 2))`, is
    `v = m / (2 cosh b) exp(-b τ(t) e(t)) e(t)`, which the ball follows from the start when it starts at
    `m / (2 cosh b)`. The system has the velocity `ball.v`, raised by the impulses `push` and lowered by the impulses
    `pull`.

    Args:
        v:
            The initial velocity, or `None` for the value `m / (2 cosh b)` of the periodic solution at time 0.

        b:
            The damping rate.

        m:
            The strength of every impulse.

        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.mechatronics import MagneticLevitationSystem
        >>> round(MagneticLevitationSystem(b=1.0, m=0.2).prepare().system_.elements[0].v, 4)
        0.0648
    """

    field = 'engineering/mechatronics'
    topics = ('mechatronics', 'levitation', 'impulses', 'events', 'ode')
    references = ('Pilipchuk 2010', 'Trzaska 2023')
    until = 20.0
    dt = 0.01

    def __init__(
        self,
        v: float | None = None,
        *,
        b: float = 1.0,
        m: float = 0.2,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.v = v
        self.b = b
        self.m = m

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_`, the ball, its damping, and the impulses that push and pull it."""
        super()._prepare(context)
        start = self.m / (2 * math.cosh(self.b)) if self.v is None else self.v
        push = {'v': lambda s: s.target.v + self.m}
        pull = {'v': lambda s: s.target.v - self.m}
        self.system_ = System(
            self.label,
            elements=[LevitatedBallElement('ball', v=start)],
            interactions=[
                DampingInteraction('damping', target='ball', b=self.b),
                PulseInteraction('push', target='ball', reset=push, period=IMPULSE_PERIOD, start=3.0),
                PulseInteraction('pull', target='ball', reset=pull, period=IMPULSE_PERIOD, start=1.0),
            ],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • LevitatedBallElement, from Element

Interactions:

  • DampingInteraction, from Interaction
  • PulseInteraction, from Interaction
class LevitatedBallElement(Element):
    """Conductive ball levitated in a vacuum, with the velocity `v`.

    The damping and the impulses of `MagneticLevitationSystem` change the velocity.

    Args:
        label:
            The label of the ball.

        v:
            The initial velocity.

    Examples:
        >>> from skcomplex.systems.engineering.mechatronics import LevitatedBallElement
        >>> LevitatedBallElement('ball', v=0.1).v
        0.1
    """

    def __init__(self, label: str, *, v: float = 0.0) -> None:
        super().__init__(label)
        self.v = v

class DampingInteraction(Interaction):
    """Damping that relaxes the velocity of the target at the rate `b`, as `v' = -b v`.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the element whose velocity relaxes.

        b:
            The damping rate.

    Examples:
        >>> from skcomplex.systems.engineering.mechatronics import DampingInteraction
        >>> DampingInteraction('damping', target='ball').b
        1.0
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        b: Annotated[float, RealSet.open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.b = b

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the relaxation of the velocity.

        Args:
            context:
                The namespace of the target.
        """
        super()._prepare(context)
        v = context.target.v
        self.laws_: list[BaseLaw] = [RateLaw(v.diff(context.t), -context.b * v)]

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.

ball.v: diff(v_ball(t), t) == -b_damping*v_ball(t)