response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
A slightly modified version of the ERFA function ``eraAticq``.
``eraAticq`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
There are two issues with the version of aticq in ERFA. Both are associated
with the handling of light deflection.
The companion function ``eraAtciqz`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
In addition, ERFA's aticq assumes a distant source, so there is no difference between
the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a
few arcseconds in the worst case (e.g a Venus transit).
Parameters
----------
srepr : `~astropy.coordinates.SphericalRepresentation`
Astrometric GCRS or CIRS position of object from observer
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
-------
rc : float or `~numpy.ndarray`
Right Ascension in radians
dc : float or `~numpy.ndarray`
Declination in radians | def aticq(srepr, astrom):
"""
A slightly modified version of the ERFA function ``eraAticq``.
``eraAticq`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
There are two issues with the version of aticq in ERFA. Both are associated
with the handling of light deflection.
The companion function ``eraAtciqz`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
In addition, ERFA's aticq assumes a distant source, so there is no difference between
the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a
few arcseconds in the worst case (e.g a Venus transit).
Parameters
----------
srepr : `~astropy.coordinates.SphericalRepresentation`
Astrometric GCRS or CIRS position of object from observer
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
-------
rc : float or `~numpy.ndarray`
Right Ascension in radians
dc : float or `~numpy.ndarray`
Declination in radians
"""
# ignore parallax effects if no distance, or far away
srepr_distance = srepr.distance
ignore_distance = srepr_distance.unit == u.one
# RA, Dec to cartesian unit vectors
pos = erfa.s2c(srepr.lon.radian, srepr.lat.radian)
# Bias-precession-nutation, giving GCRS proper direction.
ppr = erfa.trxp(astrom["bpn"], pos)
# Aberration, giving GCRS natural direction
d = np.zeros_like(ppr)
for j in range(2):
before = norm(ppr - d)
after = erfa.ab(before, astrom["v"], astrom["em"], astrom["bm1"])
d = after - before
pnat = norm(ppr - d)
# Light deflection by the Sun, giving BCRS coordinate direction
d = np.zeros_like(pnat)
for j in range(5):
before = norm(pnat - d)
if ignore_distance:
# No distance to object, assume a long way away
q = before
else:
# Find BCRS direction of Sun to object.
# astrom['eh'] and astrom['em'] contain Sun to observer unit vector,
# and distance, respectively.
eh = astrom["em"][..., np.newaxis] * astrom["eh"]
# unit vector from Sun to object
q = eh + srepr_distance[..., np.newaxis].to_value(u.au) * before
sundist, q = erfa.pn(q)
sundist = sundist[..., np.newaxis]
# calculation above is extremely unstable very close to the sun
# in these situations, default back to ldsun-style behaviour,
# since this is reversible and drops to zero within stellar limb
q = np.where(sundist > 1.0e-10, q, before)
after = erfa.ld(1.0, before, q, astrom["eh"], astrom["em"], 1e-6)
d = after - before
pco = norm(pnat - d)
# ICRS astrometric RA, Dec
rc, dc = erfa.c2s(pco)
return erfa.anp(rc), dc |
A slightly modified version of the ERFA function ``eraAtciqz``.
``eraAtciqz`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
There are two issues with the version of atciqz in ERFA. Both are associated
with the handling of light deflection.
The companion function ``eraAticq`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
In addition, ERFA's atciqz assumes a distant source, so there is no difference between
the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a
few arcseconds in the worst case (e.g a Venus transit).
Parameters
----------
srepr : `~astropy.coordinates.SphericalRepresentation`
Astrometric ICRS position of object from observer
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
-------
ri : float or `~numpy.ndarray`
Right Ascension in radians
di : float or `~numpy.ndarray`
Declination in radians | def atciqz(srepr, astrom):
"""
A slightly modified version of the ERFA function ``eraAtciqz``.
``eraAtciqz`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
There are two issues with the version of atciqz in ERFA. Both are associated
with the handling of light deflection.
The companion function ``eraAticq`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
In addition, ERFA's atciqz assumes a distant source, so there is no difference between
the object-Sun vector and the observer-Sun vector. This can lead to errors of up to a
few arcseconds in the worst case (e.g a Venus transit).
Parameters
----------
srepr : `~astropy.coordinates.SphericalRepresentation`
Astrometric ICRS position of object from observer
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
-------
ri : float or `~numpy.ndarray`
Right Ascension in radians
di : float or `~numpy.ndarray`
Declination in radians
"""
# ignore parallax effects if no distance, or far away
srepr_distance = srepr.distance
ignore_distance = srepr_distance.unit == u.one
# BCRS coordinate direction (unit vector).
pco = erfa.s2c(srepr.lon.radian, srepr.lat.radian)
# Find BCRS direction of Sun to object
if ignore_distance:
# No distance to object, assume a long way away
q = pco
else:
# Find BCRS direction of Sun to object.
# astrom['eh'] and astrom['em'] contain Sun to observer unit vector,
# and distance, respectively.
eh = astrom["em"][..., np.newaxis] * astrom["eh"]
# unit vector from Sun to object
q = eh + srepr_distance[..., np.newaxis].to_value(u.au) * pco
sundist, q = erfa.pn(q)
sundist = sundist[..., np.newaxis]
# calculation above is extremely unstable very close to the sun
# in these situations, default back to ldsun-style behaviour,
# since this is reversible and drops to zero within stellar limb
q = np.where(sundist > 1.0e-10, q, pco)
# Light deflection by the Sun, giving BCRS natural direction.
pnat = erfa.ld(1.0, pco, q, astrom["eh"], astrom["em"], 1e-6)
# Aberration, giving GCRS proper direction.
ppr = erfa.ab(pnat, astrom["v"], astrom["em"], astrom["bm1"])
# Bias-precession-nutation, giving CIRS proper direction.
# Has no effect if matrix is identity matrix, in which case gives GCRS ppr.
pi = erfa.rxp(astrom["bpn"], ppr)
# CIRS (GCRS) RA, Dec
ri, di = erfa.c2s(pi)
return erfa.anp(ri), di |
Get barycentric position and velocity, and heliocentric position of Earth.
Parameters
----------
time : `~astropy.time.Time`
time at which to calculate position and velocity of Earth
Returns
-------
earth_pv : `np.ndarray`
Barycentric position and velocity of Earth, in au and au/day
earth_helio : `np.ndarray`
Heliocentric position of Earth in au | def prepare_earth_position_vel(time):
"""
Get barycentric position and velocity, and heliocentric position of Earth.
Parameters
----------
time : `~astropy.time.Time`
time at which to calculate position and velocity of Earth
Returns
-------
earth_pv : `np.ndarray`
Barycentric position and velocity of Earth, in au and au/day
earth_helio : `np.ndarray`
Heliocentric position of Earth in au
"""
# this goes here to avoid circular import errors
from astropy.coordinates.solar_system import (
get_body_barycentric,
get_body_barycentric_posvel,
solar_system_ephemeris,
)
# get barycentric position and velocity of earth
ephemeris = solar_system_ephemeris.get()
# if we are using the builtin erfa based ephemeris,
# we can use the fact that epv00 already provides all we need.
# This avoids calling epv00 twice, once
# in get_body_barycentric_posvel('earth') and once in
# get_body_barycentric('sun')
if ephemeris == "builtin":
jd1, jd2 = get_jd12(time, "tdb")
earth_pv_heliocentric, earth_pv = erfa.epv00(jd1, jd2)
earth_heliocentric = earth_pv_heliocentric["p"]
# all other ephemeris providers probably don't have a shortcut like this
else:
earth_p, earth_v = get_body_barycentric_posvel("earth", time)
# get heliocentric position of earth, preparing it for passing to erfa.
sun = get_body_barycentric("sun", time)
earth_heliocentric = (earth_p - sun).get_xyz(xyz_axis=-1).to_value(u.au)
# Also prepare earth_pv for passing to erfa, which wants it as
# a structured dtype.
earth_pv = pav2pv(
earth_p.get_xyz(xyz_axis=-1).to_value(u.au),
earth_v.get_xyz(xyz_axis=-1).to_value(u.au / u.d),
)
return earth_pv, earth_heliocentric |
Returns the offset of the Sun center from the solar-system barycenter (SSB).
Parameters
----------
time : `~astropy.time.Time`
Time at which to calculate the offset
include_velocity : `bool`
If ``True``, attach the velocity as a differential. Defaults to ``False``.
reverse : `bool`
If ``True``, return the offset of the barycenter from the Sun. Defaults to ``False``.
Returns
-------
`~astropy.coordinates.CartesianRepresentation`
The offset | def get_offset_sun_from_barycenter(time, include_velocity=False, reverse=False):
"""
Returns the offset of the Sun center from the solar-system barycenter (SSB).
Parameters
----------
time : `~astropy.time.Time`
Time at which to calculate the offset
include_velocity : `bool`
If ``True``, attach the velocity as a differential. Defaults to ``False``.
reverse : `bool`
If ``True``, return the offset of the barycenter from the Sun. Defaults to ``False``.
Returns
-------
`~astropy.coordinates.CartesianRepresentation`
The offset
"""
if include_velocity:
# Import here to avoid a circular import
from astropy.coordinates.solar_system import get_body_barycentric_posvel
offset_pos, offset_vel = get_body_barycentric_posvel("sun", time)
if reverse:
offset_pos, offset_vel = -offset_pos, -offset_vel
offset_vel = offset_vel.represent_as(CartesianDifferential)
offset_pos = offset_pos.with_differentials(offset_vel)
else:
# Import here to avoid a circular import
from astropy.coordinates.solar_system import get_body_barycentric
offset_pos = get_body_barycentric("sun", time)
if reverse:
offset_pos = -offset_pos
return offset_pos |
Get the first line of a docstring.
Skips possible empty first lines, and then combine following text until
the first period or a fully empty line. | def _get_doc_header(cls):
"""Get the first line of a docstring.
Skips possible empty first lines, and then combine following text until
the first period or a fully empty line.
"""
out = []
# NOTE: cls.__doc__ is None for -OO flag
if not cls.__doc__:
return ""
for line in cls.__doc__.splitlines():
if line:
parts = line.split(".")
out.append(parts[0].strip())
if len(parts) > 1:
break
elif out:
break
return " ".join(out) + "." |
Generates a string that can be used in other docstrings to include a
transformation graph, showing the available transforms and
coordinate systems.
Parameters
----------
transform_graph : `~astropy.coordinates.TransformGraph`
Returns
-------
docstring : str
A string that can be added to the end of a docstring to show the
transform graph. | def make_transform_graph_docs(transform_graph):
"""
Generates a string that can be used in other docstrings to include a
transformation graph, showing the available transforms and
coordinate systems.
Parameters
----------
transform_graph : `~astropy.coordinates.TransformGraph`
Returns
-------
docstring : str
A string that can be added to the end of a docstring to show the
transform graph.
"""
from textwrap import dedent
coosys = {
(cls := transform_graph.lookup_name(item)).__name__: cls
for item in transform_graph.get_names()
}
# currently, all of the priorities are set to 1, so we don't need to show
# then in the transform graph.
graphstr = transform_graph.to_dot_graph(
addnodes=list(coosys.values()), priorities=False
)
docstr = """
The diagram below shows all of the built in coordinate systems,
their aliases (useful for converting other coordinates to them using
attribute-style access) and the pre-defined transformations between
them. The user is free to override any of these transformations by
defining new transformations between these systems, but the
pre-defined transformations should be sufficient for typical usage.
The color of an edge in the graph (i.e., the transformations between two
frames) is set by the type of transformation; the legend box defines the
mapping from transform class name to color.
.. Wrap the graph in a div with a custom class to allow theming.
.. container:: frametransformgraph
.. graphviz::
"""
docstr = dedent(docstr) + " " + graphstr.replace("\n", "\n ")
# colors are in dictionary mapping transform class to color
from astropy.coordinates.transformations.graph import trans_to_color
html_list_items = []
for cls, color in trans_to_color.items():
block = f"""
<li style='list-style: none;'>
<p style="font-size: 12px;line-height: 24px;font-weight: normal;color: #848484;padding: 0;margin: 0;">
<b>{cls.__name__}:</b>
<span style="font-size: 24px; color: {color};"><b>➝</b></span>
</p>
</li>
"""
html_list_items.append(block)
nl = "\n"
graph_legend = f"""
.. raw:: html
<ul class="cooframelegend">
{nl.join(html_list_items)}
</ul>
"""
docstr = docstr + dedent(graph_legend)
# Add table with built-in frame classes.
template = """
* - `~astropy.coordinates.{}`
- {}
"""
table = """
Built-in Frame Classes
^^^^^^^^^^^^^^^^^^^^^^
.. list-table::
:widths: 20 80
""" + "".join(
template.format(name, _get_doc_header(coosys[name]))
for name in __all__
if name in coosys
)
return docstr + dedent(table) |
Get the fully qualified name of a class. | def _fqn_class(cls):
"""Get the fully qualified name of a class."""
return cls.__module__ + "." + cls.__qualname__ |
Returns a hash value that should be invariable if the
`REPRESENTATION_CLASSES` and `DIFFERENTIAL_CLASSES` dictionaries have not
changed. | def get_reprdiff_cls_hash():
"""
Returns a hash value that should be invariable if the
`REPRESENTATION_CLASSES` and `DIFFERENTIAL_CLASSES` dictionaries have not
changed.
"""
return hash(tuple(REPRESENTATION_CLASSES.items())) + hash(
tuple(DIFFERENTIAL_CLASSES.items())
) |
For given operator, return functions that adjust lon, lat, distance. | def _spherical_op_funcs(op, *args):
"""For given operator, return functions that adjust lon, lat, distance."""
if op is operator.neg:
return lambda x: x + 180 * u.deg, operator.neg, operator.pos
try:
scale_sign = np.sign(args[0])
except Exception:
# This should always work, even if perhaps we get a negative distance.
return operator.pos, operator.pos, lambda x: op(x, *args)
scale = abs(args[0])
return (
lambda x: x + 180 * u.deg * np.signbit(scale_sign),
lambda x: x * scale_sign,
lambda x: op(x, scale),
) |
SkyCoord equality useful for testing. | def skycoord_equal(sc1, sc2):
"""SkyCoord equality useful for testing."""
if not sc1.is_equivalent_frame(sc2):
return False
if sc1.representation_type is not sc2.representation_type:
return False
if sc1.shape != sc2.shape:
return False # Maybe raise ValueError corresponding to future numpy behavior
eq = np.ones(shape=sc1.shape, dtype=bool)
for comp in sc1.data.components:
eq &= getattr(sc1.data, comp) == getattr(sc2.data, comp)
return np.all(eq) |
Tests creating and accessing Angle objects | def test_create_angles():
"""
Tests creating and accessing Angle objects
"""
""" The "angle" is a fundamental object. The internal
representation is stored in radians, but this is transparent to the user.
Units *must* be specified rather than a default value be assumed. This is
as much for self-documenting code as anything else.
Angle objects simply represent a single angular coordinate. More specific
angular coordinates (e.g. Longitude, Latitude) are subclasses of Angle."""
a1 = Angle(54.12412, unit=u.degree)
a2 = Angle("54.12412", unit=u.degree)
a3 = Angle("54:07:26.832", unit=u.degree)
a4 = Angle("54.12412 deg")
a5 = Angle("54.12412 degrees")
a6 = Angle("54.12412°") # because we like Unicode
a8 = Angle("54°07'26.832\"")
a9 = Angle([54, 7, 26.832], unit=u.degree)
assert_allclose(a9.value, [54, 7, 26.832])
assert a9.unit is u.degree
a10 = Angle(3.60827466667, unit=u.hour)
a11 = Angle("3:36:29.7888000120", unit=u.hour)
Angle(0.944644098745, unit=u.radian)
with pytest.raises(u.UnitsError):
Angle(54.12412)
# raises an exception because this is ambiguous
with pytest.raises(u.UnitsError):
Angle(54.12412, unit=u.m)
with pytest.raises(ValueError):
Angle(12.34, unit="not a unit")
a14 = Angle("03h36m29.7888000120") # no trailing 's', but unambiguous
a15 = Angle("5h4m3s") # single digits, no decimal
assert a15.unit == u.hourangle
a16 = Angle("1 d")
a17 = Angle("1 degree")
assert a16.degree == 1
assert a17.degree == 1
a18 = Angle("54 07.4472", unit=u.degree)
a19 = Angle("54:07.4472", unit=u.degree)
a20 = Angle("54d07.4472m", unit=u.degree)
a21 = Angle("3h36m", unit=u.hour)
a22 = Angle("3.6h", unit=u.hour)
a23 = Angle("- 3h", unit=u.hour)
a24 = Angle("+ 3h", unit=u.hour)
a25 = Angle(3.0, unit=u.hour**1)
# ensure the above angles that should match do
assert a1 == a2 == a3 == a4 == a5 == a6 == a8 == a18 == a19 == a20
assert_allclose(a1.radian, a2.radian)
assert_allclose(a2.degree, a3.degree)
assert_allclose(a3.radian, a4.radian)
assert_allclose(a4.radian, a5.radian)
assert_allclose(a5.radian, a6.radian)
assert_allclose(a10.degree, a11.degree)
assert a11 == a14
assert a21 == a22
assert a23 == -a24
assert a24 == a25
# check for illegal ranges / values
with pytest.raises(IllegalSecondError):
Angle("12 32 99", unit=u.degree)
with pytest.raises(IllegalMinuteError):
Angle("12 99 23", unit=u.degree)
with pytest.raises(IllegalSecondError):
Angle("12 32 99", unit=u.hour)
with pytest.raises(IllegalMinuteError):
Angle("12 99 23", unit=u.hour)
with pytest.raises(IllegalHourError):
Angle("99 25 51.0", unit=u.hour)
with pytest.raises(ValueError):
Angle("12 25 51.0xxx", unit=u.hour)
with pytest.raises(ValueError):
Angle("12h34321m32.2s")
assert a1 is not None |
Tests operations on Angle objects | def test_angle_ops():
"""
Tests operations on Angle objects
"""
# Angles can be added and subtracted. Multiplication and division by a
# scalar is also permitted. A negative operator is also valid. All of
# these operate in a single dimension. Attempting to multiply or divide two
# Angle objects will return a quantity. An exception will be raised if it
# is attempted to store output with a non-angular unit in an Angle [#2718].
a1 = Angle(3.60827466667, unit=u.hour)
a2 = Angle("54:07:26.832", unit=u.degree)
a1 + a2 # creates new Angle object
a1 - a2
-a1
assert_allclose((a1 * 2).hour, 2 * 3.6082746666700003)
assert abs((a1 / 3.123456).hour - 3.60827466667 / 3.123456) < 1e-10
# commutativity
assert (2 * a1).hour == (a1 * 2).hour
a3 = Angle(a1) # makes a *copy* of the object, but identical content as a1
assert_allclose(a1.radian, a3.radian)
assert a1 is not a3
a4 = abs(-a1)
assert a4.radian == a1.radian
a5 = Angle(5.0, unit=u.hour)
assert a5 > a1
assert a5 >= a1
assert a1 < a5
assert a1 <= a5
# check operations with non-angular result give Quantity.
a6 = Angle(45.0, u.degree)
a7 = a6 * a5
assert type(a7) is u.Quantity
# but those with angular result yield Angle.
# (a9 is regression test for #5327)
a8 = a1 + 1.0 * u.deg
assert type(a8) is Angle
a9 = 1.0 * u.deg + a1
assert type(a9) is Angle
with pytest.raises(TypeError):
a6 *= a5
with pytest.raises(TypeError):
a6 *= u.m
with pytest.raises(TypeError):
np.sin(a6, out=a6) |
Test unit conversion of Angle objects | def test_angle_convert():
"""
Test unit conversion of Angle objects
"""
angle = Angle("54.12412", unit=u.degree)
assert_allclose(angle.hour, 3.60827466667)
assert_allclose(angle.radian, 0.944644098745)
assert_allclose(angle.degree, 54.12412)
assert len(angle.hms) == 3
assert isinstance(angle.hms, tuple)
assert angle.hms[0] == 3
assert angle.hms[1] == 36
assert_allclose(angle.hms[2], 29.78879999999947)
# also check that the namedtuple attribute-style access works:
assert angle.hms.h == 3
assert angle.hms.m == 36
assert_allclose(angle.hms.s, 29.78879999999947)
assert len(angle.dms) == 3
assert isinstance(angle.dms, tuple)
assert angle.dms[0] == 54
assert angle.dms[1] == 7
assert_allclose(angle.dms[2], 26.831999999992036)
# also check that the namedtuple attribute-style access works:
assert angle.dms.d == 54
assert angle.dms.m == 7
assert_allclose(angle.dms.s, 26.831999999992036)
assert isinstance(angle.dms[0], float)
assert isinstance(angle.hms[0], float)
# now make sure dms and signed_dms work right for negative angles
negangle = Angle("-54.12412", unit=u.degree)
assert negangle.dms.d == -54
assert negangle.dms.m == -7
assert_allclose(negangle.dms.s, -26.831999999992036)
assert negangle.signed_dms.sign == -1
assert negangle.signed_dms.d == 54
assert negangle.signed_dms.m == 7
assert_allclose(negangle.signed_dms.s, 26.831999999992036) |
Tests string formatting for Angle objects | def test_angle_formatting():
"""
Tests string formatting for Angle objects
"""
"""
The string method of Angle has this signature:
def string(self, unit=DEGREE, decimal=False, sep=" ", precision=5,
pad=False):
The "decimal" parameter defaults to False since if you need to print the
Angle as a decimal, there's no need to use the "format" method (see
above).
"""
angle = Angle("54.12412", unit=u.degree)
# __str__ is the default `format`
assert str(angle) == angle.to_string()
res = "Angle as HMS: 3h36m29.7888s"
assert f"Angle as HMS: {angle.to_string(unit=u.hour)}" == res
res = "Angle as HMS: 3:36:29.7888"
assert f"Angle as HMS: {angle.to_string(unit=u.hour, sep=':')}" == res
res = "Angle as HMS: 3:36:29.79"
assert f"Angle as HMS: {angle.to_string(unit=u.hour, sep=':', precision=2)}" == res
# Note that you can provide one, two, or three separators passed as a
# tuple or list
res = "Angle as HMS: 3h36m29.7888s"
assert (
"Angle as HMS:"
f" {angle.to_string(unit=u.hour, sep=('h', 'm', 's'), precision=4)}" == res
)
res = "Angle as HMS: 3-36|29.7888"
assert (
f"Angle as HMS: {angle.to_string(unit=u.hour, sep=['-', '|'], precision=4)}"
== res
)
res = "Angle as HMS: 3-36-29.7888"
assert f"Angle as HMS: {angle.to_string(unit=u.hour, sep='-', precision=4)}" == res
res = "Angle as HMS: 03h36m29.7888s"
assert f"Angle as HMS: {angle.to_string(unit=u.hour, precision=4, pad=True)}" == res
# Same as above, in degrees
angle = Angle("3 36 29.78880", unit=u.degree)
res = "Angle as DMS: 3d36m29.7888s"
assert f"Angle as DMS: {angle.to_string(unit=u.degree)}" == res
res = "Angle as DMS: 3:36:29.7888"
assert f"Angle as DMS: {angle.to_string(unit=u.degree, sep=':')}" == res
res = "Angle as DMS: 3:36:29.79"
assert (
f"Angle as DMS: {angle.to_string(unit=u.degree, sep=':', precision=2)}" == res
)
# Note that you can provide one, two, or three separators passed as a
# tuple or list
res = "Angle as DMS: 3d36m29.7888s"
assert (
f"Angle as DMS: {angle.to_string(unit=u.deg, sep=('d', 'm', 's'), precision=4)}"
== res
)
res = "Angle as DMS: 3-36|29.7888"
assert (
f"Angle as DMS: {angle.to_string(unit=u.degree, sep=['-', '|'], precision=4)}"
== res
)
res = "Angle as DMS: 3-36-29.7888"
assert (
f"Angle as DMS: {angle.to_string(unit=u.degree, sep='-', precision=4)}" == res
)
res = "Angle as DMS: 03d36m29.7888s"
assert (
f"Angle as DMS: {angle.to_string(unit=u.degree, precision=4, pad=True)}" == res
)
res = "Angle as rad: 0.0629763 rad"
assert f"Angle as rad: {angle.to_string(unit=u.radian)}" == res
res = "Angle as rad decimal: 0.0629763"
assert (
f"Angle as rad decimal: {angle.to_string(unit=u.radian, decimal=True)}" == res
)
# check negative angles
angle = Angle(-1.23456789, unit=u.degree)
angle2 = Angle(-1.23456789, unit=u.hour)
assert angle.to_string() == "-1d14m04.444404s"
assert angle.to_string(pad=True) == "-01d14m04.444404s"
assert angle.to_string(unit=u.hour) == "-0h04m56.2962936s"
assert angle2.to_string(unit=u.hour, pad=True) == "-01h14m04.444404s"
assert angle.to_string(unit=u.radian, decimal=True) == "-0.0215473"
# We should recognize units that are equal but not identical
assert angle.to_string(unit=u.hour**1) == "-0h04m56.2962936s" |
Ensures that the string representation of an angle can be used to create a
new valid Angle. | def test_angle_format_roundtripping():
"""
Ensures that the string representation of an angle can be used to create a
new valid Angle.
"""
a1 = Angle(0, unit=u.radian)
a2 = Angle(10, unit=u.degree)
a3 = Angle(0.543, unit=u.degree)
a4 = Angle("1d2m3.4s")
assert Angle(str(a1)).degree == a1.degree
assert Angle(str(a2)).degree == a2.degree
assert Angle(str(a3)).degree == a3.degree
assert Angle(str(a4)).degree == a4.degree
# also check Longitude/Latitude
ra = Longitude("1h2m3.4s")
dec = Latitude("1d2m3.4s")
assert_allclose(Angle(str(ra)).degree, ra.degree)
assert_allclose(Angle(str(dec)).degree, dec.degree) |
Tests creation/operations of Longitude and Latitude objects | def test_radec():
"""
Tests creation/operations of Longitude and Latitude objects
"""
"""
Longitude and Latitude are objects that are subclassed from Angle. As with Angle, Longitude
and Latitude can parse any unambiguous format (tuples, formatted strings, etc.).
The intention is not to create an Angle subclass for every possible
coordinate object (e.g. galactic l, galactic b). However, equatorial Longitude/Latitude
are so prevalent in astronomy that it's worth creating ones for these
units. They will be noted as "special" in the docs and use of the just the
Angle class is to be used for other coordinate systems.
"""
with pytest.raises(u.UnitsError):
Longitude("4:08:15.162342") # error - hours or degrees?
with pytest.raises(u.UnitsError):
Longitude("-4:08:15.162342")
# the "smart" initializer allows >24 to automatically do degrees, but the
# Angle-based one does not
# TODO: adjust in 0.3 for whatever behavior is decided on
# ra = Longitude("26:34:15.345634") # unambiguous b/c hours don't go past 24
# assert_allclose(ra.degree, 26.570929342)
with pytest.raises(u.UnitsError):
Longitude("26:34:15.345634")
# ra = Longitude(68)
with pytest.raises(u.UnitsError):
Longitude(68)
with pytest.raises(u.UnitsError):
Longitude(12)
with pytest.raises(ValueError):
Longitude("garbage containing a d and no units")
ra = Longitude("12h43m23s")
assert_allclose(ra.hour, 12.7230555556)
# Units can be specified
ra = Longitude("4:08:15.162342", unit=u.hour)
# TODO: this was the "smart" initializer behavior - adjust in 0.3 appropriately
# Where Longitude values are commonly found in hours or degrees, declination is
# nearly always specified in degrees, so this is the default.
# dec = Latitude("-41:08:15.162342")
with pytest.raises(u.UnitsError):
Latitude("-41:08:15.162342")
dec = Latitude("-41:08:15.162342", unit=u.degree) |
Test that angles above 360 degrees can be output as strings,
in repr, str, and to_string. (regression test for #1413) | def test_large_angle_representation():
"""Test that angles above 360 degrees can be output as strings,
in repr, str, and to_string. (regression test for #1413)"""
a = Angle(350, u.deg) + Angle(350, u.deg)
a.to_string()
a.to_string(u.hourangle)
repr(a)
repr(a.to(u.hourangle))
str(a)
str(a.to(u.hourangle)) |
Creating an angle from an (h,m,s) tuple should fail. | def test_create_tuple_fail(angle_class, unit):
"""Creating an angle from an (h,m,s) tuple should fail."""
with pytest.raises(TypeError, match="no longer supported"):
angle_class((12, 14, 52), unit=unit) |
Regression test for subtle bugs from situations where an Angle is
created via numpy channels that don't do the standard __new__ but instead
depend on array_finalize to set state. Longitude is used because the
bug was in its _wrap_angle not getting initialized correctly | def test_wrap_at_without_new():
"""
Regression test for subtle bugs from situations where an Angle is
created via numpy channels that don't do the standard __new__ but instead
depend on array_finalize to set state. Longitude is used because the
bug was in its _wrap_angle not getting initialized correctly
"""
l1 = Longitude([1] * u.deg)
l2 = Longitude([2] * u.deg)
l = np.concatenate([l1, l2])
assert l._wrap_angle is not None |
Check the __str__ method used in printing the Angle | def test__str__():
"""
Check the __str__ method used in printing the Angle
"""
# scalar angle
scangle = Angle("10.2345d")
strscangle = scangle.__str__()
assert strscangle == "10d14m04.2s"
# non-scalar array angles
arrangle = Angle(["10.2345d", "-20d"])
strarrangle = arrangle.__str__()
assert strarrangle == "[10d14m04.2s -20d00m00s]"
# summarizing for large arrays, ... should appear
bigarrangle = Angle(np.ones(10000), u.deg)
assert "..." in bigarrangle.__str__() |
Check the _repr_latex_ method, used primarily by IPython notebooks | def test_repr_latex():
"""
Check the _repr_latex_ method, used primarily by IPython notebooks
"""
# try with both scalar
scangle = Angle(2.1, u.deg)
rlscangle = scangle._repr_latex_()
# and array angles
arrangle = Angle([1, 2.1], u.deg)
rlarrangle = arrangle._repr_latex_()
assert rlscangle == r"$2^\circ06{}^\prime00{}^{\prime\prime}$"
assert rlscangle.split("$")[1] in rlarrangle
# make sure the ... appears for large arrays
bigarrangle = Angle(np.ones(50000) / 50000.0, u.deg)
assert "..." in bigarrangle._repr_latex_() |
Regression test for #5350
Especially the example in
https://github.com/astropy/astropy/issues/5350#issuecomment-248770151 | def test_angle_with_cds_units_enabled():
"""Regression test for #5350
Especially the example in
https://github.com/astropy/astropy/issues/5350#issuecomment-248770151
"""
# the problem is with the parser, so remove it temporarily
from astropy.coordinates.angles.formats import _AngleParser
from astropy.units import cds
del _AngleParser._thread_local._parser
with cds.enable():
Angle("5d")
del _AngleParser._thread_local._parser
Angle("5d") |
Regression test for issue #7168 | def test_angle_multithreading():
"""
Regression test for issue #7168
"""
angles = ["00:00:00"] * 10000
def parse_test(i=0):
Angle(angles, unit="hour")
for i in range(10):
threading.Thread(target=parse_test, args=(i,)).start() |
Regression test for issue #11473 | def test_str_repr_angles_nan(cls, input, expstr, exprepr):
"""
Regression test for issue #11473
"""
q = cls(input)
assert str(q) == expstr
# Deleting whitespaces since repr appears to be adding them for some values
# making the test fail.
assert repr(q).replace(" ", "") == f"<{cls.__name__}{exprepr}>".replace(" ", "") |
Test that the wrapping of the Longitude value range in radians works
in both float32 and float64. | def test_longitude_wrap(value, expected_value, dtype, expected_dtype, sign):
"""
Test that the wrapping of the Longitude value range in radians works
in both float32 and float64.
"""
# This prevents upcasting to float64 as sign * value would do.
if sign < 0:
value = -value
expected_value = -expected_value
result = Longitude(value, u.rad, dtype=dtype)
assert result.value == expected_value
assert result.dtype == expected_dtype
assert result.unit == u.rad |
Test that the validation of the Latitude value range in radians works
in both float32 and float64.
As discussed in issue #13708, before, the float32 representation of pi/2
was rejected as invalid because the comparison always used the float64
representation. | def test_latitude_limits(value, expected_value, dtype, expected_dtype, sign):
"""
Test that the validation of the Latitude value range in radians works
in both float32 and float64.
As discussed in issue #13708, before, the float32 representation of pi/2
was rejected as invalid because the comparison always used the float64
representation.
"""
# this prevents upcasting to float64 as sign * value would do
if sign < 0:
value = -value
expected_value = -expected_value
result = Latitude(value, u.rad, dtype=dtype)
assert result.value == expected_value
assert result.dtype == expected_dtype
assert result.unit == u.rad |
Test that values slightly larger than pi/2 are rejected for different dtypes.
Test cases for issue #13708 | def test_latitude_out_of_limits(value, dtype):
"""
Test that values slightly larger than pi/2 are rejected for different dtypes.
Test cases for issue #13708
"""
with pytest.raises(ValueError, match=r"Latitude angle\(s\) must be within.*"):
Latitude(value, u.rad, dtype=dtype) |
Ensure that after pickling we can still do to_string on hourangle.
Regression test for gh-13923. | def test_angle_pickle_to_string():
"""
Ensure that after pickling we can still do to_string on hourangle.
Regression test for gh-13923.
"""
angle = Angle(0.25 * u.hourangle)
expected = angle.to_string()
via_pickle = pickle.loads(pickle.dumps(angle))
via_pickle_string = via_pickle.to_string() # This used to fail.
assert via_pickle_string == expected |
Tests that the angular separation object also behaves correctly. | def test_angsep():
"""
Tests that the angular separation object also behaves correctly.
"""
from astropy.coordinates import angular_separation
# check it both works with floats in radians, Quantities, or Angles
for conv in (np.deg2rad, lambda x: u.Quantity(x, "deg"), lambda x: Angle(x, "deg")):
for (lon1, lat1, lon2, lat2), corrsep in zip(coords, correct_seps):
angsep = angular_separation(conv(lon1), conv(lat1), conv(lon2), conv(lat2))
assert np.fabs(angsep - conv(corrsep)) < conv(correctness_margin) |
Test angular separation functionality | def test_proj_separations():
"""
Test angular separation functionality
"""
c1 = ICRS(ra=0 * u.deg, dec=0 * u.deg)
c2 = ICRS(ra=0 * u.deg, dec=1 * u.deg)
# these operations have ambiguous interpretations for points on a sphere
with pytest.raises(TypeError):
c1 + c2
with pytest.raises(TypeError):
c1 - c2 |
Test arrays values with Angle objects. | def test_angle_arrays():
"""
Test arrays values with Angle objects.
"""
# Tests incomplete
a1 = Angle([0, 45, 90, 180, 270, 360, 720.0], unit=u.degree)
npt.assert_almost_equal([0.0, 45.0, 90.0, 180.0, 270.0, 360.0, 720.0], a1.value)
a2 = Angle(np.array([-90, -45, 0, 45, 90, 180, 270, 360]), unit=u.degree)
npt.assert_almost_equal([-90, -45, 0, 45, 90, 180, 270, 360], a2.value)
a3 = Angle(["12 degrees", "3 hours", "5 deg", "4rad"])
npt.assert_almost_equal([12.0, 45.0, 5.0, 229.18311805], a3.value)
assert a3.unit == u.degree
a4 = Angle(["12 degrees", "3 hours", "5 deg", "4rad"], u.radian)
npt.assert_almost_equal(a4.degree, a3.value)
assert a4.unit == u.radian
a5 = Angle([0, 45, 90, 180, 270, 360], unit=u.degree)
a6 = a5.sum()
npt.assert_almost_equal(a6.value, 945.0)
assert a6.unit is u.degree
with ExitStack() as stack:
if NUMPY_LT_1_24:
stack.enter_context(pytest.raises(TypeError))
stack.enter_context(
pytest.warns(
np.VisibleDeprecationWarning,
match="Creating an ndarray from ragged nested sequences",
)
)
else:
stack.enter_context(pytest.raises(ValueError))
Angle([a1, a2, a3], unit=u.degree)
a8 = Angle(["04:02:02", "03:02:01", "06:02:01"], unit=u.degree)
npt.assert_almost_equal(a8.value, [4.03388889, 3.03361111, 6.03361111])
a9 = Angle(np.array(["04:02:02", "03:02:01", "06:02:01"]), unit=u.degree)
npt.assert_almost_equal(a9.value, a8.value)
with pytest.raises(u.UnitsError):
Angle(["04:02:02", "03:02:01", "06:02:01"]) |
Test creating coordinates from arrays. | def test_array_coordinates_creation():
"""
Test creating coordinates from arrays.
"""
c = ICRS(np.array([1, 2]) * u.deg, np.array([3, 4]) * u.deg)
assert not c.ra.isscalar
with pytest.raises(ValueError):
ICRS(np.array([1, 2]) * u.deg, np.array([3, 4, 5]) * u.deg)
with pytest.raises(ValueError):
ICRS(np.array([1, 2, 4, 5]) * u.deg, np.array([[3, 4], [5, 6]]) * u.deg)
# make sure cartesian initialization also works
cart = CartesianRepresentation(
x=[1.0, 2.0] * u.kpc, y=[3.0, 4.0] * u.kpc, z=[5.0, 6.0] * u.kpc
)
c = ICRS(cart)
# also ensure strings can be arrays
c = SkyCoord(["1d0m0s", "2h02m00.3s"], ["3d", "4d"])
# but invalid strings cannot
with pytest.raises(ValueError):
SkyCoord(Angle(["10m0s", "2h02m00.3s"]), Angle(["3d", "4d"]))
with pytest.raises(ValueError):
SkyCoord(Angle(["1d0m0s", "2h02m00.3s"]), Angle(["3x", "4d"])) |
Test creating coordinates from arrays and distances. | def test_array_coordinates_distances():
"""
Test creating coordinates from arrays and distances.
"""
# correct way
ICRS(
ra=np.array([1, 2]) * u.deg,
dec=np.array([3, 4]) * u.deg,
distance=[0.1, 0.2] * u.kpc,
)
with pytest.raises(ValueError):
# scalar distance and mismatched array coordinates
ICRS(
ra=np.array([1, 2, 3]) * u.deg,
dec=np.array([[3, 4], [5, 6]]) * u.deg,
distance=2.0 * u.kpc,
)
with pytest.raises(ValueError):
# more distance values than coordinates
ICRS(
ra=np.array([1, 2]) * u.deg,
dec=np.array([3, 4]) * u.deg,
distance=[0.1, 0.2, 3.0] * u.kpc,
) |
Test transformation on coordinates with array content (first length-2 1D, then a 3D array) | def test_array_coordinates_transformations(arrshape, distance):
"""
Test transformation on coordinates with array content (first length-2 1D, then a 3D array)
"""
# M31 coordinates from test_transformations
raarr = np.ones(arrshape) * 10.6847929
decarr = np.ones(arrshape) * 41.2690650
if distance is not None:
distance = np.ones(arrshape) * distance
print(raarr, decarr, distance)
c = ICRS(ra=raarr * u.deg, dec=decarr * u.deg, distance=distance)
g = c.transform_to(Galactic())
assert g.l.shape == arrshape
npt.assert_array_almost_equal(g.l.degree, 121.17440967)
npt.assert_array_almost_equal(g.b.degree, -21.57299631)
if distance is not None:
assert g.distance.unit == c.distance.unit
# now make sure round-tripping works through FK5
c2 = c.transform_to(FK5()).transform_to(ICRS())
npt.assert_array_almost_equal(c.ra.radian, c2.ra.radian)
npt.assert_array_almost_equal(c.dec.radian, c2.dec.radian)
assert c2.ra.shape == arrshape
if distance is not None:
assert c2.distance.unit == c.distance.unit
# also make sure it's possible to get to FK4, which uses a direct transform function.
fk4 = c.transform_to(FK4())
npt.assert_array_almost_equal(fk4.ra.degree, 10.0004, decimal=4)
npt.assert_array_almost_equal(fk4.dec.degree, 40.9953, decimal=4)
assert fk4.ra.shape == arrshape
if distance is not None:
assert fk4.distance.unit == c.distance.unit
# now check the reverse transforms run
cfk4 = fk4.transform_to(ICRS())
assert cfk4.ra.shape == arrshape |
Ensures that FK5 coordinates as arrays precess their equinoxes | def test_array_precession():
"""
Ensures that FK5 coordinates as arrays precess their equinoxes
"""
j2000 = Time("J2000")
j1975 = Time("J1975")
fk5 = FK5([1, 1.1] * u.radian, [0.5, 0.6] * u.radian)
assert fk5.equinox.jyear == j2000.jyear
fk5_2 = fk5.transform_to(FK5(equinox=j1975))
assert fk5_2.equinox.jyear == j1975.jyear
npt.assert_array_less(0.05, np.abs(fk5.ra.degree - fk5_2.ra.degree))
npt.assert_array_less(0.05, np.abs(fk5.dec.degree - fk5_2.dec.degree)) |
Check replacements against erfa versions for consistency. | def test_atciqz_aticq(t, pos):
"""Check replacements against erfa versions for consistency."""
jd1, jd2 = get_jd12(t, "tdb")
astrom, _ = erfa.apci13(jd1, jd2)
ra = pos.lon.to_value(u.rad)
dec = pos.lat.to_value(u.rad)
assert_allclose(erfa.atciqz(ra, dec, astrom), atciqz(pos, astrom))
assert_allclose(erfa.aticq(ra, dec, astrom), aticq(pos, astrom)) |
This tests a variety of coordinate conversions for the Chandra point-source
catalog location of M31 from NED. | def test_m31_coord_transforms(fromsys, tosys, fromcoo, tocoo):
"""
This tests a variety of coordinate conversions for the Chandra point-source
catalog location of M31 from NED.
"""
coo1 = fromsys(ra=fromcoo[0] * u.deg, dec=fromcoo[1] * u.deg, distance=m31_dist)
coo2 = coo1.transform_to(tosys())
if tosys is FK4:
coo2_prec = coo2.transform_to(FK4(equinox=Time("B1950")))
# convert_precision <1 arcsec
assert (coo2_prec.spherical.lon - tocoo[0] * u.deg) < convert_precision
assert (coo2_prec.spherical.lat - tocoo[1] * u.deg) < convert_precision
else:
assert (coo2.spherical.lon - tocoo[0] * u.deg) < convert_precision # <1 arcsec
assert (coo2.spherical.lat - tocoo[1] * u.deg) < convert_precision
assert coo1.distance.unit == u.kpc
assert coo2.distance.unit == u.kpc
assert m31_dist.unit == u.kpc
assert (coo2.distance - m31_dist) < dist_precision
# check round-tripping
coo1_2 = coo2.transform_to(fromsys())
assert (coo1_2.spherical.lon - fromcoo[0] * u.deg) < roundtrip_precision
assert (coo1_2.spherical.lat - fromcoo[1] * u.deg) < roundtrip_precision
assert (coo1_2.distance - m31_dist) < dist_precision |
Ensures that FK4 and FK5 coordinates precess their equinoxes | def test_precession():
"""
Ensures that FK4 and FK5 coordinates precess their equinoxes
"""
j2000 = Time("J2000")
b1950 = Time("B1950")
j1975 = Time("J1975")
b1975 = Time("B1975")
fk4 = FK4(ra=1 * u.radian, dec=0.5 * u.radian)
assert fk4.equinox.byear == b1950.byear
fk4_2 = fk4.transform_to(FK4(equinox=b1975))
assert fk4_2.equinox.byear == b1975.byear
fk5 = FK5(ra=1 * u.radian, dec=0.5 * u.radian)
assert fk5.equinox.jyear == j2000.jyear
fk5_2 = fk5.transform_to(FK4(equinox=j1975))
assert fk5_2.equinox.jyear == j1975.jyear |
Check that FK5 -> Galactic gives the same as FK5 -> FK4 -> Galactic. | def test_fk5_galactic():
"""
Check that FK5 -> Galactic gives the same as FK5 -> FK4 -> Galactic.
"""
fk5 = FK5(ra=1 * u.deg, dec=2 * u.deg)
direct = fk5.transform_to(Galactic())
indirect = fk5.transform_to(FK4()).transform_to(Galactic())
assert direct.separation(indirect).degree < 1.0e-10
direct = fk5.transform_to(Galactic())
indirect = fk5.transform_to(FK4NoETerms()).transform_to(Galactic())
assert direct.separation(indirect).degree < 1.0e-10 |
Check Galactic<->Supergalactic and Galactic<->ICRS conversion. | def test_supergalactic():
"""
Check Galactic<->Supergalactic and Galactic<->ICRS conversion.
"""
# Check supergalactic North pole.
npole = Galactic(l=47.37 * u.degree, b=+6.32 * u.degree)
assert allclose(npole.transform_to(Supergalactic()).sgb.deg, +90, atol=1e-9)
# Check the origin of supergalactic longitude.
lon0 = Supergalactic(sgl=0 * u.degree, sgb=0 * u.degree)
lon0_gal = lon0.transform_to(Galactic())
assert allclose(lon0_gal.l.deg, 137.37, atol=1e-9)
assert allclose(lon0_gal.b.deg, 0, atol=1e-9)
# Test Galactic<->ICRS with some positions that appear in Foley et al. 2008
# (https://ui.adsabs.harvard.edu/abs/2008A%26A...484..143F)
# GRB 021219
supergalactic = Supergalactic(sgl=29.91 * u.degree, sgb=+73.72 * u.degree)
icrs = SkyCoord("18h50m27s +31d57m17s")
assert supergalactic.separation(icrs) < 0.005 * u.degree
# GRB 030320
supergalactic = Supergalactic(sgl=-174.44 * u.degree, sgb=+46.17 * u.degree)
icrs = SkyCoord("17h51m36s -25d18m52s")
assert supergalactic.separation(icrs) < 0.005 * u.degree |
Test CIRS<->ICRS transformations, including self transform | def test_cirs_icrs():
"""
Test CIRS<->ICRS transformations, including self transform
"""
t = Time("J2010")
MOONDIST = 385000 * u.km # approximate moon semi-major orbit axis of moon
MOONDIST_CART = CartesianRepresentation(
3**-0.5 * MOONDIST, 3**-0.5 * MOONDIST, 3**-0.5 * MOONDIST
)
loc = EarthLocation(lat=0 * u.deg, lon=0 * u.deg)
cirs_geo_frame = CIRS(obstime=t)
cirs_topo_frame = CIRS(obstime=t, location=loc)
moon_geo = cirs_geo_frame.realize_frame(MOONDIST_CART)
moon_topo = moon_geo.transform_to(cirs_topo_frame)
# now check that the distance change is similar to earth radius
assert (
1000 * u.km
< np.abs(moon_topo.distance - moon_geo.distance).to(u.au)
< 7000 * u.km
)
# now check that it round-trips
moon2 = moon_topo.transform_to(moon_geo)
assert_allclose(moon_geo.cartesian.xyz, moon2.cartesian.xyz)
# now check ICRS transform gives a decent distance from Barycentre
moon_icrs = moon_geo.transform_to(ICRS())
assert_allclose(moon_icrs.distance - 1 * u.au, 0.0 * u.R_sun, atol=3 * u.R_sun) |
Tests functionality for Coordinate class distances and cartesian
transformations. | def test_distances():
"""
Tests functionality for Coordinate class distances and cartesian
transformations.
"""
"""
Distances can also be specified, and allow for a full 3D definition of a
coordinate.
"""
# try all the different ways to initialize a Distance
distance = Distance(12, u.parsec)
Distance(40, unit=u.au)
Distance(value=5, unit=u.kpc)
# need to provide a unit
with pytest.raises(u.UnitsError):
Distance(12)
with pytest.raises(ValueError, match="none of `value`, `z`, `distmod`,"):
Distance(unit=u.km)
# standard units are pre-defined
npt.assert_allclose(distance.lyr, 39.138765325702551)
npt.assert_allclose(distance.km, 370281309776063.0)
# Coordinate objects can be assigned a distance object, giving them a full
# 3D position
c = Galactic(
l=158.558650 * u.degree,
b=-43.350066 * u.degree,
distance=Distance(12, u.parsec),
)
assert quantity_allclose(c.distance, 12 * u.pc)
# or initialize distances via redshifts - this is actually tested in the
# function below that checks for scipy. This is kept here as an example
# c.distance = Distance(z=0.2) # uses current cosmology
# with whatever your preferred cosmology may be
# c.distance = Distance(z=0.2, cosmology=WMAP5)
# Coordinate objects can be initialized with a distance using special
# syntax
c1 = Galactic(l=158.558650 * u.deg, b=-43.350066 * u.deg, distance=12 * u.kpc)
# Coordinate objects can be instantiated with cartesian coordinates
# Internally they will immediately be converted to two angles + a distance
cart = CartesianRepresentation(x=2 * u.pc, y=4 * u.pc, z=8 * u.pc)
c2 = Galactic(cart)
sep12 = c1.separation_3d(c2)
# returns a *3d* distance between the c1 and c2 coordinates
# not that this does *not*
assert isinstance(sep12, Distance)
npt.assert_allclose(sep12.pc, 12005.784163916317, 10)
"""
All spherical coordinate systems with distances can be converted to
cartesian coordinates.
"""
cartrep2 = c2.cartesian
assert isinstance(cartrep2.x, u.Quantity)
npt.assert_allclose(cartrep2.x.value, 2)
npt.assert_allclose(cartrep2.y.value, 4)
npt.assert_allclose(cartrep2.z.value, 8)
# with no distance, the unit sphere is assumed when converting to cartesian
c3 = Galactic(l=158.558650 * u.degree, b=-43.350066 * u.degree, distance=None)
unitcart = c3.cartesian
npt.assert_allclose(
((unitcart.x**2 + unitcart.y**2 + unitcart.z**2) ** 0.5).value, 1.0
)
# TODO: choose between these when CartesianRepresentation gets a definite
# decision on whether or not it gets __add__
#
# CartesianRepresentation objects can be added and subtracted, which are
# vector/elementwise they can also be given as arguments to a coordinate
# system
# csum = ICRS(c1.cartesian + c2.cartesian)
csumrep = CartesianRepresentation(c1.cartesian.xyz + c2.cartesian.xyz)
csum = ICRS(csumrep)
npt.assert_allclose(csumrep.x.value, -8.12016610185)
npt.assert_allclose(csumrep.y.value, 3.19380597435)
npt.assert_allclose(csumrep.z.value, -8.2294483707)
npt.assert_allclose(csum.ra.degree, 158.529401774)
npt.assert_allclose(csum.dec.degree, -43.3235825777)
npt.assert_allclose(csum.distance.kpc, 11.9942200501) |
The distance-related tests that require scipy due to the cosmology
module needing scipy integration routines | def test_distances_scipy():
"""
The distance-related tests that require scipy due to the cosmology
module needing scipy integration routines
"""
from astropy.cosmology import WMAP5
# try different ways to initialize a Distance
d4 = Distance(z=0.23) # uses default cosmology - as of writing, WMAP7
npt.assert_allclose(d4.z, 0.23, rtol=1e-8)
d5 = Distance(z=0.23, cosmology=WMAP5)
npt.assert_allclose(d5.compute_z(WMAP5), 0.23, rtol=1e-8)
d6 = Distance(z=0.23, cosmology=WMAP5, unit=u.km)
npt.assert_allclose(d6.value, 3.5417046898762366e22)
with pytest.raises(ValueError, match="a `cosmology` was given but `z`"):
Distance(parallax=1 * u.mas, cosmology=WMAP5)
# Regression test for #12531
with pytest.raises(ValueError, match=MULTIPLE_INPUTS_ERROR_MSG):
Distance(z=0.23, parallax=1 * u.mas)
# vectors! regression test for #11949
d4 = Distance(z=[0.23, 0.45]) # as of writing, Planck18
npt.assert_allclose(d4.z, [0.23, 0.45], rtol=1e-8) |
test that distance behaves like a proper quantity | def test_distance_is_quantity():
"""
test that distance behaves like a proper quantity
"""
Distance(2 * u.kpc)
d = Distance([2, 3.1], u.kpc)
assert d.shape == (2,)
a = d.view(np.ndarray)
q = d.view(u.Quantity)
a[0] = 1.2
q.value[1] = 5.4
assert d[0].value == 1.2
assert d[1].value == 5.4
q = u.Quantity(d, copy=True)
q.value[1] = 0
assert q.value[1] == 0
assert d.value[1] != 0
# regression test against #2261
d = Distance([2 * u.kpc, 250.0 * u.pc])
assert d.unit is u.kpc
assert np.all(d.value == np.array([2.0, 0.25])) |
test that distances can be created from quantities and that cartesian
representations come out right | def test_distance_in_coordinates():
"""
test that distances can be created from quantities and that cartesian
representations come out right
"""
ra = Longitude("4:08:15.162342", unit=u.hour)
dec = Latitude("-41:08:15.162342", unit=u.degree)
coo = ICRS(ra, dec, distance=2 * u.kpc)
cart = coo.cartesian
assert isinstance(cart.xyz, u.Quantity) |
Test optional kwarg allow_negative | def test_negative_distance():
"""Test optional kwarg allow_negative"""
error_message = (
r"^distance must be >= 0\. Use the argument `allow_negative=True` to allow "
r"negative values\.$"
)
with pytest.raises(ValueError, match=error_message):
Distance([-2, 3.1], u.kpc)
with pytest.raises(ValueError, match=error_message):
Distance([-2, -3.1], u.kpc)
with pytest.raises(ValueError, match=error_message):
Distance(-2, u.kpc)
d = Distance(-2, u.kpc, allow_negative=True)
assert d.value == -2 |
Ensure comparisons of distances work (#2206, #2250) | def test_distance_comparison():
"""Ensure comparisons of distances work (#2206, #2250)"""
a = Distance(15 * u.kpc)
b = Distance(15 * u.kpc)
assert a == b
c = Distance(1.0 * u.Mpc)
assert a < c |
Any operation that leaves units other than those of length
should turn a distance into a quantity (#2206, #2250) | def test_distance_to_quantity_when_not_units_of_length():
"""Any operation that leaves units other than those of length
should turn a distance into a quantity (#2206, #2250)"""
d = Distance(15 * u.kpc)
twice = 2.0 * d
assert isinstance(twice, Distance)
area = 4.0 * np.pi * d**2
assert area.unit.is_equivalent(u.m**2)
assert not isinstance(area, Distance)
assert type(area) is u.Quantity |
Test angle-like behavior of Distance.parallax for object with a unit attribute.
Adapted from #15693 | def test_distance_parallax_angle_like():
"""Test angle-like behavior of Distance.parallax for object with a unit attribute.
Adapted from #15693
"""
assert quantity_allclose(
Distance(parallax=Column([1.0, 2.0, 4.0], unit=u.mas)),
[1000, 500, 250] * u.pc,
)
class FloatMas(float):
unit = u.mas
assert Distance(parallax=FloatMas(1.0)) == 1000 * u.pc |
Test that we reproduce erfa/src/t_erfa_c.c t_gc2gd | def test_gc2gd():
"""Test that we reproduce erfa/src/t_erfa_c.c t_gc2gd"""
x, y, z = (2e6, 3e6, 5.244e6)
status = 0 # help for copy & paste of vvd
location = EarthLocation.from_geocentric(x, y, z, u.m)
e, p, h = location.to_geodetic("WGS84")
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e2", status)
vvd(p, 0.97160184820607853, 1e-14, "eraGc2gd", "p2", status)
vvd(h, 331.41731754844348, 1e-8, "eraGc2gd", "h2", status)
e, p, h = location.to_geodetic("GRS80")
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e2", status)
vvd(p, 0.97160184820607853, 1e-14, "eraGc2gd", "p2", status)
vvd(h, 331.41731754844348, 1e-8, "eraGc2gd", "h2", status)
e, p, h = location.to_geodetic("WGS72")
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e3", status)
vvd(p, 0.97160181811015119, 1e-14, "eraGc2gd", "p3", status)
vvd(h, 333.27707261303181, 1e-8, "eraGc2gd", "h3", status) |
Test that we reproduce erfa/src/t_erfa_c.c t_gd2gc | def test_gd2gc():
"""Test that we reproduce erfa/src/t_erfa_c.c t_gd2gc"""
e = 3.1 * u.rad
p = -0.5 * u.rad
h = 2500.0 * u.m
status = 0 # help for copy & paste of vvd
location = EarthLocation.from_geodetic(e, p, h, ellipsoid="WGS84")
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5599000.5577049947, 1e-7, "eraGd2gc", "0/1", status)
vvd(xyz[1], 233011.67223479203, 1e-7, "eraGd2gc", "1/1", status)
vvd(xyz[2], -3040909.4706983363, 1e-7, "eraGd2gc", "2/1", status)
location = EarthLocation.from_geodetic(e, p, h, ellipsoid="GRS80")
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5599000.5577260984, 1e-7, "eraGd2gc", "0/2", status)
vvd(xyz[1], 233011.6722356703, 1e-7, "eraGd2gc", "1/2", status)
vvd(xyz[2], -3040909.4706095476, 1e-7, "eraGd2gc", "2/2", status)
location = EarthLocation.from_geodetic(e, p, h, ellipsoid="WGS72")
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5598998.7626301490, 1e-7, "eraGd2gc", "0/3", status)
vvd(xyz[1], 233011.5975297822, 1e-7, "eraGd2gc", "1/3", status)
vvd(xyz[2], -3040908.6861467111, 1e-7, "eraGd2gc", "2/3", status) |
Regression test against #4304. | def test_pickling():
"""Regression test against #4304."""
el = EarthLocation(0.0 * u.m, 6000 * u.km, 6000 * u.km)
s = pickle.dumps(el)
el2 = pickle.loads(s)
assert el == el2 |
Regression test for issue #4542 | def test_repr_latex():
"""
Regression test for issue #4542
"""
somelocation = EarthLocation(lon="149:3:57.9", lat="-31:16:37.3")
somelocation._repr_latex_()
somelocation2 = EarthLocation(lon=[1.0, 2.0] * u.deg, lat=[-1.0, 9.0] * u.deg)
somelocation2._repr_latex_() |
Test that the interpolation also works for nd-arrays | def test_interpolation_nd():
"""
Test that the interpolation also works for nd-arrays
"""
fact = EarthLocation(
lon=-17.891105 * u.deg,
lat=28.761584 * u.deg,
height=2200 * u.m,
)
interp_provider = ErfaAstromInterpolator(300 * u.s)
provider = ErfaAstrom()
for shape in [(), (1,), (10,), (3, 2), (2, 10, 5), (4, 5, 3, 2)]:
# create obstimes of the desired shapes
delta_t = np.linspace(0, 12, np.prod(shape, dtype=int)) * u.hour
obstime = (Time("2020-01-01T18:00") + delta_t).reshape(shape)
altaz = AltAz(location=fact, obstime=obstime)
gcrs = GCRS(obstime=obstime)
cirs = CIRS(obstime=obstime)
for frame, tcode in zip([altaz, cirs, gcrs], ["apio", "apco", "apcs"]):
without_interp = getattr(provider, tcode)(frame)
assert without_interp.shape == shape
with_interp = getattr(interp_provider, tcode)(frame)
assert with_interp.shape == shape |
We are testing that the mechanism of calling a function works. If the function
returns a constant value we can compare the numbers with what we get if we specify
a constant dt directly. | def test_dt_function(dt, expected_vel):
"""We are testing that the mechanism of calling a function works. If the function
returns a constant value we can compare the numbers with what we get if we specify
a constant dt directly.
"""
gcrs_coord = GCRS(
ra=12 * u.deg,
dec=47 * u.deg,
distance=100 * u.au,
pm_ra_cosdec=0 * u.marcsec / u.yr,
pm_dec=0 * u.marcsec / u.yr,
radial_velocity=0 * u.km / u.s,
obstime=Time("J2020"),
)
with frame_transform_graph.impose_finite_difference_dt(
lambda fromcoord, toframe: dt
):
icrs_coord = gcrs_coord.transform_to(ICRS())
assert_quantity_allclose(
icrs_coord.cartesian.xyz, [66.535756, 15.074734, 73.518509] * u.au
)
assert_quantity_allclose(
icrs_coord.cartesian.differentials["s"].d_xyz, expected_vel, rtol=2e-6
) |
Tests the numerical stability of the default settings for the finite
difference transformation calculation. This is *known* to fail for at
>~1kpc, but this may be improved in future versions. | def test_numerical_limits(distance):
"""
Tests the numerical stability of the default settings for the finite
difference transformation calculation. This is *known* to fail for at
>~1kpc, but this may be improved in future versions.
"""
gcrs_coord = ICRS(
ra=0 * u.deg,
dec=10 * u.deg,
distance=distance,
pm_ra_cosdec=0 * u.marcsec / u.yr,
pm_dec=0 * u.marcsec / u.yr,
radial_velocity=0 * u.km / u.s,
).transform_to(GCRS(obstime=Time("J2017") + np.linspace(-0.5, 0.5, 100) * u.year))
# if its a lot bigger than this - ~the maximal velocity shift along
# the direction above with a small allowance for noise - finite-difference
# rounding errors have ruined the calculation
assert np.ptp(gcrs_coord.radial_velocity) < 65 * u.km / u.s |
Useful for plotting a frame with multiple times. *Not* used in the testing
suite per se, but extremely useful for interactive plotting of results from
tests in this module. | def diff_info_plot(frame, time):
"""
Useful for plotting a frame with multiple times. *Not* used in the testing
suite per se, but extremely useful for interactive plotting of results from
tests in this module.
"""
from matplotlib import pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 12))
ax1.plot_date(
time.plot_date, frame.data.differentials["s"].d_xyz.to(u.km / u.s).T, fmt="-"
)
ax1.legend(["x", "y", "z"])
ax2.plot_date(
time.plot_date,
np.sum(frame.data.differentials["s"].d_xyz.to(u.km / u.s) ** 2, axis=0) ** 0.5,
fmt="-",
)
ax2.set_title("total")
sd = frame.data.differentials["s"].represent_as(SphericalDifferential, frame.data)
ax3.plot_date(time.plot_date, sd.d_distance.to(u.km / u.s), fmt="-")
ax3.set_title("radial")
ax4.plot_date(time.plot_date, sd.d_lat.to(u.marcsec / u.yr), fmt="-", label="lat")
ax4.plot_date(time.plot_date, sd.d_lon.to(u.marcsec / u.yr), fmt="-", label="lon")
return fig |
Regression test for a bug that caused ``to_string`` to crash for angles in
radians when specifying the precision. | def test_to_string_radian_with_precision():
"""
Regression test for a bug that caused ``to_string`` to crash for angles in
radians when specifying the precision.
"""
# Check that specifying the precision works
a = Angle(3.0, unit=u.rad)
assert a.to_string(precision=3, sep="fromunit") == "3.000 rad" |
Copy original 'REPRESENTATIONCLASSES' as attribute in function. | def setup_function(func):
"""Copy original 'REPRESENTATIONCLASSES' as attribute in function."""
func.REPRESENTATION_CLASSES_ORIG = deepcopy(REPRESENTATION_CLASSES) |
Reset REPRESENTATION_CLASSES to original value. | def teardown_function(func):
"""Reset REPRESENTATION_CLASSES to original value."""
REPRESENTATION_CLASSES.clear()
REPRESENTATION_CLASSES.update(func.REPRESENTATION_CLASSES_ORIG) |
Unit tests of the Attribute descriptor. | def test_frame_attribute_descriptor():
"""Unit tests of the Attribute descriptor."""
class TestAttributes:
attr_none = Attribute()
attr_2 = Attribute(default=2)
attr_3_attr2 = Attribute(default=3, secondary_attribute="attr_2")
attr_none_attr2 = Attribute(default=None, secondary_attribute="attr_2")
attr_none_nonexist = Attribute(default=None, secondary_attribute="nonexist")
t = TestAttributes()
# Defaults
assert t.attr_none is None
assert t.attr_2 == 2
assert t.attr_3_attr2 == 3
assert t.attr_none_attr2 == t.attr_2
assert t.attr_none_nonexist is None # No default and non-existent secondary attr
# Setting values via '_'-prefixed internal vars
# (as would normally done in __init__)
t._attr_none = 10
assert t.attr_none == 10
t._attr_2 = 20
assert t.attr_2 == 20
assert t.attr_3_attr2 == 3
assert t.attr_none_attr2 == t.attr_2
t._attr_none_attr2 = 40
assert t.attr_none_attr2 == 40
# Make sure setting values via public attribute fails
with pytest.raises(AttributeError) as err:
t.attr_none = 5
assert "Cannot set frame attribute" in str(err.value) |
Unit test of the attribute descriptors in subclasses. | def test_frame_subclass_attribute_descriptor():
"""Unit test of the attribute descriptors in subclasses."""
_EQUINOX_B1980 = Time("B1980", scale="tai")
class MyFK4(FK4):
# equinox inherited from FK4, obstime overridden, and newattr is new
obstime = TimeAttribute(default=_EQUINOX_B1980)
newattr = Attribute(default="newattr")
mfk4 = MyFK4()
assert mfk4.equinox.value == "B1950.000"
assert mfk4.obstime.value == "B1980.000"
assert mfk4.newattr == "newattr"
with pytest.warns(AstropyDeprecationWarning):
assert set(mfk4.get_frame_attr_names()) == {"equinox", "obstime", "newattr"}
mfk4 = MyFK4(equinox="J1980.0", obstime="J1990.0", newattr="world")
assert mfk4.equinox.value == "J1980.000"
assert mfk4.obstime.value == "J1990.000"
assert mfk4.newattr == "world" |
Ensure that all attributes are accumulated in case of inheritance from
multiple BaseCoordinateFrames. See
https://github.com/astropy/astropy/pull/11099#issuecomment-735829157 | def test_frame_multiple_inheritance_attribute_descriptor():
"""
Ensure that all attributes are accumulated in case of inheritance from
multiple BaseCoordinateFrames. See
https://github.com/astropy/astropy/pull/11099#issuecomment-735829157
"""
class Frame1(BaseCoordinateFrame):
attr1 = Attribute()
class Frame2(BaseCoordinateFrame):
attr2 = Attribute()
class Frame3(Frame1, Frame2):
pass
assert len(Frame3.frame_attributes) == 2
assert "attr1" in Frame3.frame_attributes
assert "attr2" in Frame3.frame_attributes
# In case the same attribute exists in both frames, the one from the
# left-most class in the MRO should take precedence
class Frame4(BaseCoordinateFrame):
attr1 = Attribute()
attr2 = Attribute()
class Frame5(Frame1, Frame4):
pass
assert Frame5.frame_attributes["attr1"] is Frame1.frame_attributes["attr1"]
assert Frame5.frame_attributes["attr2"] is Frame4.frame_attributes["attr2"] |
This test just makes sure the transform architecture works, but does *not*
actually test all the builtin transforms themselves are accurate. | def test_transform():
"""
This test just makes sure the transform architecture works, but does *not*
actually test all the builtin transforms themselves are accurate.
"""
i = ICRS(ra=[1, 2] * u.deg, dec=[3, 4] * u.deg)
f = i.transform_to(FK5())
i2 = f.transform_to(ICRS())
assert i2.data.__class__ == r.UnitSphericalRepresentation
assert_allclose(i.ra, i2.ra)
assert_allclose(i.dec, i2.dec)
i = ICRS(ra=[1, 2] * u.deg, dec=[3, 4] * u.deg, distance=[5, 6] * u.kpc)
f = i.transform_to(FK5())
i2 = f.transform_to(ICRS())
assert i2.data.__class__ != r.UnitSphericalRepresentation
f = FK5(ra=1 * u.deg, dec=2 * u.deg, equinox=Time("J2001"))
f4 = f.transform_to(FK4())
f4_2 = f.transform_to(FK4(equinox=f.equinox))
# make sure attributes are copied over correctly
assert f4.equinox == FK4().equinox
assert f4_2.equinox == f.equinox
# make sure self-transforms also work
i = ICRS(ra=[1, 2] * u.deg, dec=[3, 4] * u.deg)
i2 = i.transform_to(ICRS())
assert_allclose(i.ra, i2.ra)
assert_allclose(i.dec, i2.dec)
f = FK5(ra=1 * u.deg, dec=2 * u.deg, equinox=Time("J2001"))
f2 = f.transform_to(FK5()) # default equinox, so should be *different*
assert f2.equinox == FK5().equinox
with pytest.raises(AssertionError):
assert_allclose(f.ra, f2.ra)
with pytest.raises(AssertionError):
assert_allclose(f.dec, f2.dec)
# finally, check Galactic round-tripping
i1 = ICRS(ra=[1, 2] * u.deg, dec=[3, 4] * u.deg)
i2 = i1.transform_to(Galactic()).transform_to(ICRS())
assert_allclose(i1.ra, i2.ra)
assert_allclose(i1.dec, i2.dec) |
Test different flavors of item setting for a Frame without a velocity. | def test_setitem_no_velocity():
"""Test different flavors of item setting for a Frame without a velocity."""
obstime = "B1955"
sc0 = FK4([1, 2] * u.deg, [3, 4] * u.deg, obstime=obstime)
sc2 = FK4([10, 20] * u.deg, [30, 40] * u.deg, obstime=obstime)
sc1 = sc0.copy()
sc1_repr = repr(sc1)
assert "representation" in sc1.cache
sc1[1] = sc2[0]
assert sc1.cache == {}
assert repr(sc2) != sc1_repr
assert np.allclose(sc1.ra.to_value(u.deg), [1, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [3, 30])
assert sc1.obstime == sc2.obstime
assert sc1.name == "fk4"
sc1 = sc0.copy()
sc1[:] = sc2[0]
assert np.allclose(sc1.ra.to_value(u.deg), [10, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [30, 30])
sc1 = sc0.copy()
sc1[:] = sc2[:]
assert np.allclose(sc1.ra.to_value(u.deg), [10, 20])
assert np.allclose(sc1.dec.to_value(u.deg), [30, 40])
sc1 = sc0.copy()
sc1[[1, 0]] = sc2[:]
assert np.allclose(sc1.ra.to_value(u.deg), [20, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [40, 30])
# Works for array-valued obstime so long as they are considered equivalent
sc1 = FK4(sc0.ra, sc0.dec, obstime=[obstime, obstime])
sc1[0] = sc2[0]
# Multidimensional coordinates
sc1 = FK4([[1, 2], [3, 4]] * u.deg, [[5, 6], [7, 8]] * u.deg)
sc2 = FK4([[10, 20], [30, 40]] * u.deg, [[50, 60], [70, 80]] * u.deg)
sc1[0] = sc2[0]
assert np.allclose(sc1.ra.to_value(u.deg), [[10, 20], [3, 4]])
assert np.allclose(sc1.dec.to_value(u.deg), [[50, 60], [7, 8]]) |
Test different flavors of item setting for a Frame with a velocity. | def test_setitem_velocities():
"""Test different flavors of item setting for a Frame with a velocity."""
sc0 = FK4(
[1, 2] * u.deg,
[3, 4] * u.deg,
radial_velocity=[1, 2] * u.km / u.s,
obstime="B1950",
)
sc2 = FK4(
[10, 20] * u.deg,
[30, 40] * u.deg,
radial_velocity=[10, 20] * u.km / u.s,
obstime="B1950",
)
sc1 = sc0.copy()
sc1[1] = sc2[0]
assert np.allclose(sc1.ra.to_value(u.deg), [1, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [3, 30])
assert np.allclose(sc1.radial_velocity.to_value(u.km / u.s), [1, 10])
assert sc1.obstime == sc2.obstime
assert sc1.name == "fk4"
sc1 = sc0.copy()
sc1[:] = sc2[0]
assert np.allclose(sc1.ra.to_value(u.deg), [10, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [30, 30])
assert np.allclose(sc1.radial_velocity.to_value(u.km / u.s), [10, 10])
sc1 = sc0.copy()
sc1[:] = sc2[:]
assert np.allclose(sc1.ra.to_value(u.deg), [10, 20])
assert np.allclose(sc1.dec.to_value(u.deg), [30, 40])
assert np.allclose(sc1.radial_velocity.to_value(u.km / u.s), [10, 20])
sc1 = sc0.copy()
sc1[[1, 0]] = sc2[:]
assert np.allclose(sc1.ra.to_value(u.deg), [20, 10])
assert np.allclose(sc1.dec.to_value(u.deg), [40, 30])
assert np.allclose(sc1.radial_velocity.to_value(u.km / u.s), [20, 10]) |
Test validation and conversion of inputs for equinox and obstime attributes. | def test_time_inputs():
"""
Test validation and conversion of inputs for equinox and obstime attributes.
"""
c = FK4(1 * u.deg, 2 * u.deg, equinox="J2001.5", obstime="2000-01-01 12:00:00")
assert c.equinox == Time("J2001.5")
assert c.obstime == Time("2000-01-01 12:00:00")
with pytest.raises(ValueError) as err:
c = FK4(1 * u.deg, 2 * u.deg, equinox=1.5)
assert "Invalid time input" in str(err.value)
with pytest.raises(ValueError) as err:
c = FK4(1 * u.deg, 2 * u.deg, obstime="hello")
assert "Invalid time input" in str(err.value)
# A vector time should work if the shapes match, and we automatically
# broadcast the basic data.
c = FK4([1, 2] * u.deg, [2, 3] * u.deg, obstime=["J2000", "J2001"])
assert c.shape == (2,)
c = FK4(1 * u.deg, 2 * u.deg, obstime=["J2000", "J2001"])
assert c.shape == (2,)
# If the shapes are not broadcastable, then we should raise an exception.
with pytest.raises(ValueError, match="inconsistent shapes"):
FK4([1, 2, 3] * u.deg, [4, 5, 6] * u.deg, obstime=["J2000", "J2001"]) |
Check that the `is_frame_attr_default` machinery works as expected | def test_is_frame_attr_default():
"""
Check that the `is_frame_attr_default` machinery works as expected
"""
c1 = FK5(ra=1 * u.deg, dec=1 * u.deg)
c2 = FK5(
ra=1 * u.deg, dec=1 * u.deg, equinox=FK5.get_frame_attr_defaults()["equinox"]
)
c3 = FK5(ra=1 * u.deg, dec=1 * u.deg, equinox=Time("J2001.5"))
assert c1.equinox == c2.equinox
assert c1.equinox != c3.equinox
assert c1.is_frame_attr_default("equinox")
assert not c2.is_frame_attr_default("equinox")
assert not c3.is_frame_attr_default("equinox")
c4 = c1.realize_frame(r.UnitSphericalRepresentation(3 * u.deg, 4 * u.deg))
c5 = c2.realize_frame(r.UnitSphericalRepresentation(3 * u.deg, 4 * u.deg))
assert c4.is_frame_attr_default("equinox")
assert not c5.is_frame_attr_default("equinox") |
Test the getter and setter properties for `representation` | def test_representation():
"""
Test the getter and setter properties for `representation`
"""
# Create the frame object.
icrs = ICRS(ra=1 * u.deg, dec=1 * u.deg)
data = icrs.data
# Create some representation objects.
icrs_cart = icrs.cartesian
icrs_spher = icrs.spherical
icrs_cyl = icrs.cylindrical
# Testing when `_representation` set to `CartesianRepresentation`.
icrs.representation_type = r.CartesianRepresentation
assert icrs.representation_type == r.CartesianRepresentation
assert icrs_cart.x == icrs.x
assert icrs_cart.y == icrs.y
assert icrs_cart.z == icrs.z
assert icrs.data == data
# Testing that an ICRS object in CartesianRepresentation must not have spherical attributes.
for attr in ("ra", "dec", "distance"):
with pytest.raises(AttributeError) as err:
getattr(icrs, attr)
assert "object has no attribute" in str(err.value)
# Testing when `_representation` set to `CylindricalRepresentation`.
icrs.representation_type = r.CylindricalRepresentation
assert icrs.representation_type == r.CylindricalRepresentation
assert icrs.data == data
# Testing setter input using text argument for spherical.
icrs.representation_type = "spherical"
assert icrs.representation_type is r.SphericalRepresentation
assert icrs_spher.lat == icrs.dec
assert icrs_spher.lon == icrs.ra
assert icrs_spher.distance == icrs.distance
assert icrs.data == data
# Testing that an ICRS object in SphericalRepresentation must not have cartesian attributes.
for attr in ("x", "y", "z"):
with pytest.raises(AttributeError) as err:
getattr(icrs, attr)
assert "object has no attribute" in str(err.value)
# Testing setter input using text argument for cylindrical.
icrs.representation_type = "cylindrical"
assert icrs.representation_type is r.CylindricalRepresentation
assert icrs_cyl.rho == icrs.rho
assert icrs_cyl.phi == icrs.phi
assert icrs_cyl.z == icrs.z
assert icrs.data == data
# Testing that an ICRS object in CylindricalRepresentation must not have spherical attributes.
for attr in ("ra", "dec", "distance"):
with pytest.raises(AttributeError) as err:
getattr(icrs, attr)
assert "object has no attribute" in str(err.value)
with pytest.raises(ValueError) as err:
icrs.representation_type = "WRONG"
assert "but must be a BaseRepresentation class" in str(err.value)
with pytest.raises(ValueError) as err:
icrs.representation_type = ICRS
assert "but must be a BaseRepresentation class" in str(err.value) |
Make sure current representation survives __getitem__ even if different
from data representation. | def test_getitem_representation():
"""
Make sure current representation survives __getitem__ even if different
from data representation.
"""
c = ICRS([1, 1] * u.deg, [2, 2] * u.deg)
c.representation_type = "cartesian"
assert c[0].representation_type is r.CartesianRepresentation |
Check that a data-less frame gives useful error messages about not having
data when the attributes asked for are possible coordinate components | def test_component_error_useful():
"""
Check that a data-less frame gives useful error messages about not having
data when the attributes asked for are possible coordinate components
"""
i = ICRS()
with pytest.raises(ValueError) as excinfo:
i.ra
assert "does not have associated data" in str(excinfo.value)
with pytest.raises(AttributeError) as excinfo1:
i.foobar
with pytest.raises(AttributeError) as excinfo2:
i.lon # lon is *not* the component name despite being the underlying representation's name
assert "object has no attribute 'foobar'" in str(excinfo1.value)
assert "object has no attribute 'lon'" in str(excinfo2.value) |
This test checks that the component names are frame component names, not
representation or differential names, when referenced in an exception raised
when not passing in enough data. For example:
ICRS(ra=10*u.deg)
should state:
TypeError: __init__() missing 1 required positional argument: 'dec' | def test_missing_component_error_names():
"""
This test checks that the component names are frame component names, not
representation or differential names, when referenced in an exception raised
when not passing in enough data. For example:
ICRS(ra=10*u.deg)
should state:
TypeError: __init__() missing 1 required positional argument: 'dec'
"""
with pytest.raises(TypeError) as e:
ICRS(ra=150 * u.deg)
assert "missing 1 required positional argument: 'dec'" in str(e.value)
with pytest.raises(TypeError) as e:
ICRS(
ra=150 * u.deg,
dec=-11 * u.deg,
pm_ra=100 * u.mas / u.yr,
pm_dec=10 * u.mas / u.yr,
)
assert "pm_ra_cosdec" in str(e.value) |
Note: this is a regression test for #11096 | def test_nameless_frame_subclass():
"""Note: this is a regression test for #11096"""
class Test:
pass
# Subclass from a frame class and a non-frame class.
# This subclassing is the test!
class NewFrame(ICRS, Test):
pass |
Test that frame can be compared to a SkyCoord | def test_frame_coord_comparison():
"""Test that frame can be compared to a SkyCoord"""
frame = ICRS(0 * u.deg, 0 * u.deg)
coord = SkyCoord(frame)
other = SkyCoord(ICRS(0 * u.deg, 1 * u.deg))
assert frame == coord
assert frame != other
assert not (frame == other)
error_msg = "objects must have equivalent frames"
with pytest.raises(TypeError, match=error_msg):
frame == SkyCoord(AltAz("0d", "1d")) # noqa: B015
coord = SkyCoord(ra=12 * u.hourangle, dec=5 * u.deg, frame=FK5(equinox="J1950"))
frame = FK5(ra=12 * u.hourangle, dec=5 * u.deg, equinox="J2000")
with pytest.raises(TypeError, match=error_msg):
coord == frame # noqa: B015
frame = ICRS()
coord = SkyCoord(0 * u.deg, 0 * u.deg, frame=frame)
error_msg = "Can only compare SkyCoord to Frame with data"
with pytest.raises(ValueError, match=error_msg):
frame == coord |
Note: Regression test for #5982 | def test_altaz_broadcast(s1, s2):
"""Note: Regression test for #5982"""
where = EarthLocation.from_geodetic(lat=45 * u.deg, lon=30 * u.deg, height=0 * u.m)
time = Time(np.full(s1, 58000.0), format="mjd")
angle = np.full(s2, 45.0) * u.deg
result = AltAz(alt=angle, az=angle, obstime=time, location=where)
assert result.shape == np.broadcast_shapes(s1, s2) |
Note: Regression test for #12965 | def test_transform_altaz_array_obstime():
"""Note: Regression test for #12965"""
obstime = Time("2010-01-01T00:00:00")
location = EarthLocation(0 * u.deg, 0 * u.deg, 0 * u.m)
frame1 = AltAz(location=location, obstime=obstime)
coord1 = SkyCoord(alt=80 * u.deg, az=0 * u.deg, frame=frame1)
obstimes = obstime + np.linspace(0, 15, 50) * u.min
frame2 = AltAz(location=location, obstime=obstimes)
coord2 = SkyCoord(alt=coord1.alt, az=coord1.az, frame=frame2)
assert np.all(coord2.alt == 80 * u.deg)
assert np.all(coord2.az == 0 * u.deg)
assert coord2.shape == (50,)
# test transformation to ICRS works
assert len(coord2.icrs) == 50 |
Note: Regression test for #14383 | def test_spherical_offsets_by_broadcast():
"""Note: Regression test for #14383"""
assert SkyCoord(
ra=np.array([123, 134, 145]), dec=np.array([45, 56, 67]), unit=u.deg
).spherical_offsets_by(2 * u.deg, 2 * u.deg).shape == (3,) |
There are already tests in test_transformations.py that check that
an AffineTransform fails without full-space data, but this just checks that
things work as expected at the frame level as well. | def test_frame_affinetransform(kwargs, expect_success):
"""There are already tests in test_transformations.py that check that
an AffineTransform fails without full-space data, but this just checks that
things work as expected at the frame level as well.
"""
with galactocentric_frame_defaults.set("latest"):
icrs = ICRS(**kwargs)
if expect_success:
_ = icrs.transform_to(Galactocentric())
else:
with pytest.raises(ConvertError):
icrs.transform_to(Galactocentric()) |
Test passing in an explicit differential class to the initializer or
changing the differential class via set_representation_cls | def test_differential_type_arg():
"""
Test passing in an explicit differential class to the initializer or
changing the differential class via set_representation_cls
"""
icrs = ICRS(
**POSITION_ON_SKY,
pm_ra=10 * u.mas / u.yr,
pm_dec=-11 * u.mas / u.yr,
differential_type=r.UnitSphericalDifferential,
)
assert icrs.pm_ra == 10 * u.mas / u.yr
icrs = ICRS(
**POSITION_ON_SKY,
pm_ra=10 * u.mas / u.yr,
pm_dec=-11 * u.mas / u.yr,
differential_type={"s": r.UnitSphericalDifferential},
)
assert icrs.pm_ra == 10 * u.mas / u.yr
icrs = ICRS(
ra=1 * u.deg,
dec=60 * u.deg,
pm_ra_cosdec=10 * u.mas / u.yr,
pm_dec=-11 * u.mas / u.yr,
)
icrs.set_representation_cls(s=r.UnitSphericalDifferential)
assert quantity_allclose(icrs.pm_ra, 20 * u.mas / u.yr)
# incompatible representation and differential
with pytest.raises(TypeError):
ICRS(**POSITION_ON_SKY, **CARTESIAN_VELOCITY)
# specify both
icrs = ICRS(**CARTESIAN_POSITION, **CARTESIAN_VELOCITY)
assert icrs.x == 1 * u.pc
assert icrs.y == 2 * u.pc
assert icrs.z == 3 * u.pc
assert icrs.v_x == 1 * u.km / u.s
assert icrs.v_y == 2 * u.km / u.s
assert icrs.v_z == 3 * u.km / u.s |
Regression test: #7408
Make sure that negative parallaxes turned into distances are handled right | def test_negative_distance(icrs_coords):
"""Regression test: #7408
Make sure that negative parallaxes turned into distances are handled right
"""
c = ICRS(distance=(-10 * u.mas).to(u.pc, u.parallax()), **icrs_coords)
assert quantity_allclose(c.ra, 37.4 * u.deg)
assert quantity_allclose(c.dec, -55.8 * u.deg) |
Check that the differential data given has compatible units
with the time-derivative of representation data | def test_velocity_units():
"""Check that the differential data given has compatible units
with the time-derivative of representation data"""
with pytest.raises(
ValueError,
match=(
'^x has unit "pc" with physical type "length", but v_x has incompatible'
' unit "" with physical type "dimensionless" instead of the expected'
r' "speed/velocity".$'
),
):
ICRS(**CARTESIAN_POSITION, v_x=1, v_y=2, v_z=3, differential_type="cartesian") |
Test that `get_sun` works and it behaves roughly as it should (in GCRS) | def test_sun():
"""
Test that `get_sun` works and it behaves roughly as it should (in GCRS)
"""
northern_summer_solstice = Time("2010-6-21")
northern_winter_solstice = Time("2010-12-21")
equinox_1 = Time("2010-3-21")
equinox_2 = Time("2010-9-21")
gcrs1 = get_sun(equinox_1)
assert np.abs(gcrs1.dec.deg) < 1
gcrs2 = get_sun(
Time([northern_summer_solstice, equinox_2, northern_winter_solstice])
)
assert np.all(np.abs(gcrs2.dec - [23.5, 0, -23.5] * u.deg) < 1 * u.deg) |
This function does the same thing the astropy layer is supposed to do, but
all in erfa | def _erfa_check(ira, idec, astrom):
"""
This function does the same thing the astropy layer is supposed to do, but
all in erfa
"""
cra, cdec = erfa.atciq(ira, idec, 0, 0, 0, 0, astrom)
az, zen, ha, odec, ora = erfa.atioq(cra, cdec, astrom)
alt = np.pi / 2 - zen
cra2, cdec2 = erfa.atoiq("A", az, zen, astrom)
ira2, idec2 = erfa.aticq(cra2, cdec2, astrom)
dct = locals()
del dct["astrom"]
return dct |
Test the full transform from ICRS <-> AltAz | def test_iau_fullstack(
fullstack_icrs,
fullstack_fiducial_altaz,
fullstack_times,
fullstack_locations,
fullstack_obsconditions,
):
"""
Test the full transform from ICRS <-> AltAz
"""
# create the altaz frame
altazframe = AltAz(
obstime=fullstack_times,
location=fullstack_locations,
pressure=fullstack_obsconditions[0],
temperature=fullstack_obsconditions[1],
relative_humidity=fullstack_obsconditions[2],
obswl=fullstack_obsconditions[3],
)
aacoo = fullstack_icrs.transform_to(altazframe)
# compare aacoo to the fiducial AltAz - should always be different
assert np.all(
np.abs(aacoo.alt - fullstack_fiducial_altaz.alt) > 50 * u.milliarcsecond
)
assert np.all(
np.abs(aacoo.az - fullstack_fiducial_altaz.az) > 50 * u.milliarcsecond
)
# if the refraction correction is included, we *only* do the comparisons
# where altitude >5 degrees. The SOFA guides imply that below 5 is where
# where accuracy gets more problematic, and testing reveals that alt<~0
# gives garbage round-tripping, and <10 can give ~1 arcsec uncertainty
if fullstack_obsconditions[0].value == 0:
# but if there is no refraction correction, check everything
msk = slice(None)
tol = 5 * u.microarcsecond
else:
msk = aacoo.alt > 5 * u.deg
# most of them aren't this bad, but some of those at low alt are offset
# this much. For alt > 10, this is always better than 100 masec
tol = 750 * u.milliarcsecond
# now make sure the full stack round-tripping works
icrs2 = aacoo.transform_to(ICRS())
adras = np.abs(fullstack_icrs.ra - icrs2.ra)[msk]
addecs = np.abs(fullstack_icrs.dec - icrs2.dec)[msk]
assert np.all(
adras < tol
), f"largest RA change is {np.max(adras.arcsec * 1000)} mas, > {tol}"
assert np.all(
addecs < tol
), f"largest Dec change is {np.max(addecs.arcsec * 1000)} mas, > {tol}"
# check that we're consistent with the ERFA alt/az result
iers_tab = iers.earth_orientation_table.get()
xp, yp = u.Quantity(iers_tab.pm_xy(fullstack_times)).to_value(u.radian)
lon = fullstack_locations.geodetic[0].to_value(u.radian)
lat = fullstack_locations.geodetic[1].to_value(u.radian)
height = fullstack_locations.geodetic[2].to_value(u.m)
jd1, jd2 = get_jd12(fullstack_times, "utc")
pressure = fullstack_obsconditions[0].to_value(u.hPa)
temperature = fullstack_obsconditions[1].to_value(u.deg_C)
# Relative humidity can be a quantity or a number.
relative_humidity = u.Quantity(fullstack_obsconditions[2], u.one).value
obswl = fullstack_obsconditions[3].to_value(u.micron)
astrom, eo = erfa.apco13(
jd1,
jd2,
fullstack_times.delta_ut1_utc,
lon,
lat,
height,
xp,
yp,
pressure,
temperature,
relative_humidity,
obswl,
)
erfadct = _erfa_check(fullstack_icrs.ra.rad, fullstack_icrs.dec.rad, astrom)
npt.assert_allclose(erfadct["alt"], aacoo.alt.radian, atol=1e-7)
npt.assert_allclose(erfadct["az"], aacoo.az.radian, atol=1e-7) |
Test the full transform from ICRS <-> AltAz | def test_fiducial_roudtrip(fullstack_icrs, fullstack_fiducial_altaz):
"""
Test the full transform from ICRS <-> AltAz
"""
aacoo = fullstack_icrs.transform_to(fullstack_fiducial_altaz)
# make sure the round-tripping works
icrs2 = aacoo.transform_to(ICRS())
npt.assert_allclose(fullstack_icrs.ra.deg, icrs2.ra.deg)
npt.assert_allclose(fullstack_icrs.dec.deg, icrs2.dec.deg) |
While this does test the full stack, it is mostly meant to check that a
warning is raised when attempting to get to AltAz in the future (beyond
IERS tables) | def test_future_altaz():
"""
While this does test the full stack, it is mostly meant to check that a
warning is raised when attempting to get to AltAz in the future (beyond
IERS tables)
"""
# this is an ugly hack to get the warning to show up even if it has already
# appeared
from astropy.coordinates.builtin_frames import utils
from astropy.utils.exceptions import AstropyWarning
if hasattr(utils, "__warningregistry__"):
utils.__warningregistry__.clear()
location = EarthLocation(lat=0 * u.deg, lon=0 * u.deg)
t = Time("J2161")
# check that these message(s) appear among any other warnings. If tests are run with
# --remote-data then the IERS table will be an instance of IERS_Auto which is
# assured of being "fresh". In this case getting times outside the range of the
# table does not raise an exception. Only if using IERS_B (which happens without
# --remote-data, i.e. for all CI testing) do we expect another warning.
if PYTEST_LT_8_0:
ctx1 = ctx2 = nullcontext()
else:
ctx1 = pytest.warns(erfa.core.ErfaWarning)
ctx2 = pytest.warns(AstropyWarning, match=".*times are outside of range.*")
with (
ctx1,
ctx2,
pytest.warns(
AstropyWarning,
match="Tried to get polar motions for times after IERS data is valid.*",
) as found_warnings,
):
SkyCoord(1 * u.deg, 2 * u.deg).transform_to(AltAz(location=location, obstime=t))
if isinstance(iers.earth_orientation_table.get(), iers.IERS_B):
assert any(
"(some) times are outside of range covered by IERS table." in str(w.message)
for w in found_warnings
) |
Check ICRS<->AltAz for consistency with ICRS<->CIRS<->AltAz
The latter is extensively tested in test_intermediate_transformations.py | def test_icrs_altaz_consistency():
"""
Check ICRS<->AltAz for consistency with ICRS<->CIRS<->AltAz
The latter is extensively tested in test_intermediate_transformations.py
"""
usph = golden_spiral_grid(200)
dist = np.linspace(0.5, 1, len(usph)) * u.km * 1e5
icoo = SkyCoord(ra=usph.lon, dec=usph.lat, distance=dist)
observer = EarthLocation(28 * u.deg, 23 * u.deg, height=2000.0 * u.km)
obstime = Time("J2010")
aa_frame = AltAz(obstime=obstime, location=observer)
# check we are going direct!
trans = frame_transform_graph.get_transform(ICRS, AltAz).transforms
assert len(trans) == 1
# check that ICRS-AltAz and ICRS->CIRS->AltAz are consistent
aa1 = icoo.transform_to(aa_frame)
aa2 = icoo.transform_to(CIRS()).transform_to(aa_frame)
assert_allclose(aa1.separation_3d(aa2), 0 * u.mm, atol=1 * u.mm)
# check roundtrip
roundtrip = icoo.transform_to(aa_frame).transform_to(icoo)
assert_allclose(roundtrip.separation_3d(icoo), 0 * u.mm, atol=1 * u.mm)
# check there and back via CIRS mish-mash
roundtrip = icoo.transform_to(aa_frame).transform_to(CIRS()).transform_to(icoo)
assert_allclose(roundtrip.separation_3d(icoo), 0 * u.mm, atol=1 * u.mm) |
Check ICRS<->HADec for consistency with ICRS<->CIRS<->HADec | def test_icrs_hadec_consistency():
"""
Check ICRS<->HADec for consistency with ICRS<->CIRS<->HADec
"""
usph = golden_spiral_grid(200)
dist = np.linspace(0.5, 1, len(usph)) * u.km * 1e5
icoo = SkyCoord(ra=usph.lon, dec=usph.lat, distance=dist)
observer = EarthLocation(28 * u.deg, 23 * u.deg, height=2000.0 * u.km)
obstime = Time("J2010")
hd_frame = HADec(obstime=obstime, location=observer)
# check we are going direct!
trans = frame_transform_graph.get_transform(ICRS, HADec).transforms
assert len(trans) == 1
# check that ICRS-HADec and ICRS->CIRS->HADec are consistent
aa1 = icoo.transform_to(hd_frame)
aa2 = icoo.transform_to(CIRS()).transform_to(hd_frame)
assert_allclose(aa1.separation_3d(aa2), 0 * u.mm, atol=1 * u.mm)
# check roundtrip
roundtrip = icoo.transform_to(hd_frame).transform_to(icoo)
assert_allclose(roundtrip.separation_3d(icoo), 0 * u.mm, atol=1 * u.mm)
# check there and back via CIRS mish-mash
roundtrip = icoo.transform_to(hd_frame).transform_to(CIRS()).transform_to(icoo)
assert_allclose(roundtrip.separation_3d(icoo), 0 * u.mm, atol=1 * u.mm) |
Check a few cases of ICRS<->CIRS for consistency.
Also includes the CIRS<->CIRS transforms at different times, as those go
through ICRS | def test_icrs_cirs():
"""
Check a few cases of ICRS<->CIRS for consistency.
Also includes the CIRS<->CIRS transforms at different times, as those go
through ICRS
"""
usph = golden_spiral_grid(200)
dist = np.linspace(0.0, 1, len(usph)) * u.pc
inod = ICRS(usph)
iwd = ICRS(ra=usph.lon, dec=usph.lat, distance=dist)
cframe1 = CIRS()
cirsnod = inod.transform_to(cframe1) # uses the default time
# first do a round-tripping test
inod2 = cirsnod.transform_to(ICRS())
assert_allclose(inod.ra, inod2.ra)
assert_allclose(inod.dec, inod2.dec)
# now check that a different time yields different answers
cframe2 = CIRS(obstime=Time("J2005"))
cirsnod2 = inod.transform_to(cframe2)
assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8)
assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8)
# parallax effects should be included, so with and w/o distance should be different
cirswd = iwd.transform_to(cframe1)
assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8)
assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8)
# and the distance should transform at least somehow
assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8)
# now check that the cirs self-transform works as expected
cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op
assert_allclose(cirsnod.ra, cirsnod3.ra)
assert_allclose(cirsnod.dec, cirsnod3.dec)
cirsnod4 = cirsnod.transform_to(cframe2) # should be different
assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8)
assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8)
cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same
assert_allclose(cirsnod.ra, cirsnod5.ra)
assert_allclose(cirsnod.dec, cirsnod5.dec) |
Check ICRS<->GCRS for consistency | def test_icrs_gcrs(icoo):
"""
Check ICRS<->GCRS for consistency
"""
gcrscoo = icoo.transform_to(gcrs_frames[0]) # uses the default time
# first do a round-tripping test
icoo2 = gcrscoo.transform_to(ICRS())
assert_allclose(icoo.distance, icoo2.distance)
assert_allclose(icoo.ra, icoo2.ra)
assert_allclose(icoo.dec, icoo2.dec)
assert isinstance(icoo2.data, icoo.data.__class__)
# now check that a different time yields different answers
gcrscoo2 = icoo.transform_to(gcrs_frames[1])
assert not allclose(gcrscoo.ra, gcrscoo2.ra, rtol=1e-8, atol=1e-10 * u.deg)
assert not allclose(gcrscoo.dec, gcrscoo2.dec, rtol=1e-8, atol=1e-10 * u.deg)
# now check that the cirs self-transform works as expected
gcrscoo3 = gcrscoo.transform_to(gcrs_frames[0]) # should be a no-op
assert_allclose(gcrscoo.ra, gcrscoo3.ra)
assert_allclose(gcrscoo.dec, gcrscoo3.dec)
gcrscoo4 = gcrscoo.transform_to(gcrs_frames[1]) # should be different
assert not allclose(gcrscoo4.ra, gcrscoo.ra, rtol=1e-8, atol=1e-10 * u.deg)
assert not allclose(gcrscoo4.dec, gcrscoo.dec, rtol=1e-8, atol=1e-10 * u.deg)
gcrscoo5 = gcrscoo4.transform_to(gcrs_frames[0]) # should be back to the same
assert_allclose(gcrscoo.ra, gcrscoo5.ra, rtol=1e-8, atol=1e-10 * u.deg)
assert_allclose(gcrscoo.dec, gcrscoo5.dec, rtol=1e-8, atol=1e-10 * u.deg)
# also make sure that a GCRS with a different geoloc/geovel gets a different answer
# roughly a moon-like frame
gframe3 = GCRS(obsgeoloc=[385000.0, 0, 0] * u.km, obsgeovel=[1, 0, 0] * u.km / u.s)
gcrscoo6 = icoo.transform_to(gframe3) # should be different
assert not allclose(gcrscoo.ra, gcrscoo6.ra, rtol=1e-8, atol=1e-10 * u.deg)
assert not allclose(gcrscoo.dec, gcrscoo6.dec, rtol=1e-8, atol=1e-10 * u.deg)
icooviag3 = gcrscoo6.transform_to(ICRS()) # and now back to the original
assert_allclose(icoo.ra, icooviag3.ra)
assert_allclose(icoo.dec, icooviag3.dec) |
Check that with and without distance give different ICRS<->GCRS answers | def test_icrs_gcrs_dist_diff(gframe):
"""
Check that with and without distance give different ICRS<->GCRS answers
"""
gcrsnod = icrs_coords[0].transform_to(gframe)
gcrswd = icrs_coords[1].transform_to(gframe)
# parallax effects should be included, so with and w/o distance should be different
assert not allclose(gcrswd.ra, gcrsnod.ra, rtol=1e-8, atol=1e-10 * u.deg)
assert not allclose(gcrswd.dec, gcrsnod.dec, rtol=1e-8, atol=1e-10 * u.deg)
# and the distance should transform at least somehow
assert not allclose(
gcrswd.distance, icrs_coords[1].distance, rtol=1e-8, atol=1e-10 * u.pc
) |
Check the basic CIRS<->AltAz transforms. More thorough checks implicitly
happen in `test_iau_fullstack` | def test_cirs_to_altaz():
"""
Check the basic CIRS<->AltAz transforms. More thorough checks implicitly
happen in `test_iau_fullstack`
"""
from astropy.coordinates import EarthLocation
usph = golden_spiral_grid(200)
dist = np.linspace(0.5, 1, len(usph)) * u.pc
cirs = CIRS(usph, obstime="J2000")
crepr = SphericalRepresentation(lon=usph.lon, lat=usph.lat, distance=dist)
cirscart = CIRS(
crepr, obstime=cirs.obstime, representation_type=CartesianRepresentation
)
loc = EarthLocation(lat=0 * u.deg, lon=0 * u.deg, height=0 * u.m)
altazframe = AltAz(location=loc, obstime=Time("J2005"))
cirs2 = cirs.transform_to(altazframe).transform_to(cirs)
cirs3 = cirscart.transform_to(altazframe).transform_to(cirs)
# check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert_allclose(cirs.ra, cirs3.ra)
assert_allclose(cirs.dec, cirs3.dec) |
Check the basic CIRS<->HADec transforms. | def test_cirs_to_hadec():
"""
Check the basic CIRS<->HADec transforms.
"""
from astropy.coordinates import EarthLocation
usph = golden_spiral_grid(200)
dist = np.linspace(0.5, 1, len(usph)) * u.pc
cirs = CIRS(usph, obstime="J2000")
crepr = SphericalRepresentation(lon=usph.lon, lat=usph.lat, distance=dist)
cirscart = CIRS(
crepr, obstime=cirs.obstime, representation_type=CartesianRepresentation
)
loc = EarthLocation(lat=0 * u.deg, lon=0 * u.deg, height=0 * u.m)
hadecframe = HADec(location=loc, obstime=Time("J2005"))
cirs2 = cirs.transform_to(hadecframe).transform_to(cirs)
cirs3 = cirscart.transform_to(hadecframe).transform_to(cirs)
# check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert_allclose(cirs.ra, cirs3.ra)
assert_allclose(cirs.dec, cirs3.dec) |
Check basic GCRS<->ITRS transforms for round-tripping. | def test_gcrs_itrs():
"""
Check basic GCRS<->ITRS transforms for round-tripping.
"""
usph = golden_spiral_grid(200)
gcrs = GCRS(usph, obstime="J2000")
gcrs6 = GCRS(usph, obstime="J2006")
gcrs2 = gcrs.transform_to(ITRS()).transform_to(gcrs)
gcrs6_2 = gcrs6.transform_to(ITRS()).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs2.ra)
assert_allclose(gcrs.dec, gcrs2.dec)
# these should be different:
assert not allclose(gcrs.ra, gcrs6_2.ra, rtol=1e-8)
assert not allclose(gcrs.dec, gcrs6_2.dec, rtol=1e-8)
# also try with the cartesian representation
gcrsc = gcrs.realize_frame(gcrs.data)
gcrsc.representation_type = CartesianRepresentation
gcrsc2 = gcrsc.transform_to(ITRS()).transform_to(gcrsc)
assert_allclose(gcrsc.spherical.lon, gcrsc2.ra)
assert_allclose(gcrsc.spherical.lat, gcrsc2.dec) |
Check basic CIRS<->ITRS geocentric transforms for round-tripping. | def test_cirs_itrs():
"""
Check basic CIRS<->ITRS geocentric transforms for round-tripping.
"""
usph = golden_spiral_grid(200)
cirs = CIRS(usph, obstime="J2000")
cirs6 = CIRS(usph, obstime="J2006")
cirs2 = cirs.transform_to(ITRS()).transform_to(cirs)
cirs6_2 = cirs6.transform_to(ITRS()).transform_to(cirs) # different obstime
# just check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert not allclose(cirs.ra, cirs6_2.ra)
assert not allclose(cirs.dec, cirs6_2.dec) |
Check basic CIRS<->ITRS topocentric transforms for round-tripping. | def test_cirs_itrs_topo():
"""
Check basic CIRS<->ITRS topocentric transforms for round-tripping.
"""
loc = EarthLocation(lat=0 * u.deg, lon=0 * u.deg, height=0 * u.m)
usph = golden_spiral_grid(200)
cirs = CIRS(usph, obstime="J2000", location=loc)
cirs6 = CIRS(usph, obstime="J2006", location=loc)
cirs2 = cirs.transform_to(ITRS(location=loc)).transform_to(cirs)
# different obstime
cirs6_2 = cirs6.transform_to(ITRS(location=loc)).transform_to(cirs)
# just check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert not allclose(cirs.ra, cirs6_2.ra)
assert not allclose(cirs.dec, cirs6_2.dec) |
Check GCRS<->CIRS transforms for round-tripping. More complicated than the
above two because it's multi-hop | def test_gcrs_cirs():
"""
Check GCRS<->CIRS transforms for round-tripping. More complicated than the
above two because it's multi-hop
"""
usph = golden_spiral_grid(200)
gcrs = GCRS(usph, obstime="J2000")
gcrs6 = GCRS(usph, obstime="J2006")
gcrs2 = gcrs.transform_to(CIRS()).transform_to(gcrs)
gcrs6_2 = gcrs6.transform_to(CIRS()).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs2.ra)
assert_allclose(gcrs.dec, gcrs2.dec)
# these should be different:
assert not allclose(gcrs.ra, gcrs6_2.ra, rtol=1e-8)
assert not allclose(gcrs.dec, gcrs6_2.dec, rtol=1e-8)
# now try explicit intermediate pathways and ensure they're all consistent
gcrs3 = (
gcrs.transform_to(ITRS())
.transform_to(CIRS())
.transform_to(ITRS())
.transform_to(gcrs)
)
assert_allclose(gcrs.ra, gcrs3.ra)
assert_allclose(gcrs.dec, gcrs3.dec)
gcrs4 = (
gcrs.transform_to(ICRS())
.transform_to(CIRS())
.transform_to(ICRS())
.transform_to(gcrs)
)
assert_allclose(gcrs.ra, gcrs4.ra)
assert_allclose(gcrs.dec, gcrs4.dec) |
Check GCRS<->AltAz transforms for round-tripping. Has multiple paths | def test_gcrs_altaz():
"""
Check GCRS<->AltAz transforms for round-tripping. Has multiple paths
"""
from astropy.coordinates import EarthLocation
usph = golden_spiral_grid(128)
gcrs = GCRS(usph, obstime="J2000")[None] # broadcast with times below
# check array times sure N-d arrays work
times = Time(np.linspace(2456293.25, 2456657.25, 51) * u.day, format="jd")[:, None]
loc = EarthLocation(lon=10 * u.deg, lat=80.0 * u.deg)
aaframe = AltAz(obstime=times, location=loc)
aa1 = gcrs.transform_to(aaframe)
aa2 = gcrs.transform_to(ICRS()).transform_to(CIRS()).transform_to(aaframe)
aa3 = gcrs.transform_to(ITRS()).transform_to(CIRS()).transform_to(aaframe)
# make sure they're all consistent
assert_allclose(aa1.alt, aa2.alt)
assert_allclose(aa1.az, aa2.az)
assert_allclose(aa1.alt, aa3.alt)
assert_allclose(aa1.az, aa3.az) |
Check GCRS<->HADec transforms for round-tripping. Has multiple paths | def test_gcrs_hadec():
"""
Check GCRS<->HADec transforms for round-tripping. Has multiple paths
"""
from astropy.coordinates import EarthLocation
usph = golden_spiral_grid(128)
gcrs = GCRS(usph, obstime="J2000") # broadcast with times below
# check array times sure N-d arrays work
times = Time(np.linspace(2456293.25, 2456657.25, 51) * u.day, format="jd")[:, None]
loc = EarthLocation(lon=10 * u.deg, lat=80.0 * u.deg)
hdframe = HADec(obstime=times, location=loc)
hd1 = gcrs.transform_to(hdframe)
hd2 = gcrs.transform_to(ICRS()).transform_to(CIRS()).transform_to(hdframe)
hd3 = gcrs.transform_to(ITRS()).transform_to(CIRS()).transform_to(hdframe)
# make sure they're all consistent
assert_allclose(hd1.dec, hd2.dec)
assert_allclose(hd1.ha, hd2.ha)
assert_allclose(hd1.dec, hd3.dec)
assert_allclose(hd1.ha, hd3.ha) |
Sanity-check that the sun is at a reasonable distance from any altaz | def test_gcrs_altaz_sunish(testframe):
"""
Sanity-check that the sun is at a reasonable distance from any altaz
"""
sun = get_sun(testframe.obstime)
assert sun.frame.name == "gcrs"
# the .to(u.au) is not necessary, it just makes the asserts on failure more readable
assert (EARTHECC - 1) * u.au < sun.distance.to(u.au) < (EARTHECC + 1) * u.au
sunaa = sun.transform_to(testframe)
assert (EARTHECC - 1) * u.au < sunaa.distance.to(u.au) < (EARTHECC + 1) * u.au |
Subsets and Splits