Skip to content

Pendulum on a sliding cart

A pendulum hanging from a cart.

  • Class: CartPendulumSystem
  • Import: from skcomplex.systems.physics.mechanics import CartPendulumSystem
  • Field: physics/mechanics
  • Topics: mechanics, ode, second order, lagrangian, momentum
  • References:
    • Ryzhov 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.mechanics import CartPendulumSystem

trajectory = CartPendulumSystem().prepare().simulate()

Parameters

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

Parameter Default
theta 0.5
y 0.0
m1 1.0
m2 1.0
l 1.0
g 9.81
F 0.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 CartPendulumSystem(systems.BaseSystem):
    """A pendulum hanging from a cart.

    The cart slides without friction along a horizontal track.

    The Lagrange equations `(m1 + m2) y'' + m2 l (θ'' cos θ - θ'² sin θ) = F` and `l θ'' + y'' cos θ + g sin θ = 0`
    couple the position `y` of the cart and the angle `θ` of the pendulum. Without a force the horizontal momentum is
    conserved, so the cart swings against the pendulum. The system has the cart position `cart.y` and the angle
    `cart.theta`, and their velocities `cart.y'` and `cart.theta'`.

    Args:
        theta:
            The initial angle of the pendulum.

        y:
            The initial position of the cart.

        m1:
            The mass of the cart.

        m2:
            The mass of the bob.

        l:
            The length of the rod.

        g:
            The gravitational acceleration.

        F:
            A constant horizontal force on the cart.

        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.physics.mechanics import CartPendulumSystem
        >>> CartPendulumSystem(m1=5.0).prepare().system_.elements[0].m1
        5.0
    """

    field = 'physics/mechanics'
    topics = ('mechanics', 'ode', 'second order', 'lagrangian', 'momentum')
    references = ('Ryzhov et al. 2021',)
    until = 10.0
    dt = 0.02

    def __init__(
        self,
        theta: float = 0.5,
        y: float = 0.0,
        *,
        m1: float = 1.0,
        m2: float = 1.0,
        l: float = 1.0,
        g: float = 9.81,
        F: float = 0.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.theta = theta
        self.y = y
        self.m1 = m1
        self.m2 = m2
        self.l = l
        self.g = g
        self.F = F

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a pendulum hanging from a cart that slides along a horizontal track.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        cart = CartPendulumElement('cart', y=self.y, theta=self.theta, m1=self.m1, m2=self.m2, l=self.l, g=self.g)
        motion = CartPendulumInteraction('motion', target='cart', F=self.F)
        self.system_ = systems.System(self.label, elements=[cart], interactions=[motion])

Components

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

Elements:

  • CartPendulumElement, from Element

Interactions:

  • CartPendulumInteraction, from Interaction
class CartPendulumElement(Element):
    """Cart on a horizontal track at the position `y`.

    A pendulum of angle `theta` hangs from the cart.

    The position `y` and the angle `theta` are the coordinates of `CartPendulumInteraction`, and their velocities are
    `y'` and `theta'`.

    Args:
        label:
            The label of the cart and pendulum.

        y:
            The initial position of the cart.

        theta:
            The initial angle of the pendulum.

        m1:
            The mass of the cart.

        m2:
            The mass of the bob.

        l:
            The length of the rod.

        g:
            The gravitational acceleration.

    Examples:
        >>> from skcomplex.systems.physics.mechanics import CartPendulumElement
        >>> CartPendulumElement('cart', m1=5.0).m1
        5.0
    """

    visual = VisualSpec('bodies', {'positions': _get_cart_and_bob, 'rods': True, 'traced': [1]})

    def __init__(
        self,
        label: str,
        *,
        y: float = 0.0,
        theta: Annotated[float, Period(2 * math.pi)] = 0.5,
        m1: Annotated[float, RealSet.open(0, oo)] = 1.0,
        m2: Annotated[float, RealSet.open(0, oo)] = 1.0,
        l: Annotated[float, RealSet.open(0, oo)] = 1.0,
        g: Annotated[float, RealSet.open(0, oo)] = 9.81,
    ) -> None:
        super().__init__(label)
        self.y = y
        self.theta = theta
        self.m1 = m1
        self.m2 = m2
        self.l = l
        self.g = g

class CartPendulumInteraction(LagrangianInteraction):
    """Motion of a cart and the pendulum that hangs from it.

    The motion is the Euler-Lagrange equations with a force on the cart.

    The Lagrangian is `(m1 + m2) y'² / 2 + m2 l y' θ' cos θ + m2 l² θ'² / 2 + m2 g l cos θ`, and the force `F` drives
    the position `y` of the cart.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the cart and pendulum.

        F:
            A constant horizontal force on the cart.

    Examples:
        >>> from skcomplex.systems.physics.mechanics import CartPendulumInteraction
        >>> CartPendulumInteraction('motion', target='cart', F=1.0).F
        1.0
    """

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

    def _get_coordinates(self, context: SimpleNamespace) -> list[Expression]:
        """Return the position of the cart and the angle of the pendulum."""
        return [context.target.y, context.target.theta]

    def _get_forces(
        self,
        context: SimpleNamespace,
        positions: list[Expression],
        velocities: list[Expression],
    ) -> list[Expression]:
        """Return the generalized forces, the force `F` on the cart and none on the angle."""
        return [context.F, 0]

    def _get_lagrangian(
        self,
        context: SimpleNamespace,
        positions: list[Expression],
        velocities: list[Expression],
    ) -> Expression:
        """Return the Lagrangian of the cart and pendulum.

        Args:
            context:
                The namespace of the cart, the time `t`, and the force.

            positions:
                The symbols of the position and the angle.

            velocities:
                The symbols of the velocity and the angular velocity.

        Returns:
            lagrangian:
                The Lagrangian.
        """
        p = context.target
        theta = positions[1]
        v, w = velocities
        kinetic = (p.m1 + p.m2) * v**2 / 2 + p.m2 * p.l * v * w * cos(theta) + p.m2 * p.l**2 * w**2 / 2
        return kinetic + p.m2 * p.g * p.l * cos(theta)

Equations

The equations are those that symbolic returns for the system with its default parameters.

cart.y: diff(y_cart(t), t, t) == -(g_cart*l_cart*m2_cart*sin(theta_cart(t)) + (l_cart*m2_cart*sin(theta_cart(t))*diff(theta_cart(t), t)^2 + F_motion)*l_cart*m2_cart*cos(theta_cart(t))/(m1_cart + m2_cart))*l_cart*m2_cart*cos(theta_cart(t))/((l_cart^2*m2_cart^2*cos(theta_cart(t))^2/(m1_cart + m2_cart) - l_cart^2*m2_cart)*(m1_cart + m2_cart)) + (l_cart*m2_cart*sin(theta_cart(t))*diff(theta_cart(t), t)^2 + F_motion)/(m1_cart + m2_cart)
cart.theta: diff(theta_cart(t), t, t) == (g_cart*l_cart*m2_cart*sin(theta_cart(t)) + (l_cart*m2_cart*sin(theta_cart(t))*diff(theta_cart(t), t)^2 + F_motion)*l_cart*m2_cart*cos(theta_cart(t))/(m1_cart + m2_cart))/(l_cart^2*m2_cart^2*cos(theta_cart(t))^2/(m1_cart + m2_cart) - l_cart^2*m2_cart)