response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Sanity-check that an object resembling the moon goes to the right place with a GCRS->AltAz transformation
def test_gcrs_altaz_moonish(testframe): """ Sanity-check that an object resembling the moon goes to the right place with a GCRS->AltAz transformation """ moon = GCRS(MOONDIST_CART, obstime=testframe.obstime) moonaa = moon.transform_to(testframe) # now check that the distance change is similar to earth radius assert 1000 * u.km < np.abs(moonaa.distance - moon.distance).to(u.au) < 7000 * u.km # now check that it round-trips moon2 = moonaa.transform_to(moon) assert_allclose(moon.cartesian.xyz, moon2.cartesian.xyz)
Repeat of both the moonish and sunish tests above to make sure the two routes through the coordinate graph are consistent with each other
def test_gcrs_altaz_bothroutes(testframe): """ Repeat of both the moonish and sunish tests above to make sure the two routes through the coordinate graph are consistent with each other """ sun = get_sun(testframe.obstime) sunaa_viaicrs = sun.transform_to(ICRS()).transform_to(testframe) sunaa_viaitrs = sun.transform_to(ITRS(obstime=testframe.obstime)).transform_to( testframe ) moon = GCRS(MOONDIST_CART, obstime=testframe.obstime) moonaa_viaicrs = moon.transform_to(ICRS()).transform_to(testframe) moonaa_viaitrs = moon.transform_to(ITRS(obstime=testframe.obstime)).transform_to( testframe ) assert_allclose(sunaa_viaicrs.cartesian.xyz, sunaa_viaitrs.cartesian.xyz) assert_allclose(moonaa_viaicrs.cartesian.xyz, moonaa_viaitrs.cartesian.xyz)
Sanity-check that an object resembling the moon goes to the right place with a CIRS<->AltAz transformation
def test_cirs_altaz_moonish(testframe): """ Sanity-check that an object resembling the moon goes to the right place with a CIRS<->AltAz transformation """ moon = CIRS(MOONDIST_CART, obstime=testframe.obstime) moonaa = moon.transform_to(testframe) assert 1000 * u.km < np.abs(moonaa.distance - moon.distance).to(u.km) < 7000 * u.km # now check that it round-trips moon2 = moonaa.transform_to(moon) assert_allclose(moon.cartesian.xyz, moon2.cartesian.xyz)
Check that a UnitSphericalRepresentation coordinate round-trips for the CIRS<->AltAz transformation.
def test_cirs_altaz_nodist(testframe): """ Check that a UnitSphericalRepresentation coordinate round-trips for the CIRS<->AltAz transformation. """ coo0 = CIRS( UnitSphericalRepresentation(10 * u.deg, 20 * u.deg), obstime=testframe.obstime ) # check that it round-trips coo1 = coo0.transform_to(testframe).transform_to(coo0) assert_allclose(coo0.cartesian.xyz, coo1.cartesian.xyz)
check that something like the moon goes to about the right distance from the ICRS origin when starting from CIRS
def test_cirs_icrs_moonish(testframe): """ check that something like the moon goes to about the right distance from the ICRS origin when starting from CIRS """ moonish = CIRS(MOONDIST_CART, obstime=testframe.obstime) moonicrs = moonish.transform_to(ICRS()) assert 0.97 * u.au < moonicrs.distance < 1.03 * u.au
check that something like the moon goes to about the right distance from the ICRS origin when starting from GCRS
def test_gcrs_icrs_moonish(testframe): """ check that something like the moon goes to about the right distance from the ICRS origin when starting from GCRS """ moonish = GCRS(MOONDIST_CART, obstime=testframe.obstime) moonicrs = moonish.transform_to(ICRS()) assert 0.97 * u.au < moonicrs.distance < 1.03 * u.au
check that the ICRS barycenter goes to about the right distance from various ~geocentric frames (other than testframe)
def test_icrs_gcrscirs_sunish(testframe): """ check that the ICRS barycenter goes to about the right distance from various ~geocentric frames (other than testframe) """ # slight offset to avoid divide-by-zero errors icrs = ICRS(0 * u.deg, 0 * u.deg, distance=10 * u.km) gcrs = icrs.transform_to(GCRS(obstime=testframe.obstime)) assert (EARTHECC - 1) * u.au < gcrs.distance.to(u.au) < (EARTHECC + 1) * u.au cirs = icrs.transform_to(CIRS(obstime=testframe.obstime)) assert (EARTHECC - 1) * u.au < cirs.distance.to(u.au) < (EARTHECC + 1) * u.au itrs = icrs.transform_to(ITRS(obstime=testframe.obstime)) assert ( (EARTHECC - 1) * u.au < itrs.spherical.distance.to(u.au) < (EARTHECC + 1) * u.au )
Check that something expressed in *ICRS* as being moon-like goes to the right AltAz distance
def test_icrs_altaz_moonish(testframe): """ Check that something expressed in *ICRS* as being moon-like goes to the right AltAz distance """ # we use epv00 instead of get_sun because get_sun includes aberration earth_pv_helio, earth_pv_bary = erfa.epv00(*get_jd12(testframe.obstime, "tdb")) earth_icrs_xyz = earth_pv_bary[0] * u.au moonoffset = [0, 0, MOONDIST.value] * MOONDIST.unit moonish_icrs = ICRS(CartesianRepresentation(earth_icrs_xyz + moonoffset)) moonaa = moonish_icrs.transform_to(testframe) # now check that the distance change is similar to earth radius assert 1000 * u.km < np.abs(moonaa.distance - MOONDIST).to(u.au) < 7000 * u.km
Tests GCRS self transform for objects which are nearby and thus have reasonable parallax. Moon positions were originally created using JPL DE432s ephemeris. The two lunar positions (one geocentric, one at a defined location) are created via a transformation from ICRS to two different GCRS frames. We test that the GCRS-GCRS self transform can correctly map one GCRS frame onto the other.
def test_gcrs_self_transform_closeby(): """ Tests GCRS self transform for objects which are nearby and thus have reasonable parallax. Moon positions were originally created using JPL DE432s ephemeris. The two lunar positions (one geocentric, one at a defined location) are created via a transformation from ICRS to two different GCRS frames. We test that the GCRS-GCRS self transform can correctly map one GCRS frame onto the other. """ t = Time("2014-12-25T07:00") moon_geocentric = SkyCoord( GCRS( 318.10579159 * u.deg, -11.65281165 * u.deg, 365042.64880308 * u.km, obstime=t, ) ) # this is the location of the Moon as seen from La Palma obsgeoloc = [-5592982.59658935, -63054.1948592, 3059763.90102216] * u.m obsgeovel = [4.59798494, -407.84677071, 0.0] * u.m / u.s moon_lapalma = SkyCoord( GCRS( 318.7048445 * u.deg, -11.98761996 * u.deg, 369722.8231031 * u.km, obstime=t, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel, ) ) transformed = moon_geocentric.transform_to(moon_lapalma.frame) delta = transformed.separation_3d(moon_lapalma) assert_allclose(delta, 0.0 * u.m, atol=1 * u.m)
Test case transform from TEME to ITRF. Test case derives from example on appendix C of Vallado, Crawford, Hujsak & Kelso (2006). See https://celestrak.org/publications/AIAA/2006-6753/AIAA-2006-6753-Rev2.pdf
def test_teme_itrf(): """ Test case transform from TEME to ITRF. Test case derives from example on appendix C of Vallado, Crawford, Hujsak & Kelso (2006). See https://celestrak.org/publications/AIAA/2006-6753/AIAA-2006-6753-Rev2.pdf """ v_itrf = CartesianDifferential( -3.225636520, -2.872451450, 5.531924446, unit=u.km / u.s ) p_itrf = CartesianRepresentation( -1033.479383, 7901.2952740, 6380.35659580, unit=u.km, differentials={"s": v_itrf}, ) t = Time("2004-04-06T07:51:28.386") teme = ITRS(p_itrf, obstime=t).transform_to(TEME(obstime=t)) v_teme = CartesianDifferential( -4.746131487, 0.785818041, 5.531931288, unit=u.km / u.s ) p_teme = CartesianRepresentation( 5094.18016210, 6127.64465050, 6380.34453270, unit=u.km, differentials={"s": v_teme}, ) assert_allclose( teme.cartesian.without_differentials().xyz, p_teme.without_differentials().xyz, atol=30 * u.cm, ) assert_allclose( teme.cartesian.differentials["s"].d_xyz, p_teme.differentials["s"].d_xyz, atol=1.0 * u.cm / u.s, ) # test round trip itrf = teme.transform_to(ITRS(obstime=t)) assert_allclose( itrf.cartesian.without_differentials().xyz, p_itrf.without_differentials().xyz, atol=100 * u.cm, ) assert_allclose( itrf.cartesian.differentials["s"].d_xyz, p_itrf.differentials["s"].d_xyz, atol=1 * u.cm / u.s, )
Check that we can set the IERS table used as Earth Reference. Use the here and now to be sure we get a difference.
def test_earth_orientation_table(monkeypatch): """Check that we can set the IERS table used as Earth Reference. Use the here and now to be sure we get a difference. """ monkeypatch.setattr("astropy.utils.iers.conf.auto_download", True) t = Time.now() location = EarthLocation(lat=0 * u.deg, lon=0 * u.deg) altaz = AltAz(location=location, obstime=t) sc = SkyCoord(1 * u.deg, 2 * u.deg) # Default: uses IERS_Auto, which will give a prediction. # Note: tests run with warnings turned into errors, so it is # meaningful if this passes. if CI: with warnings.catch_warnings(): # Server occasionally blocks IERS download in CI. warnings.filterwarnings("ignore", message=r".*using local IERS-B.*") # This also captures unclosed socket warning that is ignored in pyproject.toml warnings.filterwarnings("ignore", message=r".*unclosed.*") altaz_auto = sc.transform_to(altaz) else: altaz_auto = sc.transform_to(altaz) # No warnings with iers.earth_orientation_table.set(iers.IERS_B.open()): with pytest.warns(AstropyWarning, match="after IERS data"): altaz_b = sc.transform_to(altaz) sep_b_auto = altaz_b.separation(altaz_auto) assert_allclose(sep_b_auto, 0.0 * u.deg, atol=1 * u.arcsec) assert sep_b_auto > 10 * u.microarcsecond # Check we returned to regular IERS system. altaz_auto2 = sc.transform_to(altaz) assert_allclose(altaz_auto2.separation(altaz_auto), 0 * u.deg)
We test that using different ephemerides gives very similar results for transformations
def test_ephemerides(): """ We test that using different ephemerides gives very similar results for transformations """ t = Time("2014-12-25T07:00") moon = SkyCoord( GCRS( 318.10579159 * u.deg, -11.65281165 * u.deg, 365042.64880308 * u.km, obstime=t, ) ) icrs_frame = ICRS() hcrs_frame = HCRS(obstime=t) ecl_frame = HeliocentricMeanEcliptic(equinox=t) cirs_frame = CIRS(obstime=t) moon_icrs_builtin = moon.transform_to(icrs_frame) moon_hcrs_builtin = moon.transform_to(hcrs_frame) moon_helioecl_builtin = moon.transform_to(ecl_frame) moon_cirs_builtin = moon.transform_to(cirs_frame) with solar_system_ephemeris.set("jpl"): moon_icrs_jpl = moon.transform_to(icrs_frame) moon_hcrs_jpl = moon.transform_to(hcrs_frame) moon_helioecl_jpl = moon.transform_to(ecl_frame) moon_cirs_jpl = moon.transform_to(cirs_frame) # most transformations should differ by an amount which is # non-zero but of order milliarcsecs sep_icrs = moon_icrs_builtin.separation(moon_icrs_jpl) sep_hcrs = moon_hcrs_builtin.separation(moon_hcrs_jpl) sep_helioecl = moon_helioecl_builtin.separation(moon_helioecl_jpl) sep_cirs = moon_cirs_builtin.separation(moon_cirs_jpl) assert_allclose([sep_icrs, sep_hcrs, sep_helioecl], 0.0 * u.deg, atol=10 * u.mas) assert all( sep > 10 * u.microarcsecond for sep in (sep_icrs, sep_hcrs, sep_helioecl) ) # CIRS should be the same assert_allclose(sep_cirs, 0.0 * u.deg, atol=1 * u.microarcsecond)
We test the TETE transforms for proper behaviour here. The TETE transforms are tested for accuracy against JPL Horizons in test_solar_system.py. Here we are looking to check for consistency and errors in the self transform.
def test_tete_transforms(): """ We test the TETE transforms for proper behaviour here. The TETE transforms are tested for accuracy against JPL Horizons in test_solar_system.py. Here we are looking to check for consistency and errors in the self transform. """ loc = EarthLocation.from_geodetic("-22°57'35.1", "-67°47'14.1", 5186 * u.m) time = Time("2020-04-06T00:00") p, v = loc.get_gcrs_posvel(time) gcrs_frame = GCRS(obstime=time, obsgeoloc=p, obsgeovel=v) moon = SkyCoord( 169.24113968 * u.deg, 10.86086666 * u.deg, 358549.25381755 * u.km, frame=gcrs_frame, ) tete_frame = TETE(obstime=time, location=loc) # need to set obsgeoloc/vel explicitly or skycoord behaviour over-writes tete_geo = TETE(obstime=time, location=EarthLocation(*([0, 0, 0] * u.km))) # test self-transform by comparing to GCRS-TETE-ITRS-TETE route tete_coo1 = moon.transform_to(tete_frame) tete_coo2 = moon.transform_to(tete_geo) assert_allclose(tete_coo1.separation_3d(tete_coo2), 0 * u.mm, atol=1 * u.mm) # test TETE-ITRS transform by comparing GCRS-CIRS-ITRS to GCRS-TETE-ITRS itrs1 = moon.transform_to(CIRS()).transform_to(ITRS()) itrs2 = moon.transform_to(TETE()).transform_to(ITRS()) assert_allclose(itrs1.separation_3d(itrs2), 0 * u.mm, atol=1 * u.mm) # test round trip GCRS->TETE->GCRS new_moon = moon.transform_to(TETE()).transform_to(moon) assert_allclose(new_moon.separation_3d(moon), 0 * u.mm, atol=1 * u.mm) # test round trip via ITRS tete_rt = tete_coo1.transform_to(ITRS(obstime=time)).transform_to(tete_coo1) assert_allclose(tete_rt.separation_3d(tete_coo1), 0 * u.mm, atol=1 * u.mm)
With a precise CIRS<->Observed transformation this should give Alt=90 exactly If the CIRS self-transform breaks it won't, due to improper treatment of aberration
def test_straight_overhead(): """ With a precise CIRS<->Observed transformation this should give Alt=90 exactly If the CIRS self-transform breaks it won't, due to improper treatment of aberration """ t = Time("J2010") obj = EarthLocation(-1 * u.deg, 52 * u.deg, height=10.0 * u.km) home = EarthLocation(-1 * u.deg, 52 * u.deg, height=0.0 * u.km) # An object that appears straight overhead - FOR A GEOCENTRIC OBSERVER. # Note, this won't be overhead for a topocentric observer because of # aberration. cirs_geo = obj.get_itrs(t).transform_to(CIRS(obstime=t)) # now get the Geocentric CIRS position of observatory obsrepr = home.get_itrs(t).transform_to(CIRS(obstime=t)).cartesian # topocentric CIRS position of a straight overhead object cirs_repr = cirs_geo.cartesian - obsrepr # create a CIRS object that appears straight overhead for a TOPOCENTRIC OBSERVER topocentric_cirs_frame = CIRS(obstime=t, location=home) cirs_topo = topocentric_cirs_frame.realize_frame(cirs_repr) # Check AltAz (though Azimuth can be anything so is not tested). aa = cirs_topo.transform_to(AltAz(obstime=t, location=home)) assert_allclose(aa.alt, 90 * u.deg, atol=1 * u.uas, rtol=0) # Check HADec. hd = cirs_topo.transform_to(HADec(obstime=t, location=home)) assert_allclose(hd.ha, 0 * u.hourangle, atol=1 * u.uas, rtol=0) assert_allclose(hd.dec, 52 * u.deg, atol=1 * u.uas, rtol=0)
With a precise ITRS<->Observed transformation this should give Alt=90 exactly
def test_itrs_straight_overhead(): """ With a precise ITRS<->Observed transformation this should give Alt=90 exactly """ t = Time("J2010") obj = EarthLocation(-1 * u.deg, 52 * u.deg, height=10.0 * u.km) home = EarthLocation(-1 * u.deg, 52 * u.deg, height=0.0 * u.km) # Check AltAz (though Azimuth can be anything so is not tested). aa = obj.get_itrs(t, location=home).transform_to(AltAz(obstime=t, location=home)) assert_allclose(aa.alt, 90 * u.deg, atol=1 * u.uas, rtol=0) # Check HADec. hd = obj.get_itrs(t, location=home).transform_to(HADec(obstime=t, location=home)) assert_allclose(hd.ha, 0 * u.hourangle, atol=1 * u.uas, rtol=0) assert_allclose(hd.dec, 52 * u.deg, atol=1 * u.uas, rtol=0)
Check if jplephem is installed and has version >= minversion.
def jplephem_ge(minversion): """Check if jplephem is installed and has version >= minversion.""" # This is a separate routine since somehow with pyinstaller the stanza # not HAS_JPLEPHEM or metadata.version('jplephem') < '2.15' # leads to a module not found error. try: return HAS_JPLEPHEM and metadata.version("jplephem") >= minversion except Exception: return False
These tests are provided by @mkbrewer - see issue #10356. The code that produces them agrees very well (<0.5 mas) with SkyField once Polar motion is turned off, but SkyField does not include polar motion, so a comparison to Skyfield or JPL Horizons will be ~1" off. The absence of polar motion within Skyfield and the disagreement between Skyfield and Horizons make high precision comparisons to those codes difficult. Updated 2020-11-29, after the comparison between codes became even better, down to 100 nas. Updated 2023-02-14, after IERS changes the IERS B format and analysis, causing small deviations. NOTE: the agreement reflects consistency in approach between two codes, not necessarily absolute precision. If this test starts failing, the tolerance can and should be weakened *if* it is clear that the change is due to an improvement (e.g., a new IAU precession model).
def test_aa_hd_high_precision(): """These tests are provided by @mkbrewer - see issue #10356. The code that produces them agrees very well (<0.5 mas) with SkyField once Polar motion is turned off, but SkyField does not include polar motion, so a comparison to Skyfield or JPL Horizons will be ~1" off. The absence of polar motion within Skyfield and the disagreement between Skyfield and Horizons make high precision comparisons to those codes difficult. Updated 2020-11-29, after the comparison between codes became even better, down to 100 nas. Updated 2023-02-14, after IERS changes the IERS B format and analysis, causing small deviations. NOTE: the agreement reflects consistency in approach between two codes, not necessarily absolute precision. If this test starts failing, the tolerance can and should be weakened *if* it is clear that the change is due to an improvement (e.g., a new IAU precession model). """ lat = -22.959748 * u.deg lon = -67.787260 * u.deg elev = 5186 * u.m loc = EarthLocation.from_geodetic(lon, lat, elev) # Note: at this level of precision for the comparison, we have to include # the location in the time, as it influences the transformation to TDB. t = Time("2017-04-06T00:00:00.0", location=loc) with solar_system_ephemeris.set("de430"): moon = get_body("moon", t, loc) moon_aa = moon.transform_to(AltAz(obstime=t, location=loc)) moon_hd = moon.transform_to(HADec(obstime=t, location=loc)) # Numbers from # https://github.com/astropy/astropy/pull/11073#issuecomment-735486271 # updated in https://github.com/astropy/astropy/issues/11683 # and again after the IERS_B change. TARGET_AZ, TARGET_EL = 15.032673662647138 * u.deg, 50.303110087520054 * u.deg TARGET_DISTANCE = 376252.88325051306 * u.km assert_allclose(moon_aa.az, TARGET_AZ, atol=0.1 * u.uas, rtol=0) assert_allclose(moon_aa.alt, TARGET_EL, atol=0.1 * u.uas, rtol=0) assert_allclose(moon_aa.distance, TARGET_DISTANCE, atol=0.1 * u.mm, rtol=0) ha, dec = erfa.ae2hd( moon_aa.az.to_value(u.radian), moon_aa.alt.to_value(u.radian), lat.to_value(u.radian), ) ha = u.Quantity(ha, u.radian, copy=False) dec = u.Quantity(dec, u.radian, copy=False) assert_allclose(moon_hd.ha, ha, atol=0.1 * u.uas, rtol=0) assert_allclose(moon_hd.dec, dec, atol=0.1 * u.uas, rtol=0)
These tests are designed to ensure high precision alt-az transforms. They are a slight fudge since the target values come from astropy itself. They are generated with a version of the code that passes the tests above, but for the internal solar system ephemerides to avoid the use of remote data.
def test_aa_high_precision_nodata(): """ These tests are designed to ensure high precision alt-az transforms. They are a slight fudge since the target values come from astropy itself. They are generated with a version of the code that passes the tests above, but for the internal solar system ephemerides to avoid the use of remote data. """ # Last updated when the new IERS B format and analysis was introduced. TARGET_AZ, TARGET_EL = 15.0323151 * u.deg, 50.30271925 * u.deg lat = -22.959748 * u.deg lon = -67.787260 * u.deg elev = 5186 * u.m loc = EarthLocation.from_geodetic(lon, lat, elev) t = Time("2017-04-06T00:00:00.0") moon = get_body("moon", t, loc) moon_aa = moon.transform_to(AltAz(obstime=t, location=loc)) assert_allclose(moon_aa.az - TARGET_AZ, 0 * u.mas, atol=0.5 * u.mas) assert_allclose(moon_aa.alt - TARGET_EL, 0 * u.mas, atol=0.5 * u.mas)
Test the matrix checker ``is_O3``.
def test_is_O3(): """Test the matrix checker ``is_O3``.""" # Normal rotation matrix m1 = rotation_matrix(35 * u.deg, "x") assert is_O3(m1) # and (M, 3, 3) n1 = np.tile(m1, (2, 1, 1)) assert tuple(is_O3(n1)) == (True, True) # (show the broadcasting) # Test atol parameter nn1 = np.tile(0.5 * m1, (2, 1, 1)) assert tuple(is_O3(nn1)) == (False, False) # (show the broadcasting) assert tuple(is_O3(nn1, atol=1)) == (True, True) # (show the broadcasting) # reflection m2 = m1.copy() m2[0, 0] *= -1 assert is_O3(m2) # and (M, 3, 3) n2 = np.stack((m1, m2)) assert tuple(is_O3(n2)) == (True, True) # (show the broadcasting) # Not any sort of O(3) m3 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert not is_O3(m3) # and (M, 3, 3) n3 = np.stack((m1, m3)) assert tuple(is_O3(n3)) == (True, False)
Test the rotation matrix checker ``is_rotation``.
def test_is_rotation(): """Test the rotation matrix checker ``is_rotation``.""" # Normal rotation matrix m1 = rotation_matrix(35 * u.deg, "x") assert is_rotation(m1) assert is_rotation(m1, allow_improper=True) # (a less restrictive test) # and (M, 3, 3) n1 = np.tile(m1, (2, 1, 1)) assert tuple(is_rotation(n1)) == (True, True) # (show the broadcasting) # Test atol parameter nn1 = np.tile(0.5 * m1, (2, 1, 1)) assert tuple(is_rotation(nn1)) == (False, False) # (show the broadcasting) assert tuple(is_rotation(nn1, atol=10)) == (True, True) # (show the broadcasting) # Improper rotation (unit rotation + reflection) m2 = np.identity(3) m2[0, 0] = -1 assert not is_rotation(m2) assert is_rotation(m2, allow_improper=True) # and (M, 3, 3) n2 = np.stack((m1, m2)) assert tuple(is_rotation(n2)) == (True, False) # (show the broadcasting) # Not any sort of rotation m3 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert not is_rotation(m3) assert not is_rotation(m3, allow_improper=True) # and (M, 3, 3) n3 = np.stack((m1, m3)) assert tuple(is_rotation(n3)) == (True, False)
This is a regression test for issue #9249: https://github.com/astropy/astropy/issues/9249
def test_skyoffset_pickle(pickle_protocol, frame): # noqa: F811 """ This is a regression test for issue #9249: https://github.com/astropy/astropy/issues/9249 """ check_pickling_recovery(frame, pickle_protocol)
PR #5085 was put in place to fix the following issue. Issue: https://github.com/astropy/astropy/issues/5069 At root was the transformation of Ecliptic coordinates with non-scalar times.
def test_regression_5085(): """ PR #5085 was put in place to fix the following issue. Issue: https://github.com/astropy/astropy/issues/5069 At root was the transformation of Ecliptic coordinates with non-scalar times. """ # Note: for regression test, we need to be sure that we use UTC for the # epoch, even though more properly that should be TT; but the "expected" # values were calculated using that. j2000 = Time("J2000", scale="utc") times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"]) latitudes = Latitude([3.9807075, -5.00733806, 1.69539491] * u.deg) longitudes = Longitude([311.79678613, 72.86626741, 199.58698226] * u.deg) distances = u.Quantity([0.00243266, 0.0025424, 0.00271296] * u.au) coo = GeocentricMeanEcliptic( lat=latitudes, lon=longitudes, distance=distances, obstime=times, equinox=times ) # expected result ras = Longitude([310.50095400, 314.67109920, 319.56507428] * u.deg) decs = Latitude([-18.25190443, -17.1556676, -15.71616522] * u.deg) distances = u.Quantity([1.78309901, 1.710874, 1.61326649] * u.au) expected_result = GCRS( ra=ras, dec=decs, distance=distances, obstime=j2000 ).cartesian.xyz actual_result = coo.transform_to(GCRS(obstime=j2000)).cartesian.xyz assert_quantity_allclose(expected_result, actual_result)
Issue: https://github.com/astropy/astropy/issues/3920
def test_regression_3920(): """ Issue: https://github.com/astropy/astropy/issues/3920 """ loc = EarthLocation.from_geodetic(0 * u.deg, 0 * u.deg, 0) time = Time("2010-1-1") aa = AltAz(location=loc, obstime=time) sc = SkyCoord(10 * u.deg, 3 * u.deg) assert sc.transform_to(aa).shape == () # That part makes sense: the input is a scalar so the output is too sc2 = SkyCoord(10 * u.deg, 3 * u.deg, 1 * u.AU) assert sc2.transform_to(aa).shape == () # in 3920 that assert fails, because the shape is (1,) # check that the same behavior occurs even if transform is from low-level classes icoo = ICRS(sc.data) icoo2 = ICRS(sc2.data) assert icoo.transform_to(aa).shape == () assert icoo2.transform_to(aa).shape == ()
Issue: https://github.com/astropy/astropy/issues/3938
def test_regression_3938(): """ Issue: https://github.com/astropy/astropy/issues/3938 """ # Set up list of targets - we don't use `from_name` here to avoid # remote_data requirements, but it does the same thing # vega = SkyCoord.from_name('Vega') vega = SkyCoord(279.23473479 * u.deg, 38.78368896 * u.deg) # capella = SkyCoord.from_name('Capella') capella = SkyCoord(79.17232794 * u.deg, 45.99799147 * u.deg) # sirius = SkyCoord.from_name('Sirius') sirius = SkyCoord(101.28715533 * u.deg, -16.71611586 * u.deg) targets = [vega, capella, sirius] # Feed list of targets into SkyCoord combined_coords = SkyCoord(targets) # Set up AltAz frame time = Time("2012-01-01 00:00:00") location = EarthLocation("10d", "45d", 0) aa = AltAz(location=location, obstime=time) combined_coords.transform_to(aa)
Issue: https://github.com/astropy/astropy/issues/3998
def test_regression_3998(): """ Issue: https://github.com/astropy/astropy/issues/3998 """ time = Time("2012-01-01 00:00:00") assert time.isscalar sun = get_sun(time) assert sun.isscalar # in 3998, the above yields False - `sun` is a length-1 vector assert sun.obstime is time
Issue: https://github.com/astropy/astropy/issues/4033
def test_regression_4033(): """ Issue: https://github.com/astropy/astropy/issues/4033 """ # alb = SkyCoord.from_name('Albireo') alb = SkyCoord(292.68033548 * u.deg, 27.95968007 * u.deg) alb_wdist = SkyCoord(alb, distance=133 * u.pc) # de = SkyCoord.from_name('Deneb') de = SkyCoord(310.35797975 * u.deg, 45.28033881 * u.deg) de_wdist = SkyCoord(de, distance=802 * u.pc) aa = AltAz( location=EarthLocation(lat=45 * u.deg, lon=0 * u.deg), obstime="2010-1-1" ) deaa = de.transform_to(aa) albaa = alb.transform_to(aa) alb_wdistaa = alb_wdist.transform_to(aa) de_wdistaa = de_wdist.transform_to(aa) # these work fine sepnod = deaa.separation(albaa) sepwd = deaa.separation(alb_wdistaa) assert_quantity_allclose(sepnod, 22.2862 * u.deg, rtol=1e-6) assert_quantity_allclose(sepwd, 22.2862 * u.deg, rtol=1e-6) # parallax should be present when distance added assert np.abs(sepnod - sepwd) > 1 * u.marcsec # in 4033, the following fail with a recursion error assert_quantity_allclose( de_wdistaa.separation(alb_wdistaa), 22.2862 * u.deg, rtol=1e-3 ) assert_quantity_allclose(alb_wdistaa.separation(deaa), 22.2862 * u.deg, rtol=1e-3)
Issue: https://github.com/astropy/astropy/issues/4082
def test_regression_4082(): """ Issue: https://github.com/astropy/astropy/issues/4082 """ from astropy.coordinates import search_around_3d, search_around_sky cat = SkyCoord([10.076, 10.00455], [18.54746, 18.54896], unit="deg") search_around_sky(cat[0:1], cat, seplimit=u.arcsec * 60, storekdtree=False) # in the issue, this raises a TypeError # also check 3d for good measure, although it's not really affected by this bug directly cat3d = SkyCoord( [10.076, 10.00455] * u.deg, [18.54746, 18.54896] * u.deg, distance=[0.1, 1.5] * u.kpc, ) search_around_3d(cat3d[0:1], cat3d, 1 * u.kpc, storekdtree=False)
Issue: https://github.com/astropy/astropy/issues/4210 Related PR with actual change: https://github.com/astropy/astropy/pull/4211
def test_regression_4210(): """ Issue: https://github.com/astropy/astropy/issues/4210 Related PR with actual change: https://github.com/astropy/astropy/pull/4211 """ crd = SkyCoord(0 * u.deg, 0 * u.deg, distance=1 * u.AU) ecl = crd.geocentricmeanecliptic # bug was that "lambda", which at the time was the name of the geocentric # ecliptic longitude, is a reserved keyword. So this just makes sure the # new name is are all valid ecl.lon # and for good measure, check the other ecliptic systems are all the same # names for their attributes from astropy.coordinates.builtin_frames import ecliptic for frame_name in ecliptic.__all__: eclcls = getattr(ecliptic, frame_name) eclobj = eclcls(1 * u.deg, 2 * u.deg, 3 * u.AU) eclobj.lat eclobj.lon eclobj.distance
Checks that an error is not raised for future times not covered by IERS tables (at least in a simple transform like CIRS->ITRS that simply requires the UTC<->UT1 conversion). Relevant comment: https://github.com/astropy/astropy/pull/4302#discussion_r44836531
def test_regression_futuretimes_4302(): """ Checks that an error is not raised for future times not covered by IERS tables (at least in a simple transform like CIRS->ITRS that simply requires the UTC<->UT1 conversion). Relevant comment: https://github.com/astropy/astropy/pull/4302#discussion_r44836531 """ # 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() # check that out-of-range warning appears 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 isinstance(iers.earth_orientation_table.get(), iers.IERS_B): ctx1 = pytest.warns( AstropyWarning, match=r"\(some\) times are outside of range covered by IERS table.*", ) else: ctx1 = nullcontext() if PYTEST_LT_8_0: ctx2 = ctx3 = nullcontext() else: ctx2 = pytest.warns(ErfaWarning, match=".*dubious year.*") ctx3 = pytest.warns(AstropyWarning, match=".*times after IERS data is valid.*") with ctx1, ctx2, ctx3: future_time = Time("2511-5-1") c = CIRS(1 * u.deg, 2 * u.deg, obstime=future_time) c.transform_to(ITRS(obstime=future_time))
Really just an extra test on FK4 no e, after finding that the units were not always taken correctly. This test is against explicitly doing the transformations on pp170 of Explanatory Supplement to the Astronomical Almanac (Seidelmann, 2005). See https://github.com/astropy/astropy/pull/4293#issuecomment-234973086
def test_regression_4293(): """Really just an extra test on FK4 no e, after finding that the units were not always taken correctly. This test is against explicitly doing the transformations on pp170 of Explanatory Supplement to the Astronomical Almanac (Seidelmann, 2005). See https://github.com/astropy/astropy/pull/4293#issuecomment-234973086 """ # Check all over sky, but avoiding poles (note that FK4 did not ignore # e terms within 10∘ of the poles... see p170 of explan.supp.). ra, dec = np.meshgrid(np.arange(0, 359, 45), np.arange(-80, 81, 40)) fk4 = FK4(ra.ravel() * u.deg, dec.ravel() * u.deg) Dc = -0.065838 * u.arcsec Dd = +0.335299 * u.arcsec # Dc * tan(obliquity), as given on p.170 Dctano = -0.028553 * u.arcsec fk4noe_dec = ( fk4.dec - (Dd * np.cos(fk4.ra) - Dc * np.sin(fk4.ra)) * np.sin(fk4.dec) - Dctano * np.cos(fk4.dec) ) fk4noe_ra = fk4.ra - (Dc * np.cos(fk4.ra) + Dd * np.sin(fk4.ra)) / np.cos(fk4.dec) fk4noe = fk4.transform_to(FK4NoETerms()) # Tolerance here just set to how well the coordinates match, which is much # better than the claimed accuracy of <1 mas for this first-order in # v_earth/c approximation. # Interestingly, if one divides by np.cos(fk4noe_dec) in the ra correction, # the match becomes good to 2 μas. assert_quantity_allclose(fk4noe.ra, fk4noe_ra, atol=11.0 * u.uas, rtol=0) assert_quantity_allclose(fk4noe.dec, fk4noe_dec, atol=3.0 * u.uas, rtol=0)
check that distances are not lost on SkyCoord init
def test_regression_5209(): "check that distances are not lost on SkyCoord init" time = Time("2015-01-01") moon = get_body("moon", time) new_coord = SkyCoord([moon]) assert_quantity_allclose(new_coord[0].distance, moon.distance)
Test to check if alt-az calculations respect height of observer Because ITRS is geocentric and includes aberration, an object that appears 'straight up' to a geocentric observer (ITRS) won't be straight up to a topocentric observer - see https://github.com/astropy/astropy/issues/10983 This is worse for small height above the Earth, which is why this test uses large distances.
def test_itrs_vals_5133(): """ Test to check if alt-az calculations respect height of observer Because ITRS is geocentric and includes aberration, an object that appears 'straight up' to a geocentric observer (ITRS) won't be straight up to a topocentric observer - see https://github.com/astropy/astropy/issues/10983 This is worse for small height above the Earth, which is why this test uses large distances. """ time = Time("2010-1-1") height = 500000.0 * u.km el = EarthLocation.from_geodetic(lon=20 * u.deg, lat=45 * u.deg, height=height) lons = [20, 30, 20] * u.deg lats = [44, 45, 45] * u.deg alts = u.Quantity([height, height, 10 * height]) coos = [ EarthLocation.from_geodetic(lon, lat, height=alt).get_itrs(time) for lon, lat, alt in zip(lons, lats, alts) ] aaf = AltAz(obstime=time, location=el) aacs = [coo.transform_to(aaf) for coo in coos] assert all(coo.isscalar for coo in aacs) # the ~1 degree tolerance is b/c aberration makes it not exact assert_quantity_allclose(aacs[0].az, 180 * u.deg, atol=1 * u.deg) assert aacs[0].alt < 0 * u.deg assert aacs[0].distance > 5000 * u.km # it should *not* actually be 90 degrees, b/c constant latitude is not # straight east anywhere except the equator... but should be close-ish assert_quantity_allclose(aacs[1].az, 90 * u.deg, atol=5 * u.deg) assert aacs[1].alt < 0 * u.deg assert aacs[1].distance > 5000 * u.km assert_quantity_allclose(aacs[2].alt, 90 * u.deg, atol=1 * u.arcminute) assert_quantity_allclose(aacs[2].distance, 9 * height)
Simple test to check if alt-az calculations respect height of observer Because ITRS is geocentric and includes aberration, an object that appears 'straight up' to a geocentric observer (ITRS) won't be straight up to a topocentric observer - see https://github.com/astropy/astropy/issues/10983 This is why we construct a topocentric GCRS SkyCoord before calculating AltAz
def test_regression_simple_5133(): """ Simple test to check if alt-az calculations respect height of observer Because ITRS is geocentric and includes aberration, an object that appears 'straight up' to a geocentric observer (ITRS) won't be straight up to a topocentric observer - see https://github.com/astropy/astropy/issues/10983 This is why we construct a topocentric GCRS SkyCoord before calculating AltAz """ t = Time("J2010") obj = EarthLocation(-1 * u.deg, 52 * u.deg, height=[10.0, 0.0] * u.km) home = EarthLocation(-1 * u.deg, 52 * u.deg, height=5.0 * u.km) obsloc_gcrs, obsvel_gcrs = home.get_gcrs_posvel(t) gcrs_geo = obj.get_itrs(t).transform_to(GCRS(obstime=t)) obsrepr = home.get_itrs(t).transform_to(GCRS(obstime=t)).cartesian topo_gcrs_repr = gcrs_geo.cartesian - obsrepr topocentric_gcrs_frame = GCRS( obstime=t, obsgeoloc=obsloc_gcrs, obsgeovel=obsvel_gcrs ) gcrs_topo = topocentric_gcrs_frame.realize_frame(topo_gcrs_repr) aa = gcrs_topo.transform_to(AltAz(obstime=t, location=home)) # az is more-or-less undefined for straight up or down assert_quantity_allclose(aa.alt, [90, -90] * u.deg, rtol=1e-7) assert_quantity_allclose(aa.distance, 5 * u.km)
This tests the more subtle flaw that #6597 indirectly uncovered: that even in the case that the frames are ra/dec, they still might be the wrong *kind*
def test_regression_6597_2(): """ This tests the more subtle flaw that #6597 indirectly uncovered: that even in the case that the frames are ra/dec, they still might be the wrong *kind* """ frame = FK4(equinox="J1949") c1 = SkyCoord(1, 3, unit="deg", frame=frame) c2 = SkyCoord(2, 4, unit="deg", frame=frame) sc1 = SkyCoord([c1, c2]) assert sc1.frame.name == frame.name
Test for regression of a bug in get_gcrs_posvel that introduced errors at the 1m/s level. Comparison data is derived from calculation in PINT https://github.com/nanograv/PINT/blob/master/pint/erfautils.py
def test_regression_6697(): """ Test for regression of a bug in get_gcrs_posvel that introduced errors at the 1m/s level. Comparison data is derived from calculation in PINT https://github.com/nanograv/PINT/blob/master/pint/erfautils.py """ pint_vels = CartesianRepresentation( 348.63632871, -212.31704928, -0.60154936, unit=u.m / u.s ) location = EarthLocation( 5327448.9957829, -1718665.73869569, 3051566.90295403, unit=u.m ) t = Time(2458036.161966612, format="jd") obsgeopos, obsgeovel = location.get_gcrs_posvel(t) delta = (obsgeovel - pint_vels).norm() assert delta < 1 * u.cm / u.s
This checks that the ValueError in BaseRepresentation._re_represent_differentials is raised properly
def test_regression_8924(): """This checks that the ValueError in BaseRepresentation._re_represent_differentials is raised properly """ # A case where the representation has a 's' differential, but we try to # re-represent only with an 's2' differential rep = CartesianRepresentation(1, 2, 3, unit=u.kpc) dif = CartesianDifferential(4, 5, 6, u.km / u.s) rep = rep.with_differentials(dif) with pytest.raises(ValueError): rep._re_represent_differentials( CylindricalRepresentation, {"s2": CylindricalDifferential} )
Check that we still get a proper motion even for SkyCoords without distance
def test_regression_10092(): """ Check that we still get a proper motion even for SkyCoords without distance """ c = SkyCoord( l=10 * u.degree, b=45 * u.degree, pm_l_cosb=34 * u.mas / u.yr, pm_b=-117 * u.mas / u.yr, frame="galactic", obstime=Time("1988-12-18 05:11:23.5"), ) with pytest.warns(ErfaWarning, match='ERFA function "pmsafe" yielded .*'): newc = c.apply_space_motion(dt=10 * u.year) assert_quantity_allclose( newc.pm_l_cosb, 33.99980714 * u.mas / u.yr, atol=1.0e-5 * u.mas / u.yr )
Check that we can get a GCRS for a scalar EarthLocation and a size=1 non-scalar Time.
def test_regression_10422(mjd): """ Check that we can get a GCRS for a scalar EarthLocation and a size=1 non-scalar Time. """ # Avoid trying to download new IERS data. with iers.earth_orientation_table.set(iers.IERS_B.open(iers.IERS_B_FILE)): t = Time(mjd, format="mjd", scale="tai") loc = EarthLocation(88258.0 * u.m, -4924882.2 * u.m, 3943729.0 * u.m) p, v = loc.get_gcrs_posvel(obstime=t) assert p.shape == v.shape == t.shape
According to https://eclipse.gsfc.nasa.gov/OH/transit12.html, the minimum separation between Venus and the Sun during the 2012 transit is 554 arcseconds for an observer at the Geocenter. If light deflection from the Sun is incorrectly applied, this increases to 557 arcseconds.
def test_regression_10291(): """ According to https://eclipse.gsfc.nasa.gov/OH/transit12.html, the minimum separation between Venus and the Sun during the 2012 transit is 554 arcseconds for an observer at the Geocenter. If light deflection from the Sun is incorrectly applied, this increases to 557 arcseconds. """ t = Time("2012-06-06 01:29:36") sun = get_body("sun", t) venus = get_body("venus", t) assert_quantity_allclose( venus.separation(sun), 554.427 * u.arcsecond, atol=0.001 * u.arcsecond )
Regression test for #5889.
def test_representation_repr_multi_d(): """Regression test for #5889.""" cr = CartesianRepresentation(np.arange(27).reshape(3, 3, 3), unit="m") assert ( repr(cr) == "<CartesianRepresentation (x, y, z) in m\n" " [[(0., 9., 18.), (1., 10., 19.), (2., 11., 20.)],\n" " [(3., 12., 21.), (4., 13., 22.), (5., 14., 23.)],\n" " [(6., 15., 24.), (7., 16., 25.), (8., 17., 26.)]]>" ) # This was broken before. assert ( repr(cr.T) == "<CartesianRepresentation (x, y, z) in m\n" " [[(0., 9., 18.), (3., 12., 21.), (6., 15., 24.)],\n" " [(1., 10., 19.), (4., 13., 22.), (7., 16., 25.)],\n" " [(2., 11., 20.), (5., 14., 23.), (8., 17., 26.)]]>" )
Regression test for #5889.
def test_representation_str_multi_d(): """Regression test for #5889.""" cr = CartesianRepresentation(np.arange(27).reshape(3, 3, 3), unit="m") assert ( str(cr) == "[[(0., 9., 18.), (1., 10., 19.), (2., 11., 20.)],\n" " [(3., 12., 21.), (4., 13., 22.), (5., 14., 23.)],\n" " [(6., 15., 24.), (7., 16., 25.), (8., 17., 26.)]] m" ) # This was broken before. assert ( str(cr.T) == "[[(0., 9., 18.), (3., 12., 21.), (6., 15., 24.)],\n" " [(1., 10., 19.), (4., 13., 22.), (7., 16., 25.)],\n" " [(2., 11., 20.), (5., 14., 23.), (8., 17., 26.)]] m" )
Test that to_cartesian drops the differential.
def test_to_cartesian(): """ Test that to_cartesian drops the differential. """ sd = SphericalDifferential(d_lat=1 * u.deg, d_lon=2 * u.deg, d_distance=10 * u.m) sr = SphericalRepresentation( lat=1 * u.deg, lon=2 * u.deg, distance=10 * u.m, differentials=sd ) cart = sr.to_cartesian() assert cart.get_name() == "cartesian" assert not cart.differentials
This fixture is used
def unitphysics(): """ This fixture is used """ had_unit = False if hasattr(PhysicsSphericalRepresentation, "_unit_representation"): orig = PhysicsSphericalRepresentation._unit_representation had_unit = True class UnitPhysicsSphericalRepresentation(BaseRepresentation): attr_classes = {"phi": Angle, "theta": Angle} def __init__(self, *args, copy=True, **kwargs): super().__init__(*args, copy=copy, **kwargs) # Wrap/validate phi/theta if copy: self._phi = self._phi.wrap_at(360 * u.deg) else: # necessary because the above version of `wrap_at` has to be a copy self._phi.wrap_at(360 * u.deg, inplace=True) if np.any(self._theta < 0.0 * u.deg) or np.any(self._theta > 180.0 * u.deg): raise ValueError( "Inclination angle(s) must be within 0 deg <= angle <= 180 deg, " f"got {self._theta.to(u.degree)}" ) @property def phi(self): return self._phi @property def theta(self): return self._theta def unit_vectors(self): sinphi, cosphi = np.sin(self.phi), np.cos(self.phi) sintheta, costheta = np.sin(self.theta), np.cos(self.theta) return { "phi": CartesianRepresentation(-sinphi, cosphi, 0.0, copy=False), "theta": CartesianRepresentation( costheta * cosphi, costheta * sinphi, -sintheta, copy=False ), } def scale_factors(self): sintheta = np.sin(self.theta) l = np.broadcast_to(1.0 * u.one, self.shape, subok=True) return {"phi", sintheta, "theta", l} def to_cartesian(self): x = np.sin(self.theta) * np.cos(self.phi) y = np.sin(self.theta) * np.sin(self.phi) z = np.cos(self.theta) return CartesianRepresentation(x=x, y=y, z=z, copy=False) @classmethod def from_cartesian(cls, cart): """ Converts 3D rectangular cartesian coordinates to spherical polar coordinates. """ s = np.hypot(cart.x, cart.y) phi = np.arctan2(cart.y, cart.x) theta = np.arctan2(s, cart.z) return cls(phi=phi, theta=theta, copy=False) def norm(self): return u.Quantity(np.ones(self.shape), u.dimensionless_unscaled, copy=False) PhysicsSphericalRepresentation._unit_representation = ( UnitPhysicsSphericalRepresentation ) yield UnitPhysicsSphericalRepresentation if had_unit: PhysicsSphericalRepresentation._unit_representation = orig else: del PhysicsSphericalRepresentation._unit_representation # remove from the module-level representations, if present REPRESENTATION_CLASSES.pop(UnitPhysicsSphericalRepresentation.get_name(), None)
Regression test for - #868, #891: methods raised errors in case of frames with equinoxes - #3106, #15659: unspecified equinox should be interpreted as frame default, both in `SkyCoord` methods (#3106) and in `BaseCoordinateFrame` methods with `SkyCoord` input (#15659). - #5702: `position_angle()` didn't check if equinoxes differed
def test_equinox_conversion(coord, other_coord, method): """ Regression test for - #868, #891: methods raised errors in case of frames with equinoxes - #3106, #15659: unspecified equinox should be interpreted as frame default, both in `SkyCoord` methods (#3106) and in `BaseCoordinateFrame` methods with `SkyCoord` input (#15659). - #5702: `position_angle()` didn't check if equinoxes differed """ assert_quantity_allclose( getattr(coord, method)(other_coord.coord), getattr(other_coord, method) ) assert_quantity_allclose( getattr(other_coord.coord, method)(coord), getattr(other_coord, f"reversed_{method}"), )
This is especially important for SkyCoord because SkyCoord instances expose the methods of their underlying frame at runtime, so they cannot be checked statically.
def test_return_types(coord_class, method, output_type): """ This is especially important for SkyCoord because SkyCoord instances expose the methods of their underlying frame at runtime, so they cannot be checked statically. """ coord = coord_class(0 * u.deg, 0 * u.deg, 1 * u.pc) assert type(getattr(coord, method)(coord)) is output_type
A regression test for a typo bug pointed out at the bottom of https://github.com/astropy/astropy/pull/4042
def test_non_EarthLocation(): """ A regression test for a typo bug pointed out at the bottom of https://github.com/astropy/astropy/pull/4042 """ class EarthLocation2(EarthLocation): pass # This lets keeps us from needing to do remote_data # note that this does *not* mess up the registry for EarthLocation because # registry is cached on a per-class basis EarthLocation2._get_site_registry(force_builtin=True) el2 = EarthLocation2.of_site("greenwich") assert type(el2) is EarthLocation2 assert el2.info.name == "Royal Observatory Greenwich"
This function checks that the builtin sites registry is consistent with the remote registry (or a registry at some other location). Note that current this is *not* run by the testing suite (because it doesn't start with "test", and is instead meant to be used as a check before merging changes in astropy-data)
def check_builtin_matches_remote(download_url=True): """ This function checks that the builtin sites registry is consistent with the remote registry (or a registry at some other location). Note that current this is *not* run by the testing suite (because it doesn't start with "test", and is instead meant to be used as a check before merging changes in astropy-data) """ builtin_registry = EarthLocation._get_site_registry(force_builtin=True) dl_registry = EarthLocation._get_site_registry(force_download=download_url) in_dl = {} matches = {} for name in builtin_registry.names: in_dl[name] = name in dl_registry if in_dl[name]: matches[name] = quantity_allclose( builtin_registry[name].geocentric, dl_registry[name].geocentric ) else: matches[name] = False if not all(matches.values()): # this makes sure we actually see which don't match print("In builtin registry but not in download:") for name in in_dl: if not in_dl[name]: print(" ", name) print("In both but not the same value:") for name in matches: if not matches[name] and in_dl[name]: print( " ", name, "builtin:", builtin_registry[name], "download:", dl_registry[name], ) raise AssertionError( "Builtin and download registry aren't consistent - failures printed to stdout" )
Test transforms between AltAz frames with different attributes.
def test_altaz_attribute_transforms(): """Test transforms between AltAz frames with different attributes.""" el1 = EarthLocation(0 * u.deg, 0 * u.deg, 0 * u.m) origin1 = AltAz( 0 * u.deg, 0 * u.deg, obstime=Time("2000-01-01T12:00:00"), location=el1 ) coo1 = SkyCoord(1 * u.deg, 1 * u.deg, frame=SkyOffsetFrame(origin=origin1)) origin2 = AltAz( 0 * u.deg, 0 * u.deg, obstime=Time("2000-01-01T11:00:00"), location=el1 ) coo2 = coo1.transform_to(SkyOffsetFrame(origin=origin2)) assert_allclose( [coo2.lon.wrap_at(180 * u.deg), coo2.lat], [1.22522446, 0.70624298] * u.deg, atol=CONVERT_PRECISION, ) el3 = EarthLocation(0 * u.deg, 90 * u.deg, 0 * u.m) origin3 = AltAz( 0 * u.deg, 90 * u.deg, obstime=Time("2000-01-01T12:00:00"), location=el3 ) coo3 = coo2.transform_to(SkyOffsetFrame(origin=origin3)) assert_allclose( [coo3.lon.wrap_at(180 * u.deg), coo3.lat], [1 * u.deg, 1 * u.deg], atol=CONVERT_PRECISION, )
This tests a variety of coordinate conversions for the Chandra point-source catalog location of M31 from NED, via SkyOffsetFrames
def test_m31_coord_transforms(from_origin, to_origin): """ This tests a variety of coordinate conversions for the Chandra point-source catalog location of M31 from NED, via SkyOffsetFrames """ from_pos = SkyOffsetFrame(1 * u.deg, 1 * u.deg, origin=from_origin) to_astroframe = SkyOffsetFrame(origin=to_origin) target_pos = from_pos.transform_to(to_astroframe) assert_allclose( to_origin.separation(target_pos), np.hypot(from_pos.lon, from_pos.lat), atol=CONVERT_PRECISION, ) roundtrip_pos = target_pos.transform_to(from_pos) assert_allclose( [roundtrip_pos.lon.wrap_at(180 * u.deg), roundtrip_pos.lat], [1.0 * u.deg, 1.0 * u.deg], atol=CONVERT_PRECISION, )
Test if passing a rotation argument via SkyCoord works
def test_skycoord_skyoffset_frame_rotation(rotation, expectedlatlon): """Test if passing a rotation argument via SkyCoord works""" target = SkyCoord(45 * u.deg, 46 * u.deg) trans = target.transform_to(ICRS_45_45.skyoffset_frame(rotation=rotation)) assert_allclose( [trans.lon.wrap_at(180 * u.deg), trans.lat], expectedlatlon, atol=1e-10 * u.deg )
Regression test for gh-11277, where it turned out that the origin argument validation from one SkyOffsetFrame could interfere with that of another. Note that this example brought out a different bug than that at the top of gh-11277, viz., that an attempt was made to set origin on a SkyCoord when it should just be stay as part of the SkyOffsetFrame.
def test_skyoffset_two_frames_interfering(): """Regression test for gh-11277, where it turned out that the origin argument validation from one SkyOffsetFrame could interfere with that of another. Note that this example brought out a different bug than that at the top of gh-11277, viz., that an attempt was made to set origin on a SkyCoord when it should just be stay as part of the SkyOffsetFrame. """ # Example adapted from @bmerry's minimal example at # https://github.com/astropy/astropy/issues/11277#issuecomment-825492335 altaz_frame = AltAz( obstime=Time("2020-04-22T13:00:00Z"), location=EarthLocation(18, -30) ) target = SkyCoord(alt=70 * u.deg, az=150 * u.deg, frame=altaz_frame) dirs_altaz_offset = SkyCoord( lon=[-0.02, 0.01, 0.0, 0.0, 0.0] * u.rad, lat=[0.0, 0.2, 0.0, -0.3, 0.1] * u.rad, frame=target.skyoffset_frame(), ) dirs_altaz = dirs_altaz_offset.transform_to(altaz_frame) dirs_icrs = dirs_altaz.transform_to(ICRS()) target_icrs = target.transform_to(ICRS()) # The line below was almost guaranteed to fail. dirs_icrs.transform_to(target_icrs.skyoffset_frame())
Test method ``is_transformable_to`` with string input. The only difference from the frame method of the same name is that strings are allowed. As the frame tests cover ``is_transform_to``, here we only test the added string option.
def test_is_transformable_to_str_input(): """Test method ``is_transformable_to`` with string input. The only difference from the frame method of the same name is that strings are allowed. As the frame tests cover ``is_transform_to``, here we only test the added string option. """ # make example SkyCoord c = SkyCoord(90 * u.deg, -11 * u.deg) # iterate through some frames, checking consistency names = frame_transform_graph.get_names() for name in names: frame = frame_transform_graph.lookup_name(name)() assert c.is_transformable_to(name) == c.is_transformable_to(frame)
Test round tripping out and back using transform_to in every combination.
def test_round_tripping(frame0, frame1, equinox0, equinox1, obstime0, obstime1): """ Test round tripping out and back using transform_to in every combination. """ attrs0 = {"equinox": equinox0, "obstime": obstime0} attrs1 = {"equinox": equinox1, "obstime": obstime1} # Remove None values attrs0 = {k: v for k, v in attrs0.items() if v is not None} attrs1 = {k: v for k, v in attrs1.items() if v is not None} # Go out and back sc = SkyCoord(RA, DEC, frame=frame0, **attrs0) # Keep only frame attributes for frame1 attrs1 = { attr: val for attr, val in attrs1.items() if attr in frame1.frame_attributes } sc2 = sc.transform_to(frame1(**attrs1)) # When coming back only keep frame0 attributes for transform_to attrs0 = { attr: val for attr, val in attrs0.items() if attr in frame0.frame_attributes } # also, if any are None, fill in with defaults for attrnm in frame0.frame_attributes: if attrs0.get(attrnm, None) is None: if attrnm == "obstime" and frame0.get_frame_attr_defaults()[attrnm] is None: if "equinox" in attrs0: attrs0[attrnm] = attrs0["equinox"] else: attrs0[attrnm] = frame0.get_frame_attr_defaults()[attrnm] sc_rt = sc2.transform_to(frame0(**attrs0)) if frame0 is Galactic: assert allclose(sc.l, sc_rt.l) assert allclose(sc.b, sc_rt.b) else: assert allclose(sc.ra, sc_rt.ra) assert allclose(sc.dec, sc_rt.dec) if equinox0: assert type(sc.equinox) is Time and sc.equinox == sc_rt.equinox if obstime0: assert type(sc.obstime) is Time and sc.obstime == sc_rt.obstime
Spherical or Cartesian representation input coordinates.
def test_coord_init_string(): """ Spherical or Cartesian representation input coordinates. """ sc = SkyCoord("1d 2d") assert allclose(sc.ra, 1 * u.deg) assert allclose(sc.dec, 2 * u.deg) sc = SkyCoord("1d", "2d") assert allclose(sc.ra, 1 * u.deg) assert allclose(sc.dec, 2 * u.deg) sc = SkyCoord("1°2′3″", "2°3′4″") assert allclose(sc.ra, Angle("1°2′3″")) assert allclose(sc.dec, Angle("2°3′4″")) sc = SkyCoord("1°2′3″ 2°3′4″") assert allclose(sc.ra, Angle("1°2′3″")) assert allclose(sc.dec, Angle("2°3′4″")) with pytest.raises(ValueError) as err: SkyCoord("1d 2d 3d") assert "Cannot parse first argument data" in str(err.value) sc1 = SkyCoord("8 00 00 +5 00 00.0", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc1, SkyCoord) assert allclose(sc1.ra, Angle(120 * u.deg)) assert allclose(sc1.dec, Angle(5 * u.deg)) sc11 = SkyCoord("8h00m00s+5d00m00.0s", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc11, SkyCoord) assert allclose(sc1.ra, Angle(120 * u.deg)) assert allclose(sc1.dec, Angle(5 * u.deg)) sc2 = SkyCoord("8 00 -5 00 00.0", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc2, SkyCoord) assert allclose(sc2.ra, Angle(120 * u.deg)) assert allclose(sc2.dec, Angle(-5 * u.deg)) sc3 = SkyCoord("8 00 -5 00.6", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc3, SkyCoord) assert allclose(sc3.ra, Angle(120 * u.deg)) assert allclose(sc3.dec, Angle(-5.01 * u.deg)) sc4 = SkyCoord("J080000.00-050036.00", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc4, SkyCoord) assert allclose(sc4.ra, Angle(120 * u.deg)) assert allclose(sc4.dec, Angle(-5.01 * u.deg)) sc41 = SkyCoord("J080000+050036", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc41, SkyCoord) assert allclose(sc41.ra, Angle(120 * u.deg)) assert allclose(sc41.dec, Angle(+5.01 * u.deg)) sc5 = SkyCoord("8h00.6m -5d00.6m", unit=(u.hour, u.deg), frame="icrs") assert isinstance(sc5, SkyCoord) assert allclose(sc5.ra, Angle(120.15 * u.deg)) assert allclose(sc5.dec, Angle(-5.01 * u.deg)) sc6 = SkyCoord("8h00.6m -5d00.6m", unit=(u.hour, u.deg), frame="fk4") assert isinstance(sc6, SkyCoord) assert allclose(sc6.ra, Angle(120.15 * u.deg)) assert allclose(sc6.dec, Angle(-5.01 * u.deg)) sc61 = SkyCoord("8h00.6m-5d00.6m", unit=(u.hour, u.deg), frame="fk4") assert isinstance(sc61, SkyCoord) assert allclose(sc6.ra, Angle(120.15 * u.deg)) assert allclose(sc6.dec, Angle(-5.01 * u.deg)) sc61 = SkyCoord("8h00.6-5d00.6", unit=(u.hour, u.deg), frame="fk4") assert isinstance(sc61, SkyCoord) assert allclose(sc6.ra, Angle(120.15 * u.deg)) assert allclose(sc6.dec, Angle(-5.01 * u.deg)) sc7 = SkyCoord("J1874221.60+122421.6", unit=u.deg) assert isinstance(sc7, SkyCoord) assert allclose(sc7.ra, Angle(187.706 * u.deg)) assert allclose(sc7.dec, Angle(12.406 * u.deg)) with pytest.raises(ValueError): SkyCoord("8 00 -5 00.6", unit=(u.deg, u.deg), frame="galactic")
Test variations of the unit keyword.
def test_coord_init_unit(): """ Test variations of the unit keyword. """ for unit in ( "deg", "deg,deg", " deg , deg ", u.deg, (u.deg, u.deg), np.array(["deg", "deg"]), ): sc = SkyCoord(1, 2, unit=unit) assert allclose(sc.ra, Angle(1 * u.deg)) assert allclose(sc.dec, Angle(2 * u.deg)) for unit in ( "hourangle", "hourangle,hourangle", " hourangle , hourangle ", u.hourangle, [u.hourangle, u.hourangle], ): sc = SkyCoord(1, 2, unit=unit) assert allclose(sc.ra, Angle(15 * u.deg)) assert allclose(sc.dec, Angle(30 * u.deg)) for unit in ("hourangle,deg", (u.hourangle, u.deg)): sc = SkyCoord(1, 2, unit=unit) assert allclose(sc.ra, Angle(15 * u.deg)) assert allclose(sc.dec, Angle(2 * u.deg)) for unit in ("deg,deg,deg,deg", [u.deg, u.deg, u.deg, u.deg], None): with pytest.raises(ValueError) as err: SkyCoord(1, 2, unit=unit) assert "Unit keyword must have one to three unit values" in str(err.value) for unit in ("m", (u.m, u.deg), ""): with pytest.raises(u.UnitsError) as err: SkyCoord(1, 2, unit=unit)
Spherical or Cartesian representation input coordinates.
def test_coord_init_list(): """ Spherical or Cartesian representation input coordinates. """ sc = SkyCoord( [("1d", "2d"), (1 * u.deg, 2 * u.deg), "1d 2d", ("1°", "2°"), "1° 2°"], unit="deg", ) assert allclose(sc.ra, Angle("1d")) assert allclose(sc.dec, Angle("2d")) with pytest.raises(ValueError) as err: SkyCoord(["1d 2d 3d"]) assert "Cannot parse first argument data" in str(err.value) with pytest.raises(ValueError) as err: SkyCoord([("1d", "2d", "3d")]) assert "Cannot parse first argument data" in str(err.value) sc = SkyCoord([1 * u.deg, 1 * u.deg], [2 * u.deg, 2 * u.deg]) assert allclose(sc.ra, Angle("1d")) assert allclose(sc.dec, Angle("2d")) with pytest.raises( ValueError, match="One or more elements of input sequence does not have a length", ): SkyCoord([1 * u.deg, 2 * u.deg])
Input in the form of a list array or numpy array
def test_coord_init_array(): """ Input in the form of a list array or numpy array """ for a in (["1 2", "3 4"], [["1", "2"], ["3", "4"]], [[1, 2], [3, 4]]): sc = SkyCoord(a, unit="deg") assert allclose(sc.ra - [1, 3] * u.deg, 0 * u.deg) assert allclose(sc.dec - [2, 4] * u.deg, 0 * u.deg) sc = SkyCoord(np.array(a), unit="deg") assert allclose(sc.ra - [1, 3] * u.deg, 0 * u.deg) assert allclose(sc.dec - [2, 4] * u.deg, 0 * u.deg)
Spherical or Cartesian representation input coordinates.
def test_coord_init_representation(): """ Spherical or Cartesian representation input coordinates. """ coord = SphericalRepresentation(lon=8 * u.deg, lat=5 * u.deg, distance=1 * u.kpc) sc = SkyCoord(coord, frame="icrs") assert allclose(sc.ra, coord.lon) assert allclose(sc.dec, coord.lat) assert allclose(sc.distance, coord.distance) with pytest.raises(ValueError) as err: SkyCoord(coord, frame="icrs", ra="1d") assert "conflicts with keyword argument 'ra'" in str(err.value) coord = CartesianRepresentation(1 * u.one, 2 * u.one, 3 * u.one) sc = SkyCoord(coord, frame="icrs") sc_cart = sc.represent_as(CartesianRepresentation) assert allclose(sc_cart.x, 1.0) assert allclose(sc_cart.y, 2.0) assert allclose(sc_cart.z, 3.0)
Different ways of providing the frame.
def test_frame_init(): """ Different ways of providing the frame. """ sc = SkyCoord(RA, DEC, frame="icrs") assert sc.frame.name == "icrs" sc = SkyCoord(RA, DEC, frame=ICRS) assert sc.frame.name == "icrs" sc = SkyCoord(sc) assert sc.frame.name == "icrs" sc = SkyCoord(C_ICRS) assert sc.frame.name == "icrs" SkyCoord(C_ICRS, frame="icrs") assert sc.frame.name == "icrs" with pytest.raises(ValueError) as err: SkyCoord(C_ICRS, frame="galactic") assert "Cannot override frame=" in str(err.value)
When initializing from an existing coord the representation attrs like equinox should be inherited to the SkyCoord. If there is a conflict then raise an exception.
def test_attr_inheritance(): """ When initializing from an existing coord the representation attrs like equinox should be inherited to the SkyCoord. If there is a conflict then raise an exception. """ sc = SkyCoord(1, 2, frame="icrs", unit="deg", equinox="J1999", obstime="J2001") sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc2 = SkyCoord(sc.frame) # Doesn't have equinox there so we get FK4 defaults assert sc2.equinox != sc.equinox assert sc2.obstime != sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc = SkyCoord(1, 2, frame="fk4", unit="deg", equinox="J1999", obstime="J2001") sc2 = SkyCoord(sc) assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance) sc2 = SkyCoord(sc.frame) # sc.frame has equinox, obstime assert sc2.equinox == sc.equinox assert sc2.obstime == sc.obstime assert allclose(sc2.ra, sc.ra) assert allclose(sc2.dec, sc.dec) assert allclose(sc2.distance, sc.distance)
Test different flavors of item setting for a SkyCoord without a velocity for different frames. Include a frame attribute that is sometimes an actual frame attribute and sometimes an extra frame attribute.
def test_setitem_no_velocity(frame): """Test different flavors of item setting for a SkyCoord without a velocity for different frames. Include a frame attribute that is sometimes an actual frame attribute and sometimes an extra frame attribute. """ sc0 = SkyCoord([1, 2] * u.deg, [3, 4] * u.deg, obstime="B1955", frame=frame) sc2 = SkyCoord([10, 20] * u.deg, [30, 40] * u.deg, obstime="B1955", frame=frame) 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 sc1.obstime == Time("B1955") assert sc1.frame.name == frame 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])
Test different flavors of item setting for a SkyCoord with a velocity.
def test_setitem_velocities(): """Test different flavors of item setting for a SkyCoord with a velocity.""" sc0 = SkyCoord( [1, 2] * u.deg, [3, 4] * u.deg, radial_velocity=[1, 2] * u.km / u.s, obstime="B1950", frame="fk4", ) sc2 = SkyCoord( [10, 20] * u.deg, [30, 40] * u.deg, radial_velocity=[10, 20] * u.km / u.s, obstime="B1950", frame="fk4", ) 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 == Time("B1950") assert sc1.frame.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])
Check conflicts resolution between coordinate attributes and init kwargs.
def test_attr_conflicts(): """ Check conflicts resolution between coordinate attributes and init kwargs. """ sc = SkyCoord(1, 2, frame="icrs", unit="deg", equinox="J1999", obstime="J2001") # OK if attrs both specified but with identical values SkyCoord(sc, equinox="J1999", obstime="J2001") # OK because sc.frame doesn't have obstime SkyCoord(sc.frame, equinox="J1999", obstime="J2100") # Not OK if attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox="J1999", obstime="J2002") assert "Coordinate attribute 'obstime'=" in str(err.value) # Same game but with fk4 which has equinox and obstime frame attrs sc = SkyCoord(1, 2, frame="fk4", unit="deg", equinox="J1999", obstime="J2001") # OK if attrs both specified but with identical values SkyCoord(sc, equinox="J1999", obstime="J2001") # Not OK if SkyCoord attrs don't match with pytest.raises(ValueError) as err: SkyCoord(sc, equinox="J1999", obstime="J2002") assert "Frame attribute 'obstime' has conflicting" in str(err.value) # Not OK because sc.frame has different attrs with pytest.raises(ValueError) as err: SkyCoord(sc.frame, equinox="J1999", obstime="J2002") assert "Frame attribute 'obstime' has conflicting" in str(err.value)
When accessing frame attributes like equinox, the value should come from self.frame when that object has the relevant attribute, otherwise from self.
def test_frame_attr_getattr(): """ When accessing frame attributes like equinox, the value should come from self.frame when that object has the relevant attribute, otherwise from self. """ sc = SkyCoord(1, 2, frame="icrs", unit="deg", equinox="J1999", obstime="J2001") assert sc.equinox == "J1999" # Just the raw value (not validated) assert sc.obstime == "J2001" sc = SkyCoord(1, 2, frame="fk4", unit="deg", equinox="J1999", obstime="J2001") assert sc.equinox == Time("J1999") # Coming from the self.frame object assert sc.obstime == Time("J2001") sc = SkyCoord(1, 2, frame="fk4", unit="deg", equinox="J1999") assert sc.equinox == Time("J1999") assert sc.obstime == Time("J1999")
Basic testing of converting SkyCoord to strings. This just tests for a single input coordinate and and 1-element list. It does not test the underlying `Angle.to_string` method itself.
def test_to_string(): """ Basic testing of converting SkyCoord to strings. This just tests for a single input coordinate and and 1-element list. It does not test the underlying `Angle.to_string` method itself. """ coord = "1h2m3s 1d2m3s" for wrap in (lambda x: x, lambda x: [x]): sc = SkyCoord(wrap(coord)) assert sc.to_string() == wrap("15.5125 1.03417") assert sc.to_string("dms") == wrap("15d30m45s 1d02m03s") assert sc.to_string("hmsdms") == wrap("01h02m03s +01d02m03s") with_kwargs = sc.to_string("hmsdms", precision=3, pad=True, alwayssign=True) assert with_kwargs == wrap("+01h02m03.000s +01d02m03.000s")
Tests miscellaneous operations like `len`
def test_ops(): """ Tests miscellaneous operations like `len` """ sc = SkyCoord(0 * u.deg, 1 * u.deg, frame="icrs") sc_arr = SkyCoord(0 * u.deg, [1, 2] * u.deg, frame="icrs") sc_empty = SkyCoord([] * u.deg, [] * u.deg, frame="icrs") assert sc.isscalar assert not sc_arr.isscalar assert not sc_empty.isscalar with pytest.raises(TypeError): len(sc) assert len(sc_arr) == 2 assert len(sc_empty) == 0 assert bool(sc) assert bool(sc_arr) assert not bool(sc_empty) assert sc_arr[0].isscalar assert len(sc_arr[:1]) == 1 # A scalar shouldn't be indexable with pytest.raises(TypeError): sc[0:] # but it should be possible to just get an item sc_item = sc[()] assert sc_item.shape == () # and to turn it into an array sc_1d = sc[np.newaxis] assert sc_1d.shape == (1,) with pytest.raises(TypeError): iter(sc) assert not isiterable(sc) assert isiterable(sc_arr) assert isiterable(sc_empty) it = iter(sc_arr) assert next(it).dec == sc_arr[0].dec assert next(it).dec == sc_arr[1].dec with pytest.raises(StopIteration): next(it)
Ensure that transforming from a SkyCoord with no frame provided works like ICRS
def test_none_transform(): """ Ensure that transforming from a SkyCoord with no frame provided works like ICRS """ sc = SkyCoord(0 * u.deg, 1 * u.deg) sc_arr = SkyCoord(0 * u.deg, [1, 2] * u.deg) sc2 = sc.transform_to(ICRS) assert sc.ra == sc2.ra and sc.dec == sc2.dec sc5 = sc.transform_to("fk5") assert sc5.ra == sc2.transform_to("fk5").ra sc_arr2 = sc_arr.transform_to(ICRS) sc_arr5 = sc_arr.transform_to("fk5") npt.assert_array_equal(sc_arr5.ra, sc_arr2.transform_to("fk5").ra)
Regression check for #3800: position_angle should accept floats.
def test_position_angle_directly(): """Regression check for #3800: position_angle should accept floats.""" from astropy.coordinates import position_angle result = position_angle(10.0, 20.0, 10.0, 20.0) assert result.unit is u.radian assert result.value == 0.0
Checks "end-to-end" use of `Table` with `SkyCoord` - the `Quantity` initializer is the intermediary that translate the table columns into something coordinates understands. (Regression test for #1762 )
def test_table_to_coord(): """ Checks "end-to-end" use of `Table` with `SkyCoord` - the `Quantity` initializer is the intermediary that translate the table columns into something coordinates understands. (Regression test for #1762 ) """ from astropy.table import Column, Table t = Table() t.add_column(Column(data=[1, 2, 3], name="ra", unit=u.deg)) t.add_column(Column(data=[4, 5, 6], name="dec", unit=u.deg)) c = SkyCoord(t["ra"], t["dec"]) assert allclose(c.ra.to(u.deg), [1, 2, 3] * u.deg) assert allclose(c.dec.to(u.deg), [4, 5, 6] * u.deg)
Compare two tuples of quantities. This assumes that the values in q1 are of order(1) and uses atol=1e-13, rtol=0. It also asserts that the units of the two quantities are the *same*, in order to check that the representation output has the expected units.
def assert_quantities_allclose(coord, q1s, attrs): """ Compare two tuples of quantities. This assumes that the values in q1 are of order(1) and uses atol=1e-13, rtol=0. It also asserts that the units of the two quantities are the *same*, in order to check that the representation output has the expected units. """ q2s = [getattr(coord, attr) for attr in attrs] assert len(q1s) == len(q2s) for q1, q2 in zip(q1s, q2s): assert q1.shape == q2.shape assert allclose(q1, q2, rtol=0, atol=1e-13 * q1.unit)
Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame.
def test_skycoord_three_components( repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3, ): """ Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame. """ sc = SkyCoord( c1, c2, c3, unit=(unit1, unit2, unit3), representation_type=representation, frame=Galactic, ) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) ) sc = SkyCoord( 1000 * c1 * u.Unit(unit1 / 1000), cls2(c2, unit=unit2), 1000 * c3 * u.Unit(unit3 / 1000), frame=Galactic, unit=(unit1, unit2, unit3), representation_type=representation, ) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) ) kwargs = {attr3: c3} sc = SkyCoord( c1, c2, unit=(unit1, unit2, unit3), frame=Galactic, representation_type=representation, **kwargs, ) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) ) kwargs = {attr1: c1, attr2: c2, attr3: c3} sc = SkyCoord( frame=Galactic, unit=(unit1, unit2, unit3), representation_type=representation, **kwargs, ) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) )
Tests positional inputs using components (COMP1, COMP2) for spherical representations. Use weird units and Galactic frame.
def test_skycoord_spherical_two_components( repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3, ): """ Tests positional inputs using components (COMP1, COMP2) for spherical representations. Use weird units and Galactic frame. """ sc = SkyCoord( c1, c2, unit=(unit1, unit2), frame=Galactic, representation_type=representation ) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2)) sc = SkyCoord( 1000 * c1 * u.Unit(unit1 / 1000), cls2(c2, unit=unit2), frame=Galactic, unit=(unit1, unit2, unit3), representation_type=representation, ) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2)) kwargs = {attr1: c1, attr2: c2} sc = SkyCoord( frame=Galactic, unit=(unit1, unit2), representation_type=representation, **kwargs, ) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2))
Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame.
def test_galactic_three_components( repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3, ): """ Tests positional inputs using components (COMP1, COMP2, COMP3) and various representations. Use weird units and Galactic frame. """ sc = Galactic( 1000 * c1 * u.Unit(unit1 / 1000), cls2(c2, unit=unit2), 1000 * c3 * u.Unit(unit3 / 1000), representation_type=representation, ) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) ) kwargs = {attr3: c3 * unit3} sc = Galactic(c1 * unit1, c2 * unit2, representation_type=representation, **kwargs) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) ) kwargs = {attr1: c1 * unit1, attr2: c2 * unit2, attr3: c3 * unit3} sc = Galactic(representation_type=representation, **kwargs) assert_quantities_allclose( sc, (c1 * unit1, c2 * unit2, c3 * unit3), (attr1, attr2, attr3) )
Tests positional inputs using components (COMP1, COMP2) for spherical representations. Use weird units and Galactic frame.
def test_galactic_spherical_two_components( repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3, representation, c1, c2, c3, ): """ Tests positional inputs using components (COMP1, COMP2) for spherical representations. Use weird units and Galactic frame. """ sc = Galactic( 1000 * c1 * u.Unit(unit1 / 1000), cls2(c2, unit=unit2), representation_type=representation, ) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2)) sc = Galactic(c1 * unit1, c2 * unit2, representation_type=representation) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2)) kwargs = {attr1: c1 * unit1, attr2: c2 * unit2} sc = Galactic(representation_type=representation, **kwargs) assert_quantities_allclose(sc, (c1 * unit1, c2 * unit2), (attr1, attr2))
Test that frame attributes get inherited as expected during transform. Driven by #3106.
def test_frame_attr_transform_inherit(): """ Test that frame attributes get inherited as expected during transform. Driven by #3106. """ c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK5) c2 = c.transform_to(FK4) assert c2.equinox.value == "B1950.000" assert c2.obstime.value == "B1950.000" c2 = c.transform_to(FK4(equinox="J1975", obstime="J1980")) assert c2.equinox.value == "J1975.000" assert c2.obstime.value == "J1980.000" c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4) c2 = c.transform_to(FK5) assert c2.equinox.value == "J2000.000" assert c2.obstime is None c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4, obstime="J1980") c2 = c.transform_to(FK5) assert c2.equinox.value == "J2000.000" assert c2.obstime.value == "J1980.000" c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4, equinox="J1975", obstime="J1980") c2 = c.transform_to(FK5) assert c2.equinox.value == "J1975.000" assert c2.obstime.value == "J1980.000" c2 = c.transform_to(FK5(equinox="J1990")) assert c2.equinox.value == "J1990.000" assert c2.obstime.value == "J1980.000" # The work-around for #5722 c = SkyCoord(1 * u.deg, 2 * u.deg, frame="fk5") c1 = SkyCoord(1 * u.deg, 2 * u.deg, frame="fk5", equinox="B1950.000") c2 = c1.transform_to(c) assert not c2.is_equivalent_frame(c) # counterintuitive, but documented assert c2.equinox.value == "B1950.000" c3 = c1.transform_to(c, merge_attributes=False) assert c3.equinox.value == "J2000.000" assert c3.is_equivalent_frame(c)
Test the search_around_* methods Here we don't actually test the values are right, just that the methods of SkyCoord work. The accuracy tests are in ``test_matching.py``
def test_search_around(): """ Test the search_around_* methods Here we don't actually test the values are right, just that the methods of SkyCoord work. The accuracy tests are in ``test_matching.py`` """ from astropy.utils import NumpyRNGContext with NumpyRNGContext(987654321): sc1 = SkyCoord( np.random.rand(20) * 360.0 * u.degree, (np.random.rand(20) * 180.0 - 90.0) * u.degree, ) sc2 = SkyCoord( np.random.rand(100) * 360.0 * u.degree, (np.random.rand(100) * 180.0 - 90.0) * u.degree, ) sc1ds = SkyCoord(ra=sc1.ra, dec=sc1.dec, distance=np.random.rand(20) * u.kpc) sc2ds = SkyCoord(ra=sc2.ra, dec=sc2.dec, distance=np.random.rand(100) * u.kpc) idx1_sky, idx2_sky, d2d_sky, d3d_sky = sc1.search_around_sky(sc2, 10 * u.deg) idx1_3d, idx2_3d, d2d_3d, d3d_3d = sc1ds.search_around_3d(sc2ds, 250 * u.pc)
Test that SkyCoord can be created in a reasonable way with lists of SkyCoords (regression for #2702)
def test_skycoord_list_creation(): """ Test that SkyCoord can be created in a reasonable way with lists of SkyCoords (regression for #2702) """ sc = SkyCoord(ra=[1, 2, 3] * u.deg, dec=[4, 5, 6] * u.deg) sc0 = sc[0] sc2 = sc[2] scnew = SkyCoord([sc0, sc2]) assert np.all(scnew.ra == [1, 3] * u.deg) assert np.all(scnew.dec == [4, 6] * u.deg) # also check ranges sc01 = sc[:2] scnew2 = SkyCoord([sc01, sc2]) assert np.all(scnew2.ra == sc.ra) assert np.all(scnew2.dec == sc.dec) # now try with a mix of skycoord, frame, and repr objects frobj = ICRS(2 * u.deg, 5 * u.deg) reprobj = UnitSphericalRepresentation(3 * u.deg, 6 * u.deg) scnew3 = SkyCoord([sc0, frobj, reprobj]) assert np.all(scnew3.ra == sc.ra) assert np.all(scnew3.dec == sc.dec) # should *fail* if different frame attributes or types are passed in scfk5_j2000 = SkyCoord(1 * u.deg, 4 * u.deg, frame="fk5") with pytest.raises(ValueError): SkyCoord([sc0, scfk5_j2000]) scfk5_j2010 = SkyCoord(1 * u.deg, 4 * u.deg, frame="fk5", equinox="J2010") with pytest.raises(ValueError): SkyCoord([scfk5_j2000, scfk5_j2010]) # but they should inherit if they're all consistent scfk5_2_j2010 = SkyCoord(2 * u.deg, 5 * u.deg, frame="fk5", equinox="J2010") scfk5_3_j2010 = SkyCoord(3 * u.deg, 6 * u.deg, frame="fk5", equinox="J2010") scnew4 = SkyCoord([scfk5_j2010, scfk5_2_j2010, scfk5_3_j2010]) assert np.all(scnew4.ra == sc.ra) assert np.all(scnew4.dec == sc.dec) assert scnew4.equinox == Time("J2010")
Regression test for #10658.
def test_equiv_skycoord_with_extra_attrs(): """Regression test for #10658.""" # GCRS has a CartesianRepresentationAttribute called obsgeoloc gcrs = GCRS( 1 * u.deg, 2 * u.deg, obsgeoloc=CartesianRepresentation([1, 2, 3], unit=u.m) ) # Create a SkyCoord where obsgeoloc tags along as an extra attribute sc1 = SkyCoord(gcrs).transform_to(ICRS) # Now create a SkyCoord with an equivalent frame but without the extra attribute sc2 = SkyCoord(sc1.frame) # The SkyCoords are therefore not equivalent, but check both directions assert not sc1.is_equivalent_frame(sc2) # This way around raised a TypeError which is fixed by #10658 assert not sc2.is_equivalent_frame(sc1)
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. """ sc = SkyCoord([1, 1] * u.deg, [2, 2] * u.deg) sc.representation_type = "cartesian" assert sc[0].representation_type is CartesianRepresentation
This tests the case where a frame is added with a new frame attribute after a SkyCoord has been created. This is necessary because SkyCoords get the attributes set at creation time, but the set of attributes can change as frames are added or removed from the transform graph. This makes sure that everything continues to work consistently.
def test_frame_attr_changes(): """ This tests the case where a frame is added with a new frame attribute after a SkyCoord has been created. This is necessary because SkyCoords get the attributes set at creation time, but the set of attributes can change as frames are added or removed from the transform graph. This makes sure that everything continues to work consistently. """ sc_before = SkyCoord(1 * u.deg, 2 * u.deg, frame="icrs") assert "fakeattr" not in dir(sc_before) class FakeFrame(BaseCoordinateFrame): fakeattr = Attribute() # doesn't matter what this does as long as it just puts the frame in the # transform graph transset = (ICRS, FakeFrame, lambda c, f: c) frame_transform_graph.add_transform(*transset) try: assert "fakeattr" in dir(sc_before) assert sc_before.fakeattr is None sc_after1 = SkyCoord(1 * u.deg, 2 * u.deg, frame="icrs") assert "fakeattr" in dir(sc_after1) assert sc_after1.fakeattr is None sc_after2 = SkyCoord(1 * u.deg, 2 * u.deg, frame="icrs", fakeattr=1) assert sc_after2.fakeattr == 1 finally: frame_transform_graph.remove_transform(*transset) assert "fakeattr" not in dir(sc_before) assert "fakeattr" not in dir(sc_after1) assert "fakeattr" not in dir(sc_after2)
Ensure no attribute for any frame can be set directly. Though it is fine if the current frame does not have it.
def test_set_attribute_exceptions(): """Ensure no attribute for any frame can be set directly. Though it is fine if the current frame does not have it.""" sc = SkyCoord(1.0 * u.deg, 2.0 * u.deg, frame="fk5") assert hasattr(sc.frame, "equinox") with pytest.raises(AttributeError): sc.equinox = "B1950" assert sc.relative_humidity is None sc.relative_humidity = 0.5 assert sc.relative_humidity == 0.5 assert not hasattr(sc.frame, "relative_humidity")
Ensure any extra attributes are dealt with correctly. Regression test against #5743.
def test_extra_attributes(): """Ensure any extra attributes are dealt with correctly. Regression test against #5743. """ obstime_string = ["2017-01-01T00:00", "2017-01-01T00:10"] obstime = Time(obstime_string) sc = SkyCoord([5, 10], [20, 30], unit=u.deg, obstime=obstime_string) assert not hasattr(sc.frame, "obstime") assert type(sc.obstime) is Time assert sc.obstime.shape == (2,) assert np.all(sc.obstime == obstime) # ensure equivalency still works for more than one obstime. assert sc.is_equivalent_frame(sc) sc_1 = sc[1] assert sc_1.obstime == obstime[1] # Transforming to FK4 should use sc.obstime. sc_fk4 = sc.transform_to("fk4") assert np.all(sc_fk4.frame.obstime == obstime) # And transforming back should not loose it. sc2 = sc_fk4.transform_to("icrs") assert not hasattr(sc2.frame, "obstime") assert np.all(sc2.obstime == obstime) # Ensure obstime get taken from the SkyCoord if passed in directly. # (regression test for #5749). sc3 = SkyCoord([0.0, 1.0], [2.0, 3.0], unit="deg", frame=sc) assert np.all(sc3.obstime == obstime) # Finally, check that we can delete such attributes. del sc3.obstime assert sc3.obstime is None
This checks that a more user-friendly error message is raised for the user if they pass, e.g., pm_ra instead of pm_ra_cosdec
def test_user_friendly_pm_error(): """ This checks that a more user-friendly error message is raised for the user if they pass, e.g., pm_ra instead of pm_ra_cosdec """ with pytest.raises(ValueError) as e: SkyCoord( 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) with pytest.raises(ValueError) as e: SkyCoord( l=150 * u.deg, b=-11 * u.deg, pm_l=100 * u.mas / u.yr, pm_b=10 * u.mas / u.yr, frame="galactic", ) assert "pm_l_cosb" in str(e.value) # The special error should not turn on here: with pytest.raises(ValueError) as e: SkyCoord( x=1 * u.pc, y=2 * u.pc, z=3 * u.pc, pm_ra=100 * u.mas / u.yr, pm_dec=10 * u.mas / u.yr, representation_type="cartesian", ) assert "pm_ra_cosdec" not in str(e.value)
Test Skycoord.contained(wcs,image)
def test_contained_by(): """ Test Skycoord.contained(wcs,image) """ header = """ WCSAXES = 2 / Number of coordinate axes CRPIX1 = 1045.0 / Pixel coordinate of reference point CRPIX2 = 1001.0 / Pixel coordinate of reference point PC1_1 = -0.00556448550786 / Coordinate transformation matrix element PC1_2 = -0.001042120133257 / Coordinate transformation matrix element PC2_1 = 0.001181477028705 / Coordinate transformation matrix element PC2_2 = -0.005590809742987 / Coordinate transformation matrix element CDELT1 = 1.0 / [deg] Coordinate increment at reference point CDELT2 = 1.0 / [deg] Coordinate increment at reference point CUNIT1 = 'deg' / Units of coordinate increment and value CUNIT2 = 'deg' / Units of coordinate increment and value CTYPE1 = 'RA---TAN' / TAN (gnomonic) projection + SIP distortions CTYPE2 = 'DEC--TAN' / TAN (gnomonic) projection + SIP distortions CRVAL1 = 250.34971683647 / [deg] Coordinate value at reference point CRVAL2 = 2.2808772582495 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = 2.2808772582495 / [deg] Native latitude of celestial pole RADESYS = 'ICRS' / Equatorial coordinate system MJD-OBS = 58612.339199259 / [d] MJD of observation matching DATE-OBS DATE-OBS= '2019-05-09T08:08:26.816Z' / ISO-8601 observation date matching MJD-OB NAXIS = 2 / NAXIS NAXIS1 = 2136 / length of first array dimension NAXIS2 = 2078 / length of second array dimension """ test_wcs = WCS(fits.Header.fromstring(header.strip(), "\n")) assert SkyCoord(254, 2, unit="deg").contained_by(test_wcs) assert not SkyCoord(240, 2, unit="deg").contained_by(test_wcs) img = np.zeros((2136, 2078)) assert SkyCoord(250, 2, unit="deg").contained_by(test_wcs, img) assert not SkyCoord(240, 2, unit="deg").contained_by(test_wcs, img) ra = np.array([254.2, 254.1]) dec = np.array([2, 12.1]) coords = SkyCoord(ra, dec, unit="deg") assert np.all(test_wcs.footprint_contains(coords) == np.array([True, False]))
This is a regression test for #8021
def test_none_differential_type(): """ This is a regression test for #8021 """ from astropy.coordinates import BaseCoordinateFrame class MockHeliographicStonyhurst(BaseCoordinateFrame): default_representation = SphericalRepresentation frame_specific_representation_info = { SphericalRepresentation: [ RepresentationMapping( reprname="lon", framename="lon", defaultunit=u.deg ), RepresentationMapping( reprname="lat", framename="lat", defaultunit=u.deg ), RepresentationMapping( reprname="distance", framename="radius", defaultunit=None ), ] } fr = MockHeliographicStonyhurst(lon=1 * u.deg, lat=2 * u.deg, radius=10 * u.au) SkyCoord(0 * u.deg, fr.lat, fr.radius, frame=fr)
Regression test for gh-8340. Non-existing attribute access inside a property should give attribute error for the attribute, not for the property.
def test_subclass_property_exception_error(): """Regression test for gh-8340. Non-existing attribute access inside a property should give attribute error for the attribute, not for the property. """ class custom_coord(SkyCoord): @property def prop(self): return self.random_attr c = custom_coord("00h42m30s", "+41d12m00s", frame="icrs") with pytest.raises(AttributeError, match="random_attr"): # Before this matched "prop" rather than "random_attr" c.prop
Conversion to unitspherical should work, even if we lose distance.
def test_cartesian_to_spherical(sph_type): """Conversion to unitspherical should work, even if we lose distance.""" c = SkyCoord( x=1 * u.kpc, y=0 * u.kpc, z=0 * u.kpc, v_x=10 * u.km / u.s, v_y=0 * u.km / u.s, v_z=4.74 * u.km / u.s, representation_type="cartesian", ) c.representation_type = sph_type assert c.ra == 0 assert c.dec == 0 assert c.pm_ra == 0 assert u.allclose(c.pm_dec, 1 * (u.mas / u.yr), rtol=1e-3) assert u.allclose(c.radial_velocity, 10 * (u.km / u.s)) if sph_type == "spherical": assert u.allclose(c.distance, 1 * u.kpc) else: assert not hasattr(c, "distance")
Test positions generated by JPL Horizons accessed on 2016-03-28, with refraction turned on.
def horizons_ephemeris(): """ Test positions generated by JPL Horizons accessed on 2016-03-28, with refraction turned on. """ geocentric_apparent_frame = TETE(obstime=Time("1980-03-25 00:00")) t = Time("2014-09-25T00:00", location=KITT_PEAK) kitt_peak_apparent_frame = TETE(obstime=t, location=t.location) return { "geocentric": { "mercury": SkyCoord( ra="22h41m47.78s", dec="-08d29m32.0s", distance=c * 6.323037 * u.min, frame=geocentric_apparent_frame, ), "moon": SkyCoord( ra="07h32m02.62s", dec="+18d34m05.0s", distance=c * 0.021921 * u.min, frame=geocentric_apparent_frame, ), "jupiter": SkyCoord( ra="10h17m12.82s", dec="+12d02m57.0s", distance=c * 37.694557 * u.min, frame=geocentric_apparent_frame, ), "sun": SkyCoord( ra="00h16m31.00s", dec="+01d47m16.9s", distance=c * 8.294858 * u.min, frame=geocentric_apparent_frame, ), }, "kitt_peak": { "mercury": SkyCoord( ra="13h38m58.50s", dec="-13d34m42.6s", distance=c * 7.699020 * u.min, frame=kitt_peak_apparent_frame, ), "moon": SkyCoord( ra="12h33m12.85s", dec="-05d17m54.4s", distance=c * 0.022054 * u.min, frame=kitt_peak_apparent_frame, ), "jupiter": SkyCoord( ra="09h09m55.55s", dec="+16d51m57.8s", distance=c * 49.244937 * u.min, frame=kitt_peak_apparent_frame, ), }, }
Test positions against those generated by skyfield.
def test_positions_skyfield(body, skyfield_ephemeris): """ Test positions against those generated by skyfield. """ planets, ts = skyfield_ephemeris t = Time("1980-03-25 00:00") frame = TETE(obstime=t) skyfield_t = ts.from_astropy(t) skyfield_coords = planets["earth"].at(skyfield_t).observe(planets[body]).apparent() ra, dec, dist = skyfield_coords.radec(epoch="date") skyfield_coords = SkyCoord( ra.to(u.deg), dec.to(u.deg), distance=dist.to(u.km), frame=frame ) # planet positions w.r.t true equator and equinox astropy_coords = get_body( "jupiter" if body == "jupiter barycenter" else body, time=t, ephemeris="de430" ).transform_to(frame) assert astropy_coords.separation(skyfield_coords) < 1 * u.arcsec assert astropy_coords.separation_3d(skyfield_coords) < 10 * u.km
Test predictions using erfa/plan94. Accuracies are maximum deviations listed in erfa/plan94.c, for Jupiter and Mercury, and that quoted in Meeus "Astronomical Algorithms" (1998) for the Moon.
def test_erfa_planet(body, sep_tol, dist_tol, location, horizons_ephemeris): """Test predictions using erfa/plan94. Accuracies are maximum deviations listed in erfa/plan94.c, for Jupiter and Mercury, and that quoted in Meeus "Astronomical Algorithms" (1998) for the Moon. """ if location == "kitt_peak": # Add uncertainty in position of Earth dist_tol += 1300 * u.km horizons = horizons_ephemeris[location][body] astropy = get_body(body, horizons.frame.obstime, ephemeris="builtin").transform_to( horizons.frame ) assert astropy.separation(horizons) < sep_tol assert_quantity_allclose(astropy.distance, horizons.distance, atol=dist_tol)
Checks that giving a kernel specifier instead of a body name works
def test_custom_kernel_spec_body(bodyname): """ Checks that giving a kernel specifier instead of a body name works """ t = Time("2014-09-25T00:00", location=KITT_PEAK) coord_by_name = get_body(bodyname, t, ephemeris="de432s") coord_by_kspec = get_body(BODY_NAME_TO_KERNEL_SPEC[bodyname], t, ephemeris="de432s") assert_quantity_allclose(coord_by_name.ra, coord_by_kspec.ra) assert_quantity_allclose(coord_by_name.dec, coord_by_kspec.dec) assert_quantity_allclose(coord_by_name.distance, coord_by_kspec.distance)
A test to compare at high precision against output of JPL horizons. Tests ephemerides, and conversions from ICRS to GCRS to TETE. We are aiming for better than 2 milli-arcsecond precision. We use the Moon since it is nearby, and moves fast in the sky so we are testing for parallax, proper handling of light deflection and aberration.
def test_horizons_consistency_with_precision(): """ A test to compare at high precision against output of JPL horizons. Tests ephemerides, and conversions from ICRS to GCRS to TETE. We are aiming for better than 2 milli-arcsecond precision. We use the Moon since it is nearby, and moves fast in the sky so we are testing for parallax, proper handling of light deflection and aberration. """ moon_data = np.loadtxt(get_pkg_data_filename("data/jpl_moon.dat")) loc = EarthLocation.from_geodetic( -67.787260 * u.deg, -22.959748 * u.deg, 5186 * u.m ) times = Time("2020-04-06 00:00") + np.arange(0, 24, 1) * u.hour apparent_frame = TETE(obstime=times, location=loc) with solar_system_ephemeris.set("de430"): astropy = get_body("moon", times, loc).transform_to(apparent_frame) # JPL Horizons has a known offset (frame bias) of 51.02 mas in RA. usrepr = UnitSphericalRepresentation( moon_data[:, 0] * u.deg + 51.02376467 * u.mas, moon_data[:, 1] * u.deg ) horizons = apparent_frame.realize_frame(usrepr) assert_quantity_allclose(astropy.separation(horizons), 0 * u.mas, atol=1.5 * u.mas)
Test that the sun from JPL and the builtin get_sun match
def test_get_sun_consistency(time): """ Test that the sun from JPL and the builtin get_sun match """ sun_jpl_gcrs = get_body("sun", time, ephemeris="de432s") assert get_sun(time).separation(sun_jpl_gcrs) < 0.1 * u.arcsec
Test that the builtin ephemeris works with non-scalar times. See Issue #5069.
def test_get_body_nonscalar_regression(): """ Test that the builtin ephemeris works with non-scalar times. See Issue #5069. """ times = Time(["2015-08-28 03:30", "2015-09-05 10:30"]) # the following line will raise an Exception if the bug recurs. get_body("moon", times, ephemeris="builtin")
Regression test for #10271
def test_get_body_accounts_for_location_on_Earth(): """Regression test for #10271""" t = Time(58973.534052125986, format="mjd") # GCRS position of ALMA at this time obs_p = CartesianRepresentation( 5724535.74068625, -1311071.58985697, -2492738.93017009, u.m ) icrs_sun_from_alma = _get_apparent_body_position("sun", t, "builtin", obs_p) icrs_sun_from_geocentre = _get_apparent_body_position( "sun", t, "builtin", CartesianRepresentation(0, 0, 0, u.m) ) difference = (icrs_sun_from_alma - icrs_sun_from_geocentre).norm() assert_quantity_allclose(difference, 0.13046941 * u.m, atol=1 * u.mm)
Regression test for #15611
def test_regression_15611(): """Regression test for #15611""" # type 3 SPICE kernel ephemeris_file = get_pkg_data_filename("coordinates/230965_2004XA192_nima_v6.bsp") # KBO 2004 XA192 pair = (10, 20230965) t = Time("2023-11-11T03:59:24") # get_body_barycentric should not raise an error get_body_barycentric([pair], t, ephemeris=ephemeris_file)
Checks that parameters are correctly copied to the new SpectralCoord object
def test_create_from_spectral_coord(observer, target): """ Checks that parameters are correctly copied to the new SpectralCoord object """ with ( nullcontext() if target is None else pytest.warns(AstropyUserWarning, match="No velocity defined on frame") ): spec_coord1 = SpectralCoord( [100, 200, 300] * u.nm, observer=observer, target=target, doppler_convention="optical", doppler_rest=6000 * u.AA, ) spec_coord2 = SpectralCoord(spec_coord1) assert spec_coord1.observer == spec_coord2.observer assert spec_coord1.target == spec_coord2.target assert spec_coord1.radial_velocity == spec_coord2.radial_velocity assert spec_coord1.doppler_convention == spec_coord2.doppler_convention assert spec_coord1.doppler_rest == spec_coord2.doppler_rest
Test basic initialization behavior or observer/target and redshift/rv
def test_observer_init_rv_behavior(): """ Test basic initialization behavior or observer/target and redshift/rv """ # Start off by specifying the radial velocity only sc_init = SpectralCoord([4000, 5000] * u.AA, radial_velocity=100 * u.km / u.s) assert sc_init.observer is None assert sc_init.target is None assert_quantity_allclose(sc_init.radial_velocity, 100 * u.km / u.s) # Next, set the observer, and check that the radial velocity hasn't changed with pytest.warns(AstropyUserWarning, match="No velocity defined on frame"): sc_init.observer = ICRS(CartesianRepresentation([0 * u.km, 0 * u.km, 0 * u.km])) assert sc_init.observer is not None assert_quantity_allclose(sc_init.radial_velocity, 100 * u.km / u.s) # Setting the target should now cause the original radial velocity to be # dropped in favor of the automatically computed one sc_init.target = SkyCoord( CartesianRepresentation([1 * u.km, 0 * u.km, 0 * u.km]), frame="icrs", radial_velocity=30 * u.km / u.s, ) assert sc_init.target is not None assert_quantity_allclose(sc_init.radial_velocity, 30 * u.km / u.s) # The observer can only be set if originally None - now that it isn't # setting it again should fail with pytest.raises(ValueError, match="observer has already been set"): sc_init.observer = GCRS(CartesianRepresentation([0 * u.km, 1 * u.km, 0 * u.km])) # And similarly, changing the target should not be possible with pytest.raises(ValueError, match="target has already been set"): sc_init.target = GCRS(CartesianRepresentation([0 * u.km, 1 * u.km, 0 * u.km]))
Checks radial velocity between Earth and Jupiter
def test_spectral_coord_jupiter(): """ Checks radial velocity between Earth and Jupiter """ obstime = time.Time("2018-12-13 9:00") obs = GREENWICH.get_gcrs(obstime) pos, vel = get_body_barycentric_posvel("jupiter", obstime) jupiter = SkyCoord( pos.with_differentials(CartesianDifferential(vel.xyz)), obstime=obstime ) spc = SpectralCoord([100, 200, 300] * u.nm, observer=obs, target=jupiter) # The velocity should be less than ~43 + a bit extra, which is the # maximum possible earth-jupiter relative velocity. We check the exact # value here (determined from SpectralCoord, so this serves as a test to # check that this value doesn't change - the value is not a ground truth) assert_quantity_allclose(spc.radial_velocity, -7.35219854 * u.km / u.s)
Checks radial velocity between Earth and Alpha Centauri
def test_spectral_coord_alphacen(): """ Checks radial velocity between Earth and Alpha Centauri """ obstime = time.Time("2018-12-13 9:00") obs = GREENWICH.get_gcrs(obstime) # Coordinates were obtained from the following then hard-coded to avoid download # acen = SkyCoord.from_name('alpha cen') acen = SkyCoord( ra=219.90085 * u.deg, dec=-60.83562 * u.deg, frame="icrs", distance=4.37 * u.lightyear, radial_velocity=-18.0 * u.km / u.s, ) spc = SpectralCoord([100, 200, 300] * u.nm, observer=obs, target=acen) # The velocity should be less than ~18 + 30 + a bit extra, which is the # maximum possible relative velocity. We check the exact value here # (determined from SpectralCoord, so this serves as a test to check that # this value doesn't change - the value is not a ground truth) assert_quantity_allclose(spc.radial_velocity, -26.328301 * u.km / u.s)