PotentialBase#

class gala.potential.potential.PotentialBase(*, units=None, origin=None, R=None, **kwargs)[source]#

Bases: CommonBase

A base class for defining gravitational potentials in Gala.

This abstract base class provides the foundation for all gravitational potential models in Gala. It handles unit conversions, coordinate transformations, and provides a consistent interface for computing gravitational forces, energies, and related quantities.

Subclasses must implement the abstract methods _energy(q, t) and _gradient(q, t) that compute the potential energy and its gradient (negative acceleration) at position q and time t. Optionally, subclasses may implement _density(q, t) and _hessian(q, t) to provide mass density and second derivative information.

Parameters:
unitsUnitSystem, optional

Set of non-reducible units that specify (at minimum) the length, mass, time, and angle units. If not specified, the default unit system will be used.

originarray_like, optional

The origin of the potential in Cartesian coordinates. Default is the origin [0, 0, 0].

Rarray_like, Rotation, optional

Rotation matrix or Rotation object to rotate the reference frame of the potential. If specified, the potential will be evaluated in the rotated coordinate system.

Attributes:
ndimint

Number of spatial dimensions (default: 3).

parametersMappingProxyType

Dictionary of potential parameters with associated units.

unitsUnitSystem

The unit system used by the potential.

Gfloat

Gravitational constant in the potential’s unit system.

originarray_like

The origin of the potential coordinate system.

Rarray_like, optional

Rotation matrix for the potential coordinate system.

Notes

The potential is evaluated in a coordinate system that may be shifted (via origin) and/or rotated (via R) relative to the input coordinates. The transformation is applied as: q_transformed = R @ (q - origin).

Attributes Summary

Methods Summary

__call__(q)

Call self as a function.

acceleration([q, t])

Compute the gravitational acceleration at the given position(s).

as_interop(package, **kwargs)

Interoperability with other Galactic dynamics packages

circular_velocity([q, t])

Estimate the circular velocity at given position(s) assuming spherical symmetry.

density([q, t])

Compute the mass density at the given position(s).

energy([q, t])

Compute the gravitational potential energy at the given position(s).

gradient([q, t])

Compute the gradient of the gravitational potential.

hessian([q, t])

Compute the Hessian matrix of the gravitational potential.

integrate_orbit(*args, **kwargs)

Integrate an orbit in the current potential using the integrator class provided.

mass_enclosed([q, t])

Estimate the mass enclosed within spherical radius at given position(s).

plot_contours(grid[, t, filled, ax, labels, ...])

Plot equipotentials contours.

plot_density_contours(grid[, t, filled, ax, ...])

Plot density contours.

plot_rotation_curve(R_grid[, t, ax, labels])

Plot the rotation curve or circular velocity curve for this potential on the input grid of cylindrical radii.

replace_units(units[, copy])

Change the unit system of this potential.

replicate(**kwargs)

Return a copy of the potential instance with some parameter values changed.

save(f)

Save the potential to a text file.

to_latex()

Return a string LaTeX representation of this potential

to_sympy()

Return a representation of this potential class as a sympy expression

Attributes Documentation

ndim = 3#
units#

Methods Documentation

__call__(q)[source]#

Call self as a function.

acceleration(q=None, t=0.0, **coord_kwargs)[source]#

Compute the gravitational acceleration at the given position(s).

The gravitational acceleration is the negative gradient of the potential: \(\vec{a} = -\nabla \phi\). This is the acceleration experienced by a test particle in the gravitational field.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to compute the gravitational acceleration. If the input has no units (i.e., is an ndarray), it is assumed to be in the same unit system as the potential. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the acceleration. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
accQuantity

The gravitational acceleration vector(s). Has the same shape as the input position array q. Units are acceleration (e.g., m/s² in SI units).

See also

gradient

Compute the potential gradient (negative acceleration).

Notes

This method is equivalent to -self.gradient(q, t) and is provided for convenience in orbital integration and dynamics calculations.

as_interop(package, **kwargs)[source]#

