Skip to content

Commit

Permalink
Allow initializing Distance from angle-like parallax
Browse files Browse the repository at this point in the history
  • Loading branch information
taldcroft committed Dec 11, 2023
1 parent 28e593f commit 585a15b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion astropy/coordinates/distances.py
Expand Up @@ -50,7 +50,7 @@ class Distance(u.SpecificTypeQuantity):
distmod : float or `~astropy.units.Quantity`
The distance modulus for this distance. Note that if ``unit`` is not
provided, a guess will be made at the unit between AU, pc, kpc, and Mpc.
parallax : `~astropy.units.Quantity` or `~astropy.coordinates.Angle`
parallax : angle-like
The parallax in angular units.
dtype : `~numpy.dtype`, optional
See `~astropy.units.Quantity`.
Expand Down Expand Up @@ -162,6 +162,7 @@ def __new__(
unit = u.pc

elif parallax is not None:
parallax = u.Quantity(parallax, copy=False)
if unit is None:
unit = u.pc
value = parallax.to_value(unit, equivalencies=u.parallax())
Expand Down
18 changes: 18 additions & 0 deletions astropy/coordinates/tests/test_distance.py
Expand Up @@ -10,6 +10,7 @@
from astropy import units as u
from astropy.coordinates import CartesianRepresentation, Distance, Latitude, Longitude
from astropy.coordinates.builtin_frames import ICRS, Galactic
from astropy.table import Column
from astropy.units import allclose as quantity_allclose
from astropy.utils.compat.optional_deps import HAS_SCIPY
from astropy.utils.exceptions import AstropyWarning
Expand Down Expand Up @@ -313,3 +314,20 @@ def test_distance_to_quantity_when_not_units_of_length():
def test_distance_nan():
# Check that giving NaNs to Distance doesn't emit a warning
Distance([0, np.nan, 1] * u.m)


def test_distance_parallax_angle_like():
"""Test angle-like behavior of Distance.parallax for object with a unit attribute.
Adapted from #15693
"""
parallax = Column([1.0, 2.0, 3.0], unit=u.mas)
d0 = Distance(parallax=parallax)
d1 = Distance(parallax=u.Quantity(parallax))
assert np.all(d0 == d1)

class FloatMas(float):
unit = u.mas

d2 = Distance(parallax=FloatMas(1.0))
assert d0[0] == d2
3 changes: 3 additions & 0 deletions docs/changes/coordinates/15712.bugfix.rst
@@ -0,0 +1,3 @@
Fix a bug in the coordinates ``Distance`` class to allow initialization with
``parallax`` as any angle-like value. This includes types like ``Column`` which have a
unit but are not ``Quantity`` objects.

0 comments on commit 585a15b

Please sign in to comment.