Skip to content

Commit 7b82928

Browse files
committed
Broadcast frames over both data and attributes
Fixes astropy#5982, fixes astropy#8812, fixes astropy#11184, fixes astropy#12965, fixes astropy#14383.
1 parent 1d11e15 commit 7b82928

5 files changed

Lines changed: 143 additions & 51 deletions

File tree

‎astropy/coordinates/baseframe.py‎

Lines changed: 25 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -337,36 +337,15 @@ def __init__(
337337
f"keywords: {list(kwargs)}"
338338
)
339339

340-
# We do ``is None`` because self._data might evaluate to false for
341-
# empty arrays or data == 0
342-
if self._data is None:
343-
# No data: we still need to check that any non-scalar attributes
344-
# have consistent shapes. Collect them for all attributes with
345-
# size > 1 (which should be array-like and thus have a shape).
346-
shapes = {
347-
fnm: value.shape
348-
for fnm, value in values.items()
349-
if getattr(value, "shape", ())
350-
}
351-
if shapes:
352-
if len(shapes) > 1:
353-
try:
354-
self._no_data_shape = check_broadcast(*shapes.values())
355-
except ValueError as err:
356-
raise ValueError(
357-
f"non-scalar attributes with inconsistent shapes: {shapes}"
358-
) from err
359-
360-
# Above, we checked that it is possible to broadcast all
361-
# shapes. By getting and thus validating the attributes,
362-
# we verify that the attributes can in fact be broadcast.
363-
for fnm in shapes:
364-
getattr(self, fnm)
365-
else:
366-
self._no_data_shape = shapes.popitem()[1]
367-
368-
else:
369-
self._no_data_shape = ()
340+
shapes = [getattr(value, "shape", ()) for value in values.values()]
341+
if self.has_data:
342+
shapes.append(getattr(self._data, "shape", ()))
343+
try:
344+
self._shape = check_broadcast(*shapes)
345+
except ValueError as err:
346+
raise ValueError(
347+
f"non-scalar attributes with inconsistent shapes: {shapes}"
348+
) from err
370349

371350
# The logic of this block is not related to the previous one
372351
if self._data is not None:
@@ -725,7 +704,7 @@ def has_data(self):
725704

726705
@property
727706
def shape(self):
728-
return self.data.shape if self.has_data else self._no_data_shape
707+
return self._shape
729708

730709
# We have to override the ShapedLikeNDArray definitions, since our shape
731710
# does not have to be that of the data.
@@ -1601,8 +1580,10 @@ def _apply(self, method, *args, **kwargs):
16011580

16021581
def apply_method(value):
16031582
if isinstance(value, ShapedLikeNDArray):
1583+
value = value._apply(np.broadcast_to, shape=self.shape, subok=True)
16041584
return value._apply(method, *args, **kwargs)
16051585
else:
1586+
value = np.broadcast_to(value, shape=self.shape, subok=True)
16061587
if callable(method):
16071588
return method(value, *args, **kwargs)
16081589
else:
@@ -1629,24 +1610,23 @@ def apply_method(value):
16291610

16301611
setattr(new, _attr, value)
16311612

1613+
shapes = [
1614+
getattr(new, "_" + attr).shape
1615+
for attr in new.frame_attributes
1616+
if (
1617+
attr not in new._attr_names_with_defaults
1618+
and getattr(getattr(new, "_" + attr), "shape", ())
1619+
)
1620+
]
1621+
16321622
if self.has_data:
16331623
new._data = apply_method(self.data)
1624+
if getattr(new._data, "shape", ()):
1625+
shapes.append(new._data.shape)
16341626
else:
16351627
new._data = None
1636-
shapes = [
1637-
getattr(new, "_" + attr).shape
1638-
for attr in new.frame_attributes
1639-
if (
1640-
attr not in new._attr_names_with_defaults
1641-
and getattr(getattr(new, "_" + attr), "shape", ())
1642-
)
1643-
]
1644-
if shapes:
1645-
new._no_data_shape = (
1646-
check_broadcast(*shapes) if len(shapes) > 1 else shapes[0]
1647-
)
1648-
else:
1649-
new._no_data_shape = ()
1628+
1629+
new._shape = check_broadcast(*shapes)
16501630