Interoperability with other Galactic dynamics packages

Parameters:
packagestr

The package to export the potential to. Currently supported packages are "galpy" and "agama".

kwargs

Any additional keyword arguments are passed to the interop function.

circular_velocity(q=None, t=0.0, **coord_kwargs)[source]#

Estimate the circular velocity at given position(s) assuming spherical symmetry.

The circular velocity is the speed required for a circular orbit at the given radius in a spherically symmetric potential. It is computed using \(v_{\rm circ}(r) = \sqrt{r |dΦ/dr|}\), where the radial derivative is evaluated from the potential gradient.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to estimate the circular velocity. The calculation uses the spherical radius from the origin. If the input has no units, it is assumed to be in the same unit system as the potential. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the circular velocity. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
vcircQuantity

Circular velocity at the spherical radius corresponding to each position. For input shape (n_dim, n_positions), returns shape (n_positions,). Units are velocity (e.g., m/s in SI units).

Notes

This method assumes the potential is approximately spherically symmetric. The circular velocity is computed using the relation:

\[v_{\rm circ}(r) = \sqrt{r \left| \frac{d\Phi}{dr} \right|}\]

where the radial derivative is computed from the Cartesian gradient via \(dΦ/dr = \vec{\nabla}Φ \cdot \hat{r}\).

For exactly spherical potentials, this gives the speed of circular orbits. For non-spherical potentials, this provides an approximation useful for initial orbit estimates.

density(q=None, t=0.0, **coord_kwargs)[source]#

Compute the mass density at the given position(s).

For potentials that have an associated mass distribution, this method computes the mass density rho(q, t) at the specified positions and time. The density is related to the potential via Poisson’s equation: \(\nabla^2 \phi = 4\pi G \rho\).

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to evaluate the mass density. If the input has no units (i.e., is an ndarray), it is assumed to be in the same unit system as the potential. Shape should be (n_dim,) for a single position or (n_dim, n_positions) for multiple positions. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the mass density. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
densQuantity

The mass density at the specified position(s). For input shape (n_dim, n_positions), returns shape (n_positions,). Units are mass density (e.g., kg/m³ in SI units).

Raises:
NotImplementedError

If the potential does not have an implemented density function.

Notes

Not all potential models have an implemented density function. For potentials without a density implementation, this method will raise a NotImplementedError.

The density is computed using the relationship with the potential’s Laplacian (when available) or from the underlying mass model.

energy(q=None, t=0.0, **coord_kwargs)[source]#

Compute the gravitational potential energy at the given position(s).

The potential energy per unit mass is evaluated at the specified position(s) and time.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to evaluate the potential. If the input has no units (i.e., is an ndarray), it is assumed to be in the same unit system as the potential. Shape should be (n_dim,) for a single position or (n_dim, n_positions) for multiple positions. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the potential. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
EQuantity

The gravitational potential energy per unit mass. For input shape (n_dim, n_positions), returns shape (n_positions,). Units are specific energy (e.g., m²/s² in SI units).

Notes

The potential energy is related to the gravitational acceleration by \(\vec{a} = -\nabla \phi\), where φ is the potential energy per unit mass.

Examples

Using Cartesian coordinates (works for all potentials):

>>> import astropy.units as u
>>> import numpy as np
>>> pot = SomePotential(...)
>>> xyz = np.array([[1., 0., 0.]]).T * u.kpc
>>> pot.energy(xyz)

For spherical potentials, you can use spherical radius:

>>> pot = HernquistPotential(m=1e10*u.Msun, c=5*u.kpc)
>>> r = np.linspace(0.1, 10, 100) * u.kpc
>>> pot.energy(r=r)

For cylindrical potentials, you can use R and z:

>>> pot = MiyamotoNagaiPotential(m=1e11*u.Msun, a=3*u.kpc, b=0.3*u.kpc)
>>> R = np.linspace(1, 15, 100) * u.kpc
>>> pot.energy(R=R, z=0*u.kpc)
>>> pot.energy(R=R)  # z defaults to 0
gradient(q=None, t=0.0, **coord_kwargs)[source]#

