def test_gcrs_cirs(): """ Check GCRS<->CIRS transforms for round-tripping. More complicated than the above two because it's multi-hop """ ra, dec, _ = randomly_sample_sphere(200) gcrs = GCRS(ra=ra, dec=dec, obstime='J2000') gcrs6 = GCRS(ra=ra, dec=dec, obstime='J2006') gcrs2 = gcrs.transform_to(CIRS).transform_to(gcrs) gcrs6_2 = gcrs6.transform_to(CIRS).transform_to(gcrs) assert_allclose(gcrs.ra, gcrs2.ra) assert_allclose(gcrs.dec, gcrs2.dec) assert not allclose(gcrs.ra, gcrs6_2.ra) assert not allclose(gcrs.dec, gcrs6_2.dec) # now try explicit intermediate pathways and ensure they're all consistent gcrs3 = gcrs.transform_to(ITRS).transform_to(CIRS).transform_to(ITRS).transform_to(gcrs) assert_allclose(gcrs.ra, gcrs3.ra) assert_allclose(gcrs.dec, gcrs3.dec) gcrs4 = gcrs.transform_to(ICRS).transform_to(CIRS).transform_to(ICRS).transform_to(gcrs) assert_allclose(gcrs.ra, gcrs4.ra) assert_allclose(gcrs.dec, gcrs4.dec)
def test_supergalactic(): """ Check Galactic<->Supergalactic and Galactic<->ICRS conversion. """ # Check supergalactic North pole. npole = Galactic(l=47.37*u.degree, b=+6.32*u.degree) assert allclose(npole.transform_to(Supergalactic).sgb.deg, +90, atol=1e-9) # Check the origin of supergalactic longitude. lon0 = Supergalactic(sgl=0*u.degree, sgb=0*u.degree) lon0_gal = lon0.transform_to(Galactic) assert allclose(lon0_gal.l.deg, 137.37, atol=1e-9) assert allclose(lon0_gal.b.deg, 0, atol=1e-9) # Test Galactic<->ICRS with some positions that appear in Foley et al. 2008 # (http://adsabs.harvard.edu/abs/2008A%26A...484..143F) # GRB 021219 supergalactic = Supergalactic(sgl=29.91*u.degree, sgb=+73.72*u.degree) icrs = SkyCoord('18h50m27s +31d57m17s') assert supergalactic.separation(icrs) < 0.005 * u.degree # GRB 030320 supergalactic = Supergalactic(sgl=-174.44*u.degree, sgb=+46.17*u.degree) icrs = SkyCoord('17h51m36s -25d18m52s') assert supergalactic.separation(icrs) < 0.005 * u.degree
def test_eloc_attributes(): from astropy.coordinates import AltAz, ITRS, GCRS, EarthLocation el = EarthLocation(lon=12.3*u.deg, lat=45.6*u.deg, height=1*u.km) it = ITRS(r.SphericalRepresentation(lon=12.3*u.deg, lat=45.6*u.deg, distance=1*u.km)) gc = GCRS(ra=12.3*u.deg, dec=45.6*u.deg, distance=6375*u.km) el1 = AltAz(location=el).location assert isinstance(el1, EarthLocation) # these should match *exactly* because the EarthLocation assert el1.lat == el.lat assert el1.lon == el.lon assert el1.height == el.height el2 = AltAz(location=it).location assert isinstance(el2, EarthLocation) # these should *not* match because giving something in Spherical ITRS is # *not* the same as giving it as an EarthLocation: EarthLocation is on an # elliptical geoid. So the longitude should match (because flattening is # only along the z-axis), but latitude should not. Also, height is relative # to the *surface* in EarthLocation, but the ITRS distance is relative to # the center of the Earth assert not allclose(el2.lat, it.spherical.lat) assert allclose(el2.lon, it.spherical.lon) assert el2.height < -6000*u.km el3 = AltAz(location=gc).location # GCRS inputs implicitly get transformed to ITRS and then onto # EarthLocation's elliptical geoid. So both lat and lon shouldn't match assert isinstance(el3, EarthLocation) assert not allclose(el3.lat, gc.dec) assert not allclose(el3.lon, gc.ra) assert np.abs(el3.height) < 500*u.km
def test_lsr_sanity(): # random numbers, but zero velocity in ICRS frame icrs = ICRS(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc, pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr, radial_velocity=0*u.km/u.s) lsr = icrs.transform_to(LSR) lsr_diff = lsr.data.differentials['s'] cart_lsr_vel = lsr_diff.represent_as(CartesianRepresentation, base=lsr.data) lsr_vel = ICRS(cart_lsr_vel) gal_lsr = lsr_vel.transform_to(Galactic).cartesian.xyz assert allclose(gal_lsr.to(u.km/u.s, u.dimensionless_angles()), lsr.v_bary.d_xyz) # moving with LSR velocity lsr = LSR(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc, pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr, radial_velocity=0*u.km/u.s) icrs = lsr.transform_to(ICRS) icrs_diff = icrs.data.differentials['s'] cart_vel = icrs_diff.represent_as(CartesianRepresentation, base=icrs.data) vel = ICRS(cart_vel) gal_icrs = vel.transform_to(Galactic).cartesian.xyz assert allclose(gal_icrs.to(u.km/u.s, u.dimensionless_angles()), -lsr.v_bary.d_xyz)
def _observers_are_equal(obs_1, obs_2, string_ok=False): if string_ok: if obs_1 == obs_2: return True if not (isinstance(obs_1, BaseCoordinateFrame) and isinstance(obs_2, BaseCoordinateFrame)): raise ValueError("To compare two observers, both must be instances of BaseCoordinateFrame. " "Cannot compare two observers {} and {}.".format(obs_1, obs_2)) return (u.allclose(obs_1.lat, obs_2.lat) and u.allclose(obs_1.lon, obs_2.lon) and u.allclose(obs_1.radius, obs_2.radius))
def test_allclose_isclose(): a = [1, 2] * u.m b = [101, 201] * u.cm delta = 2 * u.cm assert u.allclose(a, b, atol=delta) assert np.all(u.isclose(a, b, atol=delta)) c = [90, 200] * u.cm assert not u.allclose(a, c) assert not np.all(u.isclose(a, c))
def test_icrs_gcrs_dist_diff(gframe): """ Check that with and without distance give different ICRS<->GCRS answers """ gcrsnod = icrs_coords[0].transform_to(gframe) gcrswd = icrs_coords[1].transform_to(gframe) # parallax effects should be included, so with and w/o distance should be different assert not allclose(gcrswd.ra, gcrsnod.ra, rtol=1e-8, atol=1e-10*u.deg) assert not allclose(gcrswd.dec, gcrsnod.dec, rtol=1e-8, atol=1e-10*u.deg) # and the distance should transform at least somehow assert not allclose(gcrswd.distance, icrs_coords[1].distance, rtol=1e-8, atol=1e-10*u.pc)
def test_galactocentric(): # when z_sun=0, transformation should be very similar to Galactic icrs_coord = ICRS(ra=np.linspace(0, 360, 10)*u.deg, dec=np.linspace(-90, 90, 10)*u.deg, distance=1.*u.kpc) g_xyz = icrs_coord.transform_to(Galactic).cartesian.xyz gc_xyz = icrs_coord.transform_to(Galactocentric(z_sun=0*u.kpc)).cartesian.xyz diff = np.abs(g_xyz - gc_xyz) assert allclose(diff[0], 8.3*u.kpc, atol=1E-5*u.kpc) assert allclose(diff[1:], 0*u.kpc, atol=1E-5*u.kpc) # generate some test coordinates g = Galactic(l=[0, 0, 45, 315]*u.deg, b=[-45, 45, 0, 0]*u.deg, distance=[np.sqrt(2)]*4*u.kpc) xyz = g.transform_to(Galactocentric(galcen_distance=1.*u.kpc, z_sun=0.*u.pc)).cartesian.xyz true_xyz = np.array([[0, 0, -1.], [0, 0, 1], [0, 1, 0], [0, -1, 0]]).T*u.kpc assert allclose(xyz.to(u.kpc), true_xyz.to(u.kpc), atol=1E-5*u.kpc) # check that ND arrays work # from Galactocentric to Galactic x = np.linspace(-10., 10., 100) * u.kpc y = np.linspace(-10., 10., 100) * u.kpc z = np.zeros_like(x) g1 = Galactocentric(x=x, y=y, z=z) g2 = Galactocentric(x=x.reshape(100, 1, 1), y=y.reshape(100, 1, 1), z=z.reshape(100, 1, 1)) g1t = g1.transform_to(Galactic) g2t = g2.transform_to(Galactic) assert_allclose(g1t.cartesian.xyz, g2t.cartesian.xyz[:, :, 0, 0]) # from Galactic to Galactocentric l = np.linspace(15, 30., 100) * u.deg b = np.linspace(-10., 10., 100) * u.deg d = np.ones_like(l.value) * u.kpc g1 = Galactic(l=l, b=b, distance=d) g2 = Galactic(l=l.reshape(100, 1, 1), b=b.reshape(100, 1, 1), distance=d.reshape(100, 1, 1)) g1t = g1.transform_to(Galactocentric) g2t = g2.transform_to(Galactocentric) np.testing.assert_almost_equal(g1t.cartesian.xyz.value, g2t.cartesian.xyz.value[:, :, 0, 0])
def test_cirs_itrs(): """ Check basic CIRS<->ITRS transforms for round-tripping. """ ra, dec, _ = randomly_sample_sphere(200) cirs = CIRS(ra=ra, dec=dec, obstime='J2000') cirs6 = CIRS(ra=ra, dec=dec, obstime='J2006') cirs2 = cirs.transform_to(ITRS).transform_to(cirs) cirs6_2 = cirs6.transform_to(ITRS).transform_to(cirs) # different obstime # just check round-tripping assert_allclose(cirs.ra, cirs2.ra) assert_allclose(cirs.dec, cirs2.dec) assert not allclose(cirs.ra, cirs6_2.ra) assert not allclose(cirs.dec, cirs6_2.dec)
def calculate_distance(self): """ This method calculates the third coordinate of the Helioprojective frame. It assumes that the coordinate point is on the disk of the Sun at the rsun radius. If a point in the frame is off limb then NaN will be returned. Returns ------- new_frame : `~sunpy.coordinates.frames.HelioProjective` A new frame instance with all the attributes of the original but now with a third coordinate. """ # Skip if we already are 3D if (isinstance(self._data, SphericalRepresentation) and not (self.distance.unit is u.one and u.allclose(self.distance, 1*u.one))): return self if not isinstance(self.observer, BaseCoordinateFrame): raise ConvertError("Cannot calculate distance to the solar disk " "for observer '{}' " "without `obstime` being specified.".format(self.observer)) rep = self.represent_as(UnitSphericalRepresentation) lat, lon = rep.lat, rep.lon alpha = np.arccos(np.cos(lat) * np.cos(lon)).to(lat.unit) c = self.observer.radius**2 - self.rsun**2 b = -2 * self.observer.radius * np.cos(alpha) d = ((-1*b) - np.sqrt(b**2 - 4*c)) / 2 return self.realize_frame(SphericalRepresentation(lon=lon, lat=lat, distance=d))
def assert_equal(cls, old, new): assert isinstance(new, type(old)) assert new.components == old.components for comp in new.components: nc = getattr(new, comp) oc = getattr(old, comp) assert u.allclose(nc, oc)
def test_gcrs_itrs(): """ Check basic GCRS<->ITRS transforms for round-tripping. """ ra, dec, _ = randomly_sample_sphere(200) gcrs = GCRS(ra=ra, dec=dec, obstime='J2000') gcrs6 = GCRS(ra=ra, dec=dec, obstime='J2006') gcrs2 = gcrs.transform_to(ITRS).transform_to(gcrs) gcrs6_2 = gcrs6.transform_to(ITRS).transform_to(gcrs) assert_allclose(gcrs.ra, gcrs2.ra) assert_allclose(gcrs.dec, gcrs2.dec) assert not allclose(gcrs.ra, gcrs6_2.ra) assert not allclose(gcrs.dec, gcrs6_2.dec) # also try with the cartesian representation gcrsc = gcrs.realize_frame(gcrs.data) gcrsc.representation_type = CartesianRepresentation gcrsc2 = gcrsc.transform_to(ITRS).transform_to(gcrsc) assert_allclose(gcrsc.spherical.lon.deg, gcrsc2.ra.deg) assert_allclose(gcrsc.spherical.lat, gcrsc2.dec)
def hpc_to_hpc(heliopcoord, heliopframe): """ This converts from HPC to HPC, with different observer location parameters. It does this by transforming through HGS. """ if (heliopcoord.observer == heliopframe.observer or (u.allclose(heliopcoord.observer.lat, heliopframe.observer.lat) and u.allclose(heliopcoord.observer.lon, heliopframe.observer.lon) and u.allclose(heliopcoord.observer.radius, heliopframe.observer.radius))): return heliopframe.realize_frame(heliopcoord._data) if not isinstance(heliopframe.observer, BaseCoordinateFrame): raise ConvertError("Cannot transform between helioprojective frames " "without `obstime` being specified for observer {}.".format(heliopframe.observer)) if not isinstance(heliopcoord.observer, BaseCoordinateFrame): raise ConvertError("Cannot transform between helioprojective frames " "without `obstime` being specified for observer {}.".format(heliopcoord.observer)) hgs = heliopcoord.transform_to(HeliographicStonyhurst) hgs.observer = heliopframe.observer hpc = hgs.transform_to(heliopframe) return hpc
def test_valid_quantity_operations2(self): """Check that TimeDelta is treated as a quantity where possible.""" t0 = TimeDelta(100000., format='sec') f = 1./t0 assert isinstance(f, u.Quantity) assert f.unit == 1./u.day g = 10.*u.m/u.second**2 v = t0 * g assert isinstance(v, u.Quantity) assert u.allclose(v, t0.sec * g.value * u.m / u.second) q = np.log10(t0/u.second) assert isinstance(q, u.Quantity) assert q.value == np.log10(t0.sec) s = 1.*u.m v = s/t0 assert isinstance(v, u.Quantity) assert u.allclose(v, 1. / t0.sec * u.m / u.s) t = 1.*u.s t2 = t0 * t assert isinstance(t2, u.Quantity) assert u.allclose(t2, t0.sec * u.s ** 2) t3 = [1] / t0 assert isinstance(t3, u.Quantity) assert u.allclose(t3, 1 / (t0.sec * u.s)) # broadcasting t1 = TimeDelta(np.arange(100000., 100012.).reshape(6, 2), format='sec') f = np.array([1., 2.]) * u.cycle * u.Hz phase = f * t1 assert isinstance(phase, u.Quantity) assert phase.shape == t1.shape assert u.allclose(phase, t1.sec * f.value * u.cycle) q = t0 * t1 assert isinstance(q, u.Quantity) assert np.all(q == t0.to(u.day) * t1.to(u.day)) q = t1 / t0 assert isinstance(q, u.Quantity) assert np.all(q == t1.to(u.day) / t0.to(u.day))
def assert_equal(cls, old, new): """ This method is used by asdf to test that to_tree > from_tree gives an equivalent object. """ np.testing.assert_allclose(old.data, new.data) # Test the meta by force! for ok, ov in old.meta.items(): assert ok in new.meta assert new.meta[ok] == ov assert u.allclose(old.shifted_value, new.shifted_value) if old.mask is not None and new.mask is not None: np.testing.assert_allclose(old.mask, new.mask) assert old.unit == new.unit
def test_icrs_cirs(): """ Check a few cases of ICRS<->CIRS for consistency. Also includes the CIRS<->CIRS transforms at different times, as those go through ICRS """ ra, dec, dist = randomly_sample_sphere(200) inod = ICRS(ra=ra, dec=dec) iwd = ICRS(ra=ra, dec=dec, distance=dist*u.pc) cframe1 = CIRS() cirsnod = inod.transform_to(cframe1) # uses the default time # first do a round-tripping test inod2 = cirsnod.transform_to(ICRS) assert_allclose(inod.ra, inod2.ra) assert_allclose(inod.dec, inod2.dec) # now check that a different time yields different answers cframe2 = CIRS(obstime=Time('J2005', scale='utc')) cirsnod2 = inod.transform_to(cframe2) assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8) assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8) # parallax effects should be included, so with and w/o distance should be different cirswd = iwd.transform_to(cframe1) assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8) # and the distance should transform at least somehow assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8) # now check that the cirs self-transform works as expected cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op assert_allclose(cirsnod.ra, cirsnod3.ra) assert_allclose(cirsnod.dec, cirsnod3.dec) cirsnod4 = cirsnod.transform_to(cframe2) # should be different assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8) assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8) cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same assert_allclose(cirsnod.ra, cirsnod5.ra) assert_allclose(cirsnod.dec, cirsnod5.dec)
def hgs_to_hcc(heliogcoord, heliocframe): """ Convert from Heliographic Stonyhurst to Heliocentric Cartesian. """ hglon = heliogcoord.spherical.lon hglat = heliogcoord.spherical.lat r = heliogcoord.spherical.distance if r.unit is u.one and u.allclose(r, 1*u.one): r = np.ones_like(r) r *= RSUN_METERS if not isinstance(heliocframe.observer, BaseCoordinateFrame): raise ConvertError("Cannot transform heliographic coordinates to " "heliocentric coordinates for observer '{}' " "without `obstime` being specified.".format(heliocframe.observer)) l0_rad = heliocframe.observer.lon.to(u.rad) b0_deg = heliocframe.observer.lat lon = np.deg2rad(hglon) lat = np.deg2rad(hglat) cosb = np.cos(b0_deg.to(u.rad)) sinb = np.sin(b0_deg.to(u.rad)) lon = lon - l0_rad cosx = np.cos(lon) sinx = np.sin(lon) cosy = np.cos(lat) siny = np.sin(lat) x = r * cosy * sinx y = r * (siny * cosb - cosy * cosx * sinb) zz = r * (siny * sinb + cosy * cosx * cosb) representation = CartesianRepresentation( x.to(u.km), y.to(u.km), zz.to(u.km)) return heliocframe.realize_frame(representation)
def __init__(self, *args, **kwargs): _rep_kwarg = kwargs.get('representation', None) wrap = kwargs.pop('wrap_longitude', True) if ('radius' in kwargs and kwargs['radius'].unit is u.one and u.allclose(kwargs['radius'], 1*u.one)): kwargs['radius'] = RSUN_METERS.to(u.km) super(HeliographicStonyhurst, self).__init__(*args, **kwargs) # Make 3D if specified as 2D # If representation was explicitly passed, do not change the rep. if not _rep_kwarg: # If we were passed a 3D rep extract the distance, otherwise # calculate it from RSUN. if isinstance(self._data, UnitSphericalRepresentation): distance = RSUN_METERS.to(u.km) self._data = SphericalRepresentation(lat=self._data.lat, lon=self._data.lon, distance=distance) if wrap and isinstance(self._data, (UnitSphericalRepresentation, SphericalRepresentation)): self._data.lon.wrap_angle = self._default_wrap_angle
def test_icrs_gcrs(icoo): """ Check ICRS<->GCRS for consistency """ gcrscoo = icoo.transform_to(gcrs_frames[0]) # uses the default time # first do a round-tripping test icoo2 = gcrscoo.transform_to(ICRS) assert_allclose(icoo.distance, icoo2.distance) assert_allclose(icoo.ra, icoo2.ra) assert_allclose(icoo.dec, icoo2.dec) assert isinstance(icoo2.data, icoo.data.__class__) # now check that a different time yields different answers gcrscoo2 = icoo.transform_to(gcrs_frames[1]) assert not allclose(gcrscoo.ra, gcrscoo2.ra, rtol=1e-8, atol=1e-10*u.deg) assert not allclose(gcrscoo.dec, gcrscoo2.dec, rtol=1e-8, atol=1e-10*u.deg) # now check that the cirs self-transform works as expected gcrscoo3 = gcrscoo.transform_to(gcrs_frames[0]) # should be a no-op assert_allclose(gcrscoo.ra, gcrscoo3.ra) assert_allclose(gcrscoo.dec, gcrscoo3.dec) gcrscoo4 = gcrscoo.transform_to(gcrs_frames[1]) # should be different assert not allclose(gcrscoo4.ra, gcrscoo.ra, rtol=1e-8, atol=1e-10*u.deg) assert not allclose(gcrscoo4.dec, gcrscoo.dec, rtol=1e-8, atol=1e-10*u.deg) gcrscoo5 = gcrscoo4.transform_to(gcrs_frames[0]) # should be back to the same assert_allclose(gcrscoo.ra, gcrscoo5.ra, rtol=1e-8, atol=1e-10*u.deg) assert_allclose(gcrscoo.dec, gcrscoo5.dec, rtol=1e-8, atol=1e-10*u.deg) # also make sure that a GCRS with a different geoloc/geovel gets a different answer # roughly a moon-like frame gframe3 = GCRS(obsgeoloc=[385000., 0, 0]*u.km, obsgeovel=[1, 0, 0]*u.km/u.s) gcrscoo6 = icoo.transform_to(gframe3) # should be different assert not allclose(gcrscoo.ra, gcrscoo6.ra, rtol=1e-8, atol=1e-10*u.deg) assert not allclose(gcrscoo.dec, gcrscoo6.dec, rtol=1e-8, atol=1e-10*u.deg) icooviag3 = gcrscoo6.transform_to(ICRS) # and now back to the original assert_allclose(icoo.ra, icooviag3.ra) assert_allclose(icoo.dec, icooviag3.dec)
def test_2d_quantity(): shape = (3, 3) data = np.arange(np.product(shape)).reshape(shape) * u.m / u.s ltc = QuantityTableCoordinate(data) assert u.allclose(ltc.wcs.pixel_to_world(0, 0), 0 * u.m / u.s)
def test_representation_info(): from astropy.coordinates.baseframe import RepresentationMapping from astropy.coordinates.builtin_frames import ICRS class NewICRS1(ICRS): frame_specific_representation_info = { r.SphericalRepresentation: [ RepresentationMapping('lon', 'rara', u.hourangle), RepresentationMapping('lat', 'decdec', u.degree), RepresentationMapping('distance', 'distance', u.kpc)] } i1 = NewICRS1(rara=10*u.degree, decdec=-12*u.deg, distance=1000*u.pc, pm_rara_cosdecdec=100*u.mas/u.yr, pm_decdec=17*u.mas/u.yr, radial_velocity=10*u.km/u.s) assert allclose(i1.rara, 10*u.deg) assert i1.rara.unit == u.hourangle assert allclose(i1.decdec, -12*u.deg) assert allclose(i1.distance, 1000*u.pc) assert i1.distance.unit == u.kpc assert allclose(i1.pm_rara_cosdecdec, 100*u.mas/u.yr) assert allclose(i1.pm_decdec, 17*u.mas/u.yr) # this should auto-set the names of UnitSpherical: i1.set_representation_cls(r.UnitSphericalRepresentation, s=r.UnitSphericalCosLatDifferential) assert allclose(i1.rara, 10*u.deg) assert allclose(i1.decdec, -12*u.deg) assert allclose(i1.pm_rara_cosdecdec, 100*u.mas/u.yr) assert allclose(i1.pm_decdec, 17*u.mas/u.yr) # For backwards compatibility, we also support the string name in the # representation info dictionary: class NewICRS2(ICRS): frame_specific_representation_info = { 'spherical': [ RepresentationMapping('lon', 'ang1', u.hourangle), RepresentationMapping('lat', 'ang2', u.degree), RepresentationMapping('distance', 'howfar', u.kpc)] } i2 = NewICRS2(ang1=10*u.degree, ang2=-12*u.deg, howfar=1000*u.pc) assert allclose(i2.ang1, 10*u.deg) assert i2.ang1.unit == u.hourangle assert allclose(i2.ang2, -12*u.deg) assert allclose(i2.howfar, 1000*u.pc) assert i2.howfar.unit == u.kpc # Test that the differential kwargs get overridden class NewICRS3(ICRS): frame_specific_representation_info = { r.SphericalCosLatDifferential: [ RepresentationMapping('d_lon_coslat', 'pm_ang1', u.hourangle/u.year), RepresentationMapping('d_lat', 'pm_ang2'), RepresentationMapping('d_distance', 'vlos', u.kpc/u.Myr)] } i3 = NewICRS3(lon=10*u.degree, lat=-12*u.deg, distance=1000*u.pc, pm_ang1=1*u.mas/u.yr, pm_ang2=2*u.mas/u.yr, vlos=100*u.km/u.s) assert allclose(i3.pm_ang1, 1*u.mas/u.yr) assert i3.pm_ang1.unit == u.hourangle/u.year assert allclose(i3.pm_ang2, 2*u.mas/u.yr) assert allclose(i3.vlos, 100*u.km/u.s) assert i3.vlos.unit == u.kpc/u.Myr
def test_proton_collision(fe10): rate = fe10.proton_collision_excitation_rate() assert u.allclose(rate[0, 0], 4.69587161e-13 * u.cm**3 / u.s) rate = fe10.proton_collision_deexcitation_rate() assert u.allclose(rate[0, 0], 1.17688025e-12 * u.cm**3 / u.s)
def test_excitation_autoionization_rate(ion): rate = ion.excitation_autoionization_rate() assert rate.shape == ion.temperature.shape # This value has not been tested for correctness assert u.allclose(rate[0], 1.14821255e-12 * u.cm**3 / u.s)
def test_free_free(ion): emission = ion.free_free(200 * u.Angstrom) assert emission.shape == ion.temperature.shape + (1, ) # This value has not been tested for correctness assert u.allclose(emission[0], 6.81123745e-28 * u.cm**3 * u.erg / u.Angstrom / u.s)
def test_allclose_isclose_default(a, b): assert u.allclose(a, b) assert np.all(u.isclose(a, b))
def test_heliographic_latitude(generic_map): assert u.allclose(generic_map.heliographic_latitude, Latitude(sun.B0(generic_map.date)))
def test_carrington_longitude(generic_map): assert u.allclose(generic_map.carrington_longitude, sun.L0(generic_map.date))
def test_make_fits_header(map_data, hpc_test_header, hgc_test_header, hgs_test_header, hcc_test_header, hpc_test_header_notime): # Check that different coordinate frames return header MetaDict or not in the case of HCC assert isinstance(sunpy.map.make_fitswcs_header(map_data, hpc_test_header), MetaDict) assert isinstance(sunpy.map.make_fitswcs_header(map_data, hgc_test_header), MetaDict) assert isinstance(sunpy.map.make_fitswcs_header(map_data, hgs_test_header), MetaDict) # Raise the HCC error with pytest.raises(ValueError): sunpy.map.make_fitswcs_header(map_data, hcc_test_header) # Check for when coordinate argument isn't given as an `astropy.coordinate.SkyCoord` with pytest.raises(ValueError): sunpy.map.make_fitswcs_header(map_data, map_data) # Check for when an observation time isn't given with pytest.raises(ValueError): sunpy.map.make_fitswcs_header(map_data, hpc_test_header_notime) # Check that correct information is in header MetaDict including observer for HPC header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header) assert header['crval1'] == 0 assert header['crpix1'] == 5.5 assert header['ctype1'] == 'HPLN-TAN' assert u.allclose(header['dsun_obs'], hpc_test_header.frame.observer.radius.to_value(u.m)) assert u.allclose(header['rsun_ref'] * u.m, hpc_test_header.frame.rsun) assert u.allclose( header['rsun_obs'] * u.arcsec, sun._angular_radius(header['rsun_ref'] * u.m, header['dsun_obs'] * u.m)) assert u.allclose(header['hgln_obs'] * u.deg, hpc_test_header.frame.observer.lon) assert u.allclose(header['hglt_obs'] * u.deg, hpc_test_header.frame.observer.lat) assert isinstance(WCS(header), WCS) # Check no observer info for HGS header = sunpy.map.make_fitswcs_header(map_data, hgs_test_header) assert 'dsun_obs' not in header assert 'rsun_obs' not in header assert isinstance(WCS(header), WCS) # Check for observer info for HGC header = sunpy.map.make_fitswcs_header(map_data, hgc_test_header) assert u.allclose(header['dsun_obs'], hgc_test_header.frame.observer.radius.to_value(u.m)) assert isinstance(WCS(header), WCS) # Check arguments not given as astropy Quantities with pytest.raises(TypeError): header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, reference_pixel=[0, 0]) header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, scale=[0, 0]) # Check arguments of reference_pixel and scale have to be given in astropy units of pix, and arcsec/pix with pytest.raises(u.UnitsError): header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, reference_pixel=u.Quantity( [0, 0])) header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, scale=u.Quantity([0, 0])) header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, scale=u.Quantity([0, 0] * u.arcsec)) # Check keyword helper arguments header = sunpy.map.make_fitswcs_header(map_data, hpc_test_header, instrument='test name') assert header['instrume'] == 'test name' # Check returned MetaDict will make a `sunpy.map.Map` map_test = sunpy.map.Map(map_data, header) assert isinstance(map_test, sunpy.map.mapbase.GenericMap)
def __eq__(self, other): """ Return `True` if the ionic fractions, number density scaling factor (if set), and electron temperature (if set) are all equal, and `False` otherwise. Raises ------ `TypeError` If ``other`` is not an `~plasmapy.particles.ionization_state.IonizationState` instance. `ParticleError` If ``other`` corresponds to a different element or isotope. Examples -------- >>> IonizationState('H', [1, 0], tol=1e-6) == IonizationState('H', [1, 1e-6], tol=1e-6) True >>> IonizationState('H', [1, 0], tol=1e-8) == IonizationState('H', [1, 1e-6], tol=1e-5) False """ if not isinstance(other, IonizationState): raise TypeError( "An instance of the IonizationState class may only be " "compared with another IonizationState instance.") same_element = self.element == other.element same_isotope = self.isotope == other.isotope if not same_element or not same_isotope: raise ParticleError( "An instance of the IonizationState class may only be " "compared with another IonizationState instance if " "both correspond to the same element and/or isotope.") # Use the tighter of the two tolerances. For thermodynamic # quantities, use it as a relative tolerance because the values # may substantially depart from order unity. min_tol = np.min([self.tol, other.tol]) same_T_e = (np.isnan(self.T_e) and np.isnan(other.T_e) or u.allclose( self.T_e, other.T_e, rtol=min_tol * u.K, atol=0 * u.K)) same_n_elem = (np.isnan(self.n_elem) and np.isnan(other.n_elem) or u.allclose(self.n_elem, other.n_elem, rtol=min_tol * u.m**-3, atol=0 * u.m**-3)) # For the next line, recall that np.nan == np.nan is False same_fractions = np.any([ np.allclose(self.ionic_fractions, other.ionic_fractions, rtol=0, atol=min_tol), np.all(np.isnan(self.ionic_fractions)) and np.all(np.isnan(other.ionic_fractions)), ]) return np.all([ same_element, same_isotope, same_T_e, same_n_elem, same_fractions ])
def test_halofit(): """Test Smith, Takahashi and Bird Halofit models with Planck15 cosmology""" # Data for tests k = np.logspace(-4.0, 0.0, 5) z = np.linspace(0.0, 1.0, 2) p = [[705.54997046, 262.14967329], [6474.60158058, 2405.66190924], [37161.00990355, 13807.30920991], [9657.02613688, 3588.10339832], [114.60445565, 42.58170486]] ts = [[705.49027968, 262.13980368], [6469.19607307, 2404.75754883], [36849.24061946, 13757.68241714], [9028.01112208, 3628.67740715], [596.91685425, 110.08074646]] tt = [[705.48895748, 262.14055831], [6469.02581579, 2404.83678008], [36827.71983838, 13751.52554662], [9143.97447325, 3050.69467676], [662.31133378, 60.66609697]] tb = [[705.4903004, 262.13980169], [6469.19940132, 2404.75760398], [36849.2113973, 13757.8052238], [9010.83583125, 3630.48463588], [601.45212141, 111.52139435]] linear_power = np.array(p) truth_smith = np.array(ts) truth_takahashi = np.array(tt) truth_bird = np.array(tb) # Non-linear power spectra from Smith, Takahashi and Bird models nl_power_smith = halofit_smith(k, z, linear_power, Planck15) nl_power_takahashi = halofit_takahashi(k, z, linear_power, Planck15) nl_power_bird = halofit_bird(k, z, linear_power, Planck15) # Test shape of outputs assert np.shape(nl_power_smith) == np.shape(linear_power) assert np.shape(nl_power_takahashi) == np.shape(linear_power) assert np.shape(nl_power_bird) == np.shape(linear_power) # Test outputs against precomputed values assert allclose(nl_power_smith, truth_smith) assert allclose(nl_power_takahashi, truth_takahashi) assert allclose(nl_power_bird, truth_bird) # Test when redshift is a scalar z_scalar = z[0] power_1d = linear_power[:, 0] truth_scalar_redshift = truth_smith[:, 0] smith_scalar_redshift = halofit_smith(k, z_scalar, power_1d, Planck15) assert allclose(smith_scalar_redshift, truth_scalar_redshift) assert np.shape(smith_scalar_redshift) == np.shape(power_1d) # Test for failure when wavenumber is a scalar k_scalar = k[0] power_1d = linear_power[0, :] with pytest.raises(TypeError): halofit_smith(k_scalar, z, power_1d, Planck15) # Test for failure when wavenumber array is the wrong size k_wrong_size = np.logspace(-4.0, 2.0, 7) with pytest.raises(ValueError): halofit_smith(k_wrong_size, z, linear_power, Planck15) # Test for failure when redshift arry is the wrong size z_wrong_size = np.linspace(0.0, 2.0, 3) with pytest.raises(TypeError): halofit_smith(k, z_wrong_size, linear_power, Planck15) # Test for failure when wavenumber is negative k_negative = np.copy(k) k_negative[0] = -1.0 with pytest.raises(ValueError): halofit_smith(k_negative, z, linear_power, Planck15) # Test for failure when wavenumber is zero k_zero = np.copy(k) k_zero[0] = 0.0 with pytest.raises(ValueError): halofit_smith(k_zero, z, linear_power, Planck15) # Test for failure when redshift is negative z_negative = np.copy(z) z_negative[0] = -1.0 with pytest.raises(ValueError): halofit_smith(k, z_negative, linear_power, Planck15) # Test for failure when linear power spectrum is negative power_negative = np.copy(linear_power) power_negative[0, 0] = -1.0 with pytest.raises(ValueError): halofit_smith(k, z, power_negative, Planck15) # Test for failure when wavenumber array is not in asscending order k_wrong_order = k[::-1] with pytest.raises(ValueError): halofit_smith(k_wrong_order, z, linear_power, Planck15)
def carrington_rotation_time(crot, longitude: u.deg = None): """ Return the time of a given Carrington rotation. Fractional Carrington rotation numbers can be provided in two ways: * Fractional numbers to ``crot`` * Integer numbers to ``crot`` and a Carrington longitude to ``longitude`` Inputs can be arrays. If both ``crot`` and ``longitude`` are provided, the output shape will be the broadcasted combination. The round-trip from this method to `carrington_rotation_number` has absolute errors of < 0.11 seconds. Parameters ---------- crot : `int`, `float`, `~astropy.units.Quantity` Carrington rotation number(s). Can be a fractional rotation number. longitude : `~astropy.units.Quantity` Carrington longitude(s), which must be > 0 degrees and <= 360 degrees. If provided, ``crot`` must be strictly integral. Returns ------- `astropy.time.Time` Examples -------- >>> from sunpy.coordinates.sun import carrington_rotation_time >>> import astropy.units as u >>> carrington_rotation_time(2242) <Time object: scale='utc' format='iso' value=2021-03-17 22:31:37.030> >>> carrington_rotation_time(2000.25) <Time object: scale='utc' format='iso' value=2003-02-27 02:52:57.315> >>> carrington_rotation_time(2000, 270*u.deg) <Time object: scale='utc' format='iso' value=2003-02-27 02:52:57.315> """ crot = crot << u.one if longitude is not None: if not u.allclose(crot % 1, 0): raise ValueError( "Carrington rotation number(s) must be integral if `longitude` is provided." ) if (longitude <= 0 * u.deg).any() or (longitude > 360 * u.deg).any(): raise ValueError( "Carrington longitude(s) must be > 0 degrees and <= 360 degrees." ) crot = crot + (1 - longitude / (360 * u.deg)) estimate = (constants.mean_synodic_period * (crot - 1)) + constants.first_carrington_rotation # The above estimate is inaccurate (see comments below in carrington_rotation_number), # so put the estimate into carrington_rotation_number to determine a correction amount def refine(estimate): crot_estimate = carrington_rotation_number(estimate) dcrot = crot - crot_estimate # Correct the estimate using a linear fraction of the Carrington rotation period return estimate + (dcrot * constants.mean_synodic_period) # Perform two iterations of the correction to achieve sub-second accuracy estimate = refine(estimate) estimate = refine(estimate) t = Time(estimate, scale='tt', format='jd').utc t.format = 'iso' return t
def test_transform_api(): from astropy.coordinates.representation import UnitSphericalRepresentation from astropy.coordinates.builtin_frames import ICRS, FK5 from astropy.coordinates.baseframe import frame_transform_graph, BaseCoordinateFrame from astropy.coordinates.transformations import DynamicMatrixTransform # <------------------------Transformations-------------------------------------> # Transformation functionality is the key to the whole scheme: they transform # low-level classes from one frame to another. # (used below but defined above in the API) fk5 = FK5(ra=8*u.hour, dec=5*u.deg) # If no data (or `None`) is given, the class acts as a specifier of a frame, but # without any stored data. J2001 = time.Time('J2001') fk5_J2001_frame = FK5(equinox=J2001) # if they do not have data, the string instead is the frame specification assert repr(fk5_J2001_frame) == "<FK5 Frame (equinox=J2001.000)>" # Note that, although a frame object is immutable and can't have data added, it # can be used to create a new object that does have data by giving the # `realize_frame` method a representation: srep = UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg) fk5_j2001_with_data = fk5_J2001_frame.realize_frame(srep) assert fk5_j2001_with_data.data is not None # Now `fk5_j2001_with_data` is in the same frame as `fk5_J2001_frame`, but it # is an actual low-level coordinate, rather than a frame without data. # These frames are primarily useful for specifying what a coordinate should be # transformed *into*, as they are used by the `transform_to` method # E.g., this snippet precesses the point to the new equinox newfk5 = fk5.transform_to(fk5_J2001_frame) assert newfk5.equinox == J2001 # classes can also be given to `transform_to`, which then uses the defaults for # the frame information: samefk5 = fk5.transform_to(FK5) # `fk5` was initialized using default `obstime` and `equinox`, so: assert_allclose(samefk5.ra, fk5.ra, atol=1e-10*u.deg) assert_allclose(samefk5.dec, fk5.dec, atol=1e-10*u.deg) # transforming to a new frame necessarily loses framespec information if that # information is not applicable to the new frame. This means transforms are not # always round-trippable: fk5_2 = FK5(ra=8*u.hour, dec=5*u.deg, equinox=J2001) ic_trans = fk5_2.transform_to(ICRS) # `ic_trans` does not have an `equinox`, so now when we transform back to FK5, # it's a *different* RA and Dec fk5_trans = ic_trans.transform_to(FK5) assert not allclose(fk5_2.ra, fk5_trans.ra, rtol=0, atol=1e-10*u.deg) # But if you explicitly give the right equinox, all is fine fk5_trans_2 = fk5_2.transform_to(FK5(equinox=J2001)) assert_allclose(fk5_2.ra, fk5_trans_2.ra, rtol=0, atol=1e-10*u.deg) # Trying to transforming a frame with no data is of course an error: with raises(ValueError): FK5(equinox=J2001).transform_to(ICRS) # To actually define a new transformation, the same scheme as in the # 0.2/0.3 coordinates framework can be re-used - a graph of transform functions # connecting various coordinate classes together. The main changes are: # 1) The transform functions now get the frame object they are transforming the # current data into. # 2) Frames with additional information need to have a way to transform between # objects of the same class, but with different framespecinfo values # An example transform function: class SomeNewSystem(BaseCoordinateFrame): pass @frame_transform_graph.transform(DynamicMatrixTransform, SomeNewSystem, FK5) def new_to_fk5(newobj, fk5frame): ot = newobj.obstime eq = fk5frame.equinox # ... build a *cartesian* transform matrix using `eq` that transforms from # the `newobj` frame as observed at `ot` to FK5 an equinox `eq` matrix = np.eye(3) return matrix
def test_observer(mdi): assert mdi.observer_coordinate.frame.name == 'heliographic_stonyhurst' assert u.allclose(mdi.observer_coordinate.lat, Angle(mdi.meta['CRLT_OBS'] * u.degree)) assert u.allclose(mdi.observer_coordinate.radius, mdi.meta['DSUN_OBS'] * u.m)
def _is_2d(self): return (self._data is not None and self._data.norm().unit is u.one and u.allclose(self._data.norm(), 1 * u.one))
def test_free_bound(ion): emission = ion.free_bound(200 * u.Angstrom) assert emission.shape == ion.temperature.shape + (1, ) # This value has not been tested for correctness assert u.allclose(emission[0, 0], 7.20537148e-27 * u.cm**3 * u.erg / u.Angstrom / u.s)
def test_corners(simple_map): # These are the centers of the corner pixels assert u.allclose(simple_map.top_right_coord.Tx, 2 * u.arcsec) assert u.allclose(simple_map.top_right_coord.Ty, 1 * u.arcsec) assert u.allclose(simple_map.bottom_left_coord.Tx, -2 * u.arcsec) assert u.allclose(simple_map.bottom_left_coord.Ty, -1 * u.arcsec)
def test_dielectronic_recombination_rate(ion): rate = ion.dielectronic_recombination_rate() assert rate.shape == ion.temperature.shape # This value has not been tested for correctness assert u.allclose(rate[0], 1.60593802e-11 * u.cm**3 / u.s)
def test_center(simple_map): assert u.allclose(simple_map.center.Tx, 0 * u.arcsec, atol=1e-26 * u.arcsec) assert u.allclose(simple_map.center.Ty, 0 * u.arcsec)
def test_emissivity(ion): emm = ion.emissivity(1e7 * u.cm**-3) assert emm.shape == ion.temperature.shape + ( 1, ) + ion._wgfa['wavelength'].shape # This value has not been tested for correctness assert u.allclose(emm[0, 0, 0], 5.24152109e-17 * u.erg / u.cm**3 / u.s)
def test_halofit(): """Test Smith, Takahashi and Bird Halofit models with Planck15 cosmology""" # Wavenumbers and redshifts for tests k = np.logspace(-4, 2, 100, base=10) z = np.linspace(0, 2, 5) # Non-linear power spectra from Smith, Takahashi and Bird models nl_power_smith = halofit_smith(k, z, linear_power, Planck15) nl_power_takahashi = halofit_takahashi(k, z, linear_power, Planck15) nl_power_bird = halofit_bird(k, z, linear_power, Planck15) # Test shape of outputs assert np.shape(nl_power_smith) == np.shape(linear_power) assert np.shape(nl_power_takahashi) == np.shape(linear_power) assert np.shape(nl_power_bird) == np.shape(linear_power) # Test outputs against precomputed values assert allclose(nl_power_smith, truth_smith) assert allclose(nl_power_takahashi, truth_takahashi) assert allclose(nl_power_bird, truth_bird) # Test when redshift is a scalar z_scalar = z[0] power_1d = linear_power[0, :] truth_scalar_redshift = truth_smith[0, :] smith_scalar_redshift = halofit_smith(k, z_scalar, power_1d, Planck15) assert allclose(smith_scalar_redshift, truth_scalar_redshift) assert np.shape(smith_scalar_redshift) == np.shape(power_1d) # Test for failure when wavenumber is a scalar k_scalar = k[0] power_1d = linear_power[:, 0] with pytest.raises(TypeError): halofit_smith(k_scalar, z, power_1d, Planck15) # Test for failure when wavenumber array is the wrong size k_wrong_size = np.logspace(-4.0, 2.0, 7) with pytest.raises(ValueError): halofit_smith(k_wrong_size, z, linear_power, Planck15) # Test for failure when redshift array is the wrong size z_wrong_size = np.linspace(0.0, 2.0, 3) with pytest.raises(ValueError): halofit_smith(k, z_wrong_size, linear_power, Planck15) # Test for failure when wavenumber is negative k_negative = np.copy(k) k_negative[0] = -1.0 with pytest.raises(ValueError): halofit_smith(k_negative, z, linear_power, Planck15) # Test for failure when wavenumber is zero k_zero = np.copy(k) k_zero[0] = 0.0 with pytest.raises(ValueError): halofit_smith(k_zero, z, linear_power, Planck15) # Test for failure when redshift is negative z_negative = np.copy(z) z_negative[0] = -1.0 with pytest.raises(ValueError): halofit_smith(k, z_negative, linear_power, Planck15) # Test for failure when linear power spectrum is negative power_negative = np.copy(linear_power) power_negative[0, 0] = -1.0 with pytest.raises(ValueError): halofit_smith(k, z, power_negative, Planck15) # Test for failure when wavenumber array is not in asscending order k_wrong_order = k[::-1] with pytest.raises(ValueError): halofit_smith(k_wrong_order, z, linear_power, Planck15)
def test_ip(ion): assert ion.ip.dtype == np.dtype('float64') # This value has not been tested for correctness assert u.allclose(ion.ip, 1.2017997435751017e-10 * u.erg)
def test_z_at_value_bracketed(method): """ Test 2 solutions for angular diameter distance by not constraining zmin, zmax, but setting `bracket` on the appropriate side of the turning point z. Setting zmin / zmax should override `bracket`. """ cosmo = Planck13 if method == 'Bounded': with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'): z = z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method) if z > 1.6: z = 3.7914908 bracket = (0.9, 1.5) else: z = 0.6812777 bracket = (1.6, 2.0) with pytest.warns(UserWarning, match=r"Option 'bracket' is ignored"): assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=bracket), z, rtol=1e-6) else: assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(0.3, 1.0)), 0.6812777, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(2.0, 4.0)), 3.7914908, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(0.1, 1.5)), 0.6812777, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(0.1, 1.0, 2.0)), 0.6812777, rtol=1e-6) with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'): assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(0.9, 1.5)), 0.6812777, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(1.6, 2.0)), 3.7914908, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(1.6, 2.0), zmax=1.6), 0.6812777, rtol=1e-6) assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(0.9, 1.5), zmin=1.5), 3.7914908, rtol=1e-6) with pytest.raises(core.CosmologyError): with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'): z_at_value(cosmo.angular_diameter_distance, 1500 * u.Mpc, method=method, bracket=(3.9, 5.0), zmin=4.)
def test_great_arc_coordinates(points_requested, points_expected, first_point, last_point, last_inner_angle, last_distance, aia171_test_map): coordinate_frame = aia171_test_map.coordinate_frame a = SkyCoord(600 * u.arcsec, -600 * u.arcsec, frame=coordinate_frame) b = SkyCoord(-100 * u.arcsec, 800 * u.arcsec, frame=coordinate_frame) gc = GreatArc(a, b, points=points_requested) coordinates = gc.coordinates() inner_angles = gc.inner_angles() distances = gc.distances() # Ensure a GreatArc object is returned assert isinstance(gc, GreatArc) # Test the properties of the GreatArc object a_trans = a.transform_to(frames.Heliocentric) assert gc.start.x == a_trans.x assert gc.start.y == a_trans.y assert gc.start.z == a_trans.z b_trans = b.transform_to(frames.Heliocentric(observer=a.observer)) assert gc.end.x == b_trans.x assert gc.end.y == b_trans.y assert gc.end.z == b_trans.z assert gc.distance_unit == u.m assert gc.observer == a.observer assert gc.center.x == 0 * u.m assert gc.center.y == 0 * u.m assert gc.center.z == 0 * u.m assert u.allclose( gc.start_cartesian * u.m, np.asarray([428721.0913539, -428722.9051924, 341776.0910214]) * u.km) assert u.allclose( gc.end_cartesian * u.m, np.asarray([-71429.5229381, 571439.071248, 390859.5797815]) * u.km) assert u.allclose(gc.center_cartesian * u.m, np.asarray([0, 0, 0]) * u.km) assert u.allclose( gc.v1 * u.m, np.asarray([428721.0913539, -428722.9051924, 341776.0910214]) * u.km) assert u.allclose(gc._r, 696000000.0015007) assert u.allclose( gc.v2 * u.m, np.asarray([-71429.5229381, 571439.071248, 390859.5797815]) * u.km) assert u.allclose( gc.v3 * u.m, np.asarray([56761.6265851, 466230.7005856, 513637.0815867]) * u.km) # Inner angle assert gc.inner_angle.unit == u.rad np.testing.assert_almost_equal(gc.inner_angle.value, 1.8683580432741789) # Distance assert gc.distance.unit == u.m np.testing.assert_approx_equal(gc.distance.value, 1300377198.1299164) # Radius of the sphere assert gc.radius.unit == u.m assert u.isclose(gc.radius.value * u.m, 696000.000001501 * u.km) # Test the calculation of the SkyCoords # Coordinates method # Number of points assert len(coordinates) == points_expected # Start and end coordinates np.testing.assert_almost_equal(coordinates[0].Tx.value, first_point[0]) np.testing.assert_almost_equal(coordinates[0].Ty.value, first_point[1]) np.testing.assert_almost_equal(coordinates[-1].Tx.value, last_point[0]) np.testing.assert_almost_equal(coordinates[-1].Ty.value, last_point[1]) # Inner angles method # Inner angles assert len(inner_angles) == points_expected np.testing.assert_almost_equal(inner_angles[-1].value, last_inner_angle) # Distances method assert len(distances) == points_expected assert u.isclose(distances[-1].value * u.m, last_distance * u.km)
def test_sublimation_radius(self): assert u.allclose(dt_test.R_dt, 1.361 * 1e19 * u.cm, atol=0 * u.cm, rtol=1e-3)
def test_Otot(self, cosmo, z): """Test :meth:`astropy.cosmology.FLRW.Otot`. Should always be 1.""" super().test_Otot(cosmo, z) # for flat cosmologies, Otot is 1, within precision. assert u.allclose(cosmo.Otot(z), 1.0)
def test_setting_radius(self): """check that, when passed manually, the radius is correctly set""" dt = RingDustTorus(L_disk_test, 0.1, 1e3 * u.K, 1e19 * u.cm) assert u.allclose(dt.R_dt, 1e19 * u.cm, atol=0 * u.cm)
def test_carrington(mdi): assert u.allclose(mdi.carrington_longitude, Angle(mdi.meta['CRLN_OBS'] * u.deg)) assert u.allclose(mdi.carrington_latitude, Angle(mdi.meta['CRLT_OBS'] * u.deg))
def test_axis_world_coords_single(axes, ndcube_3d_ln_lt_l): coords = ndcube_3d_ln_lt_l.axis_world_coords_values(*axes) assert u.allclose(coords, [1.02e-09, 1.04e-09, 1.06e-09, 1.08e-09] * u.m) coords = ndcube_3d_ln_lt_l.axis_world_coords(*axes) assert u.allclose(coords, [1.02e-09, 1.04e-09, 1.06e-09, 1.08e-09] * u.m)
def test_axis_world_coords_single_edges(axes, ndcube_3d_ln_lt_l): coords = ndcube_3d_ln_lt_l.axis_world_coords_values(*axes, edges=True) assert u.allclose(coords, [1.01e-09, 1.03e-09, 1.05e-09, 1.07e-09, 1.09e-09] * u.m) coords = ndcube_3d_ln_lt_l.axis_world_coords(*axes, edges=True) assert u.allclose(coords, [1.01e-09, 1.03e-09, 1.05e-09, 1.07e-09, 1.09e-09] * u.m)
def test_axis_world_coords_sliced_all_3d(ndc, item): coords = ndc[item].axis_world_coords_values() assert u.allclose(coords, [1.02e-09, 1.04e-09, 1.06e-09, 1.08e-09] * u.m) coords = ndc[item].axis_world_coords() assert u.allclose(coords, [1.02e-09, 1.04e-09, 1.06e-09, 1.08e-09] * u.m)
def test_heliographic_longitude(generic_map): # Needs a small tolerance to account for 32bit rounding errors assert u.allclose(generic_map.heliographic_longitude, 0 * u.deg, atol=1e-15*u.deg)
def test_rsun(createEIT): """Tests the measurement property of the EITMap object.""" assert u.allclose(createEIT.rsun_obs, 979.0701*u.arcsec)