Skip to content

DC motor with an inertia

A DC motor whose armature circuit drives an inertia.

  • Class: DcMotorSystem
  • Import: from skcomplex.systems.engineering.mechatronics import DcMotorSystem
  • Field: engineering/mechatronics
  • Topics: mechatronics, circuit, acausal components, euler-lagrange, ode
  • References:
    • Fritzson 2015

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 DcMotorSystem

trajectory = DcMotorSystem().prepare().simulate()

Parameters

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

Parameter Default
V 12.0
R 1.0
L 0.5
k 0.5
J 0.1
b 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, static
Space none
Laws equation
Randomness deterministic
Domains real
Structure fixed

Class

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

class DcMotorSystem(BaseSystem):
    """A DC motor whose armature circuit drives an inertia.

    The armature circuit is made of components and the inertia is on a Lagrangian coordinate. A voltage source drives a
    resistor, an inductor, and the armature in series. The armature has the voltage `k phi'`, and its current exerts the
    torque `k i` on the angle of an inertia with viscous friction, so the angular velocity settles at
    `k V / (R b + k^2)`. The system has the angle `rotor.phi`, the angular velocity `rotor.phi'`, and the current
    `winding.i`.

    Args:
        V:
            The voltage of the source.

        R:
            The resistance of the armature circuit.

        L:
            The inductance of the armature circuit.

        k:
            The motor constant.

        J:
            The moment of inertia of the rotor.

        b:
            The coefficient of viscous friction of the rotor.

        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 DcMotorSystem
        >>> DcMotorSystem(k=0.3).prepare().system_.interactions[-1].k
        0.3
    """

    field = 'engineering/mechatronics'
    topics = ('mechatronics', 'circuit', 'acausal components', 'euler-lagrange', 'ode')
    references = ('Fritzson 2015',)
    until = 10.0
    dt = 0.01
    observables = (
        Observable('speed', _get_speed_of_rotor),
        Observable('current', _get_current_of_winding),
    )

    def __init__(
        self,
        V: float = 12.0,
        *,
        R: float = 1.0,
        L: float = 0.5,
        k: float = 0.5,
        J: float = 0.1,
        b: 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.R = R
        self.L = L
        self.k = k
        self.J = J
        self.b = b

    @staticmethod
    def _get_rotor_lagrangian(s: SimpleNamespace) -> Expression:
        """Return the kinetic energy of the rotor."""
        energy: Expression = s.target.J * s.target.phi.diff(s.t) ** 2 / 2
        return energy

    @staticmethod
    def _get_rotor_dissipation(s: SimpleNamespace) -> Expression:
        """Return the Rayleigh dissipation of the viscous friction of the rotor."""
        dissipation: Expression = s.target.b * s.target.phi.diff(s.t) ** 2 / 2
        return dissipation

    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)
        self.system_ = System(
            self.label,
            elements=[
                *[Element(name, values={'v': 0.0}) for name in ('supply', 'middle', 'terminal', 'neutral')],
                *[Element(name, values={'i': 0.0}) for name in ('source', 'coil', 'winding', 'earth')],
                InertiaElement('rotor', J=self.J, b=self.b),
            ],
            interactions=[
                VoltageSourceInteraction('mains', a='supply', b='neutral', branch='source', V=self.V),
                ResistorInteraction('resistor', a='supply', b='middle', R=self.R),
                InductorInteraction('inductor', a='middle', b='terminal', branch='coil', L=self.L),
                GroundInteraction('ground', node='neutral', branch='earth'),
                EulerLagrangeInteraction(
                    'rotation',
                    target='rotor',
                    states='phi',
                    lagrangian=self._get_rotor_lagrangian,
                    dissipation=self._get_rotor_dissipation,
                ),
                MotorCouplingInteraction(
                    'motor',
                    a='terminal',
                    b='neutral',
                    winding='winding',
                    rotor='rotor',
                    k=self.k,
                ),
            ],
        )

Components

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

Elements:

Interactions:

  • VoltageSourceInteraction, from Interaction
  • ResistorInteraction, from Interaction
  • InductorInteraction, from Interaction
  • GroundInteraction, from Interaction
  • EulerLagrangeInteraction, from Interaction, through the shared recipe EulerLagrangeInteraction
  • MotorCouplingInteraction, from Interaction
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 InertiaElement(Element):
    """Rotating inertia of the angle `phi`, a coordinate of a Lagrangian.

    Args:
        label:
            The label of the element, unique among the components of its system.

        phi:
            The initial angle, whose derivative `phi'` is the angular velocity.

        J:
            The moment of inertia.

        b:
            The coefficient of viscous friction.

    Examples:
        >>> from skcomplex.systems.engineering.mechatronics import InertiaElement
        >>> InertiaElement('rotor', J=0.5).J
        0.5
    """

    def __init__(
        self,
        label: str,
        *,
        phi: object = 0.0,
        J: Annotated[object, POSITIVE] = 1.0,
        b: Annotated[object, POSITIVE] = 1.0,
    ) -> None:
        super().__init__(label)
        self.phi = phi
        self.J = J
        self.b = b

class VoltageSourceInteraction(BranchInteraction):
    """Ideal source that holds the node `a` at the voltage `V` above the node `b`.

    Its current `i`, from `a` through the source to `b`, lives on the element `branch`.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the positive node.

        b:
            The path of the negative node.

        branch:
            The path of the element that holds the current `i` of the source.

        V:
            The voltage.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import VoltageSourceInteraction
        >>> VoltageSourceInteraction('battery', a='plus', b='minus', branch='cell', V=9.0).V
        9.0
    """

    def __init__(self, label: str, *, a: Role, b: Role, branch: Role, V: float = 1.0) -> None:
        super().__init__(label, a=a, b=b)
        self.branch = branch
        self.V = V

    def _get_branch_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the voltage of the source as the equation of its current, and the current into both balances."""
        i = s.branch.i
        return [
            ConstraintLaw(s.a.v - s.b.v, s.V, target=i),
            ConstraintLaw(-i, 0, target=s.a.v),
            ConstraintLaw(i, 0, target=s.b.v),
        ]

class ResistorInteraction(BranchInteraction):
    """Resistor that obeys Ohm's law, with the current `(a.v - b.v) / R`.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the node the current leaves.

        b:
            The path of the node the current enters.

        R:
            The resistance.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import ResistorInteraction
        >>> ResistorInteraction('load', a='top', b='bottom', R=2.0).R
        2.0
    """

    def __init__(self, label: str, *, a: Role, b: Role, R: Annotated[float, POSITIVE] = 1.0) -> None:
        super().__init__(label, a=a, b=b)
        self.R = R

    def _get_current(self, s: SimpleNamespace) -> Expression:
        """Return the current of Ohm's law."""
        current: Expression = (s.a.v - s.b.v) / s.R
        return current

class InductorInteraction(BranchInteraction):
    """Inductor whose current `i` lives on the element `branch`, with `L i' = a.v - b.v`.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the node the current leaves.

        b:
            The path of the node the current enters.

        branch:
            The path of the element that holds the current `i` of the inductor.

        L:
            The inductance.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import InductorInteraction
        >>> InductorInteraction('coil', a='top', b='bottom', branch='coil', L=0.5).L
        0.5
    """

    def __init__(
        self,
        label: str,
        *,
        a: Role,
        b: Role,
        branch: Role,
        L: Annotated[float, POSITIVE] = 1.0,
    ) -> None:
        super().__init__(label, a=a, b=b)
        self.branch = branch
        self.L = L

    def _get_branch_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the voltage of the inductor and its current into the balances of both nodes."""
        i = s.branch.i
        return [
            ConstraintLaw(s.L * i.diff(s.t), s.a.v - s.b.v, target=i),
            ConstraintLaw(-i, 0, target=s.a.v),
            ConstraintLaw(i, 0, target=s.b.v),
        ]

class GroundInteraction(Interaction):
    """Reference that holds the potential of a node at zero.

    The current that the ground feeds into the node, `i` of the element `branch`, balances the node.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        node:
            The path of the node held at zero potential.

        branch:
            The path of the element that holds the current `i` from the ground into the node.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import GroundInteraction
        >>> GroundInteraction('ground', node='bottom', branch='earth').node
        'bottom'
    """

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

    def __init__(self, label: str, *, node: Role, branch: Role) -> None:
        super().__init__(label)
        self.node = node
        self.branch = branch

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the zero potential as the equation of the current, and the current into the balance of the node.

        Args:
            context:
                The namespace of the node and the branch.
        """
        super()._prepare(context)
        i = context.branch.i
        self.laws_: list[BaseLaw] = [
            ConstraintLaw(context.node.v, 0, target=i),
            ConstraintLaw(i, 0, target=context.node.v),
        ]