Compute the gradient of the gravitational potential.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to evaluate the potential gradient. If the input has no units (i.e., is an ndarray), it is assumed to be in the same unit system as the potential. Shape should be (n_dim,) for a single position or (n_dim, n_positions) for multiple positions. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the potential gradient. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
gradQuantity

The gradient of the gravitational potential. Has the same shape as the input position array q. Units are acceleration (e.g., m/s² in SI units). To get gravitational acceleration, use acceleration() or compute -gradient().

See also

acceleration

Compute gravitational acceleration (negative gradient).

Notes

The relationship between potential φ, gradient, and acceleration is:

\[\vec{a} = -\nabla \phi = -\frac{\partial \phi}{\partial \vec{q}}\]

The gradient is always returned in Cartesian coordinates, even when using symmetry coordinates as input.

hessian(q=None, t=0.0, **coord_kwargs)[source]#

Compute the Hessian matrix of the gravitational potential.

The Hessian matrix contains the second partial derivatives of the potential: \(H_{ij} = \frac{\partial^2 \phi}{\partial q_i \partial q_j}\). This is useful for stability analysis, computing tidal tensors, and orbital frequency analysis.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to evaluate the Hessian matrix. If the input has no units (i.e., is an ndarray), it is assumed to be in the same unit system as the potential. Shape should be (n_dim,) for a single position or (n_dim, n_positions) for multiple positions. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the Hessian matrix. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
hessQuantity

The Hessian matrix of second derivatives. For input shape (n_dim, n_positions), returns shape (n_dim, n_dim, n_positions). Each n_dim x n_dim slice corresponds to the Hessian matrix at one position. Units are acceleration per length (e.g., s⁻² in SI units).

Raises:
NotImplementedError

If the potential does not have an implemented Hessian function, or if the potential is rotated (R is not the identity).

Notes

Computing Hessian matrices for rotated potentials (when R is not the identity matrix) is currently not supported and will raise a NotImplementedError.

Not all potential models have an implemented Hessian function. For potentials without a Hessian implementation, this method will raise a NotImplementedError.

The Hessian matrix is symmetric for time-independent potentials.

integrate_orbit(*args, **kwargs)[source]#

Integrate an orbit in the current potential using the integrator class provided. Uses same time specification as Integrator() – see the documentation for gala.integrate for more information.

Parameters:
w0PhaseSpacePosition, array_like

Initial conditions.

IntegratorIntegrator (optional)

Integrator class to use.

Integrator_kwargsdict (optional)

Any extra keyword argumets to pass to the integrator class when initializing. Only works in non-Cython mode.

cython_if_possiblebool (optional)

If there is a Cython version of the integrator implemented, and the potential object has a C instance, using Cython will be much faster.

save_allbool (optional)

Controls whether to store the phase-space position at all intermediate timesteps. Set to False to store only the final values (i.e. the phase-space position(s) at the final timestep). Default is True.

**time_spec

Specification of how long to integrate. See documentation for parse_time_specification.

Returns:
orbitOrbit
mass_enclosed(q=None, t=0.0, **coord_kwargs)[source]#

Estimate the mass enclosed within spherical radius at given position(s).

This method estimates the enclosed mass by assuming spherical symmetry and using the relation \(M_{\rm enc}(r) = r^2 |dΦ/dr| / G\), where the radial derivative is computed numerically using finite differences.

Parameters:
qPhaseSpacePosition, Quantity, array_like, optional

Position(s) at which to estimate the enclosed mass. The enclosed mass is computed at the spherical radius corresponding to each position. If the input has no units, it is assumed to be in the same unit system as the potential. If using symmetry coordinates, pass those as keyword arguments instead and leave q as None.

tnumeric, Quantity, optional

Time at which to evaluate the enclosed mass. Default is 0.

**coord_kwargs

