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 |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |