Skip to content

Commit 1f3a2b6

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 dac44e8 commit 1f3a2b6

5 files changed

Lines changed: 144 additions & 51 deletions

File tree

‎astropy/coordinates/baseframe.py‎

Lines changed: 25 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -333,36 +333,15 @@ def __init__(
333333
f"keywords: {list(kwargs)}"
334334
)
335335

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

367346
# The logic of this block is not related to the previous one
368347
if self._data is not None:
@@ -721,7 +700,7 @@ def has_data(self):
721700

722701
@property
723702
def shape(self):
724-
return self.data.shape if self.has_data else self._no_data_shape
703+
return self._shape
725704

726705
# We have to override the ShapedLikeNDArray definitions, since our shape
727706
# does not have to be that of the data.
@@ -1597,8 +1576,10 @@ def _apply(self, method, *args, **kwargs):
15971576

15981577
def apply_method(value):
15991578
if isinstance(value, ShapedLikeNDArray):
1579+
value = value._apply(np.broadcast_to, shape=self.shape, subok=True)
16001580
return value._apply(method, *args, **kwargs)
16011581
else:
1582+
value = np.broadcast_to(value, shape=self.shape, subok=True)
16021583
if callable(method):
16031584
return method(value, *args, **kwargs)
16041585
else:
@@ -1625,24 +1606,23 @@ def apply_method(value):
16251606

16261607
setattr(new, _attr, value)
16271608

1609+
shapes = [
1610+
getattr(new, "_" + attr).shape
1611+
for attr in new.frame_attributes
1612+
if (
1613+
attr not in new._attr_names_with_defaults
1614+
and getattr(getattr(new, "_" + attr), "shape", ())
1615+
)
1616+
]
1617+
16281618
if self.has_data:
16291619
new._data = apply_method(self.data)
1620+
if getattr(new._data, "shape", ()):
1621+
shapes.append(new._data.shape)
16301622
else:
16311623
new._data = None
1632-
shapes = [
1633-
getattr(new, "_" + attr).shape
1634-
for attr in new.frame_attributes
1635-
if (
1636-
attr not in new._attr_names_with_defaults
1637-
and getattr(getattr(new, "_" + attr), "shape", ())
1638-
)
1639-
]
1640-
if shapes:
1641-
new._no_data_shape = (
1642-
check_broadcast(*shapes) if len(shapes) > 1 else shapes[0]
1643-
)
1644-
else:
1645-
new._no_data_shape = ()
1624+
1625+
new._shape = check_broadcast(*shapes)
16461626

16471627
return new
16481628

‎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: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ In particular, this release includes:
1414

1515
* :ref:`whatsnew-6.0-geodetic-representation-geometry`
1616
* :ref:`whatsnew-6.0-planetary-wcs-bodyfixed`
17+
* :ref:`whatsnew-6.0-broadcasting-frame-attributes`
1718
* :ref:`whatsnew-6.0-cosmology-latex-export`
1819
* :ref:`whatsnew-6.0-iers-data`
1920

@@ -74,6 +75,64 @@ See :ref:`creating_planetary_wcs` for an example.
7475
Planetary images or spectral cube WCS description can be manipulated using the
7576
:mod:`~astropy.wcs` module.
7677

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

79138
Updates to `~astropy.cosmology`

0 commit comments

Comments
 (0)