16511631
return new
16521632

‎astropy/coordinates/tests/test_frames.py‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -753,12 +753,12 @@ def test_time_inputs():
753753
c = FK4(1 * u.deg, 2 * u.deg, obstime="hello")
754754
assert "Invalid time input" in str(err.value)
755755

756-
# A vector time should work if the shapes match, but we don't automatically
757-
# broadcast the basic data (just like time).
758-
FK4([1, 2] * u.deg, [2, 3] * u.deg, obstime=["J2000", "J2001"])
759-
with pytest.raises(ValueError) as err:
760-
FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"])
761-
assert "shape" in str(err.value)
756+
# A vector time should work if the shapes match, and we automatically
757+
# broadcast the basic data.
758+
c = FK4([1, 2] * u.deg, [2, 3] * u.deg, obstime=["J2000", "J2001"])
759+
assert c.shape == (2,)
760+
c = FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"])
761+
assert c.shape == (2,)
762762

763763

764764
def test_is_frame_attr_default():
@@ -1676,3 +1676,49 @@ def test_frame_coord_comparison():
16761676
error_msg = "Can only compare SkyCoord to Frame with data"
16771677
with pytest.raises(ValueError, match=error_msg):
16781678
frame == coord # noqa: B015
1679+
1680+
1681+
@pytest.mark.parametrize(
1682+
["s1", "s2"],
1683+
(
1684+
((1,), (1,)),
1685+
((2,), (1,)),
1686+
((1,), (2,)),
1687+
((2,), (2,)),
1688+
((2, 1), (1,)),
1689+
((1,), (2, 1)),
1690+
((2, 1), (1, 3)),
1691+
),
1692+
)
1693+
def test_altaz_broadcast(s1, s2):
1694+
"""Note: Regression test for #5982"""
1695+
where = EarthLocation.from_geodetic(lat=45 * u.deg, lon=30 * u.deg, height=0 * u.m)
1696+
time = Time(np.full(s1, 58000.0), format="mjd")
1697+
angle = np.full(s2, 45.0) * u.deg
1698+
result = AltAz(alt=angle, az=angle, obstime=time, location=where)
1699+
assert result.shape == np.broadcast_shapes(s1, s2)
1700+
1701+
1702+
def test_transform_altaz_array_obstime():
1703+
"""Note: Regression test for #12965"""
1704+
obstime = Time("2010-01-01T00:00:00")
1705+
location = EarthLocation(0 * u.deg, 0 * u.deg, 0 * u.m)
1706+
1707+
frame1 = AltAz(location=location, obstime=obstime)
1708+
coord1 = SkyCoord(alt=80 * u.deg, az=0 * u.deg, frame=frame1)
1709+
1710+
obstimes = obstime + np.linspace(0, 15, 50) * u.min
1711+
frame2 = AltAz(location=location, obstime=obstimes)
1712+
coord2 = SkyCoord(alt=coord1.alt, az=coord1.az, frame=frame2)
1713+
assert np.all(coord2.alt == 80 * u.deg)
1714+
assert np.all(coord2.az == 0 * u.deg)
1715+
1716+
# test transformation to ICRS works
1717+
assert len(coord2.icrs) == 50
1718+
1719+
1720+
def test_spherical_offsets_by_broadcast():
1721+
"""Note: Regression test for #14383"""
1722+
assert SkyCoord(
1723+
ra=np.array([123, 134, 145]), dec=np.array([45, 56, 67]), unit=u.deg
1724+
).spherical_offsets_by(2 * u.deg, 2 * u.deg).shape == (3,)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Support Numpy broadcasting over frame data and attributes. See
2+
:ref:`whatsnew-6.0-broadcasting-frame-attributes`.

