Some tools for Hamiltonian systems
Project description
pyHamSys
pyHamSys (short for Python Hamiltonian Systems) is an open-source Python library for scientific computing involving Hamiltonian systems. It provides tools to model, analyze, and simulate Hamiltonian systems. In particular, the library offers a streamlined and user-friendly environment for implementing and running symplectic-split integrators. These specialized numerical methods are designed to preserve the geometric structure of Hamiltonian systems, ensuring accurate and stable simulations of their dynamics over long time periods.
Installation
Installation within a Python virtual environment:
python3 -m pip install pyhamsys
For more information on creating a Python virtual environment, click here. For a summary with the main steps, click here.
Symplectic Integrators
pyHamSys features a dedicated class, SymplecticIntegrator, which provides a comprehensive implementation of symplectic-split integrators. These integrators are designed specifically for the numerical integration of Hamiltonian systems, ensuring the preservation of the symplectic structure of phase space—a key property that underpins the stability and accuracy of long-term simulations of such systems.
Symplectic-split integrators decompose the Hamiltonian into subcomponents that are individually solvable, allowing for efficient and accurate integration. This decomposition is particularly effective for complex or high-dimensional systems, as it minimizes numerical drift and conserves critical invariants like energy over extended time intervals.
The SymplecticIntegrator class offers a variety of splitting methods, enabling users to select the most appropriate scheme for their specific Hamiltonian system and computational requirements. Each integrator is implemented to handle both autonomous and non-autonomous systems, supporting applications in classical mechanics, molecular dynamics, astrophysics, and quantum mechanics.
Pre-defined integrators are:
Verlet(order 2, all-purpose), also referred to as Strang or Störmer-Verlet splitting- From Forest, Ruth, Physica D 43, 105 (1990):
FR(order 4, all-purpose)
- From Yoshida, Phys. Lett. A 150, 262 (1990):
Yo#: # should be replaced by an even integer, e.g.,Yo6for 6th order symplectic integrator (all-purpose)Yos6: (order 6, all-purpose) optimized symplectic integrator (solution A from Table 1)
- From McLachlan, SIAM J. Sci. Comp. 16, 151 (1995):
M2(order 2, all-purpose)M4(order 4, all-purpose)
- From Omelyan, Mryglod, Folk, Comput. Phys. Commun. 146, 188 (2002):
EFRL(order 4) optimized for H = A + BPEFRLandVEFRL(order 4) optimized for H = A(p) + B(q). ForPEFRL, chi should be exp(h XA)exp(h XB). ForVEFRL, chi should be exp(h XB)exp(h XA).
- From Blanes, Moan, J. Comput. Appl. Math. 142, 313 (2002):
BM4(order 4, all-purpose) refers to S6BM6(order 6, all-purpose) refers to S10RKN4b(order 4) refers to SRKN6b optimized for H = A(p) + B(q). Here chi should be exp(h XB)exp(h XA).RKN6b(order 6) refers to SRKN11b optimized for H = A(p) + B(q). Here chi should be exp(h XB)exp(h XA).RKN6a(order 6) refers to SRKN14a optimized for H = A(p) + B(q). Here chi should be exp(h XA)exp(h XB).
- From Blanes, Casas, Farrés, Laskar, Makazaga, Murua, Appl. Numer. Math. 68, 58 (2013):
ABA104(order (10,4)) optimized for H = A + ε B. Here chi should be exp(h XA)exp(h XB).ABA864(order (8,6,4)) optimized for H = A + ε B. Here chi should be exp(h XA)exp(h XB).ABA1064(order (10,6,4)) optimized for H = A + ε B. Here chi should be exp(h XA)exp(h XB).
All-purpose integrators are for any splitting of the Hamiltonian H=∑k Ak in any order of the functions Ak. Otherwise, the order of the operators is specified for each integrator. These integrators are used in the functions solve_ivp_symp and solve_ivp_sympext by specifying the entry method (default is BM4).
HamSys class
The HamSys class provides a robust framework for defining and integrating Hamiltonian systems. It allows users to specify the number of degrees of freedom, coordinate representations, and key attributes like the Hamiltonian and associated equations of motion.
Parameters
ndof: integer or half-integer, optional
The number of degrees of freedom in the Hamiltonian system. Half integers denote an explicit time dependence. Default is 1.btype: str, optional Information on the Poisson bracket used in the equations of motion. For btype='pq', a canonical Poisson bracket in (p,q) is used, i.e., the dynamical variables (q, p) are real and canonically conjugate. If btype='psi', the dynamical variables are (ψ, ψ*) where $\psi=(q + i p)/\sqrt{2}$. Default is 'pq'. For other btypes, the functioncouplingshould be specified for the element of the classHamSys.
Parameters and Attributes
y_dot: callable, optional
A function of (t, y) which returns {y,H(t,y)} where y is the state vector and H is the Hamiltonian. In (real) canonical coordinates where y = (q, p), this function returns (∂H/∂p, -∂H/∂q). In complex coordinate ψ, this function returns -i ∂H/∂ψ*. For practical implementation, the state vector y should be represented as a one-dimensional array with a shape of (n,), where n denotes the total number of dynamical variables in the system. This ensures compatibility with numerical solvers and facilitates efficient computation of the system's evolution.k_dot: callable, optional
A function of (t, y) which returns {k,H(t,y)} = -∂H/∂t where k is canonically conjugate to t and H is the Hamiltonian.chiandchi_star: callable, optional
Functions of (h, t, y) which returns, respectively, exp(h XN)...exp(h X1)y and exp(h X1)...exp(h XN)y at time t for its use in symplectic-split integration (without phase space extension). See [2] for more details.hamiltonian: callable, optional
A function of (t, y) which returns the Hamiltonian H(t,y) where y is the state vector.coupling(for exended phases space with the restraint as in [3]) : callable, optional
A function of (h, y, ω) which advances y from time t to t+h for the coupling Hamiltonian $\omega (y - \bar{y})^2/2$. This function is already computed for the types btype='pq' and 'psi'. For any other type, it should be provided.
Functions
-
compute_vector_field: from a callable function (Hamiltonian in canonical coordinates) written with symbolic variables (SymPy), computes the vector fields,y_dotandk_dot.Determine Hamilton's equations of motion from a given scalar function –the Hamiltonian– H(q, p, t) where q and p are respectively positions and momenta. However, it is preferrable to code explicitly and optimize
y_dotandk_dot.Parameters
hamiltonian: callable
Function H(q, p, t) –the Hamiltonian expressed in symbolic variables–, expressed using SymPy functions.output: bool, optional
If True, displays the equations of motion. Default is False.
The function
compute_vector_fielddetermines the HamSys function attributesy_dotandk_dotto be used insolve_ivp_sympext. The derivatives are computed symbolically using SymPy. -
integrate: callable
Integrate the Hamiltonian system using either a pre-defined symplectic solver (see above for a complete list) or a standard IVP solver ('RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'). Supports optional symplectic extension and energy conservation checks.- z0 (
array_like)
Initial condition(s) of the system. - t_eval (
array_like)
Times at which the solution is evaluated and stored. - params (
Parameters)
Parameters for the integration of the Hamiltonian system. Step must be provided. - command (void function of (t, y), optional)
Void function to be run at each step size (e.g., plotting an observable associated with the state vector y, modify global or mutable variables, or register specific events).
Parameters
The integration parameters are defined through an element params of the dataclass
ParametersofpyHamSys. See examples for its usage. Below are all the possible parameters to tune.-
step (
float)
Fixed integration step size used in symplectic solvers, and maximium step size in variable step size methods for IVP solvers. -
solver (
str, optional, default="BM4")
Solver method. Must be a member ofMETHODS(symplectic solvers), orIVP_METHODS(classical IVP solvers). -
extension (
bool, optional, default=False)
IfTrue, use a symplectic extension method in phase space. -
tol (
float, optional, default=1e-8)
Absolute and relative tolerance for IVP solvers. Also, tolerance for the implict determination of the symmetric projection. -
display (
bool, optional, default=True)
IfTrue, prints runtime information such as CPU time, error in energy, and copy distance (if available). -
check_energy (
bool, optional, default=False)
IfTrue, appends an auxiliary variable to track the Hamiltonian. Requireshamiltonianandk_dotto be defined. -
projection (
str, optional, default=None)
If specified, uses the 'midpoint' or 'symmetric' projection to move from the extended phase space to the true phase space. Possibilities includesymmetricandmidpoint. -
omega (
float, optional, default=None)
Restraint parameter for symplectic extension solvers as in [4]. -
diss (
float, optional, default=0)
Dissipative coefficient for improved accuracy when time steps are too large. -
max_iter (
int, optional, default=100)
Maximum number of iterations for the implict determination of the symmetric projection.Returns
-
sol (
object)
Solution object. Its attributes depend on the solver used:y: state trajectoryt: time pointsstep: integration time stepcpu_time: total CPU time usederr: (ifcheck_energy=True) maximum error in energyprojection: Type of projection successfully used in the computation (only forextension=True)proj_dist: Maximum distance between the two copies of the state in the extended phase space (only forextension=True)
Notes
- Symplectic solvers (
METHODS)
Ifextension=False, requireschiandchi_starto be defined. Ifextension=True, requiresy_dotto be defined.
Preserves geometric properties of Hamiltonian flows. - IVP solvers (
IVP_METHODS)
Requirey_dot(andk_dotifcheck_energy=True). Allow adaptive step sizes bounded bystep. - Energy checking
Whencheck_energy=True, an auxiliary variable is added and the error in Hamiltonian is computed relative to its initial value.
- z0 (
Remarks:
- Use
extension=Falseif the Hamiltonian can be split and if each partial operator exp(h Xk) can be easily and explicitly expressed/computed. Otherwise useextension=True. - The step size is slightly readjusted so that the final time tf corresponds to an integer number of step sizes. The step size used in the computation is recorded in the solution as
sol.step. - For integrating multiple trajectories at the same time, extend phase space and define a state vector y = (y1, y2,...yN) where N is the number of trajectories. The Hamiltonian is given by $H(t,\mathbf{y})=\sum_{i=1}^N h(t, y_i)$.
References:
- [1] Hairer, Lubich, Wanner, 2003, Geometric Numerical Integration: Structure-Preserving Algorithms for Ordinary Differential Equations (Springer)
- [2] McLachlan, R., Tuning symplectic integrators is easy and worthwhile, Commun. Comput. Phys. 31, 987 (2022); arxiv:2104.10269
- [3] Pihajoki, P., Explicit methods in extended phase space for inseparable Hamiltonian problems, Celest. Mech. Dyn. Astron. 121, 211 (2015)
- [4] Tao, M., Explicit symplectic approximation of nonseparable Hamiltonians: Algorithm and long time performance, Phys. Rev. E 94, 043303 (2016)
- [5] Jayawardana, B., Ohsawa, T. Semiexplicit symplectic integrators for non-separable Hamiltonian systems, Math. Comp. 92.339, 251 (2023)
Example
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
from pyhamsys import HamSys, Parameters
hs = HamSys()
hamiltonian = lambda q, p, t: p**2 / 2 - sp.cos(q)
hs.compute_vector_field(hamiltonian, output=True)
y0 = np.asarray([3, 0])
t_eval = np.linspace(0, 20, 2**9)
params = Parameters(step=1e-1, extension=True, check_energy=True)
sol = hs.integrate(y0, t_eval, params=params)
plt.plot(sol.y[0], sol.y[1])
plt.show()
For more examples, click Examples
This work has been carried out within the framework of the French Federation for Magnetic Fusion Studies (FR-FCM).
For more information: cristel.chandre@cnrs.fr
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyhamsys-0.90.tar.gz.
File metadata
- Download URL: pyhamsys-0.90.tar.gz
- Upload date:
- Size: 25.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
09bc4283cda6054ec43ebef1aded5140977e9cc64d78ed69242ff39204b76c4f
|
|
| MD5 |
c6703406c0fcaa3f896b84ceb681761e
|
|
| BLAKE2b-256 |
ca5848d3f2039a79925569c26d3432ae0aa90d02413cd45837bd4f87bceac7ac
|
File details
Details for the file pyhamsys-0.90-py3-none-any.whl.
File metadata
- Download URL: pyhamsys-0.90-py3-none-any.whl
- Upload date:
- Size: 20.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fba5ab1b8964166dd87362a94839d5b1ac46e79679c448fd107bf7ced81adef9
|
|
| MD5 |
96f3e781b3db12cb2962575dd2221f32
|
|
| BLAKE2b-256 |
39e37285d82b9d5566d99db12d53669375539b02a69fc7fce5e16fbc2ff87476
|