Skip to content

Mechanics

Mechanics realizations shared by the physics packages.

The package holds the swing of a pendulum, the equations of Hamilton and Lagrange, and the Poisson brackets and Noether charges of a mechanical system.

HamiltonianInteraction(label, *, target, coordinates='q', momenta='p', hamiltonian=None)

Bases: Interaction

An interaction that moves canonical pairs by Hamilton's equations.

A Hamiltonian H is the total energy of a system as a function of its coordinates q and momenta p. The interaction gives Hamilton's equations q' = dH/dp and p' = -dH/dq, one rate per coordinate and per momentum. The coordinates and momenta are states of every role that binds one element or group, target by default, and they pair in order. The rates of one state add, so a coupling between two oscillators is an interaction of its own whose Hamiltonian holds only the coupling energy. Dissipation or forcing is a RateLaw on the momenta in an interaction of its own.

Unlike EulerLagrangeInteraction, which takes coordinates and velocities, it takes coordinates and momenta and gives first order rates, which symplectic solvers keep on the surface of constant energy. Choose it when the energy is known in canonical form and long runs must conserve it.

It appears in many fields. Planets orbit a star, atoms vibrate in a molecule, and charged particles move in a magnetic trap by Hamilton's equations.

Parameters:

Name Type Description Default
label str

The name of the interaction, unique among the components of its system, such as 'orbit'.

required
target Role

The path of the element or group whose states are the canonical pairs.

required
coordinates str | Sequence[str]

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

'q'
momenta str | Sequence[str]

The name of the state of order 1 that is the momentum of the coordinate, or the names of several states in the order of the coordinates.

'p'
hamiltonian Callable[[SimpleNamespace], object] | None

A function of the namespace that returns the Hamiltonian.

None

Raises:

Type Description
ValidationError

A state is not a name, the coordinates and the momenta differ in count, the Hamiltonian is not callable, or a coordinate and its momentum differ in size. Preparing a system raises it too when another law gives a coordinate a rate of a higher derivative.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.mechanics import HamiltonianInteraction
>>> energy = lambda s: (s.target.p**2 + s.target.q**2) / 2
>>> spring = HamiltonianInteraction('spring', target='mass', hamiltonian=energy)
>>> system = System(elements=[Element('mass', values={'q': 1.0, 'p': 0.0})], interactions=[spring]).prepare()
>>> trajectory = system.simulate(until=3.14159, dt=0.01)
>>> round(float(trajectory.get_values('mass.q')[-1]), 3)
-1.0
Source code in src/skcomplex/systems/physics/common/mechanics/_hamiltonian.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    label: str,
    *,
    target: Role,
    coordinates: str | Sequence[str] = 'q',
    momenta: str | Sequence[str] = 'p',
    hamiltonian: Callable[[SimpleNamespace], object] | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.coordinates = coordinates
    self.momenta = momenta
    self.hamiltonian = hamiltonian

LagrangianInteraction(label, *, roles=None, laws=None, among=None, along=None, within=None)

Bases: Interaction

Motion of mechanical coordinates from the Euler-Lagrange equations of a Lagrangian L.