‎docs/coordinates/performance.inc.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ coordinate::
1515

1616
>>> coord = SkyCoord(ra_array, dec_array, unit='deg') # doctest: +SKIP
1717

18+
Frame attributes can be arrays too, as long as the coordinate data and all of
19+
the frame attributes have shapes that are compatible according to
20+
:doc:`Numpy broadcasting rules <numpy:user/basics.broadcasting>`::
21+
22+
>>> coord = FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"]) # doctest: +SKIP
23+
1824
In addition, looping over a |SkyCoord| object can be slow. If you need to
1925
transform the coordinates to a different frame, it is much faster to transform a
2026
single |SkyCoord| with arrays of values as opposed to looping over the

‎docs/whatsnew/6.0.rst‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ the 5.3 release.
1313
In particular, this release includes:
1414

1515
* :ref:`whatsnew-6.0-geodetic-representation-geometry`
16+
* :ref:`whatsnew-6.0-broadcasting-frame-attributes`
1617
* :ref:`whatsnew-6.0-cosmology-latex-export`
1718
* :ref:`whatsnew-6.0-iers-data`
1819

@@ -59,6 +60,63 @@ bodies by subclassing `~astropy.coordinates.BaseGeodeticRepresentation` or
5960
See :ref:`astropy-coordinates-create-geodetic` for more details.
6061

6162

63+
.. _whatsnew-6.0-broadcasting-frame-attributes:
64+
65+
Support for Numpy broadcasting over frame data and attributes
66+
=============================================================
67+
68+
Frames in `astropy.coordinates` now support
69+
:doc:`Numpy broadcasting rules <numpy:user/basics.broadcasting>` over both
70+
frame data and frame attributes. Previously, broadcasting was only supported
71+
over framed data. This makes it much easier and faster to do positional
72+
astronomy calculations and transformations on sweeps of parameters.
73+
74+
For example, the user can now create frame objects with scalar data but vector
75+
frame attributes, such as::
76+
77+
from astropy.coordinates import FK4
78+
from astropy import units as u
79+
80+
FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"])
81+
82+
But where this really shines is doing fast observability calculations over
83+
arrays. The following example constructs an `~astropy.coordinates.EarthLocation`
84+
array of length :samp:`{L}`, a `~astropy.coordinates.SkyCoord` array of length
85+
:samp:`{M}`, and a `~astropy.time.Time` array of length :samp:`N`. It uses
86+
Numpy broadcasting rules to evaluate a boolean array of shape
87+
:samp:`({L}, {M}, {N})` that is `True` for those observing locations, times,
88+
and sky coordinates, for which the target is above an altitude limit::
89+
90+
from astropy.coordinates import EarthLocation, AltAz, SkyCoord
91+
from astropy.coordinates.angle_utilities import uniform_spherical_random_surface
92+
from astropy.time import Time
93+
from astropy import units as u
94+
import numpy as np
95+
96+
L = 25
97+
M = 100
98+
N = 50
99+
100+
# Earth locations of length
101+
c = uniform_spherical_random_surface(L)
102+
locations = EarthLocation.from_geodetic(c.lon, c.lat)
103+
104+
# Celestial coordinates of length M
105+
coords = SkyCoord(uniform_spherical_random_surface(M))
106+
107+
# Observation times of length N
108+
obstimes = Time('2023-08-04') + np.linspace(0, 24, N) * u.hour
109+
110+
# AltAz coordinates of shape (L, M, N)
111+
frame = AltAz(
112+
location=locations[:, np.newaxis, np.newaxis],
113+
obstime=obstimes[np.newaxis, np.newaxis, :])
114+
altaz = coords[np.newaxis, :, np.newaxis].transform_to(frame)
115+
116+
min_altitude = 30 * u.deg
117+
is_above_altitude_limit = (altaz.alt > min_altitude)
118+
119+
62120
.. _whatsnew-6.0-cosmology-latex-export:
63121

64122
Updates to `~astropy.cosmology`

0 commit comments

Comments
 (0)