physics
physics.py — Lagrangian and Hamiltonian toolkit: Legendre transforms and symbolic PDEs
Overview
The physics module provides a unified interface for transforming between
Lagrangian and Hamiltonian descriptions of physical systems, both symbolically
and numerically.
It implements:
the classical Legendre transform for smooth, invertible momentum maps
p ↦ ∂L/∂p;the Legendre–Fenchel transform, i.e. the convex conjugate
H(x, u, ξ) = sup_p (⟨ξ, p⟩ − L(x, u, p)),
for non-quadratic or non-invertible cases;
a numeric Fenchel path for 1D and 2D problems, using either a deterministic grid search or SciPy local optimisation when available;
a heuristic decomposition of a Hamiltonian symbol into polynomial/local and non-polynomial/non-local parts;
generation of formal symbolic PDEs using the placeholder
ψOp(H, u)for a pseudo-differential operator with symbolH.
Main classes
- LagrangianHamiltonianConverter
Converts
L(x, u, p)toH(x, u, ξ)and back.- HamiltonianSymbolicConverter
Converts a Hamiltonian symbol into a formal PDE representation.
Supported dimensions
The public API currently supports one- and two-dimensional coordinate spaces.
For one coordinate, the conjugate momentum is ξ.
For two coordinates, the conjugate momenta are ξ and η.
Transformation methods
LagrangianHamiltonianConverter.L_to_H accepts the following methods:
method="legendre"Classical symbolic Legendre transform. Preferred when
Lis smooth and the Hessian∂²L/∂p²is invertible.method="fenchel_symbolic"Symbolic Legendre–Fenchel attempt. Useful for some convex non-quadratic cases, but it rejects manifestly nonsmooth expressions such as
Absorsign.method="fenchel_numeric"Numerical approximation of the convex conjugate. Returns a formal SymPy placeholder together with a callable that evaluates the approximation.
PDE modes
HamiltonianSymbolicConverter.hamiltonian_to_symbolic_pde supports:
"stationary"
ψOp(H, u) = E u
"heat"
∂_t u = −ψOp(H, u)
"schrodinger"
i ∂_t u = ψOp(H, u)
"wave"
∂_{tt} u + ψOp(H, u) = 0
Mathematical background
In classical mechanics, a Lagrangian L(x, u, p) depends on position x,
an optional field variable u, and generalised velocities p. The
conjugate momenta are defined by
ξ = ∂L/∂p.
When this relation can be inverted, the Hamiltonian is obtained from the Legendre transform
H(x, u, ξ) = ⟨ξ, p⟩ − L(x, u, p),
with p expressed in terms of ξ.
If the Hessian ∂²L/∂p² is singular, or if L is not strictly convex,
the classical transform may fail. The Legendre–Fenchel conjugate
H(x, u, ξ) = sup_p (⟨ξ, p⟩ − L(x, u, p))
always produces a convex function of ξ, when the supremum is well defined.
This module provides both symbolic and numerical treatments of this supremum.
In pseudo-differential operator formalism, a Hamiltonian H(x, ξ) can be
viewed as the symbol of an operator. The module splits H into a polynomial,
local part and a non-polynomial, non-local part, for example terms containing
√(1 + ξ²). This decomposition is heuristic and is used to assemble formal
PDEs involving ψOp(H, u).
Notes
The numeric Fenchel transform is computed over a bounded search domain
p ∈ p_bounds. Therefore it approximates a constrained convex conjugate. If the true maximiser lies outside the supplied bounds, the result may be inaccurate.The symbolic paths may fail when SymPy cannot solve the momentum relations. Setting
force=Trueallows the implementation to attempt recovery, but it does not guarantee a mathematically valid transform.ψOpis a formal placeholder. It records the intended operator action but does not implement quantisation, composition rules, boundary conditions, or functional calculus.SciPy is optional. If unavailable, numeric Fenchel methods fall back to grid search.
Matplotlib is imported optionally for possible plotting helpers, but the core conversion API does not require it.
Examples
Construct a Hamiltonian from a quadratic Lagrangian:
>>> from sympy import symbols
>>> from physics import LagrangianHamiltonianConverter
>>> x, u = symbols("x u")
>>> p = symbols("p", real=True)
>>> L = p**2 / 2
>>> H, xi = LagrangianHamiltonianConverter.L_to_H(L, (x,), u, (p,))
>>> H
xi**2/2
Build a formal Schrödinger-type PDE from a Hamiltonian symbol:
>>> from sympy import Function, symbols
>>> from physics import HamiltonianSymbolicConverter
>>> x, t = symbols("x t")
>>> xi = symbols("xi", real=True)
>>> u = Function("u")(x, t)
>>> H = xi**2
>>> result = HamiltonianSymbolicConverter.hamiltonian_to_symbolic_pde(
... H, (x,), t, u, mode="schrodinger"
... )
>>> result["formal_string"]
'i ∂_t u = ψOp(H, u) (H = H(x; xi))'
References
- class physics.HamiltonianSymbolicConverter[source]
Bases:
objectSymbolic converter between Hamiltonians and formal pseudo-differential PDEs.
This class treats a Hamiltonian H(x, ξ) as the symbol of a formal pseudo-differential operator. The operator action on a field u is represented by the placeholder ψOp(H, u).
The converter can split a Hamiltonian into a polynomial, local part and a non-polynomial, non-local part, and then assemble formal evolution or eigenvalue equations such as
ψOp(H, u) = E u,
i ∂ₜ u = ψOp(H, u),
∂ₜ u + ψOp(H, u) = 0.
Notes
The symbol ψOp is formal. It encodes the intended pseudo-differential operator action but does not by itself provide numerical evaluation, functional calculus, or rigorous operator-domain information.
See also
LagrangianHamiltonianConverterConstructs Hamiltonians from Lagrangians.
- static decompose_hamiltonian(H_expr: Expr, xi_vars: Sequence[Symbol]) Tuple[Expr, Expr][source]
Decompose a Hamiltonian into polynomial/local and non-polynomial/non-local parts.
The decomposition is heuristic. Terms that are polynomial in the momentum variables are collected as the local part. Terms containing objects such as sqrt, Abs, or sign, or terms that are not recognised as polynomial in the momentum variables, are collected as the non-local part.
- Parameters:
H_expr (Expr) – Symbolic Hamiltonian expression.
xi_vars (Sequence[Symbol]) – Momentum variables with respect to which polynomiality is tested.
- Returns:
H_poly (Expr) – Polynomial, local part of the Hamiltonian.
H_nonlocal (Expr) – Non-polynomial, non-local remainder.
Notes
The method first expands H_expr and then inspects ordered terms. This is useful for identifying principal polynomial symbols and lower-order or non-local remainders, but it is not a rigorous pseudo-differential operator calculus.
In particular, the classification depends on SymPy’s notion of polynomiality and on the chosen momentum variables. Coefficients depending on coordinates or fields are not automatically treated as non-local; only the momentum dependence is inspected.
- classmethod hamiltonian_to_symbolic_pde(H_expr: Expr, coords: Tuple[Symbol, ...], t: Symbol, u: Expr, mode: Literal['stationary', 'heat', 'schrodinger', 'wave'] = 'schrodinger') Dict[str, Any][source]
Build a formal symbolic PDE from a Hamiltonian symbol.
The Hamiltonian is first decomposed into local and non-local parts. The full Hamiltonian is then inserted into the placeholder operator ψOp(H, u), and a formal equation is constructed according to mode.
- Parameters:
H_expr (Expr) – Symbolic Hamiltonian H(x, ξ) or H(x, u, ξ).
coords (Tuple[Symbol, ...]) – Spatial coordinate symbols. Must contain one or two symbols.
t (Symbol) – Time symbol used by evolutionary modes.
u (Expr) – Unknown field symbol or expression.
mode ({"stationary", "heat", "schrodinger", "wave"}, optional) –
Type of formal PDE to generate:
”stationary”:
ψOp(H, u) = E u
”heat”:
∂ₜ u = −ψOp(H, u)
”schrodinger”:
i ∂ₜ u = ψOp(H, u)
”wave”:
∂ₜₜ u + ψOp(H, u) = 0
Default is “schrodinger”.
- Returns:
Dictionary with the following keys:
- ”pde”Expr
Formal SymPy equation representing the selected PDE.
- ”H_poly”Expr
Polynomial/local part of the Hamiltonian.
- ”H_nonlocal”Expr
Non-polynomial/non-local part of the Hamiltonian.
- ”formal_string”str
Human-readable formal expression, including the coordinate and momentum variable names.
- ”mode”str
Selected mode.
- Return type:
dict
- Raises:
ValueError – If coords does not have length one or two.
ValueError – If mode is not one of “stationary”, “heat”, “schrodinger”, or “wave”.
Notes
In one spatial dimension, the conjugate momentum variable is named ξ. In two spatial dimensions, the momentum variables are named ξ and η.
The returned PDE is formal. The placeholder ψOp represents the action of a pseudo-differential operator with symbol H, but it does not perform operator composition, quantisation, boundary-condition handling, or functional calculus.
- class physics.LagrangianHamiltonianConverter[source]
Bases:
objectBidirectional converter between Lagrangian and Hamiltonian descriptions.
This class implements symbolic and numeric transformations between a Lagrangian L(x, u, p) and a Hamiltonian H(x, u, ξ), where p denotes generalised velocities and ξ denotes conjugate momenta.
The classical Legendre transform is used when the momentum map
p ↦ ∂L/∂p
can be inverted. When inversion fails, or when L is non-quadratic or only convex, a Legendre–Fenchel conjugate can be used:
H(x, u, ξ) = sup_p (⟨ξ, p⟩ − L(x, u, p)).
Supported transformation methods are:
“legendre”: classical symbolic Legendre transform.
“fenchel_symbolic”: symbolic convex-conjugate attempt.
“fenchel_numeric”: numeric convex-conjugate approximation.
Only one-dimensional and two-dimensional coordinate sets are currently supported by the high-level API.
- _numeric_cache
Internal cache mapping symbolic numeric Hamiltonian placeholders to their numerical callables. The cache is keyed by object identity and is intended for internal use only.
- Type:
Dict[int, NumericCallable]
Notes
The numeric Fenchel path returns a SymPy placeholder such as H_numeric(ξ) together with a callable that evaluates the same object numerically. The placeholder is formal; use the returned callable for numerical evaluation.
See also
HamiltonianSymbolicConverterConverts Hamiltonians into formal PDEs.
- static H_to_L(H_expr: Expr, coords: Tuple[Symbol, ...], u: Expr, xi_vars: Tuple[Symbol, ...], force: bool = False) Tuple[Expr, Tuple[Symbol, ...]][source]
Perform the inverse classical Legendre transform from Hamiltonian to Lagrangian.
Given a Hamiltonian H(x, u, ξ), this method solves
p = ∂H/∂ξ
for ξ = ξ(p), then computes
L(x, u, p) = ⟨p, ξ(p)⟩ − H(x, u, ξ(p)).
- Parameters:
H_expr (Expr) – Symbolic Hamiltonian expression.
coords (Tuple[Symbol, ...]) – Spatial or configuration coordinate symbols. Must contain one or two symbols.
u (Expr) – Field symbol or field expression.
xi_vars (Tuple[Symbol, ...]) – Conjugate momentum symbols appearing in H_expr. In one dimension this is usually (ξ,); in two dimensions (ξ, η).
force (bool, optional) – If True, attempt to continue after some symbolic solving failures. Default is False.
- Returns:
L_expr (Expr) – Symbolic Lagrangian expression.
p_vars (Tuple[Symbol, …]) – Velocity/momentum symbols introduced by the inverse transform: (p,) in one dimension, or (p_x, p_y) in two dimensions.
- Raises:
ValueError – If coords does not have length one or two.
ValueError – If the system p = ∂H/∂ξ cannot be solved symbolically and force=False.
ValueError – If the inverse Legendre transform fails because no suitable expression ξ(p) can be constructed.
Notes
This routine implements only the classical inverse Legendre transform. It does not compute a Fenchel biconjugate and does not attempt to recover a Lagrangian from a nonsmooth or nonconvex Hamiltonian.
The inverse transform is well behaved when H is smooth and strictly convex in ξ. In other cases, symbolic solving may fail or return a branch-dependent result.
- static L_to_H(L_expr: Expr, coords: Tuple[Symbol, ...], u: Expr, p_vars: Tuple[Symbol, ...], return_symbol_only: bool = False, force: bool = False, method: Literal['legendre', 'fenchel_symbolic'] = 'legendre', fenchel_opts: Dict[str, Any] | None = None) Tuple[Expr, Tuple[Symbol, ...]][source]
- static L_to_H(L_expr: Expr, coords: Tuple[Symbol, ...], u: Expr, p_vars: Tuple[Symbol, ...], return_symbol_only: bool = False, force: bool = False, method: Literal['fenchel_numeric'] = 'fenchel_numeric', fenchel_opts: Dict[str, Any] | None = None) Tuple[Expr, Tuple[Symbol, ...], Callable[[float | ndarray], float | ndarray]]
Convert a Lagrangian L(x, u, p) into a Hamiltonian H(x, u, ξ).
The transformation can be classical Legendre, symbolic Fenchel, or numeric Fenchel. For one coordinate, the conjugate momentum variable is ξ; for two coordinates, the conjugate momentum variables are ξ and η.
- Parameters:
L_expr (Expr) – Symbolic Lagrangian expression.
coords (Tuple[Symbol, ...]) – Spatial or configuration coordinate symbols. Must contain one or two symbols.
u (Expr) – Field symbol or field expression. If return_symbol_only=True, occurrences of u are replaced by zero in symbolic outputs.
p_vars (Tuple[Symbol, ...]) – Velocity/momentum variables appearing in L_expr. This tuple should have the same length as coords.
return_symbol_only (bool, optional) – If True, remove explicit field dependence by substituting u = 0 in symbolic results. This option does not change the numerical callable returned by “fenchel_numeric”.
force (bool, optional) – If True, attempt to continue after recoverable symbolic failures, for example when the Hessian determinant cannot be verified or when the classical Legendre inversion is problematic.
method ({"legendre", "fenchel_symbolic", "fenchel_numeric"}, optional) –
Transformation strategy:
”legendre”: classical symbolic Legendre transform.
”fenchel_symbolic”: symbolic Legendre–Fenchel attempt.
”fenchel_numeric”: numerical Legendre–Fenchel approximation.
Default is “legendre”.
fenchel_opts (dict, optional) –
Options for the numeric Fenchel transform. Recognised keys depend on the spatial dimension.
For one-dimensional problems:
- p_boundsTuple[float, float]
Search interval for p. Default is (-10.0, 10.0).
- n_gridint
Number of grid points for the fallback grid search. Default is 2001.
- mode{“auto”, “scipy”, “grid”}
Numerical strategy. Default is “auto”.
- scipy_multistartint
Number of SciPy starting points. Default is 8.
For two-dimensional problems:
- p_boundsSequence[Tuple[float, float]]
Search intervals for each momentum component. Default is [(-10.0, 10.0), (-10.0, 10.0)].
- n_grid_per_dimint
Number of grid points per dimension for the fallback grid search. Default is 41.
- mode{“auto”, “scipy”, “grid”}
Numerical strategy. Default is “auto”.
- scipy_multistartint
Accepted for API compatibility. Default is 20.
- multistart_restartsint
Number of random restarts for the SciPy multistart search. Default is 8.
- Returns:
H_expr (Expr) – For “legendre” and “fenchel_symbolic”, the symbolic Hamiltonian. For “fenchel_numeric”, a formal placeholder such as H_numeric(ξ) or H_numeric(ξ, η).
xi_vars (Tuple[Symbol, …]) – Conjugate momentum symbols: (ξ,) in one dimension, or (ξ, η) in two dimensions.
H_numeric (NumericCallable) – Numerical evaluator returned only when method=”fenchel_numeric”.
- Raises:
ValueError – If coords does not have length one or two.
ValueError – If the classical Legendre transform is not invertible and force=False.
ValueError – If symbolic solving fails and force=False.
ValueError – If nonsmooth expressions such as Abs or sign are supplied to the symbolic Fenchel method.
ValueError – If method is not one of “legendre”, “fenchel_symbolic”, or “fenchel_numeric”.
Notes
For quadratic Lagrangians, the implementation first tries the analytic path based on the Hessian
A = ∂²L/∂p².
If A is invertible, the transform is computed from
ξ = A p + b.
The numeric Fenchel transform approximates
H(ξ) = sup_p (⟨ξ, p⟩ − L(p))
over a bounded domain. It is therefore an approximation of the convex conjugate, not an exact symbolic object.
When method=”fenchel_numeric” is used, the returned SymPy expression is only a placeholder. The actual numerical evaluation is performed by the returned callable. The placeholder is stored in an internal cache keyed by object identity.