Every coordinate q follows d/dt (dL/dq') - dL/dq + dD/dq' = Q, with the Rayleigh dissipation D and the generalized force Q. The equations are linear in the accelerations, so the interaction solves them and gives the acceleration of every coordinate. A subclass returns its coordinates from _get_coordinates, its Lagrangian from _get_lagrangian, and may return a dissipation from _get_dissipation and forces from _get_forces. It is the swing of a pendulum, the precession of a gyroscope, or the sway of a crane with its load.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required

Examples:

>>> from sage.all__sagemath_symbolics import cos
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.types import Role
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.mechanics import LagrangianInteraction
>>> class SwingInteraction(LagrangianInteraction):
...     def __init__(self, label, *, target: Role):
...         super().__init__(label)
...         self.target = target
...
...     def _get_coordinates(self, context):
...         return [context.target.q]
...
...     def _get_lagrangian(self, context, positions, velocities):
...         return velocities[0] ** 2 / 2 + cos(positions[0])
>>> bob = Element('bob', values={'q': 0.1})
>>> system = System(elements=[bob], interactions=[SwingInteraction('swing', target='bob')]).prepare()
>>> round(float(system.simulate(until=3.2, dt=0.01).get_values('bob.q')[-1]), 2)
-0.1
Source code in src/skcomplex/core/components/interactions/_interaction.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def __init__(
    self,
    label: str,
    *,
    roles: Mapping[str, object] | None = None,
    laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
    among: str | None = None,
    along: bool | str | tuple[str, int] | RandomPartition | None = None,
    within: RadiusNeighborhood | None = None,
) -> None:
    super().__init__(label)
    self.roles = roles
    self.laws = laws
    self.among = among
    self.along = along
    self.within = within

NoetherResult(invariant, remainder, charge) dataclass

A result of noether, whether a symmetry leaves a system unchanged and its conserved charge.

Parameters:

Name Type Description Default
invariant bool

Whether the Hamiltonian, or else the Lagrangian, is unchanged to first order by the symmetry.

required
remainder Expression

The first-order change of the Hamiltonian or the Lagrangian under the symmetry, zero when it is invariant.

required
charge Expression

The Noether charge of the symmetry, conserved when the symmetry leaves the system unchanged.

required

PendulumSwingInteraction(label, *, target)

Bases: LagrangianInteraction

Motion of a pendulum, the Euler-Lagrange equation of L = m l² θ'² / 2 + m g l cos θ.

The equation is Newton's law m l² θ'' = -m g l sin θ for the angle θ of the target, whose mass m, length l, and gravity g are values of the target.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the pendulum.

required

Examples:

>>> from skcomplex.systems.physics.common.mechanics import PendulumSwingInteraction
>>> PendulumSwingInteraction('swing', target='bob').target
'bob'
Source code in src/skcomplex/systems/physics/common/mechanics/_pendulum_swing.py
36
37
38
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

SymmetrySpec(label, generator) dataclass

Bases: BaseSpec

A spec of a continuous symmetry of a system.

It is the infinitesimal variation of the coordinates it moves. The generator is a function of the namespace of the system, where s.<element>.<state> is the symbol of a state, that maps the path of every coordinate it moves, such as 'body.q', to its infinitesimal variation dq, an expression for a scalar state or a vector for a vector state.

Parameters:

Name Type Description Default
label str

The label of the symmetry.

required
generator Callable[[SimpleNamespace], Mapping[str, object]]

A function of the namespace of the system that returns the variation of every coordinate it moves.

required

Raises:

Type Description
ValidationError

The label is empty, or the generator is not callable.

Examples:

>>> from sage.all__sagemath_symbolics import vector
>>> from skcomplex.systems.physics.common.mechanics import SymmetrySpec
>>> rotation = SymmetrySpec('rotation', lambda s: {'body.q': vector([-s.body.q[1], s.body.q[0]])})
>>> rotation.label
'rotation'

noether(source, symmetry, *, samples=16, random_state=None)

Return whether a symmetry leaves a mechanical system unchanged, and its Noether charge.

The Hamiltonian is the sum of those of the system's HamiltonianInteractions, and the Lagrangian the sum of those of its EulerLagrangeInteractions. The symmetry leaves the system unchanged when the first-order change of the Hamiltonian, or else of the Lagrangian, under its variation simplifies to zero, or vanishes within a tolerance at random states when simplification does not decide. The charge is sum p dq for a Hamiltonian and sum dL/dq' dq for a Lagrangian, with the variation of the velocities dq' = sum_j d(dq)/dq_j q_j'.

Parameters:

Name Type Description Default
source DataSource

The system, or a trajectory of it.

required
symmetry SymmetrySpec

The symmetry to check.

required
samples int

The number of random states of the numeric check.

16
random_state int | Generator | None

The seed or generator of the random states.

None

Returns:

Name Type Description
result NoetherResult

Whether the symmetry leaves the system unchanged, the first-order change, and the Noether charge.

Raises:

Type Description
AnalysisError

The symmetry is not a SymmetrySpec, or the system has neither a Hamiltonian nor an Euler-Lagrange interaction.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.mechanics import HamiltonianInteraction, SymmetrySpec, noether
>>> free = lambda s: s.target.p**2 / 2
>>> system = System(
...     elements=[Element('ball', values={'q': 0.0, 'p': 1.0})],
...     interactions=[HamiltonianInteraction('motion', target='ball', hamiltonian=free)],
... )
>>> result = noether(system, SymmetrySpec('translation', lambda s: {'ball.q': 1}))
>>> result.invariant, result.charge
(True, p_ball)
Source code in src/skcomplex/systems/physics/common/mechanics/_invariants.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def noether(
    source: DataSource,
    symmetry: SymmetrySpec,
    *,
    samples: int = 16,
    random_state: int | np.random.Generator | None = None,
) -> NoetherResult:
    """Return whether a symmetry leaves a mechanical system unchanged, and its Noether charge.

    The Hamiltonian is the sum of those of the system's `HamiltonianInteraction`s, and the Lagrangian the sum of those
    of its `EulerLagrangeInteraction`s. The symmetry leaves the system unchanged when the first-order change of the
    Hamiltonian, or else of the Lagrangian, under its variation simplifies to zero, or vanishes within a tolerance at
    random states when simplification does not decide. The charge is `sum p dq` for a Hamiltonian and
    `sum dL/dq' dq` for a Lagrangian, with the variation of the velocities `dq' = sum_j d(dq)/dq_j q_j'`.

    Args:
        source:
            The system, or a trajectory of it.

        symmetry:
            The symmetry to check.

        samples:
            The number of random states of the numeric check.

        random_state:
            The seed or generator of the random states.

    Returns:
        result:
            Whether the symmetry leaves the system unchanged, the first-order change, and the Noether charge.

    Raises:
        AnalysisError:
            The symmetry is not a `SymmetrySpec`, or the system has neither a Hamiltonian nor an Euler-Lagrange
            interaction.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.mechanics import HamiltonianInteraction, SymmetrySpec, noether
        >>> free = lambda s: s.target.p**2 / 2
        >>> system = System(
        ...     elements=[Element('ball', values={'q': 0.0, 'p': 1.0})],
        ...     interactions=[HamiltonianInteraction('motion', target='ball', hamiltonian=free)],
        ... )
        >>> result = noether(system, SymmetrySpec('translation', lambda s: {'ball.q': 1}))
        >>> result.invariant, result.charge
        (True, p_ball)
    """
    if not isinstance(symmetry, SymmetrySpec):
        error_msg = f'The symmetry is {symmetry!r}. Give a SymmetrySpec to check.'
        raise AnalysisError(error_msg)
    symmetry._check()
    base = invariants(source)
    variations = _get_variations(base.namespace, symmetry)
    if _get_hamiltonians(base.system):
        hamiltonian = _get_hamiltonian(base)
        terms = [hamiltonian.diff(item) * dq for item, dq in variations.items()]
        charge = sum((p * variations[q] for q, p in _get_pairs(base) if q in variations), SR(0))
    else:
        terms, charge = _get_lagrangian_change(base, variations)
    remainder = sum(terms, SR(0)).simplify_full()
    invariant = bool(remainder.is_zero()) or (
        not remainder.is_numeric() and _vanishes(base, terms, np.random.default_rng(random_state), samples)
    )
    return NoetherResult(invariant, SR(0) if invariant else remainder, SR(charge).simplify_full())

poisson_brackets(source, expressions)

Return the Poisson bracket of every pair of expressions of a mechanical system.

The bracket is {f, g} = sum df/dq dg/dp - df/dp dg/dq, summed over the canonical pairs of the system's HamiltonianInteractions. The expressions are Observables whose expression is a function of the namespace of the system, where s.<element>.<state> is the symbol of a state.

Parameters:

Name Type Description Default
source DataSource

The system, or a trajectory of it.

required
expressions Sequence[Observable]

The expressions to bracket.

required

Returns:

Name Type Description
brackets dict[tuple[str, str], Expression]

A mapping from every pair of labels to the bracket of their expressions.

Raises:

Type Description
AnalysisError

The system has no Hamiltonian interaction, or an expression is not one of the system.

Examples:

>>> from skcomplex.core.components import Observable
>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.mechanics import HamiltonianInteraction, poisson_brackets
>>> energy = lambda s: (s.target.p**2 + s.target.q**2) / 2
>>> system = System(
...     elements=[Element('mass', values={'q': 1.0, 'p': 0.0})],
...     interactions=[HamiltonianInteraction('spring', target='mass', hamiltonian=energy)],
... )
>>> expressions = [Observable('position', lambda s: s.mass.q), Observable('momentum', lambda s: s.mass.p)]
>>> poisson_brackets(system, expressions)
{('position', 'momentum'): 1}
Source code in src/skcomplex/systems/physics/common/mechanics/_invariants.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def poisson_brackets(source: DataSource, expressions: Sequence[Observable]) -> dict[tuple[str, str], Expression]:
    """Return the Poisson bracket of every pair of expressions of a mechanical system.

    The bracket is `{f, g} = sum df/dq dg/dp - df/dp dg/dq`, summed over the canonical pairs of the system's
    `HamiltonianInteraction`s. The expressions are `Observable`s whose expression is a function of the namespace of the
    system, where `s.<element>.<state>` is the symbol of a state.

    Args:
        source:
            The system, or a trajectory of it.

        expressions:
            The expressions to bracket.

    Returns:
        brackets:
            A mapping from every pair of labels to the bracket of their expressions.

    Raises:
        AnalysisError:
            The system has no Hamiltonian interaction, or an expression is not one of the system.

    Examples:
        >>> from skcomplex.core.components import Observable
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.mechanics import HamiltonianInteraction, poisson_brackets
        >>> energy = lambda s: (s.target.p**2 + s.target.q**2) / 2
        >>> system = System(
        ...     elements=[Element('mass', values={'q': 1.0, 'p': 0.0})],
        ...     interactions=[HamiltonianInteraction('spring', target='mass', hamiltonian=energy)],
        ... )
        >>> expressions = [Observable('position', lambda s: s.mass.q), Observable('momentum', lambda s: s.mass.p)]
        >>> poisson_brackets(system, expressions)
        {('position', 'momentum'): 1}
    """
    base = invariants(source, expressions=expressions)
    pairs = _get_pairs(base)
    values = {expression.label: _evaluate(base.namespace, expression) for expression in expressions}
    return {
        (first, second): sum(_get_bracket_terms(values[first], values[second], pairs), SR(0)).simplify_full()
        for first, second in itertools.combinations(values, 2)
    }