For potentials with spherical or cylindrical symmetry, you can optionally provide coordinates in the natural coordinate system. For spherical potentials, use r=.... For cylindrical potentials, use R=... and optionally z=... (defaults to 0).

Returns:
mencQuantity

Mass enclosed within the spherical radius at each position. For input shape (n_dim, n_positions), returns shape (n_positions,). Units are mass (e.g., kg in SI units).

Notes

This method assumes the potential is approximately spherically symmetric. The enclosed mass is estimated using a finite difference approximation to the radial derivative of the potential.

For potentials with negative mass parameters (e.g., some composite models), the sign is handled appropriately.

The calculation uses the relation derived from Gauss’s law:

\[M_{\rm enc}(r) = \frac{r^2}{G} \left| \frac{d\Phi}{dr} \right|\]
plot_contours(grid, t=0.0, filled=True, ax=None, labels=None, subplots_kw=None, **kwargs)[source]#

Plot equipotentials contours. Computes the potential energy on a grid (specified by the array grid).

Warning

Right now the grid input must be arrays and must already be in the unit system of the potential. Quantity support is coming…

Parameters:
gridtuple

Coordinate grids or slice value for each dimension. Should be a tuple of 1D arrays or numbers.

tquantity-like (optional)

The time to evaluate at.

filledbool (optional)

Use contourf() instead of contour(). Default is True.

axmatplotlib.Axes (optional)
labelsiterable (optional)

List of axis labels.

subplots_kwdict

kwargs passed to matplotlib’s subplots() function if an axes object is not specified.

kwargsdict

kwargs passed to either contourf() or plot().

Returns:
figFigure
plot_density_contours(grid, t=0.0, filled=True, ax=None, labels=None, subplots_kw=None, **kwargs)[source]#

Plot density contours. Computes the density on a grid (specified by the array grid).

Warning

For now, the grid input must be arrays and must already be in the unit system of the potential. Quantity support is coming…

Parameters:
gridtuple

Coordinate grids or slice value for each dimension. Should be a tuple of 1D arrays or numbers.

tquantity-like (optional)

The time to evaluate at.

filledbool (optional)

Use contourf() instead of contour(). Default is True.

axmatplotlib.Axes (optional)
labelsiterable (optional)

List of axis labels.

subplots_kwdict

kwargs passed to matplotlib’s subplots() function if an axes object is not specified.

kwargsdict

kwargs passed to either contourf() or plot().

Returns:
figFigure
plot_rotation_curve(R_grid, t=0.0, ax=None, labels=None, **plot_kwargs)[source]#

Plot the rotation curve or circular velocity curve for this potential on the input grid of cylindrical radii.

Parameters:
R_gridarray_like

A grid of radius values to compute the rotation curve at. This should be a one-dimensional grid.

tquantity-like (optional)

The time to evaluate at.

axmatplotlib.Axes (optional)
labelsiterable (optional)

List of axis labels. Set to False to disable adding labels.

plot_kwargsdict

kwargs passed to plot().

Returns:
figFigure
axAxes
replace_units(units, copy=True)[source]#

Change the unit system of this potential.

Parameters:
unitsUnitSystem, str

Set of non-reducable units that specify (at minimum) the length, mass, time, and angle units.

copybool (optional)

If True, returns a copy, if False, changes this object.

replicate(**kwargs)[source]#

Return a copy of the potential instance with some parameter values changed. This always produces copies of any parameter arrays.

Parameters:
**kwargs

All other keyword arguments are used to overwrite parameter values when making the copy.

Returns:
replicantPotentialBase subclass instance

The replicated potential.

save(f)[source]#

Save the potential to a text file. See save() for more information.

Parameters:
fstr, file_like

A filename or file-like object to write the input potential object to.

classmethod to_latex()[source]#

Return a string LaTeX representation of this potential

Returns:
latex_strstr

The latex expression as a Python string.

classmethod to_sympy()[source]#

Return a representation of this potential class as a sympy expression

Returns:
exprsympy expression
varsdict

A dictionary of sympy symbols used in the expression.