Skip to content

Commit aa1989c

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 312a417 commit aa1989c

3 files changed

Lines changed: 115 additions & 51 deletions

File tree

‎astropy/coordinates/baseframe.py‎

Lines changed: 27 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -337,36 +337,17 @@ 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 = [
341+
value.shape for value in values.values() if getattr(value, "shape", ())
342+
]
343+
if self._data is not None and getattr(self._data, "shape", ()):
344+
shapes.append(self._data.shape)
345+
try:
346+
self._shape = check_broadcast(*shapes)
347+
except ValueError as err:
348+
raise ValueError(
349+
f"non-scalar attributes with inconsistent shapes: {shapes}"
350+
) from err
370351

371352
# The logic of this block is not related to the previous one
372353
if self._data is not None:
@@ -725,7 +706,7 @@ def has_data(self):
725706

726707
@property
727708
def shape(self):
728-
return self.data.shape if self.has_data else self._no_data_shape
709+
return self._shape
729710

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

16021583
def apply_method(value):
16031584
if isinstance(value, ShapedLikeNDArray):
1585+
value = value._apply(np.broadcast_to, shape=self.shape, subok=True)
16041586
return value._apply(method, *args, **kwargs)
16051587
else:
1588+
value = np.broadcast_to(value, shape=self.shape, subok=True)
16061589
if callable(method):
16071590
return method(value, *args, **kwargs)
16081591
else:
@@ -1629,24 +1612,23 @@ def apply_method(value):
16291612

16301613
setattr(new, _attr, value)
16311614

1615+
shapes = [
1616+
getattr(new, "_" + attr).shape
1617+
for attr in new.frame_attributes
1618+
if (
1619+
attr not in new._attr_names_with_defaults
1620+
and getattr(getattr(new, "_" + attr), "shape", ())
1621+
)
1622+
]
1623+
16321624
if self.has_data:
16331625
new._data = apply_method(self.data)
1626+
if getattr(new._data, "shape", ()):
1627+
shapes.append(new._data.shape)
16341628
else:
16351629
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 = ()
1630+
1631+
new._shape = check_broadcast(*shapes)
16501632

16511633
return new
16521634

‎astropy/coordinates/tests/test_frames.py‎

Lines changed: 51 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,48 @@ 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(np.prod(s1), 58000.0).reshape(s1), format="mjd")
1697+
angle = np.full(np.prod(s2), 45.0).reshape(s2) * u.deg
1698+
AltAz(alt=angle, az=angle, obstime=time, location=where)
1699+
1700+
1701+
def test_transform_altaz_array_obstime():
1702+
"""Note: Regression test for #12965"""
1703+
obstime = Time("2010-01-01T00:00:00")
1704+
location = EarthLocation(0 * u.deg, 0 * u.deg, 0 * u.m)
1705+
1706+
frame1 = AltAz(location=location, obstime=obstime)
1707+
coord1 = SkyCoord(alt=80 * u.deg, az=0 * u.deg, frame=frame1)
1708+
1709+
obstimes = obstime + np.linspace(0, 15, 50) * u.min
1710+
frame2 = AltAz(location=location, obstime=obstimes)
1711+
coord2 = SkyCoord(alt=coord1.alt, az=coord1.az, frame=frame2)
1712+
assert np.all(coord2.alt == 80 * u.deg)
1713+
assert np.all(coord2.az == 0 * u.deg)
1714+
1715+
# test transformation to ICRS works
1716+
assert len(coord2.icrs) == 50
1717+
1718+
1719+
def test_spherical_offsets_by_broadcast():
1720+
"""Note: Regression test for #14383"""
1721+
assert SkyCoord(
1722+
ra=np.array([123, 134, 145]), dec=np.array([45, 56, 67]), unit=u.deg
1723+
).spherical_offsets_by(2 * u.deg, 2 * u.deg).shape == (3,)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
Support Numpy broadcasting over frame data and attributes.
2+
3+
For example, you can now create frame objects with scalar data but vector frame
4+
attributes, such as::
5+
6+
FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"])
7+
8+
This is very useful for doing fast observability calculations over sweeps of
9+
parameters, for instance::
10+
11+
from astropy.coordinates import EarthLocation, AltAz, SkyCoord
12+
from astropy.coordinates.angle_utilities import uniform_spherical_random_surface
13+
from astropy.time import Time
14+
from astropy import units as u
15+
import numpy as np
16+
17+
L = 25
18+
N = 100
19+
M = 50
20+
21+
# Earth locations of length
22+
c = uniform_spherical_random_surface(L)
23+
locations = EarthLocation.from_geodetic(c.lon, c.lat)
24+
25+
# Celestial coordinates of length M
26+
coords = SkyCoord(uniform_spherical_random_surface(M))
27+
28+
# Observation times of length M
29+
obstimes = Time('2023-08-04') + np.linspace(0, 24, N) * u.hour
30+
31+
# AltAz coordinatdes of shape (L, M, N)
32+
frame = AltAz(
33+
location=locations[:, np.newaxis, np.newaxis],
34+
obstime=obstimes[np.newaxis, :, np.newaxis])
35+
altaz = coords[np.newaxis, np.newaxis, :].transform_to(frame)
36+
37+
is_above_elevation_limit = (altaz.alt > 15 * u.deg)

0 commit comments

Comments
 (0)