class EulerLagrangeInteraction(Interaction):
    """An interaction that moves coordinates by the equations of a Lagrangian.

    A Lagrangian `L` is the kinetic minus the potential energy of a mechanical system. The interaction gives the
    equations of motion `d/dt dL/dq' - dL/dq = Q - dR/dq'` for the coordinates `q`, with the dissipation function `R`
    and the generalized forces `Q`. It returns one equation per coordinate, and the compiler solves them together for
    the accelerations, so a Lagrangian with a mass matrix, such as that of a double pendulum, needs no inversion by
    hand. Equations of one coordinate from several interactions add, so a spring between two
    pendulums is an interaction of its own whose Lagrangian holds only the coupling energy.

    A Lagrangian, dissipation, or forcing function takes a namespace with the roles, the time `t`, and the parameters a
    subclass declares, and writes the velocity of a coordinate `q` as `q.diff(t)`. The coordinates are the states of
    every role that binds one element or group, `target` by default, and every component of a vector state is a
    coordinate. Every other value of the roles, such as a mass or an inertia, is held fixed when the momenta change in
    time, so it stays a parameter.

    Unlike `HamiltonianInteraction`, which needs canonical momenta, it takes the energy in coordinates and velocities.
    Choose it when the energy is easier to write than the forces, as for linked bodies.

    It appears in many fields. Pendulums and linkages in mechanics, electric circuits written by their energy, and the
    joints of a robot arm follow the equations of a Lagrangian.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'pendulum'`.

        target:
            The path of the element or group whose states are the coordinates.

        states:
            The name of the state that is a coordinate, or the names of several states.

        lagrangian:
            A function of the namespace that returns the Lagrangian.

        dissipation:
            A function of the namespace that returns the Rayleigh dissipation function, or `None` for none.

        forcing:
            A function of the namespace that returns the generalized forces, or `None` for none.

    Raises:
        ValidationError:
            A state is not a name, or a function is not callable.

    Examples:
        >>> from sage.all__sagemath_symbolics import cos
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.mechanics import EulerLagrangeInteraction
        >>> swing = EulerLagrangeInteraction(
        ...     'swing',
        ...     target='bob',
        ...     states='q',
        ...     lagrangian=lambda s: s.target.q.diff(s.t) ** 2 / 2 + cos(s.target.q),
        ... )
        >>> system = System(elements=[Element('bob', values={'q': 0.1})], interactions=[swing])
        >>> trajectory = system.prepare().simulate(until=3.2, dt=0.01)
        >>> round(float(trajectory.get_values('bob.q')[-1]), 2)
        -0.1
    """

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

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        states: str | Sequence[str] = 'x',
        lagrangian: Callable[[SimpleNamespace], object] | None = None,
        dissipation: Callable[[SimpleNamespace], object] | None = None,
        forcing: Callable[[SimpleNamespace], object] | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.states = states
        self.lagrangian = lagrangian
        self.dissipation = dissipation
        self.forcing = forcing

    def _get_names(self) -> tuple[str, ...]:
        """Return the names of the states that are coordinates."""
        return (self.states,) if isinstance(self.states, str) else tuple(self.states)

    def _check_arguments(self) -> None:
        """Raise an error for a state that is not a name, or an uncallable function.

        Raises:
            ValidationError:
                The type declares states, a state is not a name, or a function is not callable.
        """
        super()._check_arguments()
        names = self._get_names()
        if not names or not all(isinstance(name, str) and name.isidentifier() for name in names):
            error_msg = f'{type(self).__name__} {self.label!r} reads the states {self.states!r}. Give names of states.'
            raise ValidationError(error_msg)
        for name in ('lagrangian', 'dissipation', 'forcing'):
            value = getattr(self, name)
            if value is not None and not callable(value):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function of the namespace.'
                raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of a binding.

        Args:
            context:
                The namespace of the elements it binds, whose Euler-Lagrange equations it sets in `laws_`.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_equations(context)

    def _get_lagrangian(self, namespace: SimpleNamespace) -> object:
        """Return the Lagrangian.

        This is the hook a subclass overrides to derive it from its parameters.
        """
        if self.lagrangian is None:
            error_msg = f'{type(self).__name__} {self.label!r} has no Lagrangian. Give a function of the namespace.'
            raise ValidationError(error_msg)
        return self.lagrangian(namespace)

    def _get_coordinates(self, namespace: SimpleNamespace) -> list[Expression]:
        """Return the coordinates.

        They are every component of the states of every role that binds one path.
        """
        coordinates = []
        for name in self._get_roles(single=True):
            for state in self._get_names():
                value = getattr(getattr(namespace, name), state)
                coordinates += list(value) if isinstance(value, FreeModuleElement) else [value]
        return coordinates

    def _get_forces(self, namespace: SimpleNamespace, count: int) -> list[Expression]:
        """Return the generalized force of every coordinate, zero without a forcing."""
        if self.forcing is None:
            return [SR(0)] * count
        forces = self.forcing(namespace)
        forces = list(forces) if isinstance(forces, FreeModuleElement | list | tuple) else [forces]
        if len(forces) != count:
            error_msg = f'The forcing of {self.label!r} returns {len(forces)} forces for {count} coordinates.'
            raise ValidationError(error_msg)
        return [SR(force) for force in forces]

    def _get_lagrangian_of(self, namespace: SimpleNamespace, velocities: Mapping[Expression, Expression]) -> Expression:
        """Return the Lagrangian in the symbols of the states and of the velocities.

        The namespace holds the states as symbols, and the velocity `q.diff(t)` of a coordinate `q` becomes the symbol
        `velocities[q]`, as the invariants analysis reads it.
        """
        time = getattr(namespace, 't', SR.var('t'))
        functions: dict[str, Expression] = {}
        functional = SimpleNamespace(
            **{
                name: self._get_functional(item, time, functions) if isinstance(item, SimpleNamespace | tuple) else item
                for name, item in vars(namespace).items()
            },
        )
        rates = {self._get_function_of(q)(time).diff(time): velocity for q, velocity in velocities.items()}
        states = {self._get_function_of(symbol)(time): symbol for symbol in functions.values()}
        return SR(self._get_lagrangian(functional)).subs(rates).subs(states)

    @staticmethod
    def _get_values(value: object) -> list[Expression]:
        """Return the values of a namespace of roles, with every component of a vector."""
        if isinstance(value, SimpleNamespace):
            return [item for member in vars(value).values() for item in EulerLagrangeInteraction._get_values(member)]
        if isinstance(value, tuple | FreeModuleElement):
            return [item for member in value for item in EulerLagrangeInteraction._get_values(member)]
        return [value] if isinstance(value, Expression) else []

    def _get_held(self, namespace: SimpleNamespace, coordinates: Sequence[Expression]) -> dict[Expression, Expression]:
        """Return a symbol for every value of the roles that is a function of time.

        The coordinates are left out. Such a value, such as the inertia `J(t)` of a rotor, is held fixed while a
        momentum changes in time.
        """
        time = SR(namespace.t)
        values = [
            item
            for name in self._get_roles(single=True)
            for item in self._get_values(getattr(namespace, name))
            if item.operator() is not None and item.operands() == [time] and item not in coordinates
        ]
        return {item: SR.var(f'_held_{index}') for index, item in enumerate(dict.fromkeys(values))}

    def _get_equations(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the Euler-Lagrange equation of every coordinate.

        The coordinates, their velocities `q.diff(t)`, and their accelerations `q.diff(t, 2)` take symbols while the
        Lagrangian is differentiated, and the equations are written back in them. The other values of the roles are
        held fixed while a momentum changes in time.
        """
        time = SR(namespace.t)
        coordinates = self._get_coordinates(namespace)
        positions = [SR.var(f'_position_{index}') for index in range(len(coordinates))]
        slots = [SR.var(f'_velocity_{index}') for index in range(len(coordinates))]
        accelerations = [SR.var(f'_acceleration_{index}') for index in range(len(coordinates))]
        rates = {q.diff(time): slot for q, slot in zip(coordinates, slots, strict=True)}
        states = dict(zip(coordinates, positions, strict=True))
        held = self._get_held(namespace, coordinates)
        released = {symbol: value for value, symbol in held.items()}

        def slotted(value: object) -> Expression:
            return SR(value).subs(rates).subs(states)

        back = {
            **{slot: q.diff(time) for q, slot in zip(coordinates, slots, strict=True)},
            **{item: q for q, item in zip(coordinates, positions, strict=True)},
            **{item: q.diff(time, 2) for q, item in zip(coordinates, accelerations, strict=True)},
        }
        lagrangian = slotted(self._get_lagrangian(namespace))
        dissipation = slotted(0 if self.dissipation is None else self.dissipation(namespace))
        forces = [slotted(force) for force in self._get_forces(namespace, len(coordinates))]
        laws: list[BaseLaw] = []
        for q, position, slot, force in zip(coordinates, positions, slots, forces, strict=True):
            momentum = lagrangian.diff(slot)
            change = momentum.subs(held).diff(time).subs(released) + sum(
                momentum.diff(other) * other_slot + momentum.diff(other_slot) * acceleration
                for other, other_slot, acceleration in zip(positions, slots, accelerations, strict=True)
            )
            lhs = (change - lagrangian.diff(position)).subs(back)
            rhs = (force - dissipation.diff(slot)).subs(back)
            laws.append(ConstraintLaw(lhs == rhs, target=q))
        return laws

class MotorCouplingInteraction(BranchInteraction):
    """Winding of a motor between the nodes `a` and `b` that drives an inertia with the motor constant `k`.

    The voltage of the winding is the back electromotive force `k phi'` of the angle `phi` of the rotor, and its current
    `i`, from `a` to `b`, exerts the torque `k i` on the angle, which adds to the Euler-Lagrange equation of the angle.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the node the current leaves.

        b:
            The path of the node the current enters.

        winding:
            The path of the element that holds the current `i` of the winding.

        rotor:
            The path of the inertia, whose angle is `phi`.

        k:
            The motor constant.

    Examples:
        >>> from skcomplex.systems.engineering.mechatronics import MotorCouplingInteraction
        >>> MotorCouplingInteraction('motor', a='terminal', b='neutral', winding='winding', rotor='rotor', k=0.5).k
        0.5
    """

    def __init__(
        self,
        label: str,
        *,
        a: Role,
        b: Role,
        winding: Role,
        rotor: Role,
        k: Annotated[float, POSITIVE] = 1.0,
    ) -> None:
        super().__init__(label, a=a, b=b)
        self.winding = winding
        self.rotor = rotor
        self.k = k

    def _get_branch_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the back electromotive force, the current into both balances, and the torque on the angle."""
        i, phi = s.winding.i, s.rotor.phi
        return [
            ConstraintLaw(s.a.v - s.b.v, s.k * phi.diff(s.t), target=i),
            ConstraintLaw(-i, 0, target=s.a.v),
            ConstraintLaw(i, 0, target=s.b.v),
            ConstraintLaw(-s.k * i, 0, target=phi),
        ]