Skip to content

Spring chains and guitar string

Masses joined in a row by springs of zero rest length between two anchors.

  • Class: SpringChainSystem
  • Import: from skcomplex.systems.physics.waves import SpringChainSystem
  • Field: physics/waves
  • Topics: waves, ode, springs, normal modes, mechanics
  • References:
    • Argun et al. 2021

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.physics.waves import SpringChainSystem

trajectory = SpringChainSystem().prepare().simulate()

Parameters

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

Parameter Default
n_masses 15
length 1.0
k 1.0
mass 0.01
pluck 0.05
pluck_at 0.5
amplitude 0.0
omega 2.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 continuous
Laws rate
Randomness deterministic
Domains vector
Structure fixed

Class

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

class SpringChainSystem(BaseSystem):
    """Masses joined in a row by springs of zero rest length between two anchors.

    The chain is a discrete string.

    The masses start evenly spaced between the anchors at `0` and `length`, stretched, so the chain carries tension.
    With `pluck`, the masses start on a triangle of that height peaking at the fraction `pluck_at` of the length, the
    pluck of a guitar string. With `amplitude`, the left anchor moves transversally as `amplitude sin(omega t)` and
    sends a transverse wave along the chain. Springs of zero rest length are linear, so the transverse modes are
    independent, with frequencies `2 sqrt(k / m) sin(n pi / (2 (N + 1)))`. The system has the masses `mass_<i>` and
    their positions `mass_<i>.x` in two dimensions.

    Args:
        n_masses:
            The number of masses between the anchors.

        length:
            The distance between the anchors.

        k:
            The stiffness of every spring.

        mass:
            The mass of every mass.

        pluck:
            The initial transverse displacement of the plucked point.

        pluck_at:
            The plucked point, as a fraction of the length.

        amplitude:
            The amplitude of the transverse motion of the left anchor.

        omega:
            The angular frequency of the left anchor.

        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 velocity Verlet with the step 0.01.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.physics.waves import SpringChainSystem
        >>> len(SpringChainSystem(4).prepare().system_.interactions)
        5
    """

    field = 'physics/waves'
    topics = ('waves', 'ode', 'springs', 'normal modes', 'mechanics')
    references = ('Argun et al. 2021',)
    until = 20.0
    dt = 0.05

    def __init__(
        self,
        n_masses: int = 15,
        *,
        length: float = 1.0,
        k: float = 1.0,
        mass: float = 0.01,
        pluck: float = 0.05,
        pluck_at: float = 0.5,
        amplitude: float = 0.0,
        omega: float = 2.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_masses = n_masses
        self.length = length
        self.k = k
        self.mass = mass
        self.pluck = pluck
        self.pluck_at = pluck_at
        self.amplitude = amplitude
        self.omega = omega

    @staticmethod
    def _pluck(positions: np.ndarray, length: float, height: float, at: float) -> np.ndarray:
        """Return the triangular shape of a plucked string.

        The string is pulled to a height at a fraction of its length.
        """
        peak = at * length
        return np.where(positions <= peak, height * positions / peak, height * (length - positions) / (length - peak))

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to masses joined in a row by springs of zero rest length between two anchors.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        spacing = self.length / (self.n_masses + 1)
        positions = spacing * np.arange(1, self.n_masses + 1)
        heights = (
            self._pluck(positions, self.length, self.pluck, self.pluck_at) if self.pluck else np.zeros(self.n_masses)
        )
        masses = [
            MassPointElement(
                f'mass_{index}',
                x=[float(positions[index]), float(heights[index])],
                m=self.mass,
            )
            for index in range(self.n_masses)
        ]
        springs = [
            SpringInteraction(f'spring_{index}', first=f'mass_{index}', second=f'mass_{index + 1}', k=self.k)
            for index in range(self.n_masses - 1)
        ]
        anchors = [
            DrivenAnchorInteraction(
                'left_end',
                target='mass_0',
                k=self.k,
                center=[0.0, 0.0],
                amplitude=self.amplitude,
                omega=self.omega,
            ),
            DrivenAnchorInteraction(
                'right_end',
                target=f'mass_{self.n_masses - 1}',
                k=self.k,
                center=[self.length, 0.0],
            ),
        ]
        self.system_ = System(
            self.label,
            elements=masses,
            interactions=[*anchors, *springs],
            space=ContinuousSpace(n_dim=2),
            solver=VelocityVerletSolver(dt=0.01),
        )

Components

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

Elements:

Interactions:

class MassPointElement(PointElement):
    """Point mass, a point at the position `x` with the mass `m`.

    The forces on the point give the acceleration `x''` of its position divided by its mass, and its velocity is the
    value `x'`. It is an atom of a gas, a bead of a polymer, or a star of a cluster.

    Args:
        label:
            The label of the point.

        x:
            The initial position. A number applies to every component.

        m:
            The mass.

        values:
            Further values by name, such as the starting velocity `"x'"`.

        size:
            The number of points, or `None` for one.

        space:
            The space whose sites hold one point each, or `None`.

    Examples:
        >>> from skcomplex.systems.physics.common.particles import MassPointElement
        >>> MassPointElement('ball', x=[0.0, 1.0], m=2.0, values={"x'": [1.0, 0.0]}).m
        2.0
    """

    def __init__(
        self,
        label: str,
        x: npt.ArrayLike = 0.0,
        *,
        m: Annotated[float, RealSet.open(0, oo)] = 1.0,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, x=x, values=values, size=size, space=space)
        self.m = m

class DrivenAnchorInteraction(HarmonicPotentialInteraction):
    """Spring that ties a particle to an anchor point.

    The anchor oscillates transversally as `amplitude sin(omega t)`.

    The energy is `k |x - center - (0, amplitude sin(omega t))|² / 2`, and a zero amplitude gives a fixed anchor.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the particle.

        k:
            The stiffness of the spring.

        center:
            The rest position of the anchor.

        amplitude:
            The amplitude of the transverse motion of the anchor.

        omega:
            The angular frequency of the anchor.

    Examples:
        >>> from skcomplex.systems.physics.waves import DrivenAnchorInteraction
        >>> DrivenAnchorInteraction('end', target='mass_0', center=[0.0, 0.0], amplitude=0.1).amplitude
        0.1
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        k: Annotated[float, RealSet.open(0, oo)] = 1.0,
        center: npt.ArrayLike = 0.0,
        amplitude: float = 0.0,
        omega: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label, target=target, k=k, center=center)
        self.amplitude = amplitude
        self.omega = omega

    def _get_center(self, s: SimpleNamespace) -> Expression:
        """Return the position `center + (0, amplitude sin(omega t))` of the anchor."""
        return s.center + vector(SR, [0, s.amplitude * sin(s.omega * s.t)])

class SpringInteraction(PotentialEnergyInteraction):
    """Spring between two particles.

    The energy is `k * (|x_first - x_second| - length)**2 / 2`, and its gradient moves both particles.

    Args:
        label:
            The label of the interaction.

        first:
            The path of the first particle.

        second:
            The path of the second particle.

        k:
            The stiffness.

        length:
            The rest length.

        states:
            The name of the vector state that holds the positions of the particles.


    Examples:
        >>> from skcomplex.systems.physics.waves import SpringInteraction
        >>> SpringInteraction('spring', first='a', second='b', k=3.0, length=1.0).length
        1.0
    """

    def __init__(
        self,
        label: str,
        *,
        first: Role,
        second: Role,
        k: Annotated[float, RealSet.open(0, oo)] = 1.0,
        length: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        states: str = 'x',
    ) -> None:
        super().__init__(label, target=first, states=states)
        self.first = first
        self.second = second
        self.k = k
        self.length = length

    def _get_potential(self, s: SimpleNamespace) -> Expression:
        """Return `k * (|x_first - x_second| - length)**2 / 2`.

        Args:
            s:
                The namespace of the symbols the energy can use.

        Returns:
            energy:
                The potential energy as a symbolic expression.
        """
        gap = getattr(s.first, self._get_names()[0]) - getattr(s.second, self._get_names()[0])
        return s.k * (sqrt(gap.dot_product(gap)) - s.length) ** 2